Example usage for org.joda.time Duration Duration

List of usage examples for org.joda.time Duration Duration

Introduction

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

Prototype

public Duration(ReadableInstant start, ReadableInstant end) 

Source Link

Document

Creates a duration from the given interval endpoints.

Usage

From source file:com.okmich.taxilocator.gui.FlowMediatorImpl.java

private TaxiData processValue(String s) {
    TaxiData data = TaxiData.fromString(s);
    if (data == null) {
        return null;
    }/*from  w  w w. jav a 2  s.co m*/
    String key = String.valueOf(data.getNo());
    String cached = recordCache.getTaxiRecord(key);
    if (cached != null) {
        TaxiData prevData = TaxiData.fromString(cached);
        //calculate the difference in time
        float mins = new Duration(prevData.getTimeAsDate().getTime(), data.getTimeAsDate().getTime())
                .getStandardSeconds() / 60f;

        //calculate the distance covered in this space of time
        float distance = (float) Utili.distance(prevData.getLat(), data.getLat(), prevData.getLon(),
                data.getLon(), 0f, 0f);

        //calculate the current speed
        float speed = (mins == 0) ? 0 : distance / (mins * 60);

        //update the data
        data.setCurrentSpeed(speed);
        data.setTotDist(prevData.getTotDist() + distance);
        data.setTotNumMins(prevData.getTotNumMins() + mins);
    }

    recordCache.setTaxiRecord(key, data.toString());
    return data;
}

From source file:com.palominolabs.crm.sf.soap.MetadataConnectionImpl.java

License:Apache License

@Override
@Nonnull/*from w  w w . j av a  2s . c  om*/
public WaitForAsyncResult waitForAsyncResults(@Nonnull List<AsyncResult> results, long maxMillisToWait)
        throws ApiException, InterruptedException {

    DateTime startTime = new DateTime();

    long millisWaited = 0;
    long nextWait = 1000;

    List<AsyncResult> latestAsyncResults = results;

    // flag to exit the loop at the right point
    boolean maxTimeHit = false;

    while (true) {
        List<Id> idsToCheck = new ArrayList<Id>();

        for (AsyncResult result : latestAsyncResults) {
            if (result.isDone()) {
                // do not check this id
                continue;
            }

            idsToCheck.add(result.getId());
        }

        if (idsToCheck.isEmpty() || maxTimeHit) {
            // we've got all the results, or we're done waiting
            DateTime endTime = new DateTime();
            Duration elapsed = new Duration(startTime, endTime);

            return new WaitForAsyncResult(elapsed, latestAsyncResults);
        }

        latestAsyncResults = this.checkStatus(idsToCheck);

        if (millisWaited >= maxMillisToWait) {
            maxTimeHit = true;
            // do not wait, instead, loop through one more time to hit the timing processing block
            continue;
        }

        Thread.sleep(nextWait);
        millisWaited += nextWait;
        nextWait *= 2;

        // if the next wait will push us over the limit, trim the nextWait

        if (millisWaited + nextWait > maxMillisToWait) {
            nextWait = maxMillisToWait - millisWaited;
        }
    }
}

From source file:com.robwilliamson.healthyesther.util.time.Range.java

License:Open Source License

public Duration length() {
    return new Duration(from, to);
}

From source file:com.rubenlaguna.en4j.sync.SyncAction.java

License:Open Source License

public void actionPerformed(ActionEvent e) {
    // TODO implement action body
    final SynchronizationService sservice = Lookup.getDefault().lookup(SynchronizationService.class);

    Runnable task = new Runnable() {

        public void run() {
            DateTime startTime = new DateTime();
            StatusDisplayer.getDefault().setStatusText("Sync started at " + startTime.toString("HH:mm"));

            if (toolbarPresenter.startAnimator()) { //dont run if it was already running
                sservice.sync();//from   w w  w .j a  v  a2s . c  o m
                toolbarPresenter.stopAnimator();
                if (sservice.isSyncFailed()) {
                    StatusDisplayer.getDefault().setStatusText("Sync failed.");
                } else {
                    DateTime finishTime = new DateTime();
                    Duration dur = new Duration(startTime, finishTime);
                    Minutes minutes = dur.toPeriod().toStandardMinutes();
                    Seconds seconds = dur.toPeriod().minus(minutes).toStandardSeconds();
                    final String message = "sync finished at " + finishTime.toString("HH:mm") + ". Sync took "
                            + minutes.getMinutes() + " minutes and " + seconds.getSeconds() + " seconds.";
                    final StatusDisplayer.Message sbMess = StatusDisplayer.getDefault().setStatusText(message,
                            1);
                    RP.post(new Runnable() {
                        public void run() {
                            sbMess.clear(10000);
                        }
                    });
                }
            }
        }
    };
    RP.post(task);
}

