Example usage for org.joda.time DateTime plusYears

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

Introduction

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

Prototype

public DateTime plusYears(int years) 

Source Link

Document

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

Usage

From source file:edu.unc.lib.deposit.normalize.Proquest2N3BagJob.java

License:Apache License

private void setEmbargoUntil(Model model, Resource primaryResource, Element dataRoot) {

    String embargoCode = dataRoot.getAttributeValue("embargo_code");

    if (embargoCode != null) {

        DateTime currentDate = new DateTime();

        // Get the completion year and create a date time out of the end of the year, to make the most generous embargo possible
        String compDateString = dataRoot.getChild("DISS_description").getChild("DISS_dates")
                .getChildText("DISS_comp_date");
        DateTime compDate = new DateTime(Integer.parseInt(compDateString), 12, 31, 0, 0, 0, 0);

        // Embargo start time is the lowest of either the current date or the completion date
        DateTime embargoEnd = currentDate.compareTo(compDate) < 0 ? currentDate : compDate;

        if ("2".equals(embargoCode))
            embargoEnd = embargoEnd.plusYears(1);
        else if ("3".equals(embargoCode))
            embargoEnd = embargoEnd.plusYears(2);
        else/*from   www .  j a v a2  s  .  c o m*/
            embargoEnd = null;

        // If the embargo end date isn't coming from comp_date then make sure it hasn't already expired
        if (embargoEnd != null && embargoEnd != currentDate && embargoEnd.compareTo(currentDate) < 0) {
            // Embargo has already expired, no need to set it
            embargoEnd = null;
        }

        // Add the embargo end date as a triple
        if (embargoEnd != null) {
            model.add(primaryResource, cdrprop(model, embargoUntil),
                    DateTimeUtil.utcYMDFormatter.print(embargoEnd) + "T00:00:00", XSDDatatype.XSDdateTime);
        }
    }
}

From source file:fr.gouv.vitam.mdbes.MainSimpleRequest.java

License:Open Source License

protected static void oneShot(MongoDbAccess dbvitam) throws InvalidParseOperationException,
        InvalidExecOperationException, InstantiationException, IllegalAccessException {
    // Requesting
    String comdtree = request.toString();
    BasicDBObject query = (BasicDBObject) JSON.parse(comdtree);
    if (ids != null) {
        BasicDBObject id = (BasicDBObject) JSON.parse(ids);
        DateTime date = new DateTime(-123456789012345L);
        query = new BasicDBObject("OldDate", date.toDate());
        System.out.println("Date: " + date + " upd: " + query + " => " + date.getYear());
        dbvitam.daips.collection.update(id, query);
        final DBCursor cursor = dbvitam.daips.collection.find(id);
        while (cursor.hasNext()) {
            final DAip maip = (DAip) cursor.next();
            maip.load(dbvitam);//from w w w  .j a va 2 s  . com
            System.out.println(maip);
        }
        cursor.close();
        System.out.println("====");
        date = date.plusYears(10);
        id.append("OldDate", new BasicDBObject("$lt", date.toDate()));
        System.out.println("Date: " + date + " find: " + id + " => " + date.getYear());
        final DBCursor cursor2 = dbvitam.daips.collection.find(id);
        while (cursor2.hasNext()) {
            final DAip maip = (DAip) cursor2.next();
            Date madate = maip.getDate("OldDate");
            System.out.println("Madate: " + madate);
            System.out.println("Madate: " + madate.getTime());
            System.out.println("Madate: " + new DateTime(madate));
            maip.load(dbvitam);
            System.out.println(maip);
        }
        cursor2.close();
    } else {
        final DBCursor cursor = dbvitam.find(dbvitam.daips, query, ID_NBCHILD);
        while (cursor.hasNext()) {
            final DAip maip = (DAip) cursor.next();
            maip.load(dbvitam);
            System.out.println(maip);
        }
        cursor.close();
    }
}

From source file:fr.nicopico.dashclock.birthday.BirthdayService.java

License:Apache License

