Example usage for com.google.common.collect HashBiMap create

List of usage examples for com.google.common.collect HashBiMap create

Introduction

In this page you can find the example usage for com.google.common.collect HashBiMap create.

Prototype

public static <K, V> HashBiMap<K, V> create(Map<? extends K, ? extends V> map) 

Source Link

Document

Constructs a new bimap containing initial values from map .

Usage

From source file:monasca.api.app.AlarmDefinitionService.java

/**
 * Returns an entry containing Maps of old, changed, and new sub expressions by comparing the
 * {@code alarmExpression} to the existing sub expressions for the {@code alarmDefId}.
 *//*w  ww .  j  av a  2 s . com*/
SubExpressions subExpressionsFor(final Map<String, AlarmSubExpression> initialSubExpressions,
        AlarmExpression alarmExpression) {
    BiMap<String, AlarmSubExpression> oldExpressions = HashBiMap.create(initialSubExpressions);
    Set<AlarmSubExpression> oldSet = oldExpressions.inverse().keySet();
    Set<AlarmSubExpression> newSet = new HashSet<>(alarmExpression.getSubExpressions());

    // Identify old or changed expressions
    Set<AlarmSubExpression> oldOrChangedExpressions = new HashSet<>(Sets.difference(oldSet, newSet));

    // Identify new or changed expressions
    Set<AlarmSubExpression> newOrChangedExpressions = new HashSet<>(Sets.difference(newSet, oldSet));

    // Find changed expressions
    Map<String, AlarmSubExpression> changedExpressions = new HashMap<>();
    for (Iterator<AlarmSubExpression> oldIt = oldOrChangedExpressions.iterator(); oldIt.hasNext();) {
        AlarmSubExpression oldExpr = oldIt.next();
        for (Iterator<AlarmSubExpression> newIt = newOrChangedExpressions.iterator(); newIt.hasNext();) {
            AlarmSubExpression newExpr = newIt.next();
            if (sameKeyFields(oldExpr, newExpr)) {
                oldIt.remove();
                newIt.remove();
                changedExpressions.put(oldExpressions.inverse().get(oldExpr), newExpr);
            }
        }
    }

    // Create the list of unchanged expressions
    BiMap<String, AlarmSubExpression> unchangedExpressions = HashBiMap.create(oldExpressions);
    unchangedExpressions.values().removeAll(oldOrChangedExpressions);
    unchangedExpressions.keySet().removeAll(changedExpressions.keySet());

    // Remove old sub expressions
    oldExpressions.values().retainAll(oldOrChangedExpressions);

    // Create IDs for new expressions
    Map<String, AlarmSubExpression> newExpressions = new HashMap<>();
    for (AlarmSubExpression expression : newOrChangedExpressions)
        newExpressions.put(UUID.randomUUID().toString(), expression);

    SubExpressions subExpressions = new SubExpressions();
    subExpressions.oldAlarmSubExpressions = oldExpressions;
    subExpressions.changedSubExpressions = changedExpressions;
    subExpressions.unchangedSubExpressions = unchangedExpressions;
    subExpressions.newAlarmSubExpressions = newExpressions;
    return subExpressions;
}

From source file:org.lealone.cluster.locator.TokenMetaData.java

/**
 * Create a copy of TokenMetaData with only tokenToEndpointMap. That is, pending ranges,
 * bootstrap tokens and leaving endpoints are not included in the copy.
 *//*from ww w  .  j  av a  2s.c om*/
public TokenMetaData cloneOnlyTokenMap() {
    lock.readLock().lock();
    try {
        return new TokenMetaData(
                SortedBiMultiValMap.<Token, InetAddress>create(tokenToEndpointMap, null, inetaddressCmp),
                HashBiMap.create(endpointToHostIdMap), new Topology(topology));
    } finally {
        lock.readLock().unlock();
    }
}

From source file:org.apache.rya.indexing.smarturi.SmartUriAdapter.java

/**
 * Deserializes a URI into a map of URI's to values.
 * @param uri the {@link URI}./*from w ww.  j av a 2s . co m*/
 * @return the {@link Map} of {@link URI}s to {@link Value}s.
 * @throws SmartUriException
 */
