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

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

Introduction

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

Prototype

Collection<Map.Entry<K, V>> entries();

Source Link

Document

Returns a view collection of all key-value pairs contained in this multimap, as Map.Entry instances.

Usage

From source file:uk.ac.ebi.mdk.apps.tool.Align2Reference.java

@Override
public void process() {

    System.out.print("Reading query...");
    final Reconstruction query = getReconstruction("query");
    System.out.println("done");
    System.out.print("Reading reference...");
    final Reconstruction reference = getReconstruction("reference");
    System.out.println("done");

    System.out.printf("    Query reconstruction %20s %6s,%6s\n", query.getAccession(),
            query.getMetabolome().size(), query.getReactome().size());
    System.out.printf("Reference reconstruction %20s %6s,%6s\n", reference.getAccession(),
            reference.getMetabolome().size(), reference.getReactome().size());

    if (has("profile")) {
        // break point for starting visual vm

        Scanner scanner = new Scanner(System.in);
        System.out.print("Ready to go? [y/n]:\n");
        while (!scanner.nextLine().equalsIgnoreCase("y")) {

            // await signal
            System.out.println("Okay, let me know");
            System.out.print("Ready to go? [y/n]:");
        }//from   www .  j  a  v a2 s  .c om
    }

    MolecularHashFactory.getInstance().setDepth(1);

    final EntityAligner<Metabolite> aligner = new MappedEntityAligner<Metabolite>(
            reference.getMetabolome().toList(), false);

    final List<MetaboliteHashCodeMatcher> hashCodeMatchers = new ArrayList<MetaboliteHashCodeMatcher>();
    hashCodeMatchers.add(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class,
            StereoSeed.class, ConnectedAtomSeed.class, ChargeSeed.class));
    hashCodeMatchers.add(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class,
            ConnectedAtomSeed.class, StereoSeed.class));
    hashCodeMatchers.add(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class,
            ConnectedAtomSeed.class, ChargeSeed.class));

    aligner.push(new DirectMatcher<Metabolite>());
    aligner.push(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class, StereoSeed.class,
            ConnectedAtomSeed.class, ChargeSeed.class));
    aligner.push(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class,
            ConnectedAtomSeed.class, StereoSeed.class));
    aligner.push(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class,
            ConnectedAtomSeed.class, ChargeSeed.class));
    aligner.push(new MetaboliteHashCodeMatcher(AtomicNumberSeed.class, BondOrderSumSeed.class,
            ConnectedAtomSeed.class));
    aligner.push(new NameMatcher<Metabolite>());
    aligner.push(new NameMatcher<Metabolite>(true, true));

    final EntityMatcher<Metabolite, ?> nameMatcher = new NameMatcher<Metabolite>(true, true);

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {

            Collection<Metabolite> unmatched = new ArrayList<Metabolite>();
            Collection<Multimap<Metabolite, Metabolite>> mismatched = new ArrayList<Multimap<Metabolite, Metabolite>>();

            int matched = 0;

            long start = System.currentTimeMillis();

            for (Metabolite m : query.getMetabolome()) {

                List<Metabolite> matches = aligner.getMatches(m);
                matched += matches.isEmpty() ? 0 : 1;

                if (matches.isEmpty()) {
                    unmatched.add(m);
                }

                //                    for (Metabolite r : matches) {
                //                        if (!nameMatcher.matches(m, r)) {
                //                            Multimap multimap = HashMultimap.create();
                //                            multimap.putAll(m, matches);
                //                            mismatched.add(multimap);
                //                            break;
                //                        }
                //                    }

            }

            long end = System.currentTimeMillis();

            System.out.println("Completed in " + (end - start) + " ms");
            System.out.println("Matched " + matched + "/" + query.getMetabolome().size() + " entities");
            System.out.println("Structure mismatch " + mismatched.size());

            try {
                File tmp = File.createTempFile("unmatched", ".tsv");
                CSVWriter writer = new CSVWriter(new FileWriter(tmp), '\t');
                for (Metabolite m : unmatched) {
                    writer.writeNext(new String[] { m.getAccession(), m.getName(),
                            m.getAnnotationsExtending(CrossReference.class).toString() });
                }
                writer.close();

                System.out.println("Unmatched entries written to: " + tmp);

            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
            try {
                File tmp = File.createTempFile("miss-matched", ".tsv");
                CSVWriter writer = new CSVWriter(new FileWriter(tmp), '\t');
                for (Multimap<Metabolite, Metabolite> emap : mismatched) {
                    for (Map.Entry<Metabolite, Metabolite> e : emap.entries()) {

                        List<Set<Integer>> qh = new ArrayList<Set<Integer>>();
                        List<Set<Integer>> rh = new ArrayList<Set<Integer>>();

                        for (MetaboliteHashCodeMatcher matcher : hashCodeMatchers) {
                            qh.add(matcher.calculatedMetric(e.getKey()));
                        }
                        for (MetaboliteHashCodeMatcher matcher : hashCodeMatchers) {
                            rh.add(matcher.calculatedMetric(e.getValue()));
                        }

                        writer.writeNext(new String[] { e.getKey().getAccession(), e.getKey().getName(),
                                e.getKey().getAnnotationsExtending(CrossReference.class).toString(),

                                e.getValue().getAccession(), e.getValue().getName(),
                                e.getValue().getAnnotationsExtending(CrossReference.class).toString(), "",
                                Joiner.on(", ").join(qh), Joiner.on(", ").join(rh) });
                    }
                }
                writer.close();

                System.out.println("Miss-matched entries written to: " + tmp);

            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }

        }
    });
    t.setName("METABOLOME ALIGNMENT");
    t.start();
    try {
        t.join();
    } catch (InterruptedException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

    final Map<Metabolite, Integer> countMap = new HashMap<Metabolite, java.lang.Integer>();
    Reactome reactome = query.getReactome();
    for (Metabolite m : query.getMetabolome()) {
        countMap.put(m, reactome.participatesIn(m).size());
    }

    System.out.println("Most common metabolites:");
    for (Map.Entry<Metabolite, Integer> e : entriesSortedByValues(countMap)) {
        if (e.getValue() > 40) {
            System.out.println(e.getKey() + ":" + e.getKey().hashCode() + ":" + e.getValue());
        }
    }

    Set<Metabolite> queryCurrencyMetabolites = new HashSet<Metabolite>();
    Set<Metabolite> referenceCurrencyMetabolites = new HashSet<Metabolite>();
    queryCurrencyMetabolites.addAll(query.getMetabolome().ofName("H+"));
    queryCurrencyMetabolites.addAll(query.getMetabolome().ofName("H2O"));
    queryCurrencyMetabolites.addAll(query.getMetabolome().ofName("CO2"));
    queryCurrencyMetabolites.addAll(query.getMetabolome().ofName("ammonium"));
    queryCurrencyMetabolites.addAll(query.getMetabolome().ofName("ammonia"));
    referenceCurrencyMetabolites.addAll(reference.getMetabolome().ofName("H+"));
    referenceCurrencyMetabolites.addAll(reference.getMetabolome().ofName("H2O"));
    referenceCurrencyMetabolites.addAll(reference.getMetabolome().ofName("CO2"));
    referenceCurrencyMetabolites.addAll(reference.getMetabolome().ofName("ammonium"));
    referenceCurrencyMetabolites.addAll(reference.getMetabolome().ofName("ammonia"));
    referenceCurrencyMetabolites.addAll(reference.getMetabolome().ofName("Phosphate"));

    int count = 0;
    int transport = 0;

    System.out.println();
    System.out.println("| REACTOME ALIGNMENT |");

    EntityAligner<MetabolicReaction> reactionAligner = new MappedEntityAligner<MetabolicReaction>(
            reference.reactome().toList());

    reactionAligner.push(new ReactionMatcher(aligner));
    reactionAligner.push(new ReactionMatcher(aligner, false));
    reactionAligner.push(new ReactionMatcher(aligner, true,
            Collections.singleton(reference.getMetabolome().ofName("H+").iterator().next())));
    reactionAligner.push(new ReactionMatcher(aligner, false,
            Collections.singleton(reference.getMetabolome().ofName("H+").iterator().next())));
    reactionAligner.push(new ReactionMatcher(aligner, false,
            new HashSet<Metabolite>(Arrays.asList(reference.getMetabolome().ofName("H+").iterator().next(),
                    reference.getMetabolome().ofName("H2O").iterator().next()))));
    reactionAligner.push(new ReactionMatcher(aligner, false, referenceCurrencyMetabolites));

    for (MetabolicReaction reaction : reactome) {

        // skip transport reactsions for now
        if (TransportReactionUtil.isTransport(reaction)) {
            transport++;
            continue;
        }

        System.out.println(reaction.getIdentifier() + ": " + reaction);

        Collection<MetabolicReaction> matches = reactionAligner.getMatches(reaction);
        for (MetabolicReaction rxnMatch : matches) {
            System.out.println("\t" + rxnMatch);
        }

        count += matches.isEmpty() ? 1 : 0;

        if (true)
            continue;

        Map<Identifier, MutableInt> reactionReferences = new HashMap<Identifier, MutableInt>();

        for (Participant<Metabolite, ?> p : reaction.getParticipants()) {

            Metabolite m = p.getMolecule();

            System.out.print("\t" + m.getName() + " == ");

            for (Metabolite r : aligner.getMatches(m)) {

                System.out.print(r + " ");

                for (Reaction rxnRef : reference.participatesIn(r)) {

                    Identifier identifier = rxnRef.getIdentifier();

                    if (!reactionReferences.containsKey(identifier)) {
                        reactionReferences.put(identifier, new MutableInt());
                    }

                    reactionReferences.get(identifier).increment();

                }
            }

            System.out.println();

        }

        Map<Identifier, MetabolicReaction> idToReaction = new HashMap<Identifier, MetabolicReaction>();
        for (MetabolicReaction r : reference.reactome()) {
            idToReaction.put(r.getIdentifier(), r);
        }

        System.out.println("Candidate matches for " + reaction);
        for (Map.Entry<Identifier, MutableInt> e : reactionReferences.entrySet()) {

            int nParticipants = e.getValue().toInteger();

            if (nParticipants >= adjustedCount(reaction, queryCurrencyMetabolites)) {

                Collection<MetabolicParticipant> refps = adjustedParticipants(idToReaction.get(e.getKey()),
                        referenceCurrencyMetabolites);

                boolean show = true;

                MetabolicReaction referenceReaction = idToReaction.get(e.getKey());

                System.out.println(referenceReaction);

                for (Participant<Metabolite, ?> p : adjustedParticipants(reaction, queryCurrencyMetabolites)) {

                    List<Metabolite> referenceMetabolites = aligner.getMatches(p.getMolecule());

                    if (referenceMetabolites.isEmpty()) {
                        // missing reference
                        show = false;
                        break;
                    }

                    if (referenceMetabolites.size() > 1) {
                        // complex case
                        show = false;
                        break;
                    }

                    Metabolite r = referenceMetabolites.get(0);
                    boolean found = false;
                    MetabolicParticipant remove = null;
                    for (MetabolicParticipant rp : refps) {
                        if (rp.getMolecule().equals(r)) {
                            found = true;
                            remove = rp;
                            break;
                        }
                    }

                    if (!found) {
                        show = false;
                    } else {
                        refps.remove(remove);
                    }

                }

                // matches
                if (show && refps.isEmpty()) {
                    System.out.println("\t [match] " + referenceReaction);
                    //                        MetabolicReaction rxn1 = m2.calculatedMetric(reaction).iterator().readNext();
                    //                        MetabolicReaction rxn2 = m2.calculatedMetric(referenceReaction).iterator().readNext();
                    //                        System.out.println(rxn1.hashCode());
                    //                        System.out.println(rxn2.hashCode());
                    //                        System.out.println(rxn1.equals(rxn2));

                }
            }

        }

    }

    System.out.println(count + "/" + query.getReactome().size()
            + " were not matched (transport reactions skipped by default) n transport reactions = "
            + transport);

}

