Example usage for org.apache.commons.lang.time DateUtils addDays

List of usage examples for org.apache.commons.lang.time DateUtils addDays

Introduction

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

Prototype

public static Date addDays(Date date, int amount) 

Source Link

Document

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

Usage

From source file:com.runwaysdk.business.email.EmailKey.java

/**
 * Checks if this EmailKey is valid by comparing the value
 * of the issue date with the current date. If the difference
 * between those two dates is greater than the number of days
 * specified by the value of keyExpire in email.properties then
 * the EmailKey is invalid. If this EmailKey is invalid, it is up
 * to the developer to delete it and re-issue a new one.
 * //from  www.ja v  a2  s .co m
 * @return
 */
public boolean isDateValid() {
    Date issued = getIssuedOnDate();
    int expireDays = EmailProperties.getKeyExpire();
    Date expireDate = DateUtils.addDays(issued, expireDays);

    Date now = new Date();
    return now.before(expireDate);
}

From source file:gov.nih.nci.security.upt.forms.SystemConfigurationForm.java

public void buildDBObject(UserProvisioningManager userProvisioningManager) throws Exception {
    AbstractConfiguration dataConfig = ConfigurationHelper.getConfiguration();
    Iterator entries = request.getParameterMap().entrySet().iterator();
    String prevExpiryVal = null;//ww w. ja  v a  2  s  .  com
    String[] currExpiryVal = null;
    while (entries.hasNext()) {
        Entry thisEntry = (Entry) entries.next();
        Object key = thisEntry.getKey();
        String keyString = (String) thisEntry.getKey();
        if (keyString != null && keyString.equalsIgnoreCase("PASSWORD_EXPIRY_DAYS")) {

            if (dataConfig.getProperty(keyString) != null) {

                prevExpiryVal = (String) dataConfig.getProperty(keyString);
                currExpiryVal = (String[]) thisEntry.getValue();

            }
        }

        if (dataConfig.getProperty((String) thisEntry.getKey()) != null) {
            dataConfig.setProperty((String) thisEntry.getKey(), thisEntry.getValue());
        }
        Object value = thisEntry.getValue();

    }
    if (prevExpiryVal != null && currExpiryVal[0] != null) {
        if (!prevExpiryVal.equalsIgnoreCase(currExpiryVal[0])) {
            List<User> list = userProvisioningManager.getUsers();
            if (list != null) {

                Iterator UserListIterator = list.iterator();
                while (UserListIterator.hasNext()) {
                    User user = (User) UserListIterator.next();
                    if (user != null) {
                        // compare and update the expiry dates here
                        int dateDiff = Integer.parseInt(currExpiryVal[0]) - Integer.parseInt(prevExpiryVal);
                        user.setPasswordExpiryDate(DateUtils.addDays(user.getPasswordExpiryDate(), dateDiff));
                        userProvisioningManager.modifyUser(user);
                    }

                }
            }
        }
    }

}

From source file:net.audumla.climate.bom.BOMSimpleHistoricalClimateObserver.java