@Override
protected void onUpdateData(int reason) {
    if (reason == UPDATE_REASON_SETTINGS_CHANGED) {
        updatePreferences();/*from w ww.  ja v a2 s .c om*/
    }

    final Resources res = getResources();
    final List<Birthday> birthdays = birthdayRetriever.getContactWithBirthdays(getApplicationContext(),
            contactGroupId);

    Configuration config = new Configuration();
    config.setToDefaults();

    // Disable/enable Android localization
    if (needToRefreshLocalization
            || (disableLocalization && !DEFAULT_LANG.equals(Locale.getDefault().getLanguage()))) {
        if (disableLocalization) {
            config.locale = new Locale(DEFAULT_LANG);
        } else {
            // Restore Android localization
            //noinspection ConstantConditions
            config.locale = Resources.getSystem().getConfiguration().locale;
        }

        Locale.setDefault(config.locale);
        getBaseContext().getResources().updateConfiguration(config,
                getBaseContext().getResources().getDisplayMetrics());
    }

    DateTime today = new DateTime();

    int upcomingBirthdays = 0;
    String collapsedTitle = null;
    String expandedTitle = null;
    StringBuilder body = new StringBuilder();

    for (Birthday birthday : birthdays) {
        DateTime birthdayEvent;
        MonthDay birthdayDate = birthday.birthdayDate;
        try {
            birthdayEvent = birthdayDate.toDateTime(today);
        } catch (IllegalFieldValueException e) {
            if (birthdayDate.getDayOfMonth() == 29 && birthdayDate.getMonthOfYear() == 2) {
                // Birthday on February 29th (leap year) -> March 1st
                birthdayEvent = birthdayDate.dayOfMonth().addToCopy(1).toDateTime(today);
            } else {
                Log.e(TAG, "Invalid date", e);
                continue;
            }
        }

        // How many days before the birthday ?
        int days;
        if (birthdayEvent.isAfter(today) || birthdayEvent.isEqual(today)) {
            days = Days.daysBetween(today, birthdayEvent).getDays();
        } else {
            // Next birthday event is next year
            days = Days.daysBetween(today, birthdayEvent.plusYears(1)).getDays();
        }

        // Should the birthday be displayed ?
        if (days <= daysLimit) {
            upcomingBirthdays++;

            if (upcomingBirthdays == 1) {
                // A single birthday will be displayed
                collapsedTitle = birthday.displayName;
                expandedTitle = res.getString(R.string.single_birthday_title_format, birthday.displayName);
            }

            // More than 1 upcoming birthday: display contact name
            if (upcomingBirthdays > 1) {
                body.append("\n").append(birthday.displayName).append(", ");
            }

            // Age
            if (!birthday.unknownYear) {
                int age = today.get(DateTimeFieldType.year()) - birthday.year;
                body.append(res.getQuantityString(R.plurals.age_format, age, age));
                body.append(' ');
            }

            // When
            int daysFormatResId;
            switch (days) {
            case 0:
                daysFormatResId = R.string.when_today_format;
                break;
            case 1:
                daysFormatResId = R.string.when_tomorrow_format;
                break;
            default:
                daysFormatResId = R.string.when_days_format;
            }

            body.append(res.getString(daysFormatResId, days));
        } else {
            // All visible birthdays have been processed
            break;
        }
    }

    if (upcomingBirthdays > 0) {
        Intent clickIntent = buildClickIntent(birthdays.subList(0, upcomingBirthdays));

        if (upcomingBirthdays > 1) {
            collapsedTitle += " + " + (upcomingBirthdays - 1);
        }

        // Display message
        publishUpdate(
                new ExtensionData().visible(true).icon(R.drawable.ic_extension_white).status(collapsedTitle)
                        .expandedTitle(expandedTitle).expandedBody(body.toString()).clickIntent(clickIntent));
    } else {
        // Nothing to show
        publishUpdate(new ExtensionData().visible(false));
    }
}

From source file:google.registry.flows.domain.DomainRestoreRequestFlow.java

License:Open Source License

