Example usage for org.joda.time DateTime withYear

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

Introduction

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

Prototype

public DateTime withYear(int year) 

Source Link

Document

Returns a copy of this datetime with the year field updated.

Usage

From source file:org.neotree.ui.view.DateTimeFieldView.java

License:Open Source License

@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
    DateTime value = getValue();/*from ww w  .j av  a  2s.  c o m*/
    // TODO: Decide on what is the most sensible default
    //DateTime baseDate = (value != null) ? value : DateTime.now().withTimeAtStartOfDay();
    DateTime baseDate = (value != null) ? value : DateTime.now().withTime(12, 0, 0, 0);
    value = baseDate.withYear(year).withMonthOfYear(monthOfYear + 1).withDayOfMonth(dayOfMonth);
    setValue(value);
}

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/*from w  w  w .j  a va2s .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

/**
 * Gets the current hour, minute and second from a dublin core period if available.
 *
 * @param period/*from  w  ww.j  av  a 2 s  . co  m*/
 *          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//from  w ww. j ava  2 s.c o 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.opendaylight.streamhandler.impl.KafkaStreamProducer.java

License:Open Source License

/**
 * @param timeStamp//from  ww  w  .  j av a2 s  .c o  m
 *            timestamp.
 * @return long
 *           return rfc3164TimeStamp.
 */
protected long rfc3164TimeStamp(String timeStamp) {
    DateTime currentDateTime = DateTime.now();
    int yearCurrent = currentDateTime.getYear();
    timeStamp = SPACES_TWO_CHECK.matcher(timeStamp).replaceFirst(" ");
    DateTime dateReturned;
    try {
        dateReturned = RFC3164_FORMAT_DATETIME.parseDateTime(timeStamp);
    } catch (IllegalArgumentException e) {
        log.error("rfc3164 date parse failed on (" + timeStamp + "): invalid format", e);
        return 0;
    }
    if (dateReturned != null) {
        DateTime fixedDate = dateReturned.withYear(yearCurrent);
        if (fixedDate.isAfter(currentDateTime) && fixedDate.minusMonths(1).isAfter(currentDateTime)) {
            fixedDate = dateReturned.withYear(yearCurrent - 1);
        } else if (fixedDate.isBefore(currentDateTime) && fixedDate.plusMonths(1).isBefore(currentDateTime)) {
            fixedDate = dateReturned.withYear(yearCurrent + 1);
        }
        dateReturned = fixedDate;
    }
    if (dateReturned == null) {
        return 0;
    }
    return dateReturned.getMillis();
}

From source file:org.opendaylight.streamhandler.impl.LogCollector.java

License:Open Source License

protected long rfc3164TimeStamp(String timeStamp) {
    DateTime currentDateTime = DateTime.now();
    int yearCurrent = currentDateTime.getYear();
    timeStamp = SPACES_TWO_CHECK.matcher(timeStamp).replaceFirst(" ");
    DateTime dateReturned;
    try {/*from  ww w  .  j  a v a 2s  . c o m*/
        dateReturned = RFC3164_FORMAT_DATETIME.parseDateTime(timeStamp);
    } catch (IllegalArgumentException e) {
        LOG.error("rfc3164 date parse failed on (" + timeStamp + "): invalid format", e);
        return 0;
    }
    if (dateReturned != null) {
        DateTime fixedDate = dateReturned.withYear(yearCurrent);
        if (fixedDate.isAfter(currentDateTime) && fixedDate.minusMonths(1).isAfter(currentDateTime)) {
            fixedDate = dateReturned.withYear(yearCurrent - 1);
        } else if (fixedDate.isBefore(currentDateTime) && fixedDate.plusMonths(1).isBefore(currentDateTime)) {
            fixedDate = dateReturned.withYear(yearCurrent + 1);
        }
        dateReturned = fixedDate;
    }
    if (dateReturned == null) {
        return 0;
    }
    return dateReturned.getMillis();
}

From source file:org.opendaylight.streamhandler.impl.LogCollectorTLS.java

License:Open Source License

protected long rfc3164TimeStamp(String timeStamp) {
    DateTime currentDateTime = DateTime.now();
    int yearCurrent = currentDateTime.getYear();
    timeStamp = SPACES_TWO_CHECK.matcher(timeStamp).replaceFirst(" ");
    DateTime dateReturned;
    try {//w ww. ja  va 2  s  .c  om
        dateReturned = rfc3164_FORMAT_DATETIME.parseDateTime(timeStamp);
    } catch (IllegalArgumentException e) {
        LOG.error("rfc3164 date parse failed on (" + timeStamp + "): invalid format", e);
        return 0;
    }
    if (dateReturned != null) {
        DateTime fixedDate = dateReturned.withYear(yearCurrent);
        if (fixedDate.isAfter(currentDateTime) && fixedDate.minusMonths(1).isAfter(currentDateTime)) {
            fixedDate = dateReturned.withYear(yearCurrent - 1);
        } else if (fixedDate.isBefore(currentDateTime) && fixedDate.plusMonths(1).isBefore(currentDateTime)) {
            fixedDate = dateReturned.withYear(yearCurrent + 1);
        }
        dateReturned = fixedDate;
    }
    if (dateReturned == null) {
        return 0;
    }
    return dateReturned.getMillis();
}

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  a  2 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.os.parser.LinuxSyslogYearSetter.java