private void loadHistoricalData(String url) {
    CSVReader reader = new CSVReader(
            BOMDataLoader.instance().getData(BOMDataLoader.HTTP, BOMDataLoader.BOMHTTP, url));
    // ArrayList<HistoricalData> history = new ArrayList<HistoricalData>();
    String[] data;//  ww w. ja va 2  s  .co m
    boolean pastHeader = false;
    try {
        while ((data = reader.readNext()) != null) {
            if (pastHeader) {
                // [, JulianDate, Minimum temperature (C), Maximum temperature (C), Rainfall (mm), Evaporation (mm),
                // Sunshine (hours), Direction of maximum wind gust , Speed of maximum wind gust (km/h), Time of
                // maximum wind gust, 9am Temperature (C), 9am relative humidity (%), 9am cloud amount (oktas), 9am
                // wind direction, 9am wind speed (km/h), 9am MSL pressure (hPa), 3pm Temperature (C), 3pm relative
                // humidity (%), 3pm cloud amount (oktas), 3pm wind direction, 3pm wind speed (km/h), 3pm MSL
                // pressure (hPa)]
                try {
                    Date date = historyDateFormatter.parse(data[1]);
                    Date dateM1 = DateUtils.addDays(date, -1);
                    WritableClimateData cdNow = ClimateDataFactory
                            .convertToWritableClimateData(historicalData.get(date));
                    if (cdNow == null) {
                        cdNow = ClimateDataFactory.newWritableClimateData(this, getSource()); // now
                        cdNow.setTime(date);
                        historicalData.put(date, ClimateDataFactory.convertToReadOnlyClimateData(cdNow));
                    }
                    WritableClimateData cdNowM1 = ClimateDataFactory
                            .convertToWritableClimateData(historicalData.get(dateM1));
                    if (cdNowM1 == null) {
                        cdNowM1 = ClimateDataFactory.newWritableClimateData(this, getSource()); // now
                        cdNowM1.setTime(dateM1);
                        historicalData.put(dateM1, ClimateDataFactory.convertToReadOnlyClimateData(cdNowM1));
                    }

                    cdNow.setTime(date); // 2013-02-1
                    try {
                        cdNow.setMinimumTemperature(SafeParse.parseDouble(data[2]));
                    } catch (Exception e) {
                        LOG.debug("Error setting historical field", e);
                    }
                    try {
                        cdNow.setMaximumTemperature(SafeParse.parseDouble(data[3]));
                    } catch (Exception e) {
                        LOG.debug("Error setting historical field", e);
                    }
                    try {
                        Double rain = SafeParse.parseDouble(data[4]);
                        if (rain != null) {
                            cdNowM1.setRainfall(rain);
                            cdNowM1.setRainfallProbability(cdNowM1.getRainfall() > 0 ? 100d : 0d);
                        }
                    } catch (Exception e) {
                        LOG.debug("Error setting historical field", e);
                    }
                    try {
                        cdNow.setEvaporation(SafeParse.parseDouble(data[5]));
                    } catch (Exception e) {
                        LOG.debug("Error setting historical field", e);
                    }
                    try {
                        cdNow.setSunshineHours(SafeParse.parseDouble(data[6]));
                    } catch (Exception e) {
                        LOG.debug("Error setting historical field", e);
                    }
                    WritableClimateObservation obs9 = ClimateDataFactory.newWritableClimateObservation(this,
                            getSource());
                    WritableClimateObservation obs15 = ClimateDataFactory.newWritableClimateObservation(this,
                            getSource());
                    obs9.setTime(DateUtils.setHours(date, 9));
                    obs15.setTime(DateUtils.setHours(date, 15));
                    int count = 0;
                    try {
                        obs9.setTemperature(SafeParse.parseDouble(data[10]));
                        ++count;
                    } catch (Exception e) {
                        LOG.debug("Error setting historical field", e);
                    }
                    try {
                        obs9.setHumidity(SafeParse.parseDouble(data[11]));
                        ++count;
                    } catch (Exception e) {
                        LOG.debug("Error setting historical field", e);
                    }
                    try {
                        obs9.setWindSpeed(SafeParse.parseDouble(data[14]));
                        obs9.setWindDirection(data[13]);
                        obs9.setWindSpeedHeight(10.0);

                        ++count;
                    } catch (Exception e) {
                        LOG.debug("Error setting historical field", e);
                    }
                    if (count > 0) {
                        cdNow.addObservation(obs9);
                    }
                    count = 0;
                    try {
                        obs15.setTemperature(SafeParse.parseDouble(data[16]));
                        ++count;
                    } catch (Exception e) {
                        LOG.debug("Error setting historical field", e);
                    }
                    try {
                        obs15.setHumidity(SafeParse.parseDouble(data[17]));
                        ++count;
                    } catch (Exception e) {
                        LOG.debug("Error setting historical field", e);
                    }
                    try {
                        obs15.setWindSpeed(SafeParse.parseDouble(data[20]));
                        obs15.setWindSpeedHeight(10.0);
                        obs15.setWindDirection(data[19]);
                        ++count;
                    } catch (Exception e) {
                        LOG.debug("Error setting historical field", e);
                    }
                    if (count > 0) {
                        cdNow.addObservation(obs15);
                    }
                } catch (ParseException e) {
                    LOG.error("Unable to parse date for historical record [" + getSource().toString() + "] - "
                            + Arrays.toString(data), e);
                }
            } else {
                if (data.length > 1 && data[1].contains("Date")) {
                    pastHeader = true;
                }
            }
        }
    } catch (IOException e) {
        LOG.error("Unable to load DAILY_OBSERVATION Data [" + getSource().toString() + "]", e);
    }
}

