Example usage for com.google.common.collect Multimap keySet

List of usage examples for com.google.common.collect Multimap keySet

Introduction

In this page you can find the example usage for com.google.common.collect Multimap keySet.

Prototype

Set<K> keySet();

Source Link

Document

Returns a view collection of all distinct keys contained in this multimap.

Usage

From source file:org.jboss.errai.offline.linker.DefaultCacheManifestLinker.java

@Override
public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts, boolean onePermutation)
        throws UnableToCompleteException {

    ArtifactSet toReturn = new ArtifactSet(artifacts);
    if (toReturn.find(SelectionInformation.class).isEmpty()) {
        logger.log(TreeLogger.INFO, "devmode: generating empty " + MANIFEST);
        toReturn.add(emitString(logger, "# Empty in DevMode\n", "dev." + MANIFEST));
    } else if (onePermutation) {
        // Create an artifact representing the cache manifest for the current
        // permutation
        toReturn.add(createPermutationCacheManifestArtifact(context, logger, artifacts));
    } else {/*from  www  .  j  av a 2  s  . c  o m*/
        // Group permutations per user agent
        final Multimap<String, PermutationCacheManifestArtifact> permutations = ArrayListMultimap.create();
        for (PermutationCacheManifestArtifact pcma : artifacts.find(PermutationCacheManifestArtifact.class)) {
            permutations.put(pcma.props.get("user.agent"), pcma);
        }

        for (String userAgent : permutations.keySet()) {
            // Create a cache manifest file for every user agent
            toReturn.add(
                    emitUserAgentCacheManifestFile(userAgent, permutations.get(userAgent), artifacts, logger));

        }

        logger.log(TreeLogger.INFO,
                "Make sure you have the following attribute added to your host page's <html> tag: <html manifest=\""
                        + context.getModuleFunctionName() + "/" + MANIFEST + "\">");
    }
    return toReturn;
}

From source file:hu.bme.mit.trainbenchmark.benchmark.fourstore.driver.FourStoreDriver.java

public void insertEdgesWithVertex(final Multimap<String, String> edges, final String edgeType,
        final String targetVertexType) throws IOException {
    if (edges.isEmpty()) {
        return;//from   w  w w .  j  a  va  2 s  .  c  om
    }

    final ArrayList<String> sourceVertices = new ArrayList<>(edges.keySet());
    final List<List<String>> sourceVerticesPartitions = Lists.partition(sourceVertices, PARTITION_SIZE);
    for (final List<String> sourceVerticesPartition : sourceVerticesPartitions) {

        final Multimap<String, String> edgePartition = ArrayListMultimap.create();
        for (final String sourceVertexURI : sourceVerticesPartition) {
            final Collection<String> targetVertexURIs = edges.get(sourceVertexURI);
            edgePartition.putAll(sourceVertexURI, targetVertexURIs);
        }

        insertEdgesWithVertexPartition(edgePartition, edgeType, targetVertexType);
    }

}

From source file:org.eclipse.elk.layered.compound.CompoundGraphPostprocessor.java

/**
 * {@inheritDoc}//w  w  w .  ja  va  2s.  c om
 */
