Example usage for org.joda.time DateTime plusMillis

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

Introduction

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

Prototype

public DateTime plusMillis(int millis) 

Source Link

Document

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

Usage

From source file:org.apache.storm.st.topology.window.data.TimeDataWindow.java

License:Apache License

public static TimeDataWindow newInstance(Collection<TimeData> data, final DateTime fromDate,
        final DateTime toDate) {
    return TimeDataWindow.newInstance(data, new Predicate<TimeData>() {
        @Override//from ww w. j a va 2 s.  c om
        public boolean apply(@Nullable TimeData input) {
            if (input == null) {
                return false;
            }
            final DateTime inputDate = new DateTime(input.getDate());
            return inputDate.isAfter(fromDate) && inputDate.isBefore(toDate.plusMillis(1));
        }
    });
}

From source file:org.bryantd.lightscameraaction.PluginInterface.java

private Boolean initializeImagingJobs() {
    Boolean userInputOK = true;/*from   w w  w . j  av a  2s. co  m*/
    imageJobsSchedule_ = new ArrayList<DateTime>();

    Double timeBetweenImages = Double.parseDouble((jSpinnerTimeBetween.getValue()).toString().trim());
    Integer timeBetweenImagesMS = timeBetweenImages.intValue();
    Double lightsToImageDelay = Double.parseDouble((jSpinnerDelay.getValue()).toString().trim());
    Integer lightsToImageDelayMS = lightsToImageDelay.intValue();
    Integer numImages = (Integer) jSpinnerNumImages.getValue();

    if (jRadioButtonTimeBetweenMin.isSelected()) {
        Double tempMS = timeBetweenImages * 60.0 * 1000.0;
        timeBetweenImagesMS = tempMS.intValue();
    } else if (jRadioButtonTimeBetweenS.isSelected()) {
        Double tempMS = timeBetweenImages * 1000.0;
        timeBetweenImagesMS = tempMS.intValue();
    }
    System.out.println("Time between images MS: " + timeBetweenImagesMS);

    if (jRadioButtonDelayMin.isSelected()) {
        Double tempMS = lightsToImageDelay * 60.0 * 1000.0;
        lightsToImageDelayMS = tempMS.intValue();
    } else if (jRadioButtonDelayS.isSelected()) {
        Double tempMS = lightsToImageDelay * 1000.0;
        lightsToImageDelayMS = tempMS.intValue();
    }
    System.out.println("Lights to image delay MS: " + lightsToImageDelayMS);

    if (numImages < 1 || timeBetweenImagesMS <= 0 || lightsToImageDelayMS < 0
            || timeBetweenImagesMS < 2 * lightsToImageDelayMS) {
        userInputOK = false;
        if (timeBetweenImagesMS <= 0) {
            jTextAreaStatus.append(Utilities
                    .timeStamp("Error: " + timeBetweenImagesMS + " is not a valid time between images.\n")
                    .toString());
        }
        if (lightsToImageDelayMS < 0) {
            jTextAreaStatus
                    .append(Utilities
                            .timeStamp("Error: " + lightsToImageDelayMS
                                    + "is not a valid lights off to image acquisition time delay.\n")
                            .toString());
        }
        if (timeBetweenImagesMS < 2 * lightsToImageDelayMS) {
            jTextAreaStatus.append(Utilities
                    .timeStamp("Error: time between images (" + timeBetweenImagesMS
                            + " ms) must be at least 2x delay (" + lightsToImageDelayMS + " ms).\n")
                    .toString());
        }
        if (numImages < 1) {
            jTextAreaStatus.append(Utilities
                    .timeStamp("Error: " + numImages + " is not a valid number of images to acquire.\n")
                    .toString());
        }
    }

    if (userInputOK) {
        this.lightsToImageDelayMS_ = lightsToImageDelayMS;
        imageJobsSchedule_.clear();
        DateTime now = new DateTime();
        now = now.plusSeconds(5);
        for (Integer i = 0; i < numImages; i++) {
            DateTime scheduledJob = now.plusMillis(i * timeBetweenImagesMS);
            imageJobsSchedule_.add(scheduledJob);
            System.out.println("Added " + scheduledJob);
        }
        jTextAreaStatus.append(Utilities
                .timeStamp("Added " + imageJobsSchedule_.size() + " image acquisition events to schedule.\n")
                .toString());
    }
    return userInputOK;
}

From source file:org.jruby.ext.date.RubyDate.java

License:LGPL