From source file:brooklyn.entity.nosql.cassandra.CassandraDatacenterImpl.java

@Override
public void init() {
    super.init();

    /*/*from  w ww. j  av a 2  s .  c o m*/
     * subscribe to hostname, and keep an accurate set of current seeds in a sensor;
     * then at nodes we set the initial seeds to be the current seeds when ready (non-empty)
     */
    subscribeToMembers(this, Attributes.HOSTNAME, new SensorEventListener<String>() {
        @Override
        public void onEvent(SensorEvent<String> event) {
            seedTracker.onHostnameChanged(event.getSource(), event.getValue());
        }
    });
    subscribe(this, DynamicGroup.MEMBER_REMOVED, new SensorEventListener<Entity>() {
        @Override
        public void onEvent(SensorEvent<Entity> event) {
            seedTracker.onMemberRemoved(event.getValue());
        }
    });
    subscribeToMembers(this, Attributes.SERVICE_UP, new SensorEventListener<Boolean>() {
        @Override
        public void onEvent(SensorEvent<Boolean> event) {
            seedTracker.onServiceUpChanged(event.getSource(), event.getValue());
        }
    });
    subscribeToMembers(this, Attributes.SERVICE_STATE_ACTUAL, new SensorEventListener<Lifecycle>() {
        @Override
        public void onEvent(SensorEvent<Lifecycle> event) {
            // trigger a recomputation also when lifecycle state changes, 
            // because it might not have ruled a seed as inviable when service up went true 
            // because service state was not yet running
            seedTracker.onServiceUpChanged(event.getSource(), Lifecycle.RUNNING == event.getValue());
        }
    });

    // Track the datacenters for this cluster
    subscribeToMembers(this, CassandraNode.DATACENTER_NAME, new SensorEventListener<String>() {
        @Override
        public void onEvent(SensorEvent<String> event) {
            Entity member = event.getSource();
            String dcName = event.getValue();
            if (dcName != null) {
                Multimap<String, Entity> datacenterUsage = getAttribute(DATACENTER_USAGE);
                Multimap<String, Entity> mutableDatacenterUsage = (datacenterUsage == null)
                        ? LinkedHashMultimap.<String, Entity>create()
                        : LinkedHashMultimap.create(datacenterUsage);
                Optional<String> oldDcName = getKeyOfVal(mutableDatacenterUsage, member);
                if (!(oldDcName.isPresent() && dcName.equals(oldDcName.get()))) {
                    mutableDatacenterUsage.values().remove(member);
                    mutableDatacenterUsage.put(dcName, member);
                    setAttribute(DATACENTER_USAGE, mutableDatacenterUsage);
                    setAttribute(DATACENTERS, Sets.newLinkedHashSet(mutableDatacenterUsage.keySet()));
                }
            }
        }

        private <K, V> Optional<K> getKeyOfVal(Multimap<K, V> map, V val) {
            for (Map.Entry<K, V> entry : map.entries()) {
                if (Objects.equal(val, entry.getValue())) {
                    return Optional.of(entry.getKey());
                }
            }
            return Optional.absent();
        }
    });
    subscribe(this, DynamicGroup.MEMBER_REMOVED, new SensorEventListener<Entity>() {
        @Override
        public void onEvent(SensorEvent<Entity> event) {
            Entity entity = event.getSource();
            Multimap<String, Entity> datacenterUsage = getAttribute(DATACENTER_USAGE);
            if (datacenterUsage != null && datacenterUsage.containsValue(entity)) {
                Multimap<String, Entity> mutableDatacenterUsage = LinkedHashMultimap.create(datacenterUsage);
                mutableDatacenterUsage.values().remove(entity);
                setAttribute(DATACENTER_USAGE, mutableDatacenterUsage);
                setAttribute(DATACENTERS, Sets.newLinkedHashSet(mutableDatacenterUsage.keySet()));
            }
        }
    });

    getMutableEntityType().addEffector(EXECUTE_SCRIPT, new EffectorBody<String>() {
        @Override
        public String call(ConfigBag parameters) {
            return executeScript((String) parameters.getStringKey("commands"));
        }
    });
}

