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.tortel.deploytrack.provider.WidgetProvider.java

License:Apache License

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // Check if the database needs to be upgraded
    if (DatabaseUpgrader.needsUpgrade(context)) {
        DatabaseUpgrader.doDatabaseUpgrade(context);
    }/*from ww w .  ja  va  2s.  c  o m*/

    updateAllWidgets(context, appWidgetManager);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    if (mScreenShotMode) {
        // Time screenshot mode out in 3 min
        Intent cancelScreenShotMode = new Intent(UPDATE_INTENT);
        cancelScreenShotMode.putExtra(KEY_SCREENSHOT_MODE, false);

        PendingIntent screenshotPending = PendingIntent.getBroadcast(context, 0, cancelScreenShotMode,
                PendingIntent.FLAG_CANCEL_CURRENT);

        long triggerTime = new Date().getTime() + SCREENSHOT_TIMEOUT * MILIS_PER_MIN;

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
            alarmManager.setExact(AlarmManager.RTC, triggerTime, screenshotPending);
        } else {
            alarmManager.set(AlarmManager.RTC, triggerTime, screenshotPending);
        }
    } else {
        //Schedule an update at midnight
        DateTime now = new DateTime();
        DateTime tomorrow = new DateTime(now.plusDays(1)).withTimeAtStartOfDay();

        PendingIntent pending = PendingIntent.getBroadcast(context, 0, new Intent(UPDATE_INTENT),
                PendingIntent.FLAG_CANCEL_CURRENT);

        //Adding 100msec to make sure its triggered after midnight
        Log.d("Scheduling update for " + tomorrow.getMillis() + 100);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
            alarmManager.setExact(AlarmManager.RTC, tomorrow.getMillis() + 100, pending);
        } else {
            alarmManager.set(AlarmManager.RTC, tomorrow.getMillis() + 100, pending);
        }

    }
}

From source file:com.tortel.deploytrack.service.NotificationService.java

License:Apache License

@SuppressLint("NewApi")
private void showNotification() {
    // If there isnt an ID saved, shut down the service
    if (deploymentId == -1) {
        stopSelf();/* w  w w .  j a v a2s  .co  m*/
        return;
    }
    if (DEBUG) {
        Toast.makeText(this, "NotificationService loading notification", Toast.LENGTH_SHORT).show();
    }

    // Load the Deployment object
    Deployment deployment = DatabaseManager.getInstance(this).getDeployment(deploymentId);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    RemoteViews view = new RemoteViews(getPackageName(), R.layout.notification);
    view.setImageViewBitmap(R.id.notification_pie, WidgetProvider.getChartBitmap(deployment, SIZE));
    view.setTextViewText(R.id.notification_title, deployment.getName());

    view.setTextViewText(R.id.notification_main, getResources().getString(R.string.small_notification,
            deployment.getPercentage(), deployment.getCompleted(), deployment.getLength()));

    if (prefs.getBoolean(Prefs.KEY_HIDE_DATE, false)) {
        view.setViewVisibility(R.id.notification_daterange, View.GONE);
    } else {
        view.setTextViewText(R.id.notification_daterange, getResources().getString(R.string.date_range,
                deployment.getFormattedStart(), deployment.getFormattedEnd()));
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle(deployment.getName());
    builder.setContentText(getResources().getString(R.string.small_notification, deployment.getPercentage(),
            deployment.getCompleted(), deployment.getLength()));
    builder.setOngoing(true);

    // Hide the time, its persistent
    builder.setWhen(0);

    builder.setSmallIcon(R.drawable.ic_notification);
    builder.setPriority(Integer.MAX_VALUE);

    Notification notification = builder.build();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        notification.bigContentView = view;
    }

    notificationManager.notify(NOTIFICATION_ID, notification);

    //Schedule an update at midnight
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    DateTime now = new DateTime();
    DateTime tomorrow = new DateTime(now.plusDays(1)).withTimeAtStartOfDay();

    PendingIntent pending = PendingIntent.getBroadcast(getBaseContext(), 0, new Intent(UPDATE_INTENT),
            PendingIntent.FLAG_UPDATE_CURRENT);

    //Adding 100msec to make sure its triggered after midnight
    Log.d("Scheduling notification update for " + tomorrow.getMillis() + 100);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
        alarmManager.setExact(AlarmManager.RTC, tomorrow.getMillis() + 100, pending);
    } else {
        alarmManager.set(AlarmManager.RTC, tomorrow.getMillis() + 100, pending);
    }
}