License:Open Source License

/**
 * This method returns the year of the current message. First it makes a clone of the current date.
 * Then we obtain the milliseconds for the current date and the last message's date and calculate 
 * the message time difference. Depending on the difference, return the year appropriately.
 * @param currentMessageDate the current date of the message.
 * @return the year of the message./*from w  w  w  . ja  v a 2 s  .  c o m*/
 */
public final int getDesiredYear(DateTime currentMessageDate) {
    int yearToReturn;
    DateTime curMessageDate = new DateTime(currentMessageDate);
    curMessageDate = curMessageDate.withYear(m_currentYear);
    if (m_lastSeenMessageDate == null) {
        m_lastSeenMessageDate = curMessageDate;
    }
    final long curDateMillis = curMessageDate.getMillis();
    final long lastDateMillis = m_lastSeenMessageDate.getMillis();
    final long messageTimeDiff = curDateMillis - lastDateMillis;

    if (messageTimeDiff < 0) {
        /* cur message timestamp < last message timestamp.  There are two cases: */
        if (Math.abs(messageTimeDiff) < DECREMENT_DAYS_ALLOWANCE_IN_MILLIS) {
            /* Case: Message time goes backwards (maybe by a few minutes).   
             * The year is set to current year. */
            yearToReturn = m_currentYear;
        } else {
            /* Case: Year N to Year N+1.  
             * - Message time goes from Year N to Year N+1 (e.g. actual situation is 12/31/2001 to 1/1/2002, 
             *   and our test will compare 12/31/2001 and 1/1/2001)
             */
            m_currentYear++;
            curMessageDate = curMessageDate.withYear(m_currentYear);
            yearToReturn = m_currentYear;
            m_lastSeenMessageDate = curMessageDate;
            final String msg = m_source + ": Year increase by 1, to " + m_currentYear;
            LinuxSyslog3164ParserBase.s_logger.info(msg);
        }
    } else {
        /* last message timestamp < cur message timestamp. There are two cases:
         */
        if (messageTimeDiff < INCREMENT_DAYS_LIMIT_IN_MILLIS) {
            /* Case: The log time is increasing normally. In case of a missing log, we allow a specific limit, 
             * such as 300 days. */
            yearToReturn = m_currentYear;
            m_lastSeenMessageDate = curMessageDate;
        } else {
            /* Case: Message time goes from Year N to Year N-1 (e.g. actual situation is 1/1/2002 to 
             * 12/31/2001, and out test will compare 1/1/2002 and 12/31/2002.)
             * In this case, we don't change the m_currentYear.
             */
            yearToReturn = m_currentYear - 1;
        }
    }
    return yearToReturn;
}

From source file:stroom.streamstore.server.tools.StoreCreationTool.java

License:Apache License

/**
 * Adds reference data to a stream store.
 *
 * @param feedName/* w  w w .j  a va 2  s .c o  m*/
 *            The feed name to use.
 * @param formatDefLocation
 *            The XML conversion to use.
 * @param xsltLocation
 *            The XSLT location.
 * @param dataLocation
 *            The reference data location.
 * @return A reference feed definition.
 * @throws IOException
 *             Thrown if files not found.
 */
public Feed addReferenceData(final String feedName, final TextConverterType textConverterType,
        final File textConverterLocation, final File xsltLocation, final File dataLocation) throws IOException {
    commonTestControl.createRequiredXMLSchemas();

    final Feed referenceFeed = getRefFeed(feedName, textConverterType, textConverterLocation, xsltLocation);

    // We need to ensure the reference data is older then the earliest event
    // we are going to see.
    DateTime dateTime = new DateTime();
    dateTime = dateTime.withYear(OLD_YEAR);
    long effectiveMs = dateTime.getMillis();

    // Always make sure effective date is unique.
    effectiveMs += effectiveMsOffset++;

    // Add the associated data to the stream store.
    final Stream stream = Stream.createStreamForTesting(StreamType.RAW_REFERENCE, referenceFeed, effectiveMs,
            effectiveMs);

    final String data = StreamUtil.fileToString(dataLocation);

    final StreamTarget target = streamStore.openStreamTarget(stream);

    final InputStream inputStream = new ByteArrayInputStream(data.getBytes());
    final RASegmentOutputStream outputStream = new RASegmentOutputStream(target);

    final RawInputSegmentWriter writer = new RawInputSegmentWriter();
    writer.write(inputStream, outputStream);

    streamStore.closeStreamTarget(target);

    final StreamSource checkSource = streamStore.openStreamSource(stream.getId());
    Assert.assertEquals(data, StreamUtil.streamToString(checkSource.getInputStream()));
    streamStore.closeStreamSource(checkSource);

    return referenceFeed;
}