Commit 7d574b89 authored by sml's avatar sml

初稿提交

parents
Pipeline #325 failed with stages
package com.jz.common.constant;
public class Constants {
/**
* 数据状?(1:正常;0:删除;?
*/
public static final String DATA_STATE_NORMAL = "1";
public static final String DATA_STATE_DELETE = "0";
//access_token 过期时间
public static final long ACCESS_EXPIRE = 60 * 10;
//refresh_token 过期时间 暂时没用
public static final long REFRESH_EXPIRE = 60 * 10;
public static final String privateKey ="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAK1VxmLOUE9ps4m8Xked9nIMMkqK" +
"Cn77VqC9VmEcSPcp7w38XumXed45vnRkf6+kxuooiazfqfbzqkyURRDOaXIVspzC1LbZxwArhjvE" +
"qurq9zEDu6m7+gZR6G763wRqQHMcQAoH8JJDpiLZRF7Wr3AhOCPxVEUEWNfTwbTbjM4LAgMBAAEC" +
"gYA25BzpGVDRdTXH/oEUyO9MepRKiqB8SffK+2qpYh2xN/ReR3d/HdsYBs1LarAM3W+oo6HFvybB" +
"77QUgDfG9LbrRMJJL4W3yrcLP5LlzjvW1kcCazVyRZPpETsJOaOc8Juhb0Yz6tmrGf2rWvktpdJ4" +
"L9uzlyZ9hWPms0eyw38JMQJBAPgbZnpEKza+gtqgdFZZ4NIXx6ypL2cx+aAtQB0W0baaT9jJb8Jb" +
"84e3XvxlFjzCYBaoCDgyHwPKphK5LSJFINUCQQCy2W1Gbo8JNKyAgj5TeuQg8RELMGit9gbCaCNv" +
"kjA7ZpASTPHvj8K7VMI6BPJqtNCo/qLtuo0THUdmUShvBqNfAkBJT6dfN2dhfLejrEfUACjLS5WH" +
"slI8durg5p4MOmLrRvuS/iqUzqDOGGPrxl7kwzarWylamYzKjQW3gJoSh0SlAkBhf5RJtBW30AZG" +
"HDp76d+ZcbF35xD53Mg8jObceNZgW34o69dsYHOpCgDD/lRlBWNG7WHGtU8Y33o/9fhT5kuDAkBg" +
"0mOxtUf/4fs8djLeBWP8v/MMMybro4BbM7YgO/xgK4/135XhkAMdcY+xyR28ruVF7WHJujFYunXD" +
"/TfrZUrw";
public static final String publicKey ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCtVcZizlBPabOJvF5HnfZyDDJKigp++1agvVZh" +
"HEj3Ke8N/F7pl3neOb50ZH+vpMbqKIms36n286pMlEUQzmlyFbKcwtS22ccAK4Y7xKrq6vcxA7up" +
"u/oGUehu+t8EakBzHEAKB/CSQ6Yi2URe1q9wITgj8VRFBFjX08G024zOCwIDAQAB";
}
package com.jz.common.constant;
public class JsonResult {
private String code;
private String message;
private Object data;
public JsonResult() {
this.setCode(ResultCode.SUCCESS);
this.setMessage("成功?");
}
public JsonResult(ResultCode code) {
this.setCode(code);
this.setMessage(code.msg());
}
public JsonResult(ResultCode code, String message) {
this.setCode(code);
this.setMessage(message);
}
public JsonResult(ResultCode code, Object data) {
this.setCode(code);
this.setMessage(code.msg());
this.setData(data);
}
public JsonResult(ResultCode code, String message, Object data) {
this.setCode(code);
this.setMessage(message);
this.setData(data);
}
public String getCode() {
return code;
}
public void setCode(ResultCode code) {
this.code = code.val();
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
package com.jz.common.constant;
public enum ResultCode {
/** 成功 */
SUCCESS("200", "成功"),
/** 没有登录 */
NOT_LOGIN("400", "没有登录"),
/** 发生异常 */
EXCEPTION("401", "发生异常"),
/** 系统错误 */
SYS_ERROR("402", "系统错误"),
/** 参数错误 */
PARAMS_ERROR("403", "参数错误 "),
PARAMS_ERROR_TOKEN("446", "token无效"),
/** 不支持当前请求方? */
METHOD_NOT_ALLOWED("405", "不支持当前请求方? "),
/** 不支持或已经废弃 */
NOT_SUPPORTED("410", "不支持或已经废弃"),
/** 不支持当前媒体类? */
UNSUPPORTED_MEDIA_TYPE("415", "不支持当前媒体类?"),
/** AuthCode错误 */
INVALID_AUTHCODE("444", "无权限访?"),
/** 太频繁的调用 */
TOO_FREQUENT("445", "太频繁的调用"),
/** 未知的错? */
UNKNOWN_ERROR("499", "未知错误"),
/** 内部服务出错 */
INTERNAL_SERVER_ERROR("500", "内部服务出错-逻辑异常");
private String val;
private String msg;
private ResultCode(String value, String msg) {
this.val = value;
this.msg = msg;
}
public String val() {
return val;
}
public String msg() {
return msg;
}
}
package com.jz.common.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.jz.common.constant.JsonResult;
import com.jz.common.constant.ResultCode;
import io.micrometer.core.instrument.config.validate.ValidationException;
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 403 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
public JsonResult handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
logger.error("缺少请求参数", e);
return new JsonResult(ResultCode.PARAMS_ERROR, "required_parameter_is_not_present");
}
/**
* 403 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public JsonResult handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
logger.error("参数解析失败", e);
return new JsonResult(ResultCode.PARAMS_ERROR, "could_not_read_json");
}
/**
* 403 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
logger.error("参数验证失败", e);
BindingResult result = e.getBindingResult();
FieldError error = result.getFieldError();
String field = error.getField();
String code = error.getDefaultMessage();
String message = String.format("%s:%s", field, code);
return new JsonResult(ResultCode.PARAMS_ERROR, message);
}
/**
* 403 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BindException.class)
public JsonResult handleBindException(BindException e) {
logger.error("参数绑定失败", e);
BindingResult result = e.getBindingResult();
FieldError error = result.getFieldError();
String field = error.getField();
String code = error.getDefaultMessage();
String message = String.format("%s:%s", field, code);
//return new AjaxResult().failure(message);
return new JsonResult(ResultCode.PARAMS_ERROR, message);
}
/**
* 403 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValidationException.class)
public JsonResult handleValidationException(ValidationException e) {
logger.error("参数验证失败", e);
return new JsonResult(ResultCode.PARAMS_ERROR, "validation_exception:");
}
/**
* 405 - Method Not Allowed
*/
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public JsonResult handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
logger.error("不支持当前请求方�?", e);
return new JsonResult(ResultCode.NOT_SUPPORTED, "request_method_not_supported:");
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public JsonResult handleHttpMediaTypeNotSupportedException(Exception e) {
logger.error("不支持当前媒体类�?", e);
return new JsonResult(ResultCode.UNSUPPORTED_MEDIA_TYPE, "content_type_not_supported:");
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(ServiceException.class)
public JsonResult handleServiceException(ServiceException e) {
logger.error("业务逻辑异常", e);
return new JsonResult(ResultCode.INTERNAL_SERVER_ERROR, "业务逻辑异常�?");
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public JsonResult handleException(Exception e) {
logger.error("通用逻辑异常", e);
return new JsonResult(ResultCode.INTERNAL_SERVER_ERROR, "参数错误");
}
/**
* 操作数据库出现异�?:名称重复,外键关�?
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(DataIntegrityViolationException.class)
public JsonResult handleException(DataIntegrityViolationException e) {
logger.error("操作数据库出现异�?:", e);
return new JsonResult(ResultCode.NOT_SUPPORTED, "操作数据库出现异常:字段重复、有外键关联�?");
}
}
package com.jz.common.exception;
public class ServiceException extends Exception {
private static final long serialVersionUID = 1859731705152111160L;
public ServiceException(String message) {
super(message);
}
}
package com.jz.common.filter;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jz.common.service.PatternMatcher;
import com.jz.common.service.ServletPathMatcher;
import com.jz.dmp.modules.service.AtomBaseCacheService;
import lombok.extern.slf4j.Slf4j;
import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;
/**
*
* @ClassName: LoginFilter
* @Description: TODO(这里用一句话描述这个类的作用)
* @author: niulichang
* @date: 2020年6月10日 下午4:27:06
* @最后修改人: niulichang
* @最后修改时间: 2020年6月10日 下午4:27:06
*/
@Component
@Slf4j
public class LoginFilter implements Filter {
@Autowired
private AtomBaseCacheService<String> cacheService;
public static final String PARAM_NAME_EXCLUSIONS = "exclusions";
private Set<String> excludesPattern;
protected String contextPath;
protected PatternMatcher pathMatcher = new ServletPathMatcher();
public String getContextPath() {
return contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String param = filterConfig.getInitParameter(PARAM_NAME_EXCLUSIONS);
if (param != null && param.trim().length() != 0) {
this.excludesPattern = new HashSet(Arrays.asList(param.split("\\s*,\\s*")));
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String ua = httpRequest.getHeader("User-Agent");
UserAgent userAgent = UserAgent.parseUserAgentString(ua);
Browser browser = userAgent.getBrowser();
OperatingSystem os = userAgent.getOperatingSystem();
String system = os.getName();
String browserName = browser.getName();
String token = httpRequest.getHeader("token");
httpResponse.setHeader("Access-Control-Allow-Origin", "http://zhijie-admin.9zdata.cn"); //允许来之域名为http://localhost的请求
httpResponse.setHeader("Access-Control-Allow-Headers", "Origin,No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, userId, token");
httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); //请求允许的方法
httpResponse.setHeader("Access-Control-Max-Age", "3600");
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("application/json; charset=utf-8");
String resMethods = httpRequest.getMethod();
if("OPTIONS".equals(resMethods)) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("data",null);
map.put("code","200");
map.put("msg",null);
log.info(JSONObject.toJSONString(map, SerializerFeature.WriteMapNullValue));
httpResponse.getWriter().write(JSONObject.toJSONString(map, SerializerFeature.WriteMapNullValue));
return;
}
// String requestURL = httpRequest.getRequestURI();
// if (this.isExclusion(requestURL)) {
// chain.doFilter(httpRequest,httpResponse);
// }else {
// String userId = null;
// Claims claims = JwtUtil.checkJWT(token);
// if (claims != null) {
// userId = (String) claims.get("userId");
// } else {
// PrintWriter out = httpResponse.getWriter();
// JSONObject res = new JSONObject();
// res.put("msg", ResultCode.E9998.msg());
// res.put("code", ResultCode.E9998.val());
// res.put("data",null);
// out.append(res.toString());
// out.flush();
// return;
// }
// String tokenSystem = (String) claims.get("system");
// String tokenBrowserName = (String) claims.get("browserName");
// if(!system.equals(tokenSystem)|| !browserName.equals(tokenBrowserName)) {
// PrintWriter out = httpResponse.getWriter();
// JSONObject res = new JSONObject();
// res.put("msg", ResultCode.E9998.msg());
// res.put("code", ResultCode.E9998.val());
// res.put("data",null);
// out.append(res.toString());
// out.flush();
// return;
// }
// if (userId==null){
// PrintWriter out = httpResponse.getWriter();
// JSONObject res = new JSONObject();
// res.put("msg", ResultCode.E9998.msg());
// res.put("code", ResultCode.E9998.val());
// res.put("data",null);
// out.append(res.toString());
// out.flush();
// return;
// }else {
// String access_token = cacheService.getValue("access_token"+userId);
// if(StringUtils.isBlank(access_token)|| !token.equals(access_token)) {
// PrintWriter out = httpResponse.getWriter();
// JSONObject res = new JSONObject();
// res.put("msg", ResultCode.E9998.msg());
// res.put("code", ResultCode.E9998.val());
// res.put("data",null);
// out.append(res.toString());
// out.flush();
// return;
// }
// cacheService.expire("access_token"+userId, Constants.ACCESS_EXPIRE, java.util.concurrent.TimeUnit.SECONDS);
// List<String> menu = systemMenuService.getMenuHrefListForLoginUser(Integer.parseInt(userId));
// if(!menu.contains(requestURL)) {
// PrintWriter out = httpResponse.getWriter();
// JSONObject res = new JSONObject();
// res.put("msg", ResultCode.INVALID_AUTHCODE.msg());
// res.put("code", ResultCode.INVALID_AUTHCODE.val());
// res.put("data",null);
// out.append(res.toString());
// out.flush();
// return;
// }
// chain.doFilter(httpRequest,httpResponse);
// }
// }
chain.doFilter(httpRequest,httpResponse);
}
@Override
public void destroy() {
}
public boolean isExclusion(String requestURI) {
if (this.excludesPattern == null) {
return false;
} else {
if (this.contextPath != null && requestURI.startsWith(this.contextPath)) {
requestURI = requestURI.substring(this.contextPath.length());
if (!requestURI.startsWith("/")) {
requestURI = "/" + requestURI;
}
}
Iterator i$ = this.excludesPattern.iterator();
String pattern;
do {
if (!i$.hasNext()) {
return false;
}
pattern = (String)i$.next();
} while(!this.pathMatcher.matches(pattern, requestURI));
return true;
}
}
}
package com.jz.common.jwt;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* jwt 存储的 内容
* eleven
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class JwtUserInfo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 406413522260899460L;
/**
* 账号id
*/
private String userId;
/**
* 登录账号
*/
private String loginName;
/**
* 姓名
*/
private String userName;
private String system;
private String browserName;
private String isPassword;
}
package com.jz.common.jwt;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import com.jz.common.constant.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
/**
* Secure工具类
*/
@Slf4j
public class JwtUtil {
/**
* 过期时间,5分钟
*/
/**
* 秘钥
*/
public static final String APPSECRET = "9ZzhijiekeySyrTegfae2NItSfk";
/**
* 生成jwt
*
* @param userInfo
* @return
*/
public static String geneJsonWebToken(JwtUserInfo userInfo) {
long nowMillis = System.currentTimeMillis();
long expMillis = nowMillis + Constants.ACCESS_EXPIRE;
Date exp = new Date(expMillis);
if (userInfo == null || StringUtils.isEmpty(userInfo.getUserId())) {
return null;
}
String token = Jwts.builder().setSubject(userInfo.getUserId())
.claim("userId", userInfo.getUserId())
.claim("userName", userInfo.getUserName())
.claim("loginName", userInfo.getLoginName())
.claim("system", userInfo.getSystem())
.claim("browserName", userInfo.getBrowserName())
.claim("isPassword", userInfo.getIsPassword())
.setIssuedAt(new Date())
// .setExpiration(exp)
.signWith(SignatureAlgorithm.HS256, APPSECRET).compact();
return token;
}
public static String geneJsonWebRefreshToken(JwtUserInfo userInfo) {
long nowMillis = System.currentTimeMillis();
long expMillis = nowMillis + Constants.REFRESH_EXPIRE;
Date exp = new Date(expMillis);
if (userInfo == null || StringUtils.isEmpty(userInfo.getUserId())) {
return null;
}
String token = Jwts.builder().setSubject(userInfo.getUserId())
.claim("userId", userInfo.getUserId())
.claim("userName", userInfo.getUserName())
.claim("loginName", userInfo.getLoginName())
.setIssuedAt(new Date())
.setExpiration(exp)
.signWith(SignatureAlgorithm.HS256, APPSECRET).compact();
return token;
}
/**
* 校验token
*
* @param token
* @return
*/
public static Claims checkJWT(String token) {
try {
final Claims claims = Jwts.parser().setSigningKey(APPSECRET).
parseClaimsJws(token).getBody();
return claims;
} catch (Exception e) {
}
return null;
}
/**
*
* @Title: getUserIdByToken
* @Description: TODO(获取userId)
* @最后修改人: niulichang-eleven
* @最后修改时间: 2020年6月11日 上午11:33:53
* @param token
* @return 对方法的参数进行描述
* @return: String 返回类型
* @throws
*/
public static String getUserIdByToken(String token) {
String userId = null;
Claims claims = JwtUtil.checkJWT(token);
if (claims != null) {
userId = (String) claims.get("userId");
}
return userId;
}
/**
*
* @Title: getLoginNameByToken
* @Description: TODO(获取登录名称)
* @最后修改人: niulichang-eleven
* @最后修改时间: 2020年6月11日 上午11:34:09
* @param token
* @return 对方法的参数进行描述
* @return: String 返回类型
* @throws
*/
public static String getLoginNameByToken(String token) {
String loginName = null;
Claims claims = JwtUtil.checkJWT(token);
if (claims != null) {
loginName = (String) claims.get("loginName");
} else {
try {
throw new Exception("非法token");
} catch (Exception e) {
e.printStackTrace();
}
}
return loginName;
}
/**
*
* @Title: getUserNameByToken
* @Description: TODO(获取用户名称)
* @最后修改人: niulichang-eleven
* @最后修改时间: 2020年6月11日 上午11:34:58
* @param token
* @return 对方法的参数进行描述
* @return: String 返回类型
* @throws
*/
public static String getUserNameByToken(String token) {
String userName = null;
Claims claims = JwtUtil.checkJWT(token);
if (claims != null) {
userName = (String) claims.get("userName");
} else {
try {
throw new Exception("非法token");
} catch (Exception e) {
e.printStackTrace();
}
}
return userName;
}
public static String getIsPasswordByToken(String token) {
String isPassword = null;
Claims claims = JwtUtil.checkJWT(token);
if (claims != null) {
isPassword = (String) claims.get("isPassword");
} else {
try {
throw new Exception("非法token");
} catch (Exception e) {
e.printStackTrace();
}
}
return isPassword;
}
}
package com.jz.common.service;
public interface PatternMatcher {
boolean matches(String var1, String var2);
}
package com.jz.common.service;
public class ServletPathMatcher implements PatternMatcher{
private static final ServletPathMatcher INSTANCE = new ServletPathMatcher();
public ServletPathMatcher() {
}
public static ServletPathMatcher getInstance() {
return INSTANCE;
}
public boolean matches(String pattern, String source) {
if (pattern != null && source != null) {
pattern = pattern.trim();
source = source.trim();
int start;
if (pattern.endsWith("*")) {
start = pattern.length() - 2;
if (source.length() >= start && pattern.substring(0, start).equals(source.substring(0, start))) {
return true;
}
} else if (pattern.startsWith("*")) {
start = pattern.length() - 1;
if (source.length() >= start && source.endsWith(pattern.substring(1))) {
return true;
}
} else if (pattern.contains("*")) {
start = pattern.indexOf("*");
int end = pattern.lastIndexOf("*");
if (source.startsWith(pattern.substring(0, start)) && source.endsWith(pattern.substring(end + 1))) {
return true;
}
} else if (pattern.equals(source)) {
return true;
}
return false;
} else {
return false;
}
}
}
/*
*
*/
package com.jz.common.utils;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
/**
* 日期工具类
*
*/
public class DateUtils {
private static final SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final SimpleDateFormat datetimeFormats = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
private static final SimpleDateFormat ym = new SimpleDateFormat("yyyyMM");
public static final SimpleDateFormat dfs = new SimpleDateFormat("yyyy/MM/dd");
public static final SimpleDateFormat dfsFull = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private static final SimpleDateFormat cf = new SimpleDateFormat("yyyyMMddHHmm");
private static final SimpleDateFormat cfs = new SimpleDateFormat("yyyyMMddHHmmss");
private static final SimpleDateFormat dt = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
private static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
final static long daytimes = 24 * 60 * 60 * 1000;
final static long hourtimes = 1 * 60 * 60 * 1000;
private static Calendar c = new GregorianCalendar();
public static Date parseAuto(String source) {
if (StringUtils.isBlank(source))
return null;
try {
if (source.indexOf('-') > 0) {// 以"-"分隔
if (source.indexOf(':') > 0) {
return datetimeFormat.parse(source);
} else {
return dateFormat.parse(source);
}
}
if (source.indexOf('/') > 0) {// 以"/"分隔
if (source.indexOf(':') > 0) {
return dfsFull.parse(source);
} else {
return dfs.parse(source);
}
}
try {
return cfs.parse(source);
} catch (Exception e) {
return df.parse(source);
}
} catch (Exception e) {
return null;
}
}
/**
* 获得当前时间
* <p>
* 时间格式HH:mm:ss
*
* @return
*/
public static String currentTime() {
return timeFormat.format(today());
}
/**
* 获得当前日期时间
* <p>
* 日期时间格式yyyy-MM-dd HH:mm:ss
*
* @return
*/
public static String currentDatetime() {
return datetimeFormat.format(today());
}
/**
* 获得当前日期时间
* <p>
* 日期时间格式yyyy-MM-dd HH:mm:ss SSS
*
* @return
*/
public static String currentSecondsDatetime() {
return datetimeFormats.format(today());
}
/**
* 获得当前日期
* <p>
* 日期格式yyyy-MM-dd
*
* @return String
*/
public static String currentDate() {
return dateFormat.format(today());
}
/**
* 获得当前时间的<code>java.util.Date</code>对象
*
* @return Date
*/
public static Date today() {
return new Date();
}
/**
* 获取格式化之后的当前日期 日期格式yyyy-MM-dd
*/
public static Date todayFormat() {
try {
return parseDate(currentDate());
} catch (ParseException e) {
return new Date();
}
}
public static Date yesterday() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return cal.getTime();
}
public static String yesterdayStr() {
return dateFormat.format(yesterday());
}
/**
* 格式化时间
* <p>
* 时间格式HH:mm:ss
*
* @return
*/
public static String formatTime(Date date) {
return timeFormat.format(date);
}
/**
* 格式化日期
* <p>
* 日期格式yyyy-MM-dd
*
* @return
*/
public static String formatDate(Date date) {
return dateFormat.format(date);
}
/**
* 格式化日期
* <p>
* 日期格式yyyyMMdd
*
* @return
*/
public static String df(Date date) {
return df.format(date);
}
/**
* 格式成年月 201901
* @param date
* @return
*/
public static String ym(String date) {
try {
return ym.format(dateFormat.parse(date));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
/**
* 格式化日期
* <p>
* 日期格式yyyyMMddHHmm
*
* @return
*/
public static String cf(Date date) {
return cf.format(date);
}
/**
* 格式化日期
* <p>
* 日期格式yyyyMMDDhhmmss
*
* @return
*/
public static String cfs(Date date) {
return cfs.format(date);
}
/**
* 格式化日期
* <p>
* 日期格式yyyyMMdd HH:mm
*
* @return
*/
public static String dt(Date date) {
return dt.format(date);
}
/**
* 格式化日期时间
* <p>
* 日期时间格式yyyy-MM-dd HH:mm:ss
*
* @return
*/
public static String formatDatetime(Date date) {
return datetimeFormat.format(date);
}
/**
* 格式化日期时间
*
* @param date
* @param pattern 格式化模式,详见{@link SimpleDateFormat}构造器
* <code>SimpleDateFormat(String pattern)</code>
* @return
*/
public static String formatDatetime(Date date, String pattern) {
SimpleDateFormat customFormat = (SimpleDateFormat) datetimeFormat.clone();
customFormat.applyPattern(pattern);
return customFormat.format(date);
}
public static Calendar calendar() {
Calendar cal = GregorianCalendar.getInstance(Locale.CHINESE);
cal.setFirstDayOfWeek(Calendar.MONDAY);
return cal;
}
/**
* 获得当前时间的毫秒数
* <p>
* 详见{@link System#currentTimeMillis()}
*
* @return
*/
public static long millis() {
return System.currentTimeMillis();
}
public static int year(Date date) {
c.setTime(date);
return c.get(Calendar.YEAR);
}
public static int month(Date date) {
c.setTime(date);
return c.get(Calendar.MONTH) + 1;
}
public static int weekOfYear(Date date){
Calendar cal = calendar();
cal.setTime(date);
return cal.get(Calendar.WEEK_OF_YEAR);
}
/**
* 获得月份中的第几天
*
* @return
*/
public static int dayOfMonth() {
return calendar().get(Calendar.DAY_OF_MONTH);
}
/**
* 今天是星期的第几天
*
* @return
*/
public static int dayOfWeek() {
return calendar().get(Calendar.DAY_OF_WEEK);
}
/**
* 今天是年中的第几天
*
* @return
*/
public static int dayOfYear() {
return calendar().get(Calendar.DAY_OF_YEAR);
}
/**
* 判断原日期是否在目标日期之前
*
* @param src
* @param dst
* @return
*/
public static boolean isBefore(Date src, Date dst) {
return src.before(dst);
}
/**
* 判断原日期是否在目标日期之后
*
* @param src
* @param dst
* @return
*/
public static boolean isAfter(Date src, Date dst) {
return src.after(dst);
}
/**
* 判断两日期是否相同
*
* @param date1
* @param date2
* @return
*/
public static boolean isEqual(Date date1, Date date2) {
return date1.compareTo(date2) == 0;
}
/**
* 计算两个日期相差多少天
*
* @param date1
* @param date2
* @return
*/
public static long days(String startDate, String endDate) {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
Long c=0L;
try {
c = sf.parse(endDate).getTime()-sf.parse(startDate).getTime();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return c/1000/60/60/24;//天
}
/**
* 判断某个日期是否在某个日期范围
*
* @param beginDate 日期范围开始
* @param endDate 日期范围结束
* @param src 需要判断的日期
* @return
*/
public static boolean between(Date beginDate, Date endDate, Date src) {
return beginDate.getTime() == src.getTime() || endDate.getTime() == src.getTime()
|| (beginDate.before(src) && endDate.after(src));
}
/**
* 获取指定日期的月份
*
* @param date
* @return
*/
public static int MonthOfDate(Date date) {
Calendar c = Calendar.getInstance(); // 获得一个日历的实例
if (date == null) {
date = new Date(); // 为空时当前时间计算
}
c.setTime(date);
return c.get(Calendar.MONTH) + 1;
}
/**
* 获取指定日期的日期
*
* @param date
* @return
*/
public static int DayOfDate(Date date) {
Calendar c = Calendar.getInstance(); // 获得一个日历的实例
if (date == null) {
date = new Date(); // 为空时当前时间计算
}
c.setTime(date);
return c.get(Calendar.DAY_OF_MONTH);
}
/**
* 获取指定日期当月最后一天 date为null时为当前月
*
* @param date
* @return Date
*/
public static Date getLastDayOfMonth(Date date) {
Calendar c = Calendar.getInstance();
if (date == null) {
date = new Date();
}
c.setTime(date);
c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
return c.getTime();
}
public static boolean isLastDayOfMonth(Date date) {
Calendar c = Calendar.getInstance();
if (date == null) {
date = new Date();
}
c.setTime(date);
c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
return c.getTime().compareTo(date) == 0;
}
/**
* 获取指定日期当月第一天 date为null时为当前月
*
* @param date
* @return Date
*/
public static Date getFirstDayOfMonth(Date date) {
Calendar c = Calendar.getInstance();
if (date == null) {
date = new Date();
}
c.setTime(date);
c.set(Calendar.DATE, c.getActualMinimum(Calendar.DATE));
return c.getTime();
}
public static Date weekDay(int week) {
Calendar cal = calendar();
cal.set(Calendar.DAY_OF_WEEK, week);
return cal.getTime();
}
/**
* 获得周五日期
* <p>
* 注:日历工厂方法{@link #calendar()}设置类每个星期的第一天为Monday,US等每星期第一天为sunday
*
* @return
*/
public static Date friday() {
return weekDay(Calendar.FRIDAY);
}
/**
* 获得周六日期
* <p>
* 注:日历工厂方法{@link #calendar()}设置类每个星期的第一天为Monday,US等每星期第一天为sunday
*
* @return
*/
public static Date saturday() {
return weekDay(Calendar.SATURDAY);
}
/**
* 获得周日日期
* <p>
* 注:日历工厂方法{@link #calendar()}设置类每个星期的第一天为Monday,US等每星期第一天为sunday
*
* @return
*/
public static Date sunday() {
return weekDay(Calendar.SUNDAY);
}
/**
* 将字符串日期时间转换成java.util.Date类型
* <p>
* 日期时间格式yyyy-MM-dd HH:mm:ss
*
* @param datetime
* @return
*/
public static Date parseDatetime(String datetime) throws ParseException {
return datetimeFormat.parse(datetime);
}
/**
* 将字符串日期转换成java.util.Date类型
* <p>
* 日期时间格式yyyy-MM-dd
*
* @param date
* @return
* @throws ParseException
*/
public static Date parseDate(String date) throws ParseException {
return dateFormat.parse(date);
}
/**
* 将字符串日期转换成java.util.Date类型
* <p>
* 时间格式 HH:mm:ss
*
* @param time
* @return
* @throws ParseException
*/
public static Date parseTime(String time) throws ParseException {
return timeFormat.parse(time);
}
/**
* 根据自定义pattern将字符串日期转换成java.util.Date类型
*
* @param datetime
* @param pattern
* @return
* @throws ParseException
*/
public static Date parseDatetime(String datetime, String pattern) throws ParseException {
SimpleDateFormat format = (SimpleDateFormat) datetimeFormat.clone();
format.applyPattern(pattern);
return format.parse(datetime);
}
/**
* 时间转换(date转string)
*
* @param date 需要转换的date
* @param format 格式化类型 eg.yyyy-MM-dd
*/
public static String dateToString(Date date, String format) {
SimpleDateFormat simpledateformat = new SimpleDateFormat(format);
if (date != null)
return simpledateformat.format(date);
else
return "";
}
/**
* 时间转换(string转date)
*
* @param str 需要转换的data,string格式
* @param format 格式化类型 eg.yyyy-MM-dd
*/
public static Date stringToDate(String str, String format) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(Boolean.FALSE);
Date date = sdf.parse(str);
return date;
}
// /**
// * 获得当前日期的第几周
// *
// * @param date
// * 需要转换的date
// */
// public static int getWeekOfDate(Date date) {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd|w");
// String fmt = sdf.format(date);
// return new Integer(StringUtils.substringAfter(fmt, "|"));
// }
/**
* 以自定义方式验证是否为合法日期格式
*
* @param str 需要转换的data,string格式
* @param format 格式化类型 eg.yyyy-MM-dd
* @return
*/
public static boolean isValidDate(String str, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(Boolean.FALSE);
try {
sdf.parse(str);
return Boolean.TRUE;
} catch (ParseException e) {
return Boolean.FALSE;
}
}
/**
* 按天数计算时间
*
* @param date 传入时间
* @param day 需要计算的天数
* @return 计算后的时间
*/
public static Date getCalcDay(Date date, int day) {
Calendar c = Calendar.getInstance(); // 获得一个日历的实例
if (date == null) {
date = new Date(); // 为空时当前时间计算
}
c.setTime(date);
c.add(Calendar.DATE, day);
return c.getTime();
}
/**
* 在日历的天数上减少day天
*/
public static Date getBeforeDay(int day) throws ParseException {
Calendar c = Calendar.getInstance();// 获得一个日历的实例
Date date = dateFormat.parse(currentDate());// 初始日期
c.setTime(date);// 设置日历时间
c.add(Calendar.DATE, -day); // 在日历的天数上减少day天
return c.getTime();
}
/**
* 在日历的月份上增加month个月
*/
public static Date getBeforeMonth(int month) throws ParseException {
Calendar c = Calendar.getInstance();// 获得一个日历的实例
Date date = dateFormat.parse(currentDate());// 初始日期
c.setTime(date);// 设置日历时间
c.add(Calendar.MONTH, month); // 在日历的月份上增加month个月
return c.getTime();
}
/**
* 在指定时间上增加月个数
*
* @param date
* @param amount
* @return
*/
public static Date addMonths(Date date, int amount) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, amount);
return c.getTime();
}
/**
* 时间转日期
*
* @param date
* @return
*/
public static Date timeToDate(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
}
public static Date addDay(int amount) {
Calendar c = Calendar.getInstance();
c.setTime(today());
c.add(Calendar.DAY_OF_MONTH, amount);
return c.getTime();
}
public static Date addHour(int hour) {
Calendar c = Calendar.getInstance();
c.setTime(today());
c.add(Calendar.HOUR_OF_DAY, hour);
return c.getTime();
}
/**
* 返回指定小时的时间
*
* @param hour
* @return
*/
public static Date getDateByHour(int hour) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
return c.getTime();
}
/**
* 在指定时间上增加小时数
*
* @param date
* @param hour
* @return
*/
public static Date addHour(Date date, int hour) {
c.setTime(date);
c.add(Calendar.HOUR_OF_DAY, hour);
return c.getTime();
}
/**
* 在指定时间上增加天数
*
* @param date
* @param amount
* @return
*/
public static Date addDay(Date date, int amount) {
c.setTime(date);
c.add(Calendar.DAY_OF_MONTH, amount);
return c.getTime();
}
public static Date addDay(Date date, int calendarField, int amount) {
c.setTime(date);
c.add(calendarField, amount);
return c.getTime();
}
public static Timestamp addTimestamp(Timestamp date, int calendarField, int amount) {
c.setTime(date);
c.add(calendarField, amount);
return new Timestamp(c.getTimeInMillis());
}
public static Timestamp addDay(Timestamp date, int amount) {
return addTimestamp(date, Calendar.DAY_OF_MONTH, amount);
}
public static Timestamp dateTimeTodate(Timestamp src) {
c.setTimeInMillis(src.getTime());
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
return new Timestamp(c.getTimeInMillis());
}
/**
* 在指定时间上增加年份
*
* @param date
* @param amount
* @return
*/
public static Date addYear(Date date, int amount) {
c.setTime(date);
c.add(Calendar.YEAR, amount);
return c.getTime();
}
/**
* 计算两个时间差精确到(xxx天xx小时xx分xx秒)
*
* @param date1表示终止时间 , data2
* @return
* @throws ParseException
*/
public static String getDateSubtract(Date date1, Date date2) throws ParseException {
long d1 = date1.getTime();
long d2 = date2.getTime();
Date now = datetimeFormat.parse(formatDatetime(date1));
Date date = datetimeFormat.parse(formatDatetime(date2));
long l = 0l;
if (d1 > d2) {
l = now.getTime() - date.getTime();
} else {
l = date.getTime() - now.getTime();
}
long day = l / (daytimes);
long hour = (l / (60 * 60 * 1000) - day * 24);
long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
String dayday = "" + day + "天" + hour + "小时" + min + "分" + s + "秒";
return dayday;
}
/**
* 计算两个时间相差天数
*
* @param date1
* @param date2
* @return long
*/
public static long getDateSubDays(Date date1, Date date2) {
long d1 = date1.getTime();
long d2 = date2.getTime();
long diff = 0l;
if (d1 == d2) {
return diff;
} else if (d1 > d2) {
diff = d1 - d2;
} else {
diff = d2 - d1;
}
return diff / (daytimes);
}
/**
* 计算两个时间相差天数(date1-date2)带正负符号
*
* @param date1
* @param date2
* @return long
*/
public static long getDateSubDaysSigned(Date date1, Date date2) {
long d1 = date1.getTime();
long d2 = date2.getTime();
long diff = d1 - d2;
return diff / (daytimes);
}
/**
* 计算两个时间相差月数
*
* @param date1
* @param date2
* @return long
*/
public static int getDateSubMonths(Date date1, Date date2) {
int result = 0;
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
if (date2.after(date1)) {
c1.setTime(date1);
c2.setTime(date2);
} else {
c1.setTime(date2);
c2.setTime(date1);
}
result = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12
+ (c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH));
return result == 0 ? 1 : Math.abs(result);
}
/**
* 计算两个时间相差年数
*
* @param date1
* @param date2
* @return long
*/
public static int getDateSubYear(Date date1, Date date2) {
int result = 0;
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
if (date2.after(date1)) {
c1.setTime(date1);
c2.setTime(date2);
} else {
c1.setTime(date2);
c2.setTime(date1);
}
result = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR));
return result == 0 ? 1 : Math.abs(result);
}
/**
* 按指定格式获得日期
*
* @param sourceDate
* @param format
* @return
*/
public static Date getDateByFormat(Date sourceDate, String format) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat(format);
String dateString = f.format(sourceDate);
Date date = f.parse(dateString);
return date;
}
public static Date getDateByFormat(Date sourceDate) throws ParseException {
String dateString = dateFormat.format(sourceDate);
Date date = dateFormat.parse(dateString);
return date;
}
/**
* 按指定格式获得日期
*
* @param sourceDateStr
* @param format
* @return
*/
public static Date getDateByFormat(String sourceDateStr, String format) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat(format);
Date date = f.parse(sourceDateStr);
return date;
}
/**
* 判断是否超时
*
* @param startDate 开始时间
* @param intervalTime 间隔时间,以毫秒为单位
* @return
* @throws Exception
*/
public static boolean isTimeOut(Date startDate, long intervalTime) {
boolean ret = false;
Date currentDate = new Date();
long minuteDif = currentDate.getTime() - startDate.getTime();
if (minuteDif >= intervalTime) {
ret = true;
}
return ret;
}
/**
* 判断是否是在还款时间内还款 还款时间是指一天内可进行还款操作的时间 现规定可还款时间段为04:00:00--23:30:00
*
* @return
* @throws Exception
*/
public static boolean isRepaymentTime() throws Exception {
boolean ret = false;
Date currentDate = new Date();
String startDateStr = dateFormat.format(currentDate).concat(" 04:00:00");
String ednDateStr = dateFormat.format(currentDate).concat(" 23:30:00");
Date startDate = datetimeFormat.parse(startDateStr);
Date endDate = datetimeFormat.parse(ednDateStr);
if (currentDate.getTime() > startDate.getTime() && currentDate.getTime() < endDate.getTime()) {
ret = true;
}
return ret;
}
/***
* 判断该字符串是否能转换成日期类型(用户查询条件的check)
*
* @param sourceStr
* @return
*/
public static boolean isIllegalDate(String sourceStr) {
boolean ret = false;
if (!(StringUtils.isBlank(sourceStr)) && !(StringUtils.isEmpty(sourceStr))) {
try {
Date date = dateFormat.parse(sourceStr);
if (date != null)
return Boolean.TRUE;
} catch (ParseException e) {
return Boolean.FALSE;
}
}
return ret;
}
/**
* 获得指定日期的所在星期的星期一
*
* @param date
* @return Date
*/
public static Date getMondayByDate(Date date) {
Calendar c = calendar();
c.setTime(date);
c.add(Calendar.DATE, -(DateUtils.getNumByDate(date) - 1));
return c.getTime();
}
/**
* 获得指定日期的所在星期的星期日
*
* @param date
* @return Date
*/
public static Date getSundayByDate(Date date) {
Calendar c = calendar();
c.setTime(date);
c.add(Calendar.DATE, 7 - DateUtils.getNumByDate(date));
return c.getTime();
}
/**
* 获得当前日期为这个星期的第几天 如:1 : 星期一 、 7 : 星期日
*
* @param date
* @return int
*/
public static int getNumByDate(Date date) {
Calendar c = calendar();
c.setTime(date);
int i = c.get(Calendar.DAY_OF_WEEK) - 1;
return i != 0 ? i : 7;
}
/**
* 获取日期距离今天的天数
*
* @param date
* @return
*/
public static int getDaysBetweenToday(Date date) {
Calendar calendar = calendar();
calendar.setTime(date);
long betweenDays = (calendar.getTimeInMillis() - calendar().getTimeInMillis()) / (24 * 3600 * 1000);
return Integer.parseInt(String.valueOf(betweenDays));
}
/**
* 判断两个时间是否是同一天
*
* @param date1
* @param date2
* @return
*/
public static boolean isTheSameDay(Date date1, Date date2) {
Calendar c1 = calendar();
c1.setTime(date1);
Calendar c2 = calendar();
c2.setTime(date2);
return (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)) && (c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH))
&& (c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH));
}
/**
* 判断日期是否在这之前,只比较日期
*
* @param date
* @return
*/
public static boolean isBeforeToday(Date date) throws ParseException {
if (date == null) {
return Boolean.FALSE;
}
Date today = parseDate(currentDate());
if (today.getTime() > date.getTime()) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
// /**
// * 是否法定假日
// *
// * @param date
// * @return
// */
// public static boolean isHoliday(Date date) {
// Map<Date, DaysDtl> hmap = LabelManager.getHoliday();
// DaysDtl d = null;
// if (hmap.containsKey(date)) {
// d = hmap.get(date);
// return !d.isWork();
// }
// return Boolean.FALSE;
// }
/**
* 格式化日期
* <p>
* 日期格式yyyy/MM/dd
*
* @return
*/
public static String formatDateYMD(Date date) {
return dfs.format(date);
}
/**
* 判断是否是同一周
* @param oldDate
* @param newDate
* @return
*/
public static boolean isSameWeek(Date oldDate,Date newDate){
int od = weekOfYear(oldDate);
int nd = weekOfYear(newDate);
return Integer.compare(od, nd) == 0 ? true : false;
}
/**
* 获取今天剩余时间还剩多少秒
* @return 秒
*/
public static int getEndTime(){
Calendar curDate = Calendar.getInstance();
Calendar nextDayDate = new GregorianCalendar(curDate.get(Calendar.YEAR), curDate.get(Calendar.MONTH), curDate.get(Calendar.DATE)+1, 0, 0, 0);
return (int) ((nextDayDate.getTimeInMillis() - curDate.getTimeInMillis())/1000);
}
/**
* @Title: getStrAddMonth
* @Description: TODO(时间加减月)
* @param @param date
* @param @param subtractor
* @param @param pattern
* @param @return
* @param @throws Exception 设定文件
* @return String 返回类型
* @throws
*/
public static String getStrAddMonth(Date date, int subtractor, String pattern)throws Exception{
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, subtractor);
SimpleDateFormat format = new SimpleDateFormat(pattern);
String time = format.format(c.getTime());
return time;
}
}
\ No newline at end of file
package com.jz.common.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
public class IpUtil {
/**
* 获取登录用户IP地址
*
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip.equals("0:0:0:0:0:0:0:1")) {
ip = "本地";
}
return ip;
}
public static String getIpAddrzhijie(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)) {
// 多次反向代理后会有多个IP值,第一个为真实IP。
int index = ip.indexOf(',');
if (index != -1) {
return ip.substring(0, index);
} else {
return ip;
}
} else {
return request.getRemoteAddr();
}
}
public static String getMACAddress(String ip){
String str = "";
String macAddress = "";
try {
Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
InputStreamReader ir = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (int i = 1; i < 100; i++) {
str = input.readLine();
System.out.println(str);
if (str != null) {
if (str.indexOf("MAC Address") > 1) {
macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
break;
}
}
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
return macAddress;
}
/**
* 根据IP地址获取mac地址
*
* @param ipAddress
* 127.0.0.1
* @return
* @throws SocketException
* @throws UnknownHostException
*/
public static String getLocalMac(String ipAddress) throws SocketException,
UnknownHostException {
// TODO Auto-generated method stub
String str = "";
String macAddress = "";
final String LOOPBACK_ADDRESS = "127.0.0.1";
// 如果为127.0.0.1,则获取本地MAC地址。
if (LOOPBACK_ADDRESS.equals(ipAddress)) {
InetAddress inetAddress = InetAddress.getLocalHost();
// 貌似此方法需要JDK1.6。
byte[] mac = NetworkInterface.getByInetAddress(inetAddress)
.getHardwareAddress();
// 下面代码是把mac地址拼装成String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
if (i != 0) {
sb.append("-");
}
// mac[i] & 0xFF 是为了把byte转化为正整数
String s = Integer.toHexString(mac[i] & 0xFF);
sb.append(s.length() == 1 ? 0 + s : s);
}
// 把字符串所有小写字母改为大写成为正规的mac地址并返回
macAddress = sb.toString().trim().toUpperCase();
return macAddress;
} else {
// 获取非本地IP的MAC地址
try {
System.out.println(ipAddress);
Process p = Runtime.getRuntime().exec("nbtstat -A " + ipAddress);
System.out.println("===process==" + p);
InputStreamReader ir = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(ir);
System.out.println(br.toString());
while ((str = br.readLine()) != null) {
if (str.indexOf("MAC") > 1) {
macAddress = str.substring(str.indexOf("MAC") + 9,
str.length());
macAddress = macAddress.trim();
System.out.println("macAddress:" + macAddress);
break;
}
}
p.destroy();
br.close();
ir.close();
} catch (IOException ex) {
}
return macAddress;
}
}
public static List<String> getMacList() throws Exception {
java.util.Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
StringBuilder sb = new StringBuilder();
ArrayList<String> tmpMacList = new ArrayList<>();
while (en.hasMoreElements()) {
NetworkInterface iface = en.nextElement();
List<InterfaceAddress> addrs = iface.getInterfaceAddresses();
for (InterfaceAddress addr : addrs) {
InetAddress ip = addr.getAddress();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
if (network == null) {
continue;
}
byte[] mac = network.getHardwareAddress();
if (mac == null) {
continue;
}
sb.delete(0, sb.length());
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
tmpMacList.add(sb.toString());
}
}
if (tmpMacList.size() <= 0) {
return tmpMacList;
}
/*** 去重,别忘了同一个网卡的ipv4,ipv6得到的mac都是一样的,肯定有重复,下面这段代码是。。流式处理 ***/
List<String> unique = tmpMacList.stream().distinct().collect(Collectors.toList());
return unique;
}
public static String what(String ip) throws SocketException, UnknownHostException{
NetworkInterface ne=NetworkInterface.getByInetAddress(InetAddress.getByName(ip));
byte[]mac=ne.getHardwareAddress();
StringBuffer sb = new StringBuffer("");
for(int i=0; i<mac.length; i++) {
if(i!=0) {
sb.append("-");
}
//字节转换为整数
int temp = mac[i]&0xff;
String str = Integer.toHexString(temp);
System.out.println("每8位:"+str);
if(str.length()==1) {
sb.append("0"+str);
}else {
sb.append(str);
}
}
return sb.toString().toUpperCase();
}
public static void main(String[] args) throws Exception {
System.out.println(getMACAddress("192.168.31.50"));
}
}
package com.jz.common.utils;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.UnsupportedEncodingException;
/**
*
* @ClassName: MD5SignUtils
* @Description: TODO(data + 混淆串,用MD5算法签名)
* @author: niulichang
* @date: 2020年6月12日 下午2:39:51
* @最后修改人: niulichang
* @最后修改时间: 2020年6月12日 下午2:39:51
*/
public class MD5SignUtils {
private static final String DEFAULT_CHARSET = "UTF-8";
/**
* 签名
*
* @PARAM SRCSTR
* @PARAM SALT 作为MD5混淆
* @RETURN
*/
public static String sign(String srcStr) throws UnsupportedEncodingException {
return sign(srcStr, DEFAULT_CHARSET);
}
/**
* 签名
*
* @param srcStr
* @param salt 作为MD5混淆
* @return
*/
public static String sign(String srcStr, String charset) throws UnsupportedEncodingException {
return DigestUtils.md5Hex(getContentBytes(srcStr, charset));
}
/**
* 签名字符串
* @param text 需要签名的字符串
* @param sign 签名结果
* @param salt 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
public static boolean verify(String text, String sign, String input_charset) {
String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
if(mysign.equals(sign)) {
return true;
}
else {
return false;
}
}
/**
* @param content
* @param charset
* @return
* @throws UnsupportedEncodingException
*/
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
}
package com.jz.common.utils;
import java.security.MessageDigest;
import java.util.Random;
import org.apache.commons.codec.binary.Hex;
/**
* MD5加盐加密
*/
public class PasswordUtil {
/**
* 生成含有随机盐的密码
*/
public static String generate(String password) {
Random r = new Random();
StringBuilder sb = new StringBuilder(16);
sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
int len = sb.length();
if (len < 16) {
for (int i = 0; i < 16 - len; i++) {
sb.append("0");
}
}
String salt = sb.toString();
password = md5Hex(password + salt);
char[] cs = new char[48];
for (int i = 0; i < 48; i += 3) {
cs[i] = password.charAt(i / 3 * 2);
char c = salt.charAt(i / 3);
cs[i + 1] = c;
cs[i + 2] = password.charAt(i / 3 * 2 + 1);
}
return new String(cs);
}
/**
* 生成含有随机盐的密码
*/
public static String generateMd5(String password, String salt) {
password = md5Hex(password + salt);
// char[] cs = new char[48];
// for (int i = 0; i < 48; i += 3) {
// cs[i] = password.charAt(i / 3 * 2);
// char c = salt.charAt(i / 3);
// cs[i + 1] = c;
// cs[i + 2] = password.charAt(i / 3 * 2 + 1);
// }
return password;
}
/**
* 校验密码是否正确
*/
public static boolean verify(String password, String md5) {
char[] cs1 = new char[32];
char[] cs2 = new char[16];
for (int i = 0; i < 48; i += 3) {
cs1[i / 3 * 2] = md5.charAt(i);
cs1[i / 3 * 2 + 1] = md5.charAt(i + 2);
cs2[i / 3] = md5.charAt(i + 1);
}
String salt = new String(cs2);
// System.out.println("取出盐值" + salt);
return md5Hex(password + salt).equals(new String(cs1));
}
/**
* 获取十六进制字符串形式的MD5摘要
*/
public static String md5Hex(String src) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] bs = md5.digest(src.getBytes());
return new String(new Hex().encode(bs));
} catch (Exception e) {
return null;
}
}
public static void main(String[] args) {
// 27756851e315a3f124a6505b795177b0d664d1d64dd3da0c
// System.out.println(verify("123456","409c2a69a24ed6db30e25a3ba56993103a8966657842ad2a"));
//
// String pwd1=generateMd5("123456","admin");
// String pwd2= generate(pwd1);
// System.out.println("pwa1===="+pwd1);
// System.out.println("pwa2===="+pwd2);
// System.out.println(verify(pwd1, pwd2));
String password1 = generate("111111");
//a1ee17a8d73db50f99b72a5249b86bc2f10cc3105324b28e
System.out.println("结果:" + password1 +"验证"+ verify("111111", password1));
// 加密+加盐
}
}
\ No newline at end of file
package com.jz.common.utils;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
* RSA 工具类。提供加密,解密,生成密钥对等方法。
* 需要到http://www.bouncycastle.org下载bcprov-jdk14-123.jar。
*
*/
public class RSAUtils {
public static final String KEY_ALGORITHM = "RSA";
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
private static final String PUBLIC_KEY = "RSAPublicKey";
private static final String PRIVATE_KEY = "RSAPrivateKey";
public static byte[] decryptBASE64(String key) {
return Base64.decodeBase64(key);
}
public static String encryptBASE64(byte[] bytes) {
return Base64.encodeBase64String(bytes);
}
/**
* 用私钥对信息生成数字签名
*
* @param data 加密数据
* @param privateKey 私钥
* @return
* @throws Exception
*/
public static String sign(byte[] data, String privateKey) throws Exception {
// 解密由base64编码的私钥
byte[] keyBytes = decryptBASE64(privateKey);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// 取私钥匙对象
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 用私钥对信息生成数字签名
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(priKey);
signature.update(data);
return encryptBASE64(signature.sign());
}
/**
* 校验数字签名
*
* @param data 加密数据
* @param publicKey 公钥
* @param sign 数字签名
* @return 校验成功返回true 失败返回false
* @throws Exception
*/
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
// 解密由base64编码的公钥
byte[] keyBytes = decryptBASE64(publicKey);
// 构造X509EncodedKeySpec对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// 取公钥匙对象
PublicKey pubKey = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(pubKey);
signature.update(data);
// 验证签名是否正常
return signature.verify(decryptBASE64(sign));
}
public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception {
// 对密钥解密
byte[] keyBytes = decryptBASE64(key);
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
}
/**
* 解密<br>
* 用私钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(String data, String key) {
try {
return decryptByPrivateKey(decryptBASE64(data), key);
} catch (Exception e) {
}
return null;
}
/**
* 解密<br>
* 用公钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptByPublicKey(byte[] data, String key) throws Exception {
// 对密钥解密
byte[] keyBytes = decryptBASE64(key);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);