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 Project: alf.io   Author: alfio-event   File: TicketReservationManagerIntegrationTest.java    License: 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 Project: camunda-bpm-platform   Author: camunda   File: HistoricProcessInstanceAuthorizationTest.java    License: 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 #3
Source Project: gocd   Author: gocd   File: PipelineServiceIntegrationTest.java    License: 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 #4
Source Project: tutorials   Author: eugenp   File: MapDeserializationUnitTest.java    License: 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 #5
Source Project: OpenEstate-IO   Author: OpenEstate   File: TrovitUtils.java    License: 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 #6
Source Project: alf.io   Author: alfio-event   File: EventManagerIntegrationTest.java    License: 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 #7
Source Project: camunda-bpm-platform   Author: camunda   File: IdentityServiceTest.java    License: 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 #8
Source Project: FoxBPM   Author: FoxBPM   File: GetWorkCalendarEndTimeCmd.java    License: 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 #9
Source Project: camunda-bpm-platform   Author: camunda   File: CleanableHistoricCaseInstanceReportTest.java    License: 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 #10
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 #11
Source Project: code   Author: lastwhispers   File: OrderService.java    License: 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 #12
Source Project: uyuni   Author: uyuni-project   File: MinionCheckinTest.java    License: 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 #13
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 #14
Source Project: cerberus-source   Author: cerberustesting   File: ReadTestCaseExecutionMedia.java    License: 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 #15
Source Project: seed   Author: jadyer   File: OpenFilter.java    License: 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 #16
Source Project: Milkomeda   Author: yizzuide   File: DateConstraintValidator.java    License: 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 #17
Source Project: open-capacity-platform   Author: open-capacity-platform   File: JobLogController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping("/clearLog")
@ResponseBody
public ReturnT<String> clearLog(int jobGroup, int jobId, int type){

	Date clearBeforeTime = null;
	int clearBeforeNum = 0;
	if (type == 1) {
		clearBeforeTime = DateUtils.addMonths(new Date(), -1);	// 清理一个月之前日志数据
	} else if (type == 2) {
		clearBeforeTime = DateUtils.addMonths(new Date(), -3);	// 清理三个月之前日志数据
	} else if (type == 3) {
		clearBeforeTime = DateUtils.addMonths(new Date(), -6);	// 清理六个月之前日志数据
	} else if (type == 4) {
		clearBeforeTime = DateUtils.addYears(new Date(), -1);	// 清理一年之前日志数据
	} else if (type == 5) {
		clearBeforeNum = 1000;		// 清理一千条以前日志数据
	} else if (type == 6) {
		clearBeforeNum = 10000;		// 清理一万条以前日志数据
	} else if (type == 7) {
		clearBeforeNum = 30000;		// 清理三万条以前日志数据
	} else if (type == 8) {
		clearBeforeNum = 100000;	// 清理十万条以前日志数据
	} else if (type == 9) {
		clearBeforeNum = 0;			// 清理所有日志数据
	} else {
		return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("joblog_clean_type_unvalid"));
	}

	xxlJobLogDao.clearLog(jobGroup, jobId, clearBeforeTime, clearBeforeNum);
	return ReturnT.SUCCESS;
}
 
Example #18
Source Project: org.hl7.fhir.core   Author: hapifhir   File: BaseDateTimeType.java    License: 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;
}
 
Example #19
Source Project: MVPAndroidBootstrap   Author: richardradics   File: OnClickHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tries to occupy the onclick enabler.
 * @param waitMs the time interval to occupy
 * @return if noone occupied it, returns true, else false
 */
public static boolean occupy(int waitMs){
    if(occupiedUntil != null && occupiedUntil.after(new Date())){
        return false;
    }
    occupiedUntil = DateUtils.addMilliseconds(new Date(), waitMs);
    return true;
}
 
Example #20
Source Project: dsworkbench   Author: Torridity   File: DefensePlanerWizard.java    License: Apache License 2.0 5 votes vote down vote up
private static List<SOSRequest> createSampleRequests() {
    int wallLevel = 20;
    int supportCount = 100;
    int maxAttackCount = 50;
    int maxFakeCount = 0;

    List<SOSRequest> result = new LinkedList<>();
    Village[] villages = GlobalOptions.getSelectedProfile().getTribe().getVillageList();
    Village[] attackerVillages = DataHolder.getSingleton().getTribeByName("Alexander25").getVillageList();

    for (int i = 0; i < supportCount; i++) {
        int id = (int) Math.rint(Math.random() * (villages.length - 1));
        Village target = villages[id];
        SOSRequest r = new SOSRequest(target.getTribe());
        r.addTarget(target);
        TargetInformation info = r.getTargetInformation(target);
        info.setWallLevel(wallLevel);

        TroopAmountFixed troops = new TroopAmountFixed();
        troops.setAmountForUnit("spear", (int) Math.rint(Math.random() * 14000));
        troops.setAmountForUnit("sword", (int) Math.rint(Math.random() * 14000));
        troops.setAmountForUnit("heavy", (int) Math.rint(Math.random() * 5000));
        info.setTroops(troops);

        int cnt = (int) Math.rint(maxAttackCount * Math.random());
        for (int j = 0; j < cnt; j++) {
            int idx = (int) Math.rint(Math.random() * (attackerVillages.length - 2));
            Village v = attackerVillages[idx];
            info.addAttack(v, new Date(System.currentTimeMillis() + Math.round(DateUtils.MILLIS_PER_DAY * 7 * Math.random())));
            for (int k = 0; k < (int) Math.rint(maxFakeCount * Math.random()); k++) {
                idx = (int) Math.rint(Math.random() * (attackerVillages.length - 2));
                v = attackerVillages[idx];
                info.addAttack(v, new Date(System.currentTimeMillis() + Math.round(3600 * Math.random())));
            }
        }
        result.add(r);
    }

    return result;
}
 
