Example usage for java.util.stream StreamSupport stream

List of usage examples for java.util.stream StreamSupport stream

Introduction

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

Prototype

public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) 

Source Link

Document

Creates a new sequential or parallel Stream from a Spliterator .

Usage

From source file:com.thinkbiganalytics.metadata.modeshape.BaseJcrProvider.java

public <D, R> Iterable<D> findIterable(String query, Class<D> domainClass, Class<R> resultClass) {
    return () -> {
        return StreamSupport.stream(findIterableNodes(query).spliterator(), false).map(node -> {
            try {
                @SuppressWarnings("unchecked")
                D entity = (D) ConstructorUtils.invokeConstructor(resultClass, node);
                return entity;
            } catch (Exception e) {
                throw new MetadataRepositoryException("Failed to create entity: " + resultClass, e);
            }/*w ww.j a  v  a2  s.  c om*/
        }).iterator();
    };
}

From source file:com.intuit.wasabi.repository.cassandra.impl.CassandraPagesRepository.java

@Override
public List<PageExperiment> getExperiments(Application.Name applicationName, Page.Name pageName) {
    Stream<PageExperimentByAppNamePage> resultList = Stream.empty();
    try {//from w ww. ja  v  a 2 s . c  o m
        Result<PageExperimentByAppNamePage> result = pageExperimentIndexAccessor
                .selectBy(applicationName.toString(), pageName.toString());
        resultList = StreamSupport
                .stream(Spliterators.spliteratorUnknownSize(result.iterator(), Spliterator.ORDERED), false);
    } catch (ReadTimeoutException | UnavailableException | NoHostAvailableException e) {
        throw new RepositoryException(
                new StringBuilder("Could not retrieve the experiments for applicationName:\"")
                        .append(applicationName).append("\", page:\"").append(pageName).append("\"").toString(),
                e);
    }
    //TODO: make the experiment label part of the pageExperimentIndex to save a query per page
    return resultList.map(t -> {
        Optional<com.intuit.wasabi.repository.cassandra.pojo.Experiment> experiment = Optional
                .ofNullable(experimentAccessor.selectBy(t.getExperimentId()).one());
        PageExperiment.Builder builder = new PageExperiment.Builder(Experiment.ID.valueOf(t.getExperimentId()),
                null, t.isAssign());
        if (experiment.isPresent()) {
            builder.setLabel(Experiment.Label.valueOf(experiment.get().getLabel()));
        }
        return builder.build();
    }).filter(t -> t.getLabel() != null).collect(Collectors.toList());
}

From source file:io.syndesis.dao.DeploymentDescriptorTest.java

private static void assertActionProperties(final String connectorId, final JsonNode action,
        final String actionName, final JsonNode catalogedJsonSchema) {
    final JsonNode actionDefinition = action.get("definition");

    final JsonNode propertiesFromCatalog = catalogedJsonSchema.get("properties");

    // make sure that all action properties are as defined in
    // the connector
    StreamSupport.stream(actionDefinition.get("propertyDefinitionSteps").spliterator(), true)
            .flatMap(step -> StreamSupport.stream(Spliterators
                    .spliteratorUnknownSize(step.get("properties").fields(), Spliterator.CONCURRENT), true))
            .forEach(property -> {//  w  ww.j ava2  s.  c  om
                final String propertyName = property.getKey();
                final JsonNode propertyDefinition = property.getValue();

                final JsonNode catalogedPropertyDefinition = propertiesFromCatalog.get(propertyName);

                assertThat(catalogedPropertyDefinition).as(
                        "Definition of `%s` connector's action `%s` defines a property `%s` that is not defined in the Camel connector",
                        connectorId, actionName, propertyName).isNotNull();

                assertThat(propertyDefinition.get("componentProperty"))
                        .as("`componentProperty` field is missing for connector's %s %s action property %s",
                                connectorId, actionName, propertyName)
                        .isNotNull();
                assertThat(propertyDefinition.get("componentProperty").asBoolean()).as(
                        "Definition of `%s` connector's action `%s` property `%s` should be marked as `componentProperty`",
                        connectorId, actionName, propertyName).isFalse();
                // remove Syndesis specifics
                final ObjectNode propertyDefinitionForComparisson = propertyNodeForComparisson(
                        propertyDefinition);

                // remove properties that we would like to customize
                removeCustomizedProperties(propertyDefinitionForComparisson, catalogedPropertyDefinition);

                assertThat(propertyDefinitionForComparisson).as(
                        "Definition of `%s` connector's action's `%s` property `%s` differs from the one in Camel connector",
                        connectorId, actionName, propertyName).isEqualTo(catalogedPropertyDefinition);
            });
}