private void adjustWithDayFraction(ThreadContext context, DateTime dt, final long[] rest) {
    final RubyFixnum zero = RubyFixnum.zero(context.runtime);
    int ival;//from  w  w w  . j av  a2  s .c om

    ival = RubyDateTime.getHour(context, zero, rest);
    dt = dt.plusHours(ival);

    if (rest[0] != 0) {
        ival = RubyDateTime.getMinute(context, zero, rest);
        dt = dt.plusMinutes(ival);

        if (rest[0] != 0) {
            ival = RubyDateTime.getSecond(context, zero, rest);
            dt = dt.plusSeconds(ival);

            final long r0 = rest[0], r1 = rest[1];
            if (r0 != 0) {
                long millis = (1000 * r0) / r1;
                dt = dt.plusMillis((int) millis);

                subMillisNum = ((1000 * r0) - (millis * r1));
                subMillisDen = r1;
                normalizeSubMillis();
            }
        }
    }

    this.dt = dt;
}

From source file:org.jruby.RubyTime.java

License:LGPL

private static RubyTime createTime(IRubyObject recv, IRubyObject[] args, boolean gmt, boolean utcOffset) {
    Ruby runtime = recv.getRuntime();//from www.  j a  v a 2s  . c om
    int len = ARG_SIZE;
    boolean isDst = false;
    boolean setTzRelative = false;
    long nanos = 0;

    DateTimeZone dtz;
    if (gmt) {
        dtz = DateTimeZone.UTC;
    } else if (args.length == 10 && args[9] instanceof RubyString) {
        if (utcOffset) {
            dtz = getTimeZoneFromUtcOffset(runtime, args[9]);
            setTzRelative = true;
        } else {
            dtz = getTimeZoneFromString(runtime, args[9].toString());
        }
    } else if (args.length == 10 && args[9].respondsTo("to_int")) {
        IRubyObject offsetInt = args[9].callMethod(runtime.getCurrentContext(), "to_int");
        dtz = getTimeZone(runtime, ((RubyNumeric) offsetInt).getLongValue());
    } else {
        dtz = getLocalTimeZone(runtime);
    }

    if (args.length == 10) {
        if (args[8] instanceof RubyBoolean)
            isDst = args[8].isTrue();

        args = new IRubyObject[] { args[5], args[4], args[3], args[2], args[1], args[0], runtime.getNil() };
    } else {
        // MRI accepts additional wday argument which appears to be ignored.
        len = args.length;

        if (len < ARG_SIZE) {
            IRubyObject[] newArgs = new IRubyObject[ARG_SIZE];
            System.arraycopy(args, 0, newArgs, 0, args.length);
            for (int i = len; i < ARG_SIZE; i++) {
                newArgs[i] = runtime.getNil();
            }
            args = newArgs;
            len = ARG_SIZE;
        }
    }

    if (args[0] instanceof RubyString) {
        args[0] = RubyNumeric.str2inum(runtime, (RubyString) args[0], 10, false);
    }

    int year = (int) RubyNumeric.num2long(args[0]);
    int month = 1;

    if (len > 1) {
        if (!args[1].isNil()) {
            IRubyObject tmp = args[1].checkStringType();
            if (!tmp.isNil()) {
                String monthString = tmp.toString().toLowerCase();
                Integer monthInt = MONTHS_MAP.get(monthString);

                if (monthInt != null) {
                    month = monthInt;
                } else {
                    try {
                        month = Integer.parseInt(monthString);
                    } catch (NumberFormatException nfExcptn) {
                        throw runtime.newArgumentError("Argument out of range.");
                    }
                }
            } else {
                month = (int) RubyNumeric.num2long(args[1]);
            }
        }
        if (1 > month || month > 12) {
            throw runtime.newArgumentError("Argument out of range: for month: " + month);
        }
    }

    int[] int_args = { 1, 0, 0, 0, 0, 0 };

    for (int i = 0; int_args.length >= i + 2; i++) {
        if (!args[i + 2].isNil()) {
            if (!(args[i + 2] instanceof RubyNumeric)) {
                if (args[i + 2].respondsTo("to_int")) {
                    args[i + 2] = args[i + 2].callMethod(runtime.getCurrentContext(), "to_int");
                } else {
                    args[i + 2] = args[i + 2].callMethod(runtime.getCurrentContext(), "to_i");
                }
            }

            int_args[i] = RubyNumeric.num2int(args[i + 2]);
        }
    }

    // Validate the times
    // Complying with MRI behavior makes it a little bit complicated. Logic copied from:
    // https://github.com/ruby/ruby/blob/trunk/time.c#L2609
    if ((int_args[0] < 1 || int_args[0] > 31) || (int_args[1] < 0 || int_args[1] > 24)
            || (int_args[1] == 24 && (int_args[2] > 0 || int_args[3] > 0))
            || (int_args[2] < 0 || int_args[2] > 59) || (int_args[3] < 0 || int_args[3] > 60)) {
        throw runtime.newArgumentError("argument out of range.");
    }

    DateTime dt;
    // set up with min values and then add to allow rolling over
    try {
        dt = new DateTime(year, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);

        dt = dt.plusMonths(month - 1).plusDays(int_args[0] - 1).plusHours(int_args[1]).plusMinutes(int_args[2])
                .plusSeconds(int_args[3]);

        // 1.9 will observe fractional seconds *if* not given usec
        if (!args[5].isNil() && args[6].isNil()) {
            double secs = RubyFloat.num2dbl(args[5]);
            int int_millis = (int) (secs * 1000) % 1000;
            dt = dt.plusMillis(int_millis);
            nanos = ((long) (secs * 1000000000) % 1000000);
        }

        dt = dt.withZoneRetainFields(dtz);

        // If we're at a DST boundary, we need to choose the correct side of the boundary
        if (isDst) {
            final DateTime beforeDstBoundary = dt.withEarlierOffsetAtOverlap();
            final DateTime afterDstBoundary = dt.withLaterOffsetAtOverlap();

            final int offsetBeforeBoundary = dtz.getOffset(beforeDstBoundary);
            final int offsetAfterBoundary = dtz.getOffset(afterDstBoundary);

            // If the time is during DST, we need to pick the time with the highest offset
            dt = offsetBeforeBoundary > offsetAfterBoundary ? beforeDstBoundary : afterDstBoundary;
        }
    } catch (org.joda.time.IllegalFieldValueException e) {
        throw runtime.newArgumentError("time out of range");
    }

    RubyTime time = new RubyTime(runtime, (RubyClass) recv, dt);
    // Ignores usec if 8 args (for compatibility with parsedate) or if not supplied.
    if (args.length != 8 && !args[6].isNil()) {
        boolean fractionalUSecGiven = args[6] instanceof RubyFloat || args[6] instanceof RubyRational;

        if (fractionalUSecGiven) {
            double micros = RubyNumeric.num2dbl(args[6]);
            time.dt = dt.withMillis(dt.getMillis() + (long) (micros / 1000));
            nanos = ((long) (micros * 1000) % 1000000);
        } else {
            int usec = int_args[4] % 1000;
            int msec = int_args[4] / 1000;

            if (int_args[4] < 0) {
                msec -= 1;
                usec += 1000;
            }
            time.dt = dt.withMillis(dt.getMillis() + msec);
            time.setUSec(usec);
        }
    }

    if (nanos != 0)
        time.setNSec(nanos);

    time.callInit(IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
    time.setIsTzRelative(setTzRelative);
    return time;
}

From source file:org.kuali.kpme.tklm.time.approval.service.TimeApproveServiceImpl.java

License:Educational Community License

@Override
public Map<String, TimesheetDocumentHeader> getPrincipalDocumentHeader(List<String> principalIds,
        DateTime payBeginDate, DateTime payEndDate) {
    Map<String, TimesheetDocumentHeader> principalDocumentHeader = new LinkedHashMap<String, TimesheetDocumentHeader>();
    for (String principalId : principalIds) {

        TimesheetDocumentHeader tdh = TkServiceLocator.getTimesheetDocumentHeaderService()
                .getDocumentHeader(principalId, payBeginDate, payEndDate.plusMillis(1));
        if (tdh != null) {
            principalDocumentHeader.put(principalId, tdh);
        }/*www .ja va  2s. c o  m*/
    }
    return principalDocumentHeader;
}

From source file:org.n52.sos.request.operator.AqdGetObservationOperatorV10.java

License:Open Source License

private void checkRequestForFlowAndTemporalFilter(GetObservationRequest request, ReportObligationType flow)
        throws CodedException {
    try {// ww  w. j a v a 2s. co  m
        if (!request.isSetTemporalFilter()) {
            DateTime start = null;
            DateTime end = null;
            DateTime dateTime = new DateTime();
            if (ReportObligationType.E2A.equals(flow)) {
                String timeString;
                timeString = DateTimeHelper.formatDateTime2YearMonthDayDateStringYMD(dateTime.minusDays(1));
                start = DateTimeHelper.parseIsoString2DateTime(timeString);
                int timeLength = DateTimeHelper.getTimeLengthBeforeTimeZone(timeString);
                DateTime origEnd = DateTimeHelper.parseIsoString2DateTime(timeString);
                end = DateTimeHelper.setDateTime2EndOfMostPreciseUnit4RequestedEndPosition(origEnd, timeLength);
            } else if (ReportObligationType.E1A.equals(flow) || ReportObligationType.E1B.equals(flow)) {
                String year = Integer.toString(dateTime.minusYears(1).getYear());
                start = DateTimeHelper.parseIsoString2DateTime(year);
                int timeLength = DateTimeHelper.getTimeLengthBeforeTimeZone(year);
                end = DateTimeHelper.setDateTime2EndOfMostPreciseUnit4RequestedEndPosition(
                        DateTimeHelper.parseIsoString2DateTime(year), timeLength);
            }
            if (start != null && end != null) {
                request.setTemporalFilters(
                        getTemporalFilter(new TimePeriod(start.minusMillis(1), end.plusMillis(2))));
            }
        }
    } catch (DateTimeFormatException | DateTimeParseException e) {
        throw new NoApplicableCodeException().causedBy(e).withMessage(
                "The request does not contain a temporal filter and the temporal filter creation for the flow fails!");
    }
}

From source file:org.nuxeo.elasticsearch.aggregate.DateHelper.java

License:Apache License

/**
 * Returns a new datetime plus the specified duration.
 *
 * @param origin the initial datetime/*from ww w .ja  v  a  2s.  c om*/
 * @param duration can be expressed with a noun: hour, day, month, quarter, year
 *                 or expression: 2d, 3h, 5w, 2M, 3y
 *                 or a number of ms: 1234
 * @throws IllegalArgumentException if the duration can not be parsed
 * @return a new datetime
 */
public static DateTime plusDuration(DateTime origin, String duration) {
    if (duration.matches("[a-zA-Z]+")) {
        return plusDurationAsNoun(origin, duration);
    }
    if (duration.matches("[0-9]+")) {
        return origin.plusMillis(Integer.valueOf(duration));
    }
    return plusDurationAsExpression(origin, duration);
}

From source file:rapture.dp.invocable.CheckPrerequisiteStep.java

License:Open Source License

@Override
public String invoke(CallingContext ctx) {
    PrerequisiteConfig config = getPrerequisiteConfig(ctx);
    log.info("config = " + JacksonUtil.jsonFromObject(config));
    DateTime cutoffTime = null;//from   w  w  w  .j  a  v a 2s  .co m
    if (StringUtils.trimToNull(config.getCutoffTime()) == null) {
        log.warn("No timeout/cutoff time defined - Will wait forever");
    } else {
        cutoffTime = getDateTime(config.getCutoffTime());
    }
    String cutoffAction = getCutoffAction(config.getCutoffAction());

    while (true) {
        // check if reached cutoff time
        if ((cutoffTime != null) && !cutoffTime.isAfterNow()) {
            log.info("Reached cut off time, return " + cutoffAction);
            return cutoffAction;
        }
        // check last data point
        if (isDataReady(ctx, config)) {
            log.info("Data is ready, return next");
            return NEXT;
        }
        // data not ready, get next retry time
        DateTime now = DateTime.now();
        DateTime nextRetryTime = now.plusMillis(config.getRetryInMillis());
        if ((cutoffTime != null) && nextRetryTime.isAfter(cutoffTime)) {
            log.info("Next retry is after cutoff time, set it to " + cutoffTime);
            nextRetryTime = cutoffTime;
        }
        // sleep and retry later
        long sleepTime = nextRetryTime.getMillis() - now.getMillis();
        log.info("Sleep for " + sleepTime + " ms");
        try {
            if (sleepTime > 0)
                Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            log.error("Interrupted, check if data is ready", e);
        }
    }
}

From source file:ru.org.linux.auth.FloodProtector.java

License:Apache License

private boolean check(Action action, String ip, int threshold) {
    String key = action.toString() + ':' + ip;

    DateTime date = hash.getIfPresent(key);

    if (date != null) {
        if (date.plusMillis(threshold).isAfterNow()) {
            return false;
        }/*from  w  ww  . j a v a2  s . c  om*/
    }

    hash.put(key, new DateTime());

    return true;
}

From source file:stirling.fix.session.Session.java

License:Apache License

private boolean isTimedOut(DateTime dateTime, long timeoutMsec) {
    DateTime now = currentTime();//from   w w  w .j a  v a  2s .c om
    DateTime timeOutAt = dateTime.plusMillis((int) timeoutMsec);
    return now.isAfter(timeOutAt);
}