public void process(final LGraph graph, final IElkProgressMonitor monitor) {
    monitor.begin("Compound graph postprocessor", 1);

    // whether bend points should be added whenever crossing a hierarchy boundary
    boolean addUnnecessaryBendpoints = graph.getProperty(Properties.ADD_UNNECESSARY_BENDPOINTS);

    // restore the cross-hierarchy map that was built by the preprocessor
    Multimap<LEdge, CrossHierarchyEdge> crossHierarchyMap = graph
            .getProperty(InternalProperties.CROSS_HIERARCHY_MAP);

    // remember all dummy edges we encounter; these need to be removed at the end
    Set<LEdge> dummyEdges = Sets.newHashSet();

    // iterate over all original edges
    for (LEdge origEdge : crossHierarchyMap.keySet()) {
        List<CrossHierarchyEdge> crossHierarchyEdges = new ArrayList<CrossHierarchyEdge>(
                crossHierarchyMap.get(origEdge));

        // put the cross-hierarchy edges in proper order from source to target
        Collections.sort(crossHierarchyEdges, new CrossHierarchyEdgeComparator(graph));
        LPort sourcePort = crossHierarchyEdges.get(0).getActualSource();
        LPort targetPort = crossHierarchyEdges.get(crossHierarchyEdges.size() - 1).getActualTarget();
        origEdge.getBendPoints().clear();

        // determine the reference graph for all bend points
        LNode referenceNode = sourcePort.getNode();
        LGraph referenceGraph;
        if (LGraphUtil.isDescendant(targetPort.getNode(), referenceNode)) {
            referenceGraph = referenceNode.getProperty(InternalProperties.NESTED_LGRAPH);
        } else {
            referenceGraph = referenceNode.getGraph();
        }

        // check whether there are any junction points
        KVectorChain junctionPoints = origEdge.getProperty(LayoutOptions.JUNCTION_POINTS);
        if (Iterables.any(crossHierarchyEdges, HAS_JUNCTION_POINTS_PREDICATE)) {
            // if so, make sure the original edge has an empty non-null junction point list
            if (junctionPoints == null) {
                junctionPoints = new KVectorChain();
                origEdge.setProperty(LayoutOptions.JUNCTION_POINTS, junctionPoints);
            } else {
                junctionPoints.clear();
            }
        } else if (junctionPoints != null) {
            origEdge.setProperty(LayoutOptions.JUNCTION_POINTS, null);
        }

        // apply the computed layouts to the cross-hierarchy edge
        KVector lastPoint = null;
        for (CrossHierarchyEdge chEdge : crossHierarchyEdges) {
            // transform all coordinates from the graph of the dummy edge to the reference graph
            KVector offset = new KVector();
            LGraphUtil.changeCoordSystem(offset, chEdge.getGraph(), referenceGraph);

            LEdge ledge = chEdge.getEdge();
            KVectorChain bendPoints = new KVectorChain();
            bendPoints.addAllAsCopies(0, ledge.getBendPoints());
            bendPoints.offset(offset);

            // Note: if an NPE occurs here, that means KLay Layered has replaced the original edge
            KVector sourcePoint = new KVector(ledge.getSource().getAbsoluteAnchor());
            KVector targetPoint = new KVector(ledge.getTarget().getAbsoluteAnchor());
            sourcePoint.add(offset);
            targetPoint.add(offset);

            if (lastPoint != null) {
                KVector nextPoint;
                if (bendPoints.isEmpty()) {
                    nextPoint = targetPoint;
                } else {
                    nextPoint = bendPoints.getFirst();
                }

                // we add the source point as a bend point to properly connect the hierarchy levels
                // either if the last point of the previous hierarchy edge segment is a certain
                // level of tolerance away or if we are required to add unnecessary bend points
                boolean xDiffEnough = Math
                        .abs(lastPoint.x - nextPoint.x) > OrthogonalRoutingGenerator.TOLERANCE;
                boolean yDiffEnough = Math
                        .abs(lastPoint.y - nextPoint.y) > OrthogonalRoutingGenerator.TOLERANCE;

                if ((!addUnnecessaryBendpoints && xDiffEnough && yDiffEnough)
                        || (addUnnecessaryBendpoints && (xDiffEnough || yDiffEnough))) {

                    origEdge.getBendPoints().add(sourcePoint);
                }
            }

            origEdge.getBendPoints().addAll(bendPoints);

            if (bendPoints.isEmpty()) {
                lastPoint = sourcePoint;
            } else {
                lastPoint = bendPoints.getLast();
            }

            // copy junction points
            KVectorChain ledgeJPs = ledge.getProperty(LayoutOptions.JUNCTION_POINTS);
            if (ledgeJPs != null) {
                KVectorChain jpCopies = new KVectorChain();
                jpCopies.addAllAsCopies(0, ledgeJPs);
                jpCopies.offset(offset);

                junctionPoints.addAll(jpCopies);
            }

            // add offset to target port with a special property
            if (chEdge.getActualTarget() == targetPort) {
                if (targetPort.getNode().getGraph() != chEdge.getGraph()) {
                    // the target port is in a different coordinate system -- recompute the offset
                    offset = new KVector();
                    LGraphUtil.changeCoordSystem(offset, targetPort.getNode().getGraph(), referenceGraph);
                }
                origEdge.setProperty(InternalProperties.TARGET_OFFSET, offset);
            }

            // copy labels back to the original edge
            Iterator<LLabel> labelIterator = ledge.getLabels().listIterator();
            while (labelIterator.hasNext()) {
                LLabel currLabel = labelIterator.next();
                if (currLabel.getProperty(InternalProperties.ORIGINAL_LABEL_EDGE) != origEdge) {
                    continue;
                }

                LGraphUtil.changeCoordSystem(currLabel.getPosition(), ledge.getSource().getNode().getGraph(),
                        referenceGraph);
                labelIterator.remove();
                origEdge.getLabels().add(currLabel);
            }

            // remember the dummy edge for later removal (dummy edges may be in use by several
            // different original edges, which is why we cannot just go and remove it now)
            dummyEdges.add(ledge);
        }

        // restore the original source port and target port
        origEdge.setSource(sourcePort);
        origEdge.setTarget(targetPort);
    }

    // remove the dummy edges from the graph (dummy ports and dummy nodes are retained)
    for (LEdge dummyEdge : dummyEdges) {
        dummyEdge.setSource(null);
        dummyEdge.setTarget(null);
    }

    monitor.done();
}

