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

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

Introduction

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

Prototype

boolean putAll(@Nullable K key, Iterable<? extends V> values);

Source Link

Document

Stores a key-value pair in this multimap for each of values , all using the same key, key .

Usage

From source file:io.datakernel.cube.CubeMetadataStorageSql.java

private void doSaveConsolidatedChunks(final String aggregationId, final AggregationMetadata aggregationMetadata,
        final List<AggregationChunk> originalChunks, final List<AggregationChunk.NewChunk> consolidatedChunks) {
    executeExclusiveTransaction(new TransactionalRunnable() {
        @Override/*  w w w  .  j  a  v  a2  s .  c  o m*/
        public void run(Configuration configuration) throws Exception {
            DSLContext jooq = DSL.using(configuration);

            final int revisionId = nextRevisionId(jooq);

            jooq.update(AGGREGATION_DB_CHUNK).set(AGGREGATION_DB_CHUNK.CONSOLIDATED_REVISION_ID, revisionId)
                    .set(AGGREGATION_DB_CHUNK.CONSOLIDATION_COMPLETED, currentTimestamp())
                    .where(AGGREGATION_DB_CHUNK.ID.in(newArrayList(
                            Iterables.transform(originalChunks, new Function<AggregationChunk, Long>() {
                                @Override
                                public Long apply(AggregationChunk chunk) {
                                    return chunk.getChunkId();
                                }
                            }))))
                    .execute();

            Map<AggregationMetadata, String> idMap = new HashMap<>();
            idMap.put(aggregationMetadata, aggregationId);
            Multimap<AggregationMetadata, AggregationChunk.NewChunk> chunks = HashMultimap.create();
            chunks.putAll(aggregationMetadata, consolidatedChunks);
            doSaveNewChunks(jooq, revisionId, idMap, chunks);
        }
    });
}

From source file:org.sonar.java.symexec.ExecutionState.java

private Multimap<SymbolicValue, SymbolicValue> findRelatedValues(Iterable<ExecutionState> states) {
    Multimap<SymbolicValue, SymbolicValue> result = HashMultimap.create();
    for (ExecutionState state : states) {
        for (ExecutionState current = state; !current.equals(this); current = current.parentState) {
            for (Map.Entry<SymbolicValue, Map<SymbolicValue, SymbolicRelation>> leftEntry : current.relations
                    .rowMap().entrySet()) {
                result.putAll(leftEntry.getKey(), leftEntry.getValue().keySet());
            }/*from  w  ww. java 2s . c o  m*/
        }
    }
    return result;
}

From source file:org.jboss.gwt.circuit.processor.StoreProcessor.java

