Example usage for com.google.common.collect Multimaps forMap

List of usage examples for com.google.common.collect Multimaps forMap

Introduction

In this page you can find the example usage for com.google.common.collect Multimaps forMap.

Prototype

public static <K, V> SetMultimap<K, V> forMap(Map<K, V> map) 

Source Link

Document

Returns a multimap view of the specified map.

Usage

From source file:org.apache.aurora.scheduler.thrift.ReadOnlySchedulerImpl.java

private static Set<ConfigGroup> instancesToConfigGroups(Map<Integer, ITaskConfig> tasks) {
    Multimap<ITaskConfig, Integer> instancesByDetails = Multimaps.invertFrom(Multimaps.forMap(tasks),
            HashMultimap.create());//from   w  ww  . ja  v  a2s. co  m
    return ImmutableSet.copyOf(Iterables.transform(instancesByDetails.asMap().entrySet(), TO_GROUP));
}

From source file:com.textocat.textokit.io.brat.UIMA2BratAnnotator.java

private void createBratTypesConfiguration() throws AnalysisEngineProcessException {
    // type configuration builder
    final BratTypesConfiguration.Builder tcBuilder = BratTypesConfiguration.builder();
    /*//from   ww w. j  av a  2s. co m
     * define mapping initializer that will incrementally build
    * required Brat type system as side effect
    */
    UimaBratMappingInitializer initializer = new UimaBratMappingInitializer(ts, entitiesToBrat, relationsToBrat,
            eventsToBrat, noteMappersDefinitions) {

        @Override
        protected BratEntityType getEntityType(String typeName) {
            return tcBuilder.addEntityType(typeName);
        }

        @Override
        protected BratRelationType getRelationType(String typeName, Map<String, String> argTypeNames) {
            return tcBuilder.addRelationType(typeName, argTypeNames);
        }

        @Override
        protected BratEventType getEventType(String typeName, Map<String, String> roleTypeNames,
                Set<String> multiValuedRoles) {
            Map<String, Cardinality> roleCardinalities = Maps.newHashMap();
            for (String roleName : roleTypeNames.keySet()) {
                Cardinality card = multiValuedRoles.contains(roleName) ? Cardinality.ARRAY
                        : Cardinality.OPTIONAL;
                roleCardinalities.put(roleName, card);
            }
            return tcBuilder.addEventType(typeName, Multimaps.forMap(roleTypeNames), roleCardinalities);
        }
    };
    mapping = initializer.create();
    bratTypesConfig = tcBuilder.build();
}

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

@Override
public Map<Cell, Value> get(String tableName, Map<Cell, Long> timestampByCell) {
    try {//from  w w  w.  j a v a2 s.  c o  m
        long firstTs = timestampByCell.values().iterator().next();
        if (Iterables.all(timestampByCell.values(), Predicates.equalTo(firstTs))) {
            StartTsResultsCollector collector = new StartTsResultsCollector(firstTs);
            loadWithTs(tableName, timestampByCell.keySet(), firstTs, false, collector, readConsistency);
            return collector.collectedResults;
        }

        SetMultimap<Long, Cell> cellsByTs = HashMultimap.create();
        Multimaps.invertFrom(Multimaps.forMap(timestampByCell), cellsByTs);
        Builder<Cell, Value> builder = ImmutableMap.builder();
        for (long ts : cellsByTs.keySet()) {
            StartTsResultsCollector collector = new StartTsResultsCollector(ts);
            loadWithTs(tableName, cellsByTs.get(ts), ts, false, collector, readConsistency);
            builder.putAll(collector.collectedResults);
        }
        return builder.build();
    } catch (Throwable t) {
        throw Throwables.throwUncheckedException(t);
    }
}

From source file:com.palantir.atlasdb.cleaner.Scrubber.java

private long getCommitTimestampRollBackIfNecessary(long startTimestamp,
        Multimap<String, Cell> tableNameToCell) {
    Long commitTimestamp = transactionService.get(startTimestamp);
    if (commitTimestamp == null) {
        // Roll back this transaction (note that rolling back arbitrary transactions
        // can never cause correctness issues, only liveness issues)
        try {//from   www .j a va2 s  .c  om
            transactionService.putUnlessExists(startTimestamp, TransactionConstants.FAILED_COMMIT_TS);
        } catch (KeyAlreadyExistsException e) {
            String msg = "Could not roll back transaction with start timestamp " + startTimestamp + "; either"
                    + " it was already rolled back (by a different transaction), or it committed successfully"
                    + " before we could roll it back.";
            log.error("This isn't a bug but it should be very infrequent. " + msg,
                    new TransactionFailedRetriableException(msg, e));
        }
        commitTimestamp = transactionService.get(startTimestamp);
    }
    if (commitTimestamp == null) {
        throw new RuntimeException("expected commit timestamp to be non-null for startTs: " + startTimestamp);
    }
    if (commitTimestamp == TransactionConstants.FAILED_COMMIT_TS) {
        for (String table : tableNameToCell.keySet()) {
            Map<Cell, Long> toDelete = Maps2.createConstantValueMap(tableNameToCell.get(table), startTimestamp);
            keyValueService.delete(table, Multimaps.forMap(toDelete));
        }
    }
    return commitTimestamp;
}

