Example usage for java.util Set stream

List of usage examples for java.util Set stream

Introduction

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

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:com.haulmont.cuba.web.gui.components.WebFileMultiUploadField.java

@Override
public void setPermittedExtensions(Set<String> permittedExtensions) {
    if (permittedExtensions != null) {
        this.permittedExtensions = permittedExtensions.stream().map(String::toLowerCase)
                .collect(Collectors.toSet());
    } else {// www.  j  a v a2s. c om
        this.permittedExtensions = null;
    }

    if (this.component instanceof CubaFileUpload) {
        ((CubaFileUpload) this.component).setPermittedExtensions(this.permittedExtensions);
    } else if (this.component instanceof CubaMultiUpload) {
        ((CubaMultiUpload) this.component).setPermittedExtensions(this.permittedExtensions);
        ((CubaMultiUpload) this.component).setFileTypesDescription("");
    }
}

From source file:com.oneops.transistor.util.CloudUtil.java

private Map<String, TreeSet<String>> getMissingCloudServices(long manifestPlatCiId,
        Set<String> requiredServices) {
    Map<String, TreeSet<String>> missingCloud2Services = new TreeMap<>();
    //get clouds//from w ww.jav  a2  s. c  o m
    List<CmsRfcRelation> cloudRelations = getCloudsForPlatform(manifestPlatCiId);
    // get services for all clouds
    cloudRelations.forEach(cloudRelation -> {
        Set<String> cloudServices = getCloudServices(cloudRelation);
        String cloud = cloudRelation.getToRfcCi().getCiName();
        //check if service is configured
        requiredServices.stream().filter(s -> !cloudServices.contains(s))
                .forEach(s -> missingCloud2Services.computeIfAbsent(cloud, k -> new TreeSet<>()).add(s));
        logger.debug("cloud: " + cloud + " required services:: " + requiredServices.toString()
                + " missingServices " + missingCloud2Services.keySet());
    });

    return missingCloud2Services;
}

From source file:com.act.reachables.Network.java

public String toDOT() {
    List<String> lines = new ArrayList<String>();

    lines.add("digraph " + this.name + " {");

    for (Node n : new ArrayList<Node>(this.nodeMapping.values())) {
        String id;//from  w w  w .ja va 2s  .  c  om
        String label;
        String tooltip;
        String url;
        String color = Cascade.quote("black");

        if (Boolean.valueOf((String) Node.getAttribute(n.id, "isrxn"))) {
            id = String.valueOf(n.getIdentifier());

            int reactionCount = (int) Node.getAttribute(n.id, "reaction_count");

            Set<String> rawLabel = (HashSet) Node.getAttribute(n.id, "label_string");
            List<String> filteredRawLabel = rawLabel.stream().filter(x -> !x.equals(""))
                    .collect(Collectors.toList());

            Long labelId = n.getIdentifier() - Cascade.rxnIdShift();
            if (labelId < 0) {
                labelId = Reaction.reverseNegativeId(labelId);
            }

            HashSet<String> organisms = (HashSet<String>) Node.getAttribute(n.id, "organisms");

            String fullLabel;
            if (filteredRawLabel.isEmpty()) {
                if ((boolean) Node.getAttribute(n.id, "isSpontaneous")) {
                    fullLabel = "Spontaneous";
                } else {
                    fullLabel = "Not Available";
                }
            } else {
                fullLabel = filteredRawLabel.get(0);
                if (filteredRawLabel.size() > 1) {
                    fullLabel += " and " + String.valueOf(filteredRawLabel.size() - 1) + " more";
                }
            }

            label = Cascade.quote(fullLabel);
            tooltip = Cascade.quote((String) Node.getAttribute(n.id, "tooltip_string"));
            if ((boolean) Node.getAttribute(n.id, "hasSequence")) {
                String forestGreen = "#228B22";
                color = Cascade.quote(forestGreen);
            } else if ((boolean) Node.getAttribute(n.id, "isSpontaneous")) {
                String goldenrodYellow = "#E8BD2B";
                color = Cascade.quote(goldenrodYellow);
            } else {
                String crimsonRed = "#DC143C";
                color = Cascade.quote(crimsonRed);
            }

            url = Cascade.quote((String) Node.getAttribute(n.id, "url_string"));
        } else {
            id = String.valueOf(n.getIdentifier());

            label = (String) Node.getAttribute(n.id, "label_string");
            if (label == null) {
                label = n.id >= Cascade.rxnIdShift() ? "Reaction_" + n.id.toString()
                        : "Chemical_" + n.id.toString();
            }
            tooltip = (String) Node.getAttribute(n.id, "tooltip_string");
            url = (String) Node.getAttribute(n.id, "url_string");
        }

        String node_line = id + " [shape=box," + " label=" + label + "," + " tooltip=" + tooltip + "," + " URL="
                + url + "," + " color=" + color + "," + "];";
        lines.add(node_line);
    }

    for (Edge e : new ArrayList<Edge>(this.edges)) {
        // create a line for nodeMapping like so:
        // id -> id;
        Long src_id = e.getSrc().getIdentifier();
        Long dst_id = e.getDst().getIdentifier();

        String edge_line;
        if (e.getAttribute("color") != null) {
            edge_line = src_id + " -> " + dst_id + " [color=" + e.getAttribute("color") + "]" + ";";
        } else {
            edge_line = src_id + " -> " + dst_id + ";";
        }

        lines.add(edge_line);

        Edge.setAttribute(e, "color", null);
    }

    lines.add("}");

    return StringUtils.join(lines.toArray(new String[0]), "\n");
}

