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.infinities.keystone4j.identity.controller.impl.UserV3ControllerImpl.java

@Override
public CollectionWrapper<User> listUsersInGroup(String groupid) throws Exception {
    Entry<String, String> entrys = Maps.immutableEntry("group_id", groupid);
    FilterProtectedAction<User> command = new FilterProtectedDecorator<User>(
            new ListUsersInGroupAction(identityApi, tokenProviderApi, policyApi, groupid), tokenProviderApi,
            policyApi, entrys);/*  w  w  w  . jav a  2  s  .  c o  m*/
    CollectionWrapper<User> ret = command.execute(getRequest(), "domain_id", "enabled", "name");
    return ret;
}

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

public static SchemaMigration twoToThree() {
    // The big one
    return dao -> {
        dao.legacy().renameTable(dao, "permissions", "permissions_old");
        dao.legacy().renameTable(dao, "permissions_entity", "permissions_entity_old");
        dao.legacy().renameTable(dao, "permissions_inheritance", "permissions_inheritance_old");
        dao.initializeTables();//  w  w  w . jav a2  s  .co  m

        // Transfer world inheritance
        try (PreparedStatement stmt = dao.prepareStatement(
                "SELECT id, child, parent FROM {}permissions_inheritance_old WHERE type=2 ORDER BY child, parent, id ASC")) {
            ResultSet rs = stmt.executeQuery();
            try (PreparedStatement insert = dao.prepareStatement(dao.getInsertContextInheritanceQuery())) {
                insert.setString(1, "world");
                insert.setString(3, "world");
                while (rs.next()) {
                    insert.setString(2, rs.getString(2));
                    insert.setString(4, rs.getString(3));
                    insert.addBatch();
                }
                insert.executeBatch();
            }
        }

        Map<String, List<SubjectRef>> defaultSubjects = new HashMap<>();
        Map<String, List<Map.Entry<SubjectRef, Integer>>> tempRankLadders = new HashMap<>();

        try (PreparedStatement select = dao
                .prepareStatement("SELECT type, name FROM {}permissions_entity_old")) {
            ResultSet rs = select.executeQuery();
            while (rs.next()) {
                SubjectRef ref = dao.getOrCreateSubjectRef(
                        LegacyMigration.Type.values()[rs.getInt(1)].name().toLowerCase(), rs.getString(2));
                Segment currentSeg = null;
                String currentWorld = null;
                Map<String, Segment> worldSegments = new HashMap<>();
                try (PreparedStatement selectPermissionsOptions = dao.prepareStatement(
                        "SELECT id, permission, world, value FROM {}permissions_old WHERE type=? AND name=? ORDER BY world, id DESC")) {
                    selectPermissionsOptions.setInt(1, rs.getInt(1));
                    selectPermissionsOptions.setString(2, rs.getString(2));

                    ResultSet perms = selectPermissionsOptions.executeQuery();
                    Map<String, Integer> newPerms = new HashMap<>();
                    Map<String, String> options = new HashMap<>();
                    String rank = null, rankLadder = null;
                    int defaultVal = 0;
                    while (perms.next()) {
                        String worldChecked = perms.getString(3);
                        if (worldChecked != null && worldChecked.isEmpty()) {
                            worldChecked = null;
                        }
                        if (currentSeg == null || !Objects.equals(worldChecked, currentWorld)) {
                            if (currentSeg != null) {
                                if (!options.isEmpty()) {
                                    dao.setOptions(currentSeg, options);
                                    options.clear();
                                }
                                if (!newPerms.isEmpty()) {
                                    dao.setPermissions(currentSeg, newPerms);
                                    newPerms.clear();
                                }
                                if (defaultVal != 0) {
                                    dao.setDefaultValue(currentSeg, defaultVal);
                                    defaultVal = 0;
                                }
                            }
                            currentWorld = worldChecked;
                            currentSeg = Segment.unallocated(currentWorld == null ? ImmutableSet.of()
                                    : ImmutableSet.of(Maps.immutableEntry("world", currentWorld)));
                            dao.allocateSegment(ref, currentSeg);
                            worldSegments.put(currentWorld, currentSeg);
                        }
                        String key = perms.getString(2);
                        final String value = perms.getString(4);
                        if (value == null || value.isEmpty()) {
                            // permission
                            int val = key.startsWith("-") ? -1 : 1;
                            if (val == -1) {
                                key = key.substring(1);
                            }
                            if (key.equals("*")) {
                                defaultVal = val;
                                continue;
                            }
                            key = ConversionUtils.convertLegacyPermission(key);
                            newPerms.put(key, val);
                        } else {
                            if (currentWorld == null) {
                                boolean rankEq = key.equals("rank"),
                                        rankLadderEq = !rankEq && key.equals("rank-ladder");
                                if (rankEq || rankLadderEq) {
                                    if (rankEq) {
                                        rank = value;
                                    } else { // then it's the rank ladder
                                        rankLadder = value;
                                    }
                                    if (rank != null && rankLadder != null) {
                                        List<Map.Entry<SubjectRef, Integer>> ladder = tempRankLadders
                                                .computeIfAbsent(rankLadder, ign -> new ArrayList<>());
                                        try {
                                            ladder.add(Maps.immutableEntry(ref, Integer.parseInt(rank)));
                                        } catch (IllegalArgumentException ex) {
                                        }
                                        rankLadder = null;
                                        rank = null;
                                    }
                                    continue;
                                }
                            }
                            if (key.equals("default") && value.equalsIgnoreCase("true")) {
                                defaultSubjects.computeIfAbsent(currentWorld, ign -> new ArrayList<>())
                                        .add(ref);
                                continue;
                            }
                            options.put(key, value);
                        }
                    }

                    if (currentSeg != null) {
                        if (!options.isEmpty()) {
                            dao.setOptions(currentSeg, options);
                        }
                        if (!newPerms.isEmpty()) {
                            dao.setPermissions(currentSeg, newPerms);
                        }
                        if (defaultVal != 0) {
                            dao.setDefaultValue(currentSeg, defaultVal);
                        }
                        if (rank != null) {
                            List<Map.Entry<SubjectRef, Integer>> ladder = tempRankLadders
                                    .computeIfAbsent("default", ign -> new ArrayList<>());
                            try {
                                ladder.add(Maps.immutableEntry(ref, Integer.parseInt(rank)));
                            } catch (IllegalArgumentException ex) {
                            }

                        }
                    }
                }

                for (Map.Entry<String, List<Map.Entry<SubjectRef, Integer>>> ent : tempRankLadders.entrySet()) {
                    List<SubjectRef> ladder = ent.getValue().stream()
                            .sorted((a, b) -> Integer.compare(b.getValue(), a.getValue()))
                            .map(Map.Entry::getKey).collect(GuavaCollectors.toImmutableList());
                    dao.setRankLadder(ent.getKey(), new SqlRankLadder(ent.getKey(), ladder));

                }

                if (!defaultSubjects.isEmpty()) {
                    SubjectRef defaultSubj = dao.getOrCreateSubjectRef(PermissionsEx.SUBJECTS_DEFAULTS,
                            PermissionsEx.SUBJECTS_USER);
                    List<Segment> segments = new ArrayList<>(dao.getSegments(defaultSubj));
                    for (Map.Entry<String, List<SubjectRef>> ent : defaultSubjects.entrySet()) {
                        Segment seg = null;
                        if (!segments.isEmpty()) {
                            for (Segment segment : segments) {
                                if (ent.getKey() == null && segment.getContexts().isEmpty()) {
                                    seg = segment;
                                    break;
                                } else if (segment.getContexts().size() == 1) {
                                    Map.Entry<String, String> ctx = segment.getContexts().iterator().next();
                                    if (ctx.getKey().equals("world") && ctx.getValue().equals(ent.getKey())) {
                                        seg = segment;
                                        break;
                                    }
                                }
                            }
                        }
                        if (seg == null) {
                            seg = Segment.unallocated(ent.getKey() == null ? ImmutableSet.of()
                                    : ImmutableSet.of(Maps.immutableEntry("world", ent.getKey())));
                            dao.allocateSegment(defaultSubj, seg);
                            segments.add(seg);
                        }
                        dao.setParents(seg, ent.getValue());
                    }
                }

                try (PreparedStatement selectInheritance = dao
                        .prepareStatement(dao.legacy().getSelectParentsQuery())) {
                    selectInheritance.setString(1, rs.getString(2));
                    selectInheritance.setInt(2, rs.getInt(1));

                    ResultSet inheritance = selectInheritance.executeQuery();
                    List<SubjectRef> newInheritance = new LinkedList<>();
                    while (inheritance.next()) {
                        if (currentSeg == null || !Objects.equals(inheritance.getString(3), currentWorld)) {
                            if (currentSeg != null && !newInheritance.isEmpty()) {
                                dao.setParents(currentSeg, newInheritance);
                                newInheritance.clear();
                            }
                            currentWorld = inheritance.getString(3);
                            currentSeg = worldSegments.get(currentWorld);
                            if (currentSeg == null) {
                                currentSeg = Segment.unallocated(currentWorld == null ? ImmutableSet.of()
                                        : ImmutableSet.of(Maps.immutableEntry("world", currentWorld)));
                                dao.allocateSegment(ref, currentSeg);
                                worldSegments.put(currentWorld, currentSeg);
                            }
                        }
                        newInheritance.add(dao.getOrCreateSubjectRef(PermissionsEx.SUBJECTS_GROUP,
                                inheritance.getString(2)));
                    }
                    if (currentSeg != null && !newInheritance.isEmpty()) {
                        dao.setParents(currentSeg, newInheritance);
                        newInheritance.clear();
                    }
                }

            }
        }

        dao.deleteTable("permissions_old");
        dao.deleteTable("permissions_entity_old");
        dao.deleteTable("permissions_inheritance_old");
    };
}

