Java Code Examples for org.apache.commons.lang3.time.DateUtils#addMinutes()

The following examples show how to use org.apache.commons.lang3.time.DateUtils#addMinutes() . 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: DeleteDraft.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<Draft> listDraft(EntityManagerContainer emc, String sequence) throws Exception {
	Date date = new Date();
	date = DateUtils.addMinutes(date, 0 - Config.processPlatform().getDeleteDraft().getThresholdMinutes());
	EntityManager em = emc.get(Draft.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
	Root<Draft> root = cq.from(Draft.class);
	Path<String> idPath = root.get(Draft_.id);
	Path<String> sequencePath = root.get(JpaObject_.sequence);
	Predicate p = cb.lessThan(root.get(JpaObject_.createTime), date);
	if (StringUtils.isNotEmpty(sequence)) {
		p = cb.and(p, cb.greaterThan(sequencePath, sequence));
	}
	cq.multiselect(idPath, sequencePath).where(p).orderBy(cb.asc(sequencePath));
	List<Tuple> os = em.createQuery(cq).setMaxResults(200).getResultList();
	List<Draft> list = new ArrayList<>();
	for (Tuple o : os) {
		Draft draft = new Draft();
		draft.setId(o.get(idPath));
		draft.setSequence(o.get(sequencePath));
		list.add(draft);
	}
	return list;
}
 
Example 2
Source File: DelayProcessor.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected List<Work> executing(AeiObjects aeiObjects, Delay delay) throws Exception {
	List<Work> results = new ArrayList<>();
	Date limit = null;
	if (null != delay.getDelayMode() && Objects.equals(DelayMode.until, delay.getDelayMode())) {
		limit = this.until(aeiObjects, delay);
	} else {
		Integer minutes = this.minute(aeiObjects, delay);
		if (delay.getWorkMinute()) {
			limit = Config.workTime().forwardMinutes(aeiObjects.getWork().getStartTime(), minutes);
		} else {
			limit = DateUtils.addMinutes(aeiObjects.getWork().getStartTime(), minutes);
		}
	}
	logger.debug("work title:{}, id:{}, limit time:{}.", aeiObjects.getWork().getTitle(),
			aeiObjects.getWork().getId(), limit);
	if (null == limit) {
		logger.warn("work title:{}, id:{}, on delay activity id:{}, get null date value.",
				aeiObjects.getWork().getTitle(), aeiObjects.getWork().getId(), delay.getId());
	}
	if (null != limit && (new Date()).after(limit)) {
		results.add(aeiObjects.getWork());
	}
	return results;
}
 
Example 3
Source File: RetryIntervalsConfigurationTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleRetryInterval() throws ParseException {
  // given
  BpmnModelInstance bpmnModelInstance = prepareProcessFailingServiceTaskWithRetryCycle("PT8M ");
  testRule.deploy(bpmnModelInstance);

  ClockUtil.setCurrentTime(SIMPLE_DATE_FORMAT.parse("2017-01-01T09:55:00"));

  ProcessInstance pi = runtimeService.startProcessInstanceByKey(PROCESS_ID);
  assertNotNull(pi);

  Date currentTime = SIMPLE_DATE_FORMAT.parse("2017-01-01T10:00:00");
  ClockUtil.setCurrentTime(currentTime);

  String processInstanceId = pi.getProcessInstanceId();

  int jobRetries = executeJob(processInstanceId);
  assertEquals(1, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 8);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  jobRetries = executeJob(processInstanceId);
  assertEquals(0, jobRetries);
}
 
Example 4
Source File: ComWorkflowServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean isCampaignTestFinished(WorkflowGraph workflowGraph, List<Integer> mailingTypes, Map<Integer, WorkflowMailingAware> mailingIconsByMailingId, Map<Integer, ComMailing> mailings, Map<Integer, Boolean> sentMailings, int companyId) {
    Date now = new Date();
    Date startDate = getCampaignTestStartDate(workflowGraph, mailingTypes, mailings);

    if (startDate == null) {
        return false;
    }

    for (ComMailing mailing: mailings.values()) {
        Date maxPossibleDateOfMailing = getMaxPossibleDateForTestRun(workflowGraph.findChains(mailingIconsByMailingId.get(mailing.getId()), false), startDate);
        if (now.before(maxPossibleDateOfMailing)) {
            return false;
        }

        if (!sentMailings.getOrDefault(mailing.getId(), false)) {
            String targetSQL = targetService.getSQLFromTargetExpression(mailing, false);
            int customersForMailing = workflowDao.countCustomers(companyId, mailing.getMailinglistID(), targetSQL);
            Date maxWaitForSendDate = DateUtils.addMinutes(maxPossibleDateOfMailing, ComWorkflowActivationService.TESTING_MODE_DEADLINE_DURATION);

            if (customersForMailing > 0 && now.before(maxWaitForSendDate)) {
                return false;
            }
        }
    }

    return true;
}
 
