org.apache.commons.lang3.time.DateUtils Java Examples

The following examples show how to use org.apache.commons.lang3.time.DateUtils. 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: TicketReservationManagerIntegrationTest.java    From alf.io with GNU General Public License v3.0 7 votes vote down vote up
@Test(expected = TicketReservationManager.NotEnoughTicketsException.class)
public void testTicketSelectionNotEnoughTicketsAvailable() {
    List<TicketCategoryModification> categories = Collections.singletonList(
        new TicketCategoryModification(null, "default", AVAILABLE_SEATS,
            new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()),
            DESCRIPTION, BigDecimal.TEN, false, "", false, null, null, null, null, null, 0, null, null, AlfioMetadata.empty()));
    Event event = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository).getKey();

    TicketCategory unbounded = ticketCategoryRepository.findAllTicketCategories(event.getId()).stream().filter(t -> !t.isBounded()).findFirst().orElseThrow(IllegalStateException::new);

    TicketReservationModification tr = new TicketReservationModification();
    tr.setAmount(AVAILABLE_SEATS + 1);
    tr.setTicketCategoryId(unbounded.getId());
    TicketReservationWithOptionalCodeModification mod = new TicketReservationWithOptionalCodeModification(tr, Optional.empty());

    ticketReservationManager.createTicketReservation(event, Collections.singletonList(mod), Collections.emptyList(), DateUtils.addDays(new Date(), 1), Optional.empty(), Locale.ENGLISH, false);
}
 
Example #2
Source File: GetWorkCalendarEndTimeCmd.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
/**
 * 根据日期拿到对应的规则
 * @param date
 * @return
 */
private CalendarRuleEntity getCalendarRuleByDate(Date date) {
	CalendarRuleEntity calendarRuleEntity = null;
	for (CalendarRuleEntity calendarRuleEntity2 : calendarTypeEntity.getCalendarRuleEntities()) {
		if(calendarRuleEntity2.getWeek()==DateCalUtils.dayForWeek(date)) {
			calendarRuleEntity = calendarRuleEntity2;
		}
		if(calendarRuleEntity2.getWorkdate()!=null && DateUtils.isSameDay(calendarRuleEntity2.getWorkdate(), date) && calendarRuleEntity2.getCalendarPartEntities().size()!=0) {
			calendarRuleEntity = calendarRuleEntity2;
		}
	}
	//如果这天没有规则则再加一天
	if(calendarRuleEntity==null) {
		date = DateUtils.addDays(date, 1);
		return getCalendarRuleByDate(date);
	}
	return calendarRuleEntity;
}
 
Example #3
Source File: HistoricProcessInstanceAuthorizationTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
protected void prepareProcessInstances(String key, int daysInThePast, Integer historyTimeToLive, int instanceCount) {
  ProcessDefinition processDefinition = selectProcessDefinitionByKey(key);
  disableAuthorization();
  repositoryService.updateProcessDefinitionHistoryTimeToLive(processDefinition.getId(), historyTimeToLive);
  enableAuthorization();

  Date oldCurrentTime = ClockUtil.getCurrentTime();
  ClockUtil.setCurrentTime(DateUtils.addDays(new Date(), daysInThePast));

  List<String> processInstanceIds = new ArrayList<String>();
  for (int i = 0; i < instanceCount; i++) {
    ProcessInstance processInstance = startProcessInstanceByKey(key);
    processInstanceIds.add(processInstance.getId());
  }

  disableAuthorization();
  runtimeService.deleteProcessInstances(processInstanceIds, null, true, true);
  enableAuthorization();

  ClockUtil.setCurrentTime(oldCurrentTime);
}
 
