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:com.b2international.snowowl.snomed.importer.rf2.validation.SnomedTaxonomyValidator.java

private Multimap<String, InvalidRelationship> processTaxonomy() throws IOException {
    final Rf2BasedSnomedTaxonomyBuilder builder = Rf2BasedSnomedTaxonomyBuilder
            .newInstance(new SnomedTaxonomyBuilder(conceptIds, statements), characteristicType);
    final Multimap<String, InvalidRelationship> invalidRelationships = ArrayListMultimap.create();
    if (snapshot) {

        LOGGER.info("Validating SNOMED CT ontology based on the given RF2 release files...");

        if (hasConceptImport()) {
            final String conceptFilePath = removeConceptHeader();
            builder.applyNodeChanges(conceptFilePath);
        }/*from   w w w.j  av  a2s  .  c o m*/

        if (hasRelationshipImport()) {
            final String relationshipFilePath = removeRelationshipHeader();
            builder.applyEdgeChanges(relationshipFilePath);
        }

        final SnomedTaxonomyStatus result = builder.build();
        if (!result.getStatus().isOK()) {
            invalidRelationships.putAll("", result.getInvalidRelationships());
        }

    } else {

        LOGGER.info("Validating SNOMED CT ontology based on the given RF2 release files...");

        final Map<String, File> conceptFiles = hasConceptImport() ? Rf2FileModifier.split(conceptsFile)
                : ImmutableMap.<String, File>of();
        final Map<String, File> relationshipFiles = hasRelationshipImport()
                ? Rf2FileModifier.split(relationshipsFile)
                : ImmutableMap.<String, File>of();

        final List<String> effectiveTimes = ImmutableSortedSet.orderedBy(EFFECTIVE_TIME_COMPARATOR)
                .addAll(conceptFiles.keySet()).addAll(relationshipFiles.keySet()).build().asList();

        for (final String effectiveTime : effectiveTimes) {
            LOGGER.info("Validating taxonomy in '{}'...", effectiveTime);

            final File conceptFile = conceptFiles.get(effectiveTime);
            final File relationshipFile = relationshipFiles.get(effectiveTime);

            builder.applyNodeChanges(getFilePath(conceptFile));
            builder.applyEdgeChanges(getFilePath(relationshipFile));
            final SnomedTaxonomyStatus result = builder.build();
            if (!result.getStatus().isOK()) {
                invalidRelationships.putAll(effectiveTime, result.getInvalidRelationships());
            }
        }

    }

    return invalidRelationships;
}

From source file:org.onosproject.p4runtime.ctl.P4RuntimeClientImpl.java

