Example usage for org.apache.commons.lang3.time DateUtils addHours

List of usage examples for org.apache.commons.lang3.time DateUtils addHours

Introduction

In this page you can find the example usage for org.apache.commons.lang3.time DateUtils addHours.

Prototype

public static Date addHours(final Date date, final int amount) 

Source Link

Document

Adds a number of hours to a date returning a new object.

Usage

From source file:eionet.webq.task.RemoveExpiredUserFilesTaskIntegrationTest.java

private void setFileAsExpired() {
    Date expired = DateUtils.addSeconds(DateUtils.addHours(new Date(), -task.getExpirationHours()), -1);
    factory.getCurrentSession().createQuery("UPDATE UserFile SET updated=:updated")
            .setTimestamp("updated", new Timestamp(expired.getTime())).executeUpdate();
}

From source file:com.francetelecom.clara.cloud.coremodel.EnvironmentRepositoryPurgeTest.java

@Test
@Transactional/*  w ww  .  j av  a 2 s . c om*/
public void should_find_older_removed_environments() {
    // GIVEN
    int fiveDay = 5;

    Date jMinusFourDayAndTwentyThreeHours = DateHelper.getDateDeltaDay(-4);
    jMinusFourDayAndTwentyThreeHours = DateUtils.addHours(jMinusFourDayAndTwentyThreeHours, -23);

    Date jMinusFiveDayAndOneSecond = DateHelper.getDateDeltaDay(-5);
    jMinusFiveDayAndOneSecond = DateUtils.addSeconds(jMinusFiveDayAndOneSecond, -1);
    Date jMinusHeight = DateHelper.getDateDeltaDay(-8);

    // default environment
    Environment environment = new Environment(DeploymentProfileEnum.PRODUCTION, "default", release, bob,
            technicalDeploymentInstance);
    environmentRepository.save(environment);
    LOG.info("test env {}", environment);

    // default old environment
    DateHelper.setNowDate(jMinusFiveDayAndOneSecond);
    Environment environmentOld = new Environment(DeploymentProfileEnum.PRODUCTION, "old", release, bob,
            technicalDeploymentInstance);
    Assume.assumeTrue(environmentOld.getCreationDate().equals(jMinusFiveDayAndOneSecond));
    DateHelper.resetNow();
    environmentRepository.save(environmentOld);
    LOG.info("test env {}", environmentOld);

    // given default removed environment
    DateHelper.setNowDate(jMinusFourDayAndTwentyThreeHours);
    Environment removed = new Environment(DeploymentProfileEnum.PRODUCTION, "defaultRemoved", release, bob,
            technicalDeploymentInstance);
    removed.setStatus(EnvironmentStatus.REMOVED);
    DateHelper.resetNow();
    environmentRepository.save(removed);
    LOG.info("test env {}", removed);

    // given older removed environment A (j-6)
    DateHelper.setNowDate(jMinusFiveDayAndOneSecond);
    Environment oldRemovedA = new Environment(DeploymentProfileEnum.PRODUCTION, "oldRemovedA", release, bob,
            technicalDeploymentInstance);
    oldRemovedA.setStatus(EnvironmentStatus.REMOVED);
    DateHelper.resetNow();
    Assume.assumeTrue(oldRemovedA.getDeletionDate().equals(jMinusFiveDayAndOneSecond));
    environmentRepository.save(oldRemovedA);
    LOG.info("test env {}", oldRemovedA);

    // given older removed environment B  (j-8)
    DateHelper.setNowDate(jMinusHeight);
    Environment oldRemovedB = new Environment(DeploymentProfileEnum.PRODUCTION, "oldRemovedB", release, bob,
            technicalDeploymentInstance);
    oldRemovedB.setStatus(EnvironmentStatus.REMOVED);
    DateHelper.resetNow();
    Assume.assumeTrue(oldRemovedB.getDeletionDate().equals(jMinusHeight));
    environmentRepository.save(oldRemovedB);
    LOG.info("test env {}", oldRemovedA);

    // WHEN
    List<Environment> results = environmentRepository
            .findRemovedOlderThanNDays(DateHelper.getDateDeltaDay(-fiveDay));

    // THEN
    assertThat(results).containsExactly(oldRemovedA, oldRemovedB);
}

