Example usage for org.apache.commons.lang3 Range between

List of usage examples for org.apache.commons.lang3 Range between

Introduction

In this page you can find the example usage for org.apache.commons.lang3 Range between.

Prototype

public static <T extends Comparable<T>> Range<T> between(final T fromInclusive, final T toInclusive) 

Source Link

Document

Obtains a range with the specified minimum and maximum values (both inclusive).

The range uses the natural ordering of the elements to determine where values lie in the range.

The arguments may be passed in the order (min,max) or (max,min).

Usage

From source file:org.apache.apex.examples.mobile.Application.java

@Override
public void populateDAG(DAG dag, Configuration conf) {
    String lPhoneRange = conf.get(PHONE_RANGE_PROP, null);
    if (lPhoneRange != null) {
        String[] tokens = lPhoneRange.split("-");
        if (tokens.length != 2) {
            throw new IllegalArgumentException("Invalid range: " + lPhoneRange);
        }//from   w ww .ja  v a  2  s  .c o  m
        this.phoneRange = Range.between(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]));
    }
    LOG.debug("Phone range {}", this.phoneRange);

    RandomEventGenerator phones = dag.addOperator("Receiver", RandomEventGenerator.class);
    phones.setMinvalue(this.phoneRange.getMinimum());
    phones.setMaxvalue(this.phoneRange.getMaximum());

    PhoneMovementGenerator movementGen = dag.addOperator("LocationFinder", PhoneMovementGenerator.class);
    dag.setAttribute(movementGen, OperatorContext.COUNTERS_AGGREGATOR,
            new BasicCounters.LongAggregator<MutableLong>());

    StatelessThroughputBasedPartitioner<PhoneMovementGenerator> partitioner = new StatelessThroughputBasedPartitioner<PhoneMovementGenerator>();
    partitioner.setCooldownMillis(conf.getLong(COOL_DOWN_MILLIS, 45000));
    partitioner.setMaximumEvents(conf.getLong(MAX_THROUGHPUT, 30000));
    partitioner.setMinimumEvents(conf.getLong(MIN_THROUGHPUT, 10000));
    dag.setAttribute(movementGen, OperatorContext.STATS_LISTENERS,
            Arrays.asList(new StatsListener[] { partitioner }));
    dag.setAttribute(movementGen, OperatorContext.PARTITIONER, partitioner);

    // generate seed numbers
    Random random = new Random();
    int maxPhone = phoneRange.getMaximum() - phoneRange.getMinimum();
    int phonesToDisplay = conf.getInt(TOTAL_SEED_NOS, 10);
    for (int i = phonesToDisplay; i-- > 0;) {
        int phoneNo = phoneRange.getMinimum() + random.nextInt(maxPhone + 1);
        LOG.info("seed no: " + phoneNo);
        movementGen.phoneRegister.add(phoneNo);
    }
    // done generating data
    LOG.info("Finished generating seed data.");

    URI uri = PubSubHelper.getURI(dag);
    PubSubWebSocketOutputOperator<Object> wsOut = dag.addOperator("LocationResults",
            new PubSubWebSocketOutputOperator<Object>());
    wsOut.setUri(uri);
    PubSubWebSocketInputOperator<Map<String, String>> wsIn = dag.addOperator("QueryLocation",
            new PubSubWebSocketInputOperator<Map<String, String>>());
    wsIn.setUri(uri);
    // default partitioning: first connected stream to movementGen will be partitioned
    dag.addStream("Phone-Data", phones.integer_data, movementGen.data);
    dag.addStream("Results", movementGen.locationQueryResult, wsOut.input);
    dag.addStream("Query", wsIn.outputPort, movementGen.phoneQuery);
}

From source file:org.apache.bigtop.bigpetstore.generator.PetStoreTransactionInputSplit.java

public void readFields(DataInput dataInputStream) throws IOException {
    records = dataInputStream.readInt();
    state = State.valueOf(dataInputStream.readUTF());
    customerIdRange = Range.between(dataInputStream.readLong(), dataInputStream.readLong());
}

From source file:org.apache.bigtop.bigpetstore.generator.PetStoreTransactionsInputFormat.java