Example #4
Source File: HistoricBatchManagerBatchesForCleanupTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
private String prepareHistoricBatches(int batchesCount) {
  Date startDate = ClockUtil.getCurrentTime();
  ClockUtil.setCurrentTime(DateUtils.addDays(startDate, daysInThePast));

  List<Batch> list = new ArrayList<Batch>();
  for (int i = 0; i < batchesCount; i++) {
    list.add(helper.migrateProcessInstancesAsync(1));
  }

  Batch batch1 = list.get(0);
  String batchType = batch1.getType();
  helper.completeSeedJobs(batch1);
  helper.executeJobs(batch1);
  ClockUtil.setCurrentTime(DateUtils.addDays(startDate, batch1EndTime));
  helper.executeMonitorJob(batch1);

  Batch batch2 = list.get(1);
  helper.completeSeedJobs(batch2);
  helper.executeJobs(batch2);
  ClockUtil.setCurrentTime(DateUtils.addDays(startDate, batch2EndTime));
  helper.executeMonitorJob(batch2);

  ClockUtil.setCurrentTime(new Date());

  return batchType;
}
 
Example #5
Source File: OrderService.java    From code with Apache License 2.0 6 votes vote down vote up
public void createOrder(Order order) throws Exception {
	// order current time 
	Date orderTime = new Date();
	// order insert
	orderMapper.insert(order);
	// log insert
	BrokerMessageLog brokerMessageLog = new BrokerMessageLog();
	brokerMessageLog.setMessageId(order.getMessageId());
	//save order message as json
	brokerMessageLog.setMessage(FastJsonConvertUtil.convertObjectToJSON(order));
	brokerMessageLog.setStatus("0");
	brokerMessageLog.setNextRetry(DateUtils.addMinutes(orderTime, Constants.ORDER_TIMEOUT));
	brokerMessageLog.setCreateTime(new Date());
	brokerMessageLog.setUpdateTime(new Date());
	brokerMessageLogMapper.insert(brokerMessageLog);
	// order message sender
	rabbitOrderSender.sendOrder(order);
}
 
Example #6
Source File: MinionCheckinTest.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test execution MinionCheckin job.
 * Check that we do perform a test.ping on INACTIVE minions.
 *
 * @throws Exception in case of an error
 */
public void testExecuteOnInactiveMinions() throws Exception {
    MinionServer minion1 = MinionServerFactoryTest.createTestMinionServer(user);
    minion1.setMinionId("minion1");

    Optional<MinionServer> minion = MinionServerFactory
            .findByMinionId(minion1.getMinionId());
    assertTrue(minion.isPresent());
    assertEquals(minion.get().getMinionId(), minion1.getMinionId());

    ServerInfo serverInfo = minion1.getServerInfo();
    serverInfo.setCheckin(DateUtils.addHours(new Date(), -this.thresholdMax));
    minion1.setServerInfo(serverInfo);
    TestUtils.saveAndFlush(minion1);

    SaltService saltServiceMock = mock(SaltService.class);

    context().checking(new Expectations() { {
        oneOf(saltServiceMock).checkIn(with(any(MinionList.class)));
    } });

    MinionCheckin minionCheckinJob = new MinionCheckin();
    minionCheckinJob.setSystemQuery(saltServiceMock);

    minionCheckinJob.execute(null);
}
 
Example #7
Source File: PipelineServiceIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnModificationsInCorrectOrder() throws Exception {
    File file1 = new File("file1");
    File file2 = new File("file2");
    File file3 = new File("file3");
    File file4 = new File("file4");
    Material hg1 = new HgMaterial("url1", "Dest1");
    String[] hgRevs = new String[]{"hg1_2"};

    Date latestModification = new Date();
    Date older = DateUtils.addDays(latestModification, -1);
    u.checkinFiles(hg1, "hg1_1", a(file1, file2, file3, file4), ModifiedAction.added, older);
    u.checkinFiles(hg1, "hg1_2", a(file1, file2, file3, file4), ModifiedAction.modified, latestModification);


    ScheduleTestUtil.AddedPipeline pair01 = u.saveConfigWith("pair01", "stageName", u.m(hg1));

    u.runAndPass(pair01, hgRevs);

    Pipeline pipeline = pipelineService.mostRecentFullPipelineByName("pair01");
    MaterialRevisions materialRevisions = pipeline.getBuildCause().getMaterialRevisions();
    assertThat(materialRevisions.getMaterials().size(), is(1));
    assertThat(materialRevisions.getDateOfLatestModification().getTime(), is(latestModification.getTime()));
}
 