From source file:de.cau.cs.kieler.klay.layered.compound.CompoundGraphPostprocessor.java

/**
 * {@inheritDoc}/*from  w ww.jav  a2  s.  c  o m*/
 */
public void process(final LGraph graph, final IKielerProgressMonitor monitor) {
    monitor.begin("Compound graph postprocessor", 1);

    // whether bend points should be added whenever crossing a hierarchy boundary
    boolean addUnnecessaryBendpoints = graph.getProperty(Properties.ADD_UNNECESSARY_BENDPOINTS);

    // restore the cross-hierarchy map that was built by the preprocessor
    Multimap<LEdge, CrossHierarchyEdge> crossHierarchyMap = graph
            .getProperty(InternalProperties.CROSS_HIERARCHY_MAP);

    // remember all dummy edges we encounter; these need to be removed at the end
    Set<LEdge> dummyEdges = Sets.newHashSet();

    // iterate over all original edges
    for (LEdge origEdge : crossHierarchyMap.keySet()) {
        List<CrossHierarchyEdge> crossHierarchyEdges = new ArrayList<CrossHierarchyEdge>(
                crossHierarchyMap.get(origEdge));

        // put the cross-hierarchy edges in proper order from source to target
        Collections.sort(crossHierarchyEdges, new CrossHierarchyEdgeComparator(graph));
        LPort sourcePort = crossHierarchyEdges.get(0).getActualSource();
        LPort targetPort = crossHierarchyEdges.get(crossHierarchyEdges.size() - 1).getActualTarget();
        origEdge.getBendPoints().clear();

        // determine the reference graph for all bend points
        LNode referenceNode = sourcePort.getNode();
        LGraph referenceGraph;
        if (LGraphUtil.isDescendant(targetPort.getNode(), referenceNode)) {
            referenceGraph = referenceNode.getProperty(InternalProperties.NESTED_LGRAPH);
        } else {
            referenceGraph = referenceNode.getGraph();
        }

        // check whether there are any junction points
        KVectorChain junctionPoints = origEdge.getProperty(LayoutOptions.JUNCTION_POINTS);
        if (Iterables.any(crossHierarchyEdges, HAS_JUNCTION_POINTS_PREDICATE)) {
            // if so, make sure the original edge has an empty non-null junction point list
            if (junctionPoints == null) {
                junctionPoints = new KVectorChain();
                origEdge.setProperty(LayoutOptions.JUNCTION_POINTS, junctionPoints);
            } else {
                junctionPoints.clear();
            }
        } else if (junctionPoints != null) {
            origEdge.setProperty(LayoutOptions.JUNCTION_POINTS, null);
        }

        // apply the computed layouts to the cross-hierarchy edge
        KVector lastPoint = null;
        for (CrossHierarchyEdge chEdge : crossHierarchyEdges) {
            // transform all coordinates from the graph of the dummy edge to the reference graph
            KVector offset = new KVector();
            LGraphUtil.changeCoordSystem(offset, chEdge.getGraph(), referenceGraph);

            LEdge ledge = chEdge.getEdge();
            KVectorChain bendPoints = new KVectorChain();
            bendPoints.addAllAsCopies(0, ledge.getBendPoints());
            bendPoints.offset(offset);

            // Note: if an NPE occurs here, that means KLay Layered has replaced the original edge
            KVector sourcePoint = new KVector(ledge.getSource().getAbsoluteAnchor());
            KVector targetPoint = new KVector(ledge.getTarget().getAbsoluteAnchor());
            sourcePoint.add(offset);
            targetPoint.add(offset);

            if (lastPoint != null) {
                KVector nextPoint;
                if (bendPoints.isEmpty()) {
                    nextPoint = targetPoint;
                } else {
                    nextPoint = bendPoints.getFirst();
                }

                // we add the source point as a bend point to properly connect the hierarchy levels
                // either if the last point of the previous hierarchy edge segment is a certain
                // level of tolerance away or if we are required to add unnecessary bend points
                boolean xDiffEnough = Math
                        .abs(lastPoint.x - nextPoint.x) > OrthogonalRoutingGenerator.TOLERANCE;
                boolean yDiffEnough = Math
                        .abs(lastPoint.y - nextPoint.y) > OrthogonalRoutingGenerator.TOLERANCE;

                if ((!addUnnecessaryBendpoints && xDiffEnough && yDiffEnough)
                        || (addUnnecessaryBendpoints && (xDiffEnough || yDiffEnough))) {

                    origEdge.getBendPoints().add(sourcePoint);
                }
            }

            origEdge.getBendPoints().addAll(bendPoints);

            if (bendPoints.isEmpty()) {
                lastPoint = sourcePoint;
            } else {
                lastPoint = bendPoints.getLast();
            }

            // copy junction points
            KVectorChain ledgeJPs = ledge.getProperty(LayoutOptions.JUNCTION_POINTS);
            if (ledgeJPs != null) {
                KVectorChain jpCopies = new KVectorChain();
                jpCopies.addAllAsCopies(0, ledgeJPs);
                jpCopies.offset(offset);

                junctionPoints.addAll(jpCopies);
            }

            // add offset to target port with a special property
            if (chEdge.getActualTarget() == targetPort) {
                if (targetPort.getNode().getGraph() != chEdge.getGraph()) {
                    // the target port is in a different coordinate system -- recompute the offset
                    offset = new KVector();
                    LGraphUtil.changeCoordSystem(offset, targetPort.getNode().getGraph(), referenceGraph);
                }
                origEdge.setProperty(InternalProperties.TARGET_OFFSET, offset);
            }

            // copy labels back to the original edge
            Iterator<LLabel> labelIterator = ledge.getLabels().listIterator();
            while (labelIterator.hasNext()) {
                LLabel currLabel = labelIterator.next();
                if (currLabel.getProperty(InternalProperties.ORIGINAL_LABEL_EDGE) != origEdge) {
                    continue;
                }

                LGraphUtil.changeCoordSystem(currLabel.getPosition(), ledge.getSource().getNode().getGraph(),
                        referenceGraph);
                labelIterator.remove();
                origEdge.getLabels().add(currLabel);
            }

            // remember the dummy edge for later removal (dummy edges may be in use by several
            // different original edges, which is why we cannot just go and remove it now)
            dummyEdges.add(ledge);
        }

        // restore the original source port and target port
        origEdge.setSource(sourcePort);
        origEdge.setTarget(targetPort);
    }

    // remove the dummy edges from the graph (dummy ports and dummy nodes are retained)
    for (LEdge dummyEdge : dummyEdges) {
        dummyEdge.setSource(null);
        dummyEdge.setTarget(null);
    }

    monitor.done();
}

