Example usage for org.joda.time Interval toDurationMillis

List of usage examples for org.joda.time Interval toDurationMillis

Introduction

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

Prototype

public long toDurationMillis() 

Source Link

Document

Gets the duration of this time interval in milliseconds.

Usage

From source file:com.almende.dsol.example.datacenters.Datacenter.java

License:Apache License

protected void newService(final Interval interval, final double consumptionFactor, final double cashFlowFactor)
        throws RemoteException, SimRuntimeException {
    final Service service = new Service(getModel(), this, interval,
            this.consumptionKW.draw() * consumptionFactor, this.hourlyCashflow.draw() * cashFlowFactor);

    final Interval cropped = DsolUtil.crop(interval, getTreatment());
    this.workloadHours.addValue(DsolUtil.toTimeUnit(TimeUnitInterface.HOUR, cropped.toDurationMillis(),
            TimeUnitInterface.MILLISECOND));

    // listen for service start and stop events
    service.addListener(new EventListenerInterface() {

        @Override//from w  w w  .j av a 2s.c  om
        public void notify(final EventInterface event) {
            if (consumptionFactor == 0.0)
                return;
            getCurrentServiceCount().addValue(1);
            getTotalServiceCount().addValue(1);
            if (consumptionFactor < 1.0)
                exchangedServiceCount.addValue(1);
        }
    }, Service.SERVICE_STARTED);

    service.addListener(new EventListenerInterface() {

        @Override
        public void notify(final EventInterface event) {
            getCurrentServiceCount().addValue(-1);
        }
    }, Service.SERVICE_COMPLETED);

    service.addListener(new EventListenerInterface() {

        @Override
        public void notify(final EventInterface event) {
            final Number kW = (Number) event.getContent();
            getConsumptionKWh()
                    .addRate(kW.doubleValue() * Datacenter.this.consumptionFactor.getValue().doubleValue());
            getEmissionsKgCO2()
                    .addRate(kW.doubleValue() * Datacenter.this.consumptionFactor.getValue().doubleValue()
                            * Datacenter.this.emissionsPerKWh
                            * Datacenter.this.emissionFactor.getValue().doubleValue());
            getCashflow().addRate(kW.doubleValue() * Datacenter.this.cashPerKWh);
        }
    }, Service.CONSUMPTION_CHANGED);

    service.addListener(new EventListenerInterface() {

        @Override
        public void notify(final EventInterface event) {
            getCashflow().addRate((Number) event.getContent());
        }
    }, Service.CASHFLOW_CHANGED);

}

From source file:com.almende.eve.agent.MeetingAgent.java

License:Apache License

/**
 * Apply the constraints of the the activity (for example duration)
 * /*from   w w  w . ja v  a  2 s  . c om*/
 * @param activity
 * @return changed Returns true if the activity is changed
 */
private boolean applyConstraints() {
    final Activity activity = getState().get("activity", Activity.class);
    boolean changed = false;
    if (activity == null) {
        return false;
    }

    // constraints on attendees/resources
    /*
     * TODO: copy actual attendees to status.attendees
     * List<Attendee> constraintsAttendees =
     * activity.withConstraints().withAttendees();
     * List<Attendee> attendees = new ArrayList<Attendee>();
     * for (Attendee attendee : constraintsAttendees) {
     * attendees.add(attendee.clone());
     * }
     * activity.withStatus().setAttendees(attendees);
     * // TODO: is it needed to check if the attendees are changed?
     */

    // check time constraints
    final Long duration = activity.withConstraints().withTime().getDuration();
    if (duration != null) {
        final String start = activity.withStatus().getStart();
        final String end = activity.withStatus().getEnd();
        if (start != null && end != null) {
            final DateTime startTime = new DateTime(start);
            DateTime endTime = new DateTime(end);
            final Interval interval = new Interval(startTime, endTime);
            if (interval.toDurationMillis() != duration) {
                LOG.info("status did not match constraints. " + "Changed end time to match the duration of "
                        + duration + " ms");

                // duration does not match. adjust the end time
                endTime = startTime.plus(duration);
                activity.withStatus().setEnd(endTime.toString());
                activity.withStatus().setUpdated(DateTime.now().toString());

                changed = true;
            }
        }
    }

    // location constraints
    final String newLocation = activity.withConstraints().withLocation().getSummary();
    final String oldLocation = activity.withStatus().withLocation().getSummary();
    if (newLocation != null && !newLocation.equals(oldLocation)) {
        activity.withStatus().withLocation().setSummary(newLocation);
        changed = true;
    }

    if (changed) {
        // store the updated activity
        getState().put("activity", activity);
    }
    return changed;
}