private Collection<PiActionGroup> doDumpGroups(PiActionProfileId piActionProfileId, PiPipeconf pipeconf) {
    log.debug("Dumping groups from action profile {} from {} (pipeconf {})...", piActionProfileId.id(),
            deviceId, pipeconf.id());/* ww w  . jav  a2  s. c  o  m*/

    final P4InfoBrowser browser = PipeconfHelper.getP4InfoBrowser(pipeconf);
    if (browser == null) {
        log.warn("Unable to get a P4Info browser for pipeconf {}, aborting dump action profile", pipeconf);
        return Collections.emptySet();
    }

    final int actionProfileId;
    try {
        actionProfileId = browser.actionProfiles().getByName(piActionProfileId.id()).getPreamble().getId();
    } catch (P4InfoBrowser.NotFoundException e) {
        log.warn("Unable to dump groups: {}", e.getMessage());
        return Collections.emptySet();
    }

    // Prepare read request to read all groups from the given action profile.
    final ReadRequest groupRequestMsg = ReadRequest.newBuilder().setDeviceId(p4DeviceId)
            .addEntities(Entity.newBuilder()
                    .setActionProfileGroup(
                            ActionProfileGroup.newBuilder().setActionProfileId(actionProfileId).build())
                    .build())
            .build();

    // Read groups.
    final Iterator<ReadResponse> groupResponses;
    try {
        groupResponses = blockingStub.read(groupRequestMsg);
    } catch (StatusRuntimeException e) {
        log.warn("Unable to dump action profile {} from {}: {}", piActionProfileId, deviceId, e.getMessage());
        return Collections.emptySet();
    }

    final List<ActionProfileGroup> groupMsgs = Tools.stream(() -> groupResponses)
            .map(ReadResponse::getEntitiesList).flatMap(List::stream)
            .filter(entity -> entity.getEntityCase() == ACTION_PROFILE_GROUP).map(Entity::getActionProfileGroup)
            .collect(Collectors.toList());

    log.debug("Retrieved {} groups from action profile {} on {}...", groupMsgs.size(), piActionProfileId.id(),
            deviceId);

    // Returned groups contain only a minimal description of their members.
    // We need to issue a new request to get the full description of each member.

    // Keep a map of all member IDs for each group ID, will need it later.
    final Multimap<Integer, Integer> groupIdToMemberIdsMap = HashMultimap.create();
    groupMsgs.forEach(g -> groupIdToMemberIdsMap.putAll(g.getGroupId(), g.getMembersList().stream()
            .map(ActionProfileGroup.Member::getMemberId).collect(Collectors.toList())));

    // Prepare one big read request to read all members in one shot.
    final Set<Entity> entityMsgs = groupMsgs.stream().flatMap(g -> g.getMembersList().stream())
            .map(ActionProfileGroup.Member::getMemberId)
            // Prevent issuing many read requests for the same member.
            .distinct()
            .map(id -> ActionProfileMember.newBuilder().setActionProfileId(actionProfileId).setMemberId(id)
                    .build())
            .map(m -> Entity.newBuilder().setActionProfileMember(m).build()).collect(Collectors.toSet());
    final ReadRequest memberRequestMsg = ReadRequest.newBuilder().setDeviceId(p4DeviceId)
            .addAllEntities(entityMsgs).build();

    // Read members.
    final Iterator<ReadResponse> memberResponses;
    try {
        memberResponses = blockingStub.read(memberRequestMsg);
    } catch (StatusRuntimeException e) {
        log.warn("Unable to read members of action profile {} from {}: {}", piActionProfileId, deviceId,
                e.getMessage());
        return Collections.emptyList();
    }

    final Multimap<Integer, ActionProfileMember> groupIdToMembersMap = HashMultimap.create();
    Tools.stream(() -> memberResponses).map(ReadResponse::getEntitiesList).flatMap(List::stream)
            .filter(e -> e.getEntityCase() == ACTION_PROFILE_MEMBER).map(Entity::getActionProfileMember)
            .forEach(member -> groupIdToMemberIdsMap.asMap()
                    // Get all group IDs that contain this member.
                    .entrySet().stream().filter(entry -> entry.getValue().contains(member.getMemberId()))
                    .map(Map.Entry::getKey).forEach(gid -> groupIdToMembersMap.put(gid, member)));

    log.debug("Retrieved {} group members from action profile {} on {}...", groupIdToMembersMap.size(),
            piActionProfileId.id(), deviceId);

    return groupMsgs.stream().map(groupMsg -> {
        try {
            return ActionProfileGroupEncoder.decode(groupMsg, groupIdToMembersMap.get(groupMsg.getGroupId()),
                    pipeconf);
        } catch (P4InfoBrowser.NotFoundException | EncodeException e) {
            log.warn("Unable to decode group: {}\n {}", e.getMessage(), groupMsg);
            return null;
        }
    }).filter(Objects::nonNull).collect(Collectors.toList());
}

From source file:com.palantir.atlasdb.transaction.impl.SerializableTransaction.java

