Example usage for org.joda.time DateTime getMillisOfSecond

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

Introduction

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

Prototype

public int getMillisOfSecond() 

Source Link

Document

Get the millis of second field value.

Usage

From source file:org.openmainframe.ade.ext.main.VerifyLinuxTraining.java

License:Open Source License

/**
 * Count the number of occurences of unique messages IDs in the given time range
 * for all of the sources, assumed to be from a single model group.
 * Also sets the member variables for the number of intervals and the number
 * of intervals containing messages./*w  ww  .ja v  a  2  s . co m*/
 *
 * @param sourceSet
 * @param start
 * @param end
 *
 * @return MessageMetrics - interesting data to use in computing whether the training can proceed.
 *
 * @throws AdeException
 */
private static MessageMetrics computeMessageMetrics(Ade ade, Set<ISource> sourceSet, Date start, Date end)
        throws AdeException {
    int numIntervals = 0;
    int numIntervalsWithMessages = 0;
    final Map<Integer, Integer> occurrence = new HashMap<Integer, Integer>();

    System.out.println("Start computeMessageMetrics ");

    /*
     * Get data from the database
     *
     * get list of periods from start date to end date for each source
     */
    final Collection<IPeriod> periods = new ArrayList<IPeriod>();
    for (ISource source : sourceSet) {
        periods.addAll(Ade.getAde().getDataStore().periods().getAllPeriods(source, start, end));
    }

    /* return if no periods */
    if (periods.isEmpty()) {
        return new MessageMetrics(0, 0, 0);
    }

    /* extract data from the database for each period */
    final List<IInterval> curIntervals = new ArrayList<IInterval>();
    final Comparator<IInterval> intervalComparator = new Comparator<IInterval>() {
        @Override
        public int compare(IInterval int1, IInterval int2) {
            final long diff = int1.getIntervalStartTime() - int2.getIntervalStartTime();

            // Casting to an int isn't a shortcut here.
            if (diff < 0) {
                return -1;
            } else if (diff > 0) {
                return 1;
            } else {
                return 0;
            }
        }
    };

    // Periods are days. 120 with default training params for Linux.
    for (IPeriod period : periods) {
        final FramingFlowType framingFlowType = Ade.getAde().getFlowFactory().getFlowByName("LINUX")
                .getMyFramingFlows().get("tenMinutesTrain");
        final IAdeIterator<IInterval> iterator = ade.getDataStore().periods().getPeriodIntervals(period,
                framingFlowType);

        try {
            /* For each interval update count of messages
             *   fetch data
             */
            curIntervals.clear();
            iterator.open();

            // Because intervals overlap (each includes 50 minutes of the previous interval),
            // we only want to count one interval with messages per hour so sort the intervals
            // by time and make sure that intervals in the same hour don't increases the amount
            // of messages multiple times
            IInterval curInt;
            while ((curInt = iterator.getNext()) != null) {
                curIntervals.add(curInt);
            }

            Collections.sort(curIntervals, intervalComparator);

            // We need the total number of intervals for notification messages.
            numIntervals += curIntervals.size();

            DateTime lastIntervalTime = null;
            boolean addedMessage = false;

            for (IInterval curInterval : curIntervals) {
                // Check to see if this interval is for the same hour as the previously processed one,
                // if it's not set it as the new interval and allow the amount of intervals with messages
                // to be incremented
                if (lastIntervalTime == null) {
                    lastIntervalTime = new DateTime(curInterval.getIntervalStartTime());
                } else {
                    DateTime currentIntervalTime = new DateTime(curInterval.getIntervalStartTime());
                    currentIntervalTime = currentIntervalTime
                            .minusMinutes(currentIntervalTime.getMinuteOfHour())
                            .minusSeconds(currentIntervalTime.getSecondOfMinute())
                            .minusMillis(currentIntervalTime.getMillisOfSecond());

                    if (!lastIntervalTime.isEqual(currentIntervalTime)) {
                        lastIntervalTime = currentIntervalTime;
                        addedMessage = false;
                    }
                }

                final Collection<IMessageSummary> msgSummaries = curInterval.getMessageSummaries();
                if (!msgSummaries.isEmpty() && !addedMessage) {
                    numIntervalsWithMessages++;
                    addedMessage = true;
                }
                for (IMessageSummary msgSummary : msgSummaries) {
                    final int msgID = msgSummary.getMessageInternalId();
                    if (occurrence.containsKey(msgID)) {
                        /* get number of occurrences for this msgID (internal msgID)
                         * increment it and put back again */
                        occurrence.put(msgID, occurrence.get(msgID) + 1);
                    } else {
                        /* this is first time we see this word, set value '1' */
                        occurrence.put(msgID, 1);
                    }
                }
            }
            iterator.close();
        } finally {
            iterator.quietCleanup();
        }
    }

    return new MessageMetrics(occurrence.size(), numIntervalsWithMessages, numIntervals);
}

