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:omero.cmd.graphs.DuplicateI.java

/**
 * Duplicate model object properties, linking them as appropriate with each other and with other model objects.
 * @throws GraphException if duplication failed
 *///  w  w  w  .j  a v a  2  s.c o  m
private void setDuplicatePropertyValues() throws GraphException {
    /* organize duplicate index by class name and ID */
    final Map<Entry<String, Long>, IObject> duplicatesByOriginalClassAndId = new HashMap<Entry<String, Long>, IObject>();
    for (final Entry<IObject, IObject> originalAndDuplicate : originalsToDuplicates.entrySet()) {
        final IObject original = originalAndDuplicate.getKey();
        final String originalClass = Hibernate.getClass(original).getName();
        final Long originalId = original.getId();
        final IObject duplicate = originalAndDuplicate.getValue();
        duplicatesByOriginalClassAndId.put(Maps.immutableEntry(originalClass, originalId), duplicate);
    }
    /* allow lookup regardless of if original is actually a Hibernate proxy object */
    final Function<Object, Object> duplicateLookup = new Function<Object, Object>() {
        @Override
        public Object apply(Object original) {
            if (original instanceof IObject) {
                final String originalClass;
                if (original instanceof HibernateProxy) {
                    originalClass = Hibernate.getClass(original).getName();
                } else {
                    originalClass = original.getClass().getName();
                }
                final Long originalId = ((IObject) original).getId();
                return duplicatesByOriginalClassAndId.get(Maps.immutableEntry(originalClass, originalId));
            } else {
                return null;
            }
        }
    };
    /* copy property values into duplicates and link with other model objects */
    final Session session = helper.getSession();
    for (final Entry<IObject, IObject> originalAndDuplicate : originalsToDuplicates.entrySet()) {
        final IObject original = originalAndDuplicate.getKey();
        final IObject duplicate = originalAndDuplicate.getValue();
        final String originalClass = Hibernate.getClass(original).getName();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("copying properties from " + originalClass + ":" + original.getId());
        }
        try {
            /* process property values for a given object that is duplicated */
            for (final String superclassName : graphPathBean.getSuperclassesOfReflexive(originalClass)) {
                /* process property values that link from the duplicate to other model objects */
                for (final Entry<String, String> forwardLink : graphPathBean.getLinkedTo(superclassName)) {
                    /* next forward link */
                    final String linkedClassName = forwardLink.getKey();
                    final String property = forwardLink.getValue();
                    /* ignore details for now, duplicates never preserve original ownership */
                    if (property.startsWith("details.")) {
                        continue;
                    }
                    /* note which of the objects to which the original links should be ignored */
                    final Set<Long> linkedToIdsToIgnore = new HashSet<Long>();
                    for (final Entry<String, Collection<Long>> linkedToClassIds : graphTraversal
                            .getLinkeds(superclassName, property, original.getId()).asMap().entrySet()) {
                        final String linkedToClass = linkedToClassIds.getKey();
                        final Collection<Long> linkedToIds = linkedToClassIds.getValue();
                        if (classifier.getClass(
                                Class.forName(linkedToClass).asSubclass(IObject.class)) == Inclusion.IGNORE) {
                            linkedToIdsToIgnore.addAll(linkedToIds);
                        }
                    }
                    /* check for another accessor for inaccessible properties */
                    if (graphPathBean.isPropertyAccessible(superclassName, property)) {
                        /* copy the linking from the original's property over to the duplicate's */
                        Object value;
                        try {
                            value = PropertyUtils.getNestedProperty(original, property);
                        } catch (NestedNullException e) {
                            continue;
                        }
                        if (value instanceof Collection) {
                            /* if a collection property, include only the objects that aren't to be ignored */
                            final Collection<IObject> valueCollection = (Collection<IObject>) value;
                            final Collection<IObject> valueToCopy;
                            if (value instanceof List) {
                                valueToCopy = new ArrayList<IObject>();
                            } else if (value instanceof Set) {
                                valueToCopy = new HashSet<IObject>();
                            } else {
                                throw new GraphException("unexpected collection type: " + value.getClass());
                            }
                            for (final IObject linkedTo : valueCollection) {
                                if (!linkedToIdsToIgnore.contains(linkedTo.getId())) {
                                    valueToCopy.add(linkedTo);
                                }
                            }
                            value = valueToCopy;
                        } else if (value instanceof IObject) {
                            /* if the property value is to be ignored then null it */
                            if (linkedToIdsToIgnore.contains(((IObject) value).getId())) {
                                value = null;
                            }
                        }
                        /* copy the property value, replacing originals with corresponding duplicates */
                        final Object duplicateValue = GraphUtil.copyComplexValue(duplicateLookup, value);
                        try {
                            PropertyUtils.setNestedProperty(duplicate, property, duplicateValue);
                        } catch (NestedNullException e) {
                            throw new GraphException(
                                    "cannot set property " + superclassName + '.' + property + " on duplicate");
                        }
                    } else {
                        /* this could be a one-to-many property with direct accessors protected */
                        final Class<? extends IObject> linkerClass = Class.forName(superclassName)
                                .asSubclass(IObject.class);
                        final Class<? extends IObject> linkedClass = Class.forName(linkedClassName)
                                .asSubclass(IObject.class);
                        final Method reader, writer;
                        try {
                            reader = linkerClass.getMethod("iterate" + StringUtils.capitalize(property));
                            writer = linkerClass.getMethod("add" + linkedClass.getSimpleName(), linkedClass);
                        } catch (NoSuchMethodException | SecurityException e) {
                            /* no luck, so ignore this property */
                            continue;
                        }
                        /* copy the linking from the original's property over to the duplicate's */
                        final Iterator<IObject> linkedTos = (Iterator<IObject>) reader.invoke(original);
                        while (linkedTos.hasNext()) {
                            final IObject linkedTo = linkedTos.next();
                            /* copy only links to other duplicates, as otherwise we may steal objects from the original */
                            final IObject duplicateOfLinkedTo = (IObject) duplicateLookup.apply(linkedTo);
                            if (duplicateOfLinkedTo != null) {
                                writer.invoke(duplicate, duplicateOfLinkedTo);
                            }
                        }
                    }
                }
                /* process property values that link to the duplicate from other model objects */
                for (final Entry<String, String> backwardLink : graphPathBean.getLinkedBy(superclassName)) {
                    /* next backward link */
                    final String linkingClass = backwardLink.getKey();
                    final String property = backwardLink.getValue();
                    /* ignore inaccessible properties */
                    if (!graphPathBean.isPropertyAccessible(linkingClass, property)) {
                        continue;
                    }
                    for (final Entry<String, Collection<Long>> linkedFromClassIds : graphTraversal
                            .getLinkers(linkingClass, property, original.getId()).asMap().entrySet()) {
                        final String linkedFromClass = linkedFromClassIds.getKey();
                        final Collection<Long> linkedFromIds = linkedFromClassIds.getValue();
                        if (classifier.getClass(
                                Class.forName(linkedFromClass).asSubclass(IObject.class)) == Inclusion.IGNORE) {
                            /* these linkers are to be ignored */
                            continue;
                        }
                        /* load the instances that link to the original */
                        final String rootQuery = "FROM " + linkedFromClass + " WHERE id IN (:ids)";
                        for (final List<Long> idsBatch : Iterables.partition(linkedFromIds, BATCH_SIZE)) {
                            final List<IObject> linkers = session.createQuery(rootQuery)
                                    .setParameterList("ids", idsBatch).list();
                            for (final IObject linker : linkers) {
                                if (originalsToDuplicates.containsKey(linker)) {
                                    /* ignore linkers that are to be duplicated, those are handled as forward links */
                                    continue;
                                }
                                /* copy the linking from the original's property over to the duplicate's */
                                Object value;
                                try {
                                    value = PropertyUtils.getNestedProperty(linker, property);
                                } catch (NestedNullException e) {
                                    continue;
                                }
                                /* for linkers only adjust collection properties */
                                if (value instanceof Collection) {
                                    final Collection<IObject> valueCollection = (Collection<IObject>) value;
                                    final Collection<IObject> newDuplicates = new ArrayList<IObject>();
                                    for (final IObject originalLinker : valueCollection) {
                                        final IObject duplicateOfValue = originalsToDuplicates
                                                .get(originalLinker);
                                        if (duplicateOfValue != null) {
                                            /* previous had just original, now include duplicate too */
                                            newDuplicates.add(duplicateOfValue);
                                        }
                                    }
                                    valueCollection.addAll(newDuplicates);
                                }
                            }
                        }
                    }
                }
                /* process property values that do not relate to edges in the model object graph */
                for (final String property : graphPathBean.getSimpleProperties(superclassName)) {
                    /* ignore inaccessible properties */
                    if (!graphPathBean.isPropertyAccessible(superclassName, property)) {
                        continue;
                    }
                    /* copy original property value to duplicate */
                    final Object value = PropertyUtils.getProperty(original, property);
                    PropertyUtils.setProperty(duplicate, property,
                            GraphUtil.copyComplexValue(duplicateLookup, value));
                }
            }
        } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException
                | NoSuchMethodException e) {
            throw new GraphException("failed to duplicate " + originalClass + ':' + original.getId());
        }
    }
}

