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:com.facebook.buck.apple.XctoolRunTestsStep.java

private static void formatXctoolFilterParams(TestSelectorList testSelectorList,
        Multimap<String, TestDescription> testTargetsToDescriptions,
        ImmutableList.Builder<String> filterParamsBuilder) {
    for (String testTarget : testTargetsToDescriptions.keySet()) {
        StringBuilder sb = new StringBuilder();
        boolean matched = false;
        for (TestDescription testDescription : testTargetsToDescriptions.get(testTarget)) {
            if (!testSelectorList.isIncluded(testDescription)) {
                continue;
            }/*from ww  w .  j  a v a  2s .c o m*/
            if (!matched) {
                matched = true;
                sb.append(testTarget);
                sb.append(':');
            } else {
                sb.append(',');
            }
            sb.append(testDescription.getClassName());
            sb.append('/');
            sb.append(testDescription.getMethodName());
        }
        if (matched) {
            filterParamsBuilder.add("-only");
            filterParamsBuilder.add(sb.toString());
        }
    }
}

From source file:msi.gama.util.GAML.java

public static String getDocumentationOn(final String query) {
    final String keyword = StringUtils.removeEnd(StringUtils.removeStart(query.trim(), "#"), ":");
    final Multimap<GamlIdiomsProvider<?>, IGamlDescription> results = GamlIdiomsProvider.forName(keyword);
    if (results.isEmpty()) {
        return "No result found";
    }/*from  ww  w. jav a2 s  . c o  m*/
    final StringBuilder sb = new StringBuilder();
    final int max = results.keySet().stream().mapToInt(each -> each.name.length()).max().getAsInt();
    final String separator = StringUtils.repeat("", max + 6).concat(Strings.LN);
    results.asMap().forEach((provider, list) -> {
        sb.append("").append(separator).append("|| ");
        sb.append(StringUtils.rightPad(provider.name, max));
        sb.append(" ||").append(Strings.LN).append(separator);
        for (final IGamlDescription d : list) {
            sb.append("== ").append(toText(d.getTitle())).append(Strings.LN)
                    .append(toText(provider.document(d))).append(Strings.LN);
        }
    });

    return sb.toString();

    //
}

From source file:com.zimbra.cs.service.mail.Sync.java

private static void encodePagedDelete(Element eDeleted, PagedDelete pgDelete, SyncToken newSyncToken,
        TypedIdList tombstones, boolean typedDeletes) {
    Collection<Integer> itemIds = pgDelete.getAllIds();
    if (itemIds.isEmpty()) {
        eDeleted.detach();//from ww w . j  a  v a  2 s.  c o m
    } else {
        if (typedDeletes) {
            Multimap<MailItem.Type, Integer> type2Id = pgDelete.getTypedItemIds();
            StringBuilder typed = new StringBuilder();
            for (MailItem.Type type : type2Id.keySet()) {
                String eltName = elementNameForType(type);
                typed.setLength(0);
                for (Integer id : type2Id.get(type)) {
                    typed.append(typed.length() == 0 ? "" : ",").append(id);
                }
                eDeleted.addElement(eltName).addAttribute(MailConstants.A_IDS, typed.toString());
            }
        }
        StringBuilder deleted = new StringBuilder();
        for (Integer itemId : itemIds) {
            deleted.append(deleted.length() == 0 ? "" : ",").append(itemId);
        }
        eDeleted.addAttribute(MailConstants.A_IDS, deleted.toString());
    }
    if (pgDelete.isDeleteOverFlow()) {
        newSyncToken.setDeleteItemId(pgDelete.getLastItemId());
        newSyncToken.setDeleteModSeq(pgDelete.getCutOffModsequnce() - 1);
    }
}

From source file:org.ms2ms.io.PsmWriters.java

