Example usage for org.joda.time DateTime plusDays

List of usage examples for org.joda.time DateTime plusDays

Introduction

In this page you can find the example usage for org.joda.time DateTime plusDays.

Prototype

public DateTime plusDays(int days) 

Source Link

Document

Returns a copy of this datetime plus the specified number of days.

Usage

From source file:com.mycollab.common.service.impl.TimelineTrackingServiceImpl.java

License:Open Source License

@Override
public Map<String, List<GroupItem>> findTimelineItems(String fieldGroup, List<String> groupVals, Date start,
        Date end, TimelineTrackingSearchCriteria criteria) {
    try {/*from   w  ww  .  ja v  a2 s  .  co m*/
        DateTime startDate = new DateTime(start);
        final DateTime endDate = new DateTime(end);
        if (startDate.isAfter(endDate)) {
            throw new UserInvalidInputException("Start date must be greaterThan than end date");
        }
        List<Date> dates = boundDays(startDate, endDate.minusDays(1));
        Map<String, List<GroupItem>> items = new HashMap<>();
        criteria.setFieldgroup(StringSearchField.and(fieldGroup));
        List<GroupItem> cacheTimelineItems = timelineTrackingCachingMapperExt.findTimelineItems(groupVals,
                dates, criteria);

        DateTime calculatedDate = startDate.toDateTime();
        if (cacheTimelineItems.size() > 0) {
            GroupItem item = cacheTimelineItems.get(cacheTimelineItems.size() - 1);
            String dateValue = item.getGroupname();
            calculatedDate = DateTime.parse(dateValue, DateTimeFormat.forPattern("yyyy-MM-dd"));

            for (GroupItem map : cacheTimelineItems) {
                String groupVal = map.getGroupid();
                Object obj = items.get(groupVal);
                if (obj == null) {
                    List<GroupItem> itemLst = new ArrayList<>();
                    itemLst.add(map);
                    items.put(groupVal, itemLst);
                } else {
                    List<GroupItem> itemLst = (List<GroupItem>) obj;
                    itemLst.add(map);
                }
            }
        }

        dates = boundDays(calculatedDate.plusDays(1), endDate);
        if (dates.size() > 0) {
            boolean isValidForBatchSave = true;
            final Set<String> types = criteria.getTypes().getValues();
            SetSearchField<Integer> extraTypeIds = criteria.getExtraTypeIds();
            Integer tmpExtraTypeId = null;
            if (extraTypeIds != null) {
                if (extraTypeIds.getValues().size() == 1) {
                    tmpExtraTypeId = extraTypeIds.getValues().iterator().next();
                } else {
                    isValidForBatchSave = false;
                }
            }
            final Integer extraTypeId = tmpExtraTypeId;

            final List<Map> timelineItems = timelineTrackingMapperExt.findTimelineItems(groupVals, dates,
                    criteria);
            if (isValidForBatchSave) {
                final Integer sAccountId = (Integer) criteria.getSaccountid().getValue();
                final String itemFieldGroup = criteria.getFieldgroup().getValue();
                JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

                final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
                final List<Map> filterCollections = new ArrayList<>(
                        Collections2.filter(timelineItems, input -> {
                            String dateStr = (String) input.get("groupname");
                            DateTime dt = formatter.parseDateTime(dateStr);
                            return !dt.equals(endDate);
                        }));
                jdbcTemplate.batchUpdate(
                        "INSERT INTO `s_timeline_tracking_cache`(type, fieldval,extratypeid,sAccountId,"
                                + "forDay, fieldgroup,count) VALUES(?,?,?,?,?,?,?)",
                        new BatchPreparedStatementSetter() {
                            @Override
                            public void setValues(PreparedStatement preparedStatement, int i)
                                    throws SQLException {
                                Map item = filterCollections.get(i);
                                //                            preparedStatement.setString(1, types);
                                String fieldVal = (String) item.get("groupid");
                                preparedStatement.setString(2, fieldVal);
                                preparedStatement.setInt(3, extraTypeId);
                                preparedStatement.setInt(4, sAccountId);
                                String dateStr = (String) item.get("groupname");
                                DateTime dt = formatter.parseDateTime(dateStr);
                                preparedStatement.setDate(5, new java.sql.Date(dt.toDate().getTime()));
                                preparedStatement.setString(6, itemFieldGroup);
                                int value = ((BigDecimal) item.get("value")).intValue();
                                preparedStatement.setInt(7, value);
                            }

                            @Override
                            public int getBatchSize() {
                                return filterCollections.size();
                            }
                        });
            }

            for (Map map : timelineItems) {
                String groupVal = (String) map.get("groupid");
                GroupItem item = new GroupItem();
                item.setValue(((BigDecimal) map.get("value")).doubleValue());
                item.setGroupid((String) map.get("groupid"));
                item.setGroupname((String) map.get("groupname"));
                Object obj = items.get(groupVal);
                if (obj == null) {
                    List<GroupItem> itemLst = new ArrayList<>();
                    itemLst.add(item);
                    items.put(groupVal, itemLst);
                } else {
                    List<GroupItem> itemLst = (List<GroupItem>) obj;
                    itemLst.add(item);
                }
            }
        }

        return items;
    } catch (Exception e) {
        LOG.error("Error", e);
        return null;
    }
}