From source file:com.facebook.buck.maven.Resolver.java

private Map.Entry<Path, Prebuilt> downloadArtifact(final Artifact artifactToDownload,
        TraversableGraph<Artifact> graph) throws IOException, ArtifactResolutionException {
    String projectName = getProjectName(artifactToDownload);
    Path project = buckRepoRoot.resolve(buckThirdPartyRelativePath).resolve(projectName);
    Files.createDirectories(project);

    Prebuilt library = resolveLib(artifactToDownload, project);

    // Populate deps
    Iterable<Artifact> incoming = graph.getIncomingNodesFor(artifactToDownload);
    for (Artifact artifact : incoming) {
        String groupName = getProjectName(artifact);
        if (projectName.equals(groupName)) {
            library.addDep(String.format(":%s", artifact.getArtifactId()));
        } else {// w w  w.j av  a2s .  c  o  m
            library.addDep(buckThirdPartyRelativePath, artifact);
        }
    }

    // Populate visibility
    Iterable<Artifact> outgoing = graph.getOutgoingNodesFor(artifactToDownload);
    for (Artifact artifact : outgoing) {
        String groupName = getProjectName(artifact);
        if (!groupName.equals(projectName)) {
            library.addVisibility(buckThirdPartyRelativePath, artifact);
        }
    }

    if (specifiedDependencies.containsKey(buildKey(artifactToDownload))) {
        for (String rule : visibility) {
            library.addVisibility(rule);
        }
    }
    return Maps.immutableEntry(project, library);
}