From source file:com.almende.eve.agent.MeetingAgent.java

License:Apache License

/**
 * Convert a calendar event into an activity
 * /*from  www. j  a va2 s . c o  m*/
 * @param event
 * @return activity
 */
private Activity convertEventToActivity(final ObjectNode event) {
    final Activity activity = new Activity();

    // agent
    URI agent = null;
    if (event.has("agent")) {
        agent = URI.create(event.get("agent").asText());
    }
    activity.setAgent(agent);

    // summary
    String summary = null;
    if (event.has("summary")) {
        summary = event.get("summary").asText();
    }
    activity.setSummary(summary);

    // description
    String description = null;
    if (event.has("description")) {
        description = event.get("description").asText();
    }
    activity.setDescription(description);

    // updated
    String updated = null;
    if (event.has("updated")) {
        updated = event.get("updated").asText();
    }
    activity.withStatus().setUpdated(updated);

    // start
    String start = null;
    if (event.with("start").has("dateTime")) {
        start = event.with("start").get("dateTime").asText();
    }
    activity.withStatus().setStart(start);

    // end
    String end = null;
    if (event.with("end").has("dateTime")) {
        end = event.with("end").get("dateTime").asText();
    }
    activity.withStatus().setEnd(end);

    // duration
    if (start != null && end != null) {
        final Interval interval = new Interval(new DateTime(start), new DateTime(end));
        final Long duration = interval.toDurationMillis();
        activity.withConstraints().withTime().setDuration(duration);
    }

    // location
    String location = null;
    if (event.has("location")) {
        location = event.get("location").asText();
    }
    activity.withConstraints().withLocation().setSummary(location);

    return activity;
}

From source file:com.almende.eve.agent.MeetingAgent.java

License:Apache License

/**
 * Calculate the average preference for given interval.
 * The method aggregates over all stored preferences
 * Default preference is 0./*from  w  w  w. j a  v a2  s .c o  m*/
 * 
 * @param preferredIntervals
 *            list with intervals ordered by start
 * @param test
 *            test interval
 * @return preference
 */
private double calculatePreference(final List<Weight> preferredIntervals, final Interval test) {
    double preference = 0;

    for (final Weight interval : preferredIntervals) {
        final Interval overlap = test.overlap(interval.getInterval());
        if (overlap != null) {
            final Double weight = interval.getWeight();
            if (weight != null) {
                final double durationCheck = test.toDurationMillis();
                final double durationOverlap = overlap.toDurationMillis();
                final double avgWeight = (durationOverlap / durationCheck) * weight;
                preference += avgWeight;
            }
        }

        if (interval.getStart().isAfter(test.getEnd())) {
            // as the list is ordered, we can exit as soon as we have an
            // interval which starts after the wanted interval.
            break;
        }
    }

    return preference;
}

From source file:com.almende.pi5.common.PowerTimeLine.java

License:Apache License

/**
 * Make this TL discrete, returning the TL;
 * As a side effect, removes values outside the start and end times.
 *
 * @param start/*www . java2s  .c o m*/
 *            the start
 * @param end
 *            the end
 * @param stepSize
 *            the step size
 * @return this
 */