Example 5
Source File: AppServiceImpl.java    From Moss with Apache License 2.0 5 votes vote down vote up
private static Duration durationBuilder() {
    Date endDate = new Date();
    String end = DateFormatUtils.format(endDate, "yyyy-MM-dd HHmm");
    Date StartDate = DateUtils.addMinutes(endDate, -15);
    String start = DateFormatUtils.format(StartDate, "yyyy-MM-dd HHmm");

    Duration duration = new Duration();
    duration.setStart(start);
    duration.setEnd(end);
    duration.setStep("MINUTE");
    return duration;
}
 
Example 6
Source File: RetryIntervalsConfigurationTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetryGlobalConfiguration() throws ParseException {
  // given global retry conf. ("PT5M,PT20M, PT3M")
  BpmnModelInstance bpmnModelInstance = prepareProcessFailingServiceTask();
  testRule.deploy(bpmnModelInstance);

  ClockUtil.setCurrentTime(SIMPLE_DATE_FORMAT.parse("2017-01-01T09:55:00"));

  ProcessInstance pi = runtimeService.startProcessInstanceByKey(PROCESS_ID);

  Date currentTime = SIMPLE_DATE_FORMAT.parse("2017-01-01T10:00:00");
  ClockUtil.setCurrentTime(currentTime);

  String processInstanceId = pi.getProcessInstanceId();

  int jobRetries = executeJob(processInstanceId);
  assertEquals(3, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 5);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  jobRetries = executeJob(processInstanceId);
  assertEquals(2, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 20);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  jobRetries = executeJob(processInstanceId);
  assertEquals(1, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 3);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  jobRetries = executeJob(processInstanceId);
  assertEquals(0, jobRetries);
}
 
Example 7
Source File: RetryIntervalsConfigurationTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetryIntervals() throws ParseException {
  // given
  BpmnModelInstance bpmnModelInstance = prepareProcessFailingServiceTaskWithRetryCycle("PT3M, PT10M,PT8M");
  testRule.deploy(bpmnModelInstance);

  ClockUtil.setCurrentTime(SIMPLE_DATE_FORMAT.parse("2017-01-01T09:55:00"));

  ProcessInstance pi = runtimeService.startProcessInstanceByKey(PROCESS_ID);
  assertNotNull(pi);

  Date currentTime = SIMPLE_DATE_FORMAT.parse("2017-01-01T10:00:00");
  ClockUtil.setCurrentTime(currentTime);

  String processInstanceId = pi.getProcessInstanceId();

  int jobRetries = executeJob(processInstanceId);
  assertEquals(3, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 3);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  jobRetries = executeJob(processInstanceId);
  assertEquals(2, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 10);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  jobRetries = executeJob(processInstanceId);
  assertEquals(1, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 8);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  jobRetries = executeJob(processInstanceId);
  assertEquals(0, jobRetries);
}
 