public static void writeNovor(String filename, Multimap<SpectrumIdentifier, PeptideMatch> id_match,
        String score, String input) throws IOException {
    if (!Tools.isSet(id_match) || !Strs.isSet(filename))
        return;/*  w ww . j a  v a2 s. co  m*/

    System.out.print("Writing the PSMs to " + filename);

    FileWriter w = new FileWriter(filename);

    // write the header as required
    w.write(newNovorHeader(input).toString());

    int counts = 1;
    String delim = ", ";
    w.write("# id, scanNum, RT, mz(data), z, pepMass(denovo), err(data-denovo), ppm(1e6*err/(mz*z)), score, peptide, aaScore, \n");
    for (SpectrumIdentifier id : id_match.keySet()) {
        // only care about the run as indicated
        if (id.getSpectrum().indexOf(input) != 0)
            continue;

        for (PeptideMatch m : id_match.get(id)) {
            // let's fake an aaScore
            String aascore = null;
            for (int i = 0; i < m.size(); i++)
                aascore = Strs.extend(aascore, "1", "-");

            w.write((counts++) + delim + id.getScanNumbers().getFirst().getValue() + delim
                    + (Tools.isSet(id.getRetentionTimes()) ? id.getRetentionTimes().getFirst().getTime() : 0)
                    + delim + id.getPrecursorMz().get() + delim + id.getAssumedCharge().get() + delim
                    + m.getNeutralPeptideMass() + delim + m.getMassDiff() + delim
                    + 1E6 * m.getMassDiff() / m.getNeutralPeptideMass() + delim + m.getScore(score) + delim
                    + m.toSymbolString() + delim + aascore + "\n");
        }
    }
    System.out.println(" --> " + counts);
    w.close();
}

From source file:org.crypto.sse.DynRH2Lev.java

public static TreeMultimap<String, byte[]> tokenUpdate(byte[] key, Multimap<String, String> lookup)
        throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, NoSuchPaddingException, IOException {

    TreeMultimap<String, byte[]> tokenUp = TreeMultimap.create(Ordering.natural(), Ordering.usingToString());

    SecureRandom random = new SecureRandom();
    random.setSeed(CryptoPrimitives.randomSeed(16));
    byte[] iv = new byte[16];

    for (String word : lookup.keySet()) {

        byte[] key3 = CryptoPrimitives.generateCmac(key, 3 + new String());

        byte[] key4 = CryptoPrimitives.generateCmac(key, 4 + word);

        for (String id : lookup.get(word)) {
            random.nextBytes(iv);//from w  w w  .  j a  va  2  s .c  o m

            int counter = 0;

            if (state.get(word) != null) {
                counter = state.get(word);
            }

            state.put(word, counter + 1);

            byte[] l = CryptoPrimitives.generateCmac(key4, "" + counter);

            byte[] value = CryptoPrimitives.encryptAES_CTR_String(key3, iv, id, sizeOfFileIdentifer);

            tokenUp.put(new String(l), value);
        }

    }

    return tokenUp;

}

From source file:com.tasktop.c2c.server.internal.cloud.hp.HPCloudService.java

protected static Node convertServerToNode(Server server) {
    Node node = new Node();
    node.setIdentity(String.valueOf(server.getId()));
    Multimap<String, Address> addressMap = server.getAddresses();
    // There may be a bug in the JClouds code: both public and private IPs appear
    // for the same "private" key in the map; the private IP is first, the public IP is second
    if (addressMap != null) {
        for (String key : addressMap.keySet()) {
            Collection<Address> addresses = addressMap.get(key);
            if (addresses != null && addresses.size() > 1) {
                for (Address address : addresses) {
                    try {
                        if (!InetAddress.getByName(address.getAddr()).isSiteLocalAddress()) {
                            node.setIpAddress(address.getAddr());
                            break;
                        }//from  w ww . j  a va  2  s .co  m
                    } catch (UnknownHostException e) {
                        LOGGER.debug("Caught Exception examining IP: " + address.getAddr(), e);
                    }
                }
            }
        }
    }
    node.setName(server.getName());
    node.setStatus(convertServerStatusToNodeStatus(server.getStatus()));
    // URI is left null but it is not yet needed
    return node;
}

From source file:com.googlecode.blaisemath.graph.GraphUtils.java

/**
 * Generates ordered set of nodes from an adjacency map
 * @param <V> graph node type//from ww  w . j av a  2s .c om
 * @param adj an adjacency map
 * @return list of nodes
 */