From source file:com.act.biointerpretation.networkanalysis.MetabolismNetwork.java

/**
 * Trace the pathway back from the given startNode for up to numSteps steps, and return the subgraph of all
 * precursors found.  This is intended to supply explanatory pathways for the input node.
 *
 * @param startNode The node to explain.
 * @param numSteps The number of steps back from the node to search.
 * @return A report representing the precursors of the given starting metabolite.
 *///from w w w  .ja  v a  2 s  .c  o m
public PrecursorReport getPrecursorReport(NetworkNode startNode, int numSteps) {
    if (numSteps <= 0) {
        throw new IllegalArgumentException("Precursor graph is only well-defined for numSteps > 0");
    }

    MetabolismNetwork subgraph = new MetabolismNetwork();
    Map<NetworkNode, Integer> levelMap = new HashMap<>();
    Set<NetworkNode> frontier = new HashSet<>();
    frontier.add(startNode);
    levelMap.put(startNode, 0);

    for (MutableInt l = new MutableInt(1); l.toInteger() <= numSteps; l.increment()) {
        // Get edges leading into the derivative frontier
        List<NetworkEdge> edges = frontier.stream().flatMap(n -> n.getInEdges().stream())
                .collect(Collectors.toList());
        // Add all of the nodes adjacent to the edges, and the edges themselves, to the subgraph
        edges.forEach(e -> this.getSubstrates(e).forEach(subgraph::addNode));
        edges.forEach(e -> this.getProducts(e).forEach(subgraph::addNode));
        edges.forEach(subgraph::addEdge);
        // Calculate new frontier, excluding already-labeled nodes to avoid cycles
        frontier = edges.stream().flatMap(e -> this.getSubstrates(e).stream()).collect(Collectors.toSet());
        frontier.removeIf(levelMap::containsKey);
        // Label remaining nodes with appropriate level.
        frontier.forEach(n -> levelMap.put(n, l.toInteger()));
    }

    return new PrecursorReport(startNode.getMetabolite(), subgraph, levelMap);
}

From source file:com.walmart.gatling.commons.Master.java