From source file:de.hzi.helmholtz.Compare.PathwayComparisonWithModules.java

public double Calculations4SubsetBitScore(Map<String, Map<String, Double>> bestResultMappings) {
    SmithWaterman_b sw = new SmithWaterman_b();
    int MatchingSubstrateCount = 0;
    int MismatchSubstrateCount = 0;
    int MatchingFunctionCount = 0;
    int MismatchFunctionCount = 0;

    Multiset<String> qfunction = LinkedHashMultiset.create();
    Multiset<String> tfunction = LinkedHashMultiset.create();
    List<Set<String>> qsubstrate = new ArrayList<Set<String>>();
    List<Set<String>> tsubstrate = new ArrayList<Set<String>>();
    String GeneKey = "";
    int FunctionMatch = 0, StatusMatch = 0, SubstrateMatch = 0;
    int FunctionMisMatch = 0, StatusMisMatch = 0, SubstrateMisMatch = 0;
    int TranspositionDomains = 0;
    for (Map.Entry<String, Map<String, Double>> i : bestResultMappings.entrySet()) {
        for (Map.Entry<String, Double> j : i.getValue().entrySet()) {

            GeneKey = i.getKey() + "->" + j.getKey();
        }//  w  w w  . j a va  2 s  .c o  m
        Collection<Multimap<String, Integer>> Function = ScoreFunctionMatchMisMatch.get(GeneKey);
        for (Multimap<String, Integer> GetFunction : Function) {
            for (Map.Entry<String, Integer> Get : GetFunction.entries()) {
                String[] points = Get.getKey().split("-");
                FunctionMatch += Integer.parseInt(points[0].trim());
                FunctionMisMatch += Integer.parseInt(points[1].trim());
                TranspositionDomains += Get.getValue();
                break;
            }
            break;
        }
        Collection<Multimap<String, Integer>> Status = ScoreStatusMatchMisMatch.get(GeneKey);
        for (Multimap<String, Integer> GetFunction : Status) {
            for (Map.Entry<String, Integer> Get : GetFunction.entries()) {
                String[] points = Get.getKey().split("-");
                StatusMatch += Integer.parseInt(points[0].trim());
                StatusMisMatch += Integer.parseInt(points[1].trim());
                break;
            }
            break;
        }
        Collection<Multimap<String, Integer>> Substrate = ScoreSubstrateMatchMisMatch.get(GeneKey);
        for (Multimap<String, Integer> GetFunction : Substrate) {
            for (Map.Entry<String, Integer> Get : GetFunction.entries()) {
                String[] points = Get.getKey().split("-");
                SubstrateMatch += Integer.parseInt(points[0].trim());
                SubstrateMisMatch += Integer.parseInt(points[1].trim());
                break;
            }
            break;
        }
    }

    if (FunctionMisMatch == 0) {

    }
    //////System.out.println(MismatchCount + "                 " + MatchingCount);
    int rawFunctionScore = ((FunctionMatch * 3) - (FunctionMisMatch * 2) - TranspositionDomains);
    int rawStatusScore = (StatusMatch * 3) - (StatusMisMatch * 2);
    int rawSubstrateScore = (SubstrateMatch * 3) - (SubstrateMisMatch * 2);

    double SubstrateBitScore = (((lambda * rawSubstrateScore) + Math.log(kscore)) / Math.log(2));
    double StatusBitScore = (((lambda * rawStatusScore) + Math.log(kscore)) / Math.log(2));
    double FunctionBitScore = (((lambda * rawFunctionScore) + Math.log(kscore)) / Math.log(2));
    Double BitScore = SubstrateBitScore + StatusBitScore + FunctionBitScore;
    ////System.out.println(rawFunctionScore + "                " + MatchingSubstrateCount + "              " + BitScore);
    ScoreFunctionMatchMisMatch.clear();
    ScoreStatusMatchMisMatch.clear();
    ScoreSubstrateMatchMisMatch.clear();
    return BitScore;
}

