Example usage for org.joda.time DateTime minusDays

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

Introduction

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

Prototype

public DateTime minusDays(int days) 

Source Link

Document

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

Usage

From source file:com.marand.thinkmed.medications.therapy.impl.TherapyUpdaterImpl.java

License:Open Source License

@Override
@EventProducer(ReissueTherapy.class)
public void reissueTherapy(final String patientId, final String compositionUid, final String ehrOrderName,
        final DateTime when) {
    final MedicationOrderComposition composition = medicationsOpenEhrDao
            .loadMedicationOrderComposition(patientId, compositionUid);

    final NamedExternalDto user = RequestContextHolder.getContext().getUserMetadata()
            .map(meta -> new NamedExternalDto(meta.getId(), meta.getFullName())).get();
    MedicationsEhrUtils.addMedicationActionTo(composition, MedicationActionEnum.REISSUE, user, when);

    medicationsOpenEhrDao.modifyMedicationOrderComposition(patientId, composition);

    final DateTime lastTaskTimestamp = medicationsTasksProvider.findLastAdministrationTaskTimeForTherapy(
            patientId, TherapyIdUtils.createTherapyId(compositionUid, ehrOrderName),
            Intervals.infiniteFrom(when.minusDays(30)), true).orElse(when);

    createTherapyTasks(patientId,/*from  w  w  w .jav a  2 s  . com*/
            medicationsOpenEhrDao.getTherapyInstructionPair(patientId, compositionUid, ehrOrderName).getFirst(),
            AdministrationTaskCreateActionEnum.REISSUE, lastTaskTimestamp, when);
}

From source file:com.marklogic.samplestack.dbclient.DateFacetBuilder.java

License:Apache License

public static ObjectNode dateFacet(DateTime min, DateTime max) {
    DateFacetBuilder fb = new DateFacetBuilder(new CustomObjectMapper());
    fb.name("date");
    /*//from   w  w  w. j a  v a2  s .c  om
    long interval = max.getMillis() - min.getMillis();
    if (interval / BucketInterval.BY_DAY.bucketDuration() < 40) {
       fb.period("DAY");
       DateTime bucketStart = min.minus(min.getMillisOfDay());
       while (bucketStart.isBefore(max)) {
    DateTime bucketEnd = bucketStart.plusDays(1);
    fb.bucket(bucketStart, bucketEnd);
    bucketStart = bucketStart.plusDays(1);
       }
    }
    else if (interval / BucketInterval.BY_WEEK.bucketDuration() < 40) {
       fb.period("WEEK");
       DateTime bucketStart = min.minusDays(min.getDayOfWeek()).minus(min.getMillisOfDay());
       while (bucketStart.isBefore(max)) {
    DateTime bucketEnd = bucketStart.plusWeeks(1);
    fb.bucket(bucketStart, bucketEnd);
    bucketStart = bucketStart.plusWeeks(1);
       }
    } else {
    */
    // for 8.0-1 we are only doing facets by month
    fb.period("MONTH");
    DateTime bucketStart = min.minusDays(min.getDayOfMonth() - 1).minus(min.getMillisOfDay());
    bucketStart = new DateTime(bucketStart);
    while (bucketStart.isBefore(max)) {
        DateTime bucketEnd = bucketStart.plusMonths(1);
        fb.bucket(bucketStart, bucketEnd);
        bucketStart = bucketStart.plusMonths(1);
    }
    // }
    return fb.facetNode;
}

From source file:com.mobiaware.auction.event.AuctionResource.java

License:Apache License

@GET
@Path("/{auction}/stop")
public Auction stopAuction(@PathParam("auction") final int auctionUid) {
    Auction auction = _dataService.getAuction(auctionUid);

    if (auction == null) {
        throw new NotFoundException();
    }/*from   ww w.  j  ava 2s . c  o m*/

    DateTime today = new DateTime();
    DateTime yesterday = today.minusDays(1); // -1 days

    auction = auction.toBuilder().setStartDate(today.getMillis()).setEndDate(yesterday.getMillis()).build();

    int uid = _dataService.editAuction(auction);

    if (uid < 0) {
        throw new InternalServerErrorException();
    }

    return auction;
}

From source file:com.money.manager.ex.servicelayer.RecurringTransactionService.java

