cn.hutool.core.date.DateUtil Java Examples

The following examples show how to use cn.hutool.core.date.DateUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SysUserServiceTest.java    From fw-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 构建实体
 */
private SysUser initEntity(){
    SysUser sysUser=new SysUser();
    sysUser.setId(RandomUtil.randomLong());
    sysUser.setCreateTime(DateUtil.date());
    sysUser.setUpdateTime(DateUtil.date());
    sysUser.setCreateUser("sys");
    sysUser.setUpdateUser("sys");
    sysUser.setDeleteFlag(1);
    sysUser.setDisableFlag(1);
    sysUser.setPosCode("pos");
    sysUser.setAvatar("avatar");
    sysUser.setEmail(RandomUtil.randomNumber()+"@qq.com");
    sysUser.setPassword("123456");
    sysUser.setUserName("root");
    sysUser.setRealName("fwcloud");
    sysUser.setDeptCode("dept");
    sysUser.setUserPhone(String.valueOf(RandomUtil.randomNumber()));
    return sysUser;
}
 
Example #2
Source File: TomcatEditController.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 添加Tomcat
 *
 * @param tomcatInfoModel Tomcat信息
 * @return 操作结果
 */
@RequestMapping(value = "add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String add(TomcatInfoModel tomcatInfoModel) {
    // 根据Tomcat名称查询tomcat是否已经存在
    String name = tomcatInfoModel.getName();
    TomcatInfoModel tomcatInfoModelTemp = tomcatEditService.getItemByName(name);
    if (tomcatInfoModelTemp != null) {
        return JsonMessage.getString(401, "名称已经存在,请使用其他名称!");
    }
    tomcatInfoModel.setId(SecureUtil.md5(DateUtil.now()));
    tomcatInfoModel.setCreator(getUserName());

    // 设置tomcat路径,去除多余的符号
    tomcatInfoModel.setPath(FileUtil.normalize(tomcatInfoModel.getPath()));
    Objects.requireNonNull(tomcatInfoModel.pathAndCheck());
    tomcatEditService.addItem(tomcatInfoModel);
    tomcatInfoModel.initTomcat();
    return JsonMessage.getString(200, "保存成功");
}
 
Example #3
Source File: DbLogInterceptor.java    From Aooms with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

    boolean logEnable = Aooms.self().getPropertyObject().getAoomsProperty().getGlobal().isLogEnable();
    if(logEnable){
        AuthenticationInfo authenticationInfo = SSOAuthentication.getAuthenticationInfo();
        if(authenticationInfo != null) {
            Record record = new Record();
            record.set(AoomsVar.ID, IDGenerator.getStringValue());
            record.set("user_id", authenticationInfo.getId());
            record.set("user_account", authenticationInfo.getAccount());
            record.set("user_name", authenticationInfo.getUserName());
            record.set("create_time", DateUtil.now());
            record.set("ip_address", IpHelper.getIpAddr(AoomsContext.getRequest()));
            record.set("status", "0");  //0 - 正常  1 - 错误日志
            record.set("resource_url", AoomsContext.getRequest().getRequestURI());
            record.set("cost", System.currentTimeMillis());
            request.setAttribute(DB_LOGGER ,record);
        }
    }
    return  true;
}
 
Example #4
Source File: OrderTest.java    From java-tutorial with MIT License 6 votes vote down vote up
@Test
public void TestOrderType() throws IllegalAccessException {
    OrderDTO order = new OrderDTO();
    order.setOrderId(RandomUtil.randomNumbers(8));
    order.setOrderType(2);
    order.setPrice(127300.46f);
    order.setOrderDate(DateUtil.parseDate("2019-08-08 12:12"));

    String result = orderService.handleOrder(order);
    System.out.println(order.toString());
    System.out.println(result);

    System.out.println("\n===========================================================================\n");

    order.setOrderId(RandomUtil.randomNumbers(8));
    order.setOrderType(1);
    order.setPrice(145500.46f);
    order.setOrderDate(DateUtil.parseDate("2019-09-09 12:12"));

    result = orderService.handleOrder(order);
    System.out.println(order.toString());
    System.out.println(result);

}
 
