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:barrysw19.calculon.engine.ChessEngine.java
private List<SearchContext> getScoredMoves(final BitBoard bitBoard, final List<SearchContext> movesFilter) { ImmutableMap<String, SearchContext> movesToAnalyse = Maps.uniqueIndex(movesFilter, SearchContext::getAlgebraicMove); List<FutureTask<SearchContext>> tasks = new ArrayList<>(); for (Iterator<BitBoardMove> moveItr = moveGeneratorFactory.createMoveGenerator(bitBoard); moveItr .hasNext();) {/*from w w w . ja v a 2 s. com*/ final BitBoardMove move = moveItr.next(); final BitBoard cloneBitBoard = BitBoard.createCopy(bitBoard); final String algebraic = move.getAlgebraic(); if (!movesToAnalyse.isEmpty() && !movesToAnalyse.containsKey(algebraic)) { // LOG.debug("Skipping move {}", algebraic); continue; } FutureTask<SearchContext> scoredMoveFutureTask = new FutureTask<>(() -> { cloneBitBoard.makeMove(move); final SearchContext searchContext = new SearchContext(algebraic); int score = alphaBeta(-BIG_VALUE, BIG_VALUE, depthForSearch, cloneBitBoard, searchContext.descend()); searchContext.setScore(score); LOG.debug("Ran: {}", searchContext); cloneBitBoard.unmakeMove(); return searchContext; }); tasks.add(scoredMoveFutureTask); executorService.submit(scoredMoveFutureTask); } final List<SearchContext> rv = new ArrayList<>(); for (FutureTask<SearchContext> i : tasks) { try { rv.add(i.get()); } catch (InterruptedException | ExecutionException e) { LOG.error("Unexpected exception", e); } } return rv; }
From source file:org.sonar.server.component.ws.AppAction.java
private Map<String, MeasureDto> measuresByMetricKey(ComponentDto component, DbSession session) { MeasureQuery query = MeasureQuery.builder().setComponentUuid(component.uuid()).setMetricKeys(METRIC_KEYS) .build();//from w ww .j a v a 2 s . co m List<MeasureDto> measures = dbClient.measureDao().selectByQuery(session, query); Set<Integer> metricIds = measures.stream().map(MeasureDto::getMetricId).collect(Collectors.toSet()); List<MetricDto> metrics = dbClient.metricDao().selectByIds(session, metricIds); Map<Integer, MetricDto> metricsById = Maps.uniqueIndex(metrics, MetricDto::getId); return Maps.uniqueIndex(measures, m -> metricsById.get(m.getMetricId()).getKey()); }
From source file:uk.co.revsys.content.repository.cloud.CloudCacheStore.java
@Override public void start() throws CacheLoaderException { super.start(); if (constructInternalBlobstores) { if (cfg.getCloudService() == null) { throw new ConfigurationException("CloudService must be set!"); }/*from w w w . j ava 2 s. c o m*/ if (cfg.getIdentity() == null) { throw new ConfigurationException("Identity must be set"); } if (cfg.getPassword() == null) { throw new ConfigurationException("Password must be set"); } } if (cfg.getBucketPrefix() == null) { throw new ConfigurationException("CloudBucket must be set"); } containerName = getThisContainerName(); try { if (constructInternalBlobstores) { // add an executor as a constructor param to // EnterpriseConfigurationModule, pass // property overrides instead of Properties() ctx = new BlobStoreContextFactory().createContext(cfg.getCloudService(), cfg.getIdentity(), cfg.getPassword(), ImmutableSet.of(new EnterpriseConfigurationModule(), new Log4JLoggingModule()), new Properties()); blobStore = ctx.getBlobStore(); asyncBlobStore = ctx.getAsyncBlobStore(); } if (!blobStore.containerExists(containerName)) { Location chosenLoc = null; if (cfg.getCloudServiceLocation() != null && cfg.getCloudServiceLocation().trim().length() > 0) { Map<String, ? extends Location> idToLocation = Maps .uniqueIndex(blobStore.listAssignableLocations(), new Function<Location, String>() { @Override public String apply(Location input) { return input.getId(); } }); String loc = cfg.getCloudServiceLocation().trim().toLowerCase(); chosenLoc = idToLocation.get(loc); if (chosenLoc == null) { log.unableToConfigureCloudService(loc, cfg.getCloudService(), idToLocation.keySet()); } } blobStore.createContainerInLocation(chosenLoc, containerName); } pollFutures = !cfg.getAsyncStoreConfig().isEnabled(); } catch (RuntimeException ioe) { throw new CacheLoaderException("Unable to create context", ioe); } }
From source file:org.apache.aurora.scheduler.http.SchedulerzRole.java
private Map<IJobKey, Map<?, ?>> fetchCronJobsBy(final String role, final Optional<String> environment) { Predicate<IJobConfiguration> byRoleEnv = new Predicate<IJobConfiguration>() { @Override//w ww . ja v a 2 s . c o m public boolean apply(IJobConfiguration job) { boolean roleMatch = job.getOwner().getRole().equals(role); boolean envMatch = !environment.isPresent() || job.getKey().getEnvironment().equals(environment.get()); return roleMatch && envMatch; } }; Iterable<IJobConfiguration> jobs = FluentIterable.from(cronJobManager.getJobs()).filter(byRoleEnv); return Maps.transformValues(Maps.uniqueIndex(jobs, JobKeys.FROM_CONFIG), new Function<IJobConfiguration, Map<?, ?>>() { @Override public Map<?, ?> apply(IJobConfiguration job) { return ImmutableMap.<Object, Object>builder().put("jobKey", job.getKey()) .put("name", job.getKey().getName()) .put("environment", job.getKey().getEnvironment()) .put("pendingTaskCount", job.getInstanceCount()) .put("cronSchedule", job.getCronSchedule()) .put("nextRun", cronPredictor.predictNextRun(job.getCronSchedule()).getTime()) .put("cronCollisionPolicy", cronCollisionPolicy(job)) .put("packages", getPackages(job)).build(); } }); }
From source file:com.ebay.pulsar.analytics.cache.MemcachedCache.java
@Override public Map<NamedKey, byte[]> getBulk(Iterable<NamedKey> keys) { Map<String, NamedKey> keyLookup = Maps.uniqueIndex(keys, new Function<NamedKey, String>() { @Override//from w w w . j av a 2s.c om public String apply(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(); logger.warn("Unable to queue cache operation: " + e.getMessage()); 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(); logger.warn("Exception pulling item from cache: " + e.getMessage()); return results; } }
From source file:com.facebook.presto.cassandra.CachingCassandraSchemaProvider.java
private Map<String, String> loadAllTables(final String databaseName) throws Exception { return retry().stopOn(NotFoundException.class).stopOnIllegalExceptions().run("getAllTables", () -> { String caseSensitiveDatabaseName = getCaseSensitiveSchemaName(databaseName); if (caseSensitiveDatabaseName == null) { caseSensitiveDatabaseName = databaseName; }/*from w ww . j a v a 2s. co m*/ List<String> tables = session.getAllTables(caseSensitiveDatabaseName); Map<String, String> nameMap = Maps.uniqueIndex(tables, CachingCassandraSchemaProvider::toLowerCase); if (tables.isEmpty()) { // Check to see if the database exists session.getSchema(databaseName); } return nameMap; }); }
From source file:org.eclipse.sw360.portal.tags.CompareAttachments.java
private static Map<String, Attachment> getAttachmentsById(Set<Attachment> currentAttachments) { return Maps.uniqueIndex(currentAttachments, Attachment::getAttachmentContentId); }
From source file:com.facebook.buck.js.ReactNativeBundle.java
@Override public ImmutableList<SourcePath> getInputsAfterBuildingLocally() throws IOException { ImmutableList.Builder<SourcePath> inputs = ImmutableList.builder(); // Use the generated depfile to determinate which sources ended up being used. ImmutableMap<Path, SourcePath> pathToSourceMap = Maps.uniqueIndex(srcs, getResolver()::getAbsolutePath); Path depFile = getPathToDepFile(getBuildTarget(), getProjectFilesystem()); for (String line : getProjectFilesystem().readLines(depFile)) { Path path = getProjectFilesystem().getPath(line); SourcePath sourcePath = pathToSourceMap.get(path); if (sourcePath == null) { throw new IOException( String.format("%s: entry path '%s' transitively uses source file not preset in `srcs`: %s", getBuildTarget(), entryPath, path)); }//from w w w .jav a 2 s . c o m inputs.add(sourcePath); } return inputs.build(); }
From source file:com.siemens.sw360.commonIO.TypeMappings.java
@NotNull public static Map<Integer, Todo> getTodoMap(LicenseService.Iface licenseClient, Map<Integer, Obligation> obligationMap, Map<Integer, Set<Integer>> obligationTodoMapping, InputStream in) throws TException { List<CSVRecord> todoRecords = ImportCSV.readAsCSVRecords(in); final List<Todo> todos = CommonUtils.nullToEmptyList(licenseClient.getTodos()); Map<Integer, Todo> todoMap = Maps.newHashMap(Maps.uniqueIndex(todos, getTodoIdentifier())); final List<Todo> todosToAdd = ConvertRecord.convertTodos(todoRecords); final ImmutableList<Todo> filteredTodos = getElementsWithIdentifiersNotInMap(getTodoIdentifier(), todoMap, todosToAdd);//from w w w. j a va 2 s .com final ImmutableMap<Integer, Todo> filteredMap = Maps.uniqueIndex(filteredTodos, getTodoIdentifier()); putToTodos(obligationMap, filteredMap, obligationTodoMapping); if (filteredTodos.size() > 0) { final List<Todo> addedTodos = licenseClient.addTodos(filteredTodos); if (addedTodos != null) { final ImmutableMap<Integer, Todo> addedTodoMap = Maps.uniqueIndex(addedTodos, getTodoIdentifier()); todoMap.putAll(addedTodoMap); } } return todoMap; }
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 av a 2 s . c om*/ public Map<UserId, User> getUsers() { InstanceIdentifier<Users> usersInsId = InstanceIdentifier.builder(Users.class).build(); ListenableFuture<Optional<Users>> usersFuture = dataBroker.newReadOnlyTransaction() .read(LogicalDatastoreType.CONFIGURATION, usersInsId); final Optional<Users> usersOpt; try { // TODO: consider time out here? usersOpt = usersFuture.get(); } catch (InterruptedException e) { LOG.error("Cannot read user information.", e); return null; } catch (ExecutionException e) { LOG.error("Cannot read user information.", e); return null; } // TODO: change to Java 8 lambda expressions return usersOpt.transform(new Function<Users, Map<UserId, User>>() { @Override public Map<UserId, User> apply(Users input) { return Maps.uniqueIndex(input.getUser(), new Function<User, UserId>() { @Override public UserId apply(User user) { return user.getUserId(); } }); } }).or(new HashMap<UserId, User>()); }