public static <V> Set<V> nodes(Multimap<V, V> adj) {
    Set<V> result = Sets.newLinkedHashSet();
    result.addAll(adj.keySet());
    result.addAll(adj.values());
    return result;
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CQLKeyValueServices.java

public static void waitForSchemaVersionsToCoalesce(String encapsulatingOperationDescription,
        CQLKeyValueService kvs) {/*from   www . j  a  v a2s  .  c  o  m*/
    PreparedStatement peerInfoQuery = kvs.getPreparedStatement(CassandraConstants.NO_TABLE,
            "select peer, schema_version from system.peers;", kvs.session);
    peerInfoQuery.setConsistencyLevel(ConsistencyLevel.ALL);

    Multimap<UUID, InetAddress> peerInfo = ArrayListMultimap.create();
    long start = System.currentTimeMillis();
    long sleepTime = 100;
    do {
        peerInfo.clear();
        for (Row row : kvs.session.execute(peerInfoQuery.bind()).all()) {
            peerInfo.put(row.getUUID("schema_version"), row.getInet("peer"));
        }

        if (peerInfo.keySet().size() <= 1) { // full schema agreement
            return;
        }
        sleepTime = Math.min(sleepTime * 2, 5000);
    } while (System.currentTimeMillis() < start + CassandraConstants.SECONDS_WAIT_FOR_VERSIONS * 1000);

    StringBuilder sb = new StringBuilder();
    sb.append(String.format(
            "Cassandra cluster cannot come to agreement on schema versions, during operation: %s.",
            encapsulatingOperationDescription));

    for (Entry<UUID, Collection<InetAddress>> versionToPeer : peerInfo.asMap().entrySet()) {
        sb.append(String.format("\nAt schema version %s:", versionToPeer.getKey()));
        for (InetAddress peer : versionToPeer.getValue()) {
            sb.append(String.format("\n\tNode: %s", peer));
        }
    }
    sb.append("\nFind the nodes above that diverge from the majority schema "
            + "(or have schema 'UNKNOWN', which likely means they are down/unresponsive) "
            + "and examine their logs to determine the issue. Fixing the underlying issue and restarting Cassandra "
            + "should resolve the problem. You can quick-check this with 'nodetool describecluster'.");
    throw new IllegalStateException(sb.toString());
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CassandraVerifier.java

static Set<String> sanityCheckDatacenters(Cassandra.Client client, int desiredRf, boolean safetyDisabled)
        throws InvalidRequestException, TException {
    ensureTestKeyspaceExists(client);//from  www  .  j  a  va 2 s . c o m
    Set<String> hosts = Sets.newHashSet();

    Multimap<String, String> dataCenterToRack = HashMultimap.create();
    List<TokenRange> ring = client.describe_ring(CassandraConstants.SIMPLE_RF_TEST_KEYSPACE);
    for (TokenRange tokenRange : ring) {
        for (EndpointDetails details : tokenRange.getEndpoint_details()) {
            dataCenterToRack.put(details.datacenter, details.rack);
            hosts.add(details.host);
        }
    }

    if (dataCenterToRack.size() == 1) {
        String dc = dataCenterToRack.keySet().iterator().next();
        String rack = dataCenterToRack.values().iterator().next();
        if (dc.equals(CassandraConstants.DEFAULT_DC) && rack.equals(CassandraConstants.DEFAULT_RACK)
                && desiredRf > 1) {
            // We don't allow greater than RF=1 because they didn't set up their network.
            logErrorOrThrow(
                    "The cassandra cluster is not set up to be datacenter and rack aware.  "
                            + "Please set this up before running with a replication factor higher than 1.",
                    safetyDisabled);

        }
        if (dataCenterToRack.values().size() < desiredRf && hosts.size() > desiredRf) {
            logErrorOrThrow("The cassandra cluster only has one DC, "
                    + "and is set up with less racks than the desired number of replicas, "
                    + "and there are more hosts than the replication factor. "
                    + "It is very likely that your rack configuration is incorrect and replicas would not be placed correctly for the failure tolerance you want.",
                    safetyDisabled);
        }
    }

    return dataCenterToRack.keySet();
}

From source file:org.crypto.sse.IEX2Lev.java

public static IEX2Lev setup(List<byte[]> keys, Multimap<String, String> lookup,
        Multimap<String, String> lookup2, int bigBlock, int smallBlock, int dataSize)
        throws InterruptedException, ExecutionException, IOException {

    // Instantiation of the object that contains Global MM, Local MMs and
    // the dictionary
    RR2Lev[] localMultiMap = new RR2Lev[lookup.keySet().size()];
    Multimap<String, Integer> dictionaryForMM = ArrayListMultimap.create();

    Printer.debugln("Number of (w, id) pairs " + lookup.size());

    Printer.debugln("Number of keywords " + lookup.keySet().size());

    BufferedWriter writer = new BufferedWriter(new FileWriter("logs.txt", true));

    writer.write("\n *********************Stats******* \n");
    writer.write("\n Number of (w, id) pairs " + lookup2.size());
    writer.write("\n Number of keywords " + lookup.keySet().size());

    int counter = 0;

    ///////////////////// Computing Filtering Factor and exact needed data
    ///////////////////// size/////////////////////////////

    HashMap<Integer, Integer> histogram = new HashMap<Integer, Integer>();
    Printer.debugln("Number of documents " + lookup2.keySet().size());
    for (String keyword : lookup.keySet()) {
        if (histogram.get(lookup.get(keyword).size()) != null) {
            int tmp = histogram.get(lookup.get(keyword).size());
            histogram.put(lookup.get(keyword).size(), tmp + 1);
        } else {/*from  w w w  .j  a v a  2s  . c  o  m*/
            histogram.put(lookup.get(keyword).size(), 1);
        }

        if (dataSize < lookup.get(keyword).size()) {
            dataSize = lookup.get(keyword).size();
        }

    }

    // Construction of the global multi-map
    Printer.debugln("\nBeginning of Global MM creation \n");

    long startTime1 = System.nanoTime();

    IEX2Lev disj2 = new IEX2Lev(RR2Lev.constructEMMParGMM(keys.get(0), lookup, bigBlock, smallBlock, dataSize),
            localMultiMap, dictionaryForMM);

    long endTime1 = System.nanoTime();

    writer.write("\n Time of MM global setup time #(w, id)/#DB " + (endTime1 - startTime1) / lookup2.size());
    writer.close();

    numberPairs = numberPairs + lookup.size();

    // Construction of the local multi-map

    Printer.debugln("Start of Local Multi-Map construction");

    long startTime = System.nanoTime();

    for (String keyword : lookup.keySet()) {

        // Stats for keeping track with the evaluation

        for (int j = 0; j < 100; j++) {

            if (counter == (int) ((j + 1) * lookup.keySet().size() / 100)) {
                BufferedWriter writer2 = new BufferedWriter(new FileWriter("temp-logs.txt", true));
                writer2.write("\n Number of local multi-maps created" + j + " %");
                writer2.close();

                break;
            }
        }

        // Filter setting optional. For a setup without any filtering set
        // filterParameter to 0
        if (((double) lookup.get(keyword).size() / TextExtractPar.maxTupleSize > filterParameter)) {

            // Stats
            Printer.debugln("Keyword in LMM " + keyword);
            BufferedWriter writer3 = new BufferedWriter(new FileWriter("words-logs.txt", true));
            writer3.write("\n Keyword in LMM " + keyword);
            writer3.close();

            for (int j = 0; j < 10; j++) {

                if (counter == (int) ((j + 1) * lookup.keySet().size() / 10)) {
                    Printer.statsln("Number of total keywords processed equals " + j + "0 % \n");
                    break;
                }
            }

            // First computing V_w. Determine Doc identifiers

            Set<String> VW = new TreeSet<String>();
            for (String idDoc : lookup.get(keyword)) {
                VW.addAll(lookup2.get(idDoc));
            }

            Multimap<String, String> secondaryLookup = ArrayListMultimap.create();

            // here we are only interested in documents in the intersection
            // between "keyword" and "word"
            for (String word : VW) {
                // Filter setting optional. For a setup without any
                // filtering set filterParameter to 0
                if (((double) lookup.get(word).size() / TextExtractPar.maxTupleSize > filterParameter)) {
                    Collection<String> l1 = new ArrayList<String>(lookup.get(word));
                    Collection<String> l2 = new ArrayList<String>(lookup.get(keyword));
                    l1.retainAll(l2);
                    secondaryLookup.putAll(word, l1);
                }
            }

            // End of VW construction
            RR2Lev.counter = 0;
            // dataSize = (int) filterParameter;
            disj2.getLocalMultiMap()[counter] = RR2Lev.constructEMMParGMM(
                    CryptoPrimitives.generateCmac(keys.get(0), keyword), secondaryLookup, bigBlock, smallBlock,
                    dataSize);
            byte[] key3 = CryptoPrimitives.generateCmac(keys.get(1), 3 + keyword);
            numberPairs = numberPairs + secondaryLookup.size();
            dictionaryForMM.put(new String(key3), counter);

        }
        counter++;

    }

    long endTime = System.nanoTime();

    Printer.statsln("Time to construct LMM " + (endTime - startTime) / 1000000000);

    disj2.setDictionaryForMM(dictionaryForMM);
    return disj2;

}