List of usage examples for com.google.common.collect ImmutableMap entrySet
public final ImmutableSet<Entry<K, V>> entrySet()
From source file:com.facebook.buck.android.exopackage.ExopackageInstaller.java
private void installFiles(String filesType, ImmutableMap<Path, Path> filesToInstall) throws Exception { try (SimplePerfEvent.Scope ignored = SimplePerfEvent.scope(eventBus, "multi_install_" + filesType); AutoCloseable ignored1 = device.createForward()) { // Make sure all the directories exist. filesToInstall.keySet().stream().map(p -> dataRoot.resolve(p).getParent()).distinct().forEach(p -> { try { device.mkDirP(p.toString()); } catch (Exception e) { throw new RuntimeException(e); }//from w w w . j a v a 2 s. co m }); // Plan the installation. Map<Path, Path> installPaths = filesToInstall.entrySet().stream() .collect(Collectors.toMap(entry -> dataRoot.resolve(entry.getKey()), entry -> projectFilesystem.resolve(entry.getValue()))); // Install the files. device.installFiles(filesType, installPaths); } }
From source file:org.kiji.scoring.impl.InternalFreshKijiTableReader.java
/** * Filter a map of Fresheners down to only those attached to columns in a given list. Columns * which do not have Fresheners attached will not be reflected in the return value of this * method. An empty return indicates that no Fresheners are attached to the given columns. * * @param columnsToFreshen a list of columns for which to get Fresheners. * @param fresheners a map of all available fresheners. This map will not be modified by this * method.//from ww w.j av a2 s. c o m * @return all Fresheners attached to columns in columnsToFresh available in fresheners. */ private static ImmutableMap<KijiColumnName, Freshener> filterFresheners( final ImmutableList<KijiColumnName> columnsToFreshen, final ImmutableMap<KijiColumnName, Freshener> fresheners) { final Map<KijiColumnName, Freshener> collectedFresheners = Maps.newHashMap(); for (KijiColumnName column : columnsToFreshen) { if (column.isFullyQualified()) { final Freshener freshener = fresheners.get(column); if (null != freshener) { collectedFresheners.put(column, freshener); } else { final KijiColumnName family = new KijiColumnName(column.getFamily(), null); final Freshener familyFreshener = fresheners.get(family); if (null != familyFreshener) { collectedFresheners.put(family, familyFreshener); } } } else { for (Map.Entry<KijiColumnName, Freshener> freshenerEntry : fresheners.entrySet()) { if (freshenerEntry.getKey().getFamily().equals(column.getFamily())) { collectedFresheners.put(freshenerEntry.getKey(), freshenerEntry.getValue()); } } } } return ImmutableMap.copyOf(collectedFresheners); }
From source file:com.facebook.buck.versions.VersionedTargetGraphBuilder.java
/** * Get/cache the transitive version info for this node. *//*from w w w .ja v a 2 s . c om*/ private VersionInfo getVersionInfo(TargetNode<?, ?> node) { VersionInfo info = this.versionInfo.get(node.getBuildTarget()); if (info != null) { return info; } Map<BuildTarget, ImmutableSet<Version>> versionDomain = new HashMap<>(); Optional<TargetNode<VersionedAliasDescription.Arg, ?>> versionedNode = TargetGraphVersionTransformations .getVersionedNode(node); if (versionedNode.isPresent()) { ImmutableMap<Version, BuildTarget> versions = versionedNode.get().getConstructorArg().versions; // Merge in the versioned deps and the version domain. versionDomain.put(node.getBuildTarget(), versions.keySet()); // If this version has only one possible choice, there's no need to wrap the constraints from // it's transitive deps in an implication constraint. if (versions.size() == 1) { Map.Entry<Version, BuildTarget> ent = versions.entrySet().iterator().next(); VersionInfo depInfo = getVersionInfo(getNode(ent.getValue())); versionDomain.putAll(depInfo.getVersionDomain()); } else { // For each version choice, inherit the transitive constraints by wrapping them in an // implication dependent on the specific version that pulls them in. for (Map.Entry<Version, BuildTarget> ent : versions.entrySet()) { VersionInfo depInfo = getVersionInfo(getNode(ent.getValue())); versionDomain.putAll(depInfo.getVersionDomain()); } } } else { // Merge in the constraints and version domain/deps from transitive deps. for (BuildTarget depTarget : TargetGraphVersionTransformations.getDeps(node)) { TargetNode<?, ?> dep = getNode(depTarget); if (TargetGraphVersionTransformations.isVersionPropagator(dep) || TargetGraphVersionTransformations.getVersionedNode(dep).isPresent()) { VersionInfo depInfo = getVersionInfo(dep); versionDomain.putAll(depInfo.getVersionDomain()); } } } info = VersionInfo.of(versionDomain); this.versionInfo.put(node.getBuildTarget(), info); return info; }
From source file:me.lucko.luckperms.bukkit.LPBukkitPlugin.java
@Override public void onEnable() { scheduler = new LPBukkitScheduler(this); localeManager = new NoopLocaleManager(); senderFactory = new BukkitSenderFactory(this); log = new LoggerImpl(getConsoleSender()); LuckPermsPlugin.sendStartupBanner(getConsoleSender(), this); ignoringLogs = ConcurrentHashMap.newKeySet(); debugHandler = new DebugHandler(scheduler.getAsyncBukkitExecutor(), getVersion()); permissionCache = new PermissionCache(scheduler.getAsyncBukkitExecutor()); getLog().info("Loading configuration..."); configuration = new BukkitConfig(this); configuration.init();//from w w w .j a va 2s .com configuration.loadAll(); Set<StorageType> storageTypes = StorageFactory.getRequiredTypes(this, StorageType.H2); DependencyManager.loadDependencies(this, storageTypes); // setup the Bukkit defaults hook defaultsProvider = new DefaultsProvider(); childPermissionProvider = new ChildPermissionProvider(); // give all plugins a chance to load their defaults, then refresh. scheduler.doSyncLater(() -> { defaultsProvider.refresh(); childPermissionProvider.setup(); getServer().getScheduler().runTaskAsynchronously(this, () -> { for (Map.Entry<String, Boolean> e : defaultsProvider.getOpDefaults().entrySet()) { permissionCache.offer(e.getKey()); } for (Map.Entry<String, Boolean> e : defaultsProvider.getNonOpDefaults().entrySet()) { permissionCache.offer(e.getKey()); } ImmutableMap<Map.Entry<String, Boolean>, ImmutableMap<String, Boolean>> permissions = childPermissionProvider .getPermissions(); for (Map.Entry<Map.Entry<String, Boolean>, ImmutableMap<String, Boolean>> e : permissions .entrySet()) { permissionCache.offer(e.getKey().getKey()); for (Map.Entry<String, Boolean> e1 : e.getValue().entrySet()) { permissionCache.offer(e1.getKey()); } } }); }, 1L); // register events PluginManager pm = getServer().getPluginManager(); listener = new BukkitListener(this); pm.registerEvents(listener, this); // initialise datastore storage = StorageFactory.getInstance(this, StorageType.H2); // initialise messaging String messagingType = getConfiguration().get(ConfigKeys.MESSAGING_SERVICE).toLowerCase(); if (messagingType.equals("none") && getConfiguration().get(ConfigKeys.REDIS_ENABLED)) { messagingType = "redis"; } if (messagingType.equals("redis")) { getLog().info("Loading redis..."); if (getConfiguration().get(ConfigKeys.REDIS_ENABLED)) { RedisMessaging redis = new RedisMessaging(this); try { redis.init(getConfiguration().get(ConfigKeys.REDIS_ADDRESS), getConfiguration().get(ConfigKeys.REDIS_PASSWORD)); getLog().info("Loaded redis successfully..."); messagingService = redis; } catch (Exception e) { getLog().warn("Couldn't load redis..."); e.printStackTrace(); } } else { getLog().warn("Messaging Service was set to redis, but redis is not enabled!"); } } else if (messagingType.equals("bungee")) { getLog().info("Loading bungee messaging service..."); BungeeMessagingService bungeeMessaging = new BungeeMessagingService(this); bungeeMessaging.init(); messagingService = bungeeMessaging; } else if (messagingType.equals("lilypad")) { getLog().info("Loading LilyPad messaging service..."); if (getServer().getPluginManager().getPlugin("LilyPad-Connect") == null) { getLog().warn("LilyPad-Connect plugin not present."); } else { LilyPadMessagingService lilyPadMessaging = new LilyPadMessagingService(this); lilyPadMessaging.init(); messagingService = lilyPadMessaging; } } else if (!messagingType.equals("none")) { getLog().warn("Messaging service '" + messagingType + "' not recognised."); } // setup the update task buffer updateTaskBuffer = new BufferedRequest<Void>(1000L, this::doAsync) { @Override protected Void perform() { new UpdateTask(LPBukkitPlugin.this).run(); return null; } }; // load locale localeManager = new SimpleLocaleManager(); File locale = new File(getDataFolder(), "lang.yml"); if (locale.exists()) { getLog().info("Found locale file. Attempting to load from it."); try { localeManager.loadFromFile(locale); } catch (Exception e) { e.printStackTrace(); } } // register commands getLog().info("Registering commands..."); BukkitCommand commandManager = new BukkitCommand(this); PluginCommand main = getServer().getPluginCommand("luckperms"); main.setExecutor(commandManager); main.setTabCompleter(commandManager); main.setAliases(Arrays.asList("perms", "lp", "permissions", "perm")); // load internal managers getLog().info("Loading internal permission managers..."); uuidCache = new UuidCache(this); userManager = new GenericUserManager(this); groupManager = new GenericGroupManager(this); trackManager = new GenericTrackManager(); importer = new Importer(commandManager); calculatorFactory = new BukkitCalculatorFactory(this); cachedStateManager = new CachedStateManager(this); contextManager = new ContextManager<>(); worldCalculator = new WorldCalculator(this); pm.registerEvents(worldCalculator, this); contextManager.registerCalculator(worldCalculator); contextManager.registerCalculator(new ServerCalculator<>(getConfiguration())); // Provide vault support tryVaultHook(false); // register with the LP API getLog().info("Registering API..."); apiProvider = new ApiProvider(this); ApiHandler.registerProvider(apiProvider); getServer().getServicesManager().register(LuckPermsApi.class, apiProvider, this, ServicePriority.Normal); // schedule update tasks int mins = getConfiguration().get(ConfigKeys.SYNC_TIME); if (mins > 0) { long ticks = mins * 60 * 20; scheduler.doAsyncRepeating(() -> updateTaskBuffer.request(), ticks); } scheduler.doAsyncLater(() -> updateTaskBuffer.request(), 40L); // run an update instantly. updateTaskBuffer.requestDirectly(); // register tasks scheduler.doAsyncRepeating(new ExpireTemporaryTask(this), 60L); scheduler.doAsyncRepeating(new CacheHousekeepingTask(this), 2400L); // register permissions registerPermissions(getConfiguration().get(ConfigKeys.COMMANDS_ALLOW_OP) ? PermissionDefault.OP : PermissionDefault.FALSE); if (!getConfiguration().get(ConfigKeys.OPS_ENABLED)) { scheduler.doSync(() -> getServer().getOperators().forEach(o -> o.setOp(false))); } // replace the temporary executor when the Bukkit one starts getServer().getScheduler().runTaskAsynchronously(this, () -> { scheduler.setUseBukkitAsync(true); }); // Load any online users (in the case of a reload) for (Player player : getServer().getOnlinePlayers()) { scheduler.doAsync(() -> { listener.onAsyncLogin(player.getUniqueId(), player.getName()); User user = getUserManager().get(getUuidCache().getUUID(player.getUniqueId())); if (user != null) { scheduler.doSync(() -> { try { LPPermissible lpPermissible = new LPPermissible(player, user, this); Injector.inject(player, lpPermissible); } catch (Throwable t) { t.printStackTrace(); } }); } }); } started = true; getLog().info("Successfully loaded."); }
From source file:google.registry.tools.RegistryCli.java
void run(String programName, String[] args, ImmutableMap<String, ? extends Class<? extends Command>> commands) throws Exception { Security.addProvider(new BouncyCastleProvider()); JCommander jcommander = new JCommander(this); jcommander.addConverterFactory(new ParameterFactory()); jcommander.setProgramName(programName); // Store the instances of each Command class here so we can retrieve the same one for the // called command later on. JCommander could have done this for us, but it doesn't. Map<String, Command> commandInstances = new HashMap<>(); HelpCommand helpCommand = new HelpCommand(jcommander); jcommander.addCommand("help", helpCommand); commandInstances.put("help", helpCommand); for (Map.Entry<String, ? extends Class<? extends Command>> entry : commands.entrySet()) { Command command = entry.getValue().newInstance(); jcommander.addCommand(entry.getKey(), command); commandInstances.put(entry.getKey(), command); }/*w ww .j a v a 2 s. c o m*/ try { jcommander.parse(args); } catch (ParameterException e) { // If we failed to fully parse the command but at least found a valid command name, show only // the usage for that command. Otherwise, show full usage. Either way, rethrow the error. if (jcommander.getParsedCommand() == null) { jcommander.usage(); } else { jcommander.usage(jcommander.getParsedCommand()); } // Don't rethrow if we said: nomulus command --help if ("Unknown option: --help".equals(e.getMessage())) { return; } throw e; } if (showAllCommands) { for (Map.Entry<String, ? extends Class<? extends Command>> entry : commands.entrySet()) { System.out.println(entry.getKey()); } return; } checkState(RegistryToolEnvironment.get() == environment, "RegistryToolEnvironment argument pre-processing kludge failed."); Command command = commandInstances.get(jcommander.getParsedCommand()); if (command == null) { jcommander.usage(); return; } loggingParams.configureLogging(); // Must be called after parameters are parsed. // Decide which HTTP connection to use for App Engine HttpRequestFactoryComponent requestFactoryComponent; if (appEngineConnectionFlags.getServer().getHostText().equals("localhost")) { requestFactoryComponent = new LocalhostRequestFactoryComponent(); } else { requestFactoryComponent = new BasicHttpRequestFactoryComponent(); } // Create the main component and use it to inject the command class. RegistryToolComponent component = DaggerRegistryToolComponent.builder() .httpRequestFactoryComponent(requestFactoryComponent) .appEngineConnectionFlagsModule(new AppEngineConnectionFlagsModule(appEngineConnectionFlags)) .build(); injectReflectively(RegistryToolComponent.class, component, command); if (!(command instanceof RemoteApiCommand)) { command.run(); return; } AppEngineConnection connection = component.appEngineConnection(); if (command instanceof ServerSideCommand) { ((ServerSideCommand) command).setConnection(connection); } // RemoteApiCommands need to have the remote api installed to work. RemoteApiInstaller installer = new RemoteApiInstaller(); RemoteApiOptions options = new RemoteApiOptions(); options.server(connection.getServer().getHostText(), connection.getServer().getPort()); if (connection.isLocalhost()) { // Use dev credentials for localhost. options.useDevelopmentServerCredential(); } else { options.useApplicationDefaultCredential(); } installer.install(options); // Ensure that all entity classes are loaded before command code runs. ObjectifyService.initOfy(); try { command.run(); } finally { installer.uninstall(); } }
From source file:org.elasticsearch.cluster.block.ClusterBlocks.java
ClusterBlocks(ImmutableSet<ClusterBlock> global, ImmutableMap<String, ImmutableSet<ClusterBlock>> indicesBlocks) { this.global = global; this.indicesBlocks = indicesBlocks; levelHolders = new ImmutableLevelHolder[ClusterBlockLevel.values().length]; for (ClusterBlockLevel level : ClusterBlockLevel.values()) { ImmutableSet.Builder<ClusterBlock> globalBuilder = ImmutableSet.builder(); for (ClusterBlock block : global) { if (block.contains(level)) { globalBuilder.add(block); }/* www. jav a2 s.c o m*/ } ImmutableMap.Builder<String, ImmutableSet<ClusterBlock>> indicesBuilder = ImmutableMap.builder(); for (Map.Entry<String, ImmutableSet<ClusterBlock>> entry : indicesBlocks.entrySet()) { ImmutableSet.Builder<ClusterBlock> indexBuilder = ImmutableSet.builder(); for (ClusterBlock block : entry.getValue()) { if (block.contains(level)) { indexBuilder.add(block); } } indicesBuilder.put(entry.getKey(), indexBuilder.build()); } levelHolders[level.id()] = new ImmutableLevelHolder(globalBuilder.build(), indicesBuilder.build()); } }
From source file:com.facebook.buck.cxx.AbstractCxxSourceRuleFactory.java
public ImmutableSet<CxxInferCapture> requireInferCaptureBuildRules(ImmutableMap<String, CxxSource> sources, InferBuckConfig inferConfig, CxxInferSourceFilter sourceFilter) { ImmutableSet.Builder<CxxInferCapture> objects = ImmutableSet.builder(); for (Map.Entry<String, CxxSource> entry : sources.entrySet()) { String name = entry.getKey(); CxxSource source = entry.getValue(); Preconditions.checkState(CxxSourceTypes.isPreprocessableType(source.getType()), "Only preprocessable source types are currently supported"); if (sourceFilter.isBlacklisted(source)) { continue; }//from w w w .jav a 2 s.c o m CxxInferCapture rule = requireInferCaptureBuildRule(name, source, inferConfig); objects.add(rule); } return objects.build(); }
From source file:org.apache.abdera2.common.protocol.Session.java
public boolean doFormLogin(String uri, String userfield, String userid, String passfield, String password, ImmutableMap<String, String> additional) { try {/*from ww w . ja va 2s. c o m*/ HttpPost httpost = new HttpPost(uri); ImmutableList.Builder<BasicNameValuePair> pairs = ImmutableList.<BasicNameValuePair>builder() .add(new BasicNameValuePair(userfield, userid)) .add(new BasicNameValuePair(passfield, password)); for (Map.Entry<String, String> entry : additional.entrySet()) pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); httpost.setEntity(new UrlEncodedFormEntity(pairs.build(), HTTP.UTF_8)); HttpResponse response = getClient().execute(httpost, localContext); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); ResponseType type = ResponseType.select(response.getStatusLine().getStatusCode()); return type == ResponseType.SUCCESSFUL; } catch (Throwable t) { throw new RuntimeException(t); } }
From source file:com.netflix.priam.resources.CassandraAdminResource.java
@GET @Path("/tpstats") public Response tpstats() throws Exception { final JMXNodeTool nodetool = getNodeTool(); final Iterable<Stage> stages = Stage.jmxEnabledStages(); final List<Map<String, Object>> threadPoolArray = Lists.newArrayList(); final ImmutableMap<String, String> metricNames = ImmutableMap.<String, String>builder() .put("ActiveTasks", "active").put("PendingTasks", "pending").put("CompletedTasks", "completed") .put("TotalBlockedTasks", "total blocked").put("CurrentlyBlockedTasks", "blocked") .put("MaxPoolSize", "max size").build(); for (final Stage stage : stages) { final Map<String, Object> tpObj = Maps.newLinkedHashMap(); tpObj.put("pool name", stage.getJmxName()); for (final Entry<String, String> metricName : metricNames.entrySet()) { final Object tpStat = nodetool.getThreadPoolMetric(stage, metricName.getKey()); tpObj.put(metricName.getValue(), tpStat); }//w w w.ja v a 2 s.c o m threadPoolArray.add(tpObj); } Map<String, Object> droppedMsgs = Maps.newLinkedHashMap(); for (Entry<String, Integer> entry : nodetool.getDroppedMessages().entrySet()) { droppedMsgs.put(entry.getKey(), entry.getValue()); } Map<String, Object> rootObj = Maps.newLinkedHashMap(); rootObj.put("thread pool", threadPoolArray); rootObj.put("dropped messages", droppedMsgs); return Response.ok(rootObj, MediaType.APPLICATION_JSON).build(); }
From source file:com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider.java
private Environment.Frame createGlobals(ImmutableMap<String, Object> skylarkAccessibleToplLevels, ImmutableList<Class<?>> modules) { try (Mutability mutability = Mutability.create("ConfiguredRuleClassProvider globals")) { Environment env = createSkylarkRuleClassEnvironment(mutability, SkylarkModules.getGlobals(modules), null, null, null);/*www . j a va 2 s. co m*/ for (Map.Entry<String, Object> entry : skylarkAccessibleToplLevels.entrySet()) { env.setup(entry.getKey(), entry.getValue()); } return env.getGlobals(); } }