@JsonIgnore
public PowerTimeLine discrete(final DateTime start, final DateTime end, final Duration stepSize) {
    final PowerTimeLine newTL = new PowerTimeLine();
    newTL.timestamp = this.timestamp;
    final ArrayList<PowerTime> steps = new ArrayList<PowerTime>();

    long offset = new Duration(timestamp, start).getMillis();
    Interval interval = stepSize.toIntervalFrom(start);
    while (interval.getEnd().isBefore(end) || interval.getEnd().isEqual(end)) {
        steps.add(new PowerTime(offset, 0));
        offset += interval.toDurationMillis();
        interval = stepSize.toIntervalFrom(timestamp.plusMillis((int) offset));
    }
    newTL.setSeries(steps);
    this.add(newTL).zeroBefore(start).zeroFrom(end);

    final Duration diff = new Duration(start, end);
    if (series.size() > (diff.getMillis() / stepSize.getMillis())) {
        int index = 0;
        long expectedOffset = new Duration(timestamp, start).getMillis() + stepSize.getMillis();
        while (index < series.size() - 1) {
            PowerTime pt = series.get(index);
            ArrayList<PowerTime> temp = new ArrayList<PowerTime>();

            int nextIndex = index + 1;
            PowerTime next = series.get(nextIndex);
            while (next.getOffset() < expectedOffset) {
                temp.add(next);
                series.remove(nextIndex);
                if (nextIndex == series.size()) {
                    break;
                }
                next = series.get(nextIndex);
            }
            if (temp.size() > 0) {
                temp.add(0, pt);
                double integral = getIntegral(pt.getOffset(), pt.getOffset() + stepSize.getMillis(), temp);
                series.set(index, new PowerTime(pt.getOffset(), integral / stepSize.getMillis()));
            }
            index++;
            expectedOffset += stepSize.getMillis();
        }
    }

    return this;
}

From source file:com.enonic.cms.server.service.portal.mvc.controller.PortalRenderResponseServer.java

License:Open Source License

private void setHttpCacheHeaders(final User requester, final DateTime requestTime,
        final DateTime expirationTime, final HttpServletResponse httpResponse, final boolean forceNoCache,
        final SiteEntity site) {
    final Interval maxAge = new Interval(requestTime, expirationTime);

    @SuppressWarnings({ "UnnecessaryLocalVariable" })
    boolean notCachableByClient = forceNoCache;
    if (notCachableByClient) {
        HttpServletUtil.setCacheControlNoCache(httpResponse);
    } else {/*from   w  w  w  .ja v a 2s .c o  m*/
        HttpCacheControlSettings cacheControlSettings = new HttpCacheControlSettings();

        // To eliminate proxy caching of pages (decided by TSI)
        cacheControlSettings.publicAccess = false;

        boolean setCacheTimeToZero = dynamicResolversEnabled(site);

        if (setCacheTimeToZero) {
            cacheControlSettings.maxAgeSecondsToLive = new Long(0);
            HttpServletUtil.setExpiresHeader(httpResponse, requestTime.toDate());
        } else {
            cacheControlSettings.maxAgeSecondsToLive = maxAge.toDurationMillis() / SECOND_IN_MILLIS;
            HttpServletUtil.setExpiresHeader(httpResponse, expirationTime.toDate());
        }

        HttpServletUtil.setCacheControl(httpResponse, cacheControlSettings);
    }
}

From source file:com.enonic.cms.web.portal.page.PortalResponseProcessor.java

License:Open Source License

private void setHttpCacheHeaders(final DateTime requestTime, final DateTime expirationTime,
        final boolean forceNoCache) {
    final Interval maxAge = new Interval(requestTime, expirationTime);

    @SuppressWarnings({ "UnnecessaryLocalVariable" })
    boolean notCachableByClient = forceNoCache;
    if (notCachableByClient) {
        HttpServletUtil.setCacheControlNoCache(httpResponse);
    } else {//from   w ww.j  a va2 s.c om
        HttpCacheControlSettings cacheControlSettings = new HttpCacheControlSettings();

        // To eliminate proxy caching of pages (decided by TSI)
        cacheControlSettings.publicAccess = false;

        boolean setCacheTimeToZero = dynamicResolversEnabled();

        if (setCacheTimeToZero) {
            cacheControlSettings.maxAgeSecondsToLive = new Long(0);
            HttpServletUtil.setExpiresHeader(httpResponse, requestTime.toDate());
        } else {
            cacheControlSettings.maxAgeSecondsToLive = maxAge.toDurationMillis() / SECOND_IN_MILLIS;
            HttpServletUtil.setExpiresHeader(httpResponse, expirationTime.toDate());
        }

        HttpServletUtil.setCacheControl(httpResponse, cacheControlSettings);
    }
}

From source file:com.metamx.druid.master.BalancerCostAnalyzer.java

License:Open Source License

/**
 * This defines the unnormalized cost function between two segments.  There is a base cost given by
 * the minimum size of the two segments and additional penalties.
 * recencyPenalty: it is more likely that recent segments will be queried together
 * dataSourcePenalty: if two segments belong to the same data source, they are more likely to be involved
 * in the same queries//from   ww  w .ja  v a  2 s  .  com
 * gapPenalty: it is more likely that segments close together in time will be queried together
 *
 * @param segment1 The first DataSegment.
 * @param segment2 The second DataSegment.
 *
 * @return The joint cost of placing the two DataSegments together on one node.
 */
