List of usage examples for com.google.common.collect ImmutableMap isEmpty
@Override public boolean isEmpty()
From source file:vazkii.botania.client.model.SpecialFlowerModel.java
@Override public IModel process(ImmutableMap<String, String> customData) { // Load the base variant from blockstate json, and also add all the model paths we received from external API ImmutableMap.Builder<Optional<String>, ModelResourceLocation> blockBuilder = ImmutableMap.builder(); ImmutableMap.Builder<Optional<String>, ModelResourceLocation> itemBuilder = ImmutableMap.builder(); for (String key : customData.keySet()) { if ("base".equals(key)) { blockBuilder.put(Optional.empty(), getLocation(customData.get(key))); }// w w w.j a v a2 s.co m } for (Map.Entry<String, ModelResourceLocation> e : BotaniaAPIClient.getRegisteredSubtileBlockModels() .entrySet()) { blockBuilder.put(Optional.of(e.getKey()), e.getValue()); } for (Map.Entry<String, ModelResourceLocation> e : BotaniaAPIClient.getRegisteredSubtileItemModels() .entrySet()) { itemBuilder.put(Optional.of(e.getKey()), e.getValue()); } ImmutableMap<Optional<String>, ModelResourceLocation> blockModels = blockBuilder.build(); ImmutableMap<Optional<String>, ModelResourceLocation> itemModels = itemBuilder.build(); if (blockModels.isEmpty() && itemModels.isEmpty()) return INSTANCE; return new SpecialFlowerModel(blockModels, itemModels); }
From source file:com.google.devtools.build.android.desugar.Desugar.java
/** * Desugar the classes that are generated on the fly when we are desugaring the classes in the * specified inputs./*w ww . java2 s . c om*/ */ private void desugarAndWriteDumpedLambdaClassesToOutput(OutputFileProvider outputFileProvider, ClassLoader loader, ClassReaderFactory readerFactory, Builder<String> interfaceLambdaMethodCollector) throws IOException { ImmutableSet<String> interfaceLambdaMethods = interfaceLambdaMethodCollector.build(); checkState(!allowDefaultMethods || interfaceLambdaMethods.isEmpty(), "Desugaring with default methods enabled moved interface lambdas"); // Write out the lambda classes we generated along the way ImmutableMap<Path, LambdaInfo> lambdaClasses = lambdas.drain(); checkState(!options.onlyDesugarJavac9ForLint || lambdaClasses.isEmpty(), "There should be no lambda classes generated: %s", lambdaClasses.keySet()); for (Map.Entry<Path, LambdaInfo> lambdaClass : lambdaClasses.entrySet()) { try (InputStream bytecode = Files.newInputStream(dumpDirectory.resolve(lambdaClass.getKey()))) { ClassReader reader = rewriter.reader(bytecode); UnprefixingClassWriter writer = rewriter.writer(ClassWriter.COMPUTE_MAXS /*for invoking bridges*/); ClassVisitor visitor = createClassVisitorsForDumpedLambdaClasses(loader, readerFactory, interfaceLambdaMethods, lambdaClass.getValue(), writer); reader.accept(visitor, 0); String filename = rewriter.unprefix(lambdaClass.getValue().desiredInternalName()) + ".class"; outputFileProvider.write(filename, writer.toByteArray()); } } }
From source file:org.openqa.selenium.remote.session.ChromeFilter.java
@Override public Map<String, Object> apply(Map<String, Object> unmodifiedCaps) { ImmutableMap<String, Object> caps = unmodifiedCaps.entrySet().parallelStream() .filter(entry -> ("browserName".equals(entry.getKey()) && "chrome".equals(entry.getValue())) || entry.getKey().startsWith("goog:") || "chromeOptions".equals(entry.getKey())) .filter(entry -> Objects.nonNull(entry.getValue())).distinct() .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue)); return caps.isEmpty() ? null : caps; }
From source file:org.openqa.selenium.remote.session.FirefoxFilter.java
@Override public Map<String, Object> apply(Map<String, Object> unmodifiedCaps) { ImmutableMap<String, Object> caps = unmodifiedCaps.entrySet().parallelStream() .filter(entry -> ("browserName".equals(entry.getKey()) && "firefox".equals(entry.getValue())) || entry.getKey().startsWith("firefox_") || entry.getKey().startsWith("moz:")) .filter(entry -> Objects.nonNull(entry.getValue())).distinct() .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue)); return caps.isEmpty() ? null : caps; }
From source file:com.google.devtools.kythe.analyzers.base.EntrySet.java
protected EntrySet(VName source, String edgeKind, VName target, ImmutableMap<String, byte[]> properties) { Preconditions.checkArgument((edgeKind == null) == (target == null), "edgeKind and target must be both non-null or both null"); this.source = source; this.edgeKind = edgeKind; this.target = target; if (properties.isEmpty()) { this.properties = EMPTY_PROPERTIES; } else {/* ww w . jav a 2 s . com*/ this.properties = properties; } }
From source file:com.google.javascript.jscomp.newtypes.NominalType.java
NominalType(ImmutableMap<String, JSType> typeMap, RawNominalType rawType) { Preconditions.checkState(typeMap.isEmpty() || typeMap.keySet().containsAll(rawType.getTypeParameters()) && rawType.getTypeParameters().containsAll(typeMap.keySet())); this.typeMap = typeMap; this.rawType = rawType; }
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 www . j av a2s. c o 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.facebook.buck.jvm.java.JavaBinaryDescription.java
@Override public <A extends Args> BuildRule createBuildRule(TargetGraph targetGraph, BuildRuleParams params, BuildRuleResolver resolver, A args) throws NoSuchBuildTargetException { SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver); SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder); ImmutableMap<String, SourcePath> nativeLibraries = JavaLibraryRules.getNativeLibraries(params.getDeps(), cxxPlatform);/*from w ww. j a v a 2 s .c om*/ BuildRuleParams binaryParams = params; // If we're packaging native libraries, we'll build the binary JAR in a separate rule and // package it into the final fat JAR, so adjust it's params to use a flavored target. if (!nativeLibraries.isEmpty()) { binaryParams = params.copyWithChanges( params.getBuildTarget().withAppendedFlavors(FAT_JAR_INNER_JAR_FLAVOR), params.getDeclaredDeps(), params.getExtraDeps()); } // Construct the build rule to build the binary JAR. ImmutableSet<JavaLibrary> transitiveClasspathDeps = JavaLibraryClasspathProvider .getClasspathDeps(binaryParams.getDeps()); ImmutableSet<Path> transitiveClasspaths = JavaLibraryClasspathProvider .getClasspathsFromLibraries(transitiveClasspathDeps); BuildRule rule = new JavaBinary(binaryParams.appendExtraDeps(transitiveClasspathDeps), pathResolver, javaOptions.getJavaRuntimeLauncher(), args.mainClass.orElse(null), args.manifestFile.orElse(null), args.mergeManifests.orElse(true), args.metaInfDirectory.orElse(null), args.blacklist, transitiveClasspathDeps, transitiveClasspaths, javaBuckConfig.shouldCacheBinaries()); // If we're packaging native libraries, construct the rule to build the fat JAR, which packages // up the original binary JAR and any required native libraries. if (!nativeLibraries.isEmpty()) { BuildRule innerJarRule = rule; resolver.addToIndex(innerJarRule); SourcePath innerJar = new BuildTargetSourcePath(innerJarRule.getBuildTarget()); rule = new JarFattener( params.appendExtraDeps(Suppliers.<Iterable<BuildRule>>ofInstance( ruleFinder.filterBuildRuleInputs(ImmutableList.<SourcePath>builder().add(innerJar) .addAll(nativeLibraries.values()).build()))), pathResolver, ruleFinder, javacOptions, innerJar, nativeLibraries, javaOptions.getJavaRuntimeLauncher()); } return rule; }
From source file:org.openqa.selenium.remote.session.OperaFilter.java
@Override public Map<String, Object> apply(Map<String, Object> unmodifiedCaps) { ImmutableMap<String, Object> caps = unmodifiedCaps.entrySet().parallelStream() .filter(entry -> ("browserName".equals(entry.getKey()) && "opera".equals(entry.getValue())) || ("browserName".equals(entry.getKey()) && "operablink".equals(entry.getValue())) || "operaOptions".equals(entry.getKey())) .distinct().filter(entry -> Objects.nonNull(entry.getValue())) .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue)); return caps.isEmpty() ? null : caps; }
From source file:org.grycap.gpf4med.DownloadService.java
/** * Uses a group of URIs to retrieve objects and writes them to the same number of files. This method will do * its best effort to optimally handle the downloads, opening a pool of connections to the servers and reusing * them as much as possible. Also, it will create several concurrent threads in the JVM in order to perform * simultaneous downloads./*from w w w .j a va2s.co m*/ * @param requests a key-value map with the list of requests to handle. The source of the object is the key of * the map, while the value is the destination file. * @param validator checks the file for correctness. * @param config download settings. * @param encryptionProvider an optional encryption provider that, when available, is used to encrypt the * files after download. * @param task an optional task that will be executed passing each individual file as parameter, when the download * of the file ends. * @return the requests that could not be served after exhausting the individual retries. * @throws IOException if an error occurs in the execution of the operation. */ public ImmutableMap<URI, File> download(final ImmutableMap<URI, File> requests, final @Nullable FileValidator validator, final DownloadConfiguration config, final @Nullable FileEncryptionProvider encryptionProvider, final @Nullable PostProcessTask<File> task) throws IOException { checkArgument(requests != null, "Uninitialized request"); checkArgument(config != null, "Uninitialized configuration"); ImmutableMap<URI, File> pending = ImmutableMap.copyOf(requests); final List<URI> cancelled = new ArrayList<URI>(); try { for (int attempt = 0; attempt < config.getRetries() && !pending.isEmpty() && pending.size() > cancelled.size(); attempt++) { LOGGER.info("Attempt " + (attempt + 1) + " to download " + requests.size() + " files"); // create connection manager final PoolingNHttpClientConnectionManager connectionManager = createConnectionManager(); // create HTTP asynchronous client int eSoTimeoutMs = config.soToMs + (int) (config.soToMs * attempt * (config.toIncPercent >= 0.0d && config.toIncPercent <= 1.0d ? config.toIncPercent : 0.0d)); int eConnTimeoutMs = config.connToMs + (int) (config.connToMs * attempt * (config.toIncPercent >= 0.0d && config.toIncPercent <= 1.0d ? config.toIncPercent : 0.0d)); final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(eConnTimeoutMs) .setConnectionRequestTimeout(eConnTimeoutMs).setSocketTimeout(eSoTimeoutMs).build(); final CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom() .setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build(); httpclient.start(); // attempt to perform download try { final CountDownLatch latch = new CountDownLatch(pending.size()); for (final Map.Entry<URI, File> entry : pending.entrySet()) { final URI uri = entry.getKey(); if (cancelled.contains(uri)) { continue; } final File file = entry.getValue(); FileUtils.forceMkdir(file.getParentFile()); final HttpGet request = new HttpGet(uri); final HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer( new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), request); final ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(file) { @Override protected File process(final HttpResponse response, final File file, final ContentType contentType) throws Exception { releaseResources(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { FileUtils.deleteQuietly(file); throw new ClientProtocolException( "Download failed: " + response.getStatusLine()); } if (validator != null && !validator.isValid(file)) { FileUtils.deleteQuietly(file); cancelled.add(uri); throw new IOException( file.getCanonicalPath() + " not recognised as a supported file format"); } if (encryptionProvider != null) { try { final File cipherFile = File .createTempFile(RandomStringUtils.random(8, true, true), ".tmp"); encryptionProvider.encrypt(new FileInputStream(file), new FileOutputStream(cipherFile)); FileUtils.deleteQuietly(file); FileUtils.moveFile(cipherFile, file); LOGGER.info("File encrypted: " + file.getCanonicalPath()); } catch (Exception e) { FileUtils.deleteQuietly(file); cancelled.add(uri); LOGGER.warn("Failed to encrypt: " + file.getCanonicalPath(), e); throw new IOException("File encryption failed"); } } LOGGER.info("Download succeed to file: " + file.getCanonicalPath()); return file; } }; httpclient.execute(producer, consumer, new FutureCallback<File>() { @Override public void completed(final File result) { request.releaseConnection(); latch.countDown(); if (task != null) { task.apply(result); } LOGGER.info("Request succeed: " + request.getRequestLine() + " => Response file length: " + result.length()); } @Override public void failed(final Exception ex) { request.releaseConnection(); FileUtils.deleteQuietly(file); latch.countDown(); LOGGER.error("Request failed: " + request.getRequestLine() + "=>" + ex); } @Override public void cancelled() { request.releaseConnection(); FileUtils.deleteQuietly(file); latch.countDown(); LOGGER.error("Request cancelled: " + request.getRequestLine()); } }); } latch.await(); } finally { try { httpclient.close(); } catch (Exception ignore) { } try { shutdown(connectionManager, 0l); } catch (Exception ignore) { } } // populate the pending list with the files that does not exist final ImmutableMap.Builder<URI, File> builder = new ImmutableMap.Builder<URI, File>(); for (final Map.Entry<URI, File> entry : requests.entrySet()) { if (!entry.getValue().exists()) { builder.put(entry.getKey(), entry.getValue()); } } pending = builder.build(); if ((attempt + 1) < config.retries && !pending.isEmpty() && pending.size() > cancelled.size()) { final long waitingTime = (long) (config.soToMs * 0.1d); LOGGER.info("Waiting " + waitingTime + " ms before attempt " + (attempt + 2) + " to download " + requests.size() + " pending files"); Thread.sleep(waitingTime); } } } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new IOException("Download has failed", e); } return pending; }