From source file:com.mycollab.core.utils.DateTimeUtils.java

License:Open Source License

/**
 * @param date//  w  ww.j a va 2  s  . c o  m
 * @param duration Example: Date date = subtractOrAddDayDuration(new Date(), -2);
 *                 // Result: the last 2 days
 *
 *                 Date date = subtractOrAddDayDuration(new Date(), 2); //
 *                 Result: the next 2 days
 * @return
 */
public static Date subtractOrAddDayDuration(Date date, int duration) {
    DateTime localDate = new DateTime(date);
    return localDate.plusDays(duration).toDate();
}

From source file:com.netflix.raigad.indexmanagement.ElasticSearchIndexManager.java

License:Apache License

/**
 * Courtesy Jae Bae//from  ww w. j a  v  a2  s.c  o  m
 */
public void preCreateIndex(IndexMetadata indexMetadata, Client esTransportClient)
        throws UnsupportedAutoIndexException {
    logger.info("Running PreCreate Index task");
    IndicesStatusResponse getIndicesResponse = getIndicesStatusResponse(esTransportClient);
    Map<String, IndexStatus> indexStatusMap = getIndicesResponse.getIndices();
    if (!indexStatusMap.isEmpty()) {
        for (String indexNameWithDateSuffix : indexStatusMap.keySet()) {
            if (config.isDebugEnabled())
                logger.debug("Index Name = <" + indexNameWithDateSuffix + ">");
            if (indexMetadata.getIndexNameFilter().filter(indexNameWithDateSuffix)
                    && indexMetadata.getIndexNameFilter().getNamePart(indexNameWithDateSuffix)
                            .equalsIgnoreCase(indexMetadata.getIndexName())) {

                for (int i = 0; i < indexMetadata.getRetentionPeriod(); ++i) {

                    DateTime dt = new DateTime();
                    int addedDate;

                    switch (indexMetadata.getRetentionType()) {
                    case DAILY:
                        dt = dt.plusDays(i);
                        addedDate = Integer.parseInt(String.format("%d%02d%02d", dt.getYear(),
                                dt.getMonthOfYear(), dt.getDayOfMonth()));
                        break;
                    case MONTHLY:
                        dt = dt.plusMonths(i);
                        addedDate = Integer
                                .parseInt(String.format("%d%02d", dt.getYear(), dt.getMonthOfYear()));
                        break;
                    case YEARLY:
                        dt = dt.plusYears(i);
                        addedDate = Integer.parseInt(String.format("%d", dt.getYear()));
                        break;
                    default:
                        throw new UnsupportedAutoIndexException(
                                "Given index is not (DAILY or MONTHLY or YEARLY), please check your configuration.");

                    }

                    if (config.isDebugEnabled())
                        logger.debug("Added Date = " + addedDate);
                    if (!esTransportClient.admin().indices()
                            .prepareExists(indexMetadata.getIndexName() + addedDate).execute()
                            .actionGet(config.getAutoCreateIndexTimeout()).isExists()) {
                        esTransportClient.admin().indices()
                                .prepareCreate(indexMetadata.getIndexName() + addedDate).execute()
                                .actionGet(config.getAutoCreateIndexTimeout());
                        logger.info(indexMetadata.getIndexName() + addedDate + " is created");
                    } else {
                        //TODO: Change to Debug after Testing
                        logger.warn(indexMetadata.getIndexName() + addedDate + " already exists");
                    }
                }
            }
        }
    } else {
        logger.info("No existing indices, hence can not pre-create any indices");
    }
}