@Override
public List<InputSplit> getSplits(JobContext arg) throws IOException {
    int numRecordsDesired = arg.getConfiguration()
            .getInt(PetStoreTransactionsInputFormat.props.bigpetstore_records.name(), -1);
    if (numRecordsDesired == -1) {
        throw new RuntimeException(
                "# of total records not set in configuration object: " + arg.getConfiguration());
    }//from   w w  w  .java 2  s.  c  o m

    List<InputSplit> list = new ArrayList<InputSplit>();
    long customerIdStart = 1;
    for (State s : State.values()) {
        int numRecords = numRecords(numRecordsDesired, s.probability);
        // each state is assigned a range of customer-ids from which it can choose.
        // The number of customers can be as many as the number of transactions.
        Range<Long> customerIdRange = Range.between(customerIdStart, customerIdStart + numRecords - 1);
        PetStoreTransactionInputSplit split = new PetStoreTransactionInputSplit(numRecords, customerIdRange, s);
        System.out.println(s + " _ " + split.records);
        list.add(split);
        customerIdStart += numRecords;
    }
    return list;
}

From source file:org.apache.metron.profiler.client.stellar.IntervalPredicateTest.java

@Test
public void testBasicTest() {
    List<Range<Long>> intervals = new ArrayList<Range<Long>>() {
        {//from  w w  w.j ava  2s  .c  o  m
            add(Range.between(0L, 10L));
            add(Range.between(20L, 30L));
            add(Range.between(40L, 50L));
        }
    };
    IntervalPredicate<Long> predicate = new IntervalPredicate.Identity(intervals);
    Assert.assertTrue(predicate.test(0L));
    Assert.assertTrue(predicate.test(10L));
    Assert.assertTrue(predicate.test(5L));
    Assert.assertFalse(predicate.test(51L));
    Assert.assertFalse(predicate.test(15L));
}

From source file:org.apache.metron.profiler.client.stellar.IntervalPredicateTest.java

@Test
public void testWithOverlap() {
    List<Range<Long>> intervals = new ArrayList<Range<Long>>() {
        {//from w ww. j a  v a 2  s .  c o  m
            add(Range.between(0L, 10L));
            add(Range.between(5L, 30L));
            add(Range.between(40L, 50L));
        }
    };
    IntervalPredicate<Long> predicate = new IntervalPredicate.Identity(intervals);
    Assert.assertTrue(predicate.test(0L));
    Assert.assertTrue(predicate.test(5L));
    Assert.assertTrue(predicate.test(30L));
    Assert.assertTrue(predicate.test(10L));
    Assert.assertFalse(predicate.test(51L));
    Assert.assertTrue(predicate.test(15L));
    Assert.assertFalse(predicate.test(31L));
    Assert.assertTrue(predicate.test(45L));
}

From source file:org.apache.metron.profiler.client.stellar.IntervalPredicateTest.java

@Test
public void testTrivialCase() {
    List<Range<Long>> intervals = new ArrayList<Range<Long>>() {
        {// www. j a v  a  2s  . c  o  m
            add(Range.between(0L, 10L));
        }
    };
    IntervalPredicate<Long> predicate = new IntervalPredicate.Identity(intervals);
    Assert.assertTrue(predicate.test(0L));
    Assert.assertTrue(predicate.test(5L));
    Assert.assertTrue(predicate.test(10L));
    Assert.assertFalse(predicate.test(51L));
    Assert.assertFalse(predicate.test(15L));
}

From source file:org.apache.metron.profiler.client.stellar.IntervalPredicateTest.java

@Test
public void testDegenerateCase() {
    List<Range<Long>> intervals = new ArrayList<Range<Long>>() {
        {//  w  w  w .  j a  v  a2 s. co m
            add(Range.between(10L, 10L));
        }
    };
    IntervalPredicate<Long> predicate = new IntervalPredicate.Identity(intervals);
    Assert.assertFalse(predicate.test(0L));
    Assert.assertFalse(predicate.test(5L));
    Assert.assertTrue(predicate.test(10L));
    Assert.assertFalse(predicate.test(11L));
}