private void verifyRows(Transaction ro) {
    for (String table : rowsRead.keySet()) {
        final ConcurrentNavigableMap<Cell, byte[]> readsForTable = getReadsForTable(table);
        Multimap<ColumnSelection, byte[]> map = Multimaps.newSortedSetMultimap(
                Maps.<ColumnSelection, Collection<byte[]>>newHashMap(), new Supplier<SortedSet<byte[]>>() {
                    @Override//from w w w  .j a va2 s  .c om
                    public TreeSet<byte[]> get() {
                        return Sets.newTreeSet(UnsignedBytes.lexicographicalComparator());
                    }
                });
        for (RowRead r : rowsRead.get(table)) {
            map.putAll(r.cols, r.rows);
        }
        for (final ColumnSelection cols : map.keySet()) {
            for (List<byte[]> batch : Iterables.partition(map.get(cols), 1000)) {
                SortedMap<byte[], RowResult<byte[]>> currentRows = ro.getRows(table, batch, cols);
                for (byte[] row : batch) {
                    RowResult<byte[]> currentRow = currentRows.get(row);
                    Map<Cell, byte[]> orignalReads = readsForTable
                            .tailMap(Cells.createSmallestCellForRow(row), true)
                            .headMap(Cells.createLargestCellForRow(row), true);

                    // We want to filter out all our reads to just the set that matches our column selection.
                    orignalReads = Maps.filterKeys(orignalReads, new Predicate<Cell>() {
                        @Override
                        public boolean apply(Cell input) {
                            return cols.contains(input.getColumnName());
                        }
                    });

                    if (writesByTable.get(table) != null) {
                        // We don't want to verify any reads that we wrote to cause we will just read our own values.
                        // NB: We filter our write set out here because our normal SI checking handles this case to ensure the value hasn't changed.
                        orignalReads = Maps.filterKeys(orignalReads,
                                Predicates.not(Predicates.in(writesByTable.get(table).keySet())));
                    }

                    if (currentRow == null && orignalReads.isEmpty()) {
                        continue;
                    }

                    if (currentRow == null) {
                        throw TransactionSerializableConflictException.create(table, getTimestamp(),
                                System.currentTimeMillis() - timeCreated);
                    }

                    Map<Cell, byte[]> currentCells = Maps2.fromEntries(currentRow.getCells());
                    if (writesByTable.get(table) != null) {
                        // We don't want to verify any reads that we wrote to cause we will just read our own values.
                        // NB: We filter our write set out here because our normal SI checking handles this case to ensure the value hasn't changed.
                        currentCells = Maps.filterKeys(currentCells,
                                Predicates.not(Predicates.in(writesByTable.get(table).keySet())));
                    }
                    if (!areMapsEqual(orignalReads, currentCells)) {
                        throw TransactionSerializableConflictException.create(table, getTimestamp(),
                                System.currentTimeMillis() - timeCreated);
                    }
                }
            }
        }

    }
}

From source file:org.eclipse.tracecompass.internal.lttng2.kernel.core.analysis.vm.module.VirtualMachineCpuAnalysis.java

/**
 * Get the status intervals for the threads from a virtual machine. Those
 * intervals are correlated with the data from the virtual CPU's preemption
 * status.//  ww w .j  ava  2  s .  c o  m
 *
 * This method uses the Linux Kernel Analysis data for the thread's status
 * intervals.
 *
 * @param vmQuark
 *            The quark of the virtual machine
 * @param start
 *            The start time of the period to get the intervals from
 * @param end
 *            The end time of the period to get the intervals from
 * @param resolution
 *            The resolution
 * @param monitor
 *            A progress monitor for this task
 * @return A map of status intervals for the machine's threads, including
 *         preempted intervals. Intervals from the thread status and the CPU
 *         preemption status overlap and are ordered such that CPU
 *         preemption intervals are after any interval they overlap with
 */