Example #21
Source Project: logbook   Author: sanaehirotaka   File: ResourceChartDialogEx.java    License: MIT License 5 votes vote down vote up
/**
 * DateTimeで選択されている日付からCalendarインスタンスを作成します
 *
 * @param dateTime
 * @return
 */
private static Calendar getCalendar(DateTime dateTime) {
    Calendar cal = DateUtils.truncate(Calendar.getInstance(TimeZone.getDefault()), Calendar.DAY_OF_MONTH);
    cal.set(Calendar.YEAR, dateTime.getYear());
    cal.set(Calendar.MONTH, dateTime.getMonth());
    cal.set(Calendar.DAY_OF_MONTH, dateTime.getDay());
    return cal;
}
 
Example #22
Source Project: weixin-java-tools   Author: DarLiner   File: WxMaAnalysisServiceImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDailyRetainInfo() throws Exception {
  final WxMaAnalysisService service = wxMaService.getAnalysisService();
  Date twoDaysAgo = DateUtils.addDays(new Date(), -2);
  WxMaRetainInfo retainInfo = service.getDailyRetainInfo(twoDaysAgo, twoDaysAgo);
  assertNotNull(retainInfo);
  System.out.println(retainInfo);
}
 
Example #23
Source Project: sample-timesheets   Author: cuba-platform   File: HolidaysCache.java    License: Apache License 2.0 5 votes vote down vote up
private String doLoadCache(boolean lockReadBeforeFinish) {
    try {
        lock.writeLock().lock();
        cache = new TreeMap<>();
        LoadContext<Holiday> loadContext = new LoadContext<>(Holiday.class);
        loadContext.setQueryString("select e from ts$Holiday e " +
                "where (e.startDate between :start and :end) or (e.endDate between :start and :end)")
                .setParameter("start", DateUtils.addYears(timeSource.currentTimestamp(), -1))
                .setParameter("end", DateUtils.addYears(timeSource.currentTimestamp(), 1));
        List<Holiday> holidays = dataManager.loadList(loadContext);
        for (Holiday holiday : holidays) {
            Date startDate = holiday.getStartDate();
            Date endDate = holiday.getEndDate();
            Date currentDate = startDate;
            while (currentDate.before(endDate)) {
                cache.put(currentDate, holiday);
                currentDate = DateUtils.addDays(currentDate, 1);
            }
        }

        if (lockReadBeforeFinish) {
            lock.readLock().lock();
        }
        return "Successfully loaded";
    } finally {
        lock.writeLock().unlock();
    }
}
 
Example #24
Source Project: vjtools   Author: DarLiner   File: CleanUpScheduler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * return current date time by specified hour:minute
 * 
 * @param plan format: hh:mm
 */
public static Date getCurrentDateByPlan(String plan, String pattern) {
	try {
		FastDateFormat format = FastDateFormat.getInstance(pattern);
		Date end = format.parse(plan);
		Calendar today = Calendar.getInstance();
		end = DateUtils.setYears(end, (today.get(Calendar.YEAR)));
		end = DateUtils.setMonths(end, today.get(Calendar.MONTH));
		end = DateUtils.setDays(end, today.get(Calendar.DAY_OF_MONTH));
		return end;
	} catch (Exception e) {
		throw ExceptionUtil.unchecked(e);
	}
}
 
Example #25
Source Project: alf.io   Author: alfio-event   File: TicketReservationManager.java    License: 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 #26
Source Project: camunda-bpm-platform   Author: camunda   File: FailedJobListenerWithRetriesTest.java    License: 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 #27
Source Project: cuba   Author: cuba-platform   File: DataManagerTest.java    License: 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 #28
Source Project: jvue-admin   Author: ccfish86   File: SearchUtils.java    License: 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 #29
Source Project: o2oa   Author: o2oa   File: DateTools.java    License: 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 #30
Source Project: alf.io   Author: alfio-event   File: NotificationManager.java    License: 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();
}