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:com.qpark.eip.core.spring.lockedoperation.EipTest.java

/**
 * Test to run several asynchronous {@link LockableOperation}s in parallel.
 *///w  w w.  j av a  2 s .  co  m
@Test
public void testLockableOperationTestAsyncCall() {
    this.logger.debug("+testLockableOperationTestAsyncCall");
    int threadCount = 4;
    OperationEventEnumType start = OperationEventEnumType.START;
    LockableOperationContext context = new LockableOperationContext();
    List<OperationStateEnumType> status = new ArrayList<>();
    IntStream.range(0, threadCount).forEach(i -> {
        OperationStateEnumType value = this.operationAsync.runOperation(this.operationAsync.getUUID(), start,
                context);
        status.add(value);
        this.logger.debug(" testLockableOperationTestAsyncCall returned {}", value);
    });

    int runnings = status.stream().filter(s -> s.equals(OperationStateEnumType.RUNNING))
            .collect(Collectors.toList()).size();
    int idle = status.stream().filter(s -> s.equals(OperationStateEnumType.STARTED))
            .collect(Collectors.toList()).size();
    Assert.assertEquals("No the right number of async proccesses got the RUNNING return.", runnings,
            threadCount - 1);
    Assert.assertEquals("To many STARTED async processes", idle, 1);

    EipTest.sleep();

    OperationStateEnumType idleResult = this.operationSync.runOperation(this.operationSync.getUUID(),
            OperationEventEnumType.CHECK_STATE, context);
    Assert.assertEquals("Cleanup missing at sync processes", idleResult, OperationStateEnumType.IDLE);
    this.logger.debug("+testLockableOperationTestAsyncCall");
}

From source file:com.cloudbees.jenkins.support.filter.FilteredOutputStreamTest.java

@Issue("JENKINS-21670")
@Test//  w  ww  .  j av  a 2s. co m
public void shouldModifyStream() throws IOException {
    final int nrLines = FilteredConstants.DEFAULT_DECODER_CAPACITY;
    String inputContents = IntStream.range(0, nrLines).mapToObj(i -> "Line " + i)
            .collect(joining(System.lineSeparator()));
    CharSequenceInputStream input = new CharSequenceInputStream(inputContents, UTF_8);
    ContentFilter filter = s -> s.replace("Line", "Network");
    FilteredOutputStream output = new FilteredOutputStream(testOutput, filter);

    IOUtils.copy(input, output);
    output.flush();
    String outputContents = new String(testOutput.toByteArray(), UTF_8);

    assertThat(outputContents).isNotEmpty();
    String[] lines = FilteredConstants.EOL.split(outputContents);
    assertThat(lines).allMatch(line -> !line.contains("Line") && line.startsWith("Network")).hasSize(nrLines);
}

From source file:org.apache.james.backends.cassandra.migration.CassandraMigrationService.java

public Migration upgradeToVersion(SchemaVersion newVersion) {
    SchemaVersion currentVersion = getCurrentVersion().orElse(DEFAULT_VERSION);

    Migration migrationCombination = IntStream.range(currentVersion.getValue(), newVersion.getValue()).boxed()
            .map(SchemaVersion::new).map(this::validateVersionNumber).map(this::toMigration)
            .reduce(Migration.IDENTITY, Migration::combine);
    return new MigrationTask(migrationCombination, newVersion);
}

From source file:it.unibo.alchemist.boundary.monitors.PositionSampler.java

@Override
protected Iterable<Position> computeSamples(final Environment<T> env, final Reaction<T> r, final Time time,
        final long step) {
    if (!HashUtils.pointerEquals(samples, sCache) || !HashUtils.pointerEquals(env, envCache)) {
        envCache = env;//from   w  w  w.  ja v  a 2 s.co m
        try {
            final int n = Integer.parseInt(samples);
            if (n > 0) {
                sCache = samples;
                final double sx = env.getSize()[0];
                final double sy = env.getSize()[1];
                final double dx = env.getOffset()[0];
                final double dy = env.getOffset()[1];
                final int nx = (int) round(sqrt(sx / sy * n));
                final int ny = (int) round(sqrt(sy / sx * n));
                final double stepx = sx / nx;
                final double stepy = sy / ny;
                final Environment2DWithObstacles<?, ?> oenv = env instanceof Environment2DWithObstacles<?, ?>
                        ? (Environment2DWithObstacles<?, ?>) env
                        : null;
                result = IntStream.range(0, n).collect(ArrayList::new, (array, i) -> {
                    final double px = dx + stepx * (i % nx);
                    final double py = dy + stepy * ((i / nx) % ny);
                    final Position pos = new Continuous2DEuclidean(px, py);
                    if (oenv == null
                            || !oenv.intersectsObstacle(nextDown(px), nextDown(py), nextUp(px), nextUp(py))) {
                        array.add(pos);
                    }
                }, (c1, c2) -> c1.addAll(c2));
            } else {
                L.warn("Update discarded: Samples must be a positive integer value.");
            }
        } catch (NumberFormatException e) {
            L.warn("Update discarded: Samples must be a positive integer value.", e);
        }
    }
    return result;
}

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

protected static void setUp(MemoryCompactionPolicy memoryCompaction) throws Exception {
    TEST_UTIL.getConfiguration().set(TABLES_ON_MASTER, "none");
    TEST_UTIL.getConfiguration().setLong(HBASE_CLIENT_META_OPERATION_TIMEOUT, 60000L);
    TEST_UTIL.getConfiguration().setInt(ByteBufferPool.MAX_POOL_SIZE_KEY, 100);
    TEST_UTIL.getConfiguration().set(CompactingMemStore.COMPACTING_MEMSTORE_TYPE_KEY,
            String.valueOf(memoryCompaction));

    TEST_UTIL.startMiniCluster(5);/*from www  .j  av  a  2s . c o  m*/
    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()).get();
    TABLE = CONN.getRawTableBuilder(TABLE_NAME).setReadRpcTimeout(1, TimeUnit.SECONDS).setMaxRetries(1000)
            .build();
    TABLE.putAll(IntStream.range(0, COUNT).mapToObj(i -> new Put(Bytes.toBytes(String.format("%03d", i)))
            .addColumn(FAMILY, QUALIFIER, Bytes.toBytes(i))).collect(Collectors.toList())).get();
}