From source file:org.apache.metron.common.stellar.shell.StellarShell.java

/**
 * Handles user interaction when executing a Magic command.
 * @param rawExpression The expression to execute.
 *//* w  w w  .  j av a  2s  .co  m*/
private void handleMagic(String rawExpression) {
    String expression = rawExpression.trim();
    if (MAGIC_FUNCTIONS.equals(expression)) {

        // list all functions
        String functions = StreamSupport
                .stream(executor.getFunctionResolver().getFunctionInfo().spliterator(), false)
                .map(info -> String.format("%s", info.getName())).sorted().collect(Collectors.joining(", "));
        writeLine(functions);

    } else if (MAGIC_VARS.equals(expression)) {

        // list all variables

        executor.getVariables().forEach((k, v) -> writeLine(String.format("%s = %s", k, v)));

    } else {
        writeLine(ERROR_PROMPT + "undefined magic command: " + expression);
    }
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.services.ElasticsearchIndexService.java

/** Check if a new mapping based on a schema is equivalent to a mapping previously stored (from a schema) 
 * @param stored_mapping//ww w.  ja  v  a 2 s .  c  o m
 * @param new_mapping
 * @param mapper
 * @return
 * @throws JsonProcessingException
 * @throws IOException
 */
protected static boolean mappingsAreEquivalent(final IndexTemplateMetaData stored_mapping,
        final JsonNode new_mapping, final ObjectMapper mapper) throws JsonProcessingException, IOException {

    final ObjectNode stored_json_mappings = StreamSupport.stream(stored_mapping.mappings().spliterator(), false)
            .reduce(mapper.createObjectNode(), Lambdas.wrap_u(
                    (acc, kv) -> (ObjectNode) acc.setAll((ObjectNode) mapper.readTree(kv.value.string()))),
                    (acc1, acc2) -> acc1); // (can't occur)

    final JsonNode new_json_mappings = Optional.ofNullable(new_mapping.get("mappings"))
            .orElse(mapper.createObjectNode());

    final JsonNode stored_json_settings = mapper.convertValue(Optional.ofNullable(stored_mapping.settings())
            .orElse(ImmutableSettings.settingsBuilder().build()).getAsMap(), JsonNode.class);

    final JsonNode new_json_settings = Optional.ofNullable(new_mapping.get("settings"))
            .orElse(mapper.createObjectNode());

    final ObjectNode stored_json_aliases = StreamSupport
            .stream(Optional.ofNullable(
                    stored_mapping.aliases()).orElse(
                            ImmutableOpenMap.of())
                    .spliterator(), false)
            .reduce(mapper.createObjectNode(), Lambdas.wrap_u((acc, kv) -> (ObjectNode) acc.set(kv.key,
                    kv.value.filteringRequired() ? mapper.createObjectNode().set("filter",
                            mapper.readTree(kv.value.filter().string())) : mapper.createObjectNode())),
                    (acc1, acc2) -> acc1); // (can't occur)

    final JsonNode new_json_aliases = Optional.ofNullable(new_mapping.get("aliases"))
            .orElse(mapper.createObjectNode());

    return stored_json_mappings.equals(new_json_mappings) && stored_json_settings.equals(new_json_settings)
            && stored_json_aliases.equals(new_json_aliases);
}

From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java

private static Stream<WidgetVarLocation> findWidgetVars(Path sourceDirectory, String sourcePattern,
        ThreadPoolExecutor threadPool) throws IOException {
    BlockingQueue<WidgetVarLocation> pipe = new LinkedBlockingQueue<>();
    List<Future<?>> futures = new ArrayList<>();
    Files.walkFileTree(sourceDirectory, new FileActionVisitor(sourceDirectory, sourcePattern,
            sourceFile -> futures.add(threadPool.submit(() -> {
                try (BufferedReader br = Files.newBufferedReader(sourceFile, StandardCharsets.UTF_8)) {
                    int lineNr = 0;
                    String line;/* w ww . j  av  a  2 s.co  m*/
                    while ((line = br.readLine()) != null) {
                        lineNr++;

                        if (line.contains("widgetVar=\"")) {
                            int startIndex = line.indexOf("widgetVar=\"") + "widgetVar=\"".length();
                            int endIndex = line.indexOf('"', startIndex);
                            String var = line.substring(startIndex, endIndex);
                            WidgetVarLocation widgetVar = new WidgetVarLocation(var, sourceFile, lineNr,
                                    startIndex, line);

                            pipe.add(widgetVar);
                        }
                    }
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }))));

    return StreamSupport.stream(new PipeSpliterator(pipe, futures), true);
}

From source file:ch.rasc.edsutil.optimizer.WebResourceProcessor.java

private Map<String, List<WebResource>> readVariableResources() throws IOException {

    try (InputStream is = new ClassPathResource(this.webResourcesConfigName).getInputStream()) {
        Constructor constructor = new Constructor(VariableConfig.class);
        Yaml yaml = new Yaml(constructor);
        return StreamSupport.stream(yaml.loadAll(is).spliterator(), false).map(e -> (VariableConfig) e)
                .map(this::createWebResources).flatMap(wr -> wr.stream())
                .collect(Collectors.groupingBy(WebResource::getVarName));
    }//from ww  w  .j  av a  2s  .  c o  m
}

From source file:org.jboss.set.aphrodite.issue.trackers.jira.IssueWrapper.java

IssueInput issueToFluentUpdate(Issue issue, com.atlassian.jira.rest.client.api.domain.Issue jiraIssue,
        Project project) throws NotFoundException {
    checkUnsupportedUpdateFields(issue);
    IssueInputBuilder inputBuilder = new IssueInputBuilder(jiraIssue.getProject().getKey(),
            jiraIssue.getIssueType().getId());

    issue.getSummary().ifPresent(inputBuilder::setSummary);
    inputBuilder.setFieldInput(new FieldInput(IssueFieldId.COMPONENTS_FIELD, issue.getComponents().stream()
            .map(e -> ComplexIssueInputFieldValue.with("name", e)).collect(Collectors.toList())));
    issue.getDescription().ifPresent(inputBuilder::setDescription);

    issue.getAssignee().ifPresent(assignee -> inputBuilder.setFieldInput(new FieldInput(
            IssueFieldId.ASSIGNEE_FIELD,
            ComplexIssueInputFieldValue.with("name", assignee.getName().orElseThrow(this::nullUsername)))));

    // this is ok but does nothing if there is no permissions.
    issue.getStage().getStateMap().entrySet().stream().filter(entry -> entry.getValue() != FlagStatus.NO_SET)
            .forEach(entry -> inputBuilder.setFieldInput(new FieldInput(
                    JSON_CUSTOM_FIELD + FLAG_MAP.get(entry.getKey()), entry.getValue().getSymbol())));

    Map<String, Version> versionsMap = StreamSupport.stream(project.getVersions().spliterator(), false)
            .collect(Collectors.toMap(Version::getName, Function.identity()));
    updateFixVersions(issue, versionsMap, inputBuilder);
    updateStreamStatus(issue, jiraIssue, versionsMap, inputBuilder);

    return inputBuilder.build();
}

From source file:org.talend.dataprep.preparation.service.PreparationService.java

/**
 * List all preparations details in the given folder.
 *
 * @param folderId the folder where to look for preparations.
 * @return the list of preparations details for the given folder path.
 *///from  ww  w.  j a  va2 s  . co  m
private Stream<Preparation> searchByFolder(String folderId) {
    LOGGER.debug("looking for preparations in {}", folderId);
    final Iterable<FolderEntry> entries = folderRepository.entries(folderId, PREPARATION);
    return StreamSupport.stream(entries.spliterator(), false) //
            .map(e -> preparationRepository.get(e.getContentId(), Preparation.class));
}

From source file:com.epam.reportportal.extension.bugtracking.jira.JiraStrategy.java

@Override
public List<PostFormField> getTicketFields(final String ticketType, ExternalSystem details) {
    List<PostFormField> result = new ArrayList<>();
    try (JiraRestClient client = getClient(details.getUrl(), details.getUsername(),
            simpleEncryptor.decrypt(details.getPassword()))) {
        Project jiraProject = getProject(client, details);
        Optional<IssueType> issueType = StreamSupport.stream(jiraProject.getIssueTypes().spliterator(), false)
                .filter(input -> ticketType.equalsIgnoreCase(input.getName())).findFirst();
        GetCreateIssueMetadataOptions options = new GetCreateIssueMetadataOptionsBuilder()
                .withExpandedIssueTypesFields().withProjectKeys(jiraProject.getKey()).build();
        Iterable<CimProject> projects = client.getIssueClient().getCreateIssueMetadata(options).claim();
        CimProject project = projects.iterator().next();
        CimIssueType cimIssueType = EntityHelper.findEntityById(project.getIssueTypes(),
                issueType.get().getId());
        for (String key : cimIssueType.getFields().keySet()) {
            List<String> defValue = null;
            CimFieldInfo issueField = cimIssueType.getFields().get(key);
            // Field ID for next JIRA POST ticket requests
            String fieldID = issueField.getId();
            String fieldType = issueField.getSchema().getType();
            List<AllowedValue> allowed = new ArrayList<>();
            // Field NAME for user friendly UI output (for UI only)
            String fieldName = issueField.getName();

            if (fieldID.equalsIgnoreCase(IssueFieldId.COMPONENTS_FIELD.id)) {
                for (BasicComponent component : jiraProject.getComponents()) {
                    allowed.add(new AllowedValue(String.valueOf(component.getId()), component.getName()));
                }//from w w  w .j  a va  2s  .  c o  m
            }
            if (fieldID.equalsIgnoreCase(IssueFieldId.FIX_VERSIONS_FIELD.id)) {
                for (Version version : jiraProject.getVersions()) {
                    allowed.add(new AllowedValue(String.valueOf(version.getId()), version.getName()));
                }
            }
            if (fieldID.equalsIgnoreCase(IssueFieldId.AFFECTS_VERSIONS_FIELD.id)) {
                for (Version version : jiraProject.getVersions()) {
                    allowed.add(new AllowedValue(String.valueOf(version.getId()), version.getName()));
                }
            }
            if (fieldID.equalsIgnoreCase(IssueFieldId.PRIORITY_FIELD.id)) {
                if (null != cimIssueType.getField(IssueFieldId.PRIORITY_FIELD)) {
                    Iterable<Object> allowedValuesForPriority = cimIssueType
                            .getField(IssueFieldId.PRIORITY_FIELD).getAllowedValues();
                    for (Object singlePriority : allowedValuesForPriority) {
                        BasicPriority priority = (BasicPriority) singlePriority;
                        allowed.add(new AllowedValue(String.valueOf(priority.getId()), priority.getName()));
                    }
                }
            }
            if (fieldID.equalsIgnoreCase(IssueFieldId.ISSUE_TYPE_FIELD.id)) {
                defValue = Lists.newArrayList(BUG);
            }
            if (fieldID.equalsIgnoreCase(IssueFieldId.ASSIGNEE_FIELD.id)) {
                allowed = getJiraProjectAssignee(jiraProject);
            }

            //@formatter:off
            // Skip project field as external from list
            // Skip attachment cause we are not providing this functionality now
            // Skip timetracking field cause complexity. There are two fields with Original Estimation and Remaining Estimation.
            // Skip Story Link as greenhopper plugin field.
            // Skip Sprint field as complex one.
            //@formatter:on
            if ("project".equalsIgnoreCase(fieldID) || "attachment".equalsIgnoreCase(fieldID)
                    || "timetracking".equalsIgnoreCase(fieldID) || "Epic Link".equalsIgnoreCase(fieldName)
                    || "Sprint".equalsIgnoreCase(fieldName))
                continue;

            result.add(new PostFormField(fieldID, fieldName, fieldType, issueField.isRequired(), defValue,
                    allowed));
        }
        return result;
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return new ArrayList<>();
    }

}