Example #5
Source File: OrderTask.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
public void cancelOrder(){
    Date now = new Date();
    logger.info("取消超时未支付订单。。。");
    // 获取30分钟之前未支付的订单
    List<Order> orders = orderService.listOrderAndOrderItems(OrderStatus.UNPAY.value(),DateUtil.offsetMinute(now, -30));
    if (CollectionUtil.isEmpty(orders)) {
        return;
    }
    orderService.cancelOrders(orders);
    for (Order order : orders) {
        List<OrderItem> orderItems = order.getOrderItems();
        for (OrderItem orderItem : orderItems) {
            productService.removeProductCacheByProdId(orderItem.getProdId());
            skuService.removeSkuCacheBySkuId(orderItem.getSkuId(),orderItem.getProdId());
        }
    }
}
 
Example #6
Source File: OrgService.java    From Aooms with Apache License 2.0 6 votes vote down vote up
@Transactional
public void update() {
       Record record = Record.empty();
       record.setByJsonKey("formData");
       record.set("update_time",DateUtil.now());
       /*String parentId = record.getString("parent_org_id");
       String orgPermission = this.permissionCode(parentId);
       record.set("org_permission", orgPermission);
       record.set("org_level", this.orgLevel(record.getString("parent_org_id")) + 1);
       record.set("data_permission", this.dataPermission(parentId,orgPermission));*/
       db.update("aooms_rbac_org",record);
       this.rebuildDataPermission();

       record.set("icon","el-icon-news");
       this.setResultValue(AoomsVar.RS_VO, record);
   }
 
Example #7
Source File: BaseServerController.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 处理分页的时间字段
 *
 * @param page    分页
 * @param entity  条件
 * @param colName 字段名称
 */
protected void doPage(Page page, Entity entity, String colName) {
    String time = getParameter("time");
    colName = colName.toUpperCase();
    page.addOrder(new Order(colName, Direction.DESC));
    // 时间
    if (StrUtil.isNotEmpty(time)) {
        String[] val = StrUtil.split(time, "~");
        if (val.length == 2) {
            DateTime startDateTime = DateUtil.parse(val[0], DatePattern.NORM_DATETIME_FORMAT);
            entity.set(colName, ">= " + startDateTime.getTime());

            DateTime endDateTime = DateUtil.parse(val[1], DatePattern.NORM_DATETIME_FORMAT);
            if (startDateTime.equals(endDateTime)) {
                endDateTime = DateUtil.endOfDay(endDateTime);
            }
            // 防止字段重复
            entity.set(colName + " ", "<= " + endDateTime.getTime());
        }
    }
}
 
Example #8
Source File: NoBootTest.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testBeanUtil() {

    //10000 - 511
    //50000 - 719
    //100000 - 812
    //1000000 - 2303

    TimeInterval timer = DateUtil.timer();
    for (int i = 0; i <= 1000000; i++) {
        Org org = Org.builder()
                .label("string")
                .id(123L + i)
                .createTime(LocalDateTime.now())
                .build();
        Station station = Station.builder().id(1L + i).name("nihaoa").createTime(LocalDateTime.now()).orgId(new RemoteData(12L, org)).build();

        StationPageDTO stationPageDTO = new StationPageDTO();

        BeanUtil.copyProperties(station, stationPageDTO);
    }

    long interval = timer.interval();// 花费毫秒数
    long intervalMinute = timer.intervalMinute();// 花费分钟数
    StaticLog.info("本次程序执行 花费毫秒数: {} ,   花费分钟数:{} . ", interval, intervalMinute);
}
 
Example #9
Source File: BackupController.java    From blog-sharon with Apache License 2.0 6 votes vote down vote up
/**
 * 备份资源文件 重要
 *
 * @return JsonResult
 */
