Example usage for java.util.stream IntStream range

List of usage examples for java.util.stream IntStream range

Introduction

In this page you can find the example usage for java.util.stream IntStream range.

Prototype

public static IntStream range(int startInclusive, int endExclusive) 

Source Link

Document

Returns a sequential ordered IntStream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1 .

Usage

From source file:org.apache.hadoop.hbase.client.TestAsyncGetMultiThread.java

@BeforeClass
public static void setUp() throws Exception {
    TEST_UTIL.getConfiguration().set(TABLES_ON_MASTER, "none");
    TEST_UTIL.getConfiguration().setLong(HBASE_CLIENT_META_OPERATION_TIMEOUT, 60000L);
    TEST_UTIL.getConfiguration().setLong(HBASE_RPC_READ_TIMEOUT_KEY, 1000L);
    TEST_UTIL.getConfiguration().setInt(HBASE_CLIENT_RETRIES_NUMBER, 1000);
    TEST_UTIL.getConfiguration().setInt(ByteBufferPool.MAX_POOL_SIZE_KEY, 100);
    TEST_UTIL.startMiniCluster(5);/* www .  j av a2s  .  com*/
    SPLIT_KEYS = new byte[8][];
    for (int i = 111; i < 999; i += 111) {
        SPLIT_KEYS[i / 111 - 1] = Bytes.toBytes(String.format("%03d", i));
    }
    TEST_UTIL.createTable(TABLE_NAME, FAMILY);
    TEST_UTIL.waitTableAvailable(TABLE_NAME);
    CONN = ConnectionFactory.createAsyncConnection(TEST_UTIL.getConfiguration());
    RawAsyncTable table = CONN.getRawTable(TABLE_NAME);
    List<CompletableFuture<?>> futures = new ArrayList<>();
    IntStream.range(0, COUNT).forEach(i -> futures.add(table.put(
            new Put(Bytes.toBytes(String.format("%03d", i))).addColumn(FAMILY, QUALIFIER, Bytes.toBytes(i)))));
    CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0])).get();
}

From source file:org.apache.james.jmap.methods.integration.cucumber.SetMailboxesMethodStepdefs.java

@Given("^mailbox \"([^\"]*)\" with (\\d+) messages$")
public void mailboxWithMessages(String mailboxName, int messageCount) throws Throwable {
    mainStepdefs.jmapServer.serverProbe().createMailbox("#private", userStepdefs.lastConnectedUser,
            mailboxName);//  ww  w .  ja v a 2 s  .  co  m
    MailboxPath mailboxPath = new MailboxPath(MailboxConstants.USER_NAMESPACE, userStepdefs.lastConnectedUser,
            mailboxName);
    IntStream.range(0, messageCount).forEach(Throwing.intConsumer(i -> appendMessage(mailboxPath, i)));
    mainStepdefs.awaitMethod.run();
}

From source file:org.esa.s3tbx.olci.radiometry.rayleigh.SpikeInterpolation.java

public static double getLowerBound(double[] doubles, double val) {
    final double[] xMin = new double[1];
    int length = doubles.length;
    IntStream.range(0, length).forEach(i -> {
        double v = doubles[i];
        xMin[0] = v < val ? v : xMin[0];
    });/*from  www  . jav  a 2  s  .com*/
    if (xMin[0] > val) {
        throw new IllegalArgumentException("Can find the closest min value of " + val);
    }
    return xMin[0];
}

From source file:org.apache.bookkeeper.clients.utils.TestNetUtils.java

@Test
public void testParseEndpoints() {
    List<String> hostnames = Lists.newArrayList("10.138.10.56", "10.138.10.57", "10.138.10.58");
    List<Integer> ports = Lists.newArrayList(1234, 2345, 3456);
    List<Endpoint> endpoints = IntStream.range(0, hostnames.size())
            .mapToObj(i -> createEndpoint(hostnames.get(i), ports.get(i))).collect(Collectors.toList());
    String endpointStr = StringUtils.join(IntStream.range(0, hostnames.size())
            .mapToObj(i -> hostnames.get(i) + ":" + ports.get(i)).collect(Collectors.toList()), ',');
    List<Endpoint> parsedEndpoints = parseEndpoints(endpointStr);
    assertEquals(endpoints, parsedEndpoints);
}

From source file:org.apache.sysml.runtime.controlprogram.paramserv.ParamServer.java

ParamServer(ListObject model, String aggFunc, Statement.PSUpdateType updateType, ExecutionContext ec,
        int workerNum) {
    _gradientsQueue = new LinkedBlockingDeque<>();
    _modelMap = new HashMap<>(workerNum);
    IntStream.range(0, workerNum).forEach(i -> {
        // Create a single element blocking queue for workers to receive the broadcasted model
        _modelMap.put(i, new ArrayBlockingQueue<>(1));
    });/*w w w  . ja  v a2s. com*/
    _model = model;
    _aggService = new AggregationService(aggFunc, updateType, ec, workerNum);
    try {
        _aggService.broadcastModel();
    } catch (InterruptedException e) {
        throw new DMLRuntimeException("Param server: failed to broadcast the initial model.", e);
    }
    BasicThreadFactory factory = new BasicThreadFactory.Builder().namingPattern("agg-service-pool-thread-%d")
            .build();
    _es = Executors.newSingleThreadExecutor(factory);
}

From source file:com.abixen.platform.service.businessintelligence.multivisualisation.service.impl.AbstractDatabaseService.java