public static Map<URI, Value> deserializeUri(final URI uri) throws SmartUriException {
    final String uriString = uri.stringValue();
    final int fragmentPosition = uriString.indexOf("#");
    String prefix = uriString.substring(0, fragmentPosition + 1);
    if (fragmentPosition == -1) {
        prefix = uriString.split("\\?", 2)[0];
    }
    final String fragment = uriString.substring(fragmentPosition + 1, uriString.length());
    java.net.URI queryUri;

    URIBuilder uriBuilder = null;
    try {
        if (fragmentPosition > -1) {
            queryUri = new java.net.URI("urn://" + fragment);
        } else {
            queryUri = new java.net.URI(uriString);
        }
        uriBuilder = new URIBuilder(queryUri);
    } catch (final URISyntaxException e) {
        throw new SmartUriException("Unable to deserialize Smart URI", e);
    }
    final Map<URI, Value> map = new HashMap<>();
    final RyaURI subject = findSubject(uri.stringValue());

    final List<NameValuePair> parameters = uriBuilder.getQueryParams();
    Map<RyaURI, String> entityTypeMap = new LinkedHashMap<>();
    Map<String, RyaURI> invertedEntityTypeMap = new LinkedHashMap<>();
    final Map<RyaURI, Map<URI, Value>> fullMap = new LinkedHashMap<>();
    for (final NameValuePair pair : parameters) {
        final String keyString = pair.getName();
        final String valueString = pair.getValue();

        final URI keyUri = new URIImpl(prefix + keyString);
        final String decoded;
        try {
            decoded = URLDecoder.decode(valueString, Charsets.UTF_8.name());
        } catch (final UnsupportedEncodingException e) {
            throw new SmartUriException("", e);
        }
        final URI type = TypeDeterminer.determineType(decoded);
        if (type == XMLSchema.ANYURI) {
            if (keyString.equals(RYA_TYPES_URI.getLocalName())) {
                entityTypeMap = convertUriToTypeMap(new URIImpl(decoded));
                invertedEntityTypeMap = HashBiMap.create(entityTypeMap).inverse();
            }
        } else {
            final int keyPrefixLocation = keyString.indexOf(".");
            final String keyPrefix = keyString.substring(0, keyPrefixLocation);
            final RyaURI keyCorrespondingType = invertedEntityTypeMap.get(keyPrefix);
            final String keyName = keyString.substring(keyPrefixLocation + 1, keyString.length());
            final RyaType ryaType = new RyaType(type, valueString);

            final Value value = RyaToRdfConversions.convertValue(ryaType);

            final String formattedKeyUriString = removeTypePrefixFromUri(keyUri.stringValue(), keyPrefix);
            final URI formattedKeyUri = new URIImpl(formattedKeyUriString);

            map.put(formattedKeyUri, value);
        }
    }
    return map;
}

From source file:org.onos.yangtools.yang.parser.impl.YangParserImpl.java

private Map<ByteSource, Module> parseYangModelSources(final Collection<ByteSource> sources,
        final SchemaContext context) throws IOException, YangSyntaxErrorException {
    if (sources == null || sources.isEmpty()) {
        return Collections.emptyMap();
    }/*from w  ww .  j av  a  2 s  . c  o  m*/

    Map<ByteSource, ModuleBuilder> sourceToBuilder = resolveSources(sources, context);
    // sort and check for duplicates
    List<ModuleBuilder> sorted = ModuleDependencySort.sort(sourceToBuilder.values());
    Map<URI, NavigableMap<Date, ModuleBuilder>> modules = resolveModulesWithImports(sorted, null);
    Map<ModuleBuilder, Module> builderToModule = build(modules);
    Map<ModuleBuilder, ByteSource> builderToSource = HashBiMap.create(sourceToBuilder).inverse();
    sorted = ModuleDependencySort.sort(builderToModule.keySet());

    Map<ByteSource, Module> result = new LinkedHashMap<>();
    for (ModuleBuilder moduleBuilder : sorted) {
        Module value = checkNotNull(builderToModule.get(moduleBuilder), "Cannot get module for %s",
                moduleBuilder);
        result.put(builderToSource.get(moduleBuilder), value);
    }

    return result;
}

From source file:eu.esdihumboldt.hale.ui.service.align.internal.AlignmentServiceUndoSupport.java

