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.commands.utils.Util.java

public static Map.Entry<FancyMessage, String> searchUserResultToMessage(List<HeldPermission<UUID>> results,
        Function<UUID, String> uuidLookup, String label, int pageNumber) {
    if (results.isEmpty()) {
        return Maps.immutableEntry(new FancyMessage("None").color(ChatColor.getByChar('3')), null);
    }//w w w .j av  a2 s  . co  m

    List<HeldPermission<UUID>> sorted = new ArrayList<>(results);
    sorted.sort(Comparator.comparing(HeldPermission::getHolder));

    int index = pageNumber - 1;
    List<List<HeldPermission<UUID>>> pages = divideList(sorted, 15);

    if ((index < 0 || index >= pages.size())) {
        pageNumber = 1;
        index = 0;
    }

    List<HeldPermission<UUID>> page = pages.get(index);
    List<Map.Entry<String, HeldPermission<UUID>>> uuidMappedPage = page.stream()
            .map(hp -> Maps.immutableEntry(uuidLookup.apply(hp.getHolder()), hp)).collect(Collectors.toList());

    FancyMessage message = new FancyMessage("");
    String title = "&7(page &f" + pageNumber + "&7 of &f" + pages.size() + "&7 - &f" + sorted.size()
            + "&7 entries)";

    for (Map.Entry<String, HeldPermission<UUID>> ent : uuidMappedPage) {
        message = makeFancy(ent.getKey(), false, label, ent.getValue(),
                message.then("> ").color(ChatColor.getByChar('3')));
        message = makeFancy(ent.getKey(), false, label, ent.getValue(),
                message.then(ent.getKey()).color(ChatColor.getByChar('b')));
        message = makeFancy(ent.getKey(), false, label, ent.getValue(),
                message.then(" - ").color(ChatColor.getByChar('7')));
        message = makeFancy(ent.getKey(), false, label, ent.getValue(),
                message.then("" + ent.getValue().getValue()).color(
                        ent.getValue().getValue() ? ChatColor.getByChar('a') : ChatColor.getByChar('c')));
        message = appendNodeExpiry(ent.getValue().asNode(), message);
        message = appendNodeContextDescription(ent.getValue().asNode(), message);
        message = message.then("\n");
    }

    return Maps.immutableEntry(message, title);
}

From source file:ninja.leaping.permissionsex.backend.file.FileDataStore.java

@Override
public Iterable<Map.Entry<Map.Entry<String, String>, ImmutableSubjectData>> getAll() {
    return Iterables.concat(Iterables.transform(getSubjectsNode().getChildrenMap().keySet(), type -> {
        if (type == null) {
            return null;
        }/*from   w  ww . java 2 s. co m*/

        final String typeStr = type.toString();

        return Iterables.transform(getAll(typeStr), input2 -> Maps
                .immutableEntry(Maps.immutableEntry(type.toString(), input2.getKey()), input2.getValue()));
    }));
}

From source file:net.slashies.phpBridge.Dispatch.java

private BiFunction<Object, List<Object>, Object> resolveMethod(final CallSignature sig) {
    final List<Executable> methods;
    final boolean isConstructor = sig.methodName.equals("new");

    if (isConstructor) {
        methods = Arrays.stream(sig.targetType.getConstructors()).collect(Collectors.toList());
    } else {/*from   w  w w  .  j  a  v a2s. c om*/
        methods = Arrays.stream(sig.targetType.getMethods()).distinct()
                .flatMap(m -> findPublicDeclarations(m, sig.targetType)).collect(Collectors.toList());
    }

    final Set<Executable> potentials = methods.stream()
            .filter(m -> (isConstructor ? sig.targetType.getName() : sig.methodName).equals(m.getName()))
            .filter(e -> Modifier.isPublic(e.getModifiers()))
            .filter(e -> isCorrectArity(sig.argTypes.length, e)).collect(Collectors.toSet());

    final List<Executable> castMatches = potentials.stream().filter(e -> testCastMatch(sig, e))
            .collect(Collectors.toList());

    if (castMatches.size() >= 1 && hasTotalOrderOverArgs(castMatches)) {
        final Executable min;
        if (isConstructor) {
            min = castMatches.stream()
                    .min(Comparator.comparing(Function.identity(), Dispatch::argumentPartialOrder)).get();
        } else {
            min = ((Collection<Method>) (Collection) castMatches).stream()
                    .min(Comparator.comparing(Function.<Method>identity(), Dispatch::argumentPartialOrder)
                            .thenComparing(Method::getReturnType, Dispatch::compareClasses))
                    .get();
        }

        return isConstructor ? wrapConstructor(min) : wrapMethod(min);
    }

    if (castMatches.size() > 1)
        throw new AmbigiousDispatchException(sig);

    // If there is no exact match then we have to attempt to coerce the types to match
    // If this doesn't produce exactly one target then we give up
    // Better to fail then produce an unpredictable result

    final List<Map.Entry<Executable, Function<List<Object>, List<Object>>>> coercions = potentials
            .parallelStream().map(e -> Maps.immutableEntry(e, Optional.ofNullable(tryCoerceArgs(sig, e))))
            .filter(e -> e.getValue().isPresent()).map(e -> Maps.immutableEntry(e.getKey(), e.getValue().get()))
            .collect(Collectors.toList());

    if (coercions.isEmpty())
        throw new UnknownDispatchException(sig);
    else if (coercions.size() > 1)
        throw new AmbigiousDispatchException(sig);

    final Map.Entry<Executable, Function<List<Object>, List<Object>>> target = coercions.get(0);
    final Function<List<Object>, List<Object>> coercion = target.getValue();
    final BiFunction<Object, List<Object>, Object> mh;
    if (isConstructor)
        mh = wrapConstructor(target.getKey());
    else
        mh = wrapMethod(target.getKey());

    return (o, args) -> mh.apply(o, coercion.apply(args));
}