From source file:org.jclouds.blobstore.TransientAsyncBlobStore.java

protected Blob createUpdatedCopyOfBlob(Blob in) {
    checkNotNull(in, "blob");
    checkNotNull(in.getPayload(), "blob.payload");
    ByteArrayPayload payload = (in.getPayload() instanceof ByteArrayPayload)
            ? ByteArrayPayload.class.cast(in.getPayload())
            : null;/*from ww w . jav  a2 s  . c  o  m*/
    if (payload == null)
        payload = (in.getPayload() instanceof DelegatingPayload)
                ? (DelegatingPayload.class.cast(in.getPayload()).getDelegate() instanceof ByteArrayPayload)
                        ? ByteArrayPayload.class
                                .cast(DelegatingPayload.class.cast(in.getPayload()).getDelegate())
                        : null
                : null;
    try {
        if (payload == null || !(payload instanceof ByteArrayPayload)) {
            MutableContentMetadata oldMd = in.getPayload().getContentMetadata();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            in.getPayload().writeTo(out);
            payload = (ByteArrayPayload) Payloads.calculateMD5(Payloads.newPayload(out.toByteArray()));
            HttpUtils.copy(oldMd, payload.getContentMetadata());
        } else {
            if (payload.getContentMetadata().getContentMD5() == null)
                Payloads.calculateMD5(in, crypto.md5());
        }
    } catch (IOException e) {
        Throwables.propagate(e);
    }
    Blob blob = blobFactory.create(copy(in.getMetadata()));
    blob.setPayload(payload);
    blob.getMetadata().setLastModified(new Date());
    String eTag = CryptoStreams.hex(payload.getContentMetadata().getContentMD5());
    blob.getMetadata().setETag(eTag);
    // Set HTTP headers to match metadata
    blob.getAllHeaders().replaceValues(HttpHeaders.LAST_MODIFIED,
            Collections.singleton(dateService.rfc822DateFormat(blob.getMetadata().getLastModified())));
    blob.getAllHeaders().replaceValues(HttpHeaders.ETAG, Collections.singleton(eTag));
    copyPayloadHeadersToBlob(payload, blob);
    blob.getAllHeaders().putAll(Multimaps.forMap(blob.getMetadata().getUserMetadata()));
    return blob;
}

From source file:org.parceler.internal.ParcelableAnalysis.java

private HashMultimap<String, ASTReference<ASTMethod>> findValueMethods(ASTType astType,
        Predicate<ASTMethod> filter, final Function<ASTMethod, String> nameTransformer,
        final Set<MethodSignature> definedMethods, final boolean declaredProperty) {
    return Multimaps.invertFrom(
            Multimaps.forMap(FluentIterable.from(astType.getMethods()).filter(new Predicate<ASTMethod>() {
                @Override//from   www .  jav a 2s. c o m
                public boolean apply(ASTMethod astMethod) {
                    return !astMethod.isStatic() && !astMethod.isAnnotated(Transient.class)
                            && !definedMethods.contains(new MethodSignature(astMethod))
                            && (declaredProperty == astMethod.isAnnotated(ParcelProperty.class));
                }
            }).filter(filter).transform(new Function<ASTMethod, ASTReference<ASTMethod>>() {
                @Override
                public ASTReference<ASTMethod> apply(ASTMethod astMethod) {
                    return new ASTReference<ASTMethod>(astMethod, getConverter(astMethod));
                }
            }).toMap(new Function<ASTReference<ASTMethod>, String>() {
                @Override
                public String apply(ASTReference<ASTMethod> astMethodReference) {
                    return nameTransformer.apply(astMethodReference.getReference());
                }
            })), HashMultimap.<String, ASTReference<ASTMethod>>create());
}

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