From source file:com.google.javascript.jscomp.newtypes.NominalType.java

private boolean isInvariantWith(Multimap<String, JSType> typeMultimap, NominalType other) {
    Preconditions.checkState(isGeneric());
    Preconditions.checkState(this.rawType == other.rawType);
    Map<String, JSType> newTypeMap = new LinkedHashMap<>();
    for (String typeVar : typeMultimap.keySet()) {
        Collection<JSType> c = typeMultimap.get(typeVar);
        if (c.size() != 1) {
            return false;
        }//w  w w .j a v  a 2s .c  o  m
        newTypeMap.put(typeVar, Preconditions.checkNotNull(Iterables.getOnlyElement(c)));
    }
    NominalType instantiated = instantiateGenerics(newTypeMap);
    return Objects.equals(instantiated.typeMap, other.typeMap);
}

From source file:edu.buaa.satla.analysis.core.predicate.PredicatePrecision.java

/**
 * Create a new precision which contains all predicates of this precision
 * and a second one./*from w ww  . j a v a 2  s. c om*/
 */
public PredicatePrecision mergeWith(PredicatePrecision prec) {
    // create new set of global predicates
    Collection<AbstractionPredicate> newGlobalPredicates = Lists.newArrayList(getGlobalPredicates());
    newGlobalPredicates.addAll(prec.getGlobalPredicates());
    newGlobalPredicates = ImmutableSet.copyOf(newGlobalPredicates);

    // create new multimap of function-specific predicates
    Multimap<String, AbstractionPredicate> newFunctionPredicates = ArrayListMultimap
            .create(getFunctionPredicates());
    newFunctionPredicates.putAll(prec.getFunctionPredicates());

    if (!newGlobalPredicates.isEmpty()) {
        for (String function : newFunctionPredicates.keySet()) {
            newFunctionPredicates.putAll(function, newGlobalPredicates);
        }
    }
    newFunctionPredicates = ImmutableSetMultimap.copyOf(newFunctionPredicates);

    // create new multimap of location-specific predicates
    Multimap<CFANode, AbstractionPredicate> newLocalPredicates = ArrayListMultimap.create(getLocalPredicates());
    newLocalPredicates.putAll(prec.getLocalPredicates());

    if (!newGlobalPredicates.isEmpty() || !newFunctionPredicates.isEmpty()) {
        for (CFANode loc : newLocalPredicates.keySet()) {
            newLocalPredicates.putAll(loc, newGlobalPredicates);
            newLocalPredicates.putAll(loc, newFunctionPredicates.get(loc.getFunctionName()));
        }
    }

    // create new multimap of location-instance-specific predicates
    Multimap<Pair<CFANode, Integer>, AbstractionPredicate> newLocationInstanceSpecificPredicates = ArrayListMultimap
            .create(getLocationInstancePredicates());
    newLocationInstanceSpecificPredicates.putAll(prec.getLocationInstancePredicates());

    if (!newGlobalPredicates.isEmpty() || !newFunctionPredicates.isEmpty() || !newLocalPredicates.isEmpty()) {
        for (Pair<CFANode, Integer> key : newLocationInstanceSpecificPredicates.keySet()) {
            newLocationInstanceSpecificPredicates.putAll(key, newGlobalPredicates);
            newLocationInstanceSpecificPredicates.putAll(key,
                    newFunctionPredicates.get(key.getFirst().getFunctionName()));
            newLocationInstanceSpecificPredicates.putAll(key, newLocalPredicates.get(key.getFirst()));
        }
    }

    return new PredicatePrecision(newLocationInstanceSpecificPredicates, newLocalPredicates,
            newFunctionPredicates, newGlobalPredicates);
}