From source file:com.sandata.lab.wcf.lookup.impl.RestLookupTablesService.java

License:Open Source License

private boolean lastCacheUpdateTimeExpired(final SandataLogger logger) {

    boolean bResult = false;
    String method = logger.getMethodName();
    logger.setMethodName("lastCacheUpdateTimeExpired");

    LocalDateTime now = LocalDateTime.now();

    Duration duration = new Duration(lastCacheUpdateTime.toDateTime(DateTimeZone.UTC),
            now.toDateTime(DateTimeZone.UTC));
    long seconds = duration.getStandardSeconds();
    long minutes = duration.getStandardMinutes();

    logger.info(String.format("Last Cache Update: %s", TimeFormat.SecondsToString(seconds)));

    if (minutes >= updateCacheInterval) {
        bResult = true;/*from ww  w  .  j a va 2 s  . c o m*/
    }

    logger.setMethodName(method);
    return bResult;
}

From source file:com.sheepdog.mashmesh.models.RideRecord.java

License:Apache License

public double getTripMinutes() {
    return new Duration(departureTime, arrivalTime).getStandardMinutes();
}

From source file:com.sheepdog.mashmesh.models.VolunteerProfile.java

License:Apache License

public void addAppointmentTime(RideRequest rideRequest, DateTime departureTime, DateTime arrivalTime) {
    Duration commuteDuration = new Duration(departureTime, arrivalTime);
    DateTime startTime = departureTime;//from www  .j ava  2  s.co  m
    DateTime endTime = arrivalTime.plus(commuteDuration);

    AppointmentPeriod appointmentTime = new AppointmentPeriod();
    appointmentTime.rideRequestId = rideRequest.getId();
    appointmentTime.startTimeMillis = startTime.getMillis();
    appointmentTime.endTimeMillis = endTime.getMillis();

    appointmentTimes.add(appointmentTime);
}

From source file:com.sonicle.webtop.calendar.CalendarManager.java

License:Open Source License

@Override
public void updateEventInstance(UpdateEventTarget target, EventKey key, DateTime newStart, DateTime newEnd,
        String newTitle, boolean notifyAttendees) throws WTException {
    CalendarDAO calDao = CalendarDAO.getInstance();
    Connection con = null;//  w w  w.  j av a2 s .com

    try {
        con = WT.getConnection(SERVICE_ID, false);

        EventInstance ei = doEventInstanceGet(con, key.eventId, key.instanceDate, true);

        int calendarId = ei.getCalendarId();
        checkRightsOnCalendarElements(calendarId, "UPDATE");
        String provider = calDao.selectProviderById(con, calendarId);
        if (Calendar.isProviderRemote(provider))
            throw new WTException("Calendar is remote and therefore read-only [{}]", calendarId);

        if ((newStart != null) && (newEnd != null)) {
            ei.setStartDate(newStart);
            ei.setEndDate(newEnd);
        } else if (newStart != null) {
            Duration length = new Duration(ei.getStartDate(), ei.getEndDate());
            ei.setStartDate(newStart);
            ei.setEndDate(newStart.plus(length));
        } else if (newEnd != null) {
            Duration length = new Duration(ei.getStartDate(), ei.getEndDate());
            ei.setStartDate(newEnd.minus(length));
            ei.setEndDate(newEnd);
        }
        if (newTitle != null) {
            ei.setTitle(newTitle);
        }

        ei.ensureCoherence();
        doEventInstanceUpdateAndCommit(con, target, key, ei, notifyAttendees);

    } catch (SQLException | DAOException | IOException | WTException ex) {
        DbUtils.rollbackQuietly(con);
        throw wrapException(ex);
    } finally {
        DbUtils.closeQuietly(con);
    }
}