License:Open Source License

/**
 * @param date    to start calculate/*  ww w  .  j a  v  a  2  s.  c  o  m*/
 * @param repeatType type of repeating transactions
 * @param numberOfPeriods Number of instances (days, months) parameter. Used for In (x) Days, for
 *                  example to indicate x.
 * @return next Date
 */
public DateTime getNextScheduledDate(DateTime date, Recurrence repeatType, Integer numberOfPeriods) {
    if (numberOfPeriods == null || numberOfPeriods == Constants.NOT_SET) {
        numberOfPeriods = 0;
    }

    if (repeatType.getValue() >= 200) {
        repeatType = Recurrence.valueOf(repeatType.getValue() - 200);
    } // set auto execute without user acknowledgement
    if (repeatType.getValue() >= 100) {
        repeatType = Recurrence.valueOf(repeatType.getValue() - 100);
    } // set auto execute on the next occurrence

    DateTime result = new DateTime(date);

    switch (repeatType) {
    case ONCE: //none
        break;
    case WEEKLY: //weekly
        result = result.plusWeeks(1);
        break;
    case BIWEEKLY: //bi_weekly
        result = result.plusWeeks(2);
        break;
    case MONTHLY: //monthly
        result = result.plusMonths(1);
        break;
    case BIMONTHLY: //bi_monthly
        result = result.plusMonths(2);
        break;
    case QUARTERLY: //quarterly
        result = result.plusMonths(3);
        break;
    case SEMIANNUALLY: //half_year
        result = result.plusMonths(6);
        break;
    case ANNUALLY: //yearly
        result = result.plusYears(1);
        break;
    case FOUR_MONTHS: //four_months
        result = result.plusMonths(4);
        break;
    case FOUR_WEEKS: //four_weeks
        result = result.plusWeeks(4);
        break;
    case DAILY: //daily
        result = result.plusDays(1);
        break;
    case IN_X_DAYS: //in_x_days
    case EVERY_X_DAYS: //every_x_days
        result = result.plusDays(numberOfPeriods);
        break;
    case IN_X_MONTHS: //in_x_months
    case EVERY_X_MONTHS: //every_x_months
        result = result.plusMonths(numberOfPeriods);
        break;
    case MONTHLY_LAST_DAY: //month (last day)
        // if the date is not the last day of this month, set it to the end of the month.
        // else set it to the end of the next month.
        DateTime lastDayOfMonth = MmxDateTimeUtils.getLastDayOfMonth(result);
        if (!result.equals(lastDayOfMonth)) {
            // set to last day of the month
            result = lastDayOfMonth;
        } else {
            result = lastDayOfMonth.plusMonths(1);
        }
        break;

    case MONTHLY_LAST_BUSINESS_DAY: //month (last business day)
        // if the date is not the last day of this month, set it to the end of the month.
        // else set it to the end of the next month.
        DateTime lastDayOfMonth2 = MmxDateTimeUtils.getLastDayOfMonth(result);
        if (!result.equals(lastDayOfMonth2)) {
            // set to last day of the month
            result = lastDayOfMonth2;
        } else {
            result = lastDayOfMonth2.plusMonths(1);
        }
        // get the last day of the next month,
        // then iterate backwards until we are on a weekday.
        while (result.getDayOfWeek() == DateTimeConstants.SATURDAY
                || result.getDayOfWeek() == DateTimeConstants.SUNDAY) {
            result = result.minusDays(1);
        }
        break;
    }
    return result;
}

From source file:com.music.scheduled.FeedGenerator.java

License:Open Source License

@Scheduled(cron = "0 0 0 * * ?") //every midnight
@Transactional/*from w  w w . j  av a2s .  c o m*/
public void generateFeed() {
    logger.info("Generating feed");
    DateTime now = new DateTime();
    DateTime oneDayAgo = now.minusDays(1);
    List<Piece> pieces = dao.getPiecesInRange(oneDayAgo, now);
    Collections.shuffle(pieces);
    logger.info("Found " + pieces.size() + " eligible pieces");
    int persisted = 0;
    for (Piece piece : pieces) {
        if (piece.getLikes() < 3 && piece.getLikes() > -3) {
            FeedEntry entry = new FeedEntry();
            entry.setInclusionTime(now);
            entry.setPiece(piece);
            dao.persist(entry);
            persisted++;
        }
        if (persisted == 2) {
            break;
        }
    }
    logger.info("Inserted " + persisted + " entries into the feed");
}