Example #8
Source File: MapDeserializationUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenUsingCustomDateDeserializer_thenShouldReturnMapWithDate() {
    String jsonString = "{'Bob': '2017/06/01', 'Jennie':'2015/01/03'}";
    Type type = new TypeToken<Map<String, Date>>(){}.getType();
    Gson gson = new GsonBuilder()
      .registerTypeAdapter(type, new StringDateMapDeserializer())
      .create();
    Map<String, Date> empJoiningDateMap = gson.fromJson(jsonString, type);

    logger.info("The converted map: {}", empJoiningDateMap);
    logger.info("The map class {}", empJoiningDateMap.getClass());
    Assert.assertEquals(2, empJoiningDateMap.size());
    Assert.assertEquals(Date.class, empJoiningDateMap.get("Bob").getClass());
    Date dt = null;
    try {
        dt = DateUtils.parseDate("2017-06-01", "yyyy-MM-dd");
        Assert.assertEquals(dt, empJoiningDateMap.get("Bob"));
    } catch (ParseException e) {
        logger.error("Could not parse date", e);
    }
}
 
Example #9
Source File: MultiTenancyCleanableHistoricCaseInstanceReportCmdTenantCheckTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
private void prepareCaseInstances(String key, int daysInThePast, Integer historyTimeToLive, int instanceCount, String tenantId) {
  // update time to live
  List<CaseDefinition> caseDefinitions = null;
  if (tenantId != null) {
    caseDefinitions = repositoryService.createCaseDefinitionQuery().caseDefinitionKey(key).tenantIdIn(tenantId).list();
  } else {
    caseDefinitions = repositoryService.createCaseDefinitionQuery().caseDefinitionKey(key).withoutTenantId().list();
  }
  assertEquals(1, caseDefinitions.size());
  repositoryService.updateCaseDefinitionHistoryTimeToLive(caseDefinitions.get(0).getId(), historyTimeToLive);

  Date oldCurrentTime = ClockUtil.getCurrentTime();
  ClockUtil.setCurrentTime(DateUtils.addDays(new Date(), daysInThePast));

  for (int i = 0; i < instanceCount; i++) {
    CaseInstance caseInstance = caseService.createCaseInstanceById(caseDefinitions.get(0).getId());
    if (tenantId != null) {
      assertEquals(tenantId, caseInstance.getTenantId());
    }
    caseService.terminateCaseExecution(caseInstance.getId());
    caseService.closeCaseInstance(caseInstance.getId());
  }

  ClockUtil.setCurrentTime(oldCurrentTime);
}
 
Example #10
Source File: TrovitUtils.java    From OpenEstate-IO with Apache License 2.0 6 votes vote down vote up
/**
 * Read a {@link Calendar} value from XML.
 *
 * @param value XML string
 * @return parsed value or null, if the value is invalid
 */
public static Calendar parseDateValue(String value) {
    value = StringUtils.trimToNull(value);
    if (value == null) return null;

    final String[] patterns = new String[]{
            "dd/MM/yyyy",
            "dd/MM/yyyy hh:mm:ss",
            "dd-MM-yyyy",
            "dd-MM-yyyy hh:mm:ss",
            "yyyy/MM/dd",
            "yyyy/MM/dd hh:mm:ss",
            "yyyy-MM-dd",
            "yyyy-MM-dd hh:mm:ss"
    };

    try {
        Date date = DateUtils.parseDateStrictly(value, Locale.ENGLISH, patterns);
        Calendar cal = Calendar.getInstance(Locale.getDefault());
        cal.setTime(date);
        return cal;
    } catch (ParseException ex) {
        throw new IllegalArgumentException("Can't parse date value '" + value + "'!", ex);
    }
}
 
