Example usage for org.joda.time Interval getStartMillis

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

Introduction

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

Prototype

public long getStartMillis() 

Source Link

Document

Gets the start of this time interval which is inclusive.

Usage

From source file:com.github.dbourdette.otto.web.util.RandomDateUtils.java

License:Apache License

public static DateTime in(Interval interval) {
    Random random = new Random();

    long millis = (long) ((interval.getEndMillis() - interval.getStartMillis()) * random.nextDouble());

    return interval.getStart().plus(millis);
}

From source file:com.jeklsoft.cassandraclient.astyanax.AstyanaxProtocolBufferWithStandardColumnExample.java

License:Apache License

@Override
public List<Reading> querySensorReadingsByInterval(UUID sensorId, Interval interval, int maxToReturn) {

    List<Reading> readings = new ArrayList<Reading>();

    ByteBufferRange range = new RangeBuilder().setLimit(maxToReturn).setStart(interval.getStartMillis())
            .setEnd(interval.getEndMillis()).build();

    RowQuery<UUID, DateTime> query = keyspace.prepareQuery(columnFamilyInfo).getKey(sensorId).autoPaginate(true)
            .withColumnRange(range);/*  w w  w .j ava  2  s . com*/

    try {
        // Again query.execute() is available here is synchronous behavior desired.

        Future<OperationResult<ColumnList<DateTime>>> future = query.executeAsync();

        // time passes...

        OperationResult<ColumnList<DateTime>> result = future.get();

        ColumnList columns = result.getResult();

        Iterator ii = columns.iterator();
        while (ii.hasNext()) {
            Column column = (Column) ii.next();
            DateTime timestamp = (DateTime) column.getName();
            Reading reading = new Reading(sensorId, timestamp,
                    (Reading) column.getValue(ReadingSerializer.get()));
            readings.add(reading);
        }
    } catch (ConnectionException e) {
        throw new RuntimeException("Query failed", e);
    } catch (InterruptedException e) {
        throw new RuntimeException("Query failed", e);
    } catch (ExecutionException e) {
        throw new RuntimeException("Query failed", e);
    }

    return readings;
}

From source file:com.jeklsoft.cassandraclient.hector.HectorHeterogeneousSuperColumnExample.java

License:Apache License

@Override
public List<Reading> querySensorReadingsByInterval(UUID sensorId, Interval interval, int maxToReturn) {
    SuperSliceQuery query = HFactory.createSuperSliceQuery(keyspace, us, ls, ss, ByteBufferSerializer.get());

    query.setColumnFamily(columnFamilyName).setKey(sensorId).setRange(interval.getStartMillis(),
            interval.getEndMillis(), false, maxToReturn);

    QueryResult<SuperSlice<UUID, String, ByteBuffer>> result = query.execute();

    List<HSuperColumn<UUID, String, ByteBuffer>> rows = result.get().getSuperColumns();

    List<Reading> readings = new ArrayList<Reading>();

    for (HSuperColumn row : rows) {
        Reading reading = getReadingFromSuperColumn(sensorId, row);
        readings.add(reading);//from   w  w w .j av  a  2  s .c om
    }
    return readings;
}

From source file:com.jeklsoft.cassandraclient.hector.HectorProtocolBufferWithStandardColumnExample.java

License:Apache License

@Override
public List<Reading> querySensorReadingsByInterval(UUID sensorId, Interval interval, int maxToReturn) {
    SliceQuery<UUID, DateTime, Reading> query = HFactory.createSliceQuery(keyspace, us, ds, rs);

    query.setColumnFamily(columnFamilyName).setKey(sensorId).setRange(new DateTime(interval.getStartMillis()),
            new DateTime(interval.getEndMillis()), false, maxToReturn);

    QueryResult<ColumnSlice<DateTime, Reading>> result = query.execute();

    List<HColumn<DateTime, Reading>> columns = result.get().getColumns();

    List<Reading> readings = new ArrayList<Reading>();

    for (HColumn column : columns) {
        DateTime timestamp = (DateTime) column.getName();
        Reading reading = new Reading(sensorId, timestamp, (Reading) column.getValue());
        readings.add(reading);/*from  w  ww  .  j a va2s. co  m*/
    }

    return readings;
}

From source file:com.linkedin.pinot.controller.api.resources.PinotSegmentUploadRestletResource.java

License:Apache License

/**
 * Returns true if:/*www . ja  v  a  2s.  c  o m*/
 * - Segment does not have a start/end time, OR
 * - The start/end time are in a valid range (Jan 01 1971 - Jan 01, 2071)
 * @param metadata Segment metadata
 * @return
 */