From source file:me.lucko.luckperms.common.verbose.VerboseListener.java

/**
 * Uploads the captured data in this listener to a paste and returns the url
 *
 * @param showTraces if stack traces should be included in the output
 * @param attachRaw if the rawdata should be attached to the gist
 * @return the url// ww w .j a  va2  s.com
 * @see PasteUtils#paste(String, List)
 */
public String uploadPasteData(boolean showTraces, boolean attachRaw) {

    // retrieve variables
    long now = System.currentTimeMillis();
    String startDate = DATE_FORMAT.format(new Date(startTime));
    String endDate = DATE_FORMAT.format(new Date(now));
    long secondsTaken = (now - startTime) / 1000L;
    String duration = DateUtil.formatTimeShort(secondsTaken);

    String filter = this.filter;
    if (filter == null || filter.equals("")) {
        filter = "any";
    } else {
        filter = "`" + filter + "`";
    }

    // start building the message output
    ImmutableList.Builder<String> prettyOutput = ImmutableList.<String>builder()
            .add("## Verbose Checking Output")
            .add("#### This file was automatically generated by [LuckPerms](https://github.com/lucko/LuckPerms) "
                    + pluginVersion)
            .add("").add("### Metadata").add("| Key | Value |").add("|-----|-------|")
            .add("| Start Time | " + startDate + " |").add("| End Time | " + endDate + " |")
            .add("| Duration | " + duration + " |")
            .add("| Count | **" + matchedCounter.get() + "** / " + counter.get() + " |")
            .add("| User | " + notifiedSender.getNameWithLocation() + " |").add("| Filter | " + filter + " |")
            .add("| Include traces | " + showTraces + " |").add("");

    // warn if data was truncated
    if (matchedCounter.get() > results.size()) {
        prettyOutput.add("**WARN:** Result set exceeded max size of " + DATA_TRUNCATION
                + ". The output below was truncated to " + DATA_TRUNCATION + " entries.");
        prettyOutput.add("");
    }

    // explain why some traces may be missing
    if (showTraces && results.size() > TRACE_DATA_TRUNCATION) {
        prettyOutput.add("**WARN:** Result set exceeded size of " + TRACE_DATA_TRUNCATION
                + ". The traced output below was truncated to " + TRACE_DATA_TRUNCATION + " entries.   ");
        prettyOutput.add(
                "Either refine the query using a more specific filter, or disable tracing by adding '--slim' to the end of the paste command.");
        prettyOutput.add("");
    }

    // print the format of the output
    prettyOutput.add("### Output").add("Format: `<checked>` `<permission>` `<value>`").add("").add("___")
            .add("");

    // build the csv output - will only be appended to if this is enabled.
    ImmutableList.Builder<String> csvOutput = ImmutableList.<String>builder().add("User,Permission,Result");

    // how many instances have been printed so far
    AtomicInteger printedCount = new AtomicInteger(0);

    for (CheckData c : results) {
        if (!showTraces) {

            // if traces aren't being shown, just append using raw markdown
            prettyOutput.add("`" + c.getCheckTarget() + "` - " + c.getPermission() + " - "
                    + getTristateSymbol(c.getResult()) + "   ");

        } else if (printedCount.incrementAndGet() > TRACE_DATA_TRUNCATION) {

            // if we've gone over the trace truncation, just append the raw info.
            // we still have to use html, as the rest of this section is still using it.
            prettyOutput.add("<br><code>" + c.getCheckTarget() + "</code> - " + c.getPermission() + " - "
                    + getTristateSymbol(c.getResult()));

        } else {

            // append the full output.
            prettyOutput.add("<details><summary><code>" + c.getCheckTarget() + "</code> - " + c.getPermission()
                    + " - " + getTristateSymbol(c.getResult()) + "</summary><p>");

            // append the spoiler text
            prettyOutput.add("<br><b>Origin:</b> <code>" + c.getCheckOrigin().name() + "</code>");
            prettyOutput.add("<br><b>Context:</b> <code>"
                    + CommandUtils.stripColor(CommandUtils.contextSetToString(c.getCheckContext()))
                    + "</code>");
            prettyOutput.add("<br><b>Trace:</b><pre>");

            int overflow = readStack(c, 30, e -> prettyOutput.add(e.getClassName() + "." + e.getMethodName()
                    + (e.getLineNumber() >= 0 ? ":" + e.getLineNumber() : "")));
            if (overflow != 0) {
                prettyOutput.add("... and " + overflow + " more");
            }

            prettyOutput.add("</pre></p></details>");
        }

        // if we're including a raw csv output, append that too
        if (attachRaw) {
            csvOutput.add(escapeCommas(c.getCheckTarget()) + "," + escapeCommas(c.getPermission()) + ","
                    + c.getResult().name().toLowerCase());
        }
    }
    results.clear();

    ImmutableList.Builder<Map.Entry<String, String>> content = ImmutableList.builder();
    content.add(Maps.immutableEntry("luckperms-verbose.md",
            prettyOutput.build().stream().collect(Collectors.joining("\n"))));

    if (attachRaw) {
        content.add(Maps.immutableEntry("raw-data.csv",
                csvOutput.build().stream().collect(Collectors.joining("\n"))));
    }

    return PasteUtils.paste("LuckPerms Verbose Checking Output", content.build());
}