From source file:io.lavagna.service.CardDataServiceTest.java

@Test
public void TestUpdateDescription() {
    assertTrue(cardDataService.findAllCommentsByCardId(card1.getId()).isEmpty());
    // when updating a card that has no description, a fresh one is created
    String newCardDescription = "test-update-description";
    cardDataService.updateDescription(card1.getId(), newCardDescription, DateUtils.addHours(new Date(), -3),
            user.getId());//from w  w w .j a v a  2s  . c o  m
    assertEquals(cardDataService.findDescriptionByCardId(card1.getId()).size(), 1);
    assertEquals(newCardDescription, cardDataService.findLatestDescriptionByCardId(card1.getId()).getContent());

    List<CardData> cardData = cardDataRepo.findAllDataLightByCardIdAndType(card1.getId(), CardType.DESCRIPTION);
    assertEquals(1, cardData.size());
    CardData cardData1 = cardDataRepo.getUndeletedDataLightById(cardData.get(0).getId());
    assertEquals(CardType.DESCRIPTION, cardData1.getType());

    cardDataService.updateDescription(card1.getId(), "test-update-description-after-update", new Date(),
            user.getId());
    List<CardData> updatedCardData = cardDataRepo.findAllDataLightByCardId(card1.getId());
    assertEquals(2, updatedCardData.size());
    assertEquals(1,
            cardDataRepo.findAllDataLightByCardIdAndType(card1.getId(), CardType.DESCRIPTION_HISTORY).size());
    assertEquals(1, cardDataRepo.findAllDataLightByCardIdAndType(card1.getId(), CardType.DESCRIPTION).size());

    assertEquals(cardData1.getId(), updatedCardData.get(0).getId());
    assertEquals("test-update-description-after-update", updatedCardData.get(0).getContent());

    assertEquals("test-update-description-after-update",
            cardDataService.findLatestDescriptionByCardId(card1.getId()).getContent());
}

From source file:de.heartbeat.charts.YearOverview.java

private List<Point> getPoints(List<HeartBeat> hbList) {
    List<Point> points = new ArrayList<>();
    int y = 0;/*from   www .  j a v a  2s  .  c o  m*/
    for (int i = hbList.size() - 1; i >= 0; i--) {
        Timestamp ts = hbList.get(i).getTime();
        Date time = new Date(ts.getTime());
        // some bug in charts or sth.
        time = DateUtils.addHours(time, 1);
        long timeL = time.getTime();
        points.add(new Point().setX(timeL).setY(Double.parseDouble(hbList.get(i).getPulse())));

    }

    return points;
}

From source file:com.nridge.core.app.mgr.ServiceTimer.java

private Date getNextTS(String aFieldName, Date aTS) {
    String timeString = getAppString(aFieldName);
    if (StringUtils.isNotEmpty(timeString)) {
        if (StringUtils.endsWithIgnoreCase(timeString, "m")) {
            String minuteString = StringUtils.stripEnd(timeString, "m");
            if ((StringUtils.isNotEmpty(minuteString)) && (StringUtils.isNumeric(minuteString))) {
                int minuteAmount = Integer.parseInt(minuteString);
                return DateUtils.addMinutes(aTS, minuteAmount);
            }/*from   w  w  w  . j ava 2  s. c o m*/
        } else if (StringUtils.endsWithIgnoreCase(timeString, "h")) {
            String hourString = StringUtils.stripEnd(timeString, "h");
            if ((StringUtils.isNotEmpty(hourString)) && (StringUtils.isNumeric(hourString))) {
                int hourAmount = Integer.parseInt(hourString);
                return DateUtils.addHours(aTS, hourAmount);
            }
        } else // we assume days
        {
            String dayString = StringUtils.stripEnd(timeString, "d");
            if ((StringUtils.isNotEmpty(dayString)) && (StringUtils.isNumeric(dayString))) {
                int dayAmount = Integer.parseInt(dayString);
                return DateUtils.addDays(aTS, dayAmount);
            }
        }
    }

    // Push 1 hour ahead to avoid triggering a match with TS

    return DateUtils.addHours(new Date(), 1);
}