Example #11
Source File: CleanableHistoricCaseInstanceReportTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
private void prepareCaseInstances(String key, int daysInThePast, Integer historyTimeToLive, int instanceCount) {
  // update time to live
  List<CaseDefinition> caseDefinitions = repositoryService.createCaseDefinitionQuery().caseDefinitionKey(key).list();
  assertEquals(1, caseDefinitions.size());
  repositoryService.updateCaseDefinitionHistoryTimeToLive(caseDefinitions.get(0).getId(), historyTimeToLive);

  Date oldCurrentTime = ClockUtil.getCurrentTime();
  ClockUtil.setCurrentTime(DateUtils.addDays(oldCurrentTime, daysInThePast));

  for (int i = 0; i < instanceCount; i++) {
    CaseInstance caseInstance = caseService.createCaseInstanceByKey(key);
    caseService.terminateCaseExecution(caseInstance.getId());
    caseService.closeCaseInstance(caseInstance.getId());
  }

  ClockUtil.setCurrentTime(oldCurrentTime);
}
 
Example #12
Source File: EventManagerIntegrationTest.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void deleteUnboundedTicketCategoryFailure() {
    List<TicketCategoryModification> cat = Collections.singletonList(
        new TicketCategoryModification(null, "default", AVAILABLE_SEATS,
            new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()),
            DESCRIPTION, BigDecimal.TEN, false, "", false, null, null, null, null, null, 0, null, null, AlfioMetadata.empty()));
    Pair<Event, String> pair = initEvent(cat, organizationRepository, userManager, eventManager, eventRepository);
    var event = pair.getLeft();
    var tickets = ticketRepository.selectNotAllocatedTicketsForUpdate(event.getId(), 1, List.of(Ticket.TicketStatus.FREE.name()));
    var categories = ticketCategoryRepository.findAllTicketCategories(event.getId());
    assertEquals(1, categories.size());
    int categoryId = categories.get(0).getId();
    String reservationId = UUID.randomUUID().toString();
    ticketReservationRepository.createNewReservation(reservationId, ZonedDateTime.now(), DateUtils.addDays(new Date(), 1), null, "en", event.getId(), event.getVat(), event.isVatIncluded(), event.getCurrency());
    int result = ticketRepository.reserveTickets(reservationId, tickets, categoryId, "en", 0, "CHF");
    assertEquals(1, result);
    assertThrows(IllegalStateException.class, () -> eventManager.deleteCategory(event.getShortName(), categoryId, pair.getRight()));
}
 
Example #13
Source File: IdentityServiceTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
@WatchLogger(loggerNames = {INDENTITY_LOGGER}, level = "INFO")
public void testUsuccessfulAttemptsResultInBlockedUser() throws ParseException {
  // given
  User user = identityService.newUser("johndoe");
  user.setPassword("xxx");
  identityService.saveUser(user);

  Date now = sdf.parse("2000-01-24T13:00:00");
  ClockUtil.setCurrentTime(now);

  // when
  for (int i = 0; i < 11; i++) {
    assertFalse(identityService.checkPassword("johndoe", "invalid pwd"));
    now = DateUtils.addMinutes(now, 1);
    ClockUtil.setCurrentTime(now);
  }

  // then
  assertThat(loggingRule.getFilteredLog(INDENTITY_LOGGER, "The user with id 'johndoe' is permanently locked.").size()).isEqualTo(1);
}
 
Example #14
Source File: FailedJobListenerWithRetriesTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
void lockTheJob(final String jobId) {
  engineRule.getProcessEngineConfiguration().getCommandExecutorTxRequiresNew().execute(new Command<Object>() {
    @Override
    public Object execute(CommandContext commandContext) {
      final JobEntity job = commandContext.getJobManager().findJobById(jobId);
      job.setLockOwner("someLockOwner");
      job.setLockExpirationTime(DateUtils.addHours(ClockUtil.getCurrentTime(), 1));
      return null;
    }
  });
}
 
Example #15
Source File: DataManagerTest.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Test
public void testTemporalType() throws Exception {
    Date nextYear = DateUtils.addYears(AppBeans.get(TimeSource.class).currentTimestamp(), 1);
    LoadContext<User> loadContext = LoadContext.create(User.class).setQuery(
            LoadContext.createQuery("select u from sec$User u where u.createTs = :ts")
                    .setParameter("ts", nextYear, TemporalType.DATE));

    List<User> users = dataManager.loadList(loadContext);
    assertTrue(users.isEmpty());
}
 