From source file:Combiner.MaxDepthCombiner.java

public List<SingleGenotypeProbability> combine(List<SingleGenotypeProbability> called,
        List<SingleGenotypeProbability> imputed, List<SingleGenotypeReads> reads) {
    if (!SingleGenotypePosition.samePositions(called, imputed)) {
        //Throw Exception
    }//  w  w  w. j a  va 2s . com

    Progress progress = ProgressFactory.get(called.size());
    return IntStream.range(0, called.size()).parallel().mapToObj(i -> {
        SingleGenotypeProbability c = called.get(i);
        SingleGenotypeProbability sgp = new SingleGenotypeProbability(c.getSample(), c.getSNP(),
                combineSingle(c.getProb(), imputed.get(i).getProb(), reads.get(i).getReads()));
        progress.done();
        return sgp;
    }).collect(Collectors.toCollection(ArrayList::new));
}

From source file:org.ballerinalang.langserver.command.testgen.ValueSpaceGenerator.java

/**
 * Returns a value space for a given BLangNode.
 *
 * @param importsAcceptor imports acceptor
 * @param currentPkgId    current package id
 * @param bLangNode       BLangNode to evaluate
 * @param template        templates to be modified
 * @return {@link String}  modified templates
 * @see #createTemplateArray(int)/*from ww  w .  j  av  a2  s.  co  m*/
 */
public static String[] getValueSpaceByNode(BiConsumer<String, String> importsAcceptor, PackageID currentPkgId,
        BLangNode bLangNode, String[] template) {
    if (bLangNode.type == null && bLangNode instanceof BLangTupleDestructure) {
        // Check for tuple assignment eg. (int, int)
        List<BLangExpression> varRefs = ((BLangTupleDestructure) bLangNode).getVariableRefs();
        String[][] list = new String[varRefs.size()][template.length];
        IntStream.range(0, varRefs.size()).forEach(j -> {
            BLangExpression bLangExpression = varRefs.get(j);
            if (bLangExpression.type != null) {
                String[] values = getValueSpaceByType(importsAcceptor, currentPkgId, bLangExpression.type,
                        createTemplateArray(template.length));
                IntStream.range(0, values.length).forEach(i -> list[i][j] = values[i]);
            }
        });
        IntStream.range(0, template.length).forEach(index -> {
            template[index] = template[index].replace(PLACE_HOLDER, "(" + String.join(", ", list[index]) + ")");
        });
        return template;
    } else if (bLangNode instanceof BLangLiteral) {
        return (String[]) Stream.of(template)
                .map(s -> s.replace(PLACE_HOLDER, ((BLangLiteral) bLangNode).getValue().toString())).toArray();
    } else if (bLangNode instanceof BLangAssignment) {
        return (String[]) Stream.of(template).map(s -> s.replace(PLACE_HOLDER, "0")).toArray();
    } else if (bLangNode instanceof BLangFunctionTypeNode) {
        BLangFunctionTypeNode funcType = (BLangFunctionTypeNode) bLangNode;
        TestFunctionGenerator generator = new TestFunctionGenerator(importsAcceptor, currentPkgId, funcType);
        StringJoiner params = new StringJoiner(", ");
        String[][] valueSpace = generator.getValueSpace();
        String[] typeSpace = generator.getTypeSpace();
        String[] nameSpace = generator.getNamesSpace();
        IntStream.range(0, typeSpace.length - 1).forEach(index -> {
            String type = typeSpace[index];
            String name = nameSpace[index];
            params.add(type + " " + name);
        });
        String returnType = "(" + typeSpace[typeSpace.length - 1] + ")";
        IntStream.range(0, template.length).forEach(index -> {
            String builder = "function (" + params.toString() + ") returns " + returnType + "{ "
                    + ((valueSpace != null) ? "return " + valueSpace[index][funcType.params.size()] : "")
                    + "; }";
            template[index] = template[index].replace(PLACE_HOLDER, builder);
        });
        return template;
    }
    return (bLangNode.type != null)
            ? getValueSpaceByType(importsAcceptor, currentPkgId, bLangNode.type, template)
            : template;
}

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

public List<DataSourceColumn> findColumns(Connection connection, String tableName) {

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

    try {/* w ww .j a  va2  s. 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.jodconverter.office.OnlineOfficeManager.java

@Override
protected OnlineOfficeManagerPoolEntry[] createPoolEntries() {

    return IntStream.range(0, poolSize).mapToObj(idx -> new OnlineOfficeManagerPoolEntry(urlConnection,
            sslConfig, (OnlineOfficeManagerPoolEntryConfig) config))
            .toArray(OnlineOfficeManagerPoolEntry[]::new);
}

From source file:org.shredzone.commons.gravatar.impl.GravatarServiceImpl.java

@Override
public String computeHash(String mail) {
    try {// www  .java 2  s  .  c o m
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.reset();
        md5.update(mail.trim().toLowerCase().getBytes("UTF-8"));

        byte[] digest = md5.digest();

        return IntStream.range(0, digest.length).mapToObj(ix -> String.format("%02x", digest[ix] & 0xFF))
                .collect(joining());
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
        // should never happen since we use standard stuff
        throw new InternalError(ex.getMessage());
    }
}