public String getBeforeTime() { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); String result = formatter.format(DateUtils.addMinutes(date, -3)); return result; }
/** * main method to interact with {@link AvailableApplicationTool}. * * @param args * @throws SchedulingException * @throws NotAVisitorException * @throws CalendarAccountNotFoundException */ public static void main(String[] args) throws CalendarAccountNotFoundException, NotAVisitorException, SchedulingException { // scan the arguments if (args.length == 0) { System.err.println( "Usage: AppointmentTool create [-owner username] [-visitor username] [-start YYYYmmdd-hhmm] [-duration minutes]"); System.exit(1); } if (CREATE.equals(args[0])) { String visitorUsername = null; String ownerUsername = null; Date startTime = null; int duration = 30; for (int i = 1; i < args.length; i++) { if (OWNER_ARG.equalsIgnoreCase(args[i])) { ownerUsername = args[++i]; } else if (VISITOR_ARG.equalsIgnoreCase(args[i])) { visitorUsername = args[++i]; } else if (START_ARG.equalsIgnoreCase(args[i])) { String start = args[++i]; SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT); try { startTime = df.parse(start); } catch (ParseException e) { System.err.println("Invalid format for start parameter, must match: " + DATE_FORMAT); System.exit(1); } } else if (DURATION_ARG.equalsIgnoreCase(args[i])) { String dur = args[++i]; duration = Integer.parseInt(dur); } } Validate.notEmpty(ownerUsername, "owner argument cannot be empty"); Validate.notEmpty(visitorUsername, "visitor argument cannot be empty"); Validate.notNull(startTime, "start argument cannot be empty"); ApplicationContext applicationContext = new ClassPathXmlApplicationContext(CONFIG); AppointmentTool tool = new AppointmentTool( (SchedulingAssistantService) applicationContext.getBean("schedulingAssistantService"), (ICalendarAccountDao) applicationContext.getBean("calendarAccountDao"), (OwnerDao) applicationContext.getBean("ownerDao"), (VisitorDao) applicationContext.getBean("visitorDao"), (AvailableScheduleDao) applicationContext.getBean("availableScheduleDao")); Date endDate = DateUtils.addMinutes(startTime, duration); VEvent event = tool.createAvailableAppointment(visitorUsername, ownerUsername, startTime, endDate); System.out.println("Event successfully created: "); System.out.println(event.toString()); } else { System.err.println("Unrecognized command: " + args[0]); System.exit(1); } }
protected void evict() { if (bruteForceAttackCache.size() > cacheSizeLimit) { final Iterator<String> cacheIterator = bruteForceAttackCache.keySet().iterator(); final Date dateLimit = DateUtils.addMinutes(new Date(), 0 - cacheExpiration); while (cacheIterator.hasNext()) { final String userKey = cacheIterator.next(); final LoginFailure value = bruteForceAttackCache.get(userKey); if (value.getDate().before(dateLimit)) { bruteForceAttackCache.remove(userKey); } } } }
private List<Predicate> getUpdatablePredicates(Root<Feed> root) { Date now = Calendar.getInstance().getTime(); Predicate hasSubscriptions = builder.isNotEmpty(root.get(Feed_.subscriptions)); Predicate neverUpdated = builder.isNull(root.get(Feed_.lastUpdated)); Predicate updatedBeforeThreshold = builder.lessThan(root.get(Feed_.lastUpdated), DateUtils.addMinutes(now, -10)); Predicate disabledDateIsNull = builder.isNull(root.get(Feed_.disabledUntil)); Predicate disabledDateIsInPast = builder.lessThan(root.get(Feed_.disabledUntil), now); return Lists.newArrayList( hasSubscriptions, builder.or(neverUpdated, updatedBeforeThreshold), builder.or(disabledDateIsNull, disabledDateIsInPast)); }
// 处理某个任务 private void doOneTask0(Task task) { logger.error("doOneTask0..."); try { Runnable runnable = (Runnable) Class.forName(task.getClz()).newInstance(); if (runnable != null) { Thread thread = new Thread(runnable); task.setThread(thread); // 计算出此任务下一次的执行时间点 String nextWorkTime = null; if (task.getUnit().equalsIgnoreCase("DAYS")) { nextWorkTime = sdf.format(DateUtils.addDays(new Date(), Integer.valueOf(task.getSleep()))); } else if (task.getUnit().equalsIgnoreCase("HOURS")) { nextWorkTime = sdf.format(DateUtils.addHours(new Date(), Integer.valueOf(task.getSleep()))); } else if (task.getUnit().equalsIgnoreCase("MINUTES")) { nextWorkTime = sdf.format(DateUtils.addMinutes(new Date(), Integer.valueOf(task.getSleep()))); } else if (task.getUnit().equalsIgnoreCase("SECONDS")) { nextWorkTime = sdf.format(DateUtils.addSeconds(new Date(), Integer.valueOf(task.getSleep()))); } else if (task.getUnit().equalsIgnoreCase("MILLISECONDS")) { nextWorkTime = sdf.format(DateUtils.addMilliseconds(new Date(), Integer.valueOf(task.getSleep()))); } task.setNextWorkTime(nextWorkTime); task.setCurrentStatus(Task.task_currentStatus_wait); thread.setDaemon(true); thread.setName(task.getCode()); thread.start(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
public void run() { String path = getChapterPath(chapterid); File dir = new File(path); if (!dir.exists()) dir.mkdirs(); int size = content.length(); int count = ((Double) Math.ceil((float) size / 500)).intValue(); String rid = chapterid.substring(0, chapterid.length() - 3); Date updateTime = getUpdateTime(rid); if (updateTime == null) { updateTime = new Date(); } String sizeValue = count + "#" + DATE_FORMAT.format(DateUtils.addMinutes(updateTime, 1)); // 写入文件大小 writeFile(path + SIZE_FILE_NAME, encoding, sizeValue); int offset = 0; int countChar = 500; for (int j = 0; j < count; j++) { String fileName = (j + 1) + ".txt"; fileName = path + File.separator + fileName; offset = j * 500; if (offset + 500 > size || j == count - 1) countChar = size - offset; if (logger.isDebugEnabled()) { logger.debug("写入文件" + fileName); } writeFile(fileName, encoding, typeSetting(content.substring(offset, offset + countChar))); } synchronized (doingSplitMap) { doingSplitMap.remove(chapterid); } }
public Members loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { Members member = memberDao.getMemberByUsername(username); if (member == null) { throw new UsernameNotFoundException("管理员[" + username + "]不存在!"); } // 解除管理员账户锁定 if (member.isAccountNonLocked() == true) { System.out.println("locked"); if (systemConfigUtil.getIsLoginFailureLock() == true) { int loginFailureLockTime = systemConfigUtil.getLoginFailureLockTime(); if (loginFailureLockTime != 0) { Date lockedDate = member.getLockedDate(); Date nonLockedTime = DateUtils.addMinutes(lockedDate, loginFailureLockTime); Date now = new Date(); if (now.after(nonLockedTime)) { member.setLoginFailureCount(0); member.setAccountNonLocked(true); member.setLockedDate(null); memberDao.update(member); } } } else { member.setLoginFailureCount(0); member.setAccountNonLocked(true); member.setLockedDate(null); memberDao.update(member); } } member.setAuthorities(getGrantedAuthorities(member)); return member; }
@Override @Transactional(readOnly = true) public Order build( Cart cart, Receiver receiver, PaymentMethod paymentMethod, ShippingMethod shippingMethod, CouponCode couponCode, boolean isInvoice, String invoiceTitle, boolean useBalance, String memo) { Assert.notNull(cart); Assert.notNull(cart.getMember()); Assert.notEmpty(cart.getCartItems()); Order order = new Order(); order.setShippingStatus(ShippingStatus.unshipped); order.setFee(new BigDecimal(0)); order.setPromotionDiscount(cart.getDiscount()); order.setCouponDiscount(new BigDecimal(0)); order.setOffsetAmount(new BigDecimal(0)); order.setPoint(cart.getEffectivePoint()); order.setMemo(memo); order.setMember(cart.getMember()); if (receiver != null) { order.setConsignee(receiver.getConsignee()); order.setAreaName(receiver.getAreaName()); order.setAddress(receiver.getAddress()); order.setZipCode(receiver.getZipCode()); order.setPhone(receiver.getPhone()); order.setArea(receiver.getArea()); } if (!cart.getPromotions().isEmpty()) { StringBuffer promotionName = new StringBuffer(); for (Promotion promotion : cart.getPromotions()) { if (promotion != null && promotion.getName() != null) { promotionName.append(" " + promotion.getName()); } } if (promotionName.length() > 0) { promotionName.deleteCharAt(0); } order.setPromotion(promotionName.toString()); } order.setPaymentMethod(paymentMethod); if (shippingMethod != null && paymentMethod != null && paymentMethod.getShippingMethods().contains(shippingMethod)) { BigDecimal freight = shippingMethod.calculateFreight(cart.getWeight()); for (Promotion promotion : cart.getPromotions()) { if (promotion.getIsFreeShipping()) { freight = new BigDecimal(0); break; } } order.setFreight(freight); order.setShippingMethod(shippingMethod); } else { order.setFreight(new BigDecimal(0)); } if (couponCode != null && cart.isCouponAllowed()) { couponCodeDao.lock(couponCode, LockModeType.PESSIMISTIC_WRITE); if (!couponCode.getIsUsed() && couponCode.getCoupon() != null && cart.isValid(couponCode.getCoupon())) { BigDecimal couponDiscount = cart.getEffectivePrice() .subtract( couponCode .getCoupon() .calculatePrice(cart.getQuantity(), cart.getEffectivePrice())); couponDiscount = couponDiscount.compareTo(new BigDecimal(0)) > 0 ? couponDiscount : new BigDecimal(0); order.setCouponDiscount(couponDiscount); order.setCouponCode(couponCode); } } List<OrderItem> orderItems = order.getOrderItems(); for (CartItem cartItem : cart.getCartItems()) { if (cartItem != null && cartItem.getProduct() != null) { Product product = cartItem.getProduct(); OrderItem orderItem = new OrderItem(); orderItem.setSn(product.getSn()); orderItem.setName(product.getName()); orderItem.setFullName(product.getFullName()); orderItem.setPrice(cartItem.getPrice()); orderItem.setWeight(product.getWeight()); orderItem.setThumbnail(product.getThumbnail()); orderItem.setIsGift(false); orderItem.setQuantity(cartItem.getQuantity()); orderItem.setShippedQuantity(0); orderItem.setReturnQuantity(0); orderItem.setProduct(product); orderItem.setOrder(order); orderItems.add(orderItem); } } for (GiftItem giftItem : cart.getGiftItems()) { if (giftItem != null && giftItem.getGift() != null) { Product gift = giftItem.getGift(); OrderItem orderItem = new OrderItem(); orderItem.setSn(gift.getSn()); orderItem.setName(gift.getName()); orderItem.setFullName(gift.getFullName()); orderItem.setPrice(new BigDecimal(0)); orderItem.setWeight(gift.getWeight()); orderItem.setThumbnail(gift.getThumbnail()); orderItem.setIsGift(true); orderItem.setQuantity(giftItem.getQuantity()); orderItem.setShippedQuantity(0); orderItem.setReturnQuantity(0); orderItem.setProduct(gift); orderItem.setOrder(order); orderItems.add(orderItem); } } Setting setting = SettingUtils.get(); if (setting.getIsInvoiceEnabled() && isInvoice && StringUtils.isNotEmpty(invoiceTitle)) { order.setIsInvoice(true); order.setInvoiceTitle(invoiceTitle); order.setTax(order.calculateTax()); } else { order.setIsInvoice(false); order.setTax(new BigDecimal(0)); } if (useBalance) { Member member = cart.getMember(); if (member.getBalance().compareTo(order.getAmount()) >= 0) { order.setAmountPaid(order.getAmount()); } else { order.setAmountPaid(member.getBalance()); } } else { order.setAmountPaid(new BigDecimal(0)); } if (order.getAmountPayable().compareTo(new BigDecimal(0)) == 0) { order.setOrderStatus(OrderStatus.confirmed); order.setPaymentStatus(PaymentStatus.paid); } else if (order.getAmountPayable().compareTo(new BigDecimal(0)) > 0 && order.getAmountPaid().compareTo(new BigDecimal(0)) > 0) { order.setOrderStatus(OrderStatus.confirmed); order.setPaymentStatus(PaymentStatus.partialPayment); } else { order.setOrderStatus(OrderStatus.unconfirmed); order.setPaymentStatus(PaymentStatus.unpaid); } if (paymentMethod != null && paymentMethod.getTimeout() != null && order.getPaymentStatus() == PaymentStatus.unpaid) { order.setExpire(DateUtils.addMinutes(new Date(), paymentMethod.getTimeout())); } return order; }
/** * 获取某个命令时间分布图 * * @param instanceId 实例id * @param commandName 命令名称 * @throws java.text.ParseException */ @RequestMapping("/getCommandStatsV2") public ModelAndView getCommandStatsV2( HttpServletRequest request, HttpServletResponse response, Model model, Long instanceId, String commandName) throws ParseException { String startDateParam = request.getParameter("startDate"); String endDateParam = request.getParameter("endDate"); if (StringUtils.isBlank(startDateParam) || StringUtils.isBlank(endDateParam)) { Date endDate = new Date(); Date startDate = DateUtils.addDays(endDate, -1); startDateParam = DateUtil.formatDate(startDate, "yyyyMMdd"); endDateParam = DateUtil.formatDate(endDate, "yyyyMMdd"); } model.addAttribute("startDate", startDateParam); model.addAttribute("endDate", endDateParam); Date startDate = DateUtil.parseYYYYMMdd(startDateParam); Date endDate = DateUtil.parseYYYYMMdd(endDateParam); if (instanceId != null) { long firstDayBegin = NumberUtils.toLong(DateUtil.formatYYYYMMdd(startDate) + "0000"); long firstDayEnd = NumberUtils.toLong(DateUtil.formatYYYYMMdd(startDate) + "2359"); long secondDayBegin = NumberUtils.toLong(DateUtil.formatYYYYMMdd(endDate) + "0000"); long secondDayEnd = NumberUtils.toLong(DateUtil.formatYYYYMMdd(endDate) + "2359"); long bt = System.currentTimeMillis(); List<InstanceCommandStats> instanceCommandStatsListFirst = instanceStatsCenter.getCommandStatsList( instanceId, firstDayBegin, firstDayEnd, commandName); List<InstanceCommandStats> instanceCommandStatsListSecond = instanceStatsCenter.getCommandStatsList( instanceId, secondDayBegin, secondDayEnd, commandName); long et = System.currentTimeMillis() - bt; Map<String, InstanceCommandStats> cmdStatsFirst = new HashMap<String, InstanceCommandStats>(); Map<String, InstanceCommandStats> cmdStatsSecond = new HashMap<String, InstanceCommandStats>(); for (InstanceCommandStats first : instanceCommandStatsListFirst) { cmdStatsFirst.put(first.getCollectTime() + "", first); } for (InstanceCommandStats second : instanceCommandStatsListSecond) { cmdStatsSecond.put(second.getCollectTime() + "", second); } SplineChartEntity splineChartEntity = new SplineChartEntity(); String container = request.getParameter("container"); if (container != null) { splineChartEntity.renderTo(container); } model.addAttribute("chart", splineChartEntity); splineChartEntity.putTitle( ChartKeysUtil.TitleKey.TEXT.getKey(), "命令:" + commandName + " 的比较曲线【" + startDateParam + "】-【" + endDateParam + "】"); splineChartEntity.setYAxisTitle("y"); List<Long> data1 = new ArrayList<Long>(); List<Long> data2 = new ArrayList<Long>(); Map<String, Object> marker = new HashMap<String, Object>(); marker.put("radius", 1); Map<String, Object> serie1 = new HashMap<String, Object>(); serie1.put("name", startDateParam); serie1.put("data", data1); serie1.put("marker", marker); Map<String, Object> serie2 = new HashMap<String, Object>(); serie2.put("name", endDateParam); serie2.put("data", data2); serie2.put("marker", marker); splineChartEntity.putSeries(serie1); splineChartEntity.putSeries(serie2); List<Object> x = new LinkedList<Object>(); for (int i = 0; i < 1440; i += 1) { Date date = DateUtils.addMinutes(startDate, i); String s = DateUtil.formatHHMM(date); if (cmdStatsFirst.containsKey(startDateParam + s)) { data1.add(cmdStatsFirst.get(startDateParam + s).getCommandCount()); } else { data1.add(0l); } if (cmdStatsSecond.containsKey(endDateParam + s)) { data2.add(cmdStatsSecond.get(endDateParam + s).getCommandCount()); } else { data2.add(0l); } x.add(s); } splineChartEntity.setXAxisCategories(x); } return new ModelAndView(""); }