List of usage examples for com.google.common.collect Maps uniqueIndex
public static <K, V> ImmutableMap<K, V> uniqueIndex(Iterator<V> values, Function<? super V, K> keyFunction)
From source file:com.kolich.blog.components.cache.EntryCache.java
@Subscribe public synchronized final void onEndReadCachedContent(final Events.EndReadCachedContentEvent e) { logger__.trace("onEndReadCachedContent: START: {}", e); // Sort the loaded entities in order based on commit date, not the natural ordering of the commits. // Oldest content/entities fall to the bottom regardless of when they were actually committed. That // is, using the Git environment variables GIT_AUTHOR_DATE and GIT_COMMITTER_DATE, you can commit to a // repo at some arbitrary point in the past. // #/> GIT_AUTHOR_DATE='Tue Dec 7 09:32:10 1982 -0800' \ // GIT_COMMITTER_DATE='Tue Dec 7 09:32:10 1982 -0800' \ // git commit // Sorting based on this commit date enforces that older content, recently committed to the repo, are // ordered correctly. final List<Entry> sorted = unsortedEntries_.stream().sorted((a, b) -> b.getDate().compareTo(a.getDate())) .collect(Collectors.toList()); // Transform the list of entities into a proper map that maps the entity name to itself. The key of the // map is the "name" of the entity, and the value is the entity. final Map<String, Entry> newCache = Maps.uniqueIndex(sorted, new Function<Entry, String>() { @Nullable/*w w w . jav a2 s. com*/ @Override public String apply(final Entry input) { checkNotNull(input, "Input cannot be null."); return input.getName(); } }); // Clear the existing cache and then add all new entries into it. This is essentially just a // synchronized "swap" in place. cache_.clear(); cache_.putAll(newCache); // Probably not really needed, but clear out the unsorted entries set for good measure. unsortedEntries_.clear(); logger__.debug("onEndReadCachedContent: END: {} -> {}", e, cache_); // Let any listeners know that the "entry cache" is ready and willing. eventBus_.post(Events.EntryCacheReadyEvent.newBuilder().setUuid(UUID.randomUUID().toString()) .setTimestamp(System.currentTimeMillis()).build()); }
From source file:com.metamx.druid.client.cache.MemcachedCache.java
@Override public Map<NamedKey, byte[]> getBulk(Iterable<NamedKey> keys) { Map<String, NamedKey> keyLookup = Maps.uniqueIndex(keys, new Function<NamedKey, String>() { @Override// w w w . ja va 2 s . co m public String apply(@Nullable NamedKey input) { return computeKeyHash(memcachedPrefix, input); } }); Map<NamedKey, byte[]> results = Maps.newHashMap(); BulkFuture<Map<String, Object>> future; try { future = client.asyncGetBulk(keyLookup.keySet()); } catch (IllegalStateException e) { // operation did not get queued in time (queue is full) errorCount.incrementAndGet(); log.warn(e, "Unable to queue cache operation"); return results; } try { Map<String, Object> some = future.getSome(timeout, TimeUnit.MILLISECONDS); if (future.isTimeout()) { future.cancel(false); timeoutCount.incrementAndGet(); } missCount.addAndGet(keyLookup.size() - some.size()); hitCount.addAndGet(some.size()); for (Map.Entry<String, Object> entry : some.entrySet()) { final NamedKey key = keyLookup.get(entry.getKey()); final byte[] value = (byte[]) entry.getValue(); results.put(key, value == null ? null : deserializeValue(key, value)); } return results; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } catch (ExecutionException e) { errorCount.incrementAndGet(); log.warn(e, "Exception pulling item from cache"); return results; } }
From source file:controllers.config.Config.java
private void overlayHostclass(final HostclassOutput hostclassOutput, final Hostclass hostclass) { final ImmutableMap<String, HostclassOutput.Package> oldPackageMap = Maps .uniqueIndex(hostclassOutput.getPackages().getProduction(), HostclassOutput.Package::getName); final Map<String, HostclassOutput.Package> newPackages = Maps.newHashMap(oldPackageMap); final ImmutableMap<String, HostclassOutput.Package> oldFailsafeMap = Maps .uniqueIndex(hostclassOutput.getPackages().getFailsafe(), HostclassOutput.Package::getName); final Map<String, HostclassOutput.Package> newFailsafe = Maps.newHashMap(oldFailsafeMap); final List<Stage> stages = Stage.getStagesForHostclass(hostclass); for (final Stage stage : stages) { final ManifestHistory snapshot = ManifestHistory.getCurrentForStage(stage); if (snapshot == null) { LOGGER.warn("snapshot for stage " + stage.getName() + "[" + stage.getId() + "] was null"); continue; }/*w ww. j ava 2s . c o m*/ final Manifest manifest = snapshot.getManifest(); for (final PackageVersion aPackage : manifest.getPackages()) { newPackages.put(aPackage.getPkg().getName(), new HostclassOutput.Package( String.format("%s-%s", aPackage.getPkg().getName(), aPackage.getVersion()))); } if (!Strings.isNullOrEmpty(snapshot.getConfig())) { injectConfig(snapshot, hostclassOutput); } } if (stages.size() > 0) { Configuration.root().getStringList("package.overlay").stream().map(HostclassOutput.Package::new) .forEach(p -> { newPackages.put(p.getName(), p); newFailsafe.put(p.getName(), p); }); } final ArrayList<HostclassOutput.Package> packageList = Lists.newArrayList(newPackages.values()); Collections.sort(packageList, Comparator.comparing(HostclassOutput.Package::getName)); hostclassOutput.getPackages().setProduction(Sets.newLinkedHashSet(packageList)); final ArrayList<HostclassOutput.Package> failsafeList = Lists.newArrayList(newFailsafe.values()); Collections.sort(failsafeList, Comparator.comparing(HostclassOutput.Package::getName)); hostclassOutput.getPackages().setFailsafe(Sets.newLinkedHashSet(failsafeList)); }
From source file:com.twitter.common.application.modules.LocalServiceRegistry.java
/** * Launches the local services if not already launched, otherwise this is a no-op. *//* ww w . j av a2 s.c om*/ void ensureLaunched() { if (primarySocket == null) { ImmutableList.Builder<LocalService> builder = ImmutableList.builder(); for (ServiceRunner runner : runnerProvider.get()) { try { LocalService service = runner.launch(); builder.add(service); shutdownRegistry.addAction(service.shutdownCommand); } catch (LaunchException e) { throw new IllegalStateException("Failed to launch " + runner, e); } } List<LocalService> localServices = builder.build(); Iterable<LocalService> primaries = Iterables.filter(localServices, IS_PRIMARY); switch (Iterables.size(primaries)) { case 0: primarySocket = Optional.absent(); break; case 1: primarySocket = Optional.of(SERVICE_TO_SOCKET.apply(Iterables.getOnlyElement(primaries))); break; default: throw new IllegalArgumentException("More than one primary local service: " + primaries); } Iterable<LocalService> auxSinglyNamed = Iterables.concat(FluentIterable.from(localServices) .filter(Predicates.not(IS_PRIMARY)).transform(AUX_NAME_BREAKOUT)); Map<String, LocalService> byName; try { byName = Maps.uniqueIndex(auxSinglyNamed, GET_NAME); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Auxiliary services with identical names.", e); } auxiliarySockets = ImmutableMap.copyOf(Maps.transformValues(byName, SERVICE_TO_SOCKET)); } }
From source file:org.opendaylight.ovsdb.lib.impl.OvsdbClientImpl.java
@Override public <E extends TableSchema<E>> TableUpdates monitor(final DatabaseSchema dbSchema, List<MonitorRequest<E>> monitorRequest, final MonitorCallBack callback) { final ImmutableMap<String, MonitorRequest<E>> reqMap = Maps.uniqueIndex(monitorRequest, new Function<MonitorRequest<E>, String>() { @Override/*ww w. j a v a 2 s . c o m*/ public String apply(MonitorRequest<E> input) { return input.getTableName(); } }); final MonitorHandle monitorHandle = new MonitorHandle(UUID.randomUUID().toString()); registerCallback(monitorHandle, callback, dbSchema); ListenableFuture<JsonNode> monitor = rpc.monitor(new Params() { @Override public List<Object> params() { return Lists.<Object>newArrayList(dbSchema.getName(), monitorHandle.getId(), reqMap); } }); JsonNode result; try { result = monitor.get(); } catch (InterruptedException | ExecutionException e) { return null; } TableUpdates updates = transformingCallback(result, dbSchema); return updates; }
From source file:com.facebook.buck.cxx.Omnibus.java
protected static OmnibusSpec buildSpec(final CxxPlatform cxxPlatform, final Iterable<? extends NativeLinkTarget> includedRoots, final Iterable<? extends NativeLinkable> excludedRoots) { // A map of targets to native linkable objects. We maintain this, so that we index our // bookkeeping around `BuildTarget` and avoid having to guarantee that all other types are // hashable.//from www . j a v a2 s. com final Map<BuildTarget, NativeLinkable> nativeLinkables = new LinkedHashMap<>(); // The nodes which should *not* be included in the omnibus link. final Set<BuildTarget> excluded = new LinkedHashSet<>(); // Process all the roots included in the omnibus link. final Map<BuildTarget, NativeLinkTarget> roots = new LinkedHashMap<>(); Map<BuildTarget, NativeLinkable> rootDeps = new LinkedHashMap<>(); for (NativeLinkTarget root : includedRoots) { roots.put(root.getBuildTarget(), root); for (NativeLinkable dep : NativeLinkables.getNativeLinkables(cxxPlatform, root.getNativeLinkTargetDeps(cxxPlatform), Linker.LinkableDepType.SHARED).values()) { Linker.LinkableDepType linkStyle = NativeLinkables .getLinkStyle(dep.getPreferredLinkage(cxxPlatform), Linker.LinkableDepType.SHARED); Preconditions.checkState(linkStyle != Linker.LinkableDepType.STATIC); // We only consider deps which aren't *only* statically linked. if (linkStyle == Linker.LinkableDepType.SHARED) { rootDeps.put(dep.getBuildTarget(), dep); nativeLinkables.put(dep.getBuildTarget(), dep); } } } // Process all roots excluded from the omnibus link, and add them to our running list of // excluded nodes. for (NativeLinkable root : excludedRoots) { nativeLinkables.put(root.getBuildTarget(), root); excluded.add(root.getBuildTarget()); } // Perform the first walk starting from the native linkable nodes immediately reachable via the // included roots. We'll accomplish two things here: // 1. Build up the map of node names to their native linkable objects. // 2. Perform an initial discovery of dependency nodes to exclude from the omnibus link. new AbstractBreadthFirstTraversal<BuildTarget>(rootDeps.keySet()) { @Override public ImmutableSet<BuildTarget> visit(BuildTarget target) { NativeLinkable nativeLinkable = Preconditions.checkNotNull(nativeLinkables.get(target)); ImmutableMap<BuildTarget, NativeLinkable> deps = Maps .uniqueIndex(getDeps(nativeLinkable, cxxPlatform), HasBuildTarget::getBuildTarget); nativeLinkables.putAll(deps); if (nativeLinkable.getPreferredLinkage(cxxPlatform) == NativeLinkable.Linkage.SHARED) { excluded.add(target); } return deps.keySet(); } }.start(); // Do another walk to flesh out the transitively excluded nodes. new AbstractBreadthFirstTraversal<BuildTarget>(excluded) { @Override public Iterable<BuildTarget> visit(BuildTarget target) { NativeLinkable nativeLinkable = Preconditions.checkNotNull(nativeLinkables.get(target)); ImmutableMap<BuildTarget, NativeLinkable> deps = Maps .uniqueIndex(getDeps(nativeLinkable, cxxPlatform), HasBuildTarget::getBuildTarget); nativeLinkables.putAll(deps); excluded.add(target); return deps.keySet(); } }.start(); // And then we can do one last walk to create the actual graph which contain only root and body // nodes to include in the omnibus link. final MutableDirectedGraph<BuildTarget> graphBuilder = new MutableDirectedGraph<>(); final Set<BuildTarget> deps = new LinkedHashSet<>(); new AbstractBreadthFirstTraversal<BuildTarget>(Sets.difference(rootDeps.keySet(), excluded)) { @Override public Iterable<BuildTarget> visit(BuildTarget target) { graphBuilder.addNode(target); Set<BuildTarget> keep = new LinkedHashSet<>(); for (BuildTarget dep : Iterables.transform(getDeps(target, roots, nativeLinkables, cxxPlatform), HasBuildTarget::getBuildTarget)) { if (excluded.contains(dep)) { deps.add(dep); } else { keep.add(dep); graphBuilder.addEdge(target, dep); } } return keep; } }.start(); DirectedAcyclicGraph<BuildTarget> graph = new DirectedAcyclicGraph<>(graphBuilder); // Since we add all undefined root symbols into the omnibus library, we also need to include // any excluded root deps as deps of omnibus, as they may fulfill these undefined symbols. // Also add any excluded nodes that are also root dependencies. deps.addAll(Sets.intersection(rootDeps.keySet(), excluded)); return ImmutableOmnibusSpec.builder().graph(graph).roots(roots) .body(FluentIterable.from(graph.getNodes()).filter(Predicates.not(roots.keySet()::contains)) .toMap(Functions.forMap(nativeLinkables))) .deps(Maps.asMap(deps, Functions.forMap(nativeLinkables))) .excluded(Maps.asMap(excluded, Functions.forMap(nativeLinkables))).build(); }
From source file:com.siemens.sw360.portal.tags.CompareAttachments.java
private static Map<String, Attachment> getAttachmentsById(Set<Attachment> currentAttachments) { return Maps.uniqueIndex(currentAttachments, new Function<Attachment, String>() { @Override/*from w ww .j av a2 s . co m*/ public String apply(Attachment input) { return input.getAttachmentContentId(); } }); }
From source file:org.graylog2.users.RoleServiceImpl.java
@Override public Map<String, Role> loadAllLowercaseNameMap() throws NotFoundException { final Set<Role> roles = loadAll(); return Maps.uniqueIndex(roles, Roles.roleToNameFunction(true)); }
From source file:org.opendaylight.nemo.user.tenantmanager.TenantManage.java
/** * * @return null if an error was encountered, or an empty map if there was no * error but no data was retrieved. */// w w w . j a va 2 s . c o m public Map<UserRoleName, UserRole> getUserRoles() { InstanceIdentifier<UserRoles> userRolesInsId = InstanceIdentifier.builder(UserRoles.class).build(); ListenableFuture<Optional<UserRoles>> userRolesFuture = this.dataBroker.newReadOnlyTransaction() .read(LogicalDatastoreType.CONFIGURATION, userRolesInsId); final Optional<UserRoles> userRolesOpt; try { // TODO: consider time out here? userRolesOpt = userRolesFuture.get(); } catch (InterruptedException e) { LOG.error("Cannot read role information.", e); return null; } catch (ExecutionException e) { LOG.error("Cannot read role information.", e); return null; } // TODO: change to Java 8 lambda expressions return userRolesOpt.transform(new Function<UserRoles, Map<UserRoleName, UserRole>>() { @Override public Map<UserRoleName, UserRole> apply(UserRoles input) { return Maps.uniqueIndex(input.getUserRole(), new Function<UserRole, UserRoleName>() { @Override public UserRoleName apply(UserRole role) { return role.getRoleName(); } }); } }).or(new HashMap<UserRoleName, UserRole>()); }
From source file:org.jclouds.abiquo.config.AbiquoRestClientModule.java
@Provides @Singleton/*ww w . jav a 2 s . c o m*/ @Memoized public Supplier<Map<Integer, Datacenter>> getAvailableRegionsIndexedById( final AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) final long seconds, @Memoized final Supplier<Enterprise> currentEnterprise) { Supplier<Map<Integer, Datacenter>> availableRegionsMapSupplier = Suppliers .compose(new Function<List<Datacenter>, Map<Integer, Datacenter>>() { @Override public Map<Integer, Datacenter> apply(final List<Datacenter> datacenters) { // Index available regions by id return Maps.uniqueIndex(datacenters, new Function<Datacenter, Integer>() { @Override public Integer apply(final Datacenter input) { return input.getId(); } }); } }, new Supplier<List<Datacenter>>() { @Override public List<Datacenter> get() { // Get the list of regions available for the user's tenant return currentEnterprise.get().listAllowedDatacenters(); } }); return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, availableRegionsMapSupplier, seconds, TimeUnit.SECONDS); }