From source file:com.stratelia.webactiv.util.DateUtilTest.java

@Test
public void testDatesAreEqual() {
    Date date1 = java.sql.Date.valueOf("2013-01-01");
    Date date2 = DateUtils.addHours(java.sql.Date.valueOf("2013-01-02"), 3);
    assertThat(false, is(DateUtil.datesAreEqual(date1, date2)));

    date1 = java.sql.Date.valueOf("2013-01-02");
    assertThat(false, is(date1.compareTo(date2) == 0));
    assertThat(true, is(DateUtil.datesAreEqual(date1, date2)));
}

From source file:com.stratelia.webactiv.util.DateUtilTest.java

@Test
public void testCompareTo() {
    Date date1 = java.sql.Date.valueOf("2013-01-01");
    Date date2 = DateUtils.addHours(java.sql.Date.valueOf("2013-01-02"), 3);
    assertThat(false, is(DateUtil.compareTo(date1, date2) == 0));
    assertThat(false, is(DateUtil.compareTo(date1, date2) > 0));
    assertThat(true, is(DateUtil.compareTo(date1, date2) < 0));

    date1 = java.sql.Date.valueOf("2013-01-02");
    assertThat(true, is(DateUtil.compareTo(date1, date2) == 0));
    assertThat(false, is(DateUtil.compareTo(date1, date2) > 0));
    assertThat(false, is(DateUtil.compareTo(date1, date2) < 0));

    assertThat(false, is(DateUtil.compareTo(date1, date2, false) == 0));
    assertThat(false, is(DateUtil.compareTo(date1, date2, false) > 0));
    assertThat(true, is(DateUtil.compareTo(date1, date2, false) < 0));

    date1 = DateUtils.addHours(java.sql.Date.valueOf("2013-01-02"), 4);
    assertThat(false, is(DateUtil.compareTo(date1, date2, false) == 0));
    assertThat(true, is(DateUtil.compareTo(date1, date2, false) > 0));
    assertThat(false, is(DateUtil.compareTo(date1, date2, false) < 0));
}

From source file:io.wcm.wcm.commons.caching.CacheHeader.java

/**
 * Set expires header to given amount of hours in the future.
 * @param response Response/*from w  ww  .  jav a 2 s . com*/
 * @param hours Hours to expire
 */
public static void setExpiresHours(HttpServletResponse response, int hours) {
    Date expiresDate = DateUtils.addHours(new Date(), hours);
    setExpires(response, expiresDate);
}

From source file:alfio.manager.WaitingQueueProcessorIntegrationTest.java