From source file:org.opensmartgridplatform.adapter.protocol.dlms.domain.commands.DlmsHelperService.java

License:Open Source License

/**
 * Creates a COSEM date-time object based on the given {@code dateTime}.
 * <p>//from w  w  w  .ja va 2 s .  c o m
 * The deviation and clock status (is daylight saving active or not) are
 * based on the zone of the given {@code dateTime}.
 * <p>
 * To use a DateTime as indication of the instant of time to be used with a
 * specific deviation (that does not have to match the zone of the
 * DateTime), use {@link #asDataObject(DateTime, int, boolean)} instead.
 *
 * @param dateTime
 *            a DateTime to translate into COSEM date-time format.
 * @return a DataObject having a CosemDateTime matching the given DateTime
 *         as value.
 */
public DataObject asDataObject(final DateTime dateTime) {

    final CosemDate cosemDate = new CosemDate(dateTime.getYear(), dateTime.getMonthOfYear(),
            dateTime.getDayOfMonth());
    final CosemTime cosemTime = new CosemTime(dateTime.getHourOfDay(), dateTime.getMinuteOfHour(),
            dateTime.getSecondOfMinute(), dateTime.getMillisOfSecond() / 10);
    final int deviation = -(dateTime.getZone().getOffset(dateTime.getMillis()) / MILLISECONDS_PER_MINUTE);
    final ClockStatus[] clockStatusBits;
    if (dateTime.getZone().isStandardOffset(dateTime.getMillis())) {
        clockStatusBits = new ClockStatus[0];
    } else {
        clockStatusBits = new ClockStatus[1];
        clockStatusBits[0] = ClockStatus.DAYLIGHT_SAVING_ACTIVE;
    }
    final CosemDateTime cosemDateTime = new CosemDateTime(cosemDate, cosemTime, deviation, clockStatusBits);
    return DataObject.newDateTimeData(cosemDateTime);
}

From source file:org.opensmartgridplatform.adapter.protocol.dlms.domain.commands.DlmsHelperService.java

License:Open Source License

/**
 * Creates a COSEM date-time object based on the given {@code dateTime}.
 * This COSEM date-time will be for the same instant in time as the given
 * {@code dateTime} but may be for another time zone.
 * <p>//from ww  w  .  j  a v  a  2s.c o m
 * Because the time zone with the {@code deviation} may be different than
 * the one with the {@code dateTime}, and the {@code deviation} alone does
 * not provide sufficient information on whether daylight savings is active
 * for the given instant in time, {@code dst} has to be provided to indicate
 * whether daylight savings are active.
 * <p>
 * If a DateTime for an instant in time is known with the correct time zone
 * set, you can use {@link #asDataObject(DateTime)} as a simpler
 * alternative.
 *
 * @param dateTime
 *            a DateTime indicating an instant in time to be used for the
 *            COSEM date-time.
 * @param deviation
 *            the deviation in minutes of local time to GMT to be included
 *            in the COSEM date-time.
 * @param dst
 *            {@code true} if daylight savings are active for the instant of
 *            the COSEM date-time, otherwise {@code false}.
 * @return a DataObject having a CosemDateTime for the instant of the given
 *         DateTime, with the given deviation and DST status information, as
 *         value.
 */