public Multimap<Integer, ITmfStateInterval> getUpdatedThreadIntervals(int vmQuark, long start, long end,
        long resolution, IProgressMonitor monitor) {

    final Multimap<Integer, ITmfStateInterval> map = createThreadMultimap();

    ITmfStateSystem ss = getStateSystem();
    if (ss == null) {
        return map;
    }
    ITmfTrace trace = getTrace();
    if (!(trace instanceof TmfExperiment)) {
        return map;
    }

    String vmHostId = ss.getAttributeName(vmQuark);
    KernelAnalysisModule kernelModule = TmfExperimentUtils
            .getAnalysisModuleOfClassForHost((TmfExperiment) trace, vmHostId, KernelAnalysisModule.class);
    if (kernelModule == null) {
        return map;
    }

    /*
     * Initialize the map with the original status intervals from the kernel
     * module
     */
    for (Integer tid : KernelThreadInformationProvider.getThreadIds(kernelModule)) {
        map.putAll(tid, KernelThreadInformationProvider.getStatusIntervalsForThread(kernelModule, tid, start,
                end, resolution, monitor));
        if (monitor.isCanceled()) {
            return map;
        }
    }

    try {
        /* Correlate thread information with virtual CPU information */
        for (Integer vcpuQuark : ss.getSubAttributes(vmQuark, false)) {
            Long virtualCPU = Long.parseLong(ss.getAttributeName(vcpuQuark));
            Integer statusQuark = ss.getQuarkRelative(vcpuQuark, VmAttributes.STATUS);

            for (ITmfStateInterval cpuInterval : StateSystemUtils.queryHistoryRange(ss, statusQuark, start,
                    end - 1, resolution, monitor)) {
                ITmfStateValue stateValue = cpuInterval.getStateValue();
                if (stateValue.getType() == Type.INTEGER) {
                    int value = stateValue.unboxInt();
                    /*
                     * If the current CPU is either preempted or in
                     * hypervisor mode, add preempted intervals to running
                     * processes
                     */
                    if ((value & (VcpuStateValues.VCPU_PREEMPT | VcpuStateValues.VCPU_VMM)) == 0) {
                        continue;
                    }
                    Integer threadOnCpu = KernelThreadInformationProvider.getThreadOnCpu(kernelModule,
                            virtualCPU, cpuInterval.getStartTime());
                    if (threadOnCpu != null) {
                        map.put(threadOnCpu, new TmfStateInterval(cpuInterval.getStartTime(),
                                cpuInterval.getEndTime(), threadOnCpu, VCPU_PREEMPT_VALUE));
                    }
                }
            }
        }
    } catch (AttributeNotFoundException | StateSystemDisposedException e) {
    }
    return map;
}

From source file:eu.stratosphere.sopremo.operator.IterativeSopremoModule.java

private Multimap<Operator<?>, Operator<?>> getSuccessorRelations(final Set<Operator<?>> stepOutputs) {
    final Multimap<Operator<?>, Operator<?>> successors = Multimaps.newMultimap(
            new IdentityHashMap<Operator<?>, Collection<Operator<?>>>(),
            IdentitySetSupplier.<Operator<?>>getInstance());
    OneTimeTraverser.INSTANCE.traverse(stepOutputs, OperatorNavigator.INSTANCE,
            new GraphTraverseListener<Operator<?>>() {
                @Override//from  w  w w .  j a  v a 2s. c  o m
                public void nodeTraversed(final Operator<?> node) {
                    for (final JsonStream input : node.getInputs()) {
                        successors.put(input.getSource().getOperator(), node);
                        successors.putAll(input.getSource().getOperator(), successors.get(node));
                    }
                }
            });
    return successors;
}

From source file:com.pidoco.juri.JURI.java

public JURI addQueryParameters(String name, Collection<String> unencodedValues) {
    startChange();//from  w w w  .  j a  va2 s. c  o m

    Multimap<String, String> params = getQueryParametersMultimap();
    params.putAll(name, unencodedValues);

    changed();
    return this;
}

From source file:org.apache.james.jmap.methods.GetMessageListMethod.java