From source file:com.tinspx.util.net.Request.java

static StringBuilder append(@NonNull StringBuilder sb, @Nullable Multimap<String, String> map,
        @NonNull Escaper escaper) {// ww  w . j  a  va 2 s  . c  o  m
    if (map == null || map.isEmpty()) {
        return sb;
    }
    boolean first = true;
    for (Map.Entry<String, String> entry : map.entries()) {
        if (sb.length() > 0 || !first) {
            sb.append('&');
        }
        first = false;
        sb.append(escaper.escape(entry.getKey()));
        if (entry.getValue() != null) {
            sb.append('=');
            sb.append(escaper.escape(entry.getValue()));
        }
    }
    return sb;
}

From source file:org.apache.brooklyn.entity.nosql.cassandra.CassandraDatacenterImpl.java

@Override
public void init() {
    super.init();

    /*//from w ww  .j a  va  2 s.co  m
     * subscribe to hostname, and keep an accurate set of current seeds in a sensor;
     * then at nodes we set the initial seeds to be the current seeds when ready (non-empty)
     */
    subscriptions().subscribeToMembers(this, Attributes.HOSTNAME, new SensorEventListener<String>() {
        @Override
        public void onEvent(SensorEvent<String> event) {
            seedTracker.onHostnameChanged(event.getSource(), event.getValue());
        }
    });
    subscriptions().subscribe(this, DynamicGroup.MEMBER_REMOVED, new SensorEventListener<Entity>() {
        @Override
        public void onEvent(SensorEvent<Entity> event) {
            seedTracker.onMemberRemoved(event.getValue());
        }
    });
    subscriptions().subscribeToMembers(this, Attributes.SERVICE_UP, new SensorEventListener<Boolean>() {
        @Override
        public void onEvent(SensorEvent<Boolean> event) {
            seedTracker.onServiceUpChanged(event.getSource(), event.getValue());
        }
    });
    subscriptions().subscribeToMembers(this, Attributes.SERVICE_STATE_ACTUAL,
            new SensorEventListener<Lifecycle>() {
                @Override
                public void onEvent(SensorEvent<Lifecycle> event) {
                    // trigger a recomputation also when lifecycle state changes, 
                    // because it might not have ruled a seed as inviable when service up went true 
                    // because service state was not yet running
                    seedTracker.onServiceUpChanged(event.getSource(), Lifecycle.RUNNING == event.getValue());
                }
            });

    // Track the datacenters for this cluster
    subscriptions().subscribeToMembers(this, CassandraNode.DATACENTER_NAME, new SensorEventListener<String>() {
        @Override
        public void onEvent(SensorEvent<String> event) {
            Entity member = event.getSource();
            String dcName = event.getValue();
            if (dcName != null) {
                Multimap<String, Entity> datacenterUsage = getAttribute(DATACENTER_USAGE);
                Multimap<String, Entity> mutableDatacenterUsage = (datacenterUsage == null)
                        ? LinkedHashMultimap.<String, Entity>create()
                        : LinkedHashMultimap.create(datacenterUsage);
                Optional<String> oldDcName = getKeyOfVal(mutableDatacenterUsage, member);
                if (!(oldDcName.isPresent() && dcName.equals(oldDcName.get()))) {
                    mutableDatacenterUsage.values().remove(member);
                    mutableDatacenterUsage.put(dcName, member);
                    sensors().set(DATACENTER_USAGE, mutableDatacenterUsage);
                    sensors().set(DATACENTERS, Sets.newLinkedHashSet(mutableDatacenterUsage.keySet()));
                }
            }
        }

        private <K, V> Optional<K> getKeyOfVal(Multimap<K, V> map, V val) {
            for (Map.Entry<K, V> entry : map.entries()) {
                if (Objects.equal(val, entry.getValue())) {
                    return Optional.of(entry.getKey());
                }
            }
            return Optional.absent();
        }
    });
    subscriptions().subscribe(this, DynamicGroup.MEMBER_REMOVED, new SensorEventListener<Entity>() {
        @Override
        public void onEvent(SensorEvent<Entity> event) {
            Entity entity = event.getSource();
            Multimap<String, Entity> datacenterUsage = getAttribute(DATACENTER_USAGE);
            if (datacenterUsage != null && datacenterUsage.containsValue(entity)) {
                Multimap<String, Entity> mutableDatacenterUsage = LinkedHashMultimap.create(datacenterUsage);
                mutableDatacenterUsage.values().remove(entity);
                sensors().set(DATACENTER_USAGE, mutableDatacenterUsage);
                sensors().set(DATACENTERS, Sets.newLinkedHashSet(mutableDatacenterUsage.keySet()));
            }
        }
    });

    getMutableEntityType().addEffector(EXECUTE_SCRIPT, new EffectorBody<String>() {
        @Override
        public String call(ConfigBag parameters) {
            return executeScript((String) parameters.getStringKey("commands"));
        }
    });
}