/**
 * @see eu.esdihumboldt.hale.ui.service.align.AlignmentService#replaceCells(java.util.Map)
 *//*ww  w  . j a v  a 2s  . c  o  m*/
@Override
public void replaceCells(Map<? extends Cell, MutableCell> cells) {
    BiMap<MutableCell, MutableCell> map = HashBiMap.create(cells.size());
    for (Entry<? extends Cell, MutableCell> e : cells.entrySet()) {
        if (e.getKey() instanceof MutableCell && e.getValue() != null
                && getAlignment().getCells().contains(e.getKey()))
            map.put((MutableCell) e.getKey(), e.getValue());
        else {
            log.warn("Replaced cells contains at least one cell which "
                    + "is either not mutable or not in the alignment. " + "No undo/redo possible.");

            super.replaceCells(cells);
            return;
        }
    }

    IUndoableOperation operation = new ReplaceOperation(map);
    executeOperation(operation);
}

From source file:org.opendaylight.yangtools.yang.parser.impl.YangParserImpl.java

private Map<ByteSource, Module> parseYangModelSources(final Collection<ByteSource> sources,
        final SchemaContext context) throws IOException, YangSyntaxErrorException {
    if (sources == null || sources.isEmpty()) {
        return Collections.emptyMap();
    }/*from   ww w  .  j  a v a 2s  .  co  m*/

    Map<ByteSource, ModuleBuilder> sourceToBuilder = resolveSources(sources, context);
    // sort and check for duplicates
    List<ModuleBuilder> sorted = ModuleDependencySort.sort(sourceToBuilder.values());
    Map<URI, TreeMap<Date, ModuleBuilder>> modules = resolveModulesWithImports(sorted, null);
    Map<ModuleBuilder, Module> builderToModule = build(modules);
    Map<ModuleBuilder, ByteSource> builderToSource = HashBiMap.create(sourceToBuilder).inverse();
    sorted = ModuleDependencySort.sort(builderToModule.keySet());

    Map<ByteSource, Module> result = new LinkedHashMap<>();
    for (ModuleBuilder moduleBuilder : sorted) {
        Module value = checkNotNull(builderToModule.get(moduleBuilder), "Cannot get module for %s",
                moduleBuilder);
        result.put(builderToSource.get(moduleBuilder), value);
    }

    return result;
}

From source file:org.apache.rya.mongodb.aggregation.AggregationPipelineQueryNode.java

@Override
public AggregationPipelineQueryNode clone() {
    return new AggregationPipelineQueryNode(collection, new LinkedList<>(pipeline),
            new HashSet<>(assuredBindingNames), new HashSet<>(bindingNames),
            HashBiMap.create(varToOriginalName));
}

From source file:com.gnapse.common.inflector.Rule.java

public static BiMap<String, String> toBiMap(String[][] arr, boolean reversed) {
    final int key = reversed ? 1 : 0;
    final BiMap<String, String> result = HashBiMap.create(arr.length);
    for (String[] entry : arr) {
        String previousValue = result.put(entry[key].toLowerCase(), entry[1 - key]);
        checkArgument(previousValue == null, "Illegal irregular mapping");
    }/*from ww  w .  jav  a2 s. c o  m*/
    return result;
}

From source file:org.apache.rya.indexing.smarturi.SmartUriAdapter.java