From source file:com.ardor3d.extension.model.collada.jdom.ColladaImporter.java

/**
 * Reads a Collada file from the given resource and returns it as a ColladaStorage object.
 * //from w w w.  j a  va 2s.c  om
 * @param resource
 *            the name of the resource to find.
 * @param geometryTool
 *            the geometry tool used to minimize the vertex count.
 * @return a ColladaStorage data object containing the Collada scene and other useful elements.
 * @throws IOException
 *             if the resource can not be loaded for some reason.
 */
public ColladaStorage load(final ResourceSource resource, final GeometryTool geometryTool) throws IOException {
    final ColladaStorage colladaStorage = new ColladaStorage();
    final DataCache dataCache = new DataCache();
    if (_externalJointMapping != null) {
        dataCache.getExternalJointMapping().putAll(_externalJointMapping);
    }
    final ColladaDOMUtil colladaDOMUtil = new ColladaDOMUtil(dataCache);
    final ColladaMaterialUtils colladaMaterialUtils = new ColladaMaterialUtils(this, dataCache, colladaDOMUtil);
    final ColladaMeshUtils colladaMeshUtils = new ColladaMeshUtils(dataCache, colladaDOMUtil,
            colladaMaterialUtils, _optimizeMeshes, _optimizeSettings, geometryTool);
    final ColladaAnimUtils colladaAnimUtils = new ColladaAnimUtils(colladaStorage, dataCache, colladaDOMUtil,
            colladaMeshUtils);
    final ColladaNodeUtils colladaNodeUtils = new ColladaNodeUtils(dataCache, colladaDOMUtil,
            colladaMaterialUtils, colladaMeshUtils, colladaAnimUtils);

    try {
        // Pull in the DOM tree of the Collada resource.
        final Element collada = readCollada(resource, dataCache);

        // if we don't specify a texture locator, add a temporary texture locator at the location of this model
        // resource..
        final boolean addLocator = _textureLocator == null;

        final RelativeResourceLocator loc;
        if (addLocator) {
            loc = new RelativeResourceLocator(resource);
            ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, loc);
        } else {
            loc = null;
        }

        final AssetData assetData = colladaNodeUtils.parseAsset(collada.getChild("asset"));

        // Collada may or may not have a scene, so this can return null.
        final Node scene = colladaNodeUtils.getVisualScene(collada);

        if (_loadAnimations) {
            colladaAnimUtils.parseLibraryAnimations(collada);
        }

        // reattach attachments to scene
        if (scene != null) {
            colladaNodeUtils.reattachAttachments(scene);
        }

        // set our scene into storage
        colladaStorage.setScene(scene);

        // set our asset data into storage
        colladaStorage.setAssetData(assetData);

        // drop our added locator if needed.
        if (addLocator) {
            ResourceLocatorTool.removeResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, loc);
        }

        // copy across our mesh colors - only for objects with multiple channels
        final Multimap<MeshData, FloatBuffer> colors = ArrayListMultimap.create();
        final Multimap<MeshData, FloatBuffer> temp = dataCache.getParsedVertexColors();
        for (final MeshData key : temp.keySet()) {
            // only copy multiple channels since their data is lost
            final Collection<FloatBuffer> val = temp.get(key);
            if (val != null && val.size() > 1) {
                colors.putAll(key, val);
            }
        }
        colladaStorage.setParsedVertexColors(colors);

        // copy across our mesh material info
        colladaStorage.setMeshMaterialInfo(dataCache.getMeshMaterialMap());
        colladaStorage.setMaterialMap(dataCache.getMaterialInfoMap());

        // return storage
        return colladaStorage;
    } catch (final Exception e) {
        throw new IOException("Unable to load collada resource from URL: " + resource, e);
    }
}

