Java源码示例:cn.hutool.core.date.DateUnit
示例1
public CommonResponse resetBlockDataByBlockId(long blockHeight) throws IOException {
Optional<BlockTaskPool> blockTaskPool = blockTaskPoolRepository.findByBlockHeight(blockHeight);
if (!blockTaskPool.isPresent()) {
return CommonResponse.NOBLOCK;
}
if (blockTaskPool.get().getSyncStatus() == TxInfoStatusEnum.DOING.getStatus()) {
return ResponseUtils.error("Some task is still running. please resend the request later.");
}
if (blockTaskPool.get().getSyncStatus() == TxInfoStatusEnum.RESET.getStatus()) {
if (DateUtil.between(blockTaskPool.get().getDepotUpdatetime(), DateUtil.date(), DateUnit.SECOND) < 60) {
return ResponseUtils.error("The block is already in progress to reset. please send the request later");
}
}
log.info("begin to refetch block {}", blockHeight);
blockTaskPoolRepository.setSyncStatusByBlockHeight((short) TxInfoStatusEnum.RESET.getStatus(), new Date(),
blockHeight);
rollBackService.rollback(blockHeight, blockHeight + 1);
singleBlockCrawlerService.parse(blockHeight);
blockTaskPoolRepository.setSyncStatusByBlockHeight((short) TxInfoStatusEnum.DONE.getStatus(), new Date(),
blockHeight);
log.info("block {} is reset!", blockHeight);
return ResponseUtils.success();
}
示例2
/**
* 后台首页
*
* @return
*/
@RequestMapping(value = { "", "index" })
public String index(Model model) {
// 查询已发布文章数
Integer countPublish = articleService.countByStatus(null, PostType.POST_TYPE_POST.getValue());
model.addAttribute("countPublish", countPublish);
// 友链总数
List<Link> lists = linksService.findLinks();
model.addAttribute("countLinks", lists.size());
// 附件总数
int countAttachment = attachmentService.countAttachment().size();
model.addAttribute("countAttachment", countAttachment);
// 成立天数
Date blogStart=DateUtil.parse(MaydayConst.OPTIONS.get("blog_start").toString());
model.addAttribute("establishDate", DateUtil.between(blogStart, DateUtil.date(), DateUnit.DAY));
// 查询最新的文章
ArticleCustom articleCustom = new ArticleCustom();
articleCustom.setArticlePost(PostType.POST_TYPE_POST.getValue());
PageInfo<ArticleCustom> pageInfo = articleService.findPageArticle(1, 5, articleCustom);
model.addAttribute("articles", pageInfo.getList());
// 查询最新的日志
PageInfo<Log> info = logService.findLogs(1, 5);
model.addAttribute("logs", info.getList());
return "admin/admin_index";
}
示例3
/**
* 获取网站详情
*/
@Override
public Map<String, Object> getSiteInfo() {
Map<String, Object> siteInfo = sysConfigMapper.getSiteInfo();
if (!CollectionUtils.isEmpty(siteInfo)) {
Date installdate = null;
SysConfig config = this.getByKey(ConfigKeyEnum.INSTALLDATE.getKey());
if (null == config || StringUtils.isEmpty(config.getConfigValue())) {
// 默认建站日期为2019-01-01
installdate = Date.from(LocalDate.of(2019, 1, 1).atStartOfDay(ZoneId.systemDefault()).toInstant());
} else {
installdate = DateUtil.parse(config.getConfigValue(), DatePattern.NORM_DATETIME_PATTERN);
}
long between = 1;
if (!installdate.after(new Date())) {
between = DateUtil.between(installdate, new Date(), DateUnit.DAY);
}
siteInfo.put("installdate", between < 1 ? 1 : between);
}
return siteInfo;
}
示例4
/**
* JDK运行时间
*/
public String getRunTime() {
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
Date date = new Date(time);
//运行多少分钟
long runMS = DateUtil.between(date, new Date(), DateUnit.MS);
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long day = runMS / nd;
long hour = runMS % nd / nh;
long min = runMS % nd % nh / nm;
return day + "天" + hour + "小时" + min + "分钟";
}
示例5
/**
* 无数据补0
* @param startTime
* @param endTime
*/
public List<OrderChartData> getFullData(List<OrderChartData> data,Date startTime, Date endTime){
List<OrderChartData> fullData = new ArrayList<>();
//相差
long betweenDay = DateUtil.between(startTime, endTime, DateUnit.DAY);
//起始时间
Date everyday = startTime;
int count = -1;
for(int i=0;i<=betweenDay;i++){
boolean flag = true;
for(OrderChartData chartData:data){
if(DateUtils.isSameDay(chartData.getTime(),everyday)){
//有数据
flag = false;
count++;
break;
}
}
if(!flag){
fullData.add(data.get(count));
}else{
OrderChartData orderChartData = new OrderChartData();
orderChartData.setTime(everyday);
orderChartData.setMoney(new BigDecimal("0"));
fullData.add(orderChartData);
}
//时间+1天
Calendar cal = Calendar.getInstance();
cal.setTime(everyday);
cal.add(Calendar.DAY_OF_MONTH, 1);
everyday = cal.getTime();
}
return fullData;
}
示例6
/**
* 请求后台页面
*
* @param model model
* @param session session
*
* @return 模板路径admin/admin_index
*/
@GetMapping(value = {"", "/index"})
public String index(Model model) {
//查询评论的条数
final Long commentCount = commentService.getCount();
model.addAttribute("commentCount", commentCount);
//查询最新的文章
final List<Post> postsLatest = postService.findPostLatest();
model.addAttribute("postTopFive", postsLatest);
//查询最新的日志
final List<Logs> logsLatest = logsService.findLogsLatest();
model.addAttribute("logs", logsLatest);
//查询最新的评论
final List<Comment> comments = commentService.findCommentsLatest();
model.addAttribute("comments", comments);
//附件数量
model.addAttribute("mediaCount", attachmentService.getCount());
//文章阅读总数
final Long postViewsSum = postService.getPostViews();
model.addAttribute("postViewsSum", postViewsSum);
//成立天数
final Date blogStart = DateUtil.parse(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_START.getProp()));
final long hadDays = DateUtil.between(blogStart, DateUtil.date(), DateUnit.DAY);
model.addAttribute("hadDays", hadDays);
return "admin/admin_index";
}
示例7
@ApiOperation("DateUtil使用:日期时间工具")
@GetMapping(value = "/dateUtil")
public CommonResult dateUtil() {
//Date、long、Calendar之间的相互转换
//当前时间
Date date = DateUtil.date();
//Calendar转Date
date = DateUtil.date(Calendar.getInstance());
//时间戳转Date
date = DateUtil.date(System.currentTimeMillis());
//自动识别格式转换
String dateStr = "2017-03-01";
date = DateUtil.parse(dateStr);
//自定义格式化转换
date = DateUtil.parse(dateStr, "yyyy-MM-dd");
//格式化输出日期
String format = DateUtil.format(date, "yyyy-MM-dd");
//获得年的部分
int year = DateUtil.year(date);
//获得月份,从0开始计数
int month = DateUtil.month(date);
//获取某天的开始、结束时间
Date beginOfDay = DateUtil.beginOfDay(date);
Date endOfDay = DateUtil.endOfDay(date);
//计算偏移后的日期时间
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
//计算日期时间之间的偏移量
long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);
return CommonResult.success(null, "操作成功");
}
示例8
/**
* 请求后台页面
*
* @param model model
* @param session session
* @return 模板路径admin/admin_index
*/
@GetMapping(value = {"", "/index"})
public String index(Model model) {
//查询评论的条数
Long commentCount = commentService.getCount();
model.addAttribute("commentCount", commentCount);
//查询最新的文章
List<Post> postsLatest = postService.findPostLatest();
model.addAttribute("postTopFive", postsLatest);
//查询最新的日志
List<Logs> logsLatest = logsService.findLogsLatest();
model.addAttribute("logs", logsLatest);
//查询最新的评论
List<Comment> comments = commentService.findCommentsLatest();
model.addAttribute("comments", comments);
//附件数量
model.addAttribute("mediaCount", attachmentService.getCount());
//文章阅读总数
Long postViewsSum = postService.getPostViews();
model.addAttribute("postViewsSum", postViewsSum);
//成立天数
Date blogStart = DateUtil.parse(HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_START.getProp()));
long hadDays = DateUtil.between(blogStart, DateUtil.date(), DateUnit.DAY);
model.addAttribute("hadDays",hadDays);
return "admin/admin_index";
}
示例9
/**
* 认证信息(身份验证) Authentication 是用来验证用户身份
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
log.info("认证-->MyShiroRealm.doGetAuthenticationInfo()");
//1.验证用户名
User user = null;
String account = (String) token.getPrincipal();
if (Validator.isEmail(account)) {
user = userService.findByEmail(account);
} else {
user = userService.findByUserName(account);
}
if (user == null) {
//用户不存在
log.info("用户不存在! 登录名:{}, 密码:{}", account, token.getCredentials());
return null;
}
//2.判断账号是否被封号
if (!Objects.equals(user.getStatus(), UserStatusEnum.NORMAL.getCode())) {
throw new LockedAccountException(localeMessageUtil.getMessage("code.admin.login.disabled.forever"));
}
//3.首先判断是否已经被禁用已经是否已经过了10分钟
Date loginLast = DateUtil.date();
if (null != user.getLoginLast()) {
loginLast = user.getLoginLast();
}
Long between = DateUtil.between(loginLast, DateUtil.date(), DateUnit.MINUTE);
if (StringUtils.equals(user.getLoginEnable(), TrueFalseEnum.FALSE.getValue()) && (between < CommonParamsEnum.TEN.getValue())) {
log.info("账号已锁定! 登录名:{}, 密码:{}", account, token.getCredentials());
throw new LockedAccountException(localeMessageUtil.getMessage("code.admin.login.disabled"));
}
//4.封装authenticationInfo,准备验证密码
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
user, // 用户名
user.getUserPass(), // 密码
ByteSource.Util.bytes("sens"), // 盐
getName() // realm name
);
System.out.println("realName:" + getName());
return authenticationInfo;
}
示例10
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// 防止流读取一次后就没有了, 所以需要将流继续写出去
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletRequest requestWrapper = new RequestWrapper(httpRequest);
Set<String> uriSet = new HashSet<>(securityProperties.getIgnoreSignUri());
String requestUri = httpRequest.getRequestURI();
boolean isMatch = false;
for (String uri : uriSet) {
isMatch = requestUri.contains(uri);
if (isMatch) {
break;
}
}
log.info("当前请求的URI是==>{},isMatch==>{}", httpRequest.getRequestURI(), isMatch);
if (isMatch) {
filterChain.doFilter(requestWrapper, response);
return;
}
String sign = requestWrapper.getHeader("Sign");
Long timestamp = Convert.toLong(requestWrapper.getHeader("Timestamp"));
if (StrUtil.isEmpty(sign)) {
returnFail("签名不允许为空", response);
return;
}
if (timestamp == null) {
returnFail("时间戳不允许为空", response);
return;
}
//重放时间限制(单位分)
Long difference = DateUtil.between(DateUtil.date(), DateUtil.date(timestamp * 1000), DateUnit.MINUTE);
if (difference > securityProperties.getSignTimeout()) {
returnFail("已过期的签名", response);
log.info("前端时间戳:{},服务端时间戳:{}", DateUtil.date(timestamp * 1000), DateUtil.date());
return;
}
boolean accept = true;
SortedMap<String, String> paramMap;
switch (requestWrapper.getMethod()) {
case "GET":
paramMap = HttpUtil.getUrlParams(requestWrapper);
accept = SignUtil.verifySign(paramMap, sign, timestamp);
break;
case "POST":
case "PUT":
case "DELETE":
paramMap = HttpUtil.getBodyParams(requestWrapper);
accept = SignUtil.verifySign(paramMap, sign, timestamp);
break;
default:
accept = true;
break;
}
if (accept) {
filterChain.doFilter(requestWrapper, response);
} else {
returnFail("签名验证不通过", response);
}
}
示例11
/**
* 验证登录信息
*
* @param loginName 登录名:邮箱/用户名
* @param loginPwd loginPwd 密码
* @param session session session
*
* @return JsonResult JsonResult
*/
@PostMapping(value = "/getLogin")
@ResponseBody
public JsonResult getLogin(@ModelAttribute("loginName") String loginName,
@ModelAttribute("loginPwd") String loginPwd,
HttpSession session) {
//已注册账号,单用户,只有一个
final User aUser = userService.findUser();
//首先判断是否已经被禁用已经是否已经过了10分钟
Date loginLast = DateUtil.date();
if (null != aUser.getLoginLast()) {
loginLast = aUser.getLoginLast();
}
final Long between = DateUtil.between(loginLast, DateUtil.date(), DateUnit.MINUTE);
if (StrUtil.equals(aUser.getLoginEnable(), TrueFalseEnum.FALSE.getDesc()) && (between < CommonParamsEnum.TEN.getValue())) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.disabled"));
}
//验证用户名和密码
User user = null;
if (Validator.isEmail(loginName)) {
user = userService.userLoginByEmail(loginName, SecureUtil.md5(loginPwd));
} else {
user = userService.userLoginByName(loginName, SecureUtil.md5(loginPwd));
}
userService.updateUserLoginLast(DateUtil.date());
//判断User对象是否相等
if (ObjectUtil.equal(aUser, user)) {
session.setAttribute(HaloConst.USER_SESSION_KEY, aUser);
//重置用户的登录状态为正常
userService.updateUserNormal();
logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_SUCCESS, request);
log.info("User {} login succeeded.", aUser.getUserDisplayName());
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.login.success"));
} else {
//更新失败次数
final Integer errorCount = userService.updateUserLoginError();
//超过五次禁用账户
if (errorCount >= CommonParamsEnum.FIVE.getValue()) {
userService.updateUserLoginEnable(TrueFalseEnum.FALSE.getDesc());
}
logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_ERROR + "[" + HtmlUtil.escape(loginName) + "," + HtmlUtil.escape(loginPwd) + "]", request);
final Object[] args = {(5 - errorCount)};
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.failed", args));
}
}
示例12
@Override
protected void onRun() {
SysLog sysLog = new SysLog();
HttpServletRequest request = RequestHolder.getRequest();
String ip = IpUtils.getIpAddr(request);
sysLog.setIp(ip);
//从Redis中获取IP来源
String jsonResult = redisUtil.get(SysConf.IP_SOURCE + BaseSysConf.REDIS_SEGMENTATION + ip);
if (StringUtils.isEmpty(jsonResult)) {
String addresses = IpUtils.getAddresses(SysConf.IP + SysConf.EQUAL_TO + ip, SysConf.UTF_8);
if (StringUtils.isNotEmpty(addresses)) {
sysLog.setIpSource(addresses);
redisUtil.setEx(SysConf.IP_SOURCE + BaseSysConf.REDIS_SEGMENTATION + ip, addresses, 24, TimeUnit.HOURS);
}
} else {
sysLog.setIpSource(jsonResult);
}
//设置请求信息
sysLog.setIp(ip);
//设置调用的类
sysLog.setClassPath(classPath);
//设置调用的方法
sysLog.setMethod(methodName);
//设置Request的请求方式 GET POST
sysLog.setType(request.getMethod());
sysLog.setUrl(request.getRequestURI());
sysLog.setOperation(operationName);
sysLog.setCreateTime(new Date());
sysLog.setUpdateTime(new Date());
SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
sysLog.setUserName(securityUser.getUsername());
sysLog.setAdminUid(securityUser.getUid());
sysLog.setParams(paramsJson);
Date endTime = new Date();
Long spendTime = DateUtil.between(startTime, endTime, DateUnit.MS);
// 计算请求接口花费的时间,单位毫秒
sysLog.setSpendTime(spendTime);
sysLog.insert();
}
示例13
/**
* 验证
*
* @param userName
* 用户名
* @param userPwd
* 用户密码
* @param session
* @return
*/
@PostMapping(value = "getLogin")
@ResponseBody
public JsonResult getLogin(@RequestParam(value = "userName") String userName,
@RequestParam(value = "userPwd") String userPwd, HttpSession session) {
try {
// 禁止时间10分钟
int inhibitTime = 10;
// 为true禁止登录
String flag = "true";
// 错误总次数5次
int errorCount = 5;
// 已注册用户
User users = userService.findUser();
// 判断账户是否被禁用十分钟
Date date = DateUtil.date();
if (users.getLoginLastTime() != null) {
date = users.getLoginLastTime();
}
// 计算两个日期之间的时间差
long between = DateUtil.between(date, DateUtil.date(), DateUnit.MINUTE);
if (StrUtil.equals(users.getLoginEnable(), flag) && (between < inhibitTime)) {
return new JsonResult(false, "账户被禁止登录10分钟,请稍后重试");
}
// 验证用户名密码
User user = userService.getByNameAndPwd(userName, SecureUtil.md5(userPwd));
// 修改最后登录时间
userService.updateLoginLastTime(DateUtil.date(), users.getUserId());
if (user != null) {
session.setAttribute(MaydayConst.USER_SESSION_KEY, user);
// 登录成功重置用户状态为正常
userService.updateUserNormal(user.getUserId());
// 添加登录日志
logService.save(new Log(LogConstant.LOGIN, LogConstant.LOGIN_SUCCES, ServletUtil.getClientIP(request),
DateUtil.date()));
log.info(userName + "登录成功");
return new JsonResult(true, "登录成功");
} else {
Integer error = userService.updateError();
if (error == errorCount) {
userService.updateLoginEnable("true",0);
}else if(error==1) {
userService.updateLoginEnable("false",1);
}
// 添加失败日志
logService.save(new Log(LogConstant.LOGIN, LogConstant.LOGIN_ERROR, ServletUtil.getClientIP(request),
DateUtil.date()));
return new JsonResult(false, "用户名或密码错误!你还有" + (5 - error) + "次机会");
}
} catch (Exception e) {
log.error("登录失败,系统错误!",e);
return new JsonResult(false, "未知错误!");
}
}
示例14
/**
* 验证登录信息
*
* @param loginName 登录名:邮箱/用户名
* @param loginPwd loginPwd 密码
* @param session session session
* @return JsonResult JsonResult
*/
@PostMapping(value = "/getLogin")
@ResponseBody
public JsonResult getLogin(@ModelAttribute("loginName") String loginName,
@ModelAttribute("loginPwd") String loginPwd,
HttpSession session) {
//已注册账号,单用户,只有一个
User aUser = userService.findUser();
//首先判断是否已经被禁用已经是否已经过了10分钟
Date loginLast = DateUtil.date();
if (null != aUser.getLoginLast()) {
loginLast = aUser.getLoginLast();
}
Long between = DateUtil.between(loginLast, DateUtil.date(), DateUnit.MINUTE);
if (StrUtil.equals(aUser.getLoginEnable(), TrueFalseEnum.FALSE.getDesc()) && (between < CommonParamsEnum.TEN.getValue())) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.disabled"));
}
//验证用户名和密码
User user = null;
if (Validator.isEmail(loginName)) {
user = userService.userLoginByEmail(loginName, SecureUtil.md5(loginPwd));
} else {
user = userService.userLoginByName(loginName, SecureUtil.md5(loginPwd));
}
userService.updateUserLoginLast(DateUtil.date());
//判断User对象是否相等
if (ObjectUtil.equal(aUser, user)) {
session.setAttribute(HaloConst.USER_SESSION_KEY, aUser);
//重置用户的登录状态为正常
userService.updateUserNormal();
logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_SUCCESS, request);
log.info("User {} login succeeded.", aUser.getUserDisplayName());
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.login.success"));
} else {
//更新失败次数
Integer errorCount = userService.updateUserLoginError();
//超过五次禁用账户
if (errorCount >= CommonParamsEnum.FIVE.getValue()) {
userService.updateUserLoginEnable(TrueFalseEnum.FALSE.getDesc());
}
logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_ERROR + "[" + HtmlUtil.escape(loginName) + "," + HtmlUtil.escape(loginPwd) + "]", request);
Object[] args = {(5 - errorCount)};
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.failed", args));
}
}