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:com.hanhuy.keepassj.PwDatabase.java

private <T extends IStructureItem & IDeepCloneable<T>> void ReorderObjectList(PwObjectList<T> vItems,
        PwObjectPool ppOrgStructure, PwObjectPool ppSrcStructure, boolean bEntries) {
    if (!ObjectListRequiresReorder(vItems, ppOrgStructure, ppSrcStructure, bEntries))
        return;//from   ww w.j av  a 2s  .  c  o m

    PwObjectList<T> vOrgListItems = vItems.CloneShallow();

    Queue<Map.Entry<Integer, Integer>> qToDo = new LinkedList<Map.Entry<Integer, Integer>>();
    qToDo.add(Maps.immutableEntry(0, vItems.getUCount() - 1));

    while (qToDo.size() > 0) {
        if ((m_slStatus != null) && !m_slStatus.ContinueWork())
            break;

        Map.Entry<Integer, Integer> kvp = qToDo.poll();
        if (kvp.getValue() <= kvp.getKey()) {
            assert false;
            continue;
        }

        Queue<PwUuid> qRelBefore = new LinkedList<PwUuid>();
        Queue<PwUuid> qRelAfter = new LinkedList<PwUuid>();
        int uPivot = FindLocationChangedPivot(vItems, kvp, ppOrgStructure, ppSrcStructure, qRelBefore,
                qRelAfter, bEntries);
        T ptPivot = vItems.GetAt(uPivot);

        List<T> vToSort = vItems.GetRange(kvp.getKey(), kvp.getValue());
        Queue<T> qBefore = new LinkedList<T>();
        Queue<T> qAfter = new LinkedList<T>();
        boolean bBefore = true;

        for (T pt : vToSort) {
            if (pt == ptPivot) {
                bBefore = false;
                continue;
            }

            boolean bAdded = false;
            for (PwUuid puBefore : qRelBefore) {
                if (puBefore.Equals(pt.getUuid())) {
                    qBefore.add(pt);
                    bAdded = true;
                    break;
                }
            }
            if (bAdded)
                continue;

            for (PwUuid puAfter : qRelAfter) {
                if (puAfter.Equals(pt.getUuid())) {
                    qAfter.add(pt);
                    bAdded = true;
                    break;
                }
            }
            if (bAdded)
                continue;

            if (bBefore)
                qBefore.add(pt);
            else
                qAfter.add(pt);
        }
        assert bBefore == false;

        int uPos = kvp.getKey();
        while (qBefore.size() > 0)
            vItems.SetAt(uPos++, qBefore.poll());
        vItems.SetAt(uPos++, ptPivot);
        while (qAfter.size() > 0)
            vItems.SetAt(uPos++, qAfter.poll());
        assert uPos == (kvp.getValue() + 1);

        int iNewPivot = vItems.IndexOf(ptPivot);
        if ((iNewPivot < (int) kvp.getKey()) || (iNewPivot > (int) kvp.getValue())) {
            assert false;
            continue;
        }

        if ((iNewPivot - 1) > (int) kvp.getKey())
            qToDo.add(Maps.immutableEntry(kvp.getKey(), (int) (iNewPivot - 1)));

        if ((iNewPivot + 1) < (int) kvp.getValue())
            qToDo.add(Maps.immutableEntry((int) (iNewPivot + 1), kvp.getValue()));
    }

    if (false) { // debug
        for (T ptItem : vOrgListItems) {
            assert vItems.IndexOf(ptItem) >= 0;
        }
    }
}

From source file:org.apache.accumulo.core.client.mapreduce.lib.impl.InputConfigurator.java

/**
 * Returns the {@link org.apache.accumulo.core.client.mapreduce.InputTableConfig} for the configuration based on the properties set using the single-table
 * input methods.//from w  ww  .  j av a  2 s .  c o  m
 *
 * @param implementingClass
 *          the class whose name will be used as a prefix for the property configuration key
 * @param conf
 *          the Hadoop instance for which to retrieve the configuration
 * @return the config object built from the single input table properties set on the job
 * @since 1.6.0
 */
