Example usage for com.google.common.collect ImmutableMultimap.Builder put

List of usage examples for com.google.common.collect ImmutableMultimap.Builder put

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMultimap.Builder put.

Prototype

@Deprecated
@Override
public boolean put(K key, V value) 

Source Link

Document

Guaranteed to throw an exception and leave the multimap unmodified.

Usage

From source file:com.facebook.presto.accumulo.index.Indexer.java

public Indexer(Connector connector, Authorizations auths, AccumuloTable table, BatchWriterConfig writerConfig)
        throws TableNotFoundException {
    this.connector = requireNonNull(connector, "connector is null");
    this.table = requireNonNull(table, "table is null");
    this.writerConfig = requireNonNull(writerConfig, "writerConfig is null");
    requireNonNull(auths, "auths is null");

    this.serializer = table.getSerializerInstance();

    // Create our batch writer
    indexWriter = connector.createBatchWriter(table.getIndexTableName(), writerConfig);

    ImmutableMultimap.Builder<ByteBuffer, ByteBuffer> indexColumnsBuilder = ImmutableMultimap.builder();
    Map<ByteBuffer, Map<ByteBuffer, Type>> indexColumnTypesBuilder = new HashMap<>();

    // Initialize metadata
    table.getColumns().forEach(columnHandle -> {
        if (columnHandle.isIndexed()) {
            // Wrap the column family and qualifier for this column and add it to
            // collection of indexed columns
            ByteBuffer family = wrap(columnHandle.getFamily().get().getBytes(UTF_8));
            ByteBuffer qualifier = wrap(columnHandle.getQualifier().get().getBytes(UTF_8));
            indexColumnsBuilder.put(family, qualifier);

            // Create a mapping for this column's Presto type, again creating a new one for the
            // family if necessary
            Map<ByteBuffer, Type> types = indexColumnTypesBuilder.get(family);
            if (types == null) {
                types = new HashMap<>();
                indexColumnTypesBuilder.put(family, types);
            }//  www  .  j a va2s  . c om
            types.put(qualifier, columnHandle.getType());
        }
    });

    indexColumns = indexColumnsBuilder.build();
    indexColumnTypes = ImmutableMap.copyOf(indexColumnTypesBuilder);

    // If there are no indexed columns, throw an exception
    if (indexColumns.isEmpty()) {
        throw new PrestoException(NOT_SUPPORTED,
                "No indexed columns in table metadata. Refusing to index a table with no indexed columns");
    }

    // Initialize metrics map
    // This metrics map is for column cardinality
    metrics.put(METRICS_TABLE_ROW_COUNT, new AtomicLong(0));

    // Scan the metrics table for existing first row and last row
    Pair<byte[], byte[]> minmax = getMinMaxRowIds(connector, table, auths);
    firstRow = minmax.getLeft();
    lastRow = minmax.getRight();
}

From source file:org.lanternpowered.server.asset.DirectoryAssetRepository.java

