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.google.devtools.build.lib.skyframe.SkylarkImportLookupFunction.java

/**
 * Computes the set of Labels corresponding to a collection of PathFragments representing absolute
 * import paths./*  ww w .  j  av a 2s.c o  m*/
 *
 * @return a map from the computed {@link Label}s to the corresponding {@link PathFragment}s;
 *     {@code null} if any Skyframe dependencies are unavailable.
 * @throws SkylarkImportFailedException
 */
@Nullable
static ImmutableMap<PathFragment, Label> labelsForAbsoluteImports(ImmutableSet<PathFragment> pathsToLookup,
        Environment env) throws SkylarkImportFailedException, InterruptedException {

    // Import PathFragments are absolute, so there is a 1-1 mapping from corresponding Labels.
    ImmutableMap.Builder<PathFragment, Label> outputMap = new ImmutableMap.Builder<>();

    // The SkyKey here represents the directory containing an import PathFragment, hence there
    // can in general be multiple imports per lookup.
    Multimap<SkyKey, PathFragment> lookupMap = LinkedHashMultimap.create();
    for (PathFragment importPath : pathsToLookup) {
        PathFragment relativeImportPath = importPath.toRelative();
        PackageIdentifier pkgToLookUp = PackageIdentifier
                .createInMainRepo(relativeImportPath.getParentDirectory());
        lookupMap.put(ContainingPackageLookupValue.key(pkgToLookUp), importPath);
    }

    // Attempt to find a package for every directory containing an import.
    Map<SkyKey, ValueOrException2<BuildFileNotFoundException, InconsistentFilesystemException>> lookupResults = env
            .getValuesOrThrow(lookupMap.keySet(), BuildFileNotFoundException.class,
                    InconsistentFilesystemException.class);
    if (env.valuesMissing()) {
        return null;
    }
    try {
        // Process lookup results.
        for (Entry<SkyKey, ValueOrException2<BuildFileNotFoundException, InconsistentFilesystemException>> entry : lookupResults
                .entrySet()) {
            ContainingPackageLookupValue lookupValue = (ContainingPackageLookupValue) entry.getValue().get();
            if (!lookupValue.hasContainingPackage()) {
                // Although multiple imports may be in the same package-less directory, we only
                // report an error for the first one.
                PackageIdentifier lookupKey = ((PackageIdentifier) entry.getKey().argument());
                PathFragment importFile = lookupKey.getPackageFragment();
                throw SkylarkImportFailedException.noBuildFile(importFile);
            }
            PackageIdentifier pkgIdForImport = lookupValue.getContainingPackageName();
            PathFragment containingPkgPath = pkgIdForImport.getPackageFragment();
            for (PathFragment importPath : lookupMap.get(entry.getKey())) {
                PathFragment relativeImportPath = importPath.toRelative();
                String targetNameForImport = relativeImportPath.relativeTo(containingPkgPath).toString();
                try {
                    outputMap.put(importPath, Label.create(pkgIdForImport, targetNameForImport));
                } catch (LabelSyntaxException e) {
                    // While the Label is for the most part guaranteed to be well-formed by construction, an
                    // error is still possible if the filename itself is malformed, e.g., contains control
                    // characters. Since we expect this error to be very rare, for code simplicity, we allow
                    // the error message to refer to a Label even though the filename was specified via a
                    // simple path.
                    throw new SkylarkImportFailedException(e);
                }
            }
        }
    } catch (BuildFileNotFoundException e) {
        // Thrown when there are IO errors looking for BUILD files.
        throw new SkylarkImportFailedException(e);
    } catch (InconsistentFilesystemException e) {
        throw new SkylarkImportFailedException(e);
    }

    return outputMap.build();
}

From source file:org.ow2.proactive.inmemory_keyvalue_store.controller.KeyValueStoreRestController.java

@RequestMapping(value = "/channels", method = RequestMethod.GET)
public Map<String, Collection<String>> listChannels() {
    ImmutableMap.Builder<String, Collection<String>> builder = ImmutableMap.builder();

    Multimap<String, String> channels = keyValueStoreService.getChannels();

    channels.keySet().forEach(k -> {
        builder.put(k, channels.get(k));
    });/*from w  ww.  ja va2 s.c  om*/

    return builder.build();
}

