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.marand.thinkmed.medications.pharmacist.impl.PharmacistTaskHandlerImpl.java

License:Open Source License

@Override
public void editSupplyReminderTask(final String taskId, final MedicationSupplyTypeEnum supplyTypeEnum,
        final Integer supplyInDays, final String comment, final DateTime when) {
    final Map<String, Object> localVariables = new HashMap<>();
    localVariables.put(SupplyReminderTaskDef.SUPPLY_REQUEST_COMMENT.getName(), comment);
    localVariables.put(SupplyReminderTaskDef.DAYS_SUPPLY.getName(), supplyInDays);
    localVariables.put(SupplyReminderTaskDef.SUPPLY_TYPE.getName(), supplyTypeEnum.name());
    localVariables.put(SupplyReminderTaskDef.IS_DISMISSED.getName(), false);
    processService.setVariablesLocal(taskId, localVariables);
    processService.setDueDate(taskId, when.plusDays(supplyInDays));
}

From source file:com.marand.thinkmed.medications.process.impl.TherapyTaskCreatorImpl.java

License:Open Source License

private DateTime getAdministrationTasksIntervalEnd(final DateTime start, final DateTime end,
        final RoundsIntervalDto roundsInterval) {
    final DateTime startOfTodaysRounds = start.withTimeAtStartOfDay().plusHours(roundsInterval.getStartHour())
            .plusMinutes(roundsInterval.getStartMinute());

    DateTime endTimestamp = start.withTimeAtStartOfDay().plusHours(roundsInterval.getEndHour())
            .plusMinutes(roundsInterval.getEndMinute());

    if (start.isAfter(startOfTodaysRounds) || start.equals(startOfTodaysRounds)) {
        endTimestamp = endTimestamp.plusDays(1);
    }//from  w w  w.j a va 2  s .c o  m

    boolean workingDay = mafDateRuleService.isDateOfType(endTimestamp.withTimeAtStartOfDay(),
            DayType.WORKING_DAY);

    while (!workingDay) {
        endTimestamp = endTimestamp.plusDays(1);
        workingDay = mafDateRuleService.isDateOfType(endTimestamp.withTimeAtStartOfDay(), DayType.WORKING_DAY);
    }
    if (end != null && endTimestamp.isAfter(end)) {
        endTimestamp = end;
    }
    return endTimestamp;
}

From source file:com.marand.thinkmed.medications.process.impl.TherapyTaskCreatorImpl.java

License:Open Source License

private List<Interval> removeInactiveTherapyDaysFromTasksInterval(final DateTime start, final DateTime end,
        final RoundsIntervalDto roundsInterval, final TimingCluster timing) {
    final List<Interval> intervals = new ArrayList<>();
    DateTime tasksStart = new DateTime(start);

    final DateTime startOfTodaysRounds = start.withTimeAtStartOfDay().plusHours(roundsInterval.getStartHour())
            .plusMinutes(roundsInterval.getStartMinute());

    DateTime tasksEnd = start.withTimeAtStartOfDay().plusHours(roundsInterval.getEndHour())
            .plusMinutes(roundsInterval.getEndMinute());

    if (start.isAfter(startOfTodaysRounds) && tasksEnd.isBefore(end)) {
        if (tasksEnd.plusDays(1).isAfter(end)) {
            tasksEnd = end;/*from w w w.  j  av  a2  s.  co m*/
        } else {
            tasksEnd = tasksEnd.plusDays(1);
        }
    }
    int daysFrequency = 1;
    if (timing != null && timing.getInterval() != null) {
        final int days = DataValueUtils.getPeriod(timing.getInterval()).getDays();
        if (days > 0) {
            daysFrequency = days;
        }
    }

    boolean previousDayWasValid = isInValidDaysOfWeek(tasksStart, timing);
    if (!previousDayWasValid) {
        tasksStart = startOfTodaysRounds.plusDays(1);
    }
    int dayIndex = 1;
    while (tasksEnd.isBefore(end) || tasksEnd.equals(end)) {
        final boolean validDayOfWeek = isInValidDaysOfWeek(tasksEnd, timing);
        final boolean validFrequency = dayIndex % daysFrequency == 0;
        if (validDayOfWeek && validFrequency) {
            previousDayWasValid = true;
        } else {
            final DateTime startOfRounds = tasksEnd.withTimeAtStartOfDay()
                    .plusHours(roundsInterval.getStartHour()).plusMinutes(roundsInterval.getStartMinute());
            if (previousDayWasValid) {
                intervals.add(new Interval(tasksStart, startOfRounds));
            }
            previousDayWasValid = false;
            tasksStart = startOfRounds.plusDays(1);
        }
        tasksEnd = tasksEnd.plusDays(1);
        dayIndex++;
    }
    if (previousDayWasValid && dayIndex > 1 || tasksEnd.minusDays(1).isBefore(end)) {
        if (!tasksStart.isAfter(end)) {
            intervals.add(new Interval(tasksStart, end));
        }
    }
    return intervals;
}