@Override
public final EppResponse run() throws EppException {
    extensionManager.register(FeeUpdateCommandExtension.class, MetadataExtension.class,
            RgpUpdateExtension.class);
    extensionManager.validate();/*from   w ww.j a  v  a 2s .c  om*/
    validateClientIsLoggedIn(clientId);
    Update command = (Update) resourceCommand;
    DateTime now = ofy().getTransactionTime();
    DomainResource existingDomain = loadAndVerifyExistence(DomainResource.class, targetId, now);
    FeesAndCredits feesAndCredits = pricingLogic.getRestorePrice(Registry.get(existingDomain.getTld()),
            targetId, now);
    FeeUpdateCommandExtension feeUpdate = eppInput.getSingleExtension(FeeUpdateCommandExtension.class);
    verifyRestoreAllowed(command, existingDomain, feeUpdate, feesAndCredits, now);
    HistoryEntry historyEntry = buildHistory(existingDomain, now);
    ImmutableSet.Builder<ImmutableObject> entitiesToSave = new ImmutableSet.Builder<>();
    entitiesToSave.addAll(createRestoreAndRenewBillingEvents(historyEntry, feesAndCredits.getRestoreCost(),
            feesAndCredits.getRenewCost(), now));
    // We don't preserve the original expiration time of the domain when we restore, since doing so
    // would require us to know if they received a grace period refund when they deleted the domain,
    // and to charge them for that again. Instead, we just say that all restores get a fresh year of
    // registration and bill them for that accordingly.
    DateTime newExpirationTime = now.plusYears(1);
    BillingEvent.Recurring autorenewEvent = newAutorenewBillingEvent(existingDomain)
            .setEventTime(newExpirationTime).setRecurrenceEndTime(END_OF_TIME).setParent(historyEntry).build();
    PollMessage.Autorenew autorenewPollMessage = newAutorenewPollMessage(existingDomain)
            .setEventTime(newExpirationTime).setAutorenewEndTime(END_OF_TIME).setParent(historyEntry).build();
    DomainResource newDomain = performRestore(existingDomain, newExpirationTime, autorenewEvent,
            autorenewPollMessage);
    updateForeignKeyIndexDeletionTime(newDomain);
    entitiesToSave.add(newDomain, historyEntry, autorenewEvent, autorenewPollMessage);
    ofy().save().entities(entitiesToSave.build());
    ofy().delete().key(existingDomain.getDeletePollMessage());
    dnsQueue.addDomainRefreshTask(existingDomain.getFullyQualifiedDomainName());
    return responseBuilder.setExtensions(
            createResponseExtensions(feesAndCredits.getRestoreCost(), feesAndCredits.getRenewCost(), feeUpdate))
            .build();
}

From source file:google.registry.model.common.TimeOfYear.java

License:Open Source License

/**
 * Constructs a {@link TimeOfYear} from a {@link DateTime}.
 *
 * <p>This handles leap years in an intentionally peculiar way by always treating February 29 as
 * February 28. It is impossible to construct a {@link TimeOfYear} for February 29th.
 *///from w w w . jav  a  2s  .c  o  m
public static TimeOfYear fromDateTime(DateTime dateTime) {
    DateTime nextYear = dateTime.plusYears(1); // This turns February 29 into February 28.
    TimeOfYear instance = new TimeOfYear();
    instance.timeString = String.format("%02d %02d %08d", nextYear.getMonthOfYear(), nextYear.getDayOfMonth(),
            nextYear.getMillisOfDay());
    return instance;
}

From source file:google.registry.model.common.TimeOfYear.java

License:Open Source License

/** Get the first {@link DateTime} with this month/day/millis that is at or after the start. */
public DateTime getNextInstanceAtOrAfter(DateTime start) {
    DateTime withSameYear = getDateTimeWithYear(start.getYear());
    return isAtOrAfter(withSameYear, start) ? withSameYear : withSameYear.plusYears(1);
}

From source file:google.registry.model.domain.DomainResource.java

License:Open Source License

/**
 * The logic in this method, which handles implicit server approval of transfers, very closely
 * parallels the logic in {@code DomainTransferApproveFlow} which handles explicit client
 * approvals./*ww w  .j a  v  a2  s . c om*/
 */