From source file:net.minecraftforge.common.ForgeChunkManager.java

static void saveWorld(World world) {
    // only persist persistent worlds
    if (!(world instanceof WorldServer)) {
        return;//from  w w  w  .  j a  v  a  2s  .  co  m
    }
    WorldServer worldServer = (WorldServer) world;
    File chunkDir = worldServer.getChunkSaveLocation();
    File chunkLoaderData = new File(chunkDir, "forcedchunks.dat");

    NBTTagCompound forcedChunkData = new NBTTagCompound();
    NBTTagList ticketList = new NBTTagList();
    forcedChunkData.setTag("TicketList", ticketList);

    Multimap<String, Ticket> ticketSet = tickets.get(worldServer);
    if (ticketSet == null)
        return;
    for (String modId : ticketSet.keySet()) {
        NBTTagCompound ticketHolder = new NBTTagCompound();
        ticketList.appendTag(ticketHolder);

        ticketHolder.setString("Owner", modId);
        NBTTagList tickets = new NBTTagList();
        ticketHolder.setTag("Tickets", tickets);

        for (Ticket tick : ticketSet.get(modId)) {
            NBTTagCompound ticket = new NBTTagCompound();
            ticket.setByte("Type", (byte) tick.ticketType.ordinal());
            ticket.setByte("ChunkListDepth", (byte) tick.maxDepth);
            if (tick.isPlayerTicket()) {
                ticket.setString("ModId", tick.modId);
                ticket.setString("Player", tick.player);
            }
            if (tick.modData != null) {
                ticket.setTag("ModData", tick.modData);
            }
            if (tick.ticketType == Type.ENTITY && tick.entity != null
                    && tick.entity.writeToNBTOptional(new NBTTagCompound())) {
                ticket.setInteger("chunkX", MathHelper.floor_double(tick.entity.chunkCoordX));
                ticket.setInteger("chunkZ", MathHelper.floor_double(tick.entity.chunkCoordZ));
                ticket.setLong("PersistentIDMSB", tick.entity.getPersistentID().getMostSignificantBits());
                ticket.setLong("PersistentIDLSB", tick.entity.getPersistentID().getLeastSignificantBits());
                tickets.appendTag(ticket);
            } else if (tick.ticketType != Type.ENTITY) {
                tickets.appendTag(ticket);
            }
        }
    }
    try {
        CompressedStreamTools.write(forcedChunkData, chunkLoaderData);
    } catch (IOException e) {
        FMLLog.log(Level.WARN, e, "Unable to write forced chunk data to %s - chunkloading won't work",
                chunkLoaderData.getAbsolutePath());
        return;
    }
}

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

public static RR2Lev constructEMMParGMM(final byte[] key, final Multimap<String, String> lookup,
        final int bigBlock, final int smallBlock, final int dataSize)
        throws InterruptedException, ExecutionException, IOException {

    final Multimap<String, byte[]> dictionary = ArrayListMultimap.create();

    random.setSeed(CryptoPrimitives.randomSeed(16));

    for (int i = 0; i < dataSize; i++) {
        // initialize all buckets with random values
        free.add(i);/*ww  w  . j a  v  a  2  s  . com*/
    }

    List<String> listOfKeyword = new ArrayList<String>(lookup.keySet());
    int threads = 0;
    if (Runtime.getRuntime().availableProcessors() > listOfKeyword.size()) {
        threads = listOfKeyword.size();
    } else {
        threads = Runtime.getRuntime().availableProcessors();
    }

    ExecutorService service = Executors.newFixedThreadPool(threads);
    ArrayList<String[]> inputs = new ArrayList<String[]>(threads);

    for (int i = 0; i < threads; i++) {
        String[] tmp;
        if (i == threads - 1) {
            tmp = new String[listOfKeyword.size() / threads + listOfKeyword.size() % threads];
            for (int j = 0; j < listOfKeyword.size() / threads + listOfKeyword.size() % threads; j++) {
                tmp[j] = listOfKeyword.get((listOfKeyword.size() / threads) * i + j);
            }
        } else {
            tmp = new String[listOfKeyword.size() / threads];
            for (int j = 0; j < listOfKeyword.size() / threads; j++) {

                tmp[j] = listOfKeyword.get((listOfKeyword.size() / threads) * i + j);
            }
        }
        inputs.add(i, tmp);
    }

    Printer.debugln("End of Partitionning  \n");

    List<Future<Multimap<String, byte[]>>> futures = new ArrayList<Future<Multimap<String, byte[]>>>();
    for (final String[] input : inputs) {
        Callable<Multimap<String, byte[]>> callable = new Callable<Multimap<String, byte[]>>() {
            public Multimap<String, byte[]> call() throws Exception {

                Multimap<String, byte[]> output = setup(key, input, lookup, bigBlock, smallBlock, dataSize);
                return output;
            }
        };
        futures.add(service.submit(callable));
    }

    service.shutdown();

    for (Future<Multimap<String, byte[]>> future : futures) {
        Set<String> keys = future.get().keySet();

        for (String k : keys) {
            dictionary.putAll(k, future.get().get(k));
        }

    }

    return new RR2Lev(dictionary, array);
}