public static Entity deserializeUriEntity(final URI uri) throws SmartUriException {
    final String uriString = uri.stringValue();
    final int fragmentPosition = uriString.indexOf("#");
    String prefix = uriString.substring(0, fragmentPosition + 1);
    if (fragmentPosition == -1) {
        prefix = uriString.split("\\?", 2)[0];
    }/*from w  w  w.j a  v a 2 s . c o m*/
    final String fragment = uriString.substring(fragmentPosition + 1, uriString.length());
    java.net.URI queryUri;

    URIBuilder uriBuilder = null;
    try {
        if (fragmentPosition > -1) {
            queryUri = new java.net.URI("urn://" + fragment);
        } else {
            queryUri = new java.net.URI(uriString);
        }
        uriBuilder = new URIBuilder(queryUri);
    } catch (final URISyntaxException e) {
        throw new SmartUriException("Unable to deserialize Smart URI", e);
    }

    final RyaURI subject = findSubject(uri.stringValue());

    final List<NameValuePair> parameters = uriBuilder.getQueryParams();
    Map<RyaURI, String> entityTypeMap = new LinkedHashMap<>();
    Map<String, RyaURI> invertedEntityTypeMap = new LinkedHashMap<>();
    final Map<RyaURI, Map<URI, Value>> fullMap = new LinkedHashMap<>();
    for (final NameValuePair pair : parameters) {
        final String keyString = pair.getName();
        final String valueString = pair.getValue();

        final URI keyUri = new URIImpl(prefix + keyString);
        final String decoded;
        try {
            decoded = URLDecoder.decode(valueString, Charsets.UTF_8.name());
        } catch (final UnsupportedEncodingException e) {
            throw new SmartUriException("", e);
        }
        final URI type = TypeDeterminer.determineType(decoded);
        if (type == XMLSchema.ANYURI) {
            if (keyString.equals(RYA_TYPES_URI.getLocalName())) {
                entityTypeMap = convertUriToTypeMap(new URIImpl(decoded));
                invertedEntityTypeMap = HashBiMap.create(entityTypeMap).inverse();
            }
        } else {
            final int keyPrefixLocation = keyString.indexOf(".");
            final String keyPrefix = keyString.substring(0, keyPrefixLocation);
            final RyaURI keyCorrespondingType = invertedEntityTypeMap.get(keyPrefix);
            final String keyName = keyString.substring(keyPrefixLocation + 1, keyString.length());
            final RyaType ryaType = new RyaType(type, valueString);

            final Value value = RyaToRdfConversions.convertValue(ryaType);

            final String formattedKeyUriString = removeTypePrefixFromUri(keyUri.stringValue(), keyPrefix);
            final URI formattedKeyUri = new URIImpl(formattedKeyUriString);
            final Map<URI, Value> map = fullMap.get(keyCorrespondingType);

            if (map == null) {
                final Map<URI, Value> subMap = new HashMap<>();
                subMap.put(formattedKeyUri, value);
                fullMap.put(keyCorrespondingType, subMap);
            } else {
                map.put(formattedKeyUri, value);
                fullMap.put(keyCorrespondingType, map);
            }
        }
    }
    final Entity entity = convertMapToEntity(subject, fullMap);
    return entity;
}

From source file:org.opencb.opencga.storage.mongodb.variant.converters.DocumentToSamplesConverter.java

