Example usage for org.joda.time DateTime withZone

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

Introduction

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

Prototype

public DateTime withZone(DateTimeZone newZone) 

Source Link

Document

Returns a copy of this datetime with a different time zone, preserving the millisecond instant.

Usage

From source file:org.opencastproject.index.service.catalog.adapter.DublinCoreMetadataUtil.java

License:Educational Community License

/**
 * Gets the current hour, minute and second from a dublin core period if available.
 *
 * @param period/* w ww . jav a2s .c om*/
 *          The current period from dublin core.
 * @return A new DateTime with the current hour, minute and second.
 */
static DateTime getCurrentStartTime(Opt<DCMIPeriod> period) {
    DateTime currentStartTime = new DateTime();
    currentStartTime = currentStartTime.withZone(DateTimeZone.UTC);
    currentStartTime = currentStartTime.withHourOfDay(0);
    currentStartTime = currentStartTime.withMinuteOfHour(0);
    currentStartTime = currentStartTime.withSecondOfMinute(0);

    if (period.isSome() && period.get().hasStart()) {
        DateTime fromDC = new DateTime(period.get().getStart().getTime());
        fromDC = fromDC.withZone(DateTimeZone.UTC);
        currentStartTime = currentStartTime.withZone(DateTimeZone.UTC);
        currentStartTime = currentStartTime.withHourOfDay(fromDC.getHourOfDay());
        currentStartTime = currentStartTime.withMinuteOfHour(fromDC.getMinuteOfHour());
        currentStartTime = currentStartTime.withSecondOfMinute(fromDC.getSecondOfMinute());
    }
    return currentStartTime;
}

From source file:org.opencastproject.index.service.catalog.adapter.DublinCoreMetadataUtil.java

License:Educational Community License

/**
 * Gets the current hour, minute and second from a dublin core period if available.
 *
 * @param period/* w w w . ja  v  a 2  s .  c o  m*/
 *          The current period from dublin core.
 * @return A new DateTime with the current hour, minute and second.
 */
static DateTime getCurrentStartDate(Opt<DCMIPeriod> period) {
    DateTime currentStartDate = new DateTime();
    currentStartDate = currentStartDate.withZone(DateTimeZone.UTC);
    currentStartDate = currentStartDate.withYear(2001);
    currentStartDate = currentStartDate.withMonthOfYear(1);
    currentStartDate = currentStartDate.withDayOfMonth(1);

    if (period.isSome() && period.get().hasStart()) {
        DateTime fromDC = new DateTime(period.get().getStart().getTime());
        fromDC = fromDC.withZone(DateTimeZone.UTC);
        currentStartDate = currentStartDate.withZone(DateTimeZone.UTC);
        currentStartDate = currentStartDate.withYear(fromDC.getYear());
        currentStartDate = currentStartDate.withMonthOfYear(fromDC.getMonthOfYear());
        currentStartDate = currentStartDate.withDayOfMonth(fromDC.getDayOfMonth());
    }
    return currentStartDate;
}

From source file:org.opencastproject.index.service.catalog.adapter.DublinCoreMetadataUtil.java

License:Educational Community License

/**
 * Sets the start date in a dublin core catalog to the right value and keeps the start time and duration the same.
 *
 * @param dc// w  w  w.  ja  va  2 s . c om
 *          The dublin core catalog to adjust
 * @param field
 *          The metadata field that contains the start date.
 * @param ename
 *          The EName in the catalog to identify the property that has the dublin core period.
 */