From source file:com.sonicle.webtop.calendar.CalendarManager.java

License:Open Source License

@Override
public Event cloneEventInstance(EventKey key, Integer newCalendarId, DateTime newStart, DateTime newEnd,
        boolean notifyAttendees) throws WTException {
    Connection con = null;//  w  ww . j  av  a 2s.c om
    EventInstance ei = null;

    try {
        con = WT.getConnection(SERVICE_ID);

        ei = doEventInstanceGet(con, key.eventId, key.instanceDate, true);
        checkRightsOnCalendarFolder(ei.getCalendarId(), "READ");
        int calendarId = (newCalendarId != null) ? newCalendarId : ei.getCalendarId();

        ei.setCalendarId(calendarId);
        ei.setPublicUid(null); // Reset value in order to make inner function generate new one!
        ei.setHref(null); // Reset value in order to make inner function generate new one!
        if ((newStart != null) && (newEnd != null)) {
            ei.setStartDate(newStart);
            ei.setEndDate(newEnd);
        } else if (newStart != null) {
            Duration length = new Duration(ei.getStartDate(), ei.getEndDate());
            ei.setStartDate(newStart);
            ei.setEndDate(newStart.plus(length));
        } else if (newEnd != null) {
            Duration length = new Duration(ei.getStartDate(), ei.getEndDate());
            ei.setStartDate(newEnd.minus(length));
            ei.setEndDate(newEnd);
        }

    } catch (SQLException | DAOException | WTException ex) {
        throw wrapException(ex);
    } finally {
        DbUtils.closeQuietly(con);
    }

    return addEvent(ei, notifyAttendees);
}

From source file:com.spotify.reaper.resources.view.RepairRunStatus.java

License:Apache License

public RepairRunStatus(long runId, String clusterName, String keyspaceName, Collection<String> columnFamilies,
        int segmentsRepaired, int totalSegments, RepairRun.RunState state, DateTime startTime, DateTime endTime,
        String cause, String owner, String lastEvent, DateTime creationTime, DateTime pauseTime,
        double intensity, RepairParallelism repairParallelism) {
    this.id = runId;
    this.cause = cause;
    this.owner = owner;
    this.clusterName = clusterName;
    this.columnFamilies = columnFamilies;
    this.keyspaceName = keyspaceName;
    this.state = state;
    this.creationTime = creationTime;
    this.startTime = startTime;
    this.endTime = endTime;
    this.pauseTime = pauseTime;
    this.intensity = CommonTools.roundDoubleNicely(intensity);
    this.totalSegments = totalSegments;
    this.repairParallelism = repairParallelism;
    this.segmentsRepaired = segmentsRepaired;
    this.lastEvent = lastEvent;

    if (startTime == null || endTime == null) {
        duration = null;//w ww. j a v  a2  s  . c o m
    } else {
        duration = DurationFormatUtils.formatDurationWords(
                new Duration(startTime.toInstant(), endTime.toInstant()).getMillis(), true, false);
    }

    if (startTime == null || endTime != null) {
        estimatedTimeOfArrival = null;
    } else {
        if (state == RepairRun.RunState.ERROR || state == RepairRun.RunState.DELETED
                || state == RepairRun.RunState.ABORTED) {
            estimatedTimeOfArrival = null;
        } else if (segmentsRepaired == 0) {
            estimatedTimeOfArrival = null;
        } else {
            long now = DateTime.now().getMillis();
            long currentDuration = now - startTime.getMillis();
            long millisecondsPerSegment = currentDuration / segmentsRepaired;
            int segmentsLeft = totalSegments - segmentsRepaired;
            estimatedTimeOfArrival = new DateTime(now + millisecondsPerSegment * segmentsLeft);
        }
    }
}