@Override
public Multimap<String, Asset> getAssetsMap(String path, boolean checkChildDirectories) {
    final ImmutableMultimap.Builder<String, Asset> builder = ImmutableMultimap.builder();
    final Pattern pattern = Pattern.compile(generateRegex(path));
    final int length = this.directory.toString().length() + 1;
    try {//from   w  ww .  java  2s . c  o  m
        Files.walkFileTree(this.directory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                final String file0 = file.toString().substring(length).replace('\\', '/');
                final Matcher matcher = pattern.matcher(file0);
                if (matcher.matches()) {
                    final String id = matcher.group(2).toLowerCase(Locale.ENGLISH);
                    final int index = id.indexOf('/');
                    if (index == -1 || (checkChildDirectories && index != id.lastIndexOf('/'))) {
                        return FileVisitResult.CONTINUE;
                    }
                    final String plugin = matcher.group(1).toLowerCase(Locale.ENGLISH);
                    builder.put(id.substring(0, index), registerAsset(plugin, plugin + ':' + id, file));
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
    return builder.build();
}

From source file:edu.ksu.cis.santos.mdcf.dml.symbol.SymbolTable.java

/**
 * Retrieves a {@link Multimap} that relates a sub type's fully-qualified name
 * (either of {@link BasicType#name} or {@link Feature#name}) to its super
 * type's fully-qualified name (either of {@link BasicType#name} or
 * {@link Feature#name})./*  www.j  a  va 2s .  c  o  m*/
 * 
 * @return an immutable {@link Multimap}.
 */
public Multimap<String, String> superTransitiveMap() {
    Multimap<String, String> result = null;
    if ((this._superMap == null) || ((result = this._superMap.get()) == null)) {
        final HashSet<String> seen = new HashSet<>();

        final HashMultimap<String, String> m = HashMultimap.create();
        for (final BasicType bt : basicTypes()) {
            superTransitive(seen, m, bt);
        }

        for (final Feature f : features()) {
            superTransitive(seen, m, f);
        }

        final ImmutableMultimap.Builder<String, String> superb = ImmutableMultimap.builder();
        final ImmutableMultimap.Builder<String, String> subb = ImmutableMultimap.builder();

        for (final String sub : m.keySet()) {
            final Set<String> sups = m.get(sub);
            for (final String sup : sups) {
                superb.put(sub, sup);
                subb.put(sup, sub);
            }
        }

        result = superb.build();
        this._superMap = new SoftReference<Multimap<String, String>>(result);
        this._subMap = new SoftReference<Multimap<String, String>>(subb.build());
    }

    return result;
}

From source file:net.minecrell.quartz.launch.mappings.Mappings.java

protected Mappings(List<ClassNode> mappingClasses) {
    requireNonNull(mappingClasses, "mappingClasses");
    if (mappingClasses.isEmpty()) {
        this.classes = ImmutableBiMap.of();
        this.methods = ImmutableTable.of();
        this.fields = ImmutableTable.of();
        this.constructors = ImmutableMultimap.of();
        this.accessMappings = ImmutableTable.of();
        return;/*from www.j  av a2 s  . c  om*/
    }

    ImmutableBiMap.Builder<String, String> classes = ImmutableBiMap.builder();

    for (ClassNode classNode : mappingClasses) {
        ParsedAnnotation annotation = MappingsParser.getAnnotation(classNode, MAPPING);
        checkState(annotation != null, "Class %s is missing the @Mapping annotation", classNode.name);
        String mapping = annotation.getString("value", "");
        if (!mapping.isEmpty()) {
            classes.put(mapping, classNode.name);
        }
    }

    this.classes = classes.build();

    // We need to remap the descriptors of the fields and methods, use ASM for convenience
    Remapper remapper = new Remapper() {

        @Override
        public String map(String className) {
            return unmap(className);
        }
    };

    // Load field, method and access mappings
    ImmutableTable.Builder<String, String, String> methods = ImmutableTable.builder();
    ImmutableTable.Builder<String, String, String> fields = ImmutableTable.builder();
    ImmutableMultimap.Builder<String, MethodNode> constructors = ImmutableMultimap.builder();
    ImmutableTable.Builder<String, String, AccessMapping> accessMappings = ImmutableTable.builder();

    for (ClassNode classNode : mappingClasses) {
        String className = classNode.name.replace('/', '.');
        String internalName = unmap(classNode.name);

        ParsedAnnotation annotation = MappingsParser.getAnnotation(classNode, ACCESSIBLE);
        if (annotation != null) {
            accessMappings.put(className, "", AccessMapping.of(classNode));
        }

        for (MethodNode methodNode : classNode.methods) {
            Map<String, ParsedAnnotation> annotations = MappingsParser.getAnnotations(methodNode);

            annotation = annotations.get(CONSTRUCTOR);
            if (annotation != null) {
                // Generate constructor call code
                Methods.visitConstructor(methodNode, classNode.name);
                constructors.put(className, methodNode);
                continue;
            }

            // TODO: Validation
            annotation = annotations.get(MAPPING);
            if (annotation != null) {
                String mapping = annotation.getString("value", "");
                if (!mapping.isEmpty()) {
                    methods.put(internalName, mapping + remapper.mapMethodDesc(methodNode.desc),
                            methodNode.name);
                }
            }

            annotation = annotations.get(ACCESSIBLE);
            if (annotation != null) {
                accessMappings.put(className, methodNode.name + methodNode.desc, AccessMapping.of(methodNode));
            }
        }

        for (FieldNode fieldNode : classNode.fields) {
            Map<String, ParsedAnnotation> annotations = MappingsParser.getAnnotations(fieldNode);

            // TODO: Validation
            annotation = annotations.get(MAPPING);
            if (annotation != null) {
                String mapping = annotation.getString("value", "");
                if (!mapping.isEmpty()) {
                    fields.put(internalName, mapping + ':' + remapper.mapDesc(fieldNode.desc), fieldNode.name);
                }
            }

            annotation = annotations.get(ACCESSIBLE);
            if (annotation != null) {
                accessMappings.put(className, fieldNode.name, AccessMapping.of(fieldNode));
            }
        }
    }

    this.methods = methods.build();
    this.fields = fields.build();
    this.constructors = constructors.build();
    this.accessMappings = accessMappings.build();
}

From source file:org.apache.gobblin.config.common.impl.InMemoryTopology.java

private synchronized void computeImportedByMap(Optional<Config> runtimeConfig) {
    if (this.fullImportedByMap != null) {
        return;/*from  w w  w . j  av  a2s .  c om*/
    }

    ImmutableMultimap.Builder<ConfigKeyPath, ConfigKeyPath> importedByBuilder = ImmutableMultimap.builder();

    // breath first search the whole topology to build ownImports map and ownImportedByMap
    // calls to retrieve cache / set cache if not present
    Collection<ConfigKeyPath> currentLevel = this.getChildren(SingleLinkedListConfigKeyPath.ROOT);

    List<ConfigKeyPath> rootImports = this.getOwnImports(SingleLinkedListConfigKeyPath.ROOT, runtimeConfig);
    Preconditions.checkArgument(rootImports == null || rootImports.size() == 0,
            "Root can not import other nodes, otherwise circular dependency will happen");

    while (!currentLevel.isEmpty()) {
        Collection<ConfigKeyPath> nextLevel = new ArrayList<>();
        for (ConfigKeyPath configKeyPath : currentLevel) {
            // calls to retrieve cache / set cache if not present
            List<ConfigKeyPath> ownImports = this.getOwnImports(configKeyPath, runtimeConfig);
            this.ownImportMap.put(configKeyPath, ownImports);
            for (ConfigKeyPath importedPath : ownImports) {
                importedByBuilder.put(importedPath, configKeyPath);
            }

            // calls to retrieve cache / set cache if not present
            Collection<ConfigKeyPath> tmp = this.getChildren(configKeyPath);
            nextLevel.addAll(tmp);
        }
        currentLevel = nextLevel;
    }

    this.fullImportedByMap = importedByBuilder.build();
}

From source file:com.exoplatform.iversion.Merge.java

public <M, T extends Version<K, V, M>> Merge(Iterable<VersionNode<K, V, M, T>> versions) {
    checkNotNull(versions, "versions");
    Iterator<VersionNode<K, V, M, T>> iter = versions.iterator();

    // No versions
    if (!iter.hasNext()) {
        mergedProperties = ImmutableMap.of();
        revisions = ImmutableSet.of();//from   w w  w . j av a2  s  . c  o m
        conflicts = ImmutableMultimap.of();
    } else {
        VersionNode<K, V, M, T> versionNode = next(iter);

        // One version
        if (!iter.hasNext()) {
            mergedProperties = versionNode.getProperties();
            revisions = ImmutableSet.of(versionNode.getRevision());
            conflicts = ImmutableMultimap.of();
        }
        // More than one version -> merge!
        else {
            Map<K, VersionProperty<V>> mergedProperties = Maps.newLinkedHashMap(versionNode.getProperties());
            Set<Long> heads = Sets.newHashSet(versionNode.getRevision());
            ImmutableMultimap.Builder<K, VersionProperty<V>> conflicts = ImmutableMultimap.builder();

            Set<Long> mergedRevisions = Sets.newHashSet(versionNode.getRevisions());
            do {
                versionNode = next(iter);

                // Version already merged?
                if (!mergedRevisions.contains(versionNode.getRevision())) {
                    for (Map.Entry<K, VersionProperty<V>> entry : versionNode.getProperties().entrySet()) {
                        K key = entry.getKey();
                        VersionProperty<V> nextValue = entry.getValue();

                        // nextValue derives from common ancestor?
                        if (!mergedRevisions.contains(nextValue.revision)) {
                            VersionProperty<V> previousValue = mergedProperties.get(key);

                            // New value
                            if (previousValue == null) {
                                mergedProperties.put(key, nextValue);
                            }
                            // Conflicting value?
                            else if (!equal(previousValue.value, nextValue.value)) {
                                conflicts.put(key, nextValue);
                            }
                        }
                    }
                    mergedRevisions.addAll(versionNode.getRevisions());

                    heads.removeAll(versionNode.getRevisions());
                    heads.add(versionNode.getRevision());
                }
            } while (iter.hasNext());

            this.mergedProperties = unmodifiableMap(mergedProperties);
            this.revisions = unmodifiableSet(heads);
            this.conflicts = conflicts.build();
        }
    }

}

From source file:grakn.core.graql.reasoner.atom.binary.RelationAtom.java

private Multimap<Role, Type> getRoleTypeMap(boolean inferTypes) {
    ImmutableMultimap.Builder<Role, Type> builder = ImmutableMultimap.builder();
    Multimap<Role, Variable> roleMap = getRoleVarMap();
    SetMultimap<Variable, Type> varTypeMap = getParentQuery().getVarTypeMap(inferTypes);

    roleMap.entries().stream().sorted(Comparator.comparing(e -> e.getKey().label()))
            .flatMap(e -> varTypeMap.get(e.getValue()).stream().map(type -> new Pair<>(e.getKey(), type)))
            .sorted(Comparator.comparing(Pair::hashCode)).forEach(p -> builder.put(p.getKey(), p.getValue()));
    return builder.build();
}

From source file:com.facebook.presto.sql.analyzer.TupleAnalyzer.java

private List<FieldOrExpression> analyzeOrderBy(QuerySpecification node, TupleDescriptor tupleDescriptor,
        AnalysisContext context, List<FieldOrExpression> outputExpressions) {
    List<SortItem> items = node.getOrderBy();

    ImmutableList.Builder<FieldOrExpression> orderByExpressionsBuilder = ImmutableList.builder();

    if (!items.isEmpty()) {
        // Compute aliased output terms so we can resolve order by expressions against them first
        ImmutableMultimap.Builder<QualifiedName, Expression> byAliasBuilder = ImmutableMultimap.builder();
        for (SelectItem item : node.getSelect().getSelectItems()) {
            if (item instanceof SingleColumn) {
                Optional<String> alias = ((SingleColumn) item).getAlias();
                if (alias.isPresent()) {
                    byAliasBuilder.put(QualifiedName.of(alias.get()), ((SingleColumn) item).getExpression()); // TODO: need to know if alias was quoted
                }// w  w  w .  j  a va 2 s  .  c  o m
            }
        }
        Multimap<QualifiedName, Expression> byAlias = byAliasBuilder.build();

        for (SortItem item : items) {
            Expression expression = item.getSortKey();

            FieldOrExpression orderByExpression = null;
            if (expression instanceof QualifiedNameReference
                    && !((QualifiedNameReference) expression).getName().getPrefix().isPresent()) {
                // if this is a simple name reference, try to resolve against output columns

                QualifiedName name = ((QualifiedNameReference) expression).getName();
                Collection<Expression> expressions = byAlias.get(name);
                if (expressions.size() > 1) {
                    throw new SemanticException(AMBIGUOUS_ATTRIBUTE, expression,
                            "'%s' in ORDER BY is ambiguous", name.getSuffix());
                } else if (expressions.size() == 1) {
                    orderByExpression = new FieldOrExpression(Iterables.getOnlyElement(expressions));
                }

                // otherwise, couldn't resolve name against output aliases, so fall through...
            } else if (expression instanceof LongLiteral) {
                // this is an ordinal in the output tuple

                long ordinal = ((LongLiteral) expression).getValue();
                if (ordinal < 1 || ordinal > outputExpressions.size()) {
                    throw new SemanticException(INVALID_ORDINAL, expression,
                            "ORDER BY position %s is not in select list", ordinal);
                }

                orderByExpression = outputExpressions.get((int) (ordinal - 1));

                if (orderByExpression.isExpression()) {
                    Type type = analysis.getType(orderByExpression.getExpression());
                    if (!type.isOrderable()) {
                        throw new SemanticException(TYPE_MISMATCH, node,
                                "The type of expression in position %s is not orderable (actual: %s), and therefore cannot be used in ORDER BY: %s",
                                ordinal, type, orderByExpression);
                    }
                } else {
                    Type type = tupleDescriptor.getFieldByIndex(orderByExpression.getFieldIndex()).getType();
                    if (!type.isOrderable()) {
                        throw new SemanticException(TYPE_MISMATCH, node,
                                "The type of expression in position %s is not orderable (actual: %s), and therefore cannot be used in ORDER BY",
                                ordinal, type);
                    }
                }
            }

            // otherwise, just use the expression as is
            if (orderByExpression == null) {
                orderByExpression = new FieldOrExpression(expression);
            }

            if (orderByExpression.isExpression()) {
                ExpressionAnalysis expressionAnalysis = analyzeExpression(orderByExpression.getExpression(),
                        tupleDescriptor, context);
                analysis.addInPredicates(node, expressionAnalysis.getSubqueryInPredicates());

                Type type = expressionAnalysis.getType(orderByExpression.getExpression());
                if (!type.isOrderable()) {
                    throw new SemanticException(TYPE_MISMATCH, node,
                            "Type %s is not orderable, and therefore cannot be used in ORDER BY: %s", type,
                            expression);
                }
            }

            orderByExpressionsBuilder.add(orderByExpression);
        }
    }

    List<FieldOrExpression> orderByExpressions = orderByExpressionsBuilder.build();
    analysis.setOrderByExpressions(node, orderByExpressions);

    if (node.getSelect().isDistinct() && !outputExpressions.containsAll(orderByExpressions)) {
        throw new SemanticException(ORDER_BY_MUST_BE_IN_SELECT, node.getSelect(),
                "For SELECT DISTINCT, ORDER BY expressions must appear in select list");
    }
    return orderByExpressions;
}

From source file:org.immutables.value.processor.meta.Round.java

public Multimap<DeclaringPackage, ValueType> collectValues() {
    ImmutableList<Protoclass> protoclasses = collectProtoclasses();
    Map<DeclaringType, ValueType> enclosingTypes = Maps.newHashMap();

    ImmutableMultimap.Builder<DeclaringPackage, ValueType> builder = ImmutableMultimap.builder();

    // Collect enclosing
    for (Protoclass protoclass : protoclasses) {
        if (protoclass.kind().isEnclosing()) {
            ValueType type = composer().compose(protoclass);
            enclosingTypes.put(protoclass.declaringType().get(), type);
        }//from   w ww.j a  va2  s. co m
    }
    // Collect remaining and attach if nested
    for (Protoclass protoclass : protoclasses) {
        @Nullable
        ValueType current = null;
        if (protoclass.kind().isNested()) {
            @Nullable
            ValueType enclosing = enclosingTypes.get(protoclass.enclosingOf().get());
            if (enclosing != null) {
                current = composer().compose(protoclass);
                // Attach nested to enclosing
                enclosing.addNested(current);
            }
        }
        // getting the ValueType if it was alredy created and put into enclosingTypes
        if (current == null && protoclass.kind().isEnclosing()) {
            current = enclosingTypes.get(protoclass.declaringType().get());
        }
        // If none then we just create it
        if (current == null) {
            current = composer().compose(protoclass);
        }
        // We put all enclosing and nested values by the package
        builder.put(protoclass.packageOf(), current);
    }

    return builder.build();
}

From source file:net.minecrell.ice.launch.transformers.AccessTransformer.java

protected AccessTransformer(String file) throws IOException {
    checkNotNull(file, "file");

    ImmutableMultimap.Builder<String, Modifier> builder = ImmutableListMultimap.builder();

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(
            getClass().getClassLoader().getResourceAsStream(file), StandardCharsets.UTF_8))) {
        String line;//w w w  .j  av a  2 s  .c om
        while ((line = reader.readLine()) != null) {
            line = substringBefore(line, '#').trim();
            if (line.isEmpty()) {
                continue;
            }

            List<String> parts = SEPARATOR.splitToList(line);
            checkArgument(parts.size() <= 3, "Invalid access transformer config line: " + line);

            String name = null;
            String desc = null;

            boolean isClass = parts.size() == 2;
            if (!isClass) {
                name = parts.get(2);
                int pos = name.indexOf('(');
                if (pos >= 0) {
                    desc = name.substring(pos);
                    name = name.substring(0, pos);
                }
            }

            String s = parts.get(0);
            int access = 0;
            if (s.startsWith("public")) {
                access = ACC_PUBLIC;
            } else if (s.startsWith("protected")) {
                access = ACC_PROTECTED;
            } else if (s.startsWith("private")) {
                access = ACC_PRIVATE;
            }

            Boolean markFinal = null;
            if (s.endsWith("+f")) {
                markFinal = true;
            } else if (s.endsWith("-f")) {
                markFinal = false;
            }

            String className = parts.get(1).replace('/', '.');
            builder.put(className, new Modifier(name, desc, isClass, access, markFinal));
        }
    }

    this.modifiers = builder.build();
}