From source file:org.computer.whunter.rpm.parser.RpmSpecParser.java

/** 
 * The values of fields and macros can themselves contain the values of other directives. Search through the 
 * properties and replace these values if they are present.
 * //from  w  ww  . j a v a2  s .c  om
 * @param properties the properties to modify by expanding any values
 */
private void expandReferences(Multimap<String, String> properties) {

    Map<Pattern, String> matcherPatterns = new HashMap<Pattern, String>();
    matcherPatterns.putAll(m_fieldReferenceMatcherPatterns);
    matcherPatterns.putAll(m_macroReferenceMatcherPatterns);

    Map<String, Pattern> replacePatterns = new HashMap<String, Pattern>();
    replacePatterns.putAll(m_fieldReferenceReplacePatterns);
    replacePatterns.putAll(m_macroReferenceReplacePatterns);

    Multimap<String, String> newProperties = ArrayListMultimap.create();
    for (Entry<String, String> property : properties.entries()) {
        String newValue = expandReferences(property.getValue().toString(), properties, matcherPatterns,
                replacePatterns);
        newProperties.put(property.getKey().toString(), newValue);
    }
    properties.clear();
    properties.putAll(newProperties);
}

From source file:org.apache.beam.sdk.io.FileSystems.java

@VisibleForTesting
static Map<String, FileSystem> verifySchemesAreUnique(PipelineOptions options,
        Set<FileSystemRegistrar> registrars) {
    Multimap<String, FileSystem> fileSystemsBySchemes = TreeMultimap.create(Ordering.<String>natural(),
            Ordering.arbitrary());/*  w  w w .  j a v a 2  s .com*/

    for (FileSystemRegistrar registrar : registrars) {
        for (FileSystem fileSystem : registrar.fromOptions(options)) {
            fileSystemsBySchemes.put(fileSystem.getScheme(), fileSystem);
        }
    }
    for (Entry<String, Collection<FileSystem>> entry : fileSystemsBySchemes.asMap().entrySet()) {
        if (entry.getValue().size() > 1) {
            String conflictingFileSystems = Joiner.on(", ")
                    .join(FluentIterable.from(entry.getValue()).transform(new Function<FileSystem, String>() {
                        @Override
                        public String apply(@Nonnull FileSystem input) {
                            return input.getClass().getName();
                        }
                    }).toSortedList(Ordering.<String>natural()));
            throw new IllegalStateException(String.format("Scheme: [%s] has conflicting filesystems: [%s]",
                    entry.getKey(), conflictingFileSystems));
        }
    }

    ImmutableMap.Builder<String, FileSystem> schemeToFileSystem = ImmutableMap.builder();
    for (Entry<String, FileSystem> entry : fileSystemsBySchemes.entries()) {
        schemeToFileSystem.put(entry.getKey(), entry.getValue());
    }
    return schemeToFileSystem.build();
}