From source file:com.tremolosecurity.provisioning.tasks.Approval.java

License:Apache License

public Approval(WorkflowTaskType taskConfig, ConfigManager cfg, Workflow wf) throws ProvisioningException {
    super(taskConfig, cfg, wf);

    this.approvers = new ArrayList<Approver>();
    this.azRules = new ArrayList<AzRule>();

    this.failed = false;

    ApprovalType att = (ApprovalType) taskConfig;

    for (AzRuleType azr : att.getApprovers().getRule()) {
        Approver approver = new Approver();

        if (azr.getScope().equalsIgnoreCase("filter")) {
            approver.type = ApproverType.Filter;
        } else if (azr.getScope().equalsIgnoreCase("group")) {
            approver.type = ApproverType.StaticGroup;
        } else if (azr.getScope().equalsIgnoreCase("dn")) {
            approver.type = ApproverType.DN;
        } else if (azr.getScope().equalsIgnoreCase("dynamicGroup")) {
            approver.type = ApproverType.DynamicGroup;
        } else if (azr.getScope().equalsIgnoreCase("custom")) {
            approver.type = ApproverType.Custom;

        }//  w w  w.j  a  va 2 s .  co  m

        approver.constraint = azr.getConstraint();

        setupCustomParameters(approver);

        this.approvers.add(approver);

        AzRule rule = new AzRule(azr.getScope(), azr.getConstraint(), azr.getClassName(), cfg, wf);

        this.azRules.add(rule);
        approver.customAz = rule.getCustomAuthorization();

    }

    this.label = att.getLabel();
    this.emailTemplate = att.getEmailTemplate();
    this.mailAttr = att.getMailAttr();
    this.failureEmailSubject = att.getFailureEmailSubject();
    this.failureEmailMsg = att.getFailureEmailMsg();

    this.escalationRules = new ArrayList<EscalationRule>();

    if (att.getEscalationPolicy() != null) {
        DateTime now = new DateTime();
        for (EscalationType ert : att.getEscalationPolicy().getEscalation()) {
            EscalationRule erule = new EsclationRuleImpl();

            DateTime when;

            if (ert.getExecuteAfterUnits().equalsIgnoreCase("sec")) {
                when = now.plusSeconds(ert.getExecuteAfterTime());
            } else if (ert.getExecuteAfterUnits().equals("min")) {
                when = now.plusMinutes(ert.getExecuteAfterTime());
            } else if (ert.getExecuteAfterUnits().equals("hr")) {
                when = now.plusHours(ert.getExecuteAfterTime());
            } else if (ert.getExecuteAfterUnits().equals("day")) {
                when = now.plusDays(ert.getExecuteAfterTime());
            } else if (ert.getExecuteAfterUnits().equals("wk")) {
                when = now.plusWeeks(ert.getExecuteAfterTime());
            } else {
                throw new ProvisioningException("Unknown time unit : " + ert.getExecuteAfterUnits());
            }

            erule.setCompleted(false);
            erule.setExecuteTS(when.getMillis());

            if (ert.getValidateEscalationClass() != null && !ert.getValidateEscalationClass().isEmpty()) {
                try {
                    erule.setVerify(
                            (VerifyEscalation) Class.forName(ert.getValidateEscalationClass()).newInstance());
                } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                    throw new ProvisioningException("Could not initialize escalation rule", e);
                }
            } else {
                erule.setVerify(null);
            }

            erule.setAzRules(new ArrayList<AzRule>());
            for (AzRuleType azr : ert.getAzRules().getRule()) {
                Approver approver = new Approver();

                if (azr.getScope().equalsIgnoreCase("filter")) {
                    approver.type = ApproverType.Filter;
                } else if (azr.getScope().equalsIgnoreCase("group")) {
                    approver.type = ApproverType.StaticGroup;
                } else if (azr.getScope().equalsIgnoreCase("dn")) {
                    approver.type = ApproverType.DN;
                } else if (azr.getScope().equalsIgnoreCase("dynamicGroup")) {
                    approver.type = ApproverType.DynamicGroup;
                } else if (azr.getScope().equalsIgnoreCase("custom")) {
                    approver.type = ApproverType.Custom;
                }

                approver.constraint = azr.getConstraint();
                setupCustomParameters(approver);
                //this.approvers.add(approver);

                AzRule rule = new AzRule(azr.getScope(), azr.getConstraint(), azr.getClassName(), cfg, wf);

                erule.getAzRules().add(rule);
                approver.customAz = rule.getCustomAuthorization();

            }

            this.escalationRules.add(erule);
            now = when;
        }

        if (att.getEscalationPolicy().getEscalationFailure().getAction() != null) {
            switch (att.getEscalationPolicy().getEscalationFailure().getAction()) {
            case "leave":
                this.failureAzRules = null;
                this.failOnNoAZ = false;
                break;
            case "assign":
                this.failOnNoAZ = true;
                this.failureAzRules = new ArrayList<AzRule>();
                for (AzRuleType azr : att.getEscalationPolicy().getEscalationFailure().getAzRules().getRule()) {
                    Approver approver = new Approver();

                    if (azr.getScope().equalsIgnoreCase("filter")) {
                        approver.type = ApproverType.Filter;
                    } else if (azr.getScope().equalsIgnoreCase("group")) {
                        approver.type = ApproverType.StaticGroup;
                    } else if (azr.getScope().equalsIgnoreCase("dn")) {
                        approver.type = ApproverType.DN;
                    } else if (azr.getScope().equalsIgnoreCase("dynamicGroup")) {
                        approver.type = ApproverType.DynamicGroup;
                    } else if (azr.getScope().equalsIgnoreCase("custom")) {
                        approver.type = ApproverType.Custom;
                    }

                    approver.constraint = azr.getConstraint();
                    setupCustomParameters(approver);
                    //this.approvers.add(approver);

                    AzRule rule = new AzRule(azr.getScope(), azr.getConstraint(), azr.getClassName(), cfg, wf);

                    this.failureAzRules.add(rule);
                    approver.customAz = rule.getCustomAuthorization();

                }
                break;

            default:
                throw new ProvisioningException("Unknown escalation failure action : "
                        + att.getEscalationPolicy().getEscalationFailure().getAction());
            }

        }
    }

}