Example 8
Source File: DeleteDraft.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private List<Work> listWork(EntityManagerContainer emc, String sequence) throws Exception {
	Date date = new Date();
	date = DateUtils.addMinutes(date, 0 - Config.processPlatform().getDeleteDraft().getThresholdMinutes());
	EntityManager em = emc.get(Work.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
	Root<Work> root = cq.from(Work.class);
	Path<String> idPath = root.get(Work_.id);
	Path<String> jobPath = root.get(Work_.job);
	Path<String> sequencePath = root.get(JpaObject_.sequence);
	Path<Date> sequenceActivityArrivedTime = root.get(Work_.activityArrivedTime);
	Predicate p = cb.lessThan(sequenceActivityArrivedTime, date);
	p = cb.and(p, cb.equal(root.get(Work_.workThroughManual), false));
	p = cb.and(p, cb.equal(root.get(Work_.workCreateType), Work.WORKCREATETYPE_SURFACE));
	if (StringUtils.isNotEmpty(sequence)) {
		p = cb.and(p, cb.greaterThan(sequencePath, sequence));
	}
	cq.multiselect(idPath, jobPath, sequencePath).where(p).orderBy(cb.asc(sequencePath));
	List<Tuple> os = em.createQuery(cq).setMaxResults(200).getResultList();
	List<Work> list = new ArrayList<>();
	for (Tuple o : os) {
		Work work = new Work();
		work.setId(o.get(idPath));
		work.setJob(o.get(jobPath));
		work.setSequence(o.get(sequencePath));
		list.add(work);
	}
	return list;
}
 
Example 9
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 10
Source File: Jobs.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@Scheduled(fixedRate = THIRTY_SECONDS)
public void cleanupExpiredPendingReservation() {
    log.trace("running job cleanupExpiredPendingReservation");
    try {
        //cleanup reservation that have a expiration older than "now minus 10 minutes": this give some additional slack.
        final Date expirationDate = DateUtils.addMinutes(new Date(), -10);
        ticketReservationManager.cleanupExpiredReservations(expirationDate);
        ticketReservationManager.cleanupExpiredOfflineReservations(expirationDate);
        ticketReservationManager.markExpiredInPaymentReservationAsStuck(expirationDate);
    } finally {
        log.trace("end job cleanupExpiredPendingReservation");
    }
}
 
Example 11
Source File: DateUtil.java    From cloudstreetmarket.com with GNU General Public License v3.0 4 votes vote down vote up
public static Date getXMinPriorDate(Date date, int nbMinutes) {
    return DateUtils.addMinutes(date, -1*nbMinutes);
}
 
Example 12
Source File: MonitorImpl.java    From peer-os with Apache License 2.0 4 votes vote down vote up
protected Date buildExpireTime()
{
    return DateUtils.addMinutes( new Date(), ALERT_LIVE_TIME );
}
 
Example 13
Source File: DateUtil.java    From cloudstreetmarket.com with GNU General Public License v3.0 4 votes vote down vote up
public static Date getXMinAfterDate(Date date, int nbMinutes) {
    return DateUtils.addMinutes(date, +1*nbMinutes);
}
 
Example 14
Source File: DateUtil.java    From j360-dubbo-app-all with Apache License 2.0 4 votes vote down vote up
/**
 * 减一分钟
 */
public static Date subMinutes(@NotNull final Date date, int amount) {
	return DateUtils.addMinutes(date, -amount);
}
 
Example 15
Source File: RetryIntervalsConfigurationTest.java    From camunda-bpm-platform with Apache License 2.0 4 votes vote down vote up
@Test
public void testIntervalsAfterUpdateRetries() throws ParseException {
  // given
  BpmnModelInstance bpmnModelInstance = prepareProcessFailingServiceTaskWithRetryCycle("PT3M, PT10M,PT8M");
  testRule.deploy(bpmnModelInstance);

  ClockUtil.setCurrentTime(SIMPLE_DATE_FORMAT.parse("2017-01-01T09:55:00"));

  ProcessInstance pi = runtimeService.startProcessInstanceByKey(PROCESS_ID);
  assertNotNull(pi);

  Date currentTime = SIMPLE_DATE_FORMAT.parse("2017-01-01T10:00:00");
  ClockUtil.setCurrentTime(currentTime);

  String processInstanceId = pi.getProcessInstanceId();

  int jobRetries = executeJob(processInstanceId);
  assertEquals(3, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 3);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  Job job = managementService.createJobQuery().processInstanceId(processInstanceId).singleResult();
  managementService.setJobRetries(Arrays.asList(job.getId()), 5);

  jobRetries = executeJob(processInstanceId);
  assertEquals(4, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 3);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  jobRetries = executeJob(processInstanceId);
  assertEquals(3, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 3);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  jobRetries = executeJob(processInstanceId);
  assertEquals(2, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 10);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  jobRetries = executeJob(processInstanceId);
  assertEquals(1, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 8);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  jobRetries = executeJob(processInstanceId);
  assertEquals(0, jobRetries);
}
 
Example 16
Source File: DateTools.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Date fromNowMinutes(Integer minutes) {
	Date date = new Date();
	return DateUtils.addMinutes(date, minutes);
}
 
Example 17
Source File: LogLongDetained.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void schedule(JobExecutionContext jobExecutionContext) throws Exception {
	try {
		TimeStamp stamp = new TimeStamp();
		String sequence = null;
		AtomicInteger workCount = new AtomicInteger();
		AtomicInteger taskCount = new AtomicInteger();
		AtomicInteger readCount = new AtomicInteger();
		Date workThreshold = DateUtils.addMinutes(new Date(),
				0 - Config.processPlatform().getLogLongDetained().getWorkThresholdMinutes());
		Date taskThreshold = DateUtils.addMinutes(new Date(),
				0 - Config.processPlatform().getLogLongDetained().getTaskThresholdMinutes());
		Date readThreshold = DateUtils.addMinutes(new Date(),
				0 - Config.processPlatform().getLogLongDetained().getReadThresholdMinutes());
		File file = new File(Config.dir_logs(true),
				"longDetained_" + DateTools.format(new Date(), DateTools.formatCompact_yyyyMMddHHmmss) + ".txt");
		try (FileWriter writer = new FileWriter(file, true)) {
			List<Work> works = new ArrayList<>();
			List<Read> reads = new ArrayList<>();
			List<Task> tasks = new ArrayList<>();
			do {
				try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
					works = this.listWork(emc, workThreshold, sequence);
				}
				if (!works.isEmpty()) {
					sequence = works.get(works.size() - 1).getSequence();
					for (Work work : works) {
						writer.append("work id:").append(work.getId()).append(", job:").append(work.getJob())
								.append(", startTime:")
								.append(DateTools.format(work.getStartTime(), DateTools.format_yyyyMMddHHmmss))
								.append(", title:").append(work.getTitle()).append(".")
								.append(System.lineSeparator());
						workCount.incrementAndGet();
					}
				}
			} while (!works.isEmpty());
			do {
				try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
					tasks = this.listTask(emc, taskThreshold, sequence);
				}
				if (!tasks.isEmpty()) {
					sequence = tasks.get(tasks.size() - 1).getSequence();
					for (Task task : tasks) {
						writer.append("task id:").append(task.getId()).append(", job:").append(task.getJob())
								.append(", startTime:")
								.append(DateTools.format(task.getStartTime(), DateTools.format_yyyyMMddHHmmss))
								.append(", title:").append(task.getTitle()).append(".")
								.append(System.lineSeparator());
						taskCount.incrementAndGet();
					}
				}
			} while (!tasks.isEmpty());
			do {
				try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
					reads = this.listRead(emc, readThreshold, sequence);
				}
				if (!reads.isEmpty()) {
					sequence = reads.get(reads.size() - 1).getSequence();
					for (Read read : reads) {
						writer.append("read id:").append(read.getId()).append(", job:").append(read.getJob())
								.append(", startTime:")
								.append(DateTools.format(read.getStartTime(), DateTools.format_yyyyMMddHHmmss))
								.append(", title:").append(read.getTitle()).append(".")
								.append(System.lineSeparator());
						readCount.incrementAndGet();
					}
				}
			} while (!reads.isEmpty());
		}
		logger.print("记录长时间停滞工作{}个,待办{}个,待阅{}个, 耗时:{}.", workCount.intValue(), taskCount.intValue(),
				readCount.intValue(), stamp.consumingMilliseconds());
	} catch (Exception e) {
		throw new JobExecutionException(e);
	}
}
 