@Override
public DomainResource cloneProjectedAtTime(final DateTime now) {

    TransferData transferData = getTransferData();
    DateTime transferExpirationTime = transferData.getPendingTransferExpirationTime();

    // If there's a pending transfer that has expired, handle it.
    if (TransferStatus.PENDING.equals(transferData.getTransferStatus())
            && isBeforeOrAt(transferExpirationTime, now)) {
        // Project until just before the transfer time. This will handle the case of an autorenew
        // before the transfer was even requested or during the request period.
        // If the transfer time is precisely the moment that the domain expires, there will not be an
        // autorenew billing event (since we end the recurrence at transfer time and recurrences are
        // exclusive of their ending), and we can just proceed with the transfer.
        DomainResource domainAtTransferTime = cloneProjectedAtTime(transferExpirationTime.minusMillis(1));
        // If we are within an autorenew grace period, the transfer will subsume the autorenew. There
        // will already be a cancellation written in advance by the transfer request flow, so we don't
        // need to worry about billing, but we do need to reduce the number of years added to the
        // expiration time by one to account for the year added by the autorenew.
        int extraYears = transferData.getExtendedRegistrationYears();
        if (domainAtTransferTime.getGracePeriodStatuses().contains(GracePeriodStatus.AUTO_RENEW)) {
            extraYears--;
        }
        // Set the expiration, autorenew events, and grace period for the transfer. (Transfer ends
        // all other graces).
        Builder builder = domainAtTransferTime.asBuilder()
                // Extend the registration by the correct number of years from the expiration time that
                // was current on the domain right before the transfer, capped at 10 years from the
                // moment of the transfer.
                .setRegistrationExpirationTime(extendRegistrationWithCap(transferExpirationTime,
                        domainAtTransferTime.getRegistrationExpirationTime(), extraYears))
                // Set the speculatively-written new autorenew events as the domain's autorenew events.
                .setAutorenewBillingEvent(transferData.getServerApproveAutorenewEvent())
                .setAutorenewPollMessage(transferData.getServerApproveAutorenewPollMessage())
                // Set the grace period using a key to the prescheduled transfer billing event.  Not using
                // GracePeriod.forBillingEvent() here in order to avoid the actual datastore fetch.
                .setGracePeriods(ImmutableSet.of(GracePeriod.create(GracePeriodStatus.TRANSFER,
                        transferExpirationTime.plus(Registry.get(getTld()).getTransferGracePeriodLength()),
                        transferData.getGainingClientId(), transferData.getServerApproveBillingEvent())));
        // Set all remaining transfer properties.
        setAutomaticTransferSuccessProperties(builder, transferData);
        // Finish projecting to now.
        return builder.build().cloneProjectedAtTime(now);
    }

    // There is no transfer. Do any necessary autorenews.

    Builder builder = asBuilder();
    if (isBeforeOrAt(registrationExpirationTime, now)) {
        // Autorenew by the number of years between the old expiration time and now.
        DateTime lastAutorenewTime = leapSafeAddYears(registrationExpirationTime,
                new Interval(registrationExpirationTime, now).toPeriod().getYears());
        DateTime newExpirationTime = lastAutorenewTime.plusYears(1);
        builder.setRegistrationExpirationTime(newExpirationTime)
                .addGracePeriod(GracePeriod.createForRecurring(GracePeriodStatus.AUTO_RENEW,
                        lastAutorenewTime.plus(Registry.get(getTld()).getAutoRenewGracePeriodLength()),
                        getCurrentSponsorClientId(), autorenewBillingEvent));
    }

    // Remove any grace periods that have expired.
    DomainResource almostBuilt = builder.build();
    builder = almostBuilt.asBuilder();
    for (GracePeriod gracePeriod : almostBuilt.getGracePeriods()) {
        if (isBeforeOrAt(gracePeriod.getExpirationTime(), now)) {
            builder.removeGracePeriod(gracePeriod);
        }
    }

    // Handle common properties like setting or unsetting linked status. This also handles the
    // general case of pending transfers for other resource types, but since we've always handled
    // a pending transfer by this point that's a no-op for domains.
    projectResourceOntoBuilderAtTime(almostBuilt, builder, now);
    return builder.build();
}

From source file:google.registry.rde.DomainResourceToXjcConverter.java

License:Open Source License