public JsonResult backupResources() {
    try {
        if (HaloUtils.getBackUps(BackupTypeEnum.RESOURCES.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
            FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/resources/");
        }
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        String srcPath = path.getAbsolutePath();
        String distName = "resources_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        //执行打包
        ZipUtil.zip(srcPath, System.getProperties().getProperty("user.home") + "/halo/backup/resources/" + distName + ".zip");
        log.info("Current time: {}, the resource file backup was performed.", DateUtil.now());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
    } catch (Exception e) {
        log.error("Backup resource file failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
    }
}
 
Example #10
Source File: HaloUtils.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取sitemap
 *
 * @param posts posts
 *
 * @return String
 */
public static String getSiteMap(List<Post> posts) {
    Assert.notEmpty(posts, "post mut not be empty");
    final StrBuilder head = new StrBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
    final StrBuilder urlBody = new StrBuilder();
    final String urlPath = HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/archives/";
    for (Post post : posts) {
        urlBody.append("<url><loc>");
        urlBody.append(urlPath);
        urlBody.append(post.getPostUrl());
        urlBody.append("</loc><lastmod>");
        urlBody.append(DateUtil.format(post.getPostDate(), "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"));
        urlBody.append("</lastmod></url>");
    }
    return head.append(urlBody).append("</urlset>").toString();
}
 
Example #11
Source File: DataInitTest.java    From spring-boot-demo with MIT License 6 votes vote down vote up
private User createUser(boolean isAdmin) {
    User user = new User();
    user.setId(snowflake.nextId());
    user.setUsername(isAdmin ? "admin" : "user");
    user.setNickname(isAdmin ? "管理员" : "普通用户");
    user.setPassword(encoder.encode("123456"));
    user.setBirthday(DateTime.of("1994-11-22", "yyyy-MM-dd")
            .getTime());
    user.setEmail((isAdmin ? "admin" : "user") + "@xkcoding.com");
    user.setPhone(isAdmin ? "17300000000" : "17300001111");
    user.setSex(1);
    user.setStatus(1);
    user.setCreateTime(DateUtil.current(false));
    user.setUpdateTime(DateUtil.current(false));
    userDao.save(user);
    return user;
}
 
Example #12
Source File: JwtUtil.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 创建JWT
 *
 * @param rememberMe  记住我
 * @param id          用户id
 * @param subject     用户名
 * @param roles       用户角色
 * @param authorities 用户权限
 * @return JWT
 */
public String createJWT(Boolean rememberMe, Long id, String subject, List<String> roles, Collection<? extends GrantedAuthority> authorities) {
    Date now = new Date();
    JwtBuilder builder = Jwts.builder()
            .setId(id.toString())
            .setSubject(subject)
            .setIssuedAt(now)
            .signWith(SignatureAlgorithm.HS256, jwtConfig.getKey())
            .claim("roles", roles)
            .claim("authorities", authorities);

    // 设置过期时间
    Long ttl = rememberMe ? jwtConfig.getRemember() : jwtConfig.getTtl();
    if (ttl > 0) {
        builder.setExpiration(DateUtil.offsetMillisecond(now, ttl.intValue()));
    }

    String jwt = builder.compact();
    // 将生成的JWT保存至Redis
    stringRedisTemplate.opsForValue()
            .set(Consts.REDIS_JWT_KEY_PREFIX + subject, jwt, ttl, TimeUnit.MILLISECONDS);
    return jwt;
}
 
Example #13
Source File: BackupController.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 备份资源文件 重要
 *
 * @return JsonResult
 */
public JsonResult backupResources() {
    try {
        if (HaloUtils.getBackUps(BackupTypeEnum.RESOURCES.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
            FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/resources/");
        }
        final File path = new File(ResourceUtils.getURL("classpath:").getPath());
        final String srcPath = path.getAbsolutePath();
        final String distName = "resources_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        //执行打包
        ZipUtil.zip(srcPath, System.getProperties().getProperty("user.home") + "/halo/backup/resources/" + distName + ".zip");
        log.info("Current time: {}, the resource file backup was performed.", DateUtil.now());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
    } catch (Exception e) {
        log.error("Backup resource file failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
    }
}
 
Example #14
Source File: BlockCheckService.java    From WeBASE-Collect-Bee with Apache License 2.0 6 votes vote down vote up
public void checkTimeOut() {
    Date offsetDate = DateUtil.offsetSecond(DateUtil.date(), 0 - BlockConstants.DEPOT_TIME_OUT);
    log.info("Begin to check timeout transactions which is ealier than {}", offsetDate);
    List<BlockTaskPool> list = blockTaskPoolRepository
            .findBySyncStatusAndDepotUpdatetimeLessThan((short) TxInfoStatusEnum.DOING.getStatus(), offsetDate);
    if (!CollectionUtils.isEmpty(list)) {
        log.info("Detect {} timeout transactions.", list.size());
    }
    list.forEach(p -> {
        log.error("Block {} sync block timeout!!, the depot_time is {}, and the threshold time is {}",
                p.getBlockHeight(), p.getDepotUpdatetime(), offsetDate);
        blockTaskPoolRepository.setSyncStatusByBlockHeight((short) TxInfoStatusEnum.TIMEOUT.getStatus(), new Date(),
                p.getBlockHeight());
    });

}
 
Example #15
Source File: BackupController.java    From blog-sharon with Apache License 2.0 6 votes vote down vote up
/**
 * 备份文章,导出markdown文件
 *
 * @return JsonResult
 */
public JsonResult backupPosts() {
    List<Post> posts = postService.findAll(PostTypeEnum.POST_TYPE_POST.getDesc());
    posts.addAll(postService.findAll(PostTypeEnum.POST_TYPE_PAGE.getDesc()));
    try {
        if (HaloUtils.getBackUps(BackupTypeEnum.POSTS.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
            FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/posts/");
        }
        //打包好的文件名
        String distName = "posts_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        String srcPath = System.getProperties().getProperty("user.home") + "/halo/backup/posts/" + distName;
        for (Post post : posts) {
            HaloUtils.postToFile(post.getPostContentMd(), srcPath, post.getPostTitle() + ".md");
        }
        //打包导出好的文章
        ZipUtil.zip(srcPath, srcPath + ".zip");
        FileUtil.del(srcPath);
        log.info("Current time: {}, performed an article backup.", DateUtil.now());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
    } catch (Exception e) {
        log.error("Backup article failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
    }
}
 
Example #16
Source File: BlockDataResetService.java    From WeBASE-Collect-Bee with Apache License 2.0 6 votes vote down vote up
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();
    }
 
Example #17
Source File: NodeWelcomeController.java    From Jpom with MIT License 6 votes vote down vote up
@RequestMapping(value = "exportTop")
public void exportTop(String time) throws UnsupportedEncodingException {
    PageResult<SystemMonitorLog> monitorData = getList(time, getCycleMillis());
    if (monitorData.getTotal() <= 0) {
        //            NodeForward.requestDownload(node, getRequest(), getResponse(), NodeUrl.exportTop);
    } else {
        NodeModel node = getNode();
        StringBuilder buf = new StringBuilder();
        buf.append("监控时间").append(",占用cpu").append(",占用内存").append(",占用磁盘").append("\r\n");
        for (SystemMonitorLog log : monitorData) {
            long monitorTime = log.getMonitorTime();
            buf.append(DateUtil.date(monitorTime).toString()).append(",")
                    .append(log.getOccupyCpu()).append("%").append(",")
                    .append(log.getOccupyMemory()).append("%").append(",")
                    .append(log.getOccupyDisk()).append("%").append("\r\n");
        }
        String fileName = URLEncoder.encode("Jpom系统监控-" + node.getId(), "UTF-8");
        HttpServletResponse response = getResponse();
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), "GBK") + ".csv");
        response.setContentType("text/csv;charset=utf-8");
        ServletUtil.write(getResponse(), buf.toString(), CharsetUtil.UTF_8);
    }
}
 
Example #18
Source File: DataInitTest.java    From spring-boot-demo with MIT License 6 votes vote down vote up
private User createUser(boolean isAdmin) {
    User user = new User();
    user.setId(snowflake.nextId());
    user.setUsername(isAdmin ? "admin" : "user");
    user.setNickname(isAdmin ? "管理员" : "普通用户");
    user.setPassword(encoder.encode("123456"));
    user.setBirthday(DateTime.of("1994-11-22", "yyyy-MM-dd")
            .getTime());
    user.setEmail((isAdmin ? "admin" : "user") + "@xkcoding.com");
    user.setPhone(isAdmin ? "17300000000" : "17300001111");
    user.setSex(1);
    user.setStatus(1);
    user.setCreateTime(DateUtil.current(false));
    user.setUpdateTime(DateUtil.current(false));
    userDao.save(user);
    return user;
}
 
Example #19
Source File: StartOrderParam.java    From runscore with Apache License 2.0 5 votes vote down vote up
public MerchantOrder convertToPo(String merchantId, Integer orderEffectiveDuration) {
	MerchantOrder po = new MerchantOrder();
	BeanUtils.copyProperties(this, po);
	po.setId(IdUtils.getId());
	po.setOrderNo(po.getId());
	po.setGatheringAmount(this.getAmount());
	po.setGatheringChannelCode(this.getPayType());
	po.setSubmitTime(new Date());
	po.setOrderState(Constant.商户订单状态_等待接单);
	po.setMerchantId(merchantId);
	po.setUsefulTime(DateUtil.offset(po.getSubmitTime(), DateField.MINUTE, orderEffectiveDuration));
	return po;
}
 
Example #20
Source File: FileUtils.java    From Jpom with MIT License 5 votes vote down vote up
private static JSONObject fileToJson(File file) {
    JSONObject jsonObject = new JSONObject(6);
    if (file.isDirectory()) {
        jsonObject.put("isDirectory", true);
        long sizeFile = FileUtil.size(file);
        jsonObject.put("fileSize", FileUtil.readableFileSize(sizeFile));
    } else {
        jsonObject.put("fileSize", FileUtil.readableFileSize(file.length()));
    }
    jsonObject.put("filename", file.getName());
    long mTime = file.lastModified();
    jsonObject.put("modifyTimeLong", mTime);
    jsonObject.put("modifyTime", DateUtil.date(mTime).toString());
    return jsonObject;
}
 
Example #21
Source File: JacksonDateSerializer.java    From hdw-dubbo with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
    String string = null;
    if (date != null) {
        string = DateUtil.format(date, DatePattern.NORM_DATETIME_PATTERN);
    }
    jsonGenerator.writeString(string);
}
 
Example #22
Source File: DataInitTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
private Role createRole(boolean isAdmin) {
    Role role = new Role();
    role.setId(snowflake.nextId());
    role.setName(isAdmin ? "管理员" : "普通用户");
    role.setDescription(isAdmin ? "超级管理员" : "普通用户");
    role.setCreateTime(DateUtil.current(false));
    role.setUpdateTime(DateUtil.current(false));
    roleDao.save(role);
    return role;
}
 
Example #23
Source File: TokenProvider.java    From eladmin with Apache License 2.0 5 votes vote down vote up
/**
 * @param token 需要检查的token
 */
public void checkRenewal(String token) {
    // 判断是否续期token,计算token的过期时间
    long time = redisUtils.getExpire(properties.getOnlineKey() + token) * 1000;
    Date expireDate = DateUtil.offset(new Date(), DateField.MILLISECOND, (int) time);
    // 判断当前时间与过期时间的时间差
    long differ = expireDate.getTime() - System.currentTimeMillis();
    // 如果在续期检查的范围内,则续期
    if (differ <= properties.getDetect()) {
        long renew = time + properties.getRenew();
        redisUtils.expire(properties.getOnlineKey() + token, renew, TimeUnit.MILLISECONDS);
    }
}
 
Example #24
Source File: JwtTokenUtil.java    From hdw-dubbo with Apache License 2.0 5 votes vote down vote up
/**
 * 判断token在指定时间内是否刚刚刷新过
 * @param token 原token
 * @param time 指定时间(秒)
 */
private boolean tokenRefreshJustBefore(String token, int time) {
    Claims claims = getClaimsFromToken(token);
    Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
    Date refreshDate = new Date();
    //刷新时间在创建时间的指定时间内
    if(refreshDate.after(created)&&refreshDate.before(DateUtil.offsetSecond(created,time))){
        return true;
    }
    return false;
}
 
Example #25
Source File: OrderController.java    From simple-microservice with Apache License 2.0 5 votes vote down vote up
/**
 * 下单方法
 *
 * @return
 */
@PostMapping("/submitOrder")
public R submitOrder(HttpServletRequest request,@RequestParam("productId") Long productId, @RequestParam("orderProductName") String orderProductName,@RequestParam("orderPrice") Double orderPrice, @RequestParam("count") int count) {
	String random = RandomUtil.randomString(16);
	//保存订单
	int orderId = orderMapper.submitOrder(random, orderProductName, orderPrice, count, DateUtil.date());
	//再扣除商品库存
	R<Boolean> result = stockServiceClient.deductionStock(productId, count);
	if (!result.getResult()) {
		return ResResultManager.setResultError("库存扣除异常,下单失败");
	}

	//返回结果
	return ResResultManager.setResultSuccess("下单成功!下单商品为:{}"+orderProductName);
}
 
Example #26
Source File: DateBusinessName.java    From magic-starter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 业务名称
 *
 * @return 业务名称
 */
@Override
public String get() {
	if (StrUtil.isBlank(businessName)) {
		this.businessName = StrUtil.EMPTY;
	}
	return this.businessName + DateUtil.today();
}
 
Example #27
Source File: UpLoadController.java    From hdw-dubbo with Apache License 2.0 5 votes vote down vote up
/**
 * 单个文件上传
 *
 * @param file 前台传过来文件路径
 * @param dir  保存文件的相对路径,相对路径必须upload开头,例如upload/test
 * @return
 * @throws Exception
 */
public Map<String, String> upload(MultipartFile file, String dir) {
    Map<String, String> params = new HashedMap();
    String resultPath = "";
    try {
        String savePath = "";
        if (StringUtils.isNotBlank(dir)) {
            savePath = fileUploadPrefix + File.separator + "upload" + File.separator
                    + dir + File.separator + DateUtil.format(new Date(), "yyyyMMdd") + File.separator;
        } else {
            savePath = fileUploadPrefix + File.separator + "upload" + File.separator
                    + DateUtil.format(new Date(), "yyyyMMdd") + File.separator;
        }
        // 保存文件
        String realFileName = file.getOriginalFilename();
        Long fileName = System.currentTimeMillis();
        File targetFile = new File(new File(savePath).getAbsolutePath() + File.separator + fileName + realFileName.substring(realFileName.indexOf(".")));
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdirs();
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(), targetFile);// 复制临时文件到指定目录下
        if (StringUtils.isNotBlank(resourceAccessUrl)) {
            resultPath = resourceAccessUrl + "/upload/" + dir + "/"
                    + DateUtil.format(new Date(), "yyyyMMdd") + "/"
                    + fileName + realFileName.substring(realFileName.indexOf("."));
        } else {
            resultPath = "/upload/" + dir + "/"
                    + DateUtil.format(new Date(), "yyyyMMdd") + "/"
                    + fileName + realFileName.substring(realFileName.indexOf("."));
        }

        params.put("fileName", realFileName);
        params.put("filePath", resultPath);

    } catch (Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
    }
    return params;
}
 