private void onWorkerRequestsFile(MasterWorkerProtocol.WorkerRequestsFile cmd) throws IOException {
    MasterWorkerProtocol.WorkerRequestsFile msg = cmd;
    Set<String> trackingIds = fileDtabase.keySet();
    Optional<String> unsentFile = trackingIds.stream().map(p -> p.concat("_").concat(msg.host))
            .filter(p -> !fileTracker.contains(p)).findFirst();
    if (unsentFile.isPresent()) {
        String tId = unsentFile.get().split("_")[0];
        UploadFile uploadFile = fileDtabase.get(tId);
        if (uploadFile.type.equalsIgnoreCase("lib")) {
            String soonToBeRemotePath = agentConfig.getMasterUrl(uploadFile.path);
            getSender().tell(new FileJob(null, uploadFile, soonToBeRemotePath), getSelf());
        } else {//from   w  w  w.  ja v a  2  s .co m
            String content = FileUtils.readFileToString(new File(uploadFile.path));
            getSender().tell(new FileJob(content, uploadFile, null), getSelf());
        }
    }
}

From source file:com.dtolabs.rundeck.plugin.resources.ec2.InstanceToNodeMapper.java

public Set<Instance> addingImageName(Set<Instance> originalInstances) {
    Set<Instance> instances = new HashSet<>();
    Map<String, Image> ec2Images = new HashMap<>();
    List<String> imagesList = originalInstances.stream().map(Instance::getImageId).collect(Collectors.toList());
    logger.debug("Image list: " + imagesList.toString());
    try {/* w  w  w  .j  ava  2s  .  c  o  m*/
        DescribeImagesRequest describeImagesRequest = new DescribeImagesRequest();
        describeImagesRequest.setImageIds(imagesList);

        DescribeImagesResult result = ec2.describeImages(describeImagesRequest);

        for (Image image : result.getImages()) {
            ec2Images.put(image.getImageId(), image);
        }
    } catch (Exception e) {
        logger.error("error getting image info" + e.getMessage());
    }

    for (final Instance inst : originalInstances) {
        if (ec2Images.containsKey(inst.getImageId())) {
            Ec2Instance customInstance = Ec2Instance.builder(inst);
            Image image = ec2Images.get(inst.getImageId());
            customInstance.setImageName(image.getName());
            instances.add(customInstance);
        } else {
            Ec2Instance customInstance = Ec2Instance.builder(inst);
            customInstance.setImageName("Not found");
            logger.debug("Image not found" + inst.getImageId());
            instances.add(customInstance);
        }
    }

    return instances;
}

From source file:io.gravitee.management.service.impl.ApplicationServiceImpl.java

@Override
public Set<ApplicationEntity> findAll() {
    try {/*from   w  ww.j  a v a  2  s  .  c om*/
        LOGGER.debug("Find all applications");

        final Set<Application> applications = applicationRepository.findAll();

        if (applications == null || applications.isEmpty()) {
            return emptySet();
        }

        final Set<ApplicationEntity> applicationEntities = new HashSet<>(applications.size());

        applicationEntities
                .addAll(applications.stream().map(ApplicationServiceImpl::convert).collect(Collectors.toSet()));

        return applicationEntities;
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to find all applications", ex);
        throw new TechnicalManagementException("An error occurs while trying to find all applications", ex);
    }
}

From source file:nu.yona.server.subscriptions.service.BuddyService.java

Set<BuddyDto> getBuddyDtos(Set<Buddy> buddyEntities) {
    loadAllBuddiesAnonymizedAtOnce(buddyEntities);
    loadAllUsersAnonymizedAtOnce(buddyEntities);
    return buddyEntities.stream().map(this::getBuddy).collect(Collectors.toSet());
}

From source file:ddf.catalog.impl.operations.SourceOperations.java

/**
 * Retrieves the {@link SourceDescriptor} info for all {@link FederatedSource}s in the fanout
 * configuration, but the all of the source info, e.g., content types, for all of the available
 * {@link FederatedSource}s is packed into one {@link SourceDescriptor} for the fanout
 * configuration with the fanout's site name in it. This keeps the individual {@link
 * FederatedSource}s' source info hidden from the external client.
 *///from w  ww.j  a  va  2s  . c o  m