static void setTemporalStartDate(DublinCoreCatalog dc, MetadataField<?> field, EName ename) {
    if (field.getValue().isNone() || (field.getValue().get() instanceof String
            && StringUtils.isBlank(field.getValue().get().toString()))) {
        logger.debug("No value was set for metadata field with dublin core id '{}' and json id '{}'",
                field.getInputID(), field.getOutputID());
        return;
    }
    try {
        // Get the current date
        SimpleDateFormat dateFormat = MetadataField.getSimpleDateFormatter(field.getPattern().get());
        Date startDate = dateFormat.parse((String) field.getValue().get());
        // Get the current period
        Opt<DCMIPeriod> period = getPeriodFromCatalog(dc, ename);
        // Get the current duration
        Long duration = getDuration(period);
        // Get the current start time hours, minutes and seconds
        DateTime currentStartTime = getCurrentStartTime(period);
        // Setup the new start time
        DateTime startDateTime = new DateTime(startDate.getTime());
        startDateTime = startDateTime.withZone(DateTimeZone.UTC);
        startDateTime = startDateTime.withHourOfDay(currentStartTime.getHourOfDay());
        startDateTime = startDateTime.withMinuteOfHour(currentStartTime.getMinuteOfHour());
        startDateTime = startDateTime.withSecondOfMinute(currentStartTime.getSecondOfMinute());
        // Get the current end date based on new date and duration.
        DateTime endDate = new DateTime(startDateTime.toDate().getTime() + duration);
        dc.set(ename, EncodingSchemeUtils.encodePeriod(new DCMIPeriod(startDateTime.toDate(), endDate.toDate()),
                Precision.Second));
    } catch (ParseException e) {
        logger.error("Not able to parse date {} to update the dublin core because: {}", field.getValue(),
                ExceptionUtils.getStackTrace(e));
    }
}

From source file:org.opencastproject.index.service.catalog.adapter.DublinCoreMetadataUtil.java

License:Educational Community License

/**
 * Gets the current hour, minute and second from a dublin core period if available.
 *
 * @param period/* w ww. j  av a2s  . c  om*/
 *          The current period from dublin core.
 * @return A new DateTime with the current hour, minute and second.
 */
private static DateTime getCurrentStartDateTime(Opt<DCMIPeriod> period) {
    DateTime currentStartTime = new DateTime();
    currentStartTime = currentStartTime.withZone(DateTimeZone.UTC);
    currentStartTime = currentStartTime.withYear(2001);
    currentStartTime = currentStartTime.withMonthOfYear(1);
    currentStartTime = currentStartTime.withDayOfMonth(1);
    currentStartTime = currentStartTime.withHourOfDay(0);
    currentStartTime = currentStartTime.withMinuteOfHour(0);
    currentStartTime = currentStartTime.withSecondOfMinute(0);

    if (period.isSome() && period.get().hasStart()) {
        DateTime fromDC = new DateTime(period.get().getStart().getTime());
        fromDC = fromDC.withZone(DateTimeZone.UTC);
        currentStartTime = currentStartTime.withZone(DateTimeZone.UTC);
        currentStartTime = currentStartTime.withYear(fromDC.getYear());
        currentStartTime = currentStartTime.withMonthOfYear(fromDC.getMonthOfYear());
        currentStartTime = currentStartTime.withDayOfMonth(fromDC.getDayOfMonth());
        currentStartTime = currentStartTime.withHourOfDay(fromDC.getHourOfDay());
        currentStartTime = currentStartTime.withMinuteOfHour(fromDC.getMinuteOfHour());
        currentStartTime = currentStartTime.withSecondOfMinute(fromDC.getSecondOfMinute());
    }
    return currentStartTime;
}

From source file:org.opencastproject.index.service.catalog.adapter.DublinCoreMetadataUtil.java

License:Educational Community License

/**
 * Sets the start time in a dublin core catalog to the right value and keeps the start date and duration the same.
 *
 * @param dc// w  w  w .ja v a2  s  . co  m
 *          The dublin core catalog to adjust
 * @param field
 *          The metadata field that contains the start time.
 * @param ename
 *          The EName in the catalog to identify the property that has the dublin core period.
 */
