List of usage examples for com.google.common.collect Maps immutableEntry
@GwtCompatible(serializable = true) public static <K, V> Entry<K, V> immutableEntry(@Nullable K key, @Nullable V value)
From source file:org.apache.hadoop.hive.accumulo.columns.ColumnMappingFactory.java
/** * Consumes the column mapping specification and breaks it into column family and column * qualifier.//from w w w.j a va 2 s . c o m */ public static Entry<String, String> parseMapping(String columnSpec) throws InvalidColumnMappingException { int index = 0; while (true) { if (index >= columnSpec.length()) { log.error("Cannot parse '" + columnSpec + "' as colon-separated column configuration"); throw new InvalidColumnMappingException( "Columns must be provided as colon-separated family and qualifier pairs"); } index = columnSpec.indexOf(AccumuloHiveConstants.COLON, index); if (-1 == index) { log.error("Cannot parse '" + columnSpec + "' as colon-separated column configuration"); throw new InvalidColumnMappingException( "Columns must be provided as colon-separated family and qualifier pairs"); } // Check for an escape character before the colon if (index - 1 > 0) { char testChar = columnSpec.charAt(index - 1); if (AccumuloHiveConstants.ESCAPE == testChar) { // this colon is escaped, search again after it index++; continue; } // If the previous character isn't an escape characters, it's the separator } // Can't be escaped, it is the separator break; } String cf = columnSpec.substring(0, index), cq = columnSpec.substring(index + 1); // Check for the escaped colon to remove before doing the expensive regex replace if (-1 != cf.indexOf(AccumuloHiveConstants.ESCAPED_COLON)) { cf = cf.replaceAll(AccumuloHiveConstants.ESCAPED_COLON_REGEX, Character.toString(AccumuloHiveConstants.COLON)); } // Check for the escaped colon to remove before doing the expensive regex replace if (-1 != cq.indexOf(AccumuloHiveConstants.ESCAPED_COLON)) { cq = cq.replaceAll(AccumuloHiveConstants.ESCAPED_COLON_REGEX, Character.toString(AccumuloHiveConstants.COLON)); } return Maps.immutableEntry(cf, cq); }
From source file:org.jooby.internal.spec.RouteParamCollector.java
@SuppressWarnings("rawtypes") private Entry<Type, Object> type(final MethodCallExpr expr, final Context ctx) { String name = expr.getName(); Type type = null;/*w w w . j a va 2 s. c o m*/ switch (name) { case "charValue": { type = char.class; } break; case "byteValue": { type = byte.class; } break; case "booleanValue": { type = boolean.class; } break; case "shortValue": { type = short.class; } break; case "intValue": { type = int.class; } break; case "longValue": { type = long.class; } break; case "floatValue": { type = float.class; } break; case "doubleValue": { type = double.class; } break; case "value": { type = String.class; } break; case "toList": { type = List.class; } break; case "toSet": { type = Set.class; } break; case "toSortedSet": { type = SortedSet.class; } break; case "toOptional": { type = Optional.class; } break; case "toUpload": { type = ctx.resolveType(expr, "org.jooby.Upload").get(); } break; } Object defaultValue = null; List<Expression> args = expr.getArgs(); if (args.size() > 0) { Expression arg = args.get(0); Object result = arg.accept(new LiteralCollector(), ctx); if (result instanceof Type) { if (type == null) { type = (Type) result; } else { type = Types.newParameterizedType(type, (Type) result); } } else if (result instanceof Enum) { Enum e = (Enum) result; type = e.getDeclaringClass(); defaultValue = e.name(); } else { if (result != null) { defaultValue = result; } else { Map<String, Object> vals = new StaticValueCollector().accept(expr, ctx); defaultValue = arg.toStringWithoutComments(); defaultValue = vals.getOrDefault(defaultValue, defaultValue); } } } else if (name.startsWith("to") && name.length() > 2 && !name.equals("toUpload")) { type = Types.newParameterizedType(type, String.class); } return Maps.immutableEntry(type, defaultValue); }
From source file:org.onosproject.net.optical.intent.impl.compiler.OpticalConnectivityIntentCompiler.java
@Override public List<Intent> compile(OpticalConnectivityIntent intent, List<Intent> installable) { // Check if source and destination are optical OCh ports ConnectPoint src = intent.getSrc();//from www .j av a 2 s. c o m ConnectPoint dst = intent.getDst(); Port srcPort = deviceService.getPort(src.deviceId(), src.port()); Port dstPort = deviceService.getPort(dst.deviceId(), dst.port()); checkArgument(srcPort instanceof OchPort); checkArgument(dstPort instanceof OchPort); log.debug("Compiling optical connectivity intent between {} and {}", src, dst); // Release of intent resources here is only a temporary solution for handling the // case of recompiling due to intent restoration (when intent state is FAILED). // TODO: try to release intent resources in IntentManager. resourceService.release(intent.id()); // Check OCh port availability Resource srcPortResource = Resources.discrete(src.deviceId(), src.port()).resource(); Resource dstPortResource = Resources.discrete(dst.deviceId(), dst.port()).resource(); // If ports are not available, compilation fails if (!Stream.of(srcPortResource, dstPortResource).allMatch(resourceService::isAvailable)) { throw new OpticalIntentCompilationException( "Ports for the intent are not available. Intent: " + intent); } List<Resource> resources = new ArrayList<>(); resources.add(srcPortResource); resources.add(dstPortResource); // Calculate available light paths Set<Path> paths = getOpticalPaths(intent); if (paths.isEmpty()) { throw new OpticalIntentCompilationException("Unable to find suitable lightpath for intent " + intent); } // Static or dynamic lambda allocation String staticLambda = srcPort.annotations().value(AnnotationKeys.STATIC_LAMBDA); OchPort srcOchPort = (OchPort) srcPort; OchPort dstOchPort = (OchPort) dstPort; Path firstPath = paths.iterator().next(); // FIXME: need to actually reserve the lambda for static lambda's // static lambda case: early return if (staticLambda != null) { allocateResources(intent, resources); OchSignal lambda = new OchSignal(Frequency.ofHz(Long.parseLong(staticLambda)), srcOchPort.lambda().channelSpacing(), srcOchPort.lambda().slotGranularity()); return ImmutableList.of(createIntent(intent, firstPath, lambda)); } // FIXME: also check destination OCh port // non-tunable case: early return if (!srcOchPort.isTunable() || !dstOchPort.isTunable()) { allocateResources(intent, resources); OchSignal lambda = srcOchPort.lambda(); return ImmutableList.of(createIntent(intent, firstPath, lambda)); } // remaining cases // Use first path that the required resources are available Optional<Map.Entry<Path, List<OchSignal>>> found = paths.stream() .map(path -> Maps.immutableEntry(path, findFirstAvailableOch(path))) .filter(entry -> !entry.getValue().isEmpty()) .filter(entry -> convertToResources(entry.getKey().links(), entry.getValue()).stream() .allMatch(resourceService::isAvailable)) .findFirst(); if (found.isPresent()) { resources.addAll(convertToResources(found.get().getKey().links(), found.get().getValue())); allocateResources(intent, resources); OchSignal ochSignal = OchSignal.toFixedGrid(found.get().getValue(), ChannelSpacing.CHL_50GHZ); return ImmutableList.of(createIntent(intent, found.get().getKey(), ochSignal)); } else { throw new OpticalIntentCompilationException("Unable to find suitable lightpath for intent " + intent); } }
From source file:fi.hsl.parkandride.back.RequestLogDao.java
private static Map<RequestLogKey, Long> normalizeTimestamps(Map<RequestLogKey, Long> logCounts) { final Map<RequestLogKey, Long> normalized = logCounts.entrySet().stream() .map(entry -> Maps.immutableEntry(entry.getKey().roundTimestampDown(), entry.getValue())) .collect(toMapSummingCounts()); if (logCounts.size() != normalized.size()) { final List<DateTime> duplicatedTimestamps = collectDuplicateTimestamps(logCounts); logger.warn(//from w w w . ja v a 2s .co m "Encountered entries with duplicated keys during timestamp normalization. The duplicated timestamps were summed. Duplicated timestamps: {}", duplicatedTimestamps); } return normalized; }
From source file:me.lucko.luckperms.bukkit.migration.MigrationGroupManager.java
@Override public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Object o, List<String> args, String label) throws CommandException { ProgressLogger log = new ProgressLogger("GroupManager"); log.addListener(plugin.getConsoleSender()); log.addListener(sender);/*from w ww . ja v a2 s .co m*/ log.log("Starting."); if (!args.get(0).equalsIgnoreCase("true") && !args.get(0).equalsIgnoreCase("false")) { log.logErr("Was expecting true/false, but got " + args.get(0) + " instead."); return CommandResult.STATE_ERROR; } boolean migrateAsGlobal = Boolean.parseBoolean(args.get(0)); final Function<String, String> worldMappingFunc = s -> migrateAsGlobal ? "" : s; if (!Bukkit.getPluginManager().isPluginEnabled("GroupManager")) { log.logErr("Plugin not loaded."); return CommandResult.STATE_ERROR; } List<String> worlds = Bukkit.getWorlds().stream().map(World::getName).map(String::toLowerCase) .collect(Collectors.toList()); GroupManager gm = (GroupManager) Bukkit.getPluginManager().getPlugin("GroupManager"); // Migrate Global Groups log.log("Starting global group migration."); GlobalGroups gg = GroupManager.getGlobalGroups(); AtomicInteger globalGroupCount = new AtomicInteger(0); for (Group g : gg.getGroupList()) { plugin.getStorage().createAndLoadGroup(g.getName().toLowerCase(), CreationCause.INTERNAL).join(); me.lucko.luckperms.common.core.model.Group group = plugin.getGroupManager() .getIfLoaded(g.getName().toLowerCase()); for (String node : g.getPermissionList()) { boolean value = true; if (node.startsWith("!") || node.startsWith("-")) { node = node.substring(1); value = false; } else if (node.startsWith("+")) { node = node.substring(1); value = true; } try { group.setPermission(node, value); } catch (Exception ex) { log.handleException(ex); } } for (String s : g.getInherits()) { try { group.setPermission("group." + s.toLowerCase(), true); } catch (Exception ex) { log.handleException(ex); } } plugin.getStorage().saveGroup(group); log.logAllProgress("Migrated {} groups so far.", globalGroupCount.incrementAndGet()); } log.log("Migrated " + globalGroupCount.get() + " global groups"); // Collect data // UUID --> Map<Entry<String, String>, Boolean> where k=world, v = node Map<UUID, Map<Map.Entry<String, String>, Boolean>> users = new HashMap<>(); // UUID --> primary group name Map<UUID, String> primaryGroups = new HashMap<>(); // String --> Map<Entry<String, String>, Boolean> where k=world, v = node Map<String, Map<Map.Entry<String, String>, Boolean>> groups = new HashMap<>(); WorldsHolder wh = gm.getWorldsHolder(); // Collect data for all users and groups. log.log("Collecting user and group data."); for (String world : worlds) { world = world.toLowerCase(); log.log("Querying world " + world); WorldDataHolder wdh = wh.getWorldData(world); AtomicInteger groupWorldCount = new AtomicInteger(0); for (Group g : wdh.getGroupList()) { groups.putIfAbsent(g.getName().toLowerCase(), new HashMap<>()); for (String node : g.getPermissionList()) { boolean value = true; if (node.startsWith("!") || node.startsWith("-")) { node = node.substring(1); value = false; } else if (node.startsWith("+")) { node = node.substring(1); value = true; } groups.get(g.getName().toLowerCase()) .put(Maps.immutableEntry(worldMappingFunc.apply(world), node), value); } for (String s : g.getInherits()) { groups.get(g.getName().toLowerCase()).put( Maps.immutableEntry(worldMappingFunc.apply(world), "group." + s.toLowerCase()), true); } log.logAllProgress("Migrated {} groups so far in world " + world, groupWorldCount.incrementAndGet()); } log.log("Migrated " + groupWorldCount.get() + " groups in world " + world); AtomicInteger userWorldCount = new AtomicInteger(0); for (User user : wdh.getUserList()) { UUID uuid; try { uuid = UUID.fromString(user.getUUID()); } catch (IllegalArgumentException e) { log.logErr("Could not parse UUID for user: " + user.getUUID()); continue; } users.putIfAbsent(uuid, new HashMap<>()); for (String node : user.getPermissionList()) { boolean value = true; if (node.startsWith("!") || node.startsWith("-")) { node = node.substring(1); value = false; } else if (node.startsWith("+")) { node = node.substring(1); value = true; } users.get(uuid).put(Maps.immutableEntry(worldMappingFunc.apply(world), node), value); } String finalWorld = worldMappingFunc.apply(world); // Collect sub groups users.get(uuid).putAll(user.subGroupListStringCopy().stream().map(n -> "group." + n) .map(n -> Maps.immutableEntry(finalWorld, n)).collect(Collectors.toMap(n -> n, n -> true))); primaryGroups.put(uuid, user.getGroupName()); log.logProgress("Migrated {} users so far in world " + world, userWorldCount.incrementAndGet()); } log.log("Migrated " + userWorldCount.get() + " users in world " + world); } log.log("All data has now been processed, now starting the import process."); log.log("Found a total of " + users.size() + " users and " + groups.size() + " groups."); log.log("Starting group migration."); AtomicInteger groupCount = new AtomicInteger(0); for (Map.Entry<String, Map<Map.Entry<String, String>, Boolean>> e : groups.entrySet()) { plugin.getStorage().createAndLoadGroup(e.getKey(), CreationCause.INTERNAL).join(); me.lucko.luckperms.common.core.model.Group group = plugin.getGroupManager().getIfLoaded(e.getKey()); for (Map.Entry<Map.Entry<String, String>, Boolean> n : e.getValue().entrySet()) { // n.key.key = world // n.key.value = node // n.value = true/false try { if (n.getKey().getKey().equals("")) { group.setPermission(n.getKey().getValue(), n.getValue()); } else { group.setPermission(n.getKey().getValue(), n.getValue(), "global", n.getKey().getKey()); } } catch (Exception ex) { log.handleException(ex); } } plugin.getStorage().saveGroup(group); log.logAllProgress("Migrated {} groups so far.", groupCount.incrementAndGet()); } log.log("Migrated " + groupCount.get() + " groups"); log.log("Starting user migration."); AtomicInteger userCount = new AtomicInteger(0); for (Map.Entry<UUID, Map<Map.Entry<String, String>, Boolean>> e : users.entrySet()) { plugin.getStorage().loadUser(e.getKey(), "null").join(); me.lucko.luckperms.common.core.model.User user = plugin.getUserManager().get(e.getKey()); for (Map.Entry<Map.Entry<String, String>, Boolean> n : e.getValue().entrySet()) { // n.key.key = world // n.key.value = node // n.value = true/false try { if (n.getKey().getKey().equals("")) { user.setPermission(n.getKey().getValue(), n.getValue()); } else { user.setPermission(n.getKey().getValue(), n.getValue(), "global", n.getKey().getKey()); } } catch (Exception ex) { log.handleException(ex); } } String primaryGroup = primaryGroups.get(e.getKey()); if (primaryGroup != null) { try { user.setPermission("group." + primaryGroup, true); } catch (ObjectAlreadyHasException ignored) { } user.setPrimaryGroup(primaryGroup); try { user.unsetPermission("group.default"); } catch (ObjectLacksException ignored) { } } plugin.getStorage().saveUser(user); plugin.getUserManager().cleanup(user); log.logProgress("Migrated {} users so far.", userCount.incrementAndGet()); } log.log("Migrated " + userCount.get() + " users."); log.log("Success! Migration complete."); return CommandResult.SUCCESS; }
From source file:org.onosproject.store.primitives.impl.TranscodingAsyncConsistentMultimap.java
@Override public CompletableFuture<Collection<Map.Entry<K1, V1>>> entries() { return backingMap.entries() .thenApply(s -> s.stream().map( e -> Maps.immutableEntry(keyDecoder.apply(e.getKey()), valueDecoder.apply(e.getValue()))) .collect(Collectors.toSet())); }
From source file:me.lucko.luckperms.common.node.NodeFactory.java
private static Map.Entry<Integer, String> parseChatMetaNode(String type, String s) { if (!s.startsWith(type + ".")) { return null; }/* w w w . j a v a 2s.c om*/ Iterator<String> metaParts = META_SPLITTER.split(s.substring((type + ".").length())).iterator(); if (!metaParts.hasNext()) return null; String priority = metaParts.next(); if (!metaParts.hasNext()) return null; String value = metaParts.next(); try { int p = Integer.parseInt(priority); String v = LegacyNodeFactory.unescapeCharacters(value).intern(); return Maps.immutableEntry(p, v); } catch (NumberFormatException e) { return null; } }
From source file:omero.cmd.fs.OriginalMetadataRequestI.java
/** * Split the given string at the rightmost '=' character among those that are the least enclosed by some kind of bracket. * @param keyValue the key = value string * @return the extracted key and value, or <code>null</code> if there is no '=' character *//*from ww w.j av a 2 s . c o m*/ private static Map.Entry<String, String> splitOnEquals(String keyValue) { Integer equalsIndex = null; Integer equalsSmallestDepth = null; int currentIndex = 0; int currentDepth = 0; while (currentIndex < keyValue.length()) { switch (keyValue.charAt(currentIndex)) { case '(': case '[': case '{': currentDepth++; break; case ')': case ']': case '}': currentDepth--; break; case '=': if (equalsSmallestDepth == null || currentDepth <= equalsSmallestDepth) { equalsIndex = currentIndex; equalsSmallestDepth = currentDepth; } break; } currentIndex++; } if (equalsIndex == null) { return null; } else { return Maps.immutableEntry(keyValue.substring(0, equalsIndex).trim(), keyValue.substring(equalsIndex + 1).trim()); } }
From source file:org.spongepowered.api.service.permission.MemorySubjectData.java
@Override public boolean removeParent(Set<Context> contexts, Subject parent) { contexts = ImmutableSet.copyOf(contexts); while (true) { Map.Entry<String, String> removeEnt = Maps .immutableEntry(parent.getContainingCollection().getIdentifier(), parent.getIdentifier()); List<Map.Entry<String, String>> oldParents = this.parents.get(contexts); List<Map.Entry<String, String>> newParents; if (oldParents == null || !oldParents.contains(removeEnt)) { return false; }//from w ww .j av a 2s . c o m newParents = new ArrayList<Map.Entry<String, String>>(oldParents); newParents.remove(removeEnt); if (updateCollection(this.parents, contexts, oldParents, Collections.unmodifiableList(newParents))) { return true; } } }
From source file:me.lucko.luckperms.common.core.model.ImmutableNode.java
/** * Make an immutable node instance/*from w w w . ja va 2s. c om*/ * * @param permission the actual permission node * @param value the value (if it's *not* negated) * @param expireAt the time when the node will expire * @param server the server this node applies on * @param world the world this node applies on * @param contexts any additional contexts applying to this node */ public ImmutableNode(String permission, boolean value, boolean override, long expireAt, String server, String world, ContextSet contexts) { if (permission == null || permission.equals("")) { throw new IllegalArgumentException("Empty permission"); } if (server != null && (server.equalsIgnoreCase("global") || server.equals(""))) { server = null; } if (world != null && (world.equalsIgnoreCase("global") || world.equals(""))) { world = null; } if (world != null && server == null) { server = "global"; } this.permission = NodeFactory.unescapeDelimiters(permission, "/", "-", "$", "(", ")", "=", ","); this.value = value; this.override = override; this.expireAt = expireAt; this.server = NodeFactory.unescapeDelimiters(server, "/", "-"); this.world = NodeFactory.unescapeDelimiters(world, "/", "-"); this.contexts = contexts == null ? ContextSet.empty() : contexts.makeImmutable(); // Setup state isGroup = this.permission.toLowerCase().startsWith("group."); if (isGroup) { groupName = this.permission.substring("group.".length()); } isWildcard = this.permission.endsWith(".*"); wildcardLevel = (int) this.permission.chars().filter(num -> num == Character.getNumericValue('.')).count(); isMeta = NodeFactory.isMetaNode(this.permission); if (isMeta) { List<String> metaPart = Splitter.on(Patterns.compileDelimitedMatcher(".", "\\")).limit(2) .splitToList(getPermission().substring("meta.".length())); meta = Maps.immutableEntry(MetaUtils.unescapeCharacters(metaPart.get(0)), MetaUtils.unescapeCharacters(metaPart.get(1))); } isPrefix = NodeFactory.isPrefixNode(this.permission); if (isPrefix) { List<String> prefixPart = Splitter.on(Patterns.compileDelimitedMatcher(".", "\\")).limit(2) .splitToList(getPermission().substring("prefix.".length())); Integer i = Integer.parseInt(prefixPart.get(0)); prefix = Maps.immutableEntry(i, MetaUtils.unescapeCharacters(prefixPart.get(1))); } isSuffix = NodeFactory.isSuffixNode(this.permission); if (isSuffix) { List<String> suffixPart = Splitter.on(Patterns.compileDelimitedMatcher(".", "\\")).limit(2) .splitToList(getPermission().substring("suffix.".length())); Integer i = Integer.parseInt(suffixPart.get(0)); suffix = Maps.immutableEntry(i, MetaUtils.unescapeCharacters(suffixPart.get(1))); } resolvedShorthand = ImmutableList.copyOf(ShorthandParser.parseShorthand(getPermission())); serializedNode = calculateSerializedNode(); }