From source file:org.apache.metron.profiler.client.window.Window.java

/**
 * Compute the set of sorted (oldest to newest) window intervals relative to the passed timestamp
 * given inclusion and exclusion predicates.
 *
 * @param now/* ww  w  .j av a 2s  .c o m*/
 * @return
 */
public List<Range<Long>> toIntervals(long now) {
    List<Range<Long>> intervals = new ArrayList<>();
    long startMillis = getStartMillis(now);
    long endMillis = getEndMillis(now);
    Iterable<Predicate<Long>> includes = getIncludes(now);
    Iterable<Predicate<Long>> excludes = getExcludes(now);
    //if we don't have a skip distance, then we just skip past everything to make the window dense
    long skipDistance = getSkipDistance().orElse(Long.MAX_VALUE);
    //if we don't have a window width, then we want the window to be completely dense.
    Optional<Long> binWidthOpt = getBinWidth();
    long binWidth = binWidthOpt.isPresent() ? binWidthOpt.get() : endMillis - startMillis;

    for (long left = startMillis; left >= 0 && left + binWidth <= endMillis; left += skipDistance) {
        Range<Long> interval = Range.between(left, left + binWidth);
        boolean include = includes.iterator().hasNext() ? false : true;
        for (Predicate<Long> inclusionPredicate : includes) {
            include |= inclusionPredicate.test(left);
        }
        if (include) {
            for (Predicate<Long> exclusionPredicate : excludes) {
                include &= !exclusionPredicate.test(left);
            }
        }
        if (include) {
            intervals.add(interval);
        }
    }
    return intervals;
}

From source file:org.bitbucket.mlopatkin.android.logviewer.TooltipGenerator.java

@Override
public void highlightText(int from, int to) {
    highlightRanges.add(Range.between(from, to));

}

From source file:org.gbif.ipt.struts2.converter.CoordinateFormatConverter.java

@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
    // The null value is needed to validate in EmlValidator.java class
    if (values[0].length() == 0) {
        return null;
    }// w ww .j  av  a2  s  .  c  om
    // The full name of the property which call the method contained in the Map context
    Object coordObject = context.get(ANGLE);
    // The latitude is validating in a range of doubles
    // validate coordinates in case the action context doesn't work properly.
    if (coordObject == null) {
        throw new TypeConversionException("Invalid decimal number: " + values[0]);
    } else {
        String coordinate = context.get(ANGLE).toString();
        // Assign the values of the range depending the property who calls the method.
        Range<Double> range;
        if (coordinate.equals(CoordinateUtils.LATITUDE)) {
            // The range of the latitude coordinate. (-90,90)
            range = Range.between(CoordinateUtils.MIN_LATITUDE, CoordinateUtils.MAX_LATITUDE);
        } else {
            // The range of the longitude coordinate. (-180,180)
            range = Range.between(CoordinateUtils.MIN_LONGITUDE, CoordinateUtils.MAX_LONGITUDE);
        }

        Double number;
        try {
            // Converts String to double if fails throws a NumberFormatException.
            // If the String contains a comma, a character, it throws the exception.
            number = Double.parseDouble(values[0]);
            // If the value is in the range, returns the double.
            if (range.contains(number)) {
                return number;
            } else {
                throw new TypeConversionException("Invalid decimal number: " + values[0]);
            }
        } catch (NumberFormatException e) {
            // Creating a pattern which will convert the comma to period
            // It will return a ParseException if the format was wrong.
            DecimalFormatSymbols symbols = new DecimalFormatSymbols();
            symbols.setDecimalSeparator(ALTERNATIVE_DECIMAL_SEPARATOR);
            DecimalFormat decimal = new DecimalFormat(DECIMAL_PATTERN, symbols);
            try {
                number = decimal.parse(values[0]).doubleValue();
                if (range.contains(number)) {
                    return number;
                } else {
                    throw new TypeConversionException("Invalid decimal number: " + values[0]);
                }
            } catch (ParseException e1) {
                throw new TypeConversionException("Invalid decimal number: " + values[0]);
            }
        }
    }
}