From source file:org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl.java

@GuardedBy("configTransactionLock")
private ConfigTransactionControllerInternal beginConfigSafe(boolean blankTransaction) {
    versionCounter++;/*from  w w w . j a v  a2s . c o  m*/
    final String transactionName = "ConfigTransaction-" + version + "-" + versionCounter;

    TransactionJMXRegistratorFactory factory = new TransactionJMXRegistratorFactory() {
        @Override
        public TransactionJMXRegistrator create() {
            return baseJMXRegistrator.createTransactionJMXRegistrator(transactionName);
        }
    };

    Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories = new HashMap<>(
            resolver.getAllFactories());

    // add all factories that disappeared from SR but are still committed
    for (ModuleInternalInfo moduleInternalInfo : currentConfig.getEntries()) {
        String name = moduleInternalInfo.getModuleFactory().getImplementationName();
        if (allCurrentFactories.containsKey(name) == false) {
            LOG.trace("Factory {} not found in SR, using reference from previous commit", name);
            allCurrentFactories.put(name, Maps.immutableEntry(moduleInternalInfo.getModuleFactory(),
                    moduleInternalInfo.getBundleContext()));
        }
    }
    allCurrentFactories = Collections.unmodifiableMap(allCurrentFactories);

    // closed by transaction controller
    ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry(
            new TransactionIdentifier(transactionName), factory, allCurrentFactories);
    SearchableServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl
            .createSRWritableRegistry(readableSRRegistry, txLookupRegistry, allCurrentFactories);

    ConfigTransactionControllerInternal transactionController = new ConfigTransactionControllerImpl(
            txLookupRegistry, version, bindingContextProvider, versionCounter, allCurrentFactories,
            transactionsMBeanServer, configMBeanServer, blankTransaction, writableRegistry);
    try {
        txLookupRegistry.registerMBean(transactionController, transactionController.getControllerObjectName());
    } catch (InstanceAlreadyExistsException e) {
        throw new IllegalStateException(e);
    }
    transactionController.copyExistingModulesAndProcessFactoryDiff(currentConfig.getEntries(),
            lastListOfFactories);
    transactionsHolder.add(transactionName, transactionController, txLookupRegistry);
    return transactionController;
}

From source file:org.apache.accumulo.tserver.session.SessionManager.java

public synchronized List<ActiveScan> getActiveScans() {

    final List<ActiveScan> activeScans = new ArrayList<ActiveScan>();
    final long ct = System.currentTimeMillis();
    final Set<Entry<Long, Session>> copiedIdleSessions = new HashSet<Entry<Long, Session>>();

    synchronized (idleSessions) {
        /**/*from   ww w .  j a  v  a 2s .co m*/
         * Add sessions so that get the list returned in the active scans call
         */
        for (Session session : idleSessions) {
            copiedIdleSessions.add(Maps.immutableEntry(expiredSessionMarker, session));
        }
    }

    for (Entry<Long, Session> entry : Iterables.concat(sessions.entrySet(), copiedIdleSessions)) {
        Session session = entry.getValue();
        if (session instanceof ScanSession) {
            ScanSession ss = (ScanSession) session;

            ScanState state = ScanState.RUNNING;

            ScanTask<ScanBatch> nbt = ss.nextBatchTask;
            if (nbt == null) {
                state = ScanState.IDLE;
            } else {
                switch (nbt.getScanRunState()) {
                case QUEUED:
                    state = ScanState.QUEUED;
                    break;
                case FINISHED:
                    state = ScanState.IDLE;
                    break;
                case RUNNING:
                default:
                    /* do nothing */
                    break;
                }
            }

            ActiveScan activeScan = new ActiveScan(ss.client, ss.getUser(), ss.extent.getTableId(),
                    ct - ss.startTime, ct - ss.lastAccessTime, ScanType.SINGLE, state, ss.extent.toThrift(),
                    Translator.translate(ss.columnSet, Translators.CT), ss.ssiList, ss.ssio,
                    ss.auths.getAuthorizationsBB(), ss.context);

            // scanId added by ACCUMULO-2641 is an optional thrift argument and not available in ActiveScan constructor
            activeScan.setScanId(entry.getKey());
            activeScans.add(activeScan);

        } else if (session instanceof MultiScanSession) {
            MultiScanSession mss = (MultiScanSession) session;

            ScanState state = ScanState.RUNNING;

            ScanTask<MultiScanResult> nbt = mss.lookupTask;
            if (nbt == null) {
                state = ScanState.IDLE;
            } else {
                switch (nbt.getScanRunState()) {
                case QUEUED:
                    state = ScanState.QUEUED;
                    break;
                case FINISHED:
                    state = ScanState.IDLE;
                    break;
                case RUNNING:
                default:
                    /* do nothing */
                    break;
                }
            }

            activeScans.add(new ActiveScan(mss.client, mss.getUser(), mss.threadPoolExtent.getTableId(),
                    ct - mss.startTime, ct - mss.lastAccessTime, ScanType.BATCH, state,
                    mss.threadPoolExtent.toThrift(), Translator.translate(mss.columnSet, Translators.CT),
                    mss.ssiList, mss.ssio, mss.auths.getAuthorizationsBB(), mss.context));
        }
    }

    return activeScans;
}