static void setTemporalStartTime(DublinCoreCatalog dc, MetadataField<?> field, EName ename) {
    if (field.getValue().isNone() || (field.getValue().get() instanceof String
            && StringUtils.isBlank(field.getValue().get().toString()))) {
        logger.debug("No value was set for metadata field with dublin core id '{}' and json id '{}'",
                field.getInputID(), field.getOutputID());
        return;
    }
    try {
        // Get the current date
        SimpleDateFormat dateFormat = MetadataField.getSimpleDateFormatter(field.getPattern().get());
        Date startDate = dateFormat.parse((String) field.getValue().get());
        // Get the current period
        Opt<DCMIPeriod> period = getPeriodFromCatalog(dc, ename);
        // Get the current duration
        Long duration = getDuration(period);
        // Get the current start date
        DateTime currentStartDate = getCurrentStartDate(period);
        // Setup the new start time
        DateTime startDateTime = new DateTime(startDate.getTime());
        startDateTime = startDateTime.withZone(DateTimeZone.UTC);
        startDateTime = startDateTime.withYear(currentStartDate.getYear());
        startDateTime = startDateTime.withMonthOfYear(currentStartDate.getMonthOfYear());
        startDateTime = startDateTime.withDayOfMonth(currentStartDate.getDayOfMonth());

        // Get the current end date based on new date and duration.
        DateTime endDate = new DateTime(startDateTime.toDate().getTime() + duration);
        dc.set(ename, EncodingSchemeUtils.encodePeriod(new DCMIPeriod(startDateTime.toDate(), endDate.toDate()),
                Precision.Second));
    } catch (ParseException e) {
        logger.error("Not able to parse date {} to update the dublin core because: {}", field.getValue(),
                ExceptionUtils.getStackTrace(e));
    }
}

From source file:org.openmainframe.ade.ext.os.parser.LinuxSyslog3164ParserBase.java

License:Open Source License

/**
 * Retrieves the date parsed from the header of a log. Unless otherwise defined in the properties file,
 * we have to use some logic to figure out the year. After parsing the date, we need to correct the time-zone. 
 * Then we set the dateTime to the current year. Now we need to check the dateTime and see if it's after today.
 * The logic is as follows://from   w  w w  .j  a v  a2  s . c  o  m
 *      - If Log time-stamp < End of day of today 
 *          (comparing Month, Day, Hour, Minutes, Seconds, with year missing), 
 *          assume it's this year.
 *      - If Log time-stamp > End of day of today 
 *          (comparing Month, Day, Hour, Minutes, Seconds, with year missing), 
 *          assume it's previous year.
 * 
 * The following restrictions will be made to customer for BulkLoad:
 *      - Cannot upload logs older than 11 months.
 *      - Cannot upload logs that are continuous for more than 11 months.
 * 
 * Note: END OF TODAY is purposely chosen instead of START OF TODAY in case a user bulk loads logs that 
 * belongs to today.  It's not possible/likely that a user would bulk load logs from last year of the 
 * same day with the restriction we specified above.
 * @param source the source name string value.
 * @param s the date and time string value.
 * @return Date object with date/time-stamp of the Linux log.
 */
@Override
public final Date toDate(String source, String s) {
    DateTime dt = null;
    for (DateTimeFormatter fmt : dt_formatters) {
        try {
            dt = fmt.parseDateTime(s);
            dt = dt.withZoneRetainFields(INPUT_TIME_ZONE);
            dt = dt.withZone(OUTPUT_TIME_ZONE);

            /* Year must be set after all the time is normalized to the timezone */
            dt = dt.withYear(curYear);

            if (s_linuxAdeExtProperties.isYearDefined()) {
                yearSetter = LinuxSyslogYearSetter.getYearSetter(source);

                /* If years is defined, then, use the defined year as a starting year */
                final int yearToUse = yearSetter.getDesiredYear(dt);
                dt = dt.withYear(yearToUse);
            } else if (dt.isAfter(END_OF_TODAY)) {
                /* Set DateTime to previous year */
                dt = dt.withYear(curYear - 1);
            } else {
                dt = dt.withYear(curYear);
            }

            /* AdeCore will take the Java Date object, and convert 
             * it to the output time-zone, then extract the hour. */
            return dt.toDate();
        } catch (IllegalArgumentException e) {
            /* This exception can occur normally when iterating
             * through the DateTimeFormatter objects. It is only 
             * an error worth noting when the dt object is not null.
             */
            if (dt != null) {
                s_logger.error("Invalid argument encountered.", e);
            }
        }
    }
    throw new IllegalArgumentException("Failed to parse date " + s);
}

From source file:org.openmainframe.ade.ext.utils.ExtDateTimeUtils.java

License:Open Source License