From source file:fi.vm.sade.organisaatio.business.impl.OrganisaatioBusinessChecker.java

public void checkOrganisaatioHierarchy(Organisaatio organisaatio, String parentOid) {
    LOG.debug("checkOrganisaatioHierarchy()");

    final OrganisationHierarchyValidator validator = new OrganisationHierarchyValidator(rootOrganisaatioOid);
    Organisaatio parentOrg = (parentOid != null) ? this.organisaatioDAO.findByOid(parentOid) : null;
    if (validator.apply(Maps.immutableEntry(parentOrg, organisaatio))) {
        //check children
        if (organisaatio.getId() != null) { // we can have children only if we are already saved
            List<Organisaatio> children = organisaatioDAO.findChildren(organisaatio.getId());
            for (Organisaatio child : children) {
                if (!validator.apply(Maps.immutableEntry(organisaatio, child))) {
                    throw new OrganisaatioHierarchyException();
                }//from www  .  jav a  2s .  co m
            }
        }
    } else {
        throw new OrganisaatioHierarchyException();
    }
}

From source file:ome.services.query.HierarchyNavigator.java

/**
 * Perform the database query to discover the IDs of the related objects.
 * @param toType the type of the objects to which the query object may be related, not <code>null</code>
 * @param fromType the query object's type, not <code>null</code>
 * @param fromIds the query objects' database IDs, none <code>null</code>
 * @return pairs of database IDs: of the query object, and an object to which it relates
 *///from   w  w  w .j  a v a2s  .c om