From source file:com.webarch.common.datetime.DateTimeUtils.java

License:Apache License

public static Date getLastDayOfWeek(Date date) {
    DateTime dateTime = new DateTime(date);
    return dateTime.plusDays(7 - dateTime.getDayOfWeek()).toDate();
}

From source file:com.webarch.common.datetime.DateTimeUtils.java

License:Apache License

/**
 * ?/* ww w . ja v  a  2  s.  c  om*/
 *
 * @param date     ?
 * @param after    ??
 * @param timeUnit ??
 * @return ??
 */
public static Date getAfterDate(Date date, final int after, final int timeUnit) {
    DateTime dateTime = new DateTime(date);
    Date result;
    switch (timeUnit) {
    case YEAR_UNIT:
        result = dateTime.plusYears(after).toDate();
        break;
    case MONTH_UNIT:
        result = dateTime.plusMonths(after).toDate();
        break;
    case DAY_UNIT:
        result = dateTime.plusDays(after).toDate();
        break;
    case HOURE_UNIT:
        result = dateTime.plusHours(after).toDate();
        break;
    case MINUTE_UNIT:
        result = dateTime.plusMinutes(after).toDate();
        break;
    default:
        result = date;
    }
    return result;
}

From source file:com.yourmediashelf.fedora.util.DateUtility.java

License:Open Source License

/**
 * Parses lexical representations of xsd:dateTimes, e.g.
 * "2010-01-31T14:21:03.001Z". Fractional seconds and timezone offset are
 * optional./*from www.  jav a2 s.com*/
 *
 * <p>Note: fractional seconds are only supported to three digits of
 * precision.</p>
 *
 * @param input
 *        an XML Schema 1.1 dateTime
 * @return a DateTime representing the input
 * @see "http://www.w3.org/TR/xmlschema11-2/#dateTime"
 */