protected static Map.Entry<String, InputTableConfig> getDefaultInputTableConfig(Class<?> implementingClass,
        Configuration conf) {
    String tableName = getInputTableName(implementingClass, conf);
    if (tableName != null) {
        InputTableConfig queryConfig = new InputTableConfig();
        List<IteratorSetting> itrs = getIterators(implementingClass, conf);
        if (itrs != null)
            queryConfig.setIterators(itrs);
        Set<Pair<Text, Text>> columns = getFetchedColumns(implementingClass, conf);
        if (columns != null)
            queryConfig.fetchColumns(columns);
        List<Range> ranges = null;
        try {
            ranges = getRanges(implementingClass, conf);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (ranges != null)
            queryConfig.setRanges(ranges);

        SamplerConfiguration samplerConfig = getSamplerConfiguration(implementingClass, conf);
        if (samplerConfig != null) {
            queryConfig.setSamplerConfiguration(samplerConfig);
        }

        queryConfig.setAutoAdjustRanges(getAutoAdjustRanges(implementingClass, conf))
                .setUseIsolatedScanners(isIsolated(implementingClass, conf))
                .setUseLocalIterators(usesLocalIterators(implementingClass, conf))
                .setOfflineScan(isOfflineScan(implementingClass, conf));
        return Maps.immutableEntry(tableName, queryConfig);
    }
    return null;
}

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

/**
 * Sets a permission node, applying a temporary modifier if the node is temporary.
 * @param node the node to set/*w w  w . j  av  a  2s .  c  om*/
 * @param modifier the modifier to use for the operation
 * @return the node that was actually set, respective of the modifier
 */
public Map.Entry<DataMutateResult, Node> setPermission(Node node, TemporaryModifier modifier) {
    // If the node is temporary, we should take note of the modifier
    if (node.isTemporary()) {
        if (modifier == TemporaryModifier.ACCUMULATE) {
            // Try to accumulate with an existing node
            Optional<Node> existing = getAlmostEquals(node, false);

            // An existing node was found
            if (existing.isPresent()) {
                Node previous = existing.get();

                // Create a new node with the same properties, but add the expiry dates together
                Node newNode = NodeFactory.builderFromExisting(node)
                        .setExpiry(previous.getExpiryUnixTime() + node.getSecondsTilExpiry()).build();

                ImmutableCollection<Node> before = getEnduringNodes().values();

                // Remove the old node & add the new one.
                nodesLock.lock();
                try {
                    nodes.remove(previous.getFullContexts().makeImmutable(), previous);
                    nodes.put(newNode.getFullContexts().makeImmutable(), newNode);
                } finally {
                    nodesLock.unlock();
                }

                invalidateCache();
                ImmutableCollection<Node> after = getEnduringNodes().values();
                plugin.getApiProvider().getEventFactory().handleNodeAdd(newNode, this, before, after);
                return Maps.immutableEntry(DataMutateResult.SUCCESS, newNode);
            }

        } else if (modifier == TemporaryModifier.REPLACE) {
            // Try to replace an existing node
            Optional<Node> existing = getAlmostEquals(node, false);

            // An existing node was found
            if (existing.isPresent()) {
                Node previous = existing.get();

                // Only replace if the new expiry time is greater than the old one.
                if (node.getExpiryUnixTime() > previous.getExpiryUnixTime()) {

                    ImmutableCollection<Node> before = getEnduringNodes().values();

                    nodesLock.lock();
                    try {
                        nodes.remove(previous.getFullContexts().makeImmutable(), previous);
                        nodes.put(node.getFullContexts().makeImmutable(), node);
                    } finally {
                        nodesLock.unlock();
                    }

                    invalidateCache();
                    ImmutableCollection<Node> after = getEnduringNodes().values();
                    plugin.getApiProvider().getEventFactory().handleNodeAdd(node, this, before, after);
                    return Maps.immutableEntry(DataMutateResult.SUCCESS, node);
                }
            }
        }

        // DENY behaviour is the default anyways.
    }

    // Fallback to the normal handling.
    return Maps.immutableEntry(setPermission(node), node);
}

From source file:me.lucko.luckperms.common.storage.backing.MSSQLBacking.java

/**
 * Compares two sets/*from w  ww  .j av a2s. c  o  m*/
 * @param local the local set
 * @param remote the remote set
 * @return the entries to add to remote, and the entries to remove from remote
 */
private static Map.Entry<Set<NodeDataHolder>, Set<NodeDataHolder>> compareSets(Set<NodeDataHolder> local,
        Set<NodeDataHolder> remote) {
    // entries in local but not remote need to be added
    // entries in remote but not local need to be removed

    Set<NodeDataHolder> toAdd = new HashSet<>(local);
    toAdd.removeAll(remote);

    Set<NodeDataHolder> toRemove = new HashSet<>(remote);
    toRemove.removeAll(local);

    return Maps.immutableEntry(toAdd, toRemove);
}

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

/**
 * Load a specific link property's object relationships into the various cache fields of {@link Planning}.
 * @param linkProperty the link property being processed
 * @param query the HQL to query the property's object relationships
 * @param ids the IDs of the related objects
 * @return which linker objects are related to which linked objects by the given property
 * @throws GraphException if the objects could not be converted to unloaded instances
 *//*from  www.  j a va  2s .com*/
private List<Entry<CI, CI>> getLinksToCache(CP linkProperty, String query, Collection<Long> ids)
        throws GraphException {
    final String linkedClassName = getLinkedClass(linkProperty);
    final boolean propertyIsAccessible = model.isPropertyAccessible(linkProperty.className,
            linkProperty.propertyName);
    final SetMultimap<Long, Long> linkerToLinked = HashMultimap.create();
    for (final List<Long> idsBatch : Iterables.partition(ids, BATCH_SIZE)) {
        for (final Object[] result : (List<Object[]>) session.createQuery(query)
                .setParameterList("ids", idsBatch).list()) {
            linkerToLinked.put((Long) result[0], (Long) result[1]);
        }
    }
    final List<Entry<CI, CI>> linkerLinked = new ArrayList<Entry<CI, CI>>();
    final Map<Long, CI> linkersById = findObjectDetails(linkProperty.className, linkerToLinked.keySet());
    final Map<Long, CI> linkedsById = findObjectDetails(linkedClassName,
            new HashSet<Long>(linkerToLinked.values()));
    for (final Entry<Long, Long> linkerIdLinkedId : linkerToLinked.entries()) {
        final CI linker = linkersById.get(linkerIdLinkedId.getKey());
        final CI linked = linkedsById.get(linkerIdLinkedId.getValue());
        if (!planning.detailsNoted.containsKey(linker)) {
            log.warn("failed to query for " + linker);
        } else if (!planning.detailsNoted.containsKey(linked)) {
            log.warn("failed to query for " + linked);
        } else {
            linkerLinked.add(Maps.immutableEntry(linker, linked));
            if (propertyIsAccessible) {
                planning.befores.put(linked, linker);
                planning.afters.put(linker, linked);
            }
            if (log.isDebugEnabled()) {
                log.debug(linkProperty.toCPI(linker.id) + " links to " + linked);
            }
        }
    }
    return linkerLinked;
}

From source file:me.lucko.luckperms.common.storage.dao.sql.SqlDao.java

/**
 * Compares two sets//from   w w w .  java  2  s .  c  o  m
 * @param local the local set
 * @param remote the remote set
 * @return the entries to add to remote, and the entries to remove from remote
 */
private static Map.Entry<Set<NodeModel>, Set<NodeModel>> compareSets(Set<NodeModel> local,
        Set<NodeModel> remote) {
    // entries in local but not remote need to be added
    // entries in remote but not local need to be removed

    Set<NodeModel> toAdd = new HashSet<>(local);
    toAdd.removeAll(remote);

    Set<NodeModel> toRemove = new HashSet<>(remote);
    toRemove.removeAll(local);

    return Maps.immutableEntry(toAdd, toRemove);
}

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

@Override
public void addGarbageCollectionSentinelValues(String tableName, Set<Cell> cells) {
    try {/*from w ww  . j  ava2 s .c  o m*/
        final Value value = Value.create(new byte[0], Value.INVALID_VALUE_TIMESTAMP);
        putInternal(tableName, Iterables.transform(cells, new Function<Cell, Map.Entry<Cell, Value>>() {
            @Override
            public Entry<Cell, Value> apply(Cell cell) {
                return Maps.immutableEntry(cell, value);
            }
        }), TransactionType.NONE);
    } catch (Throwable t) {
        throw Throwables.throwUncheckedException(t);
    }
}

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

/**
 * Note a linked object to remove from a linker property's {@link Collection} value.
 * @param linkerToIdToLinked the map from linker property to linker ID to objects in {@link Collection}s
 * @param linker the linker object/*from   ww w.  j a va 2  s  . c om*/
 * @param linked the linked object
 */
private void addRemoval(Map<CP, SetMultimap<Long, Entry<String, Long>>> linkerToIdToLinked, CPI linker,
        CI linked) {
    if (model.isPropertyAccessible(linker.className, linker.propertyName)) {
        SetMultimap<Long, Entry<String, Long>> idMap = linkerToIdToLinked.get(linker.toCP());
        if (idMap == null) {
            idMap = HashMultimap.create();
            linkerToIdToLinked.put(linker.toCP(), idMap);
        }
        idMap.put(linker.id, Maps.immutableEntry(linked.className, linked.id));
    }
}

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

/**
 * Prepare to process the targeted model objects.
 * @return the actual processor for the targeted model objects, to be used by the caller
 * @throws GraphException if the user does not have permission to process the targets or
 * if a cycle is detected in the model object graph
 *///from  ww w .  ja  va 2  s .  c om
public PlanExecutor processTargets() throws GraphException {
    if (!progress.contains(Milestone.PLANNED)) {
        throw new IllegalStateException("operation not yet planned");
    }
    final List<Entry<Map<String, Collection<Long>>, Map<String, Collection<Long>>>> toJoinAndDelete = new ArrayList<Entry<Map<String, Collection<Long>>, Map<String, Collection<Long>>>>();
    /* process the targets forward across links */
    while (!planning.blockedBy.isEmpty()) {
        /* determine which objects can be processed in this step */
        final Collection<CI> nowUnblocked = new HashSet<CI>();
        final Iterator<Entry<CI, Set<CI>>> blocks = planning.blockedBy.entrySet().iterator();
        while (blocks.hasNext()) {
            final Entry<CI, Set<CI>> block = blocks.next();
            final CI object = block.getKey();
            if (block.getValue().isEmpty()) {
                blocks.remove();
                nowUnblocked.add(object);
            }
        }
        if (nowUnblocked.isEmpty()) {
            throw new GraphException(
                    "cycle detected among " + Joiner.on(", ").join(planning.blockedBy.keySet()));
        }
        for (final Set<CI> blockers : planning.blockedBy.values()) {
            blockers.removeAll(nowUnblocked);
        }
        final SetMultimap<String, Long> toJoin = HashMultimap.create();
        final SetMultimap<String, Long> toDelete = HashMultimap.create();
        for (final CI object : nowUnblocked) {
            if (planning.included.contains(object)) {
                toJoin.put(object.className, object.id);
            } else {
                toDelete.put(object.className, object.id);
            }
        }
        /* note this group's includes and deletes */
        final Map<String, Collection<Long>> eachToJoin = toJoin.asMap();
        for (final Entry<String, Collection<Long>> oneClassToJoin : eachToJoin.entrySet()) {
            final String className = oneClassToJoin.getKey();
            final Collection<Long> allIds = oneClassToJoin.getValue();
            assertMayBeProcessed(className, allIds);
        }
        final Map<String, Collection<Long>> eachToDelete = toDelete.asMap();
        for (final Entry<String, Collection<Long>> oneClassToDelete : eachToDelete.entrySet()) {
            final String className = oneClassToDelete.getKey();
            final Collection<Long> allIds = oneClassToDelete.getValue();
            assertMayBeDeleted(className, allIds);
        }
        toJoinAndDelete.add(Maps.immutableEntry(eachToJoin, eachToDelete));
    }
    return new PlanExecutor() {
        @Override
        public void execute() throws GraphException {
            if (!progress.contains(Milestone.UNLINKED)) {
                throw new IllegalStateException("model objects not yet unlinked");
            }
            if (progress.contains(Milestone.PROCESSED)) {
                throw new IllegalStateException("model objects already processed");
            }
            /* actually do the noted processing */
            for (final Entry<Map<String, Collection<Long>>, Map<String, Collection<Long>>> next : toJoinAndDelete) {
                final Map<String, Collection<Long>> toJoin = next.getKey();
                final Map<String, Collection<Long>> toDelete = next.getValue();
                /* perform this group's deletes */
                if (!toDelete.isEmpty()) {
                    for (final Entry<String, Collection<Long>> oneClassToDelete : toDelete.entrySet()) {
                        final String className = oneClassToDelete.getKey();
                        final Collection<Long> allIds = oneClassToDelete.getValue();
                        final Collection<Collection<Long>> idGroups;
                        if (OriginalFile.class.getName().equals(className)) {
                            idGroups = ModelObjectSequencer.sortOriginalFileIds(session, allIds);
                        } else {
                            idGroups = Collections.singleton(allIds);
                        }
                        for (final Collection<Long> idGroup : idGroups) {
                            for (final List<Long> ids : Iterables.partition(idGroup, BATCH_SIZE)) {
                                processor.deleteInstances(className, ids);
                            }
                        }
                    }
                }
                /* perform this group's includes */
                if (!toJoin.isEmpty()) {
                    for (final Entry<String, Collection<Long>> oneClassToJoin : toJoin.entrySet()) {
                        final String className = oneClassToJoin.getKey();
                        final Collection<Long> allIds = oneClassToJoin.getValue();
                        for (final List<Long> ids : Iterables.partition(allIds, BATCH_SIZE)) {
                            processor.processInstances(className, ids);
                        }
                    }
                }
            }
            progress.add(Milestone.PROCESSED);
        }
    };
}

From source file:com.hanhuy.keepassj.KdbxFile.java

private void WriteList(String name, AutoTypeConfig cfgAutoType) throws IOException {
    assert name != null;
    assert cfgAutoType != null;
    if (cfgAutoType == null)
        throw new IllegalArgumentException("cfgAutoType");

    m_xmlWriter.startTag(null, name);//from   w w  w.ja va2 s  . c  om

    WriteObject(ElemAutoTypeEnabled, cfgAutoType.isEnabled());
    WriteObject(ElemAutoTypeObfuscation, cfgAutoType.getObfuscationOptions().ordinal());

    if (cfgAutoType.getDefaultSequence().length() > 0)
        WriteObject(ElemAutoTypeDefaultSeq, cfgAutoType.getDefaultSequence(), true);

    for (AutoTypeAssociation a : cfgAutoType.getAssociations())
        WriteObject(ElemAutoTypeItem, ElemWindow, ElemKeystrokeSequence,
                Maps.immutableEntry(a.getWindowName(), a.getSequence()));

    m_xmlWriter.endTag(null, name);
}