public List<DataSourceColumnWeb> getColumns(Connection connection, String tableName) {

    List<DataSourceColumnWeb> columns = new ArrayList<>();

    try {// w ww  .  ja v a2s .  c o m
        ResultSetMetaData rsmd = getDatabaseMetaData(connection, tableName);

        int columnCount = rsmd.getColumnCount();

        IntStream.range(1, columnCount + 1).forEach(i -> {
            try {
                columns.add(prepareDataSourceColumns(rsmd, i));
            } catch (SQLException e) {
                throw new PlatformRuntimeException(e);
            }
        });

    } catch (SQLException e) {
        throw new PlatformRuntimeException(e);
    }

    return columns;
}

From source file:org.apache.tinkerpop.gremlin.driver.util.ProfilingApplication.java

public long execute() throws Exception {
    final AtomicInteger tooSlow = new AtomicInteger(0);

    final Client client = cluster.connect();
    final String executionId = "[" + executionName + "]";
    try {//from   w  w  w .j  a  v  a  2  s .c  o  m
        final CountDownLatch latch = new CountDownLatch(requests);
        client.init();

        final long start = System.nanoTime();
        IntStream.range(0, requests).forEach(i -> client.submitAsync(script).thenAcceptAsync(r -> {
            try {
                r.all().get(tooSlowThreshold, TimeUnit.MILLISECONDS);
            } catch (TimeoutException ex) {
                tooSlow.incrementAndGet();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                latch.countDown();
            }
        }, executor));

        // finish once all requests are accounted for
        latch.await();

        final long end = System.nanoTime();
        final long total = end - start;
        final double totalSeconds = total / 1000000000d;
        final long requestCount = requests;
        final long reqSec = Math.round(requestCount / totalSeconds);
        System.out.println(String.format(
                StringUtils.rightPad(executionId, 10)
                        + " requests: %s | time(s): %s | req/sec: %s | too slow: %s",
                requestCount, StringUtils.rightPad(String.valueOf(totalSeconds), 14),
                StringUtils.rightPad(String.valueOf(reqSec), 7), tooSlow.get()));
        return reqSec;
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        client.close();
    }
}

From source file:com.yahoo.elide.core.filter.FilterPredicate.java

/**
 * Compute the parameter value/name pairings.
 * @return the filter parameters for this predicate
 *//*from  ww w.  j a va 2 s .  c o  m*/
public List<FilterParameter> getParameters() {
    String baseName = String.format("%s_%s_", getFieldPath().replace(PERIOD, UNDERSCORE),
            Integer.toHexString(hashCode()));
    return IntStream.range(0, values.size())
            .mapToObj(idx -> new FilterParameter(String.format("%s%d", baseName, idx), values.get(idx)))
            .collect(Collectors.toList());
}

From source file:com.devicehive.service.DeviceCommandServiceTest.java

@Test
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
public void testFindCommandsByGuid() throws Exception {
    final List<String> guids = IntStream.range(0, 5).mapToObj(i -> UUID.randomUUID().toString())
            .collect(Collectors.toList());
    final Date timestampSt = timestampService.getDate();
    final Date timestampEnd = timestampService.getDate();
    final String parameters = "{\"param1\":\"value1\",\"param2\":\"value2\"}";

    final Set<String> guidsForSearch = new HashSet<>(Arrays.asList(guids.get(0), guids.get(2), guids.get(3)));

    final Map<String, DeviceCommand> commandMap = guidsForSearch.stream()
            .collect(Collectors.toMap(Function.identity(), guid -> {
                DeviceCommand command = new DeviceCommand();
                command.setId(System.nanoTime());
                command.setDeviceGuid(guid);
                command.setCommand(RandomStringUtils.randomAlphabetic(10));
                command.setTimestamp(timestampService.getDate());
                command.setParameters(new JsonStringWrapper(parameters));
                command.setStatus(DEFAULT_STATUS);
                return command;
            }));/*from ww w  .j ava  2s  .co m*/

    when(requestHandler.handle(any(Request.class))).then(invocation -> {
        Request request = invocation.getArgumentAt(0, Request.class);
        String guid = request.getBody().cast(CommandSearchRequest.class).getGuid();
        CommandSearchResponse response = new CommandSearchResponse();
        response.setCommands(Collections.singletonList(commandMap.get(guid)));
        return Response.newBuilder().withBody(response).buildSuccess();
    });

    deviceCommandService.find(guidsForSearch, Collections.emptySet(), timestampSt, timestampEnd, DEFAULT_STATUS)
            .thenAccept(commands -> {
                assertEquals(3, commands.size());
                assertEquals(new HashSet<>(commandMap.values()), new HashSet<>(commands));
            }).get(15, TimeUnit.SECONDS);

    verify(requestHandler, times(3)).handle(argument.capture());
}

From source file:edu.pitt.dbmi.ccd.anno.error.NotFoundException.java

/**
 * Build error message/*w  w w . j av a 2s  .  c  om*/
 */
private String buildMessage() {
    final StringBuilder builder = new StringBuilder(String.format(NOT_FOUND, entity));
    final int len = (isEmpty(fields) || isEmpty(values)) ? 0 : Math.min(fields.length, values.length);
    if (len > 0) {
        builder.append(WITH).append(fields[0]).append(SEP).append(values[0]);
        if (len > 1) {
            IntStream.range(1, len).forEach(i -> {
                final String f = fields[i];
                final Object v = values[i];
                if (!isEmpty(f) && !isEmpty(v)) {
                    builder.append(AND).append(f).append(SEP).append(v);
                }
            });
        }
    }
    return builder.toString();
}