private Collection<ProcessInfo> createProcessInfos(final TypeElement storeElement,
        final List<ExecutableElement> processMethods) {
    final List<ProcessInfo> processInfos = new ArrayList<>();
    final String storeDelegate = storeElement.getSimpleName().toString();
    for (ExecutableElement methodElement : processMethods) {

        String actionType = null;
        Collection<String> dependencies = Collections.emptyList();

        // parse @Process parameter
        Optional<AnnotationMirror> processAnnotation = MoreElements.getAnnotationMirror(methodElement,
                Process.class);
        if (processAnnotation.isPresent()) {
            Map<ExecutableElement, AnnotationValue> values = AnnotationMirrors
                    .getAnnotationValuesWithDefaults(processAnnotation.get());
            for (Map.Entry<ExecutableElement, AnnotationValue> entry : values.entrySet()) {
                if ("actionType".equals(entry.getKey().getSimpleName().toString())) {
                    actionType = (String) ((Set) GenerationUtil.extractValue(entry.getValue())).iterator()
                            .next();/*from w w  w .j ava 2 s .co m*/
                } else if ("dependencies".equals(entry.getKey().getSimpleName().toString())) {
                    dependencies = GenerationUtil.extractValue(entry.getValue());
                }
            }
        }
        assert actionType != null;
        ProcessInfo processInfo = new ProcessInfo(actionType, methodElement);
        processInfos.add(processInfo);

        // collect dependencies
        for (String store : dependencies) {
            // IMPORTANT: The actual dependency is the store adaptee!
            processInfo.addDependency(store + ".class");
        }

        // analyze the process signature
        List<? extends VariableElement> parameters = methodElement.getParameters();
        if (parameters.size() == 2) {
            // first parameter is the action, the second parameter the dispatcher channel
            verifyProcessParameter(storeElement, methodElement, parameters.get(0), actionType);
            verifyProcessParameter(storeElement, methodElement, parameters.get(1),
                    Dispatcher.Channel.class.getCanonicalName());
        } else if (parameters.size() == 1) {
            // if a single param is used it has to be the dispatcher channel
            verifyProcessParameter(storeElement, methodElement, parameters.get(0),
                    Dispatcher.Channel.class.getCanonicalName());
        } else {
            // anything else is considered as an error
            throw new GenerationException(methodElement,
                    String.format("Illegal number of arguments on method '%s' in class '%s'",
                            methodElement.getSimpleName(), storeElement.getSimpleName()));
        }

        // record dependencies in a different data structures to generate GraphViz...
        GraphVizInfo graphVizInfo = graphVizInfos.get(actionType);
        if (graphVizInfo == null) {
            String shortActionType = actionType.substring(actionType.lastIndexOf('.') + 1);
            graphVizInfo = new GraphVizInfo(shortActionType);
            graphVizInfos.put(actionType, graphVizInfo);
        }
        graphVizInfo.addStore(storeDelegate);
        List<String> simpleDependencies = new LinkedList<>();
        for (String dependency : dependencies) {
            String simpleDependency = dependency.substring(dependency.lastIndexOf('.') + 1);
            simpleDependencies.add(simpleDependency);
            graphVizInfo.addStore(simpleDependency);
            graphVizInfo.addDependency(storeDelegate, simpleDependency);
        }

        // ...and verify DAG
        Multimap<String, String> dag = dagValidation.get(actionType);
        if (dag == null) {
            dag = HashMultimap.create();
            dagValidation.put(actionType, dag);
        }
        dag.putAll(storeDelegate, simpleDependencies);
    }
    return processInfos;
}

From source file:com.marvinformatics.sonarpullrequestintegration.mojo.SonarPullRequestMojo.java

private void recordGit(Multimap<String, Issue> fileViolations) throws IOException {
    GitHubClient client = new GitHubClient().setOAuth2Token(oauth2);

    RepositoryService rs = new RepositoryService(client);
    Repository repository = rs.getRepository(repositoryOwner, repositoryName);

    PullRequestService pullRequestService = new PullRequestService(client);

    Iterator<RepositoryCommit> commits = pullRequestService.getCommits(repository, pullRequestId).iterator();
    if (!commits.hasNext())
        return;//from w  ww  . j  av a2  s.c om

    RepositoryCommit lastCommit = commits.next();

    List<CommitFile> files = pullRequestService.getFiles(repository, pullRequestId);

    Multimap<String, Issue> relatedFileViolations = LinkedHashMultimap.create();

    Map<String, LinePositioner> linePositioners = Maps.newLinkedHashMap();
    for (CommitFile commitFile : files) {
        Set<String> keys = fileViolations.keySet();
        for (String key : keys) {
            if (commitFile.getFilename().contains(key)) {
                relatedFileViolations.putAll(commitFile.getFilename(), fileViolations.get(key));
                linePositioners.put(commitFile.getFilename(), new LinePositioner(commitFile.getPatch()));
            }
        }
    }

    List<CommitComment> currentComments = pullRequestService.getComments(repository, pullRequestId);
    for (CommitComment comment : currentComments) {
        Iterator<Issue> issues = relatedFileViolations.get(comment.getPath()).iterator();
        while (issues.hasNext()) {
            Issue issue = (Issue) issues.next();
            int position = linePositioners.get(comment.getPath()).toPostion(issue.line());
            if (position == comment.getPosition() && issue.message().equals(comment.getBody()))
                issues.remove();
        }
    }

    Collection<Entry<String, Issue>> entries = relatedFileViolations.entries();
    for (Entry<String, Issue> entry : entries) {
        CommitComment comment = new CommitComment();
        comment.setBody(entry.getValue().message());
        comment.setCommitId(lastCommit.getSha());
        comment.setPath(entry.getKey());

        int line = entry.getValue().line();
        comment.setLine(line);
        comment.setPosition(linePositioners.get(entry.getKey()).toPostion(line));

        pullRequestService.createComment(repository, pullRequestId, comment);
    }
}