public DataObject asDataObject(final DateTime dateTime, final int deviation, final boolean dst) {
    /*
     * Create a date time that may not point to the right instant in time,
     * but that will give proper values getting the different fields for the
     * COSEM date and time objects.
     */
    final DateTime dateTimeWithOffset = dateTime.toDateTime(DateTimeZone.UTC).minusMinutes(deviation);
    final CosemDate cosemDate = new CosemDate(dateTimeWithOffset.getYear(), dateTimeWithOffset.getMonthOfYear(),
            dateTimeWithOffset.getDayOfMonth());
    final CosemTime cosemTime = new CosemTime(dateTimeWithOffset.getHourOfDay(),
            dateTimeWithOffset.getMinuteOfHour(), dateTimeWithOffset.getSecondOfMinute(),
            dateTimeWithOffset.getMillisOfSecond() / 10);
    final ClockStatus[] clockStatusBits;

    if (dst) {
        clockStatusBits = new ClockStatus[1];
        clockStatusBits[0] = ClockStatus.DAYLIGHT_SAVING_ACTIVE;
    } else {
        clockStatusBits = new ClockStatus[0];
    }
    final CosemDateTime cosemDateTime = new CosemDateTime(cosemDate, cosemTime, deviation, clockStatusBits);
    return DataObject.newDateTimeData(cosemDateTime);
}

From source file:org.rockholla.date.DateUtility.java

License:Open Source License

/**
 * Returns a unique string based on a timestamp (DateTime must be precise to the second
 * to ensure uniqueness)//from  w  ww. ja va 2  s.  c  o m
 * 
 * @param dateTime   the org.joda.time.DateTime to use to create the ID
 * @return         a unique string representation of the date
 */
public static String getTimestampId(DateTime dateTime) {

    String id = "";

    id = NumberUtility.format(dateTime.getYear(), NumberUtility.FORMAT.TWO_CHARACTER_INTEGER)
            + NumberUtility.format(dateTime.getMonthOfYear(), NumberUtility.FORMAT.TWO_CHARACTER_INTEGER)
            + NumberUtility.format(dateTime.getDayOfMonth(), NumberUtility.FORMAT.TWO_CHARACTER_INTEGER)
            + NumberUtility.format(dateTime.getHourOfDay(), NumberUtility.FORMAT.TWO_CHARACTER_INTEGER)
            + NumberUtility.format(dateTime.getMinuteOfHour(), NumberUtility.FORMAT.TWO_CHARACTER_INTEGER)
            + NumberUtility.format(dateTime.getSecondOfMinute(), NumberUtility.FORMAT.TWO_CHARACTER_INTEGER)
            + NumberUtility.format(dateTime.getMillisOfSecond(), NumberUtility.FORMAT.TWO_CHARACTER_INTEGER);

    return id;

}

From source file:org.talend.components.netsuite.AbstractNetSuiteTestBase.java

License:Open Source License

protected static XMLGregorianCalendar composeDateTime() throws Exception {
    DateTime dateTime = DateTime.now();

    XMLGregorianCalendar xts = datatypeFactory.newXMLGregorianCalendar();
    xts.setYear(dateTime.getYear());//from ww  w.  j  a  v  a  2s. c om
    xts.setMonth(dateTime.getMonthOfYear());
    xts.setDay(dateTime.getDayOfMonth());
    xts.setHour(dateTime.getHourOfDay());
    xts.setMinute(dateTime.getMinuteOfHour());
    xts.setSecond(dateTime.getSecondOfMinute());
    xts.setMillisecond(dateTime.getMillisOfSecond());
    xts.setTimezone(dateTime.getZone().toTimeZone().getRawOffset() / 60000);

    return xts;

}

From source file:org.talend.components.netsuite.client.model.search.SearchDateFieldAdapter.java

License:Open Source License

protected XMLGregorianCalendar convertDateTime(String input) {
    String valueToParse = input;//from  www  . j a va 2s .  c o m
    String dateTimeFormatPattern = dateFormatPattern + " " + timeFormatPattern;
    if (input.length() == dateFormatPattern.length()) {
        dateTimeFormatPattern = dateFormatPattern;
    } else if (input.length() == timeFormatPattern.length()) {
        DateTime dateTime = new DateTime();
        DateTimeFormatter dateFormatter = DateTimeFormat.forPattern(dateFormatPattern);
        valueToParse = dateFormatter.print(dateTime) + " " + input;
    }

    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(dateTimeFormatPattern);

    DateTime dateTime;
    try {
        dateTime = dateTimeFormatter.parseDateTime(valueToParse);
    } catch (IllegalArgumentException e) {
        throw new NetSuiteException(new NetSuiteErrorCode(NetSuiteErrorCode.CLIENT_ERROR),
                NetSuiteRuntimeI18n.MESSAGES.getMessage("error.searchDateField.invalidDateTimeFormat",
                        valueToParse));
    }

    XMLGregorianCalendar xts = datatypeFactory.newXMLGregorianCalendar();
    xts.setYear(dateTime.getYear());
    xts.setMonth(dateTime.getMonthOfYear());
    xts.setDay(dateTime.getDayOfMonth());
    xts.setHour(dateTime.getHourOfDay());
    xts.setMinute(dateTime.getMinuteOfHour());
    xts.setSecond(dateTime.getSecondOfMinute());
    xts.setMillisecond(dateTime.getMillisOfSecond());
    xts.setTimezone(dateTime.getZone().toTimeZone().getOffset(dateTime.getMillis()) / 60000);

    return xts;
}