Example 18
Source File: DateUtil.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 减一分钟
 */
public static Date subMinutes(@NotNull final Date date, int amount) {
	return DateUtils.addMinutes(date, -amount);
}
 
Example 19
Source File: RetryIntervalsConfigurationTest.java    From camunda-bpm-platform with Apache License 2.0 4 votes vote down vote up
@Test
public void testlocalConfigurationWithNestedChangingExpression() throws ParseException {
  BpmnModelInstance bpmnModelInstance = Bpmn.createExecutableProcess("process")
      .startEvent()
      .serviceTask()
        .camundaClass("foo")
        .camundaAsyncBefore()
        .camundaFailedJobRetryTimeCycle("${var}")
      .endEvent()
      .done();

  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  Date startDate = simpleDateFormat.parse("2017-01-01T09:55:00");
  ClockUtil.setCurrentTime(startDate);

  testRule.deploy(bpmnModelInstance);

  VariableMap params = Variables.createVariables();
  params.putValue("var", "${nestedVar1},PT15M,${nestedVar3}");
  params.putValue("nestedVar", "PT13M");
  params.putValue("nestedVar1", "PT5M");
  params.putValue("nestedVar3", "PT25M");
  ProcessInstance pi = runtimeService.startProcessInstanceByKey("process", params);

  ClockUtil.setCurrentTime(SIMPLE_DATE_FORMAT.parse("2017-01-01T09:55:00"));

  assertNotNull(pi);

  Date currentTime = SIMPLE_DATE_FORMAT.parse("2017-01-01T10:00:00");
  ClockUtil.setCurrentTime(currentTime);

  String processInstanceId = pi.getProcessInstanceId();

  int jobRetries = executeJob(processInstanceId);
  assertEquals(3, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 5);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  jobRetries = executeJob(processInstanceId);
  assertEquals(2, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 15);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  runtimeService.setVariable(pi.getProcessInstanceId(), "var", "${nestedVar}");

  jobRetries = executeJob(processInstanceId);
  assertEquals(1, jobRetries);
  currentTime = DateUtils.addMinutes(currentTime, 13);
  assertDueDateTime(currentTime);
  ClockUtil.setCurrentTime(currentTime);

  jobRetries = executeJob(processInstanceId);
  assertEquals(0, jobRetries);
}
 
Example 20
Source File: DatePlusMinutes.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void add_minutes_to_date_in_java_with_apachecommons () {

	Calendar newYearsEve = Calendar.getInstance();
	newYearsEve.set(2012, 11, 31, 23, 59, 0);
	
	Date newYearsDay = DateUtils.addMinutes(newYearsEve.getTime(), 1);
	
	SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");

	logger.info(dateFormatter.format(newYearsEve.getTime()));
	logger.info(dateFormatter.format(newYearsDay));

	assertTrue(newYearsDay.after(newYearsEve.getTime()));
}