List of usage examples for com.google.common.collect ImmutableMap keySet
public ImmutableSet<K> keySet()
From source file:org.gradle.plugins.ide.eclipse.internal.EclipseNameDeduper.java
public void configureRoot(Project rootProject) { Set<Project> projects = Sets.filter(rootProject.getAllprojects(), HAS_ECLIPSE_PLUGIN); ImmutableMap<EclipseProject, Project> eclipseProjects = Maps.uniqueIndex(projects, GET_ECLIPSE_PROJECT); HierarchicalElementDeduplicator<EclipseProject> deduplicator = new HierarchicalElementDeduplicator<EclipseProject>( new EclipseDeduplicationAdapter(eclipseProjects)); Map<EclipseProject, String> deduplicated = deduplicator.deduplicate(eclipseProjects.keySet()); for (Map.Entry<EclipseProject, String> entry : deduplicated.entrySet()) { entry.getKey().setName(entry.getValue()); }/*from www . j av a 2 s.c o m*/ }
From source file:io.druid.indexing.overlord.setup.EqualDistributionWithAffinityWorkerSelectStrategy.java
@Override public Optional<ImmutableWorkerInfo> findWorkerForTask(final WorkerTaskRunnerConfig config, final ImmutableMap<String, ImmutableWorkerInfo> zkWorkers, final Task task) { // don't run other datasources on affinity workers; we only want our configured datasources to run on them ImmutableMap.Builder<String, ImmutableWorkerInfo> builder = new ImmutableMap.Builder<>(); for (String workerHost : zkWorkers.keySet()) { if (!affinityWorkerHosts.contains(workerHost)) { builder.put(workerHost, zkWorkers.get(workerHost)); }//from ww w . j av a 2s .c o m } ImmutableMap<String, ImmutableWorkerInfo> eligibleWorkers = builder.build(); List<String> workerHosts = affinityConfig.getAffinity().get(task.getDataSource()); if (workerHosts == null) { return super.findWorkerForTask(config, eligibleWorkers, task); } ImmutableMap.Builder<String, ImmutableWorkerInfo> affinityBuilder = new ImmutableMap.Builder<>(); for (String workerHost : workerHosts) { ImmutableWorkerInfo zkWorker = zkWorkers.get(workerHost); if (zkWorker != null) { affinityBuilder.put(workerHost, zkWorker); } } ImmutableMap<String, ImmutableWorkerInfo> affinityWorkers = affinityBuilder.build(); if (!affinityWorkers.isEmpty()) { Optional<ImmutableWorkerInfo> retVal = super.findWorkerForTask(config, affinityWorkers, task); if (retVal.isPresent()) { return retVal; } } return super.findWorkerForTask(config, eligibleWorkers, task); }
From source file:com.facebook.buck.android.relinker.NativeRelinker.java
public NativeRelinker(BuildRuleParams buildRuleParams, SourcePathResolver resolver, SourcePathRuleFinder ruleFinder, CxxBuckConfig cxxBuckConfig, ImmutableMap<TargetCpuType, NdkCxxPlatform> nativePlatforms, ImmutableMap<Pair<TargetCpuType, String>, SourcePath> linkableLibs, ImmutableMap<Pair<TargetCpuType, String>, SourcePath> linkableLibsAssets) { this.ruleFinder = ruleFinder; Preconditions.checkArgument(!linkableLibs.isEmpty() || !linkableLibsAssets.isEmpty(), "There should be at least one native library to relink."); this.buildRuleParams = buildRuleParams; this.resolver = resolver; this.cxxBuckConfig = cxxBuckConfig; this.nativePlatforms = nativePlatforms; /*/*from w w w .ja v a 2 s . co m*/ When relinking a library, any symbols needed by a (transitive) dependent must continue to be exported. As relinking one of those dependents may change the set of symbols that it needs, we only need to keep the symbols that are still used after a library is relinked. So, this relinking process basically works in the reverse order of the original link process. As each library is relinked, we now know the set of symbols that are needed in that library's dependencies. For linkables that can't be resolved to a BuildRule, we can't tell what libraries that one depends on. So, we essentially assume that everything depends on it. */ ImmutableMap.Builder<BuildRule, Pair<TargetCpuType, SourcePath>> ruleMapBuilder = ImmutableMap.builder(); ImmutableSet.Builder<Pair<TargetCpuType, SourcePath>> copiedLibraries = ImmutableSet.builder(); for (Map.Entry<Pair<TargetCpuType, String>, SourcePath> entry : Iterables.concat(linkableLibs.entrySet(), linkableLibsAssets.entrySet())) { SourcePath source = entry.getValue(); Optional<BuildRule> rule = ruleFinder.getRule(source); if (rule.isPresent()) { ruleMapBuilder.put(rule.get(), new Pair<>(entry.getKey().getFirst(), source)); } else { copiedLibraries.add(new Pair<>(entry.getKey().getFirst(), source)); } } ImmutableMap<BuildRule, Pair<TargetCpuType, SourcePath>> ruleMap = ruleMapBuilder.build(); ImmutableSet<BuildRule> linkableRules = ruleMap.keySet(); // Now, for every linkable build rule, we need to figure out all the other linkable build rules // that could depend on it (or rather, could use symbols from it). // This is the sub-graph that includes the linkableRules and all the dependents (including // non-linkable rules). final DirectedAcyclicGraph<BuildRule> graph = getBuildGraph(linkableRules); ImmutableList<BuildRule> sortedRules = TopologicalSort.sort(graph); // This maps a build rule to every rule in linkableRules that depends on it. This (added to the // copied libraries) is the set of linkables that could use a symbol from this build rule. ImmutableMap<BuildRule, ImmutableSet<BuildRule>> allDependentsMap = getAllDependentsMap(linkableRules, graph, sortedRules); ImmutableMap.Builder<SourcePath, SourcePath> pathMap = ImmutableMap.builder(); // Create the relinker rules for the libraries that couldn't be resolved back to a base rule. ImmutableList.Builder<RelinkerRule> relinkRules = ImmutableList.builder(); for (Pair<TargetCpuType, SourcePath> p : copiedLibraries.build()) { // TODO(cjhopman): We shouldn't really need a full RelinkerRule at this point. We know that we // are just going to copy it, we could just leave these libraries in place and only calculate // the list of needed symbols. TargetCpuType cpuType = p.getFirst(); SourcePath source = p.getSecond(); RelinkerRule relink = makeRelinkerRule(cpuType, source, ImmutableList.of()); relinkRules.add(relink); pathMap.put(source, relink.getLibFileSourcePath()); } ImmutableList<RelinkerRule> copiedLibrariesRules = relinkRules.build(); // Process the remaining linkable rules in the reverse sorted order. This makes it easy to refer // to the RelinkerRules of dependents. Iterable<Pair<TargetCpuType, SourcePath>> sortedPaths = FluentIterable.from(sortedRules) .filter(linkableRules::contains).transform(Functions.forMap(ruleMap)).toList().reverse(); Map<BuildRule, RelinkerRule> relinkerMap = new HashMap<>(); for (Pair<TargetCpuType, SourcePath> p : sortedPaths) { TargetCpuType cpuType = p.getFirst(); SourcePath source = p.getSecond(); BuildRule baseRule = ruleFinder.getRuleOrThrow((BuildTargetSourcePath) source); // Relinking this library must keep any of the symbols needed by the libraries from the rules // in relinkerDeps. ImmutableList<RelinkerRule> relinkerDeps = ImmutableList.<RelinkerRule>builder() .addAll(copiedLibrariesRules) .addAll(Lists.transform(ImmutableList.copyOf(allDependentsMap.get(baseRule)), Functions.forMap(relinkerMap))) .build(); RelinkerRule relink = makeRelinkerRule(cpuType, source, relinkerDeps); relinkRules.add(relink); pathMap.put(source, relink.getLibFileSourcePath()); relinkerMap.put(baseRule, relink); } Function<SourcePath, SourcePath> pathMapper = Functions.forMap(pathMap.build()); rules = relinkRules.build(); relinkedLibs = ImmutableMap.copyOf(Maps.transformValues(linkableLibs, pathMapper)); relinkedLibsAssets = ImmutableMap.copyOf(Maps.transformValues(linkableLibsAssets, pathMapper)); }
From source file:com.clearclouds.driver.monitor.jvm.DeadlockAnalyzer.java
private Set<LinkedHashSet<ThreadInfo>> calculateCycleDeadlockChains( ImmutableMap<Long, ThreadInfo> threadInfoMap, Set<LinkedHashSet<ThreadInfo>> cycles) { ThreadInfo allThreads[] = threadBean.getThreadInfo(threadBean.getAllThreadIds()); Set<LinkedHashSet<ThreadInfo>> deadlockChain = new HashSet<>(); Set<Long> knownDeadlockedThreads = threadInfoMap.keySet(); for (ThreadInfo threadInfo : allThreads) { Thread.State state = threadInfo.getThreadState(); if (state == Thread.State.BLOCKED && !knownDeadlockedThreads.contains(threadInfo.getThreadId())) { for (LinkedHashSet cycle : cycles) { if (cycle.contains(threadInfoMap.get(Long.valueOf(threadInfo.getLockOwnerId())))) { LinkedHashSet<ThreadInfo> chain = new LinkedHashSet<>(); for (ThreadInfo node = threadInfo; !chain.contains(node); node = threadInfoMap .get(Long.valueOf(node.getLockOwnerId()))) chain.add(node); deadlockChain.add(chain); }/*from www. j a va 2 s . c o m*/ } } } return deadlockChain; }
From source file:com.opengamma.strata.pricer.swaption.HullWhiteSwaptionPhysicalProductPricer.java
/** * Calculates the present value sensitivity of the swaption product. * <p>/* w w w . j a va 2 s . c om*/ * The present value sensitivity of the product is the sensitivity of the present value to * the underlying curves. * * @param swaption the product * @param ratesProvider the rates provider * @param hwProvider the Hull-White model parameter provider * @return the point sensitivity to the rate curves */ public PointSensitivityBuilder presentValueSensitivityRates(ResolvedSwaption swaption, RatesProvider ratesProvider, HullWhiteOneFactorPiecewiseConstantParametersProvider hwProvider) { validate(swaption, ratesProvider, hwProvider); ResolvedSwap swap = swaption.getUnderlying(); LocalDate expiryDate = swaption.getExpiryDate(); if (expiryDate.isBefore(ratesProvider.getValuationDate())) { // Option has expired already return PointSensitivityBuilder.none(); } ImmutableMap<Payment, PointSensitivityBuilder> cashFlowEquivSensi = CashFlowEquivalentCalculator .cashFlowEquivalentAndSensitivitySwap(swap, ratesProvider); ImmutableList<Payment> list = cashFlowEquivSensi.keySet().asList(); ImmutableList<PointSensitivityBuilder> listSensi = cashFlowEquivSensi.values().asList(); int nPayments = list.size(); double[] alpha = new double[nPayments]; double[] discountedCashFlow = new double[nPayments]; for (int loopcf = 0; loopcf < nPayments; loopcf++) { Payment payment = list.get(loopcf); alpha[loopcf] = hwProvider.alpha(ratesProvider.getValuationDate(), expiryDate, expiryDate, payment.getDate()); discountedCashFlow[loopcf] = paymentPricer.presentValueAmount(payment, ratesProvider); } double omega = (swap.getLegs(SwapLegType.FIXED).get(0).getPayReceive().isPay() ? -1d : 1d); double kappa = computeKappa(hwProvider, discountedCashFlow, alpha, omega); PointSensitivityBuilder point = PointSensitivityBuilder.none(); for (int loopcf = 0; loopcf < nPayments; loopcf++) { Payment payment = list.get(loopcf); double cdf = NORMAL.getCDF(omega * (kappa + alpha[loopcf])); point = point .combinedWith(paymentPricer.presentValueSensitivity(payment, ratesProvider).multipliedBy(cdf)); if (!listSensi.get(loopcf).equals(PointSensitivityBuilder.none())) { point = point.combinedWith(listSensi.get(loopcf).multipliedBy( cdf * ratesProvider.discountFactor(payment.getCurrency(), payment.getDate()))); } } return swaption.getLongShort().isLong() ? point : point.multipliedBy(-1d); }
From source file:no.ssb.vtl.model.Order.java
Order(DataStructure structure, ImmutableMap<Component, Direction> orders) { this.delegate = ImmutableMap.copyOf(orders); this.structure = checkNotNull(structure); ArrayList<Integer> indices = Lists.newArrayList(); ArrayList<Direction> directions = Lists.newArrayList(); for (Component component : orders.keySet()) { indices.add(structure.indexOf(component)); directions.add(orders.get(component)); }//from w w w . ja va 2 s . c o m this.indices = Ints.toArray(indices); this.directions = directions.toArray(new Direction[] {}); }
From source file:com.nesscomputing.cache.guava.GuavaCacheAdapter.java
@SuppressWarnings("unchecked") // Safe because the resulting Map is immutable and we only widen the key / narrow the value @Override//from w w w .j a v a2 s . c o m public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException { ImmutableMap<K, V> partialResult = getAllPresent(keys); Set<? extends K> remaining = ImmutableSet.copyOf(Iterables.filter(keys, not(in(partialResult.keySet())))); if (remaining.isEmpty()) { return partialResult; } Map<K, V> loaded = null; try { if (!bulkLoadFailed.get()) { loaded = (Map<K, V>) loader.loadAll(remaining); } } catch (UnsupportedOperationException e) { if (bulkLoadFailed.compareAndSet(false, true)) { LOG.warn(e, "Cache loader %s does not support bulk loads, disabling. Could get a nice performance benefit here!", loader); } } catch (Exception e) { LOG.error(e, "Exception from cache loader during getAll"); return partialResult; } if (loaded == null) { loaded = Maps.newHashMap(); for (K key : remaining) { try { loaded.put(key, loader.load(key)); } catch (Exception e) { LOG.error(e, "Exception from cache loader during getAll"); } } } for (Entry<K, V> e : loaded.entrySet()) { put(e.getKey(), e.getValue()); } if (!loaded.keySet().containsAll(remaining)) { throw new IncompleteCacheLoadException( String.format("loader %s did not return keys %s for request of %s", loader, Sets.difference(remaining, loaded.keySet()), remaining)); } return ImmutableMap.<K, V>builder().putAll(partialResult).putAll(loaded).build(); }
From source file:net.sf.e4ftrace.ui.model.TraceModelImplFactory.java
public TraceImpl[] createFTraces(TraceService traceService, URI uri) throws ExecutionException { ImmutableTable<Integer, Short, ITrace> data = traceService.fetch(uri, 0); UnmodifiableIterator<Integer> it = data.rowKeySet().iterator(); ArrayList<TraceImpl> rList = Lists.<TraceImpl>newArrayList(); Random random = new Random(); /* While Tasks */ while (it.hasNext()) { int atomId = it.next(); String name = TraceBiMap.getStringValue(atomId); ImmutableMap<Short, ITrace> traces = data.row(atomId); UnmodifiableIterator<Short> ck = traces.keySet().iterator(); /* While Cores */ while (ck.hasNext()) { short cpuid = ck.next(); ITrace trace = traces.get(cpuid); TraceImpl traceImpl = new TraceImpl(name, name); Iterator<IEvent> ei = trace.getEventsIterator(); long prevStamp = 0; EventImpl prevEventImpl = null; TreeSet<Long> tsSet = Sets.<Long>newTreeSet(); /* While Events */ while (ei.hasNext()) { IEvent event = ei.next(); long timestamp = event.getTime(); tsSet.add(timestamp);/*from w w w. ja va2 s. c om*/ int type = random.nextInt(8) % 7; EventImpl eventImpl = new EventImpl(timestamp, traceImpl, getEventType(type)); if (prevStamp != 0) { long duration = timestamp - prevStamp; prevEventImpl.setDuration(duration); traceImpl.addTraceEvent(prevEventImpl); } prevStamp = timestamp; prevEventImpl = eventImpl; } long timeStart = tsSet.first(); long timeEnd = tsSet.last(); traceImpl.setStartTime(timeStart); traceImpl.setStopTime(timeEnd); rList.add(traceImpl); } } TraceImpl[] ra = rList.toArray(new TraceImpl[rList.size()]); return ra; }
From source file:org.androidtransfuse.model.MethodDescriptor.java
public MethodDescriptor(JMethod method, ASTMethod astMethod, ImmutableMap<ASTParameter, TypedExpression> parameterMap, ImmutableMap<ASTType, TypedExpression> typeMap) { this.method = method; this.astMethod = astMethod; this.parameterMap = parameterMap; this.blocks.push(method.body()); ImmutableMap.Builder<ASTType, TypedExpression> queryBuilder = ImmutableMap.builder(); Set<ASTType> duplicateTypes = new HashSet<ASTType>(); duplicateTypes.addAll(typeMap.keySet()); queryBuilder.putAll(typeMap);//from www .j a v a2 s. c o m for (Map.Entry<ASTParameter, TypedExpression> parameterEntry : parameterMap.entrySet()) { if (!duplicateTypes.contains(parameterEntry.getKey().getASTType())) { queryBuilder.put(parameterEntry.getKey().getASTType(), parameterEntry.getValue()); duplicateTypes.add(parameterEntry.getKey().getASTType()); } } this.querymap = queryBuilder.build(); }
From source file:mod.steamnsteel.structure.StructureDefinitionBuilder.java
/** * Define what each character represents within the block map * @param representation char to unlocalized block name map * @exception NullPointerException thrown if block doesn't exist. */// w w w .j a v a 2 s .co m public void assignBlockDefinitions(ImmutableMap<Character, String> representation) { Builder<Character, IBlockState> builder = ImmutableMap.builder(); for (final Character c : representation.keySet()) { final String blockName = representation.get(c); final Block block = Block.getBlockFromName(blockName); checkNotNull(block, "assignBlockDefinitions.Block does not exist " + blockName); builder.put(c, block.getDefaultState()); } //default builder.put(' ', Blocks.air.getDefaultState()); builder.put('-', StructureRegistry.generalNull); repBlock = builder.build(); }