private List<Object[]> doQuery(String toType, String fromType, Collection<Long> fromIds) {
    final String queryString = hqlFromTo.get(Maps.immutableEntry(fromType, toType));
    if (queryString == null) {
        throw new IllegalArgumentException("not implemented for " + fromType + " to " + toType);
    }
    return this.iQuery.projection(queryString, new Parameters().addIds(fromIds));
}

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

public void load(File file) {
    if (!file.exists()) {
        return;// w  ww  . j  a v a2s  .co  m
    }

    try (BufferedReader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {

        String entry;
        while ((entry = reader.readLine()) != null) {
            entry = entry.trim();
            if (entry.isEmpty() || entry.startsWith("#")) {
                continue;
            }

            Iterator<String> parts = KV_SPLIT.split(entry).iterator();

            if (!parts.hasNext())
                continue;
            String key = parts.next();

            if (!parts.hasNext())
                continue;
            String value = parts.next();

            UUID uid;
            Long t;

            // contains a time (backwards compat)
            if (value.contains("|")) {
                // try to split and extract the time element from the end.
                Iterator<String> valueParts = TIME_SPLIT.split(value).iterator();

                if (!valueParts.hasNext())
                    continue;
                String uuid = valueParts.next();

                if (!valueParts.hasNext())
                    continue;
                String time = valueParts.next();

                try {
                    uid = UUID.fromString(uuid);
                } catch (IllegalArgumentException e) {
                    continue;
                }

                try {
                    t = Long.parseLong(time);
                } catch (NumberFormatException e) {
                    continue;
                }
            } else {
                // just parse from the value
                try {
                    uid = UUID.fromString(value);
                } catch (IllegalArgumentException e) {
                    continue;
                }

                t = 0L;
            }

            lookupMap.put(key, Maps.immutableEntry(uid, t));
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.palantir.atlasdb.keyvalue.impl.Cells.java

/**
 * The Collection provided to this function has to be sorted and strictly increasing.
 */// w  ww  .j  ava2 s.  co m
public static <T> Iterator<RowResult<T>> createRowView(final Collection<Map.Entry<Cell, T>> sortedIterator) {
    final PeekingIterator<Entry<Cell, T>> it = Iterators.peekingIterator(sortedIterator.iterator());
    Iterator<Map.Entry<byte[], SortedMap<byte[], T>>> resultIt = new AbstractIterator<Map.Entry<byte[], SortedMap<byte[], T>>>() {
        byte[] row = null;
        SortedMap<byte[], T> map = null;

        @Override
        protected Entry<byte[], SortedMap<byte[], T>> computeNext() {
            if (!it.hasNext()) {
                return endOfData();
            }
            row = it.peek().getKey().getRowName();
            ImmutableSortedMap.Builder<byte[], T> mapBuilder = ImmutableSortedMap
                    .orderedBy(UnsignedBytes.lexicographicalComparator());
            while (it.hasNext()) {
                Entry<Cell, T> peek = it.peek();
                if (!Arrays.equals(peek.getKey().getRowName(), row)) {
                    break;
                }
                mapBuilder.put(peek.getKey().getColumnName(), peek.getValue());
                it.next();
            }
            map = mapBuilder.build();
            return Maps.immutableEntry(row, map);
        }
    };
    return RowResults.viewOfEntries(resultIt);
}

From source file:me.lucko.luckperms.common.commands.misc.SearchCommand.java

private static <T extends Comparable<T>> void sendResult(Sender sender, List<HeldPermission<T>> results,
        Function<T, String> lookupFunction, Message headerMessage, HolderType holderType, String label,
        int page, Comparison comparison) {
    results = new ArrayList<>(results);
    results.sort(HeldPermissionComparator.normal());

    int pageIndex = page - 1;
    List<List<HeldPermission<T>>> pages = Iterators.divideIterable(results, 15);

    if (pageIndex < 0 || pageIndex >= pages.size()) {
        page = 1;/*from  ww  w  .j  a  v  a  2s .  c om*/
        pageIndex = 0;
    }

    List<HeldPermission<T>> content = pages.get(pageIndex);

    List<Map.Entry<String, HeldPermission<T>>> mappedContent = content.stream()
            .map(hp -> Maps.immutableEntry(lookupFunction.apply(hp.getHolder()), hp))
            .collect(Collectors.toList());

    // send header
    headerMessage.send(sender, page, pages.size(), results.size());

    for (Map.Entry<String, HeldPermission<T>> ent : mappedContent) {
        // only show the permission in the results if the comparison isn't equals
        String permission = "";
        if (comparison != StandardComparison.EQUAL) {
            permission = "&7 - (" + ent.getValue().getPermission() + ")";
        }

        String s = "&3> &b" + ent.getKey() + permission + "&7 - " + (ent.getValue().getValue() ? "&a" : "&c")
                + ent.getValue().getValue() + getNodeExpiryString(ent.getValue().asNode())
                + MessageUtils.getAppendableNodeContextString(sender.getPlugin().getLocaleManager(),
                        ent.getValue().asNode());
        TextComponent message = TextUtils.fromLegacy(s, CommandManager.AMPERSAND_CHAR).toBuilder()
                .applyDeep(makeFancy(ent.getKey(), holderType, label, ent.getValue(), sender.getPlugin()))
                .build();
        sender.sendMessage(message);
    }
}

From source file:ninja.leaping.permissionsex.extrabackends.groupmanager.GroupManagerSubjectData.java

@Override
public List<Map.Entry<String, String>> getParents(Set<Map.Entry<String, String>> contexts) {
    ConfigurationNode specificNode = getNodeForContexts(contexts);
    if (specificNode == null) {
        return ImmutableList.of();
    }/*from  w w w  .  j ava2  s  . c  om*/

    try {
        return Lists.transform(
                specificNode.getNode(this.type.getInheritanceKey()).getList(TypeToken.of(String.class)),
                input -> {
                    if (input.startsWith("g:")) {
                        input = input.substring(2);
                    }
                    return Maps.immutableEntry(PermissionsEx.SUBJECTS_GROUP, input);
                });
    } catch (ObjectMappingException e) {
        return ImmutableList.of();
    }
}

From source file:me.lucko.luckperms.sponge.service.storage.SubjectStorage.java

public Map.Entry<String, SubjectStorageModel> loadFromFile(File file) throws IOException {
    if (!file.exists()) {
        return null;
    }// w  w w.  j ava  2 s . c o m

    String subjectName = file.getName().substring(0, file.getName().length() - ".json".length());

    try (BufferedReader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
        JsonObject data = gson.fromJson(reader, JsonObject.class);
        SubjectStorageModel model = new SubjectStorageModel(service, data);
        return Maps.immutableEntry(subjectName, model);
    }
}

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

@Override
public boolean playerInGroup(String world, OfflinePlayer player, String group) {
    return getSubject(player).getParents(contextsFrom(world))
            .contains(Maps.immutableEntry(SUBJECTS_GROUP, group));
}