From source file:gov.nih.nci.migration.MigrationDriver.java

private void encryptDecryptUserInformation() throws EncryptionException, SQLException {
    Connection connection = getConnection();
    //Statement stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
    Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
    connection.setAutoCommit(false);//w w  w .j a v  a2  s . c om
    ResultSet resultSet = null;
    if ("oracle".equals(DATABASE_TYPE)) {
        //resultSet = stmt.executeQuery("SELECT CSM_USER.* FROM CSM_USER FOR UPDATE");
        resultSet = stmt.executeQuery("SELECT CSM_USER.* FROM CSM_USER");
    } else {
        resultSet = stmt.executeQuery("SELECT * FROM CSM_USER");
    }
    String userPassword = null;
    String firstName = null;
    String lastName = null;
    String organization = null;
    String department = null;
    String title = null;
    String phoneNumber = null;
    String emailId = null;
    String encryptedUserPassword = null;
    Date expiryDate = null;

    while (resultSet.next()) {
        userPassword = resultSet.getString("PASSWORD");
        firstName = resultSet.getString("FIRST_NAME");
        lastName = resultSet.getString("LAST_NAME");
        organization = resultSet.getString("ORGANIZATION");
        department = resultSet.getString("DEPARTMENT");
        title = resultSet.getString("TITLE");
        phoneNumber = resultSet.getString("PHONE_NUMBER");
        emailId = resultSet.getString("EMAIL_ID");

        if (!StringUtilities.isBlank(userPassword)) {
            String orgPasswordStr = desEncryption.decrypt(userPassword);
            encryptedUserPassword = aesEncryption.encrypt(orgPasswordStr);
            if (!StringUtilities.isBlank(encryptedUserPassword)) {
                resultSet.updateString("PASSWORD", encryptedUserPassword);
            }
        }
        if (!StringUtilities.isBlank(firstName))
            resultSet.updateString("FIRST_NAME", aesEncryption.encrypt(firstName));
        if (!StringUtilities.isBlank(lastName))
            resultSet.updateString("LAST_NAME", aesEncryption.encrypt(lastName));
        if (!StringUtilities.isBlank(organization))
            resultSet.updateString("ORGANIZATION", aesEncryption.encrypt(organization));
        if (!StringUtilities.isBlank(department))
            resultSet.updateString("DEPARTMENT", aesEncryption.encrypt(department));
        if (!StringUtilities.isBlank(title))
            resultSet.updateString("TITLE", aesEncryption.encrypt(title));
        if (!StringUtilities.isBlank(phoneNumber))
            resultSet.updateString("PHONE_NUMBER", aesEncryption.encrypt(phoneNumber));
        if (!StringUtilities.isBlank(emailId))
            resultSet.updateString("EMAIL_ID", aesEncryption.encrypt(emailId));

        expiryDate = DateUtils.addDays(Calendar.getInstance().getTime(), Integer.parseInt(getExpiryDays()));
        resultSet.updateDate("PASSWORD_EXPIRY_DATE", new java.sql.Date(expiryDate.getTime()));
        System.out.println("Updating user:" + resultSet.getString("LOGIN_NAME"));
        resultSet.updateRow();
    }
    connection.commit();
}

From source file:net.audumla.scheduler.quartz.SunScheduleTest.java