/** Converts {@link TransferData} to {@link XjcRdeDomainTransferDataType}. */
private static XjcRdeDomainTransferDataType convertTransferData(TransferData model, DateTime domainExpires) {
    XjcRdeDomainTransferDataType bean = new XjcRdeDomainTransferDataType();
    bean.setTrStatus(XjcEppcomTrStatusType.fromValue(model.getTransferStatus().getXmlName()));
    bean.setReRr(RdeUtil.makeXjcRdeRrType(model.getGainingClientId()));
    bean.setAcRr(RdeUtil.makeXjcRdeRrType(model.getLosingClientId()));
    bean.setReDate(model.getTransferRequestTime());
    bean.setAcDate(model.getPendingTransferExpirationTime());
    if (model.getTransferStatus() == TransferStatus.PENDING) {
        int years = Optional.fromNullable(model.getExtendedRegistrationYears()).or(0);
        bean.setExDate(domainExpires.plusYears(years));
    } else {//from w  ww .ja v  a  2  s  . c  o  m
        bean.setExDate(domainExpires);
    }
    return bean;
}

From source file:google.registry.util.DateTimeUtils.java

License:Open Source License

/**
 * Adds years to a date, in the {@code Duration} sense of semantic years. Use this instead of
 * {@link DateTime#plusYears} to ensure that we never end up on February 29.
 *//*www.  j av  a2s .  com*/
public static DateTime leapSafeAddYears(DateTime now, int years) {
    checkArgument(years >= 0);
    return years == 0 ? now : now.plusYears(1).plusYears(years - 1);
}

From source file:graph.inference.module.LaterThanWorker.java

License:Open Source License

private Interval parseDate(DAGNode date, DateTime now) {
    String dateStr = date.toString();
    if (dateStr.equals("Now") || dateStr.equals("Now-Generally"))
        return new Interval(now.getMillis(), now.getMillis() + 1);
    if (dateStr.equals("Today-Indexical"))
        return new Interval(now.dayOfYear().roundFloorCopy(), now.dayOfYear().roundCeilingCopy());
    if (dateStr.equals("Tomorrow-Indexical")) {
        return new Interval(now.plusDays(1).dayOfYear().roundFloorCopy(),
                now.plusDays(1).dayOfYear().roundCeilingCopy());
    }/*from w  w  w .ja v  a2  s .co m*/
    if (dateStr.equals("Yesterday-Indexical")) {
        return new Interval(now.minusDays(1).dayOfYear().roundFloorCopy(),
                now.minusDays(1).dayOfYear().roundCeilingCopy());
    }
    if (dateStr.equals("TheYear-Indexical")) {
        return new Interval(now.year().roundFloorCopy(), now.year().roundCeilingCopy());
    }

    // Parse the date from the DAGNode
    String parsePattern = null;
    for (int i = DATE_PARSE_INTERVALS.length - 1; i >= 0; i--) {
        StringBuilder newPattern = new StringBuilder("(" + DATE_PARSE_INTERVALS[i]);
        if (parsePattern != null)
            newPattern.append(" " + parsePattern);
        newPattern.append(")");
        parsePattern = newPattern.toString();

        DateTimeFormatter dtf = DateTimeFormat.forPattern(parsePattern);
        try {
            DateTime dateTime = dtf.parseDateTime(dateStr);
            if (dateTime != null) {
                switch (i) {
                case 0:
                    return new Interval(dateTime.getMillis(),
                            dateTime.plusSeconds(1).minusMillis(1).getMillis());
                case 1:
                    return new Interval(dateTime.getMillis(),
                            dateTime.plusMinutes(1).minusMillis(1).getMillis());
                case 2:
                    return new Interval(dateTime.getMillis(), dateTime.plusHours(1).minusMillis(1).getMillis());
                case 3:
                    return new Interval(dateTime.getMillis(), dateTime.plusDays(1).minusMillis(1).getMillis());
                case 4:
                    return new Interval(dateTime.getMillis(),
                            dateTime.plusMonths(1).minusMillis(1).getMillis());
                case 5:
                    return new Interval(dateTime.getMillis(), dateTime.plusYears(1).minusMillis(1).getMillis());
                }
            }
        } catch (Exception e) {
        }
    }
    return null;
}