From source file:com.griddynamics.jagger.engine.e1.sessioncomparation.WorstCaseDecisionMaker.java

@Override
public Decision makeDecision(Multimap<String, Verdict> verdicts) {
    Decision worstResult = Decision.OK;//  w  w w . ja  v  a 2s  . c  om
    for (String feature : verdicts.keySet()) {
        for (Verdict verdict : verdicts.get(feature)) {
            Decision decision = verdict.getDecision();
            if (decision.ordinal() > worstResult.ordinal()) {
                worstResult = decision;
            }
        }

    }

    return worstResult;
}

From source file:org.apache.tez.analyzer.plugins.ContainerReuseAnalyzer.java

@Override
public void analyze(DagInfo dagInfo) throws TezException {
    for (VertexInfo vertexInfo : dagInfo.getVertices()) {
        Multimap<Container, TaskAttemptInfo> containers = vertexInfo.getContainersMapping();
        for (Container container : containers.keySet()) {
            List<String> record = Lists.newLinkedList();
            record.add(vertexInfo.getVertexName());
            record.add(vertexInfo.getTaskAttempts().size() + "");
            record.add(container.getHost());
            record.add(container.getId());
            record.add(Integer.toString(containers.get(container).size()));
            csvResult.addRecord(record.toArray(new String[record.size()]));
        }/*from w ww  .  j a  v a2 s .c om*/
    }
}

From source file:org.thiesen.jiffs.jobs.clusterer.Clusterer.java

private void storeClusters(Multimap<Long, String> clusters) {
    System.out.println("Found " + clusters.keySet().size() + " clusters");

    for (final Entry<Long, Collection<String>> entry : clusters.asMap().entrySet()) {
        final StoryClusterDBO clusterDBO = new StoryClusterDBO();

        clusterDBO.setCreatedAt(new DateTime());
        clusterDBO.setStoryUris(Lists.newArrayList(entry.getValue()));

        _storyClusterDAO.insert(clusterDBO);

    }//from ww w . j  a va  2s. co  m

}

From source file:com.google.devtools.build.lib.query2.AbstractUnfilteredTTVDTCVisitor.java

@Override
protected Visit getVisitResult(Iterable<SkyKey> ttvKeys) throws InterruptedException {
    Multimap<SkyKey, SkyKey> deps = env.getUnfilteredDirectDepsOfSkyKeys(ttvKeys);
    return new Visit(/*keysToUseForResult=*/ deps.keySet(), /*keysToVisit=*/ deps.values().stream()
            .filter(SkyQueryEnvironment.IS_TTV).collect(ImmutableList.toImmutableList()));
}

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