From source file:com.jcwhatever.nucleus.collections.wrap.MultimapWrapper.java

@Override
public boolean putAll(@Nonnull Multimap<? extends K, ? extends V> multimap) {
    PreCon.notNull(multimap);//ww w  .  ja v  a 2s  . c o  m

    boolean isChanged = false;

    for (Entry<? extends K, ? extends V> entry : multimap.entries()) {

        isChanged = put(entry.getKey(), entry.getValue()) || isChanged;
    }

    return isChanged;
}

From source file:ai.grakn.graql.internal.reasoner.atom.binary.RelationAtom.java

/**
 * @return map of pairs role type - Id predicate describing the role player playing this role (substitution)
 *//*from   w w w .j a  v  a 2s  .  c  o m*/
private Multimap<Role, String> getRoleConceptIdMap() {
    if (roleConceptIdMap == null) {
        roleConceptIdMap = ArrayListMultimap.create();

        Map<Var, IdPredicate> varSubMap = getPartialSubstitutions().stream()
                .collect(Collectors.toMap(Atomic::getVarName, pred -> pred));
        Multimap<Role, Var> roleMap = getRoleVarMap();

        roleMap.entries().forEach(e -> {
            Role role = e.getKey();
            Var var = e.getValue();
            roleConceptIdMap.put(role,
                    varSubMap.containsKey(var) ? varSubMap.get(var).getPredicateValue() : "");
        });
    }
    return roleConceptIdMap;
}