From source file:com.palantir.atlasdb.keyvalue.impl.ProfilingKeyValueService.java

@Override
public void putWithTimestamps(String tableName, Multimap<Cell, Value> values) {
    if (log.isTraceEnabled()) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        delegate.putWithTimestamps(tableName, values);
        logCellsAndSize("putWithTimestamps", tableName, values.keySet().size(), byteSize(values), stopwatch);
    } else {/*from  www  . j a v a2  s  .c o  m*/
        delegate.putWithTimestamps(tableName, values);
    }
}

From source file:org.codeqinvest.investment.QualityInvestmentPlanService.java

public QualityInvestmentPlan computeInvestmentPlan(QualityAnalysis analysis, String basePackage,
        int investmentInMinutes) {
    Multimap<Double, QualityViolation> violationsByProfit = ArrayListMultimap.create();
    for (QualityViolation violation : filterViolationsByArtefactNameStartingWith(basePackage,
            analysis.getViolations())) {
        double profit = profitCalculator.calculateProfit(violation);
        if (Math.round(profit) > 0) {
            violationsByProfit.put(profit, violation);
        }//  w  w  w.jav  a 2 s  . com
    }

    List<Double> allProfits = new ArrayList<Double>();
    for (Double profit : violationsByProfit.keySet()) {
        int numberOfViolations = violationsByProfit.get(profit).size();
        for (int i = 0; i < numberOfViolations; i++) {
            allProfits.add(profit);
        }
    }
    Collections.sort(allProfits, new DescendingComparator<Double>());

    Set<QualityInvestmentPlanEntry> investmentPlanEntries = Sets.newTreeSet();
    int toInvest = investmentInMinutes;
    int invested = 0;

    for (double profit : allProfits) {
        List<QualityViolation> violations = new ArrayList<QualityViolation>(violationsByProfit.get(profit));
        Collections.sort(violations, new ViolationByRemediationCostsComparator());

        for (QualityViolation violation : violations) {
            int remediationCost = violation.getRemediationCosts();
            if (remediationCost <= toInvest) {

                invested += remediationCost;
                toInvest -= remediationCost;

                QualityRequirement requirement = violation.getRequirement();
                investmentPlanEntries.add(new QualityInvestmentPlanEntry(requirement.getMetricIdentifier(),
                        requirement.getOperator() + " " + requirement.getThreshold(),
                        violation.getArtefact().getName(), violation.getArtefact().getShortClassName(),
                        (int) Math.round(profit), remediationCost));
            }
        }
    }

    final int overallProfit = calculateOverallProfit(investmentPlanEntries);
    return new QualityInvestmentPlan(basePackage, invested, overallProfit,
            calculateRoi(investmentPlanEntries, overallProfit), investmentPlanEntries);
}

