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:it.greenvulcano.gvesb.gviamx.service.internal.EmailChangeManager.java

public void createEmailChangeRequest(String currentEmailAddress, String newEmailAddress)
        throws UserNotFoundException, UserExistException {

    if (newEmailAddress == null || !newEmailAddress.matches(UserActionRequest.EMAIL_PATTERN)) {
        throw new IllegalArgumentException("Invalid email: " + newEmailAddress);
    }/*from  w  ww. j  a va  2s .  c o  m*/

    try {
        usersManager.getUser(newEmailAddress.toLowerCase());
        throw new UserExistException(newEmailAddress);
    } catch (UserNotFoundException e) {

        if (usersManager
                .searchUsers(
                        SearchCriteria.builder().byEmail(newEmailAddress.toLowerCase()).limitedTo(1).build())
                .getTotalCount() > 0) {
            throw new UserExistException(newEmailAddress);
        }
    }

    User user = usersManager.getUser(currentEmailAddress.toLowerCase());

    EmailChangeRequest request = repository.get(newEmailAddress.toLowerCase(), EmailChangeRequest.class)
            .orElseGet(EmailChangeRequest::new);
    request.setUser((UserJPA) user);
    request.setEmail(newEmailAddress.toLowerCase());
    request.setIssueTime(new Date());
    request.setExpireTime(expireTime);
    request.setNotificationStatus(NotificationStatus.PENDING);

    byte[] token = new byte[4];
    secureRandom.nextBytes(token);

    String clearTextToken = String.format(Locale.US, "%02x%02x%02x%02x",
            IntStream.range(0, token.length).mapToObj(i -> Byte.valueOf(token[i])).toArray());
    request.setToken(DigestUtils.sha256Hex(clearTextToken));

    repository.add(request);

    request.setClearToken(clearTextToken);
    notificationServices.stream()
            .map(n -> new NotificationManager.NotificationTask(n, request, repository, "update"))
            .forEach(executor::submit);

}

From source file:delfos.rs.trustbased.WeightedGraph.java

private double[][] makeMatrixFromEdges(Set<PathBetweenNodes<Node>> edges) {
    double[][] matrix = new double[nodesIndex.size()][nodesIndex.size()];
    edges.parallelStream().filter(edge -> Double.isFinite(edge.getLength())).forEach(edge -> {
        Integer fromIndex = nodesIndex.get(edge.from());
        Integer toIndex = nodesIndex.get(edge.to());
        double weight = Objects.equals(fromIndex, toIndex) ? 0 : edge.getFirstWeight();
        matrix[fromIndex][toIndex] = weight;
    });/*from  ww  w. j ava2  s.co  m*/

    IntStream.range(0, matrix.length).boxed().parallel().forEach(index -> matrix[index][index] = 1);
    return matrix;
}

From source file:com.yahoo.bullet.drpc.JoinBoltTest.java

private byte[] getGroupDataWithCount(String countField, int count) {
    GroupData groupData = new GroupData(
            new HashSet<>(singletonList(new GroupOperation(COUNT, null, countField))));
    IntStream.range(0, count).forEach(i -> groupData.consume(RecordBox.get().getRecord()));
    return GroupData.toBytes(groupData);
}

From source file:com.simiacryptus.util.lang.CodeUtil.java

/**
 * Gets javadoc./*ww  w  .  ja v  a 2s .c  om*/
 *
 * @param clazz the clazz
 * @return the javadoc
 */
public static String getJavadoc(@Nullable final Class<?> clazz) {
    try {
        if (null == clazz)
            return null;
        @Nullable
        final File source = com.simiacryptus.util.lang.CodeUtil.findFile(clazz);
        if (null == source)
            return clazz.getName() + " not found";
        final List<String> lines = IOUtils.readLines(new FileInputStream(source), Charset.forName("UTF-8"));
        final int classDeclarationLine = IntStream.range(0, lines.size())
                .filter(i -> lines.get(i).contains("class " + clazz.getSimpleName())).findFirst().getAsInt();
        final int firstLine = IntStream.rangeClosed(1, classDeclarationLine).map(i -> classDeclarationLine - i)
                .filter(i -> !lines.get(i).matches("\\s*[/\\*@].*")).findFirst().orElse(-1) + 1;
        final String javadoc = lines.subList(firstLine, classDeclarationLine).stream()
                .filter(s -> s.matches("\\s*[/\\*].*")).map(s -> s.replaceFirst("^[ \t]*[/\\*]+", "").trim())
                .filter(x -> !x.isEmpty()).reduce((a, b) -> a + "\n" + b).orElse("");
        return javadoc.replaceAll("<p>", "\n");
    } catch (@javax.annotation.Nonnull final Throwable e) {
        e.printStackTrace();
        return "";
    }
}