From source file:ninja.leaping.permissionsex.PermissionsEx.java

public void uncache(String type, String identifier) {
    SubjectCache cache = subjectCaches.get(type);
    if (cache != null) {
        cache.invalidate(identifier);//from w w  w .ja  v  a2s  .  c om
    }
    cache = transientSubjectCaches.get(type);
    if (cache != null) {
        cache.invalidate(identifier);
    }
    calculatedSubjects.invalidate(Maps.immutableEntry(type, identifier));
}

From source file:org.obm.push.mail.MailBackendImpl.java

private List<Entry<MailboxPath, FolderType>> generateSpecialFolders() {
    return ImmutableList.of(
            Maps.immutableEntry(MailboxPath.of(OpushEmailConfiguration.IMAP_INBOX_NAME),
                    FolderType.DEFAULT_INBOX_FOLDER),
            Maps.immutableEntry(MailboxPath.of(emailConfiguration.imapMailboxDraft()),
                    FolderType.DEFAULT_DRAFTS_FOLDER),
            Maps.immutableEntry(MailboxPath.of(emailConfiguration.imapMailboxSent()),
                    FolderType.DEFAULT_SENT_EMAIL_FOLDER),
            Maps.immutableEntry(MailboxPath.of(emailConfiguration.imapMailboxTrash()),
                    FolderType.DEFAULT_DELETED_ITEMS_FOLDER));
}

From source file:org.eclipse.emf.compare.rcp.ui.internal.util.ResourceUIUtil.java

/**
 * Get the first loaded parent of the given resource (represented by its URI) contained in the given
 * ResourceSet.//w  w w. ja va2  s . co m
 * <p>
 * If at some point of the process the current resource (represented by its URI) has several parents, this
 * method will return <code>null</code>.
 * 
 * @param rs
 *            the ResourceSet in which the first loaded parent must be found.
 * @param uri
 *            the URI of the resource for which we want to get its first loaded parent.
 * @return an entry composed with the first loaded EObject parent of the given resource (represented by
 *         its URI) and the Resource associated if found, <code>null</code> otherwise.
 */
private static Entry<URI, Resource> getResourceParent(ResourceSet rs, URI uri) {
    Entry<URI, Resource> entry = null;
    final IGraphView<URI> graph = getResourcesURIGraph();
    if (uri != null && graph != null) {
        URI parentData = graph.getParentData(uri);
        if (parentData != null) {
            URI parent = parentData.trimFragment();
            Resource resourceParent = rs.getResource(parent, false);
            if (resourceParent != null) {
                entry = Maps.immutableEntry(parentData, resourceParent);
            } else {
                entry = getResourceParent(rs, parent);
            }
        }
    }
    return entry;
}

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

protected Set<Map.Entry<String, Versioned<byte[]>>> entrySet(Commit<? extends EntrySet> commit) {
    try {/*  www.  j  a v  a  2 s.  c om*/
        return tree.entrySet().stream().map(e -> Maps.immutableEntry(e.getKey(), toVersioned(e.getValue())))
                .collect(Collectors.toSet());
    } finally {
        commit.close();
    }
}

From source file:co.cask.cdap.internal.io.Schema.java

private Schema(Type type, Set<String> enumValues, Schema componentSchema, Schema keySchema, Schema valueSchema,
        String recordName, Map<String, Field> fieldMap, List<Schema> unionSchemas) {
    this.type = type;
    this.enumValues = createIndex(enumValues);
    this.enumIndexes = this.enumValues == null ? null : this.enumValues.inverse();
    this.componentSchema = componentSchema;
    this.keySchema = keySchema;
    this.valueSchema = valueSchema;
    this.mapSchema = (keySchema == null || valueSchema == null) ? null
            : Maps.immutableEntry(keySchema, valueSchema);
    this.recordName = recordName;
    this.fieldMap = populateRecordFields(fieldMap);
    this.fields = this.fieldMap == null ? null : ImmutableList.copyOf(this.fieldMap.values());
    this.unionSchemas = unionSchemas;
}