private Pair<String, Event> initSoldOutEvent(boolean withUnboundedCategory) throws InterruptedException {
    int boundedCategorySize = AVAILABLE_SEATS - (withUnboundedCategory ? 1 : 0);
    List<TicketCategoryModification> categories = new ArrayList<>();
    categories.add(new TicketCategoryModification(null, "default", boundedCategorySize,
            new DateTimeModification(LocalDate.now().minusDays(1), LocalTime.now()),
            new DateTimeModification(LocalDate.now().plusDays(2), LocalTime.now()), DESCRIPTION,
            BigDecimal.ZERO, false, "", true, null, null, null, null, null));

    if (withUnboundedCategory) {
        categories.add(new TicketCategoryModification(null, "unbounded", 0,
                new DateTimeModification(LocalDate.now().minusDays(1), LocalTime.now()),
                new DateTimeModification(LocalDate.now().plusDays(2), LocalTime.now()), DESCRIPTION,
                BigDecimal.ZERO, false, "", false, null, null, null, null, null));
    }/*from  w ww. j a v a2  s.  co m*/

    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);
    Event event = pair.getKey();
    List<TicketCategory> ticketCategories = eventManager.loadTicketCategories(event);
    TicketCategory bounded = ticketCategories.stream().filter(t -> t.getName().equals("default")).findFirst()
            .orElseThrow(IllegalStateException::new);
    List<Integer> boundedReserved = ticketRepository.selectFreeTicketsForPreReservation(event.getId(), 20,
            bounded.getId());
    assertEquals(boundedCategorySize, boundedReserved.size());
    List<Integer> reserved = new ArrayList<>(boundedReserved);
    String reservationId = UUID.randomUUID().toString();
    ticketReservationRepository.createNewReservation(reservationId, DateUtils.addHours(new Date(), 1), null,
            Locale.ITALIAN.getLanguage(), event.getId(), event.getVat(), event.isVatIncluded());
    List<Integer> reservedForUpdate = withUnboundedCategory ? reserved.subList(0, 19) : reserved;
    ticketRepository.reserveTickets(reservationId, reservedForUpdate, bounded.getId(),
            Locale.ITALIAN.getLanguage(), 0);
    if (withUnboundedCategory) {
        TicketCategory unbounded = ticketCategories.stream().filter(t -> t.getName().equals("unbounded"))
                .findFirst().orElseThrow(IllegalStateException::new);
        List<Integer> unboundedReserved = ticketRepository
                .selectNotAllocatedFreeTicketsForPreReservation(event.getId(), 20);
        assertEquals(1, unboundedReserved.size());
        reserved.addAll(unboundedReserved);
        ticketRepository.reserveTickets(reservationId, reserved.subList(19, 20), unbounded.getId(),
                Locale.ITALIAN.getLanguage(), 0);
    }
    ticketRepository.updateTicketsStatusWithReservationId(reservationId, Ticket.TicketStatus.ACQUIRED.name());

    //sold-out
    waitingQueueManager.subscribe(event, new CustomerName("Giuseppe Garibaldi", "Giuseppe", "Garibaldi", event),
            "peppino@garibaldi.com", null, Locale.ENGLISH);
    Thread.sleep(100L);//we are testing ordering, not concurrency...
    waitingQueueManager.subscribe(event, new CustomerName("Nino Bixio", "Nino", "Bixio", event),
            "bixio@mille.org", null, Locale.ITALIAN);
    List<WaitingQueueSubscription> subscriptions = waitingQueueRepository.loadAll(event.getId());
    assertTrue(waitingQueueRepository.countWaitingPeople(event.getId()) == 2);
    assertTrue(subscriptions.stream()
            .allMatch(w -> w.getSubscriptionType().equals(WaitingQueueSubscription.Type.SOLD_OUT)));

    //the following call shouldn't have any effect
    waitingQueueSubscriptionProcessor.distributeAvailableSeats(event);
    assertTrue(waitingQueueRepository.countWaitingPeople(event.getId()) == 2);
    return Pair.of(reservationId, event);
}

From source file:com.gargoylesoftware.htmlunit.CacheTest.java

/**
 * Ensures {@link WebResponse#cleanUp()} is called for overflow deleted entries.
 * @throws Exception if the test fails/*www  . java 2 s  .  c om*/
 */
@Test
public void cleanUpOverflow() throws Exception {
    final WebRequest request1 = new WebRequest(URL_FIRST, HttpMethod.GET);
    final WebResponse response1 = createMock(WebResponse.class);
    expect(response1.getWebRequest()).andReturn(request1);
    expectLastCall().atLeastOnce();
    expect(response1.getResponseHeaderValue("Last-Modified")).andReturn(null);
    expect(response1.getResponseHeaderValue("Expires"))
            .andReturn(StringUtils.formatHttpDate(DateUtils.addHours(new Date(), 1)));

    final WebRequest request2 = new WebRequest(URL_SECOND, HttpMethod.GET);
    final WebResponse response2 = createMock(WebResponse.class);
    expect(response2.getWebRequest()).andReturn(request2);
    expectLastCall().atLeastOnce();
    expect(response2.getResponseHeaderValue("Last-Modified")).andReturn(null);
    expect(response2.getResponseHeaderValue("Expires"))
            .andReturn(StringUtils.formatHttpDate(DateUtils.addHours(new Date(), 1)));

    response1.cleanUp();

    replay(response1, response2);

    final Cache cache = new Cache();
    cache.setMaxSize(1);
    cache.cacheIfPossible(request1, response1, null);
    Thread.sleep(10);
    cache.cacheIfPossible(request2, response2, null);

    verify(response1);
}