@Test
public void testStartAndEndEvent() throws Exception {
    AstronomicEvent startEvent = getSunRiseEvent();
    AstronomicEvent endEvent = getSunRiseEvent();
    Date now = new Date();
    if (startEvent.getCalculatedEventTime().before(now)) {
        now = DateUtils.addDays(now, 1);
    }//from   ww w .  ja  v  a2 s  . com
    AstronomicTriggerImpl trigger = (AstronomicTriggerImpl) AstronomicScheduleBuilder.astronomicalSchedule()
            .startEvent(startEvent).startEventOffset(-3).endEvent(endEvent).forEveryEvent()
            .withIntervalInSeconds(1).repeatForever().build();
    trigger.computeFirstFireTime(null);
    Date fire = trigger.getNextFireTime();
    assert DateUtils.isSameDay(fire, now);
    Assert.assertEquals(trigger.getNextFireTime().getTime(), fire.getTime());
    trigger.triggered(null);
    Assert.assertEquals(trigger.getNextFireTime().getTime(), fire.getTime() + 1000);
    trigger.triggered(null);
    Assert.assertEquals(trigger.getNextFireTime().getTime(), fire.getTime() + 2000);
    trigger.triggered(null);
    if (DateUtils.isSameDay(trigger.getNextFireTime(), fire)) {
        Assert.assertEquals(trigger.getNextFireTime().getTime(), fire.getTime() + 3000);
        trigger.triggered(null);
    }
    fire = trigger.getNextFireTime();
    assert DateUtils.isSameDay(fire, DateUtils.addDays(now, 1));
    Assert.assertEquals(trigger.getNextFireTime().getTime(), fire.getTime(), 10);
    trigger.triggered(null);
    Assert.assertEquals(trigger.getNextFireTime().getTime(), fire.getTime() + 1000, 10);
}

From source file:de.hybris.platform.b2b.services.impl.DefaultB2BOrderServiceTest.java

@Test
public void testOrderComment() throws Exception {
    final OrderModel order = createOrder(1);

    final B2BCommentModel b2BCommentModel = modelService.create(B2BCommentModel.class);
    b2BCommentModel.setCode("QuoteRequest");
    b2BCommentModel.setComment("Requesting 5% discount.");
    b2BCommentModel.setModifiedDate(new Date());

    final Date modifiedDate = DateUtils.addDays(b2BCommentModel.getModifiedDate(), 10);
    order.setQuoteExpirationDate(modifiedDate);
    order.setB2bcomments(Collections.singletonList(b2BCommentModel));
    modelService.save(order);// w w w .j  a v a  2  s  .  c om

    final OrderModel retrievedOrder = b2bOrderService.getOrderForCode(order.getCode());
    final List<B2BCommentModel> retrievedComments = (List<B2BCommentModel>) retrievedOrder.getB2bcomments();

    Assert.assertNotNull(CollectionUtils.find(retrievedComments,
            new BeanPropertyValueEqualsPredicate(B2BCommentModel.CODE, "QuoteRequest")));

    Assert.assertTrue(order.getQuoteExpirationDate().equals(modifiedDate));
}

From source file:de.hybris.platform.b2bacceleratorfacades.order.impl.DefaultB2BCheckoutFacadeIntegrationTest.java

@Test
public void testScheduleOrder() throws Exception {
    Assert.assertNotNull("cart not null", cartService.getSessionCart());
    Assert.assertNotNull("user not null", cartService.getSessionCart().getUser());
    Assert.assertEquals("DC S HH", cartService.getSessionCart().getUser().getUid());
    final TriggerData triggerData = new TriggerData();
    triggerData.setDay(Integer.valueOf(1));
    triggerData.setActivationTime(DateUtils.addDays(new Date(), 1));
    triggerData.setRelative(Boolean.TRUE);
    triggerData.setDaysOfWeek(Collections.singletonList(DayOfWeek.FRIDAY));
    triggerData.setMonth(Integer.valueOf(1));
    triggerData.setWeekInterval(Integer.valueOf(1));
    final ScheduledCartData scheduledCartData = b2bCheckoutFacade.scheduleOrder(triggerData);
    Assert.assertNotNull(scheduledCartData);

    // scheduleOrder method triggers a replenishmentOrderPlacedEmailProcess we want to try and wait for it to complete otherwise
    // the hybris test framwork will start removing items created during the test and the Process will encounter de.hybris.platform.servicelayer.exceptions.ModelSavingException: Entity not found
    TestUtils.disableFileAnalyzer("GenerateEmailAction logs ERROR when content catalog can't be found");
    waitForProcessToEnd("replenishmentOrderPlacedEmailProcess", 2000);
    TestUtils.enableFileAnalyzer();/*from  w  w w. j  a va 2s  .  c o  m*/
}