From source file:com.mycompany.wolf.Router.java

@PostConstruct
private void postConstruct() throws IOException {
    Properties properties = new Properties();
    InputStream is = Router.class.getResourceAsStream("/server.properties");
    Reader reader = new InputStreamReader(is, Charsets.UTF_8);
    properties.load(reader);/*from   ww w  . j a  v  a 2  s . c om*/

    String[] intranetAddresses = properties.getProperty("intranetAddresses").split(",");
    String[] internetAddresses = properties.getProperty("internetAddresses").split(",");
    Preconditions.checkArgument(intranetAddresses.length == internetAddresses.length);
    IntStream.range(0, internetAddresses.length).mapToObj(i -> {
        ServerInfo info = new ServerInfo();
        info.setInternetAddress(intranetAddresses[i].trim());
        info.setIntranetAddress(internetAddresses[i].trim());
        return info;
    }).forEach(servers::add);
}

From source file:com.wso2.code.quality.matrices.ChangesFinder.java

/**
 * This method is used for obtaining the repositories that contain the relevant commits belongs to the given patch
 *
 * @param gitHubToken            Github token
 * @param commitsInTheGivenPatch Commits that belongs to the given patch
 * @param restApiCaller          Instance of the RestApiCaller class for accessing the REST APIs
 * @return a Set <String> containing the commit hashes that needs to be checked for reviewers
 *//* w  w  w  .ja v  a  2 s. c  o  m*/
public Set obtainRepoNamesForCommitHashes(String gitHubToken, String[] commitsInTheGivenPatch,
        RestApiCaller restApiCaller) {

    //calling the API calling method
    IntStream.range(0, commitsInTheGivenPatch.length).mapToObj(i -> commitsInTheGivenPatch[i])
            .forEach(commitHash -> {
                setUrlForSearchingCommits(commitHash);
                JSONObject jsonObject = null;
                try {
                    jsonObject = (JSONObject) restApiCaller.callApi(getUrlForSearchingCommits(), gitHubToken,
                            true, false);
                } catch (CodeQualityMatricesException e) {
                    logger.error(e.getMessage(), e.getCause());
                    System.exit(1);
                }

                saveRepoNamesInAnArray(jsonObject, commitHash, gitHubToken);
            });
    return commitHashObtainedForPRReview;
}

From source file:ijfx.service.overlay.io.OverlayDeserializer.java

private double[] getArray(JsonNode node, String fieldName) {
    JsonNode arrayNode = node.get(fieldName);
    if (arrayNode == null)
        return new double[0];
    int arraySize = arrayNode.size();
    if (arraySize < 0)
        return new double[0];
    else {/*  www  .ja va2 s. co m*/
        return IntStream.range(0, arraySize).mapToDouble(i -> arrayNode.get(i).asDouble()).toArray();
    }
}

From source file:beast.math.NumberFormatter.java

private int getNumFractionDigits(final double value) {
    final double absValue = Math.abs(value);
    final int i = IntStream.range(0, cutoffTable.length).filter(j -> absValue < cutoffTable[j]).findFirst()
            .orElseGet(() -> 0);//from  w ww.  j  a  v a2 s . c o m
    return sf - i - 1;
}

From source file:org.apache.samza.tools.benchmark.SystemProducerBench.java

/**
 * Simple implementation to create SSPs that assumes that the partitions are ordered list of integers.
 *//*www .  j  av a 2s. c o  m*/
List<SystemStreamPartition> createSSPs(String systemName, String physicalStreamName, int startPartition,
        int endPartition) {
    return IntStream.range(startPartition, endPartition)
            .mapToObj(x -> new SystemStreamPartition(systemName, physicalStreamName, new Partition(x)))
            .collect(Collectors.toList());
}

From source file:org.jenetics.stat.MinMaxTest.java

@Test
public void parallelMinMax() {
    final Stream<Integer> stream = IntStream.range(0, 100).boxed().parallel();
    final MinMax<Integer> minMax = stream.collect(MinMax::of, MinMax::accept, MinMax::combine);

    Assert.assertEquals(minMax.getMax(), Integer.valueOf(99));
    Assert.assertEquals(minMax.getMin(), Integer.valueOf(0));
    Assert.assertEquals(100, minMax.getCount());
}