Example usage for com.google.common.collect Maps immutableEntry

List of usage examples for com.google.common.collect Maps immutableEntry

Introduction

In this page you can find the example usage for com.google.common.collect Maps immutableEntry.

Prototype

@GwtCompatible(serializable = true)
public static <K, V> Entry<K, V> immutableEntry(@Nullable K key, @Nullable V value) 

Source Link

Document

Returns an immutable map entry with the specified key and value.

Usage

From source file:me.lucko.luckperms.common.core.model.PermissionHolder.java

private SortedSet<LocalizedNode> getAllNodesCacheApply(GetAllNodesRequest getAllNodesHolder) {
    // Expand the holder.
    List<String> excludedGroups = new ArrayList<>(getAllNodesHolder.getExcludedGroups());
    ExtractedContexts contexts = getAllNodesHolder.getContexts();

    // Don't register users, as they cannot be inherited.
    if (!(this instanceof User)) {
        excludedGroups.add(getObjectName().toLowerCase());
    }//from w w  w  .ja  va2s .  co m

    // Get the objects base permissions.
    SortedSet<LocalizedNode> all = new TreeSet<>((SortedSet<LocalizedNode>) getPermissions(true));

    Contexts context = contexts.getContexts();
    String server = contexts.getServer();
    String world = contexts.getWorld();

    Set<Node> parents = all.stream().map(LocalizedNode::getNode).filter(Node::getValue)
            .filter(Node::isGroupNode)
            .filter(n -> n.shouldApplyOnServer(server, context.isApplyGlobalGroups(),
                    plugin.getConfiguration().get(ConfigKeys.APPLYING_REGEX)))
            .filter(n -> n.shouldApplyOnWorld(world, context.isApplyGlobalWorldGroups(),
                    plugin.getConfiguration().get(ConfigKeys.APPLYING_REGEX)))
            .filter(n -> n.shouldApplyWithContext(contexts.getContextSet(), false)).collect(Collectors.toSet());

    // Resolve & sort parents into order before we apply.
    TreeSet<Map.Entry<Integer, Group>> sortedParents = new TreeSet<>(WeightComparator.INSTANCE.reversed());
    for (Node node : parents) {
        Group group = plugin.getGroupManager().getIfLoaded(node.getGroupName());
        if (group != null) {
            sortedParents.add(Maps.immutableEntry(group.getWeight().orElse(0), group));
        }
    }

    for (Map.Entry<Integer, Group> e : sortedParents) {
        if (excludedGroups.contains(e.getValue().getObjectName().toLowerCase())) {
            continue;
        }

        inherited: for (LocalizedNode inherited : e.getValue().getAllNodes(excludedGroups, contexts)) {
            for (LocalizedNode existing : all) {
                if (existing.getNode().almostEquals(inherited.getNode())) {
                    continue inherited;
                }
            }

            all.add(inherited);
        }
    }

    return all;
}

From source file:io.atomix.core.map.impl.AbstractAtomicNavigableMapService.java

private Map.Entry<K, Versioned<byte[]>> toVersionedEntry(Map.Entry<K, MapEntryValue> entry) {
    return entry == null || valueIsNull(entry.getValue()) ? null
            : Maps.immutableEntry(entry.getKey(), toVersioned(entry.getValue()));
}

From source file:ninja.leaping.permissionsex.backend.sql.SqlDao.java

private Set<Entry<String, String>> getSegmentContexts(int segmentId) throws SQLException {
    try (PreparedStatement stmt = prepareStatement(getSelectContextsSegmentQuery())) {
        stmt.setInt(1, segmentId);//from w ww.j  a  v a2  s  .  c  o m
        ImmutableSet.Builder<Entry<String, String>> res = ImmutableSet.builder();

        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            res.add(Maps.immutableEntry(rs.getString(1), rs.getString(2)));
        }
        return res.build();
    }
}

From source file:com.ikanow.aleph2.shared.crud.mongodb.utils.MongoDbUtils.java