From source file:com.netflix.raigad.indexmanagement.IndexUtils.java

License:Apache License

public static int getFutureRetentionDate(IndexMetadata indexMetadata) throws UnsupportedAutoIndexException {

    DateTime dt = new DateTime();
    int currentDate;

    switch (indexMetadata.getRetentionType()) {
    case DAILY:/*from  w  w  w  . java  2s. co  m*/
        dt = dt.plusDays(indexMetadata.getRetentionPeriod());
        currentDate = Integer
                .parseInt(String.format("%d%02d%02d", dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth()));
        break;
    case MONTHLY:
        dt = dt.plusMonths(indexMetadata.getRetentionPeriod());
        currentDate = Integer.parseInt(String.format("%d%02d", dt.getYear(), dt.getMonthOfYear()));
        break;
    case YEARLY:
        dt = dt.plusYears(indexMetadata.getRetentionPeriod());
        currentDate = Integer.parseInt(String.format("%d", dt.getYear()));
        break;
    default:
        throw new UnsupportedAutoIndexException(
                "Given index is not (DAILY or MONTHLY or YEARLY), please check your configuration.");

    }
    return currentDate;
}

From source file:com.netflix.simianarmy.aws.janitor.rule.asg.OldEmptyASGRule.java

License:Apache License

/** {@inheritDoc} */
@Override//from w w  w.  j av  a  2s  . c o  m
public boolean isValid(Resource resource) {
    Validate.notNull(resource);
    if (!"ASG".equals(resource.getResourceType().name())) {
        return true;
    }

    if (StringUtils.isNotEmpty(resource.getAdditionalField(ASGJanitorCrawler.ASG_FIELD_ELBS))) {
        LOGGER.info(String.format("ASG %s has ELBs.", resource.getId()));
        return true;
    }

    if (instanceValidator.hasActiveInstance(resource)) {
        LOGGER.info(String.format("ASG %s has active instance.", resource.getId()));
        return true;
    }

    String lcName = resource.getAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_NAME);
    DateTime now = new DateTime(calendar.now().getTimeInMillis());
    if (StringUtils.isEmpty(lcName)) {
        LOGGER.error(String.format("Failed to find launch configuration for ASG %s", resource.getId()));
        markResource(resource, now);
        return false;
    }

    String lcCreationTime = resource.getAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_CREATION_TIME);
    if (StringUtils.isEmpty(lcCreationTime)) {
        LOGGER.error(String.format("Failed to find creation time for launch configuration %s", lcName));
        return true;
    }

    DateTime createTime = new DateTime(Long.parseLong(lcCreationTime));
    if (now.isBefore(createTime.plusDays(launchConfigAgeThreshold))) {
        LOGGER.info(String.format("The launch configuration %s has not been created for more than %d days",
                lcName, launchConfigAgeThreshold));
        return true;
    }
    LOGGER.info(String.format("The launch configuration %s has been created for more than %d days", lcName,
            launchConfigAgeThreshold));

    if (lastChangeDaysThreshold != null) {
        String lastChangeTimeField = resource
                .getAdditionalField(EddaASGJanitorCrawler.ASG_FIELD_LAST_CHANGE_TIME);
        if (StringUtils.isNotBlank(lastChangeTimeField)) {
            DateTime lastChangeTime = new DateTime(Long.parseLong(lastChangeTimeField));
            if (lastChangeTime.plusDays(lastChangeDaysThreshold).isAfter(now)) {
                LOGGER.info(String.format("ASG %s had change during the last %d days", resource.getId(),
                        lastChangeDaysThreshold));
                return true;
            }
        }
    }

    markResource(resource, now);
    return false;
}