private void aggregate(MailboxSession mailboxSession, Multimap<MailboxPath, MessageResult> aggregation,
        Map.Entry<MailboxId, Collection<Long>> mailboxResults)
        throws MailboxNotFoundException, MailboxException {
    MailboxPath mailboxPath = mailboxManager.getMailbox(mailboxResults.getKey(), mailboxSession)
            .getMailboxPath();//from  w ww . j  a  v  a  2s  . c  om
    MessageManager messageManager = getMessageManager(mailboxPath, mailboxSession)
            .orElseThrow(() -> new MailboxNotFoundException(mailboxPath));
    List<MessageResult> mailboxMessages = MessageRange.toRanges(mailboxResults.getValue()).stream()
            .map(Throwing.function(
                    range -> messageManager.getMessages(range, FetchGroupImpl.MINIMAL, mailboxSession)))
            .map(messageIterator -> ImmutableList.copyOf(messageIterator)).flatMap(List::stream)
            .collect(Guavate.toImmutableList());
    aggregation.putAll(mailboxPath, mailboxMessages);
}

From source file:com.sam.moca.servlet.support.SupportZip.java

/**
 * @param writer//from   w  w w. j a  v  a  2s .co m
 * @throws IOException
 * 
 */
private void generateClusterRolesEntry(ZipOutputStream zip, CsvWriter csvWriter, BufferedWriter writer)
        throws IOException {
    ClusterRoleManager manager = (ClusterRoleManager) _system.getAttribute(ClusterRoleManager.class.getName());

    if (manager != null) {
        zip.putNextEntry(new ZipEntry("cluster-roles.csv"));
        Multimap<Node, RoleDefinition> multiMap = manager.getClusterRoles();
        MocaClusterAdministration clusterAdmin = (MocaClusterAdministration) _system
                .getAttribute(MocaClusterAdministration.class.getName());
        Map<Node, InstanceUrl> urls = clusterAdmin.getKnownNodes();

        Multimap<InstanceUrl, RoleDefinition> urlRoleMap = HashMultimap.create();

        for (Entry<Node, Collection<RoleDefinition>> entry : multiMap.asMap().entrySet()) {
            urlRoleMap.putAll(urls.get(entry.getKey()), entry.getValue());
        }

        Map<InstanceUrl, List<RoleDefinition>> copy = new HashMap<InstanceUrl, List<RoleDefinition>>();
        for (Entry<InstanceUrl, Collection<RoleDefinition>> entry : urlRoleMap.asMap().entrySet()) {
            copy.put(entry.getKey(), new ArrayList<RoleDefinition>(entry.getValue()));
        }

        csvWriter.writeValue("url");
        csvWriter.writeValue("roles");
        csvWriter.writeEndLine();

        for (Entry<InstanceUrl, List<RoleDefinition>> entry : copy.entrySet()) {
            csvWriter.writeValue(entry.getKey());
            csvWriter.writeValue(entry.getValue());
            csvWriter.writeEndLine();
        }

        // Have to flush before closing the entry
        writer.flush();
        zip.closeEntry();
    }
}

From source file:com.pidoco.juri.JURI.java

public JURI replaceQueryParameters(String name, Collection<String> unencodedValues) {
    startChange();// ww  w  . j  a  va2 s.  c  o m

    Multimap<String, String> params = getQueryParametersMultimap();
    params.removeAll(name);
    params.putAll(name, unencodedValues);

    changed();
    return this;
}

From source file:com.pidoco.juri.JURI.java

public JURI addQueryParametersMulti(Map<String, Collection<String>> params) {
    startChange();//w  ww.  j av a  2s  . c  o m

    Multimap<String, String> queryParameters = getQueryParametersMultimap();
    for (Map.Entry<String, Collection<String>> entry : params.entrySet()) {
        queryParameters.putAll(entry.getKey(), entry.getValue());
    }

    changed();
    return this;
}