public static RR2Lev constructEMMPar(final byte[] key, final Multimap<String, String> lookup,
        final int bigBlock, final int smallBlock, final int dataSize)
        throws InterruptedException, ExecutionException, IOException {

    final Multimap<String, byte[]> dictionary = ArrayListMultimap.create();

    random.setSeed(CryptoPrimitives.randomSeed(16));

    for (int i = 0; i < dataSize; i++) {
        // initialize all buckets with random values
        free.add(i);//from   www  .ja  va 2  s  . c  o m
    }

    List<String> listOfKeyword = new ArrayList<String>(lookup.keySet());
    int threads = 0;
    if (Runtime.getRuntime().availableProcessors() > listOfKeyword.size()) {
        threads = listOfKeyword.size();
    } else {
        threads = Runtime.getRuntime().availableProcessors();
    }

    ExecutorService service = Executors.newFixedThreadPool(threads);
    ArrayList<String[]> inputs = new ArrayList<String[]>(threads);

    final Map<Integer, String> concurrentMap = new ConcurrentHashMap<Integer, String>();
    for (int i = 0; i < listOfKeyword.size(); i++) {
        concurrentMap.put(i, listOfKeyword.get(i));
    }

    for (int j = 0; j < threads; j++) {
        service.execute(new Runnable() {
            @SuppressWarnings("unused")
            @Override
            public void run() {

                while (concurrentMap.keySet().size() > 0) {
                    // write code
                    Set<Integer> possibleValues = concurrentMap.keySet();

                    Random rand = new Random();

                    int temp = rand.nextInt(possibleValues.size());

                    List<Integer> listOfPossibleKeywords = new ArrayList<Integer>(possibleValues);

                    // set the input as randomly selected from the remaining
                    // possible keys
                    String[] input = { concurrentMap.get(listOfPossibleKeywords.get(temp)) };

                    // remove the key
                    concurrentMap.remove(listOfPossibleKeywords.get(temp));

                    try {

                        Multimap<String, byte[]> output = setup(key, input, lookup, bigBlock, smallBlock,
                                dataSize);
                        Set<String> keys = output.keySet();

                        for (String k : keys) {
                            dictionary.putAll(k, output.get(k));
                        }
                    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException
                            | NoSuchPaddingException | IOException | InvalidAlgorithmParameterException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    // Make sure executor stops
    service.shutdown();

    // Blocks until all tasks have completed execution after a shutdown
    // request
    service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

    return new RR2Lev(dictionary, array);
}

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

public static RH2Lev constructEMMParGMM(final byte[] key, final Multimap<String, String> lookup,
        final int bigBlock, final int smallBlock, final int dataSize)
        throws InterruptedException, ExecutionException, IOException {

    final Multimap<String, byte[]> dictionary = ArrayListMultimap.create();

    for (int i = 0; i < dataSize; i++) {
        // initialize all buckets with random values
        free.add(i);/*from  w  ww  .  ja  v a 2s. c o  m*/
    }
    random.setSeed(CryptoPrimitives.randomSeed(16));

    List<String> listOfKeyword = new ArrayList<String>(lookup.keySet());
    int threads = 0;
    if (Runtime.getRuntime().availableProcessors() > listOfKeyword.size()) {
        threads = listOfKeyword.size();
    } else {
        threads = Runtime.getRuntime().availableProcessors();
    }

    ExecutorService service = Executors.newFixedThreadPool(threads);
    ArrayList<String[]> inputs = new ArrayList<String[]>(threads);

    for (int i = 0; i < threads; i++) {
        String[] tmp;
        if (i == threads - 1) {
            tmp = new String[listOfKeyword.size() / threads + listOfKeyword.size() % threads];
            for (int j = 0; j < listOfKeyword.size() / threads + listOfKeyword.size() % threads; j++) {
                tmp[j] = listOfKeyword.get((listOfKeyword.size() / threads) * i + j);
            }
        } else {
            tmp = new String[listOfKeyword.size() / threads];
            for (int j = 0; j < listOfKeyword.size() / threads; j++) {

                tmp[j] = listOfKeyword.get((listOfKeyword.size() / threads) * i + j);
            }
        }
        inputs.add(i, tmp);
    }

    Printer.debugln("End of Partitionning  \n");

    List<Future<Multimap<String, byte[]>>> futures = new ArrayList<Future<Multimap<String, byte[]>>>();
    for (final String[] input : inputs) {
        Callable<Multimap<String, byte[]>> callable = new Callable<Multimap<String, byte[]>>() {
            public Multimap<String, byte[]> call() throws Exception {

                Multimap<String, byte[]> output = setup(key, input, lookup, bigBlock, smallBlock, dataSize);
                return output;
            }
        };
        futures.add(service.submit(callable));
    }

    service.shutdown();

    for (Future<Multimap<String, byte[]>> future : futures) {
        Set<String> keys = future.get().keySet();

        for (String k : keys) {
            dictionary.putAll(k, future.get().get(k));
        }

    }

    return new RH2Lev(dictionary, array);
}