From source file:com.netflix.simianarmy.aws.janitor.rule.asg.SuspendedASGRule.java

License:Apache License

/** {@inheritDoc} */
@Override/*from  w  w w . j a  v a2  s .  c om*/
public boolean isValid(Resource resource) {
    Validate.notNull(resource);
    if (!"ASG".equals(resource.getResourceType().name())) {
        return true;
    }

    if (instanceValidator.hasActiveInstance(resource)) {
        return true;
    }

    String suspensionTimeStr = resource.getAdditionalField(ASGJanitorCrawler.ASG_FIELD_SUSPENSION_TIME);
    if (!StringUtils.isEmpty(suspensionTimeStr)) {
        DateTime createTime = ASGJanitorCrawler.SUSPENSION_TIME_FORMATTER.parseDateTime(suspensionTimeStr);
        DateTime now = new DateTime(calendar.now().getTimeInMillis());
        if (now.isBefore(createTime.plusDays(suspensionAgeThreshold))) {
            LOGGER.info(String.format("The ASG %s has not been suspended for more than %d days",
                    resource.getId(), suspensionAgeThreshold));
            return true;
        }
        LOGGER.info(String.format("The ASG %s has been suspended for more than %d days", resource.getId(),
                suspensionAgeThreshold));
        if (resource.getExpectedTerminationTime() == null) {
            Date terminationTime = calendar.getBusinessDay(new Date(now.getMillis()), retentionDays);
            resource.setExpectedTerminationTime(terminationTime);
            resource.setTerminationReason(String.format(
                    "User suspended age more than %d days and all instances are out of service in Discovery",
                    suspensionAgeThreshold + retentionDays));
        }
        return false;
    } else {
        LOGGER.info(String.format("ASG %s is not suspended from ELB.", resource.getId()));
        return true;
    }
}

From source file:com.netflix.simianarmy.aws.janitor.rule.instance.OrphanedInstanceRule.java

License:Apache License

@Override
public boolean isValid(Resource resource) {
    Validate.notNull(resource);//from  w w  w  .ja  v  a2  s  .  co  m
    if (!resource.getResourceType().name().equals("INSTANCE")) {
        // The rule is supposed to only work on AWS instances. If a non-instance resource
        // is passed to the rule, the rule simply ignores it and considers it as a valid
        // resource not for cleanup.
        return true;
    }
    String awsStatus = ((AWSResource) resource).getAWSResourceState();
    if (!"running".equals(awsStatus) || "pending".equals(awsStatus)) {
        return true;
    }
    AWSResource instanceResource = (AWSResource) resource;
    String asgName = instanceResource.getAdditionalField(InstanceJanitorCrawler.INSTANCE_FIELD_ASG_NAME);
    if (StringUtils.isEmpty(asgName)) {
        if (resource.getLaunchTime() == null) {
            LOGGER.error(String.format("The instance %s has no launch time.", resource.getId()));
            return true;
        } else {
            DateTime launchTime = new DateTime(resource.getLaunchTime().getTime());
            DateTime now = new DateTime(calendar.now().getTimeInMillis());
            if (now.isBefore(launchTime.plusDays(instanceAgeThreshold))) {
                LOGGER.info(String.format("The orphaned instance %s has not launched for more than %d days",
                        resource.getId(), instanceAgeThreshold));
                return true;
            }
            LOGGER.info(String.format("The orphaned instance %s has launched for more than %d days",
                    resource.getId(), instanceAgeThreshold));
            if (resource.getExpectedTerminationTime() == null) {
                int retentionDays = retentionDaysWithoutOwner;
                if (resource.getOwnerEmail() != null) {
                    retentionDays = retentionDaysWithOwner;
                }
                Date terminationTime = calendar.getBusinessDay(new Date(now.getMillis()), retentionDays);
                resource.setExpectedTerminationTime(terminationTime);
                resource.setTerminationReason(TERMINATION_REASON);
            }
            return false;
        }
    }
    return true;
}