From source file:com.music.scheduled.PieceDigestSendingJob.java

License:Open Source License

@Scheduled(cron = "0 0 9 ? * 1,4")
@Transactional(readOnly = true)/*from w  ww  .ja  v a  2 s  .c o m*/
public void sendPieceDigestEmails() {
    logger.info("Sending email digests started");
    DateTime now = new DateTime();
    DateTime minusTwoDays = now.minusDays(2);
    List<Piece> pieces = pieceDao.getPiecesInRange(minusTwoDays, now);
    Collections.shuffle(pieces);
    final List<Piece> includedPieces = new ArrayList<>(pieces.subList(0, Math.min(pieces.size(), 3)));
    if (includedPieces.isEmpty()) {
        return;
    }
    // for now - using the same data for all users. TODO send personalized selection
    final EmailDetails baseDetails = new EmailDetails();
    baseDetails.setMessageTemplate("digest.vm");
    baseDetails.setSubject("Computoser-generated tracks digest for you");
    Map<String, Object> model = Maps.newHashMap();
    baseDetails.setMessageTemplateModel(model);
    baseDetails.setFrom(from);
    baseDetails.setHtml(true);
    userDao.performBatched(User.class, 100, new PageableOperation<User>() {
        @Override
        public void execute() {
            for (User user : getData()) {
                if (user.isReceiveDailyDigest() && StringUtils.isNotBlank(user.getEmail())) {
                    EmailDetails email = SerializationUtils.clone(baseDetails);
                    email.setTo(user.getEmail());
                    email.setCurrentUser(user);
                    String hmac = SecurityUtils.hmac(user.getEmail(), hmacKey);
                    email.getMessageTemplateModel().put("pieces", includedPieces);
                    email.getMessageTemplateModel().put("hmac", hmac);
                    // needed due to SES restrictions
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        throw new IllegalStateException(e);
                    }
                    emailService.send(email);
                }
            }
        }
    });
}

From source file:com.music.service.PieceService.java

License:Open Source License

@Cacheable(value = "rssCache")
public List<Piece> getRssFeed() {
    DateTime now = new DateTime();
    DateTime tenDaysAgo = now.minusDays(10);
    return dao.getFeedEntryPiecesInRange(tenDaysAgo, now);
}

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 ww w  .j  a va  2s.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.netflix.raigad.indexmanagement.IndexUtils.java

License:Apache License

public static int getPastRetentionCutoffDate(IndexMetadata indexMetadata) throws UnsupportedAutoIndexException {

    DateTime dt = new DateTime();
    int currentDate;

    switch (indexMetadata.getRetentionType()) {
    case DAILY://  w ww.  j ava 2s  . co m
        dt = dt.minusDays(indexMetadata.getRetentionPeriod());
        currentDate = Integer
                .parseInt(String.format("%d%02d%02d", dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth()));
        break;
    case MONTHLY:
        dt = dt.minusMonths(indexMetadata.getRetentionPeriod());
        currentDate = Integer.parseInt(String.format("%d%02d", dt.getYear(), dt.getMonthOfYear()));
        break;
    case YEARLY:
        dt = dt.minusYears(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.ning.billing.util.clock.DefaultClock.java

License:Apache License

public static DateTime addOrRemoveDuration(final DateTime input, final List<Duration> durations,
        final boolean add) {
    DateTime result = input;
    for (final Duration cur : durations) {
        switch (cur.getUnit()) {
        case DAYS:
            result = add ? result.plusDays(cur.getNumber()) : result.minusDays(cur.getNumber());
            break;

        case MONTHS:
            result = add ? result.plusMonths(cur.getNumber()) : result.minusMonths(cur.getNumber());
            break;

        case YEARS:
            result = add ? result.plusYears(cur.getNumber()) : result.minusYears(cur.getNumber());
            break;
        case UNLIMITED:
        default:/*from w w w. ja v  a  2 s  .c om*/
            throw new RuntimeException("Trying to move to unlimited time period");
        }
    }
    return result;
}