Example #28
Source File: MonitorServiceImpl.java    From eladmin with Apache License 2.0 5 votes vote down vote up
/**
 * 获取系统相关信息,系统、运行天数、系统IP
 * @param os /
 * @return /
 */
private Map<String,Object> getSystemInfo(OperatingSystem os){
    Map<String,Object> systemInfo = new LinkedHashMap<>();
    // jvm 运行时间
    long time = ManagementFactory.getRuntimeMXBean().getStartTime();
    Date date = new Date(time);
    // 计算项目运行时间
    String formatBetween = DateUtil.formatBetween(date, new Date(),BetweenFormater.Level.HOUR);
    // 系统信息
    systemInfo.put("os", os.toString());
    systemInfo.put("day", formatBetween);
    systemInfo.put("ip", StringUtils.getLocalIp());
    return systemInfo;
}
 
Example #29
Source File: UploadController.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@PostMapping(value = "/yun", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Dict yun(@RequestParam("file") MultipartFile file) {
	if (file.isEmpty()) {
		return Dict.create().set("code", 400).set("message", "文件内容为空");
	}
	String fileName = file.getOriginalFilename();
	String rawFileName = StrUtil.subBefore(fileName, ".", true);
	String fileType = StrUtil.subAfter(fileName, ".", true);
	String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
	try {
		file.transferTo(new File(localFilePath));
		Response response = qiNiuService.uploadFile(new File(localFilePath));
		if (response.isOK()) {
			JSONObject jsonObject = JSONUtil.parseObj(response.bodyString());

			String yunFileName = jsonObject.getStr("key");
			String yunFilePath = StrUtil.appendIfMissing(prefix, "/") + yunFileName;

			FileUtil.del(new File(localFilePath));

			log.info("【文件上传至七牛云】绝对路径:{}", yunFilePath);
			return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", yunFileName).set("filePath", yunFilePath));
		} else {
			log.error("【文件上传至七牛云】失败,{}", JSONUtil.toJsonStr(response));
			FileUtil.del(new File(localFilePath));
			return Dict.create().set("code", 500).set("message", "文件上传失败");
		}
	} catch (IOException e) {
		log.error("【文件上传至七牛云】失败,绝对路径:{}", localFilePath);
		return Dict.create().set("code", 500).set("message", "文件上传失败");
	}
}
 
Example #30
Source File: ArticleController.java    From mayday with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 彻底删除文章
 * 
 * @param id
 * @return
 */
@GetMapping(value = "/remove")
public String remove(@RequestParam(value = "id") int id, HttpServletRequest request) {
	try {
		articleService.remove(id);
		// 添加日志
		logService.save(new Log(LogConstant.REMOVE_AN_ARTICLE, LogConstant.SUCCESS,
				ServletUtil.getClientIP(request), DateUtil.date()));
	} catch (Exception e) {
		log.error("删除文章失败" + e.getMessage());
	}
	return "redirect:/admin/article?status=2";
}