/** Create a MongoDB update object
 * @param update - the generic specification
 * @param add increments numbers or adds to sets/lists
 * @param remove decrements numbers of removes from sets/lists
 * @return the mongodb object// www. ja va 2 s.  c  om
 * @throws IOException 
 * @throws JsonMappingException 
 * @throws JsonGenerationException 
 */
@SuppressWarnings("unchecked")
public static <O> DBObject createUpdateObject(final UpdateComponent<O> update) {
    final ObjectMapper object_mapper = MongoJackModule
            .configure(BeanTemplateUtils.configureMapper(Optional.empty()));

    return update.getAll().entries().stream()
            .map(kv -> Patterns
                    .match(kv.getValue()._2()).<Map.Entry<String, Tuple2<UpdateOperator, Object>>>andReturn()
                    // Special case, handle bean template
                    .when(e -> null == e, __ -> kv)
                    .when(e -> e instanceof Enum,
                            e -> Maps.immutableEntry(kv.getKey(), Tuples._2T(kv.getValue()._1(), e.toString())))
                    .when(JsonNode.class,
                            j -> Maps.immutableEntry(kv.getKey(),
                                    Tuples._2T(kv.getValue()._1(), convertJsonBean(j, object_mapper))))
                    .when(BeanTemplate.class,
                            e -> Maps.immutableEntry(kv.getKey(),
                                    Tuples._2T(kv.getValue()._1(), convertBeanTemplate(e, object_mapper))))
                    // Special case, handle list of bean templates
                    .when(Collection.class, l -> !l.isEmpty() && (l.iterator().next() instanceof JsonNode),
                            l -> Maps.immutableEntry(kv.getKey(),
                                    Tuples._2T(kv.getValue()._1(),
                                            l.stream().map(j -> convertJsonBean((JsonNode) j, object_mapper))
                                                    .collect(Collectors.toList()))))
                    .when(Collection.class, l -> !l.isEmpty() && (l.iterator().next() instanceof BeanTemplate),
                            l -> Maps.immutableEntry(kv.getKey(), Tuples._2T(kv.getValue()._1(), l.stream()
                                    .map(e -> convertBeanTemplate((BeanTemplate<Object>) e, object_mapper))
                                    .collect(Collectors.toList()))))
                    .otherwise(() -> kv))
            .collect(Collector.of(BasicDBObject::new, (acc, kv) -> {
                Patterns.match(kv.getValue()._2()).andAct()
                        // Delete operator, bunch of things have to happen for safety
                        .when(o -> ((UpdateOperator.unset == kv.getValue()._1()) && kv.getKey().isEmpty()
                                && (null == kv.getValue()._2())), o -> acc.put("$unset", null))
                        //Increment
                        .when(Number.class, n -> (UpdateOperator.increment == kv.getValue()._1()),
                                n -> nestedPut(acc, "$inc", kv.getKey(), n))
                        // Set
                        .when(o -> (UpdateOperator.set == kv.getValue()._1()),
                                o -> nestedPut(acc, "$set", kv.getKey(), o))
                        // Unset
                        .when(o -> (UpdateOperator.unset == kv.getValue()._1()),
                                o -> nestedPut(acc, "$unset", kv.getKey(), 1))
                        // Add items/item to list
                        .when(Collection.class, c -> (UpdateOperator.add == kv.getValue()._1()),
                                c -> nestedPut(acc, "$push", kv.getKey(), new BasicDBObject("$each", c)))
                        .when(o -> (UpdateOperator.add == kv.getValue()._1()),
                                o -> nestedPut(acc, "$push", kv.getKey(), o))
                        // Add item/items to set
                        .when(Collection.class, c -> (UpdateOperator.add_deduplicate == kv.getValue()._1()),
                                c -> nestedPut(acc, "$addToSet", kv.getKey(), new BasicDBObject("$each", c)))
                        .when(o -> (UpdateOperator.add_deduplicate == kv.getValue()._1()),
                                o -> nestedPut(acc, "$addToSet", kv.getKey(), o))
                        // Remove items from list by query
                        .when(QueryComponent.class, q -> (UpdateOperator.remove == kv.getValue()._1()),
                                q -> nestedPut(acc, "$pull", kv.getKey(), convertToMongoQuery(q)._1()))
                        // Remove items/item from list
                        .when(Collection.class, c -> (UpdateOperator.remove == kv.getValue()._1()),
                                c -> nestedPut(acc, "$pullAll", kv.getKey(), c))
                        .when(o -> (UpdateOperator.remove == kv.getValue()._1()),
                                o -> nestedPut(acc, "$pullAll", kv.getKey(), Arrays.asList(o)))
                        .otherwise(() -> {
                        }); // (do nothing)
            }, (a, b) -> {
                a.putAll(b.toMap());
                return a;
            }, Characteristics.UNORDERED));
}