From source file:com.google.api.explorer.client.embedded.EmbeddedParameterForm.java

/** Return a {@link Map} of parameter keys to values as specified by the user. */
@Override//from w  ww .  j a  v  a  2s.  c  om
public Multimap<String, String> getParameterValues() {
    Multimap<String, String> values = ArrayListMultimap.create();
    for (Map.Entry<String, Editor> entry : nameToEditor.entrySet()) {
        Editor editor = entry.getValue();
        editor.displayValidation();
        values.putAll(entry.getKey(), editor.getValue());
    }

    String fields = this.fieldsTextBox.getText();
    if (!fields.isEmpty()) {
        values.put("fields", fields);
    }
    return values;
}

From source file:com.github.cbismuth.fdupes.io.BufferedAnalyzer.java

private void removeUniqueFiles(final Collection<ByteBuffer> buffers, final Set<PathElement> uniqueElements,
        final Multimap<PathElement, PathElement> duplicates) {
    if (!buffers.isEmpty() && buffers.size() != 1) {
        buffers.forEach(ByteBuffer::read);

        if (buffers.iterator().next().getByteString().isEmpty()) {
            final List<PathElement> collect = buffers.parallelStream().peek(ByteBuffer::close)
                    .map(ByteBuffer::getPathElement).sorted(pathComparator).collect(toList());

            final PathElement original = collect.remove(0);

            uniqueElements.add(original);
            duplicates.putAll(original, collect);
        } else {/*from  w  w w. j av a2 s  .  c o m*/
            final Collection<Collection<ByteBuffer>> values = buffers.parallelStream()
                    .collect(toMultimap(ByteBuffer::getByteString)).asMap().values();

            values.parallelStream().filter(collection -> collection.size() == 1).flatMap(Collection::stream)
                    .map(ByteBuffer::getPathElement).forEach(uniqueElements::add);

            values.parallelStream().filter(collection -> collection.size() > 1)
                    .forEach(collection -> removeUniqueFiles(collection, uniqueElements, duplicates));
        }
    }
}

From source file:io.datakernel.cube.CubeMetadataStorageSql.java

@Override
public AggregationMetadataStorage aggregationMetadataStorage(final String aggregationId,
        final AggregationMetadata aggregationMetadata, final AggregationStructure aggregationStructure) {
    return new AggregationMetadataStorage() {
        @Override//from   ww  w .j a  v  a  2 s .co m
        public void createChunkId(ResultCallback<Long> callback) {
            eventloop.callConcurrently(executor, new Callable<Long>() {
                @Override
                public Long call() throws Exception {
                    return doCreateChunkId();
                }
            }, callback);
        }

        @Override
        public void saveChunks(final List<AggregationChunk.NewChunk> newChunks, CompletionCallback callback) {
            eventloop.runConcurrently(executor, new Runnable() {
                @Override
                public void run() {
                    Map<AggregationMetadata, String> idMap = new HashMap<>();
                    idMap.put(aggregationMetadata, aggregationId);
                    Multimap<AggregationMetadata, AggregationChunk.NewChunk> chunks = HashMultimap.create();
                    chunks.putAll(aggregationMetadata, newChunks);
                    doSaveNewChunks(DSL.using(jooqConfiguration), idMap, chunks);
                }
            }, callback);
        }

        @Override
        public void startConsolidation(final List<AggregationChunk> chunksToConsolidate,
                CompletionCallback callback) {
            eventloop.runConcurrently(executor, new Runnable() {
                @Override
                public void run() {
                    doStartConsolidation(DSL.using(jooqConfiguration), chunksToConsolidate);
                }
            }, callback);
        }

        @Override
        public void loadChunks(final int lastRevisionId, final ResultCallback<LoadedChunks> callback) {
            eventloop.callConcurrently(executor, new Callable<LoadedChunks>() {
                @Override
                public LoadedChunks call() {
                    return doLoadChunks(DSL.using(jooqConfiguration), aggregationId, aggregationMetadata,
                            aggregationStructure, lastRevisionId);
                }
            }, callback);
        }

        @Override
        public void saveConsolidatedChunks(final List<AggregationChunk> originalChunks,
                final List<AggregationChunk.NewChunk> consolidatedChunks, CompletionCallback callback) {
            eventloop.runConcurrently(executor, new Runnable() {
                @Override
                public void run() {
                    doSaveConsolidatedChunks(aggregationId, aggregationMetadata, originalChunks,
                            consolidatedChunks);
                }
            }, callback);
        }
    };
}