From source file:me.lucko.luckperms.common.actionlog.ExtendedLogEntry.java

public static Map.Entry<UUID, ExtendedLogEntry> deserialize(JsonObject object) {
    ExtendedLogEntryBuilder builder = build();

    UUID id = UUID.fromString(object.get("id").getAsString());

    builder.actor(UUID.fromString(object.get("actor").getAsString()));
    builder.actorName(object.get("actorName").getAsString());
    builder.type(Type.valueOf(object.get("type").getAsString()));
    if (object.has("acted")) {
        builder.actor(UUID.fromString(object.get("acted").getAsString()));
    }/*from   w ww  .jav a 2  s  .  co m*/
    builder.actedName(object.get("actedName").getAsString());
    builder.action(object.get("action").getAsString());

    return Maps.immutableEntry(id, builder.build());
}

From source file:me.lucko.luckperms.common.commands.utils.Util.java

public static Map.Entry<FancyMessage, String> searchGroupResultToMessage(List<HeldPermission<String>> results,
        String label, int pageNumber) {
    if (results.isEmpty()) {
        return Maps.immutableEntry(new FancyMessage("None").color(ChatColor.getByChar('3')), null);
    }/*  ww w.j  a va 2s  . c o  m*/

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

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

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

    List<HeldPermission<String>> page = pages.get(index);

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

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

    return Maps.immutableEntry(message, title);
}