public double computeJointSegmentCosts(final DataSegment segment1, final DataSegment segment2) {
    final Interval gap = segment1.getInterval().gap(segment2.getInterval());

    final double baseCost = Math.min(segment1.getSize(), segment2.getSize());
    double recencyPenalty = 1;
    double dataSourcePenalty = 1;
    double gapPenalty = 1;

    if (segment1.getDataSource().equals(segment2.getDataSource())) {
        dataSourcePenalty = 2;
    }

    double maxDiff = Math.max(referenceTimestamp.getMillis() - segment1.getInterval().getEndMillis(),
            referenceTimestamp.getMillis() - segment2.getInterval().getEndMillis());
    if (maxDiff < SEVEN_DAYS_IN_MILLIS) {
        recencyPenalty = 2 - maxDiff / SEVEN_DAYS_IN_MILLIS;
    }

    /** gap is null if the two segment intervals overlap or if they're adjacent */
    if (gap == null) {
        gapPenalty = 2;
    } else {
        long gapMillis = gap.toDurationMillis();
        if (gapMillis < THIRTY_DAYS_IN_MILLIS) {
            gapPenalty = 2 - gapMillis / THIRTY_DAYS_IN_MILLIS;
        }
    }

    final double cost = baseCost * recencyPenalty * dataSourcePenalty * gapPenalty;

    return cost;
}

From source file:com.metamx.druid.master.CostBalancerStrategy.java

License:Open Source License

/**
 * This defines the unnormalized cost function between two segments.  There is a base cost given by
 * the minimum size of the two segments and additional penalties.
 * recencyPenalty: it is more likely that recent segments will be queried together
 * dataSourcePenalty: if two segments belong to the same data source, they are more likely to be involved
 * in the same queries//from  www .j  a v  a2  s. c om
 * gapPenalty: it is more likely that segments close together in time will be queried together
 *
 * @param segment1 The first DataSegment.
 * @param segment2 The second DataSegment.
 *
 * @return The joint cost of placing the two DataSegments together on one node.
 */
public double computeJointSegmentCosts(final DataSegment segment1, final DataSegment segment2) {
    final Interval gap = segment1.getInterval().gap(segment2.getInterval());

    final double baseCost = Math.min(segment1.getSize(), segment2.getSize());
    double recencyPenalty = 1;
    double dataSourcePenalty = 1;
    double gapPenalty = 1;

    if (segment1.getDataSource().equals(segment2.getDataSource())) {
        dataSourcePenalty = 2;
    }

    double maxDiff = Math.max(referenceTimestamp.getMillis() - segment1.getInterval().getEndMillis(),
            referenceTimestamp.getMillis() - segment2.getInterval().getEndMillis());
    double segment1diff = referenceTimestamp.getMillis() - segment1.getInterval().getEndMillis();
    double segment2diff = referenceTimestamp.getMillis() - segment2.getInterval().getEndMillis();
    if (segment1diff < SEVEN_DAYS_IN_MILLIS && segment2diff < SEVEN_DAYS_IN_MILLIS) {
        recencyPenalty = (2 - segment1diff / SEVEN_DAYS_IN_MILLIS) * (2 - segment2diff / SEVEN_DAYS_IN_MILLIS);
    }

    /** gap is null if the two segment intervals overlap or if they're adjacent */
    if (gap == null) {
        gapPenalty = 2;
    } else {
        long gapMillis = gap.toDurationMillis();
        if (gapMillis < THIRTY_DAYS_IN_MILLIS) {
            gapPenalty = 2 - gapMillis / THIRTY_DAYS_IN_MILLIS;
        }
    }

    final double cost = baseCost * recencyPenalty * dataSourcePenalty * gapPenalty;

    return cost;
}

From source file:com.metamx.druid.VersionedIntervalTimeline.java

License:Open Source License

private void addIntervalToTimeline(Interval interval, TimelineEntry entry,
        NavigableMap<Interval, TimelineEntry> timeline) {
    if (interval != null && interval.toDurationMillis() > 0) {
        timeline.put(interval, entry);/* w  ww  . j  a v  a  2 s  .  c o m*/
    }
}