/**
 * Method to return a "normalized" version of the input Date
 * whose time is reset to the absolute start of that same day
 * (first millisecond of first second of first minute of first hour).
 *    /*from   w  w  w.  j  ava2s . c  o  m*/
 * @param dateInst - instance of Date
 * @return - instance of Date as described
 * @throws AdeException 
 */
public static Date startOfDayUsingOutputTimeZone(Date dateInst) throws AdeException {

    if (outputTimeZone == null) {
        final TimeZone outputTimezone = Ade.getAde().getConfigProperties().getOutputTimeZone();
        outputTimeZone = DateTimeZone.forOffsetMillis(outputTimezone.getRawOffset());
    }

    if (dateInst == null) {
        throw new IllegalArgumentException();
    }

    /* Set start of today */
    DateTime startOFDay = new DateTime(dateInst);
    startOFDay = startOFDay.withZone(outputTimeZone);
    startOFDay = startOFDay.withTimeAtStartOfDay();

    return startOFDay.toDate();

}

From source file:org.openmainframe.ade.ext.utils.ExtDateTimeUtils.java

License:Open Source License

/**
 * Method to return a "normalized" version of the input Date
 * whose time is reset to the absolute start of that same day
 * (first millisecond of first second of first minute of first hour).
 *    //from  w w w  .  ja va  2 s .  com
 * @param dateInst - instance of Date
 * @return - instance of Date as described
 * @throws AdeException 
 */
public static Date endOfDayUsingOutputTimeZone(Date dateInst) throws AdeException {

    /* 
     * Note: This method generates a different end of day compare to endOfDay().
     * endOfDay() would generate timestamp: 10/10/2013 23:59:59
     * endOfDayUsingOutputTimeZone() would generate timestampe: 10/11/2013 00:00:00
     */

    if (outputTimeZone == null) {
        final TimeZone outputTimezone = Ade.getAde().getConfigProperties().getOutputTimeZone();
        outputTimeZone = DateTimeZone.forOffsetMillis(outputTimezone.getRawOffset());
    }

    if (dateInst == null) {
        throw new IllegalArgumentException();
    }

    /* Set end of today */
    DateTime startOFDay = new DateTime(dateInst);
    startOFDay = startOFDay.withZone(outputTimeZone);
    startOFDay = startOFDay.plusDays(1);
    startOFDay = startOFDay.withTimeAtStartOfDay();

    return startOFDay.toDate();

}

From source file:org.opensaml.common.impl.AbstractSAMLObject.java

License:Open Source License

/**
 * A helper function for derived classes that checks to see if the old and new value are equal and if so releases
 * the cached dom. Derived classes are expected to use this thus: <code>
 *   this.foo = prepareForAssignment(this.foo, foo);
 *   </code>/*from  www  .  ja  v a  2 s  .  com*/
 * 
 * This method will do a (null) safe compare of the objects and will also invalidate the DOM if appropriate
 * 
 * @param oldValue - current value
 * @param newValue - proposed new value
 * 
 * @return The value to assign to the saved Object.
 */
protected DateTime prepareForAssignment(DateTime oldValue, DateTime newValue) {
    DateTime utcValue = null;
    if (newValue != null) {
        utcValue = newValue.withZone(DateTimeZone.UTC);
    }

    return super.prepareForAssignment(oldValue, utcValue);
}

From source file:org.opensaml.saml.common.AbstractSAMLObject.java

License:Open Source License

/**
 * A helper function for derived classes that checks to see if the old and new value are equal and if so releases
 * the cached dom. Derived classes are expected to use this thus: <code>
 *   this.foo = prepareForAssignment(this.foo, foo);
 *   </code>/*from  w ww  .  j a  v a  2s . co  m*/
 * 
 * This method will do a (null) safe compare of the objects and will also invalidate the DOM if appropriate
 * 
 * @param oldValue - current value
 * @param newValue - proposed new value
 * 
 * @return The value to assign to the saved Object.
 */
@Nullable
protected DateTime prepareForAssignment(@Nullable final DateTime oldValue, @Nullable final DateTime newValue) {
    DateTime utcValue = null;
    if (newValue != null) {
        utcValue = newValue.withZone(DateTimeZone.UTC);
    }

    return super.prepareForAssignment(oldValue, utcValue);
}