public static DateTime parseXSDDateTime(String input) {
    Matcher m = XSD_DATETIME.matcher(input);
    if (!m.find()) {
        throw new IllegalArgumentException(input + " is not a valid XML Schema 1.1 dateTime.");
    }

    int year = Integer.parseInt(m.group(1));
    int month = Integer.parseInt(m.group(3));
    int day = Integer.parseInt(m.group(4));

    int hour = 0, minute = 0, second = 0, millis = 0;
    boolean hasEndOfDayFrag = m.group(11) != null;
    if (!hasEndOfDayFrag) {
        hour = Integer.parseInt(m.group(6));
        minute = Integer.parseInt(m.group(7));
        second = Integer.parseInt(m.group(8));
        // Parse fractional seconds
        // m.group(9), if not null/empty should be Strings such as ".5" or
        // ".050" which convert to 500 and 50, respectively.
        if (m.group(9) != null && !m.group(9).isEmpty()) {
            // parse as Double as a quick hack to drop trailing 0s.
            // e.g. ".0500" becomes 0.05
            double d = Double.parseDouble(m.group(9));

            // Something like the following would allow for int-sized
            // precision, but joda-time 1.6 only supports millis (i.e. <= 999).
            // see: org.joda.time.field.FieldUtils.verifyValueBounds
            //   int digits = String.valueOf(d).length() - 2;
            //   fractionalSeconds = (int) (d * Math.pow(10, digits));
            millis = (int) (d * 1000);
        }
    }

    DateTimeZone zone = null;
    if (m.group(13) != null) {
        String tmp = m.group(13);
        if (tmp.equals("Z")) {
            tmp = "+00:00";
        }
        zone = DateTimeZone.forID(tmp);
    }
    DateTime dt = new DateTime(year, month, day, hour, minute, second, millis, zone);

    if (hasEndOfDayFrag) {
        return dt.plusDays(1);
    }
    return dt;
}

From source file:com.yunguchang.alarm.RulesExecutor.java

@Path("/init")
@GET//from www . j  a va  2 s .c om
public void initRuleEngine() {
    synchronized (this) {
        //            if kSession.

        for (FactHandle carHandle : carHandles) {
            kSession.delete(carHandle);
        }
        carHandles.clear();

        Collection<FactHandle> handles = kSession.getFactHandles();
        for (FactHandle handle : handles) {
            Object fact = kSession.getObject(handle);
            if (fact instanceof AlarmEvent) {
                AlarmEvent alarmEvent = (AlarmEvent) fact;
                if (alarmEvent.getEnd() == null) {
                    alarmEvent.setEnd(alarmEvent.getStart().withTimeAtStartOfDay().plusDays(1));
                    clearAlarmEventSource.fire(alarmEvent);
                }
            }
            kSession.delete(handle);
        }

        List<TAzJzRelaEntity> licenseClassVehicleMappings = vehicleRepository
                .listAllLicenceClassAndVehicleMappings();
        for (TAzJzRelaEntity licenseClassVehicleMapping : licenseClassVehicleMappings) {
            LicenseVehicleMapping mapping = EntityConvert.fromEntity(licenseClassVehicleMapping);
            kSession.insert(mapping);
        }

        refreshScheduleCar();
        DateTime todayStart = DateTime.now().withTimeAtStartOfDay();
        DateTime tomorrowStart = todayStart.plusDays(1);

        List<TBusAlarmEntity> alarmEntities = alarmRepository.getNoClearedAlarmByStartEnd(todayStart,
                tomorrowStart);
        for (TBusAlarmEntity alarmEntity : alarmEntities) {
            kSession.insert(EntityConvert.fromEntity(alarmEntity));
        }

        kSession.insert(kSession.getSessionClock());

        List<TAzCarinfoEntity> carEntites = vehicleRepository.listAllCarsWithGPS();
        for (TAzCarinfoEntity carEntite : carEntites) {
            Car car = EntityConvert.fromEntity(carEntite);
            FactHandle handle = kSession.insert(car);
            carHandles.add(handle);
        }

        if (!start) {
            start = true;
            logger.debug("submit drools fireUntilHalt task");
            mes.submit(new Runnable() {
                @Override
                public void run() {
                    while (!stop) {
                        logger.debug("start drools");
                        try {
                            kSession.fireUntilHalt();
                        } catch (Exception e) {
                            logger.ruleEngineExecutingError(e);
                        }
                        logger.restartRuleEngine();
                    }

                }
            });
            logger.debug("submit successfully");
        }
    }
}