From source file:com.netflix.simianarmy.aws.janitor.rule.launchconfig.OldUnusedLaunchConfigRule.java

License:Apache License

@Override
public boolean isValid(Resource resource) {
    Validate.notNull(resource);//from  www . j a  v  a2s. c  o  m
    if (!"LAUNCH_CONFIG".equals(resource.getResourceType().name())) {
        return true;
    }
    AWSResource lcResource = (AWSResource) resource;
    String usedByASG = lcResource
            .getAdditionalField(LaunchConfigJanitorCrawler.LAUNCH_CONFIG_FIELD_USED_BY_ASG);
    if (StringUtils.isNotEmpty(usedByASG) && !Boolean.parseBoolean(usedByASG)) {
        if (resource.getLaunchTime() == null) {
            LOGGER.error(String.format("The launch config %s has no creation time.", resource.getId()));
            return true;
        } else {
            DateTime launchTime = new DateTime(resource.getLaunchTime().getTime());
            DateTime now = new DateTime(calendar.now().getTimeInMillis());
            if (now.isBefore(launchTime.plusDays(ageThreshold))) {
                LOGGER.info(
                        String.format("The unused launch config %s has not been created for more than %d days",
                                resource.getId(), ageThreshold));
                return true;
            }
            LOGGER.info(String.format("The unused launch config %s has been created for more than %d days",
                    resource.getId(), ageThreshold));
            if (resource.getExpectedTerminationTime() == null) {
                Date terminationTime = calendar.getBusinessDay(new Date(now.getMillis()), retentionDays);
                resource.setExpectedTerminationTime(terminationTime);
                resource.setTerminationReason(TERMINATION_REASON);
            }
            return false;
        }
    }
    return true;
}

From source file:com.netflix.simianarmy.aws.janitor.rule.snapshot.NoGeneratedAMIRule.java

License:Apache License

@Override
public boolean isValid(Resource resource) {
    Validate.notNull(resource);/*www  .ja  v a2 s.c  o m*/
    if (!resource.getResourceType().name().equals("EBS_SNAPSHOT")) {
        return true;
    }
    if (!"completed".equals(((AWSResource) resource).getAWSResourceState())) {
        return true;
    }
    String janitorTag = resource.getTag(JanitorMonkey.JANITOR_TAG);
    if (janitorTag != null) {
        if ("donotmark".equals(janitorTag)) {
            LOGGER.info(String.format("The snapshot %s is tagged as not handled by Janitor", resource.getId()));
            return true;
        }
        try {
            // Owners can tag the volume with a termination date in the "janitor" tag.
            Date userSpecifiedDate = new Date(TERMINATION_DATE_FORMATTER.parseDateTime(janitorTag).getMillis());
            resource.setExpectedTerminationTime(userSpecifiedDate);
            resource.setTerminationReason(String.format("User specified termination date %s", janitorTag));
            return false;
        } catch (Exception e) {
            LOGGER.error(String.format("The janitor tag is not a user specified date: %s", janitorTag));
        }
    }

    if (hasGeneratedImage(resource)) {
        return true;
    }

    if (resource.getLaunchTime() == null) {
        LOGGER.error(String.format("Snapshot %s does not have a creation time.", resource.getId()));
        return true;
    }
    DateTime launchTime = new DateTime(resource.getLaunchTime().getTime());
    DateTime now = new DateTime(calendar.now().getTimeInMillis());
    if (launchTime.plusDays(ageThreshold).isBefore(now)) {
        if (resource.getExpectedTerminationTime() == null) {
            Date terminationTime = calendar.getBusinessDay(new Date(now.getMillis()), retentionDays);
            resource.setExpectedTerminationTime(terminationTime);
            resource.setTerminationReason(TERMINATION_REASON);
            LOGGER.info(String.format(
                    "Snapshot %s is marked to be cleaned at %s as there is no AMI generated using it",
                    resource.getId(), resource.getExpectedTerminationTime()));
        } else {
            LOGGER.info(String.format("Resource %s is already marked.", resource.getId()));
        }
        return false;
    }
    return true;

}

