List of usage examples for com.google.common.collect ImmutableMap isEmpty
@Override public boolean isEmpty()
From source file:org.codice.ddf.catalog.sourcepoller.Poller.java
/** * @throws IllegalStateException if unable to wait for polls * @throws InterruptedException if the current thread was interrupted * @throws CancellationException if the task to wait for the loader {@link Callable<V>} to be * complete was cancelled//ww w . j a v a 2 s . c o m * @throws ExecutionException if the the task to wait for the loader {@link Callable<V>} threw an * exception * @throws PollerException if unable to commit the value for any of the {@code itemsToPoll} */ private void doPollItems(long timeout, TimeUnit timeoutTimeUnit, ImmutableMap<K, Callable<V>> itemsToPoll) throws InterruptedException, ExecutionException, PollerException { removeNoncurrentKeysFromTheCache(itemsToPoll.keySet()); if (itemsToPoll.isEmpty()) { LOGGER.debug("itemsToPoll is empty. Nothing to poll"); return; } // Gather any exceptions while loading or committing new values final Map<K, Throwable> exceptions = new HashMap<>(); final CompletionService<Pair<K, Commitable>> completionService = new ExecutorCompletionService<>( pollTimeoutWatcherThreadPool); final int startedLoadsCount = startLoads(timeout, timeoutTimeUnit, itemsToPoll, completionService, exceptions); boolean interrupted = false; try { for (int i = 0; i < startedLoadsCount; i++) { // Use CompletionService#poll(long, TimeUnit) instead of CompletionService#take() even // though the timeout has already been accounted for in #load(K, Callable<V>, long, // TimeUnit) to prevent blocking forever // @throws InterruptedException if interrupted while waiting final Future<Pair<K, Commitable>> nextCompletedLoadFuture = completionService.poll(timeout, timeoutTimeUnit); if (nextCompletedLoadFuture == null) { final String message = String.format("Unable to wait for polls to finish within %d %s", timeout, timeoutTimeUnit); LOGGER.debug(message); throw new IllegalStateException(message); } // @throws CancellationException if the computation was cancelled // @throws ExecutionException if the computation threw an exception // @throws InterruptedException if the current thread was interrupted final Pair<K, Commitable> nextCompletedLoad = nextCompletedLoadFuture.get(); try { attemptToCommitLoadedValue(nextCompletedLoad.getKey(), nextCompletedLoad.getValue(), exceptions); } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } if (!exceptions.isEmpty()) { throw new PollerException(exceptions); } }
From source file:org.elasticsearch.rest.action.admin.indices.mapping.get.RestGetFieldMappingAction.java
@Override public void handleRequest(final RestRequest request, final RestChannel channel) { final String[] indices = Strings.splitStringByCommaToArray(request.param("index")); final String[] types = request.paramAsStringArrayOrEmptyIfAll("type"); final String[] fields = Strings.splitStringByCommaToArray(request.param("fields")); GetFieldMappingsRequest getMappingsRequest = new GetFieldMappingsRequest(); getMappingsRequest.indices(indices).types(types).fields(fields) .includeDefaults(request.paramAsBoolean("include_defaults", false)); getMappingsRequest.indicesOptions(IndicesOptions.fromRequest(request, getMappingsRequest.indicesOptions())); getMappingsRequest.local(request.paramAsBoolean("local", getMappingsRequest.local())); client.admin().indices().getFieldMappings(getMappingsRequest, new RestBuilderListener<GetFieldMappingsResponse>(channel) { @SuppressWarnings("unchecked") @Override// w ww . j ava 2 s. c o m public RestResponse buildResponse(GetFieldMappingsResponse response, XContentBuilder builder) throws Exception { ImmutableMap<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> mappingsByIndex = response .mappings(); boolean isPossibleSingleFieldRequest = indices.length == 1 && types.length == 1 && fields.length == 1; if (isPossibleSingleFieldRequest && isFieldMappingMissingField(mappingsByIndex)) { return new BytesRestResponse(OK, builder.startObject().endObject()); } RestStatus status = OK; if (mappingsByIndex.isEmpty() && fields.length > 0) { status = NOT_FOUND; } builder.startObject(); response.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); return new BytesRestResponse(status, builder); } }); }
From source file:com.pinterest.pinlater.backends.mysql.PinLaterMySQLBackend.java
private ImmutableMap.Entry<String, MySQLDataSources> getRandomEnqueueableShard() { ImmutableMap<String, MySQLDataSources> enqueueableShardMap = getEnqueueableShards(); if (enqueueableShardMap.isEmpty()) { return null; }/*from ww w . j a v a2 s .c om*/ int rand = RANDOM.nextInt(enqueueableShardMap.size()); return enqueueableShardMap.entrySet().asList().get(rand); }
From source file:org.prebake.os.RealOsProcess.java
@Override protected Process startRunning(boolean inheritOutput, boolean closeInput, @Nullable Path outFile, boolean truncateOutput, @Nullable Path inFile, ImmutableMap<String, String> env, boolean inheritEnv) throws IOException { ProcessBuilder pb = this.pb; this.pb = null; if (inheritOutput) { pb.redirectOutput(ProcessBuilder.Redirect.INHERIT); }// w ww . j a v a 2 s. co m if (outFile != null) { assert outFile.getFileSystem() == FileSystems.getDefault(); pb.redirectOutput(new File(outFile.toUri())); } if (!pb.redirectErrorStream()) { pb.redirectError(ProcessBuilder.Redirect.INHERIT); } if (inFile != null) { assert inFile.getFileSystem() == FileSystems.getDefault(); pb.redirectInput(new File(inFile.toUri())); } if (!(inheritEnv && env.isEmpty())) { Map<String, String> procEnv = pb.environment(); if (!inheritEnv) { procEnv.clear(); } procEnv.putAll(env); } Process p = pb.start(); if (closeInput) { p.getInputStream().close(); } return p; }
From source file:com.pinterest.pinlater.backends.mysql.PinLaterMySQLBackend.java
private ImmutableMap.Entry<String, MySQLDataSources> getRandomShard() { ImmutableMap<String, MySQLDataSources> shardMap = shardMapRef.get(); if (shardMap == null || shardMap.isEmpty()) { return null; }/*from www . java 2 s .c o m*/ int rand = RANDOM.nextInt(shardMap.size()); return shardMap.entrySet().asList().get(rand); }
From source file:com.facebook.buck.android.AndroidNativeLibsPackageableGraphEnhancer.java
public AndroidNativeLibsGraphEnhancementResult enhance(AndroidPackageableCollection packageableCollection) throws NoSuchBuildTargetException { @SuppressWarnings("PMD.PrematureDeclaration") AndroidNativeLibsGraphEnhancementResult.Builder resultBuilder = AndroidNativeLibsGraphEnhancementResult .builder();/*from w w w . ja v a2 s. c o m*/ ImmutableMultimap<APKModule, NativeLinkable> nativeLinkables = packageableCollection.getNativeLinkables(); ImmutableMultimap<APKModule, NativeLinkable> nativeLinkablesAssets = packageableCollection .getNativeLinkablesAssets(); if (nativeLibraryMergeMap.isPresent() && !nativeLibraryMergeMap.get().isEmpty()) { NativeLibraryMergeEnhancementResult enhancement = NativeLibraryMergeEnhancer.enhance(cxxBuckConfig, ruleResolver, pathResolver, ruleFinder, buildRuleParams, nativePlatforms, nativeLibraryMergeMap.get(), nativeLibraryMergeGlue, nativeLinkables, nativeLinkablesAssets); nativeLinkables = enhancement.getMergedLinkables(); nativeLinkablesAssets = enhancement.getMergedLinkablesAssets(); resultBuilder.setSonameMergeMap(enhancement.getSonameMapping()); } // Iterate over all the {@link AndroidNativeLinkable}s from the collector and grab the shared // libraries for all the {@link TargetCpuType}s that we care about. We deposit them into a map // of CPU type and SONAME to the shared library path, which the {@link CopyNativeLibraries} // rule will use to compose the destination name. ImmutableMap.Builder<APKModule, CopyNativeLibraries> moduleMappedCopyNativeLibriesBuilder = ImmutableMap .builder(); boolean hasCopyNativeLibraries = false; List<NdkCxxPlatform> platformsWithNativeLibs = new ArrayList<>(); List<NdkCxxPlatform> platformsWithNativeLibsAssets = new ArrayList<>(); // Make sure we process the root module last so that we know if any of the module contain // libraries that depend on a non-system runtime and add it to the root module if needed. ImmutableSet<APKModule> apkModules = FluentIterable.from(apkModuleGraph.getAPKModules()) .filter(input -> !input.isRootModule()).append(apkModuleGraph.getRootAPKModule()).toSet(); for (APKModule module : apkModules) { ImmutableMap.Builder<Pair<NdkCxxPlatforms.TargetCpuType, String>, SourcePath> nativeLinkableLibsBuilder = ImmutableMap .builder(); ImmutableMap.Builder<Pair<NdkCxxPlatforms.TargetCpuType, String>, SourcePath> nativeLinkableLibsAssetsBuilder = ImmutableMap .builder(); // TODO(andrewjcg): We currently treat an empty set of filters to mean to allow everything. // We should fix this by assigning a default list of CPU filters in the descriptions, but // until we do, if the set of filters is empty, just build for all available platforms. ImmutableSet<NdkCxxPlatforms.TargetCpuType> filters = cpuFilters.isEmpty() ? nativePlatforms.keySet() : cpuFilters; for (NdkCxxPlatforms.TargetCpuType targetCpuType : filters) { NdkCxxPlatform platform = Preconditions.checkNotNull(nativePlatforms.get(targetCpuType), "Unknown platform type " + targetCpuType.toString()); // Populate nativeLinkableLibs and nativeLinkableLibsAssets with the appropriate entries. if (populateMapWithLinkables(nativeLinkables.get(module), nativeLinkableLibsBuilder, targetCpuType, platform) && !platformsWithNativeLibs.contains(platform)) { platformsWithNativeLibs.add(platform); } if (populateMapWithLinkables(nativeLinkablesAssets.get(module), nativeLinkableLibsAssetsBuilder, targetCpuType, platform) && !platformsWithNativeLibsAssets.contains(platform)) { platformsWithNativeLibsAssets.add(platform); } if (module.isRootModule()) { // If we're using a C/C++ runtime other than the system one, add it to the APK. NdkCxxPlatforms.CxxRuntime cxxRuntime = platform.getCxxRuntime(); if ((platformsWithNativeLibs.contains(platform) || platformsWithNativeLibsAssets.contains(platform)) && !cxxRuntime.equals(NdkCxxPlatforms.CxxRuntime.SYSTEM)) { nativeLinkableLibsBuilder.put(new Pair<>(targetCpuType, cxxRuntime.getSoname()), new PathSourcePath(buildRuleParams.getProjectFilesystem(), platform.getCxxSharedRuntimePath())); } } } ImmutableMap<Pair<NdkCxxPlatforms.TargetCpuType, String>, SourcePath> nativeLinkableLibs = nativeLinkableLibsBuilder .build(); ImmutableMap<Pair<NdkCxxPlatforms.TargetCpuType, String>, SourcePath> nativeLinkableLibsAssets = nativeLinkableLibsAssetsBuilder .build(); if (packageableCollection.getNativeLibsDirectories().get(module).isEmpty() && nativeLinkableLibs.isEmpty() && nativeLinkableLibsAssets.isEmpty()) { continue; } if (relinkerMode == RelinkerMode.ENABLED && (!nativeLinkableLibs.isEmpty() || !nativeLinkableLibsAssets.isEmpty())) { NativeRelinker relinker = new NativeRelinker( buildRuleParams .copyWithExtraDeps(Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>naturalOrder() .addAll(ruleFinder.filterBuildRuleInputs(nativeLinkableLibs.values())) .addAll(ruleFinder.filterBuildRuleInputs(nativeLinkableLibsAssets.values())) .build())), pathResolver, ruleFinder, cxxBuckConfig, nativePlatforms, nativeLinkableLibs, nativeLinkableLibsAssets); nativeLinkableLibs = relinker.getRelinkedLibs(); nativeLinkableLibsAssets = relinker.getRelinkedLibsAssets(); for (BuildRule rule : relinker.getRules()) { ruleResolver.addToIndex(rule); } } ImmutableMap<StripLinkable, StrippedObjectDescription> strippedLibsMap = generateStripRules( buildRuleParams, ruleFinder, ruleResolver, originalBuildTarget, nativePlatforms, nativeLinkableLibs); ImmutableMap<StripLinkable, StrippedObjectDescription> strippedLibsAssetsMap = generateStripRules( buildRuleParams, ruleFinder, ruleResolver, originalBuildTarget, nativePlatforms, nativeLinkableLibsAssets); BuildTarget targetForCopyNativeLibraries = BuildTarget.builder(originalBuildTarget) .addFlavors(ImmutableFlavor.of(COPY_NATIVE_LIBS + "_" + module.getName())).build(); ImmutableSortedSet<BuildRule> nativeLibsRules = BuildRules.toBuildRulesFor(originalBuildTarget, ruleResolver, packageableCollection.getNativeLibsTargets().get(module)); BuildRuleParams paramsForCopyNativeLibraries = buildRuleParams.copyWithChanges( targetForCopyNativeLibraries, Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>naturalOrder().addAll(nativeLibsRules) .addAll(ruleFinder.filterBuildRuleInputs( packageableCollection.getNativeLibsDirectories().get(module))) .addAll(strippedLibsMap.keySet()).addAll(strippedLibsAssetsMap.keySet()).build()), /* extraDeps */ Suppliers.ofInstance(ImmutableSortedSet.of())); moduleMappedCopyNativeLibriesBuilder.put(module, new CopyNativeLibraries(paramsForCopyNativeLibraries, ImmutableSet.copyOf(packageableCollection.getNativeLibsDirectories().get(module)), ImmutableSet.copyOf(strippedLibsMap.values()), ImmutableSet.copyOf(strippedLibsAssetsMap.values()), cpuFilters, module.getName())); hasCopyNativeLibraries = true; } return resultBuilder.setCopyNativeLibraries( hasCopyNativeLibraries ? Optional.of(moduleMappedCopyNativeLibriesBuilder.build()) : Optional.empty()) .build(); }
From source file:com.facebook.buck.cxx.CxxLibraryDescription.java
public static ImmutableCollection<CxxPreprocessorInput> getTransitiveCxxPreprocessorInput( BuildRuleParams params, BuildRuleResolver ruleResolver, SourcePathResolver pathResolver, CxxPlatform cxxPlatform, ImmutableMultimap<CxxSource.Type, String> exportedPreprocessorFlags, ImmutableMap<Path, SourcePath> exportedHeaders, ImmutableSet<FrameworkPath> frameworks, boolean shouldCreatePublicHeadersSymlinks) throws NoSuchBuildTargetException { // Check if there is a target node representative for the library in the action graph and, // if so, grab the cached transitive C/C++ preprocessor input from that. BuildTarget rawTarget = params.getBuildTarget().withoutFlavors(ImmutableSet.<Flavor>builder() .addAll(LIBRARY_TYPE.getFlavors()).add(cxxPlatform.getFlavor()).build()); Optional<BuildRule> rawRule = ruleResolver.getRuleOptional(rawTarget); if (rawRule.isPresent()) { CxxLibrary rule = (CxxLibrary) rawRule.get(); return rule.getTransitiveCxxPreprocessorInput(cxxPlatform, HeaderVisibility.PUBLIC).values(); }// w w w . jav a 2 s. c o m // NB: This code must return the same results as CxxLibrary.getTransitiveCxxPreprocessorInput. // In the long term we should get rid of the duplication. CxxPreprocessorInput.Builder cxxPreprocessorInputBuilder = CxxPreprocessorInput.builder() .putAllPreprocessorFlags(exportedPreprocessorFlags).addAllFrameworks(frameworks); if (!exportedHeaders.isEmpty()) { HeaderSymlinkTree symlinkTree = CxxDescriptionEnhancer.requireHeaderSymlinkTree(params, ruleResolver, pathResolver, cxxPlatform, exportedHeaders, HeaderVisibility.PUBLIC, shouldCreatePublicHeadersSymlinks); cxxPreprocessorInputBuilder .addIncludes(CxxSymlinkTreeHeaders.from(symlinkTree, CxxPreprocessables.IncludeType.LOCAL)); } Map<BuildTarget, CxxPreprocessorInput> input = Maps.newLinkedHashMap(); input.put(params.getBuildTarget(), cxxPreprocessorInputBuilder.build()); for (BuildRule rule : params.getDeps()) { if (rule instanceof CxxPreprocessorDep) { input.putAll(((CxxPreprocessorDep) rule).getTransitiveCxxPreprocessorInput(cxxPlatform, HeaderVisibility.PUBLIC)); } } return ImmutableList.copyOf(input.values()); }
From source file:org.elasticsearch.cluster.metadata.IndexMetaData.java
private IndexMetaData(String index, long version, State state, Settings settings, ImmutableOpenMap<String, MappingMetaData> mappings, ImmutableOpenMap<String, AliasMetaData> aliases, ImmutableOpenMap<String, Custom> customs) { Preconditions.checkArgument(settings.getAsInt(SETTING_NUMBER_OF_SHARDS, -1) != -1, "must specify numberOfShards for index [" + index + "]"); Preconditions.checkArgument(settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, -1) != -1, "must specify numberOfReplicas for index [" + index + "]"); this.index = index; this.version = version; this.state = state; this.settings = settings; this.mappings = mappings; this.customs = customs; this.totalNumberOfShards = numberOfShards() * (numberOfReplicas() + 1); this.aliases = aliases; ImmutableMap<String, String> requireMap = settings.getByPrefix("index.routing.allocation.require.") .getAsMap();//from ww w . j a va 2 s . co m if (requireMap.isEmpty()) { requireFilters = null; } else { requireFilters = DiscoveryNodeFilters.buildFromKeyValue(AND, requireMap); } ImmutableMap<String, String> includeMap = settings.getByPrefix("index.routing.allocation.include.") .getAsMap(); if (includeMap.isEmpty()) { includeFilters = null; } else { includeFilters = DiscoveryNodeFilters.buildFromKeyValue(OR, includeMap); } ImmutableMap<String, String> excludeMap = settings.getByPrefix("index.routing.allocation.exclude.") .getAsMap(); if (excludeMap.isEmpty()) { excludeFilters = null; } else { excludeFilters = DiscoveryNodeFilters.buildFromKeyValue(OR, excludeMap); } }
From source file:com.microsoft.thrifty.schema.Linker.java
@Nonnull ThriftType resolveType(TypeElement type) { AnnotationElement annotationElement = type.annotations(); ImmutableMap<String, String> annotations = annotationElement != null ? annotationElement.values() : ImmutableMap.<String, String>of(); ThriftType tt = typesByName.get(type.name()); if (tt != null) { // If we are resolving e.g. the type of a field element, the type // may carry annotations that are not part of the canonical type. if (!annotations.isEmpty()) { return tt.withAnnotations(annotations); } else {/*from ww w. j a v a2s. co m*/ return tt; } } if (type instanceof ListTypeElement) { ThriftType elementType = resolveType(((ListTypeElement) type).elementType()); ThriftType listType = new ListType(elementType); typesByName.put(type.name(), listType); return listType.withAnnotations(annotations); } else if (type instanceof SetTypeElement) { ThriftType elementType = resolveType(((SetTypeElement) type).elementType()); ThriftType setType = new SetType(elementType); typesByName.put(type.name(), setType); return setType.withAnnotations(annotations); } else if (type instanceof MapTypeElement) { MapTypeElement element = (MapTypeElement) type; ThriftType keyType = resolveType(element.keyType()); ThriftType valueType = resolveType(element.valueType()); ThriftType mapType = new MapType(keyType, valueType); typesByName.put(type.name(), mapType); return mapType.withAnnotations(annotations); } else if (type instanceof ScalarTypeElement) { // At this point, all user-defined types should have been registered. // If we are resolving a built-in type, then that's fine. If not, then // we have an error. tt = BuiltinType.get(type.name()); if (tt != null) { return tt.withAnnotations(annotations); } throw new LinkFailureException(type.name()); } else { throw new AssertionError("Unexpected TypeElement: " + type.getClass()); } }
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 ww w .j av a 2 s. co m 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; }