From source file:com.runwaysdk.business.email.EmailKey.java

/**
 * Checks if this EmailKey is valid by comparing the value
 * of the issue date with the given date. If the difference
 * between those two dates is greater than the number of days
 * specified by the value of keyExpire in email.properties then
 * the EmailKey is invalid. If this EmailKey is invalid, it is up
 * to the developer to delete it and re-issue a new one.
 * // ww  w  .ja v a2s. c o m
 * @return
 */
public boolean isDateValid(Date date) {
    Date issued = getIssuedOnDate();
    int expireDays = EmailProperties.getKeyExpire();
    Date expireDate = DateUtils.addDays(issued, expireDays);

    return date.before(expireDate);
}

From source file:com.ikanow.aleph2.core.shared.utils.TimeSliceDirUtils.java

/** Low level util because java8 time "plus" is odd
 * @param to_adjust/*  w  w  w .  j av a 2  s .  c  om*/
 * @param increment
 * @return
 */
private static Date adjustTime(Date to_adjust, ChronoUnit increment) {
    return Patterns.match(increment).<Date>andReturn()
            .when(t -> t == ChronoUnit.SECONDS, __ -> DateUtils.addSeconds(to_adjust, 1))
            .when(t -> t == ChronoUnit.MINUTES, __ -> DateUtils.addMinutes(to_adjust, 1))
            .when(t -> t == ChronoUnit.HOURS, __ -> DateUtils.addHours(to_adjust, 1))
            .when(t -> t == ChronoUnit.DAYS, __ -> DateUtils.addDays(to_adjust, 1))
            .when(t -> t == ChronoUnit.WEEKS, __ -> DateUtils.addWeeks(to_adjust, 1))
            .when(t -> t == ChronoUnit.MONTHS, __ -> DateUtils.addMonths(to_adjust, 1))
            .when(t -> t == ChronoUnit.YEARS, __ -> DateUtils.addYears(to_adjust, 1)).otherwiseAssert();
}

From source file:com.exxonmobile.ace.hybris.core.btg.OrganizationOrdersReportingJob.java

private List<OrganizationOrderStatisticsModel> getOrganizationOrderStatistics(final B2BUnitModel unit,
        final CurrencyModel currency, Date today, final String category) {
    String queryString = " select {stats:pk} from {OrganizationOrderStatistics as stats}   "
            + " where {stats:currency} = ?currency and {stats:unit} = ?unit                      "
            + " and {stats:date} >= ?today and {stats:date} < ?tomorrow                    ";
    if (StringUtils.isNotEmpty(category)) {
        queryString += " and {category} = ?category";
    }//from  w w  w  . j a v  a 2s .  co  m

    today = DateUtils.setHours(today, 0);
    today = DateUtils.setMinutes(today, 0);
    today = DateUtils.setSeconds(today, 0);
    Date tomorrow = DateUtils.addDays(today, 1);
    tomorrow = DateUtils.setHours(tomorrow, 0);
    tomorrow = DateUtils.setMinutes(tomorrow, 0);
    tomorrow = DateUtils.setSeconds(tomorrow, 0);

    final Map<String, Object> attr = new HashMap<String, Object>(4);
    attr.put(OrderModel.CURRENCY, currency);
    attr.put("unit", unit);
    attr.put("today", today);
    attr.put("tomorrow", tomorrow);
    attr.put("category", category);

    final FlexibleSearchQuery query = new FlexibleSearchQuery(queryString);
    query.getQueryParameters().putAll(attr);
    final SearchResult<OrganizationOrderStatisticsModel> searchResult = flexibleSearchService.search(query);
    return searchResult.getResult();

}