Example #16
Source File: SearchUtils.java    From jvue-admin with MIT License 5 votes vote down vote up
/**
 * 查询终止日期
 * @param date 日期("yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss")
 * @return 日期(次日0时0分)
 * @since  1.0
 */
public static Date dayTo(String date) {
    if (StringUtils.isEmpty(date)) {
        return null;
    }
    try {
        Date d = DateUtils.parseDate(date, PARSE_PATTERNS);
        return DateUtils.ceiling(d, Calendar.DATE);
    } catch (ParseException e) {
        LOGGER.warn("日期转换错误{},{}", date, e.getMessage());
    }
    return null;
}
 
Example #17
Source File: DateTools.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Date ceilWeekOfYear(Date date, Integer adjust) throws Exception {
	Calendar cal = DateUtils.toCalendar(date);
	cal.setFirstDayOfWeek(Calendar.MONDAY);
	cal.add(Calendar.WEEK_OF_YEAR, adjust);
	cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
	return DateUtils.ceiling(cal, Calendar.DATE).getTime();
}
 
Example #18
Source File: ClockFrame.java    From dsworkbench with Apache License 2.0 5 votes vote down vote up
public void addTimer(Attack pAttack, int pSecondsBefore) {
    if (pAttack == null) {
        return;
    }
    String name = pAttack.getSource() + " -> " + pAttack.getTarget();

    jTimerName.setText(name);
    dateTimeField1.setDate(new Date(pAttack.getSendTime().getTime() - (DateUtils.MILLIS_PER_SECOND * pSecondsBefore)));
    if (jComboBox1.getSelectedItem() == null) {
        jComboBox1.setSelectedIndex(0);
    }

    addTimer();
}
 
Example #19
Source File: TicketReservationManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
public Optional<String> createTicketReservation(Event event,
                                                List<TicketReservationWithOptionalCodeModification> list,
                                                List<ASReservationWithOptionalCodeModification> additionalServices,
                                                Optional<String> promoCodeDiscount,
                                                Locale locale,
                                                BindingResult bindingResult) {
    Date expiration = DateUtils.addMinutes(new Date(), getReservationTimeout(event));
    try {
        String reservationId = createTicketReservation(event,
            list, additionalServices, expiration,
            promoCodeDiscount,
            locale, false);
        return Optional.of(reservationId);
    } catch (TicketReservationManager.NotEnoughTicketsException nete) {
        bindingResult.reject(ErrorsCode.STEP_1_NOT_ENOUGH_TICKETS);
    } catch (TicketReservationManager.MissingSpecialPriceTokenException missing) {
        bindingResult.reject(ErrorsCode.STEP_1_ACCESS_RESTRICTED);
    } catch (TicketReservationManager.InvalidSpecialPriceTokenException invalid) {
        bindingResult.reject(ErrorsCode.STEP_1_CODE_NOT_FOUND);
    } catch (TicketReservationManager.TooManyTicketsForDiscountCodeException tooMany) {
        bindingResult.reject(ErrorsCode.STEP_2_DISCOUNT_CODE_USAGE_EXCEEDED);
    } catch (CannotProceedWithPayment cannotProceedWithPayment) {
        bindingResult.reject(ErrorsCode.STEP_1_CATEGORIES_NOT_COMPATIBLE);
        log.error("missing payment methods", cannotProceedWithPayment);
    }
    return Optional.empty();
}
 
Example #20
Source File: NotificationManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@Transactional
public int sendWaitingMessages() {
    Date now = new Date();

    emailMessageRepository.setToRetryOldInProcess(DateUtils.addHours(now, -1));

    AtomicInteger counter = new AtomicInteger();

    eventRepository.findAllActiveIds(ZonedDateTime.now(UTC))
        .stream()
        .flatMap(id -> emailMessageRepository.loadIdsWaitingForProcessing(id, now).stream())
        .distinct()
        .forEach(messageId -> counter.addAndGet(processMessage(messageId)));
    return counter.get();
}
 