private boolean isSegmentTimeValid(SegmentMetadata metadata) {
    Interval interval = metadata.getTimeInterval();
    if (interval == null) {
        return true;
    }

    long startMillis = interval.getStartMillis();
    long endMillis = interval.getEndMillis();

    if (!TimeUtils.timeValueInValidRange(startMillis) || !TimeUtils.timeValueInValidRange(endMillis)) {
        Date minDate = new Date(TimeUtils.getValidMinTimeMillis());
        Date maxDate = new Date(TimeUtils.getValidMaxTimeMillis());

        LOGGER.error(
                "Invalid start time '{}ms' or end time '{}ms' for segment {}, must be between '{}' and '{}' (timecolumn {}, timeunit {})",
                interval.getStartMillis(), interval.getEndMillis(), metadata.getName(), minDate, maxDate,
                metadata.getTimeColumn(), metadata.getTimeUnit().toString());
        return false;
    }

    return true;
}

From source file:com.linkedin.pinot.controller.api.restlet.resources.PinotSegmentUploadRestletResource.java

License:Apache License

/**
 * Returns true if:/*  ww w.  ja  v  a2  s .c o m*/
 * - Segment does not have a start/end time, OR
 * - The start/end time are in a valid range (Jan 01 1971 - Jan 01, 2071)
 * @param metadata
 * @return
 */
private boolean isSegmentTimeValid(SegmentMetadata metadata) {
    Interval interval = metadata.getTimeInterval();
    if (interval == null) {
        return true;
    }

    long startMillis = interval.getStartMillis();
    long endMillis = interval.getEndMillis();

    if (!TimeUtils.timeValueInValidRange(startMillis) || !TimeUtils.timeValueInValidRange(endMillis)) {
        Date startDate = new Date(interval.getStartMillis());
        Date endDate = new Date(interval.getEndMillis());

        Date minDate = new Date(TimeUtils.getValidMinTimeMillis());
        Date maxDate = new Date(TimeUtils.getValidMaxTimeMillis());

        LOGGER.error("Invalid start time '{}' or end time '{}' for segment, must be between '{}' and '{}'",
                startDate, endDate, minDate, maxDate);
        return false;
    }

    return true;
}

From source file:com.linkedin.pinot.controller.api.restlet.resources.PinotSegmentUploadRestletResource.java

License:Apache License

/**
 * Returns true if segment start and end time are between a valid range, or if
 * segment does not have a time interval.
 * The current valid range is between 1971 and 2071.
 * @param metadata/*from w w w .  jav a2  s . c o  m*/
 * @return
 */
private boolean validateSegmentTimeRange(SegmentMetadata metadata) {
    Interval timeInterval = metadata.getTimeInterval();
    return (timeInterval == null || (TimeUtils.timeValueInValidRange(timeInterval.getStartMillis()))
            && TimeUtils.timeValueInValidRange(timeInterval.getEndMillis()));
}

From source file:com.linkedin.pinot.controller.validation.ValidationManager.java

License:Apache License

/**
 * Computes a list of missing intervals, given a list of existing intervals and the expected frequency of the
 * intervals.//from  w  w w. j a va2  s. c o m
 *
 * @param segmentIntervals The list of existing intervals
 * @param frequency The expected interval frequency
 * @return The list of missing intervals
 */
public static List<Interval> computeMissingIntervals(List<Interval> segmentIntervals, Duration frequency) {
    // Sanity check for freuency
    if (frequency == null) {
        return Collections.emptyList();
    }

    // Default segment granularity to day level if its small than hours.
    if (frequency.getMillis() < Duration.standardHours(1).getMillis()) {
        frequency = Duration.standardDays(1);
    }

    // If there are less than two segments, none can be missing
    if (segmentIntervals.size() < 2) {
        return Collections.emptyList();
    }

    // Sort the intervals by ascending starting time
    List<Interval> sortedSegmentIntervals = new ArrayList<Interval>(segmentIntervals);
    Collections.sort(sortedSegmentIntervals, new Comparator<Interval>() {
        @Override
        public int compare(Interval first, Interval second) {
            if (first.getStartMillis() < second.getStartMillis())
                return -1;
            else if (second.getStartMillis() < first.getStartMillis())
                return 1;
            return 0;
        }
    });

    // Find the minimum starting time and maximum ending time
    final long startTime = sortedSegmentIntervals.get(0).getStartMillis();
    long endTime = Long.MIN_VALUE;
    for (Interval sortedSegmentInterval : sortedSegmentIntervals) {
        if (endTime < sortedSegmentInterval.getEndMillis()) {
            endTime = sortedSegmentInterval.getEndMillis();
        }
    }

    final long frequencyMillis = frequency.getMillis();
    int lastEndIntervalCount = 0;
    List<Interval> missingIntervals = new ArrayList<Interval>(10);
    for (Interval segmentInterval : sortedSegmentIntervals) {
        int startIntervalCount = (int) ((segmentInterval.getStartMillis() - startTime) / frequencyMillis);
        int endIntervalCount = (int) ((segmentInterval.getEndMillis() - startTime) / frequencyMillis);

        // If there is at least one complete missing interval between the end of the previous interval and the start of
        // the current interval, then mark the missing interval(s) as missing
        if (lastEndIntervalCount < startIntervalCount - 1) {
            for (int missingIntervalIndex = lastEndIntervalCount
                    + 1; missingIntervalIndex < startIntervalCount; ++missingIntervalIndex) {
                missingIntervals.add(new Interval(startTime + frequencyMillis * missingIntervalIndex,
                        startTime + frequencyMillis * (missingIntervalIndex + 1) - 1));
            }
        }

        lastEndIntervalCount = Math.max(lastEndIntervalCount, endIntervalCount);
    }

    return missingIntervals;
}