From source file:ome.services.graphs.GraphPathReport.java

/**
 * Process the Hibernate domain object model and write a report of the mapped objects.
 * @throws IOException if there was a problem in writing to the output file
 *///from w  w  w.  j a  va2s  . c o  m
private static void report() throws IOException {
    /* note all the direct superclasses and subclasses */
    final Map<String, String> superclasses = new HashMap<String, String>();
    final SortedSetMultimap<String, String> subclasses = TreeMultimap.create();
    @SuppressWarnings("unchecked")
    final Map<String, ClassMetadata> classesMetadata = sessionFactory.getAllClassMetadata();
    for (final String className : classesMetadata.keySet()) {
        try {
            final Class<?> actualClass = Class.forName(className);
            if (IObject.class.isAssignableFrom(actualClass)) {
                @SuppressWarnings("unchecked")
                final Set<String> subclassNames = sessionFactory.getEntityPersister(className)
                        .getEntityMetamodel().getSubclassEntityNames();
                for (final String subclassName : subclassNames) {
                    if (!subclassName.equals(className)) {
                        final Class<?> actualSubclass = Class.forName(subclassName);
                        if (actualSubclass.getSuperclass() == actualClass) {
                            superclasses.put(subclassName, className);
                            subclasses.put(getSimpleName(className), getSimpleName(subclassName));
                        }
                    }
                }
            } else {
                System.err.println("error: mapped class " + className + " is not a " + IObject.class.getName());
            }
        } catch (ClassNotFoundException e) {
            System.err.println("error: could not instantiate class: " + e);
        }
    }
    /* queue for processing all the properties of all the mapped entities: name, type, nullability */
    final Queue<PropertyDetails> propertyQueue = new LinkedList<PropertyDetails>();
    final Map<String, Set<String>> allPropertyNames = new HashMap<String, Set<String>>();
    for (final Map.Entry<String, ClassMetadata> classMetadata : classesMetadata.entrySet()) {
        final String className = classMetadata.getKey();
        final ClassMetadata metadata = classMetadata.getValue();
        final String[] propertyNames = metadata.getPropertyNames();
        final Type[] propertyTypes = metadata.getPropertyTypes();
        final boolean[] propertyNullabilities = metadata.getPropertyNullability();
        for (int i = 0; i < propertyNames.length; i++) {
            if (!ignoreProperty(propertyNames[i])) {
                final List<String> propertyPath = Collections.singletonList(propertyNames[i]);
                propertyQueue.add(new PropertyDetails(className, propertyPath, propertyTypes[i],
                        propertyNullabilities[i]));
            }
        }
        final Set<String> propertyNamesSet = new HashSet<String>(propertyNames.length);
        propertyNamesSet.addAll(Arrays.asList(propertyNames));
        allPropertyNames.put(className, propertyNamesSet);
    }
    /* for linkedBy, X -> Y, Z: class X is linked to by class Y with Y's property Z */
    final SetMultimap<String, Map.Entry<String, String>> linkedBy = HashMultimap.create();
    final SetMultimap<String, String> linkers = HashMultimap.create();
    final SortedMap<String, SortedMap<String, String>> classPropertyReports = new TreeMap<String, SortedMap<String, String>>();
    /* process each property to note entity linkages */
    while (!propertyQueue.isEmpty()) {
        final PropertyDetails property = propertyQueue.remove();
        /* if the property has a component type, queue the parts for processing */
        if (property.type instanceof ComponentType) {
            final ComponentType componentType = (ComponentType) property.type;
            final String[] componentPropertyNames = componentType.getPropertyNames();
            final Type[] componentPropertyTypes = componentType.getSubtypes();
            final boolean[] componentPropertyNullabilities = componentType.getPropertyNullability();
            for (int i = 0; i < componentPropertyNames.length; i++) {
                if (!ignoreProperty(componentPropertyNames[i])) {
                    final List<String> componentPropertyPath = new ArrayList<String>(property.path.size() + 1);
                    componentPropertyPath.addAll(property.path);
                    componentPropertyPath.add(componentPropertyNames[i]);
                    propertyQueue.add(new PropertyDetails(property.holder, componentPropertyPath,
                            componentPropertyTypes[i], componentPropertyNullabilities[i]));
                }
            }
        } else {
            /* determine if this property links to another entity */
            final boolean isAssociatedEntity;
            if (property.type instanceof CollectionType) {
                final CollectionType ct = (CollectionType) property.type;
                isAssociatedEntity = sessionFactory.getCollectionPersister(ct.getRole()).getElementType()
                        .isEntityType();
            } else {
                isAssociatedEntity = property.type instanceof AssociationType;
            }
            /* determine the class and property name for reporting */
            final String holderSimpleName = getSimpleName(property.holder);
            final String propertyPath = Joiner.on('.').join(property.path);
            /* build a report line for this property */
            final StringBuffer sb = new StringBuffer();
            final String valueClassName;
            if (isAssociatedEntity) {
                /* entity linkages by non-inherited properties are recorded */
                final String valueName = ((AssociationType) property.type)
                        .getAssociatedEntityName(sessionFactory);
                final String valueSimpleName = getSimpleName(valueName);
                final Map.Entry<String, String> classPropertyName = Maps.immutableEntry(holderSimpleName,
                        propertyPath);
                linkers.put(holderSimpleName, propertyPath);
                linkedBy.put(valueSimpleName, classPropertyName);
                valueClassName = linkTo(valueSimpleName);
            } else {
                /* find a Sphinx representation for this property value type */
                final UserType userType;
                if (property.type instanceof CustomType) {
                    userType = ((CustomType) property.type).getUserType();
                } else {
                    userType = null;
                }
                if (property.type instanceof EnumType) {
                    valueClassName = "enumeration";
                } else if (userType instanceof GenericEnumType) {
                    @SuppressWarnings("unchecked")
                    final Class<? extends Unit> unitQuantityClass = ((GenericEnumType) userType)
                            .getQuantityClass();
                    valueClassName = "enumeration of " + linkToJavadoc(unitQuantityClass.getName());
                } else if (property.type instanceof ListType || userType instanceof ListAsSQLArrayUserType) {
                    valueClassName = "list";
                } else if (property.type instanceof MapType) {
                    valueClassName = "map";
                } else {
                    valueClassName = "``" + property.type.getName() + "``";
                }
            }
            sb.append(valueClassName);
            if (property.type.isCollectionType()) {
                sb.append(" (multiple)");
            } else if (property.isNullable) {
                sb.append(" (optional)");
            }
            /* determine from which class the property is inherited, if at all */
            String superclassWithProperty = null;
            String currentClass = property.holder;
            while (true) {
                currentClass = superclasses.get(currentClass);
                if (currentClass == null) {
                    break;
                } else if (allPropertyNames.get(currentClass).contains(property.path.get(0))) {
                    superclassWithProperty = currentClass;
                }
            }
            /* check if the property actually comes from an interface */
            final String declaringClassName = superclassWithProperty == null ? property.holder
                    : superclassWithProperty;
            final Class<? extends IObject> interfaceForProperty = getInterfaceForProperty(declaringClassName,
                    property.path.get(0));
            /* report where the property is declared */
            if (superclassWithProperty != null) {
                sb.append(" from ");
                sb.append(linkTo(getSimpleName(superclassWithProperty)));
            } else {
                if (interfaceForProperty != null) {
                    sb.append(", see ");
                    sb.append(linkToJavadoc(interfaceForProperty.getName()));
                }
            }
            SortedMap<String, String> byProperty = classPropertyReports.get(holderSimpleName);
            if (byProperty == null) {
                byProperty = new TreeMap<String, String>();
                classPropertyReports.put(holderSimpleName, byProperty);
            }
            byProperty.put(propertyPath, sb.toString());
        }
    }
    /* the information is gathered, now write the report */
    out.write("Glossary of all OMERO Model Objects\n");
    out.write("===================================\n\n");
    out.write("Overview\n");
    out.write("--------\n\n");
    out.write("Reference\n");
    out.write("---------\n\n");
    for (final Map.Entry<String, SortedMap<String, String>> byClass : classPropertyReports.entrySet()) {
        /* label the class heading */
        final String className = byClass.getKey();
        out.write(".. _" + labelFor(className) + ":\n\n");
        out.write(className + "\n");
        final char[] underline = new char[className.length()];
        for (int i = 0; i < underline.length; i++) {
            underline[i] = '"';
        }
        out.write(underline);
        out.write("\n\n");
        /* note the class' relationships */
        final SortedSet<String> superclassOf = new TreeSet<String>();
        for (final String subclass : subclasses.get(className)) {
            superclassOf.add(linkTo(subclass));
        }
        final SortedSet<String> linkerText = new TreeSet<String>();
        for (final Map.Entry<String, String> linker : linkedBy.get(className)) {
            linkerText.add(linkTo(linker.getKey(), linker.getValue()));
        }
        if (!(superclassOf.isEmpty() && linkerText.isEmpty())) {
            /* write the class' relationships */
            /*
            out.write("Relationships\n");
            out.write("^^^^^^^^^^^^^\n\n");
            */
            if (!superclassOf.isEmpty()) {
                out.write("Subclasses: " + Joiner.on(", ").join(superclassOf) + "\n\n");
            }
            if (!linkerText.isEmpty()) {
                out.write("Used by: " + Joiner.on(", ").join(linkerText) + "\n\n");
            }
        }
        /* write the class' properties */
        /*
        out.write("Properties\n");
        out.write("^^^^^^^^^^\n\n");
        */
        out.write("Properties:\n");
        for (final Map.Entry<String, String> byProperty : byClass.getValue().entrySet()) {
            final String propertyName = byProperty.getKey();
            // if (linkers.containsEntry(className, propertyName)) {
            //     /* label properties that have other entities as values */
            //     out.write(".. _" + labelFor(className, propertyName) + ":\n\n");
            // }
            out.write("  | " + propertyName + ": " + byProperty.getValue() + "\n" /* \n */);
        }
        out.write("\n");
    }
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

private V removeAndNotify(K key, V value) {
    String encodedKey = encodeKey(key);
    byte[] encodedValue = encodeValue(value);
    Timestamp timestamp = timestampProvider.get(Maps.immutableEntry(key, value));
    Optional<MapValue> tombstone = tombstonesDisabled || timestamp == null ? Optional.empty()
            : Optional.of(MapValue.tombstone(timestamp));
    MapValue previousValue = removeInternal(encodedKey, Optional.ofNullable(encodedValue), tombstone);
    V decodedPreviousValue = null;//w w  w . ja  v a  2  s  .c om
    if (previousValue != null) {
        decodedPreviousValue = previousValue.get(this::decodeValue);
        notifyPeers(new UpdateEntry(encodedKey, tombstone.orElse(null)),
                peerUpdateFunction.select(Maps.immutableEntry(key, decodedPreviousValue), membershipService));
        if (previousValue.isAlive()) {
            notifyListeners(new MapDelegateEvent<>(REMOVE, key, decodedPreviousValue));
        }
    }
    return decodedPreviousValue;
}

From source file:com.facebook.buck.features.apple.project.WorkspaceAndProjectGenerator.java

/**
 * Transform a map from scheme name to `TargetNode` to scheme name to the associated `PBXProject`.
 *
 * @param schemeToTargetNodes Map to transform.
 * @return Map of scheme name to associated `PXBProject`s.
 *//*from   w w  w.j a v a2  s. co  m*/
private static ImmutableSetMultimap<String, PBXTarget> mapFromSchemeToPBXProject(
        ImmutableSetMultimap<String, ? extends TargetNode<?>> schemeToTargetNodes,
        ImmutableMap<BuildTarget, PBXTarget> buildTargetToPBXTarget) {
    ImmutableSetMultimap<String, PBXTarget> schemeToPBXProject = ImmutableSetMultimap
            .copyOf(schemeToTargetNodes.entries().stream()
                    .map(stringTargetNodeEntry -> Maps.immutableEntry(stringTargetNodeEntry.getKey(),
                            buildTargetToPBXTarget.get(stringTargetNodeEntry.getValue().getBuildTarget())))
                    .filter(stringPBXTargetEntry -> {
                        return stringPBXTargetEntry.getValue() != null;
                    }).collect(Collectors.toList()));
    return schemeToPBXProject;
}

From source file:cereal.impl.ProtobufMessageMapping.java

@Override
public void update(Iterable<Entry<Key, Value>> iter, InstanceOrBuilder<T> obj) {
    checkNotNull(iter, "Iterable was null");
    checkNotNull(obj, "InstanceOrBuilder was null");
    checkArgument(Type.BUILDER == obj.getType(), "Expected argument to be a builder");

    final GeneratedMessage.Builder<?> builder = (GeneratedMessage.Builder<?>) obj.get();
    final List<Entry<Key, Value>> leftoverFields = new LinkedList<>();

    for (Entry<Key, Value> entry : iter) {
        String fieldName = entry.getKey().getColumnQualifier().toString();

        int index = fieldName.indexOf(PERIOD);
        if (0 <= index) {
            leftoverFields.add(entry);//from   ww  w  .j  av a  2  s  .com
            continue;
        }

        // Find the FieldDescriptor from the Key
        for (FieldDescriptor fieldDesc : builder.getDescriptorForType().getFields()) {
            if (fieldDesc.isRepeated()) {
                int offset = fieldName.lastIndexOf(DOLLAR);
                if (offset < 0) {
                    throw new RuntimeException(
                            "Could not find offset of separator for repeated field count in " + fieldName);
                }
                fieldName = fieldName.substring(0, offset);
            }
            if (fieldName.equals(fieldDesc.getName())) {
                Value value = entry.getValue();
                switch (fieldDesc.getJavaType()) {
                case INT:
                    Integer intVal = Integer.parseInt(value.toString());
                    if (fieldDesc.isRepeated()) {
                        builder.addRepeatedField(fieldDesc, intVal);
                    } else {
                        builder.setField(fieldDesc, intVal);
                    }
                    break;
                case LONG:
                    Long longVal = Long.parseLong(value.toString());
                    if (fieldDesc.isRepeated()) {
                        builder.addRepeatedField(fieldDesc, longVal);
                    } else {
                        builder.setField(fieldDesc, longVal);
                    }
                    break;
                case FLOAT:
                    Float floatVal = Float.parseFloat(value.toString());
                    if (fieldDesc.isRepeated()) {
                        builder.addRepeatedField(fieldDesc, floatVal);
                    } else {
                        builder.setField(fieldDesc, floatVal);
                    }
                    break;
                case DOUBLE:
                    Double doubleVal = Double.parseDouble(value.toString());
                    if (fieldDesc.isRepeated()) {
                        builder.addRepeatedField(fieldDesc, doubleVal);
                    } else {
                        builder.setField(fieldDesc, doubleVal);
                    }
                    break;
                case BOOLEAN:
                    Boolean booleanVal = Boolean.parseBoolean(value.toString());
                    if (fieldDesc.isRepeated()) {
                        builder.addRepeatedField(fieldDesc, booleanVal);
                    } else {
                        builder.setField(fieldDesc, booleanVal);
                    }
                    break;
                case STRING:
                    String strVal = value.toString();
                    if (fieldDesc.isRepeated()) {
                        builder.addRepeatedField(fieldDesc, strVal);
                    } else {
                        builder.setField(fieldDesc, strVal);
                    }
                    break;
                case BYTE_STRING:
                    ByteString byteStrVal = ByteString.copyFrom(entry.getValue().get());
                    if (fieldDesc.isRepeated()) {
                        builder.addRepeatedField(fieldDesc, byteStrVal);
                    } else {
                        builder.setField(fieldDesc, byteStrVal);
                    }
                    break;
                default:
                    log.warn("Ignoring unknown serialized type {}", fieldDesc.getJavaType());
                    break;
                }
                break;
            }
        }
    }

    // All primitives in object should be filled out.
    // Make sure nested messages get filled out too.

    if (!leftoverFields.isEmpty()) {
        for (FieldDescriptor fieldDesc : builder.getDescriptorForType().getFields()) {
            if (JavaType.MESSAGE == fieldDesc.getJavaType()) {
                // For each Key-Value pair which have this prefix as the fieldname (column qualifier)
                final String fieldName = fieldDesc.getName();
                final String singularPrefix = fieldName + PERIOD, repeatedPrefix = fieldName + DOLLAR;

                log.debug("Extracting Key-Value pairs for {}", fieldDesc.getName());

                // Use a TreeMap to ensure the correct repetition order is preserved
                Map<Integer, List<Entry<Key, Value>>> fieldsForNestedMessage = new TreeMap<>();

                final Text _holder = new Text();
                Iterator<Entry<Key, Value>> leftoverFieldsIter = leftoverFields.iterator();
                while (leftoverFieldsIter.hasNext()) {
                    final Entry<Key, Value> entry = leftoverFieldsIter.next();
                    final Key key = entry.getKey();
                    entry.getKey().getColumnQualifier(_holder);

                    String colqual = _holder.toString();
                    if (colqual.startsWith(singularPrefix)) {
                        // Make a copy of the original Key, stripping the prefix off of the qualifier
                        Key copy = new Key(key.getRow(), key.getColumnFamily(),
                                new Text(colqual.substring(singularPrefix.length())), key.getColumnVisibility(),
                                key.getTimestamp());

                        List<Entry<Key, Value>> kvPairs = fieldsForNestedMessage.get(-1);
                        if (null == kvPairs) {
                            kvPairs = new LinkedList<>();
                            fieldsForNestedMessage.put(-1, kvPairs);
                        }
                        kvPairs.add(Maps.immutableEntry(copy, entry.getValue()));

                        // Remove it from the list as we should never have to reread this one again
                        leftoverFieldsIter.remove();
                    } else if (colqual.startsWith(repeatedPrefix)) {
                        // Make a copy of the original Key, stripping the prefix off of the qualifier
                        int index = colqual.indexOf(PERIOD, repeatedPrefix.length());
                        if (0 > index) {
                            throw new RuntimeException("Could not find period after dollar sign: " + colqual);
                        }

                        Integer repetition = Integer
                                .parseInt(colqual.substring(repeatedPrefix.length(), index));

                        Key copy = new Key(key.getRow(), key.getColumnFamily(),
                                new Text(colqual.substring(index + 1)), key.getColumnVisibility(),
                                key.getTimestamp());

                        List<Entry<Key, Value>> kvPairs = fieldsForNestedMessage.get(repetition);
                        if (null == kvPairs) {
                            kvPairs = new LinkedList<>();
                            fieldsForNestedMessage.put(repetition, kvPairs);
                        }
                        kvPairs.add(Maps.immutableEntry(copy, entry.getValue()));

                        // Remove it from the list as we should never have to reread this one again
                        leftoverFieldsIter.remove();
                    }
                }

                if (!fieldsForNestedMessage.isEmpty()) {
                    // We have keys, pass them down to the nested message
                    String nestedMsgClzName = getClassName(fieldDesc);

                    log.debug("Found {} Key-Value pairs for {}. Reconstituting the message.",
                            fieldsForNestedMessage.size(), nestedMsgClzName);

                    try {
                        @SuppressWarnings("unchecked")
                        // Get the class, builder and InstanceOrBuilder for the nested message
                        Class<GeneratedMessage> msgClz = (Class<GeneratedMessage>) Class
                                .forName(nestedMsgClzName);
                        Method newBuilderMethod = msgClz.getMethod("newBuilder");

                        for (Entry<Integer, List<Entry<Key, Value>>> pairsPerRepetition : fieldsForNestedMessage
                                .entrySet()) {
                            Message.Builder subBuilder = (Message.Builder) newBuilderMethod.invoke(null);
                            InstanceOrBuilder<GeneratedMessage> subIob = new InstanceOrBuilderImpl<>(subBuilder,
                                    msgClz);

                            // Get the mapping from the registry
                            ProtobufMessageMapping<GeneratedMessage> subMapping = (ProtobufMessageMapping<GeneratedMessage>) registry
                                    .get(subIob);

                            // Invoke update on the mapping with the subset of Key-Values
                            subMapping.update(pairsPerRepetition.getValue(), subIob);

                            // Set the result on the top-level obj
                            if (fieldDesc.isRepeated()) {
                                builder.addRepeatedField(fieldDesc, subBuilder.build());
                            } else {
                                builder.setField(fieldDesc, subBuilder.build());
                            }
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                // No fields for the sub message, therefore it's empty
                log.debug("Found no Key-Value pairs for {}", fieldName);
            }
            // Not a message, so we can ignore it
        }

        if (!leftoverFields.isEmpty()) {
            log.warn("Found {} leftover Key-Value pairs that were not consumed", leftoverFields.size());
        }
    }
}

From source file:org.onosproject.store.primitives.resources.impl.AtomixConsistentMapService.java

/**
 * Handles a entry set commit.//from  w w  w.ja  va  2 s.  c  o m
 *
 * @return set of map entries
 */
protected Set<Map.Entry<String, Versioned<byte[]>>> entrySet() {
    return entries().entrySet().stream()
            .filter(entry -> entry.getValue().type() != MapEntryValue.Type.TOMBSTONE)
            .map(e -> Maps.immutableEntry(e.getKey(), toVersioned(e.getValue()))).collect(Collectors.toSet());
}

From source file:io.prestosql.Session.java

public Session withDefaultProperties(Map<String, String> systemPropertyDefaults,
        Map<String, Map<String, String>> catalogPropertyDefaults) {
    requireNonNull(systemPropertyDefaults, "systemPropertyDefaults is null");
    requireNonNull(catalogPropertyDefaults, "catalogPropertyDefaults is null");

    // to remove this check properties must be authenticated and validated as in beginTransactionId
    checkState(!this.transactionId.isPresent() && this.connectorProperties.isEmpty(),
            "Session properties cannot be overridden once a transaction is active");

    Map<String, String> systemProperties = new HashMap<>();
    systemProperties.putAll(systemPropertyDefaults);
    systemProperties.putAll(this.systemProperties);

    Map<String, Map<String, String>> connectorProperties = catalogPropertyDefaults.entrySet().stream()
            .map(entry -> Maps.immutableEntry(entry.getKey(), new HashMap<>(entry.getValue())))
            .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
    for (Entry<String, Map<String, String>> catalogProperties : this.unprocessedCatalogProperties.entrySet()) {
        String catalog = catalogProperties.getKey();
        for (Entry<String, String> entry : catalogProperties.getValue().entrySet()) {
            connectorProperties.computeIfAbsent(catalog, id -> new HashMap<>()).put(entry.getKey(),
                    entry.getValue());/*from w w w  . j  av  a2  s  .  c  o  m*/
        }
    }

    return new Session(queryId, transactionId, clientTransactionSupport, identity, source, catalog, schema,
            path, traceToken, timeZoneKey, locale, remoteUserAddress, userAgent, clientInfo, clientTags,
            clientCapabilities, resourceEstimates, startTime, systemProperties, ImmutableMap.of(),
            connectorProperties, sessionPropertyManager, preparedStatements);
}