Example #21
Source File: ReadTestCaseExecutionMedia.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
private void returnText(HttpServletRequest request, HttpServletResponse response, TestCaseExecutionFile tc, String filePath) {

        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
        sdf.applyPattern("dd MMM yyyy HH:mm:ss z");

        response.setHeader("Last-Modified", sdf.format(DateUtils.addDays(Calendar.getInstance().getTime(), 2 * 360)));
        response.setHeader("Expires", sdf.format(DateUtils.addDays(Calendar.getInstance().getTime(), 2 * 360)));
        response.setHeader("Type", tc.getFileType());
        response.setHeader("Description", tc.getFileDesc());
    }
 
Example #22
Source File: AdminServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public PasswordState getPasswordState(ComAdmin admin) {
	if (admin.isOneTimePassword()) {
		// One-time password must be changed immediately upon log on.
		return PasswordState.ONE_TIME;
	}

	int expirationDays = configService.getIntegerValue(ConfigValue.UserPasswordExpireDays, admin.getCompanyID());
	if (expirationDays <= 0) {
		// Expiration is disabled for company.
		return PasswordState.VALID;
	}

	// A password is valid for N days after its last change.
	Date expirationDate = DateUtils.addDays(admin.getLastPasswordChange(), expirationDays);

	if (DateUtilities.isPast(expirationDate)) {
		int expirationLockDays = configService.getIntegerValue(ConfigValue.UserPasswordFinalExpirationDays, admin.getCompanyID());

		// A password is still can be used to log in during N days after its expiration.
		Date expirationLockDate = DateUtils.addDays(expirationDate, expirationLockDays);

		if (DateUtilities.isPast(expirationLockDate)) {
			return PasswordState.EXPIRED_LOCKED;
		} else {
			return PasswordState.EXPIRED;
		}
	} else {
		int expirationWarningDays = configService.getIntegerValue(ConfigValue.UserPasswordExpireNotificationDays, admin.getCompanyID());

		// User should get a warning message for N days before password is expired.
		Date expirationWarningDate = DateUtils.addDays(expirationDate, -expirationWarningDays);

		if (DateUtilities.isPast(expirationWarningDate)) {
			return PasswordState.EXPIRING;
		} else {
			return PasswordState.VALID;
		}
	}
}
 
Example #23
Source File: DateConstraintValidator.java    From Milkomeda with MIT License 5 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
    // 如果为空就不验证
    if (null == value || "".equals(value)) return true;
    try {
        DateUtils.parseDate(value, dateFormat);
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example #24
Source File: DyUsage.java    From jare with MIT License 5 votes vote down vote up
@Override
public void add(final Date date, final long bytes) throws IOException {
    final int day = DyUsage.asNumber(date);
    final XML xml = this.xml();
    final String xpath = String.format("/usage/day[@id='%d']/text()", day);
    final List<String> items = xml.xpath(xpath);
    final long before;
    if (items.isEmpty()) {
        before = 0L;
    } else {
        before = Long.parseLong(items.get(0));
    }
    final Node node = xml.node();
    new Xembler(
        new Directives()
            .xpath(xpath).up().remove()
            .xpath("/usage").add("day").attr("id", day).set(before + bytes)
    ).applyQuietly(node);
    new Xembler(
        new Directives().xpath(
            String.format(
                "/usage/day[number(@id) < %d]",
                DyUsage.asNumber(DateUtils.addDays(new Date(), -Tv.THIRTY))
            )
        ).remove()
    ).applyQuietly(node);
    final XML after = new XMLDocument(node);
    this.save(after.toString());
    this.save(Long.parseLong(after.xpath("sum(/usage/day)").get(0)));
}
 
Example #25
Source File: FeedUtils.java    From commafeed with Apache License 2.0 5 votes vote down vote up
/**
 * When there was an error fetching the feed
 * 
 */
public static Date buildDisabledUntil(int errorCount) {
	Date now = new Date();
	int retriesBeforeDisable = 3;

	if (errorCount >= retriesBeforeDisable) {
		int disabledHours = errorCount - retriesBeforeDisable + 1;
		disabledHours = Math.min(24 * 7, disabledHours);
		return DateUtils.addHours(now, disabledHours);
	}
	return now;
}
 
Example #26
Source File: Clean.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private List<Message> listMessage(Business business) throws Exception {
	EntityManager em = business.entityManagerContainer().get(Message.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Message> cq = cb.createQuery(Message.class);
	Root<Message> root = cq.from(Message.class);
	Date limit = DateUtils.addDays(new Date(), -Config.communicate().clean().getKeep());
	Predicate p = cb.lessThan(root.get(Message_.createTime), limit);
	return em.createQuery(cq.select(root).where(p)).setMaxResults(2000).getResultList();
}
 
Example #27
Source File: OpenFilter.java    From seed with Apache License 2.0 5 votes vote down vote up
/**
 * 验证时间戳
 */
private void verifyTimestamp(String timestamp){
    if(StringUtils.isBlank(timestamp)){
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "timestamp is blank");
    }
    try {
        long reqTime = DateUtils.parseDate(timestamp, "yyyy-MM-dd HH:mm:ss").getTime();
        if(Math.abs(System.currentTimeMillis()-reqTime) >= TIMESTAMP_VALID_MILLISECONDS){
            throw new SeedException(CodeEnum.OPEN_TIMESTAMP_ERROR);
        }
    } catch (ParseException e) {
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "timestamp is invalid");
    }
}
 