From source file:com.netflix.simianarmy.aws.janitor.rule.volume.OldDetachedVolumeRule.java

License:Apache License

@Override
public boolean isValid(Resource resource) {
    Validate.notNull(resource);/*from w w  w  . j  a  v  a 2 s  .c  o  m*/
    if (!resource.getResourceType().name().equals("EBS_VOLUME")) {
        return true;
    }
    if (!"available".equals(((AWSResource) resource).getAWSResourceState())) {
        return true;
    }
    String janitorTag = resource.getTag(JanitorMonkey.JANITOR_TAG);
    if (janitorTag != null) {
        if ("donotmark".equals(janitorTag)) {
            LOGGER.info(String.format("The volume %s is tagged as not handled by Janitor", resource.getId()));
            return true;
        }
        try {
            // Owners can tag the volume with a termination date in the "janitor" tag.
            Date userSpecifiedDate = new Date(TERMINATION_DATE_FORMATTER.parseDateTime(janitorTag).getMillis());
            resource.setExpectedTerminationTime(userSpecifiedDate);
            resource.setTerminationReason(String.format("User specified termination date %s", janitorTag));
            return false;
        } catch (Exception e) {
            LOGGER.error(String.format("The janitor tag is not a user specified date: %s", janitorTag));
        }
    }

    String janitorMetaTag = resource.getTag(JanitorMonkey.JANITOR_META_TAG);
    if (janitorMetaTag == null) {
        LOGGER.info(String.format("Volume %s is not tagged with the Janitor meta information, ignore.",
                resource.getId()));
        return true;
    }

    Map<String, String> metadata = VolumeTaggingMonkey.parseJanitorMetaTag(janitorMetaTag);
    String detachTimeTag = metadata.get(JanitorMonkey.DETACH_TIME_TAG_KEY);
    if (detachTimeTag == null) {
        return true;
    }
    DateTime detachTime = null;
    try {
        detachTime = AWSResource.DATE_FORMATTER.parseDateTime(detachTimeTag);
    } catch (Exception e) {
        LOGGER.error(String.format("Detach time in the JANITOR_META tag of %s is not in the valid format: %s",
                resource.getId(), detachTime));
        return true;
    }
    DateTime now = new DateTime(calendar.now().getTimeInMillis());
    if (detachTime != null && detachTime.plusDays(detachDaysThreshold).isBefore(now)) {
        if (resource.getExpectedTerminationTime() == null) {
            Date terminationTime = calendar.getBusinessDay(new Date(now.getMillis()), retentionDays);
            resource.setExpectedTerminationTime(terminationTime);
            resource.setTerminationReason(
                    String.format("Volume not attached for %d days", detachDaysThreshold + retentionDays));
            LOGGER.info(String.format(
                    "Volume %s is marked to be cleaned at %s as it is detached for more than %d days",
                    resource.getId(), resource.getExpectedTerminationTime(), detachDaysThreshold));
        } else {
            LOGGER.info(String.format("Resource %s is already marked.", resource.getId()));
        }
        return false;
    }
    return true;
}