@Override
public Map<Cell, Value> get(String tableName, Map<Cell, Long> timestampByCell) {
    if (timestampByCell.isEmpty()) {
        log.info("Attempted get on '{}' table with empty cells", tableName);
        return ImmutableMap.of();
    }//w w  w.j ava 2  s . co  m

    try {
        Long firstTs = timestampByCell.values().iterator().next();
        if (Iterables.all(timestampByCell.values(), Predicates.equalTo(firstTs))) {
            StartTsResultsCollector collector = new StartTsResultsCollector(firstTs);
            loadWithTs(tableName, timestampByCell.keySet(), firstTs, false, collector, readConsistency);
            return collector.collectedResults;
        }

        SetMultimap<Long, Cell> cellsByTs = Multimaps.invertFrom(Multimaps.forMap(timestampByCell),
                HashMultimap.<Long, Cell>create());
        Builder<Cell, Value> builder = ImmutableMap.builder();
        for (long ts : cellsByTs.keySet()) {
            StartTsResultsCollector collector = new StartTsResultsCollector(ts);
            loadWithTs(tableName, cellsByTs.get(ts), ts, false, collector, readConsistency);
            builder.putAll(collector.collectedResults);
        }
        return builder.build();
    } catch (Exception e) {
        throw Throwables.throwUncheckedException(e);
    }
}

From source file:org.apache.helix.model.IdealState.java

/**
 * Update the ideal state from a ResourceAssignment computed during a rebalance
 * @param assignment the new resource assignment
 * @param stateModelDef state model of the resource
 */// w  ww  .  j a  v a 2s  . c  o  m
public void updateFromAssignment(ResourceAssignment assignment, StateModelDefinition stateModelDef) {
    // clear all preference lists and maps
    _record.getMapFields().clear();
    _record.getListFields().clear();

    // assign a partition at a time
    for (PartitionId partition : assignment.getMappedPartitionIds()) {
        List<ParticipantId> preferenceList = new ArrayList<ParticipantId>();
        Map<ParticipantId, State> participantStateMap = new HashMap<ParticipantId, State>();

        // invert the map to get in state order
        Map<ParticipantId, State> replicaMap = assignment.getReplicaMap(partition);
        ListMultimap<State, ParticipantId> inverseMap = ArrayListMultimap.create();
        Multimaps.invertFrom(Multimaps.forMap(replicaMap), inverseMap);

        // update the ideal state in order of state priorities
        for (State state : stateModelDef.getTypedStatesPriorityList()) {
            if (!state.equals(State.from(HelixDefinedState.DROPPED))
                    && !state.equals(State.from(HelixDefinedState.ERROR))) {
                List<ParticipantId> stateParticipants = inverseMap.get(state);
                for (ParticipantId participant : stateParticipants) {
                    preferenceList.add(participant);
                    participantStateMap.put(participant, state);
                }
            }
        }
        setPreferenceList(partition, preferenceList);
        setParticipantStateMap(partition, participantStateMap);
    }
}

From source file:org.parceler.internal.ParcelableAnalysis.java

private HashMultimap<String, ASTReference<ASTField>> findFields(ASTType astType,
        final boolean declaredProperty) {
    return Multimaps.invertFrom(
            Multimaps.forMap(FluentIterable.from(astType.getFields()).filter(new Predicate<ASTField>() {
                @Override//from ww w.j a va 2  s  .c o m
                public boolean apply(ASTField astField) {
                    return !astField.isStatic() && !astField.isAnnotated(Transient.class)
                            && !astField.isTransient()
                            && (declaredProperty == astField.isAnnotated(ParcelProperty.class));
                }
            }).transform(new Function<ASTField, ASTReference<ASTField>>() {
                @Override
                public ASTReference<ASTField> apply(ASTField astField) {
                    return new ASTReference<ASTField>(astField, getConverter(astField));
                }
            }).toMap(new Function<ASTReference<ASTField>, String>() {
                @Override
                public String apply(ASTReference<ASTField> astFieldReference) {
                    ASTField astField = astFieldReference.getReference();
                    if (astField.isAnnotated(ParcelProperty.class)) {
                        return astField.getAnnotation(ParcelProperty.class).value();
                    }
                    return astField.getName();
                }
            })), HashMultimap.<String, ASTReference<ASTField>>create());
}

From source file:org.apache.aurora.scheduler.thrift.SchedulerThriftInterface.java

private static Set<InstanceTaskConfig> buildInitialState(Map<Integer, ITaskConfig> tasks) {
    // Translate tasks into instance IDs.
    Multimap<ITaskConfig, Integer> instancesByConfig = HashMultimap.create();
    Multimaps.invertFrom(Multimaps.forMap(tasks), instancesByConfig);

    // Reduce instance IDs into contiguous ranges.
    Map<ITaskConfig, Set<Range<Integer>>> rangesByConfig = Maps.transformValues(instancesByConfig.asMap(),
            Numbers::toRanges);// w  ww. ja v  a  2  s .c om

    ImmutableSet.Builder<InstanceTaskConfig> builder = ImmutableSet.builder();
    for (Map.Entry<ITaskConfig, Set<Range<Integer>>> entry : rangesByConfig.entrySet()) {
        builder.add(new InstanceTaskConfig().setTask(entry.getKey().newBuilder())
                .setInstances(IRange.toBuildersSet(convertRanges(entry.getValue()))));
    }

    return builder.build();
}