From source file:omero.cmd.graphs.Chmod2I.java

@Override
public Object step(int step) throws Cancel {
    helper.assertStep(step);/* w w w .  j a  v  a  2s . c  o  m*/
    try {
        switch (step) {
        case 0:
            /* if targetObjects were an IObjectList then this would need IceMapper.reverse */
            final SetMultimap<String, Long> targetMultimap = HashMultimap.create();
            for (final Entry<String, List<Long>> oneClassToTarget : targetObjects.entrySet()) {
                /* determine actual class from given target object class name */
                String targetObjectClassName = oneClassToTarget.getKey();
                final int lastDot = targetObjectClassName.lastIndexOf('.');
                if (lastDot > 0) {
                    targetObjectClassName = targetObjectClassName.substring(lastDot + 1);
                }
                final Class<? extends IObject> targetObjectClass = graphPathBean
                        .getClassForSimpleName(targetObjectClassName);
                /* check that it is legal to target the given class */
                final Iterator<Class<? extends IObject>> legalTargetsIterator = targetClasses.iterator();
                do {
                    if (!legalTargetsIterator.hasNext()) {
                        final Exception e = new IllegalArgumentException(
                                "cannot target " + targetObjectClassName);
                        throw helper.cancel(new ERR(), e, "bad-target");
                    }
                } while (!legalTargetsIterator.next().isAssignableFrom(targetObjectClass));
                /* note IDs to target for the class */
                final Collection<Long> ids = oneClassToTarget.getValue();
                targetMultimap.putAll(targetObjectClass.getName(), ids);
                targetObjectCount += ids.size();
            }
            /* only downgrade to private requires the graph policy rules to be applied */
            final Entry<SetMultimap<String, Long>, SetMultimap<String, Long>> plan;
            final Permissions newPermissions = Utils.toPermissions(perm1);
            final boolean isToGroupReadable = newPermissions.isGranted(Permissions.Role.GROUP,
                    Permissions.Right.READ);
            if (isToGroupReadable) {
                /* can always skip graph policy rules as is not downgrade to private */
                plan = graphTraversal.planOperation(helper.getSession(), targetMultimap, true, false);
            } else {
                /* determine which target groups are not already private ... */
                final String groupClass = ExperimenterGroup.class.getName();
                final SetMultimap<String, Long> targetsNotPrivate = HashMultimap.create();
                final Map<Long, Boolean> readableByGroupId = new HashMap<Long, Boolean>();
                for (final Long groupId : targetMultimap.get(groupClass)) {
                    Boolean isFromGroupReadable = readableByGroupId.get(groupId);
                    if (isFromGroupReadable == null) {
                        final Session session = helper.getSession();
                        final ExperimenterGroup group = (ExperimenterGroup) session.get(ExperimenterGroup.class,
                                groupId);
                        if (group == null) {
                            final Exception e = new IllegalArgumentException("no group " + groupId);
                            throw helper.cancel(new ERR(), e, "bad-group");
                        }
                        final Permissions permissions = group.getDetails().getPermissions();
                        isFromGroupReadable = permissions.isGranted(Permissions.Role.GROUP,
                                Permissions.Right.READ);
                        readableByGroupId.put(groupId, isFromGroupReadable);
                    }
                    if (isFromGroupReadable) {
                        targetsNotPrivate.put(groupClass, groupId);
                    }
                }
                /* ... and apply the graph policy rules to those */
                plan = graphTraversal.planOperation(helper.getSession(), targetsNotPrivate, true, true);
            }
            return Maps.immutableEntry(plan.getKey(),
                    GraphUtil.arrangeDeletionTargets(helper.getSession(), plan.getValue()));
        case 1:
            graphTraversal.assertNoPolicyViolations();
            return null;
        case 2:
            processor = graphTraversal.processTargets();
            return null;
        case 3:
            unlinker = graphTraversal.unlinkTargets(false);
            graphTraversal = null;
            return null;
        case 4:
            unlinker.execute();
            return null;
        case 5:
            processor.execute();
            return null;
        default:
            final Exception e = new IllegalArgumentException(
                    "model object graph operation has no step " + step);
            throw helper.cancel(new ERR(), e, "bad-step");
        }
    } catch (Cancel c) {
        throw c;
    } catch (GraphException ge) {
        final omero.cmd.GraphException graphERR = new omero.cmd.GraphException();
        graphERR.message = ge.message;
        throw helper.cancel(graphERR, ge, "graph-fail");
    } catch (Throwable t) {
        throw helper.cancel(new ERR(), t, "graph-fail");
    }
}