From source file:com.haulmont.cuba.core.app.dynamicattributes.DynamicAttributesManager.java

@Override
public <E extends BaseGenericIdEntity> void fetchDynamicAttributes(List<E> entities,
        @Nonnull Set<Class> dependentClasses) {
    Set<BaseGenericIdEntity> toProcess = new HashSet<>();
    entities.forEach(entity -> {/*ww  w . ja v a2s .co  m*/
        toProcess.add(entity);
        if (!dependentClasses.isEmpty()) {
            metadata.getTools().traverseAttributes(entity, new EntityAttributeVisitor() {
                @Override
                public void visit(Entity dependentEntity, MetaProperty property) {
                    if (dependentEntity instanceof BaseGenericIdEntity) {
                        toProcess.add((BaseGenericIdEntity) dependentEntity);
                    }
                }

                @Override
                public boolean skip(MetaProperty property) {
                    return metadata.getTools().isPersistent(property) && property.getRange().isClass()
                            && dependentClasses.contains(property.getJavaType());
                }
            });
        }
    });
    if (toProcess.isEmpty())
        return;

    try (Transaction tx = persistence.getTransaction()) {
        Multimap<String, BaseGenericIdEntity> entitiesByType = HashMultimap.create();
        toProcess.forEach(e -> entitiesByType.put(e.getMetaClass().getName(), e));
        entitiesByType.keySet().forEach(entityType -> {
            MetaClass metaClass = metadata.getExtendedEntities()
                    .getOriginalOrThisMetaClass(metadata.getClass(entityType));
            doFetchDynamicAttributes(metaClass, entitiesByType.get(entityType));
        });
        tx.commit();
    }
}