private SourceInfoResponse getFanoutSourceInfo(SourceInfoRequest sourceInfoRequest)
        throws SourceUnavailableException {

    SourceInfoResponse response;
    SourceDescriptorImpl sourceDescriptor;
    try {

        // request
        if (sourceInfoRequest == null) {
            throw new IllegalArgumentException("SourceInfoRequest was null");
        }

        Set<SourceDescriptor> sourceDescriptors = new LinkedHashSet<>();
        Set<String> ids = sourceInfoRequest.getSourceIds();

        // Only return source descriptor information if this sourceId is
        // specified
        if (ids != null) {
            Optional<String> notLocal = ids.stream().filter(s -> !s.equals(getId())).findFirst();
            if (notLocal.isPresent()) {
                SourceUnavailableException sourceUnavailableException = new SourceUnavailableException(
                        "Unknown source: " + notLocal.get());
                LOGGER.debug("Throwing SourceUnavailableException for unknown source: {}", notLocal.get(),
                        sourceUnavailableException);
                throw sourceUnavailableException;
            }
        }

        // Fanout will only add one source descriptor with all the contents
        // Using a List here instead of a Set because we should not rely on how Sources are compared
        final List<Source> availableSources = frameworkProperties.getFederatedSources().stream()
                .filter(this::isSourceAvailable).collect(Collectors.toList());

        final Set<ContentType> contentTypes = availableSources.stream()
                .map(source -> contentTypesCache.getCachedValueForSource(source).orElseGet(() -> {
                    LOGGER.debug("Unknown content types for source id={}", source.getId());
                    return Collections.emptySet();
                })).flatMap(Collection::stream).collect(Collectors.toSet());

        if (isSourceAvailable(catalog)) {
            availableSources.add(catalog);
            final Optional<Set<ContentType>> catalogContentTypes = contentTypesCache
                    .getCachedValueForSource(catalog);
            if (catalogContentTypes.isPresent()) {
                contentTypes.addAll(catalogContentTypes.get());
            } else {
                LOGGER.debug("Unknown content types for the localSource");
            }
        }

        List<Action> actions = getSourceActions(catalog);

        // only reveal this sourceDescriptor, not the federated sources
        sourceDescriptor = new SourceDescriptorImpl(this.getId(), contentTypes, actions);
        if (this.getVersion() != null) {
            sourceDescriptor.setVersion(this.getVersion());
        }
        sourceDescriptor.setAvailable(!availableSources.isEmpty());
        sourceDescriptors.add(sourceDescriptor);

        response = new SourceInfoResponseImpl(sourceInfoRequest, null, sourceDescriptors);

    } catch (RuntimeException re) {
        throw new SourceUnavailableException("Exception during runtime while performing getSourceInfo", re);
    }
    return response;
}

From source file:com.epam.catgenome.manager.protein.ProteinSequenceManager.java

private ArrayList<Gene> removeCdsDuplicates(final Set<Gene> allCdsList,
        final Map<Gene, List<List<Sequence>>> alternativeNucleotides) {
    ArrayList<Gene> variationCds = new ArrayList<>();
    variationCds.addAll(alternativeNucleotides.keySet());
    Set<Gene> helpAllCdsList = allCdsList;
    // Remove duplicates from all cds list.
    for (Gene cds : variationCds) {
        helpAllCdsList = allCdsList.stream()
                .filter(geneFeature -> !geneFeature.getStartIndex().equals(cds.getStartIndex())
                        && !geneFeature.getEndIndex().equals(cds.getEndIndex()))
                .collect(Collectors.toSet());
    }/*from w w w.  j  a v  a  2s  .co m*/
    variationCds.addAll(helpAllCdsList);
    return variationCds;
}