public Document convertToStorageType(StudyEntry studyEntry, int studyId, int fileId, Document otherFields,
        Set<String> samplesInFile) {
    Map<String, List<Integer>> genotypeCodes = new HashMap<>();

    final StudyConfiguration studyConfiguration = studyConfigurations.get(studyId);
    boolean excludeGenotypes = studyConfiguration.getAttributes().getBoolean(Options.EXCLUDE_GENOTYPES.key(),
            Options.EXCLUDE_GENOTYPES.defaultValue());
    boolean compressExtraParams = studyConfiguration.getAttributes().getBoolean(
            Options.EXTRA_GENOTYPE_FIELDS_COMPRESS.key(),
            Options.EXTRA_GENOTYPE_FIELDS_COMPRESS.defaultValue());

    Set<String> defaultGenotype = studyDefaultGenotypeSet.get(studyId).stream().collect(Collectors.toSet());

    HashBiMap<String, Integer> sampleIds = HashBiMap.create(studyConfiguration.getSampleIds());
    // Classify samples by genotype
    int sampleIdx = 0;
    Integer gtIdx = studyEntry.getFormatPositions().get("GT");
    List<String> studyEntryOrderedSamplesName = studyEntry.getOrderedSamplesName();
    for (List<String> data : studyEntry.getSamplesData()) {
        String sampleName = studyEntryOrderedSamplesName.get(sampleIdx);
        sampleIdx++;// w  w  w  .j a va2 s. c  o  m
        if (!samplesInFile.contains(sampleName)) {
            continue;
        }
        String genotype;
        if (gtIdx == null) {
            genotype = UNKNOWN_GENOTYPE;
        } else {
            genotype = data.get(gtIdx);
        }
        if (genotype == null) {
            genotype = UNKNOWN_GENOTYPE;
        }
        //                Genotype g = new Genotype(genotype);
        List<Integer> samplesWithGenotype = genotypeCodes.get(genotype);
        if (samplesWithGenotype == null) {
            samplesWithGenotype = new ArrayList<>();
            genotypeCodes.put(genotype, samplesWithGenotype);
        }
        samplesWithGenotype.add(sampleIds.get(sampleName));
    }

    // In Mongo, samples are stored in a map, classified by their genotype.
    // The most common genotype will be marked as "default" and the specific
    // positions where it is shown will not be stored. Example from 1000G:
    // "def" : 0|0,
    // "0|1" : [ 41, 311, 342, 358, 881, 898, 903 ],
    // "1|0" : [ 262, 290, 300, 331, 343, 369, 374, 391, 879, 918, 930 ]
    Document mongoSamples = new Document();
    Document mongoGenotypes = new Document();
    for (Map.Entry<String, List<Integer>> entry : genotypeCodes.entrySet()) {
        String genotypeStr = genotypeToStorageType(entry.getKey());
        if (!defaultGenotype.contains(entry.getKey())) {
            mongoGenotypes.append(genotypeStr, entry.getValue());
        }
    }

    if (!excludeGenotypes) {
        mongoSamples.append(DocumentToStudyVariantEntryConverter.GENOTYPES_FIELD, mongoGenotypes);
    }

    //Position for samples in this file
    HashBiMap<String, Integer> samplesPosition = HashBiMap.create();
    int position = 0;
    for (Integer sampleId : studyConfiguration.getSamplesInFiles().get(fileId)) {
        samplesPosition.put(studyConfiguration.getSampleIds().inverse().get(sampleId), position++);
    }

    List<String> extraFields = studyConfiguration.getAttributes()
            .getAsStringList(Options.EXTRA_GENOTYPE_FIELDS.key());
    List<String> extraFieldsType = studyConfiguration.getAttributes()
            .getAsStringList(Options.EXTRA_GENOTYPE_FIELDS_TYPE.key());

    for (int i = 0; i < extraFields.size(); i++) {
        String extraField = extraFields.get(i);
        String extraFieldType = i < extraFieldsType.size() ? extraFieldsType.get(i) : "String";

        VariantMongoDBProto.OtherFields.Builder builder = VariantMongoDBProto.OtherFields.newBuilder();
        //            List<Object> values = new ArrayList<>(samplesPosition.size());
        //            for (int size = samplesPosition.size(); size > 0; size--) {
        //                values.add(UNKNOWN_FIELD);
        //            }
        sampleIdx = 0;
        if (studyEntry.getFormatPositions().containsKey(extraField)) {
            Integer formatIdx = studyEntry.getFormatPositions().get(extraField);
            for (List<String> sampleData : studyEntry.getSamplesData()) {
                String sampleName = studyEntryOrderedSamplesName.get(sampleIdx);
                sampleIdx++;
                if (!samplesInFile.contains(sampleName)) {
                    continue;
                }
                //                    Integer index = samplesPosition.get(sampleName);
                String stringValue = sampleData.get(formatIdx);
                //                    Object value;
                //                    if (NumberUtils.isNumber(stringValue)) {
                //                        try {
                //                            value = Integer.parseInt(stringValue);
                //                        } catch (NumberFormatException e) {
                //                            try {
                //                                value = Double.parseDouble(stringValue);
                //                            } catch (NumberFormatException e2) {
                //                                value = stringValue;
                //                            }
                //                        }
                //                    } else {
                //                        value = stringValue;
                //                    }
                switch (extraFieldType) {
                case "Integer": {
                    builder.addIntValues(INTEGER_COMPLEX_TYPE_CONVERTER.convertToStorageType(stringValue));
                    break;
                }
                case "Float": {
                    builder.addFloatValues(FLOAT_COMPLEX_TYPE_CONVERTER.convertToStorageType(stringValue));
                    break;
                }
                case "String":
                default:
                    builder.addStringValues(stringValue);
                    break;
                }
            }

            byte[] byteArray = builder.build().toByteArray();
            if (compressExtraParams) {
                if (byteArray.length > 50) {
                    try {
                        byteArray = CompressionUtils.compress(byteArray);
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                }
            }
            otherFields.append(extraField.toLowerCase(), byteArray);
        } // else { Don't set this field }
    }

    return mongoSamples;
}