From source file:com.marand.thinkmed.medications.service.impl.MedicationsServiceImpl.java

License:Open Source License

@Override
@Transactional(readOnly = true)//  w  w  w.j  av  a 2 s  .  c  o m
@ServiceMethod(auditing = @Auditing(level = Level.WITHOUT_OUTPUT_RESULTS))
@EhrSessioned
public TherapyTimelineDto getTherapyTimeline(@Nonnull final String patientId, @Nonnull final Interval interval,
        @Nonnull final TherapySortTypeEnum sortTypeEnum, final boolean hidePastTherapies,
        final boolean hideFutureTherapies, @Nonnull final PatientDataForMedicationsDto patientData,
        final RoundsIntervalDto roundsInterval, final Locale locale) {
    StringUtils.checkNotBlank(patientId, "patientId must be defined!");
    Preconditions.checkNotNull(interval, "interval must not be null!");
    Preconditions.checkNotNull(sortTypeEnum, "sortTypeEnum must not be null!");
    Preconditions.checkNotNull(patientData, "patientData must not be null!");

    final Interval therapiesSearchInterval = hideFutureTherapies ? interval
            : Intervals.infiniteFrom(new DateTime(interval.getStartMillis()));

    final List<Pair<MedicationOrderComposition, MedicationInstructionInstruction>> instructionPairs = medicationsOpenEhrDao
            .findMedicationInstructions(patientId, therapiesSearchInterval, null);

    final List<AdministrationDto> administrations = administrationProvider
            .getTherapiesAdministrations(patientId, instructionPairs, null);

    final List<String> therapyIds = instructionPairs.stream().map(instructionPair -> TherapyIdUtils
            .createTherapyId(instructionPair.getFirst(), instructionPair.getSecond()))
            .collect(Collectors.toList());

    final List<AdministrationTaskDto> tasks = medicationsTasksProvider.findAdministrationTasks(patientId,
            therapyIds, interval, true);

    tasks.addAll(infusionBagTaskProvider.findInfusionBagTasks(patientId, therapyIds, interval));

    final DateTime when = RequestContextHolder.getContext().getRequestTimestamp();
    return overviewContentProvider.getTherapyTimeline(patientId, administrations, tasks, instructionPairs,
            sortTypeEnum, hidePastTherapies, patientData, interval, roundsInterval, locale, when);
}

From source file:com.marand.thinkmed.medications.service.impl.MedicationsServiceImpl.java

License:Open Source License

@Override
@Transactional(readOnly = true)/*from   ww  w  . ja  v a  2  s .co  m*/
@ServiceMethod(auditing = @Auditing(level = Level.WITHOUT_OUTPUT_RESULTS))
@EhrSessioned
public TherapyTimelineDto getPharmacistTimeline(@Nonnull final String patientId,
        @Nonnull final Interval interval, @Nonnull final TherapySortTypeEnum sortTypeEnum,
        final boolean hidePastTherapies, @Nonnull final PatientDataForMedicationsDto patientData,
        final RoundsIntervalDto roundsInterval, final Locale locale) {
    StringUtils.checkNotBlank(patientId, "patientId must be defined!");
    Preconditions.checkNotNull(interval, "interval must not be null!");
    Preconditions.checkNotNull(sortTypeEnum, "sortTypeEnum must not be null!");
    Preconditions.checkNotNull(patientData, "patientData must not be null!");

    final Interval intervalToInfinity = Intervals.infiniteFrom(new DateTime(interval.getStartMillis()));

    final List<Pair<MedicationOrderComposition, MedicationInstructionInstruction>> instructionPairs = medicationsOpenEhrDao
            .findMedicationInstructions(patientId, intervalToInfinity, null);

    final List<String> therapyIds = instructionPairs.stream().map(instructionPair -> TherapyIdUtils
            .createTherapyId(instructionPair.getFirst(), instructionPair.getSecond()))
            .collect(Collectors.toList());

    final List<AdministrationTaskDto> tasks = medicationsTasksProvider
            .findAdministrationTasks(patientId, therapyIds, null, null, null, false).stream()
            .map(taskDto -> administrationTaskConverter.convertTaskToAdministrationTask(taskDto))
            .collect(Collectors.toList());

    final DateTime when = RequestContextHolder.getContext().getRequestTimestamp();
    return overviewContentProvider.getTherapyTimeline(patientId, Collections.emptyList(), tasks,
            instructionPairs, sortTypeEnum, hidePastTherapies, patientData, null, roundsInterval, locale, when);
}