Example #28
Source File: ScreensHelper.java    From sample-timesheets with Apache License 2.0 5 votes vote down vote up
public static String getColumnCaption(String columnId, Date date) {
    String caption = messages.getMessage(WeeklyReportEntry.class, "WeeklyReportEntry." + columnId);
    String format = COMMON_DAY_CAPTION_STYLE;

    if (workdaysTools.isHoliday(date) || workdaysTools.isWeekend(date)) {
        format = String.format(HOLIDAY_CAPTION_STYLE, format);
    }
    if (DateUtils.isSameDay(timeSource.currentTimestamp(), date)) {
        format = String.format(TODAY_CAPTION_STYLE, format);
    }
    return String.format(format, caption, DateUtils.toCalendar(date).get(Calendar.DAY_OF_MONTH));
}
 
Example #29
Source File: BulkHistoryDeleteCmmnDisabledTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
private void prepareHistoricDecisions(int instanceCount) {
  Date oldCurrentTime = ClockUtil.getCurrentTime();
  List<DecisionDefinition> decisionDefinitions = engineRule.getRepositoryService().createDecisionDefinitionQuery().decisionDefinitionKey("decision").list();
  assertEquals(1, decisionDefinitions.size());
  engineRule.getRepositoryService().updateDecisionDefinitionHistoryTimeToLive(decisionDefinitions.get(0).getId(), 5);

  ClockUtil.setCurrentTime(DateUtils.addDays(new Date(), -6));
  for (int i = 0; i < instanceCount; i++) {
    engineRule.getDecisionService().evaluateDecisionByKey("decision").variables(Variables.createVariables().putValue("status", "silver").putValue("sum", 723))
        .evaluate();
  }
  ClockUtil.setCurrentTime(oldCurrentTime);
}
 
Example #30
Source File: BaseDateTimeType.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private boolean couldBeTheSameTime(BaseDateTimeType theArg1, BaseDateTimeType theArg2) {
    boolean theCouldBeTheSameTime = false;
    if (theArg1.getTimeZone() == null && theArg2.getTimeZone() != null) {
        long lowLeft = new DateTimeType(theArg1.getValueAsString()+"Z").getValue().getTime() - (14 * DateUtils.MILLIS_PER_HOUR);
        long highLeft = new DateTimeType(theArg1.getValueAsString()+"Z").getValue().getTime() + (14 * DateUtils.MILLIS_PER_HOUR);
        long right = theArg2.getValue().getTime();
        if (right >= lowLeft && right <= highLeft) {
            theCouldBeTheSameTime = true;
        }
    }
    return theCouldBeTheSameTime;
}