From source file:org.apache.james.jmap.methods.integration.cucumber.SetMailboxesMethodStepdefs.java

@Then("^\"([^\"]*)\" receives not updated on mailbox \"([^\"]*)\" with kind \"([^\"]*)\" and message \"([^\"]*)\"$")
public void assertNotUpdatedWithGivenProperties(String userName, String mailboxName, String type,
        String message) {/*from   w w  w. j a  va2s  . c om*/
    String mailboxId = mainStepdefs.getMailboxId(userName, mailboxName).serialize();
    assertThat(httpClient.response.getStatusLine().getStatusCode()).isEqualTo(200);
    assertThat(httpClient.jsonPath.<String>read(NAME)).isEqualTo("mailboxesSet");

    Map<String, Map<String, String>> notUpdated = httpClient.jsonPath
            .<Map<String, Map<String, String>>>read(ARGUMENTS + ".notUpdated");
    assertThat(notUpdated).hasSize(1);
    Map<String, String> parameters = notUpdated.get(mailboxId);
    assertThat(parameters).contains(Maps.immutableEntry("type", type),
            Maps.immutableEntry("description", message));
}

From source file:hu.bme.mit.massif.simulink.api.util.bus.BusSignalMappingPathFinder.java

private Entry<OutPort, String> findFragmentForMapping(Map<OutPort, String> pathFragments,
        BusSelector busSelector) {/*ww  w.ja v  a2 s. c  o m*/
    for (BusSignalMapping m : busSelector.getMappings()) {
        OutPort from = m.getMappingFrom();
        if (pathFragments.containsKey(from)) {
            // replace current path with stored
            return Maps.immutableEntry(from, pathFragments.get(from));
        }
    }
    // if there is none, the path is invalid (selector selects from farther back)
    throw new IllegalStateException("Cannot find path fragment for mapping in bus selector!");
}

From source file:ninja.leaping.permissionsex.bukkit.PEXPermissible.java

public Set<Map.Entry<String, String>> getActiveContexts() {
    ImmutableSet.Builder<Map.Entry<String, String>> builder = ImmutableSet.builder();
    builder.add(Maps.immutableEntry("world", player.getWorld().getName()));
    builder.add(Maps.immutableEntry("dimension", player.getWorld().getEnvironment().name().toLowerCase()));
    for (String serverTag : plugin.getManager().getConfig().getServerTags()) {
        builder.add(Maps.immutableEntry(PermissionsExPlugin.SERVER_TAG_CONTEXT, serverTag));
    }//  www. java2  s  .c om
    return builder.build();
}

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

@Override
public V put(K key, V value) {
    checkState(!closed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);//from w w  w .  j a v a2s  . c  o m
    checkNotNull(value, ERROR_NULL_VALUE);

    String encodedKey = encodeKey(key);
    byte[] encodedValue = encodeValue(value);

    MapValue newValue = new MapValue(encodedValue, timestampProvider.get(Maps.immutableEntry(key, value)));

    counter.incrementCount();
    AtomicReference<byte[]> oldValue = new AtomicReference<>();
    AtomicBoolean updated = new AtomicBoolean(false);
    items.compute(encodedKey, (k, existing) -> {
        if (existing == null || newValue.isNewerThan(existing)) {
            updated.set(true);
            oldValue.set(existing != null ? existing.get() : null);
            return newValue;
        }
        return existing;
    });

    if (updated.get()) {
        notifyPeers(new UpdateEntry(encodedKey, newValue),
                peerUpdateFunction.select(Maps.immutableEntry(key, value), membershipService));
        if (oldValue.get() == null) {
            notifyListeners(new MapDelegateEvent<>(INSERT, key, value));
        } else {
            notifyListeners(new MapDelegateEvent<>(UPDATE, key, value));
        }
        return decodeValue(oldValue.get());
    }
    return value;
}