From source file:org.onosproject.powermanagement.PowerConfigWebResource.java

private ObjectNode encode(PowerConfig<Object> powerConfig, String direction, String channel) {
    checkNotNull(powerConfig, "PowerConfig cannot be null");
    ObjectNode powerConfigPorts = mapper.createObjectNode();
    Multimap<PortNumber, Object> portsMap = HashMultimap.create();

    if (direction != null) {
        for (PortNumber port : powerConfig.getPorts(direction)) {
            portsMap.put(port, Direction.valueOf(direction.toUpperCase()));
        }//from  w  ww  .j a va2 s  . co m
    }

    if (channel != null) {
        for (PortNumber port : powerConfig.getPorts(channel)) {
            // TODO: channel to be handled
            portsMap.put(port, channel);
        }
    }

    for (Map.Entry<PortNumber, Object> entry : portsMap.entries()) {
        PortNumber port = entry.getKey();
        ObjectNode powerConfigComponents = mapper.createObjectNode();
        for (Object component : portsMap.get(port)) {
            // TODO: channel to be handled
            String componentName = "unknown";
            if (component instanceof Direction) {
                componentName = component.toString();
            }
            ObjectNode powerConfigNode = mapper.createObjectNode()
                    .put(CURRENT_POWER, powerConfig.currentPower(port, component).orElse(0L))
                    .put(TARGET_POWER, powerConfig.getTargetPower(port, component).orElse(0L))
                    .put(INPUT_POWER_RANGE,
                            powerConfig.getInputPowerRange(port, component).orElse(Range.closed(0L, 0L))
                                    .toString())
                    .put(TARGET_POWER_RANGE, powerConfig.getTargetPowerRange(port, component)
                            .orElse(Range.closed(0L, 0L)).toString());
            powerConfigComponents.set(componentName, powerConfigNode);
        }
        powerConfigPorts.set(port.toString(), powerConfigComponents);
    }

    ObjectNode result = mapper.createObjectNode();
    result.set("powerConfigPorts", powerConfigPorts);
    return result;
}