From source file:se.toxbee.sleepfighter.activity.AlarmActivity.java

License:Open Source License

/**
 * Start flash, animation and show the current time on display
 *//*from w  w  w  . j a  v a2  s  . c  om*/
@Override
protected void onStart() {
    super.onStart();

    // Start animation and flash
    startAnimate();

    if (alarm.isFlashEnabled()) {
        startFlash();
    }

    // Cancel previously started timers
    cancelTimer();

    timer = new Timer("SFTimer");

    final Runnable updateTask = new Runnable() {
        public void run() {
            // Set the current time on the text view
            tvTime.setText(getCurrentTime());
        }
    };

    // Update the user interface
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(updateTask);
        }
    };

    DateTime dt = DateTime.now();
    timer.scheduleAtFixedRate(timerTask, dt.getMillisOfSecond(), 1000);
}

From source file:stroom.pipeline.server.writer.PathCreator.java

License:Apache License

public static String replaceTimeVars(String path) {
    // Replace some of the path elements with system variables.
    final DateTime dateTime = new DateTime(DateTimeZone.UTC);
    path = replace(path, "year", dateTime.getYear(), 4);
    path = replace(path, "month", dateTime.getMonthOfYear(), 2);
    path = replace(path, "day", dateTime.getDayOfMonth(), 2);
    path = replace(path, "hour", dateTime.getHourOfDay(), 2);
    path = replace(path, "minute", dateTime.getMinuteOfHour(), 2);
    path = replace(path, "second", dateTime.getSecondOfMinute(), 2);
    path = replace(path, "millis", dateTime.getMillisOfSecond(), 3);
    path = replace(path, "ms", dateTime.getMillis(), 0);

    return path;//  ww  w .  j  a v  a  2s  .  c o  m
}

From source file:uk.co.jassoft.markets.utils.article.ContentGrabber.java

private Date getDateValue(final String contentsToCheck) {
    if (contentsToCheck.isEmpty())
        return null;

    Parser parser = new Parser();
    List<DateGroup> groups = parser.parse(contentsToCheck);

    Date possibleDate = null;/*from  w w  w  . j  a va 2s .  c om*/

    for (DateGroup group : groups) {
        List<Date> dates = group.getDates();

        for (Date publishedDate : dates) {
            if (new DateTime(DateTimeZone.UTC).plusDays(1).isBefore(publishedDate.getTime())) {
                LOG.debug("Date is over 1 day in the future [{}]", publishedDate.toString());
                continue;
            }

            if (possibleDate == null) {
                possibleDate = publishedDate;

                if (group.isTimeInferred()) {
                    possibleDate = new DateTime(publishedDate).withTime(0, 0, 0, 0).toDate();
                }
                continue;
            }

            DateTime latestPublishedDate = new DateTime(publishedDate);

            if (!group.isTimeInferred()) {
                possibleDate = new DateTime(possibleDate).withTime(latestPublishedDate.getHourOfDay(),
                        latestPublishedDate.getMinuteOfHour(), latestPublishedDate.getSecondOfMinute(),
                        latestPublishedDate.getMillisOfSecond()).toDate();
            }

            if (!group.isDateInferred()) {
                possibleDate = new DateTime(possibleDate).withDate(latestPublishedDate.getYear(),
                        latestPublishedDate.getMonthOfYear(), latestPublishedDate.getDayOfMonth()).toDate();
            }
        }
    }

    if (possibleDate != null) {
        return possibleDate;
    }

    return null;
}