From source file:uk.ac.ebi.apps.benchmark.ChemicalNameSearch.java

@Override
public void process() {

    loadNames();/* w ww.  j  a  v  a  2  s  .c om*/

    if (getCommandLine().getOptionValues("s").length > 1) {
        testMultiple();
        return;
    }

    final NameService<Identifier> service = (NameService<Identifier>) getNameService(get("service", "none"));
    if (!service.startup()) {
        LOGGER.error("Unable to start service");
    }
    service.setMaxResults(100);

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

    // doing the search
    long searchStart = System.currentTimeMillis();
    for (String name : names) {
        Collection<? extends Identifier> hits = service.searchName(name, has("a"));
        results.putAll(name, hits);
        found += hits.isEmpty() ? 0 : 1;
    }
    long searchEnd = System.currentTimeMillis();

    Long searchTime = (searchEnd - searchStart);

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

    // resolving

    System.out.println("Transforming for performance test");

    long resolveStart = System.currentTimeMillis();
    for (Map.Entry<String, Identifier> e : results.entries()) {
        Identifier id = e.getValue();
        nameResults.put(e.getKey(), new HashSet<String>(service.getNames(id)));
    }
    long resolveEnd = System.currentTimeMillis();

    Long resolveTime = (resolveEnd - resolveStart);

    int trueFound = getRealScore(nameResults, new ChemicalFingerprintEncoder(), null);

    SummaryStatistics statistics = getHitIndices(nameResults, new ChemicalFingerprintEncoder());

    String[] row = new String[] { get("service", "unknown"), searchTime.toString(), resolveTime.toString(),
            Integer.toString(found), Integer.toString(trueFound), Double.toString(statistics.getMax()),
            Double.toString(statistics.getMean()), Double.toString(statistics.getStandardDeviation()) };

    System.out.println(Joiner.on("\t").join(row));

}

From source file:cc.kave.commons.pointsto.analysis.inclusion.graph.ConstraintGraph.java

public Multimap<DistinctReference, ConstraintEdge> computeLeastSolution() {
    leastSolution.clear();/* w ww. j  av a 2s. co  m*/
    for (SetVariable var : getSetVariables()) {
        computeLeastSolution(var, new HashSet<>());
    }

    Multimap<DistinctReference, ConstraintEdge> distRefLS = HashMultimap.create();
    for (SetVariable var : leastSolution.keySet()) {
        DistinctReference distRef = referenceVariables.inverse().get(var);
        // temporary variables do not have a distinct reference
        if (distRef != null) {
            distRefLS.putAll(distRef, leastSolution.get(var));
        }
    }
    return distRefLS;
}

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

public void insertEdges(final Multimap<String, String> edges, final String type) throws IOException {
    if (edges.isEmpty()) {
        return;//from w  w  w  .j  a va  2 s .  c o  m
    }

    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);
        }

        insertEdgesPartition(edgePartition, type);
    }
}