From source file:com.yunguchang.alarm.RulesExecutor.java

@Path("/refresh")
@GET/*w  w  w  .  j av  a2  s.c o  m*/
public void refreshScheduleCar() {
    synchronized (this) {
        Map<String, FactHandle> scheduleCarMap = new HashMap<>();

        Collection<FactHandle> handles = kSession.getFactHandles();
        for (FactHandle handle : handles) {

            Object fact = kSession.getObject(handle);
            if (fact instanceof ScheduleCar) {
                scheduleCarMap.put(((ScheduleCar) fact).getId(), handle);
            }

        }

        DateTime todayStart = DateTime.now().withTimeAtStartOfDay();
        DateTime tomorrowStart = todayStart.plusDays(1);
        List<TBusScheduleRelaEntity> scheduleEntities = scheduleRepository.getSchedulesByStartAndEnd(todayStart,
                tomorrowStart);
        for (TBusScheduleRelaEntity scheduleEntity : scheduleEntities) {
            com.yunguchang.model.common.Schedule schedule = EntityConvert
                    .fromEntityWithScheduleCars(scheduleEntity);
            for (ScheduleCar scheduleCar : schedule.getScheduleCars()) {
                String scheduleCarId = scheduleCar.getId();
                if (ScheduleStatus.CANCELED.equals(scheduleCar.getStatus())
                        || ScheduleStatus.NOT_IN_EFFECT.equals(scheduleCar.getStatus())) {
                    removeScheduleFact(scheduleCarMap, scheduleCarId);
                    continue;
                }

                if (scheduleCarMap.containsKey(scheduleCarId)) {
                    FactHandle factHandle = scheduleCarMap.get(scheduleCarId);
                    ScheduleCar factScheduleCar = (ScheduleCar) kSession.getObject(factHandle);
                    if (factScheduleCar.getStatus() != null
                            && !factScheduleCar.getStatus().equals(scheduleCar.getStatus())
                            || factScheduleCar.getStart() != scheduleCar.getStart()
                            || factScheduleCar.getDuration() != scheduleCar.getDuration()) {
                        kSession.update(factHandle, scheduleCar);
                    }

                    continue;
                }
                if (!scheduleCarMap.containsKey(scheduleCarId)
                        && scheduleCar.getSchedule().getEnd().plusMinutes(30).isAfter(DateTime.now())) {
                    logger.insertScheduleCar(scheduleCar);
                    kSession.insert(scheduleCar);
                    continue;
                }

            }
        }
    }
}

From source file:cron.DateTimes.java

License:Open Source License

public static DateTime nearestWeekday(DateTime t) {
    if (t.getDayOfWeek() == DateTimeConstants.SATURDAY)
        return t.minusDays(1);
    else if (t.getDayOfWeek() == DateTimeConstants.SUNDAY)
        return t.plusDays(1);
    return t;/* www.  ja v  a  2s.com*/
}

From source file:cron.DayOfMonthField.java

License:Open Source License

public boolean matches(DateTime time) {
    if (unspecified)
        return true;
    final int dayOfMonth = time.getDayOfMonth();
    if (lastDay) {
        return dayOfMonth == time.dayOfMonth().withMaximumValue().getDayOfMonth();
    } else if (nearestWeekday) {
        int dayOfWeek = time.getDayOfWeek();
        if ((dayOfWeek == DateTimeConstants.MONDAY && contains(time.minusDays(1).getDayOfMonth()))
                || (dayOfWeek == DateTimeConstants.FRIDAY && contains(time.plusDays(1).getDayOfMonth()))) {
            return true;
        }/*from   w ww.  j  a  va  2 s . c  om*/
    }
    return contains(dayOfMonth);
}