From source file:com.marand.thinkmed.medications.process.impl.TherapyTaskCreatorImpl.java

License:Open Source License

private DateTime getNextAdministrationTime(final DateTime fromTime,
        final List<HourMinuteDto> possibleAdministrations) {
    int index = 0;
    DateTime foundTime = combine(fromTime, possibleAdministrations.get(index));
    while (!foundTime.isAfter(fromTime)) {
        index++;/* w  w w .java  2  s  .c  o  m*/
        if (index >= possibleAdministrations.size()) {
            index = 0;
            foundTime = foundTime.plusDays(1);
        }
        foundTime = combine(foundTime, possibleAdministrations.get(index));
    }
    return foundTime;
}

From source file:com.marand.thinkmed.medications.process.impl.TherapyTaskCreatorImpl.java

License:Open Source License

private Pair<DateTime, TherapyDoseDto> getNextAdministrationTimeWithDose(final DateTime fromTime,
        final Map<HourMinuteDto, TherapyDoseDto> administrationTimesWithDoses) {
    int index = 0;
    final List<HourMinuteDto> times = new ArrayList<>(administrationTimesWithDoses.keySet());
    Collections.sort(times);/* w w  w .jav a  2 s  .  c  o  m*/
    DateTime foundTime = combine(fromTime, times.get(index));
    TherapyDoseDto therapyDoseDto = administrationTimesWithDoses.get(times.get(0));
    while (!foundTime.isAfter(fromTime)) {
        index++;
        if (index >= administrationTimesWithDoses.size()) {
            index = 0;
            foundTime = foundTime.plusDays(1);
        }
        final HourMinuteDto hourMinute = times.get(index);
        foundTime = combine(foundTime, hourMinute);
        therapyDoseDto = administrationTimesWithDoses.get(hourMinute);
    }
    return Pair.of(foundTime, therapyDoseDto);
}

From source file:com.marand.thinkmed.medications.task.listener.SupplyReminderTaskListener.java

License:Open Source License

@Override
public void notify(final DelegateTask delegateTask) {
    if (delegateTask.getEventName().equals(TaskListener.EVENTNAME_CREATE)) {
        final DelegateExecution execution = delegateTask.getExecution();
        final String patientId = (String) execution.getVariable(PharmacySupplyProcess.patientId.name());
        final String originalTherapyId = (String) execution
                .getVariable(PharmacySupplyProcess.originalTherapyId.name());
        delegateTask.setName(SupplyReminderTaskDef.getTaskTypeEnum().buildKey(patientId));
        delegateTask.setAssignee(TherapyAssigneeEnum.PHARMACIST.name());
        final DateTime createTime = new DateTime(delegateTask.getCreateTime());
        delegateTask.setDueDate(createTime
                .plusDays((Integer) execution.getVariable(PharmacySupplyProcess.supplyInDays.name())).toDate());

        final Map<String, Object> variablesMap = new HashMap<>();
        TaskListenerUtils.setTherapyTaskDefVariables(patientId, originalTherapyId, variablesMap);
        variablesMap.put(TaskConstants.TASK_EXECUTION_ID_VARIABLE_NAME,
                SupplyReminderTaskDef.TASK_EXECUTION_ID);
        variablesMap.put(SupplyReminderTaskDef.DAYS_SUPPLY.getName(),
                execution.getVariable(PharmacySupplyProcess.supplyInDays.name()));
        variablesMap.put(SupplyReminderTaskDef.IS_DISMISSED.getName(), false);
        variablesMap.put(SupplyReminderTaskDef.SUPPLY_TYPE.getName(),
                execution.getVariable(PharmacySupplyProcess.supplyType.name()));

        delegateTask.setVariablesLocal(variablesMap);
    }/* w ww  .  j av  a2  s.c  om*/
}

From source file:com.metinkale.prayerapp.vakit.fragments.MainFragment.java

License:Apache License

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {

    switch (item.getItemId()) {

    case R.id.notification:
        Fragment frag = getActivity().getSupportFragmentManager().findFragmentByTag("notPrefs");
        if (frag == null) {
            ((Main) getActivity()).setFooterText("", false);
            getActivity().getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragContainer, NotificationPrefs.create(mTimes), "notPrefs")
                    .commitAllowingStateLoss();
        } else {/*  w ww .j av  a2 s  .  c o m*/
            ((Main) getActivity()).setFooterText(getString(R.string.monthly), true);
            getActivity().getSupportFragmentManager().beginTransaction().remove(frag).commitAllowingStateLoss();

        }

        AppRatingDialog.addToOpenedMenus("notPrefs");
        break;
    case R.id.export:
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.export).setItems(new CharSequence[] { "CSV", "PDF" },
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, final int which) {
                        long minDate = 0;
                        long maxDate = Long.MAX_VALUE;
                        if (mTimes instanceof WebTimes) {
                            minDate = ((WebTimes) mTimes).getFirstSyncedDay().toDateTimeAtCurrentTime()
                                    .getMillis();
                            maxDate = ((WebTimes) mTimes).getLastSyncedDay().toDateTimeAtCurrentTime()
                                    .getMillis();
                        }
                        final LocalDate ld = LocalDate.now();
                        final long finalMaxDate = maxDate;
                        DatePickerDialog dlg = new DatePickerDialog(getActivity(),
                                new DatePickerDialog.OnDateSetListener() {
                                    @Override
                                    public void onDateSet(DatePicker datePicker, int y, int m, int d) {
                                        final LocalDate from = new LocalDate(y, m + 1, d);
                                        DatePickerDialog dlg1 = new DatePickerDialog(getActivity(),
                                                new DatePickerDialog.OnDateSetListener() {
                                                    @Override
                                                    public void onDateSet(DatePicker datePicker, int y1, int m1,
                                                            int d1) {
                                                        final LocalDate to = new LocalDate(y1, m1 + 1, d1);
                                                        try {
                                                            export(which, from, to);
                                                        } catch (IOException e) {
                                                            e.printStackTrace();
                                                            Crashlytics.logException(e);
                                                            Toast.makeText(getActivity(), R.string.error,
                                                                    Toast.LENGTH_SHORT).show();
                                                        }
                                                    }
                                                }, ld.getYear(), ld.getMonthOfYear() - 1, ld.getDayOfMonth());
                                        DateTime startDate = DateTime.now().withDate(y, m + 1, d);
                                        long start = startDate.getMillis();
                                        if (which == 1)
                                            dlg1.getDatePicker().setMaxDate(
                                                    Math.min(finalMaxDate, startDate.plusDays(31).getMillis()));
                                        else
                                            dlg1.getDatePicker().setMaxDate(finalMaxDate);

                                        dlg1.getDatePicker().setMinDate(
                                                Math.min(start, dlg1.getDatePicker().getMaxDate()) - 1);
                                        dlg1.setTitle(R.string.to);
                                        dlg1.show();

                                    }
                                }, ld.getYear(), ld.getMonthOfYear() - 1, ld.getDayOfMonth());
                        dlg.getDatePicker().setMinDate(minDate);
                        dlg.getDatePicker().setMaxDate(maxDate);
                        dlg.setTitle(R.string.from);
                        dlg.show();
                    }
                });
        builder.show();
        break;
    case R.id.refresh:
        if (mTimes instanceof WebTimes) {
            ((WebTimes) mTimes).syncAsync();
        }
        break;

    case R.id.share:
        String txt = getString(R.string.shareTimes, mTimes.getName()) + ":";
        LocalDate date = LocalDate.now();
        String[] times = { mTimes.getTime(date, 0), mTimes.getTime(date, 1), mTimes.getTime(date, 2),
                mTimes.getTime(date, 3), mTimes.getTime(date, 4), mTimes.getTime(date, 5) };
        for (int i = 0; i < times.length; i++) {
            txt += "\n   " + Vakit.getByIndex(i).getString() + ": " + times[i];
        }

        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
        sharingIntent.putExtra(Intent.EXTRA_TEXT, txt);
        startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share)));

    }
    return super.onOptionsItemSelected(item);
}

From source file:com.mgl.updater.Updater2.java

public void process() {

    List<NewContract> nContractList = XHelper.getInstance().fromFileNameToNCList(CONTRACT_FILE);
    ControllerFactory controllerFactory = new ControllerFactory();
    ContractHelper contractHelper = new ContractHelper();

    TextPaneLogger logger = new TextPaneLogger(progressBarListener);

    try (ConnectionHandler cHandler = new ConnectionHandler(logger)) {
        cHandler.connect();/*from   www.j  av a2s.com*/
        progressBarListener.propertyChange(new PropertyChangeEvent(this, "UpdaterLog", null,
                nContractList.size() + " Contracts to be processed."));

        int counter = 0;
        for (NewContract nc : nContractList) {

            ContractEntity contractEntity = controllerFactory.getContractJpaController()
                    .findContract(nc.symbol());
            if (contractEntity == null) {
                contractEntity = new ContractEntity(nc.symbol(), nc.exchange(), nc.currency());
                controllerFactory.getContractJpaController().create(contractEntity);
            }

            BarEntity latestBar = contractHelper.getLatestBar(contractEntity,
                    controllerFactory.getBarJpaController());
            SimpleDateFormat sdf = new SimpleDateFormat(YMD); // move this 2 lines
            String endDateTime = sdf.format(new DateTime().toDate());

            counter++;
            HistoricalDataLoaderWorker handler = null;
            if (latestBar == null) {
                progressBarListener.propertyChange(
                        new PropertyChangeEvent(this, "UpdaterLog", null, "Processing all " + counter + " of "
                                + nContractList.size() + " Contract: " + contractEntity.getSymbol()));
                handler = new HistoricalDataLoaderWorker(nc, contractEntity, cHandler.getController(),
                        endDateTime, 5, Types.DurationUnit.YEAR, controllerFactory.getBarJpaController(),
                        logger);
            } else {
                DateTime endDate = new DateTime();
                DateTime startDate = new DateTime(latestBar.getDate().getTime());

                int days = 0;
                DateTime nextDay = startDate.plusDays(1);
                while (nextDay.isBefore(endDate)) {
                    DateTime.Property p = nextDay.dayOfWeek();
                    if (p.get() < 6) {
                        days++;
                    }
                    nextDay = nextDay.plusDays(1);
                }

                if (days > 1) { // TODO if after market close it can be 0.
                    progressBarListener.propertyChange(new PropertyChangeEvent(this, "UpdaterLog", null,
                            "Processing " + counter + " of " + nContractList.size() + " Contract: "
                                    + contractEntity.getSymbol() + " days: " + days));
                    handler = new HistoricalDataLoaderWorker(nc, contractEntity, cHandler.getController(),
                            endDateTime, days, controllerFactory.getBarJpaController(), logger);
                } else {
                    progressBarListener.propertyChange(new PropertyChangeEvent(this, "UpdaterLog", null,
                            "Processing " + counter + " of " + nContractList.size() + " Contract: "
                                    + contractEntity.getSymbol() + " no days"));
                }
            }
            if (progressBarListener != null) {
                float f = ((counter * 1f) / nContractList.size()) * 100f;
                progressBarListener
                        .propertyChange(new PropertyChangeEvent(this, "UpdaterProgress", null, Math.round(f)));
            }
            if (handler != null) {
                long bMillis = System.currentTimeMillis();
                handler.execute();
                handler.get();
                handler.end();
                while ((System.currentTimeMillis() - bMillis) < _10s) {
                    Thread.sleep(_1s);
                }
            }
        }
        progressBarListener.propertyChange(new PropertyChangeEvent(this, "UpdaterLog", null, "End"));
    } catch (Exception e) {
        Logger.getLogger(Updater2.class.getName()).log(Level.SEVERE, null, e);
    }

}

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

License:Apache License

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

    if (auction == null) {
        throw new NotFoundException();
    }/*w  w w  .  j  ava2  s  . co  m*/

    DateTime today = new DateTime();
    DateTime tomorrow = today.plusDays(30); // +30 days

    auction = auction.toBuilder().setStartDate(today.getMillis()).setEndDate(tomorrow.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//  w  w  w . j ava2s . com
 * @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;
}