List of usage examples for com.google.common.collect ImmutableMap values
public ImmutableCollection<V> values()
From source file:com.squid.kraken.v4.core.analysis.engine.processor.AnalysisSmartCache.java
/** * Check if the analysis with signature can match at least one candidate; if true will return a AnalysisMatch * Hypothesis: all candidates have the same filter signature as the request * @param restrict : if not empty only the filter that belongs to it will be taken into account. This may be used to generalize a match * @param request : the analysis signature we are looking to match * @param sameFiltersCandidates : a set of candidates to match - note that they all have the same filter signature as the candidate * @return/*from w w w . j a v a2 s. c om*/ */ private AnalysisSmartCacheMatch checkMatchMany(Set<Axis> restrict, AnalysisSmartCacheRequest request, HashSet<String> sameFiltersCandidatesKeys) { // iter to check if we found a compatible query ImmutableMap<String, AnalysisSmartCacheSignature> sameFiltersCandidates = cache .getAllPresent(sameFiltersCandidatesKeys); for (AnalysisSmartCacheSignature candidate : sameFiltersCandidates.values()) { // if not computing more kpis if (request.getMeasures().getKPIs().size() <= candidate.getMeasures().getKPIs().size()) { // check the filters to see if candidate contains request AnalysisSmartCacheMatch match = checkMatchSingle(restrict, request, candidate); if (match != null) { // check the measures Set<Measure> o1 = new HashSet<>(request.getMeasures().getKPIs()); Set<Measure> o2 = new HashSet<>(candidate.getMeasures().getKPIs()); if (o2.containsAll(o1)) { // hide not requested metrics if (!o2.equals(o1)) { if (o2.removeAll(o1) && !o2.isEmpty()) { match.addPostProcessing(new DataMatrixTransformHideColumns<Measure>(o2)); } } // sort if (request.getAnalysis().hasOrderBy()) { if (!request.getAnalysis().getOrders().equals(match.getAnalysis().getOrders())) { match.addPostProcessing( new DataMatrixTransformOrderBy(request.getAnalysis().getOrders())); } } // limit if (request.getAnalysis().hasLimit()) { long ending = request.getAnalysis().getLimit(); if (request.getAnalysis().hasOffset()) { ending += request.getAnalysis().getOffset(); } if (ending < match.getSignature().getRowCount()) { match.addPostProcessing(new DataMatrixTransformTruncate( request.getAnalysis().getLimit(), request.getAnalysis().getOffset())); } } return match; } } } } // else return null; }
From source file:org.apache.beam.sdk.io.kinesis.ShardReadersPool.java
private ImmutableMap<String, ShardRecordsIterator> createMapWithSuccessiveShards( ImmutableMap<String, ShardRecordsIterator> current, ShardRecordsIterator closedShardIterator, List<ShardRecordsIterator> successiveShardRecordIterators) throws TransientKinesisException { ImmutableMap.Builder<String, ShardRecordsIterator> shardsMap = ImmutableMap.builder(); Iterable<ShardRecordsIterator> allShards = Iterables.concat(current.values(), successiveShardRecordIterators); for (ShardRecordsIterator iterator : allShards) { if (!closedShardIterator.getShardId().equals(iterator.getShardId())) { shardsMap.put(iterator.getShardId(), iterator); }// w w w.j a va2 s.c o m } return shardsMap.build(); }
From source file:dagger2.internal.codegen.ProducerFactoryGenerator.java
@Override ImmutableSet<JavaWriter> write(ClassName generatedTypeName, ProductionBinding binding) { TypeMirror keyType = binding.productionType().equals(Type.MAP) ? Util.getProvidedValueTypeOfMap(MoreTypes.asDeclared(binding.key().type())) : binding.key().type();/* w w w.j a v a 2s . c o m*/ TypeName providedTypeName = TypeNames.forTypeMirror(keyType); TypeName futureTypeName = ParameterizedTypeName.create(ClassName.fromClass(ListenableFuture.class), providedTypeName); JavaWriter writer = JavaWriter.inPackage(generatedTypeName.packageName()); ClassWriter factoryWriter = writer.addClass(generatedTypeName.simpleName()); ConstructorWriter constructorWriter = factoryWriter.addConstructor(); constructorWriter.addModifiers(PUBLIC); factoryWriter.addField(binding.bindingTypeElement(), "module").addModifiers(PRIVATE, FINAL); constructorWriter.addParameter(binding.bindingTypeElement(), "module"); constructorWriter.body().addSnippet("assert module != null;").addSnippet("this.module = module;"); factoryWriter.addField(Executor.class, "executor").addModifiers(PRIVATE, FINAL); constructorWriter.addParameter(Executor.class, "executor"); constructorWriter.body().addSnippet("assert executor != null;").addSnippet("this.executor = executor;"); factoryWriter.annotate(Generated.class).setValue(ComponentProcessor.class.getName()); factoryWriter.addModifiers(PUBLIC); factoryWriter.addModifiers(FINAL); factoryWriter.setSuperType(ParameterizedTypeName.create(AbstractProducer.class, providedTypeName)); MethodWriter getMethodWriter = factoryWriter.addMethod(futureTypeName, "compute"); getMethodWriter.annotate(Override.class); getMethodWriter.addModifiers(PROTECTED); final ImmutableMap<BindingKey, FrameworkField> fields = SourceFiles .generateBindingFieldsForDependencies(dependencyRequestMapper, binding.dependencies()); for (FrameworkField bindingField : fields.values()) { TypeName fieldType = bindingField.frameworkType(); FieldWriter field = factoryWriter.addField(fieldType, bindingField.name()); field.addModifiers(PRIVATE, FINAL); constructorWriter.addParameter(field.type(), field.name()); constructorWriter.body().addSnippet("assert %s != null;", field.name()).addSnippet("this.%1$s = %1$s;", field.name()); } boolean returnsFuture = binding.bindingKind().equals(ProductionBinding.Kind.FUTURE_PRODUCTION); ImmutableList<DependencyRequest> asyncDependencies = FluentIterable.from(binding.dependencies()) .filter(new Predicate<DependencyRequest>() { @Override public boolean apply(DependencyRequest dependency) { return isAsyncDependency(dependency); } }).toList(); for (DependencyRequest dependency : asyncDependencies) { ParameterizedTypeName futureType = ParameterizedTypeName .create(ClassName.fromClass(ListenableFuture.class), asyncDependencyType(dependency)); String name = fields.get(dependency.bindingKey()).name(); Snippet futureAccess = Snippet.format("%s.get()", name); getMethodWriter.body().addSnippet("%s %sFuture = %s;", futureType, name, dependency.kind().equals(DependencyRequest.Kind.PRODUCED) ? Snippet.format("%s.createFutureProduced(%s)", ClassName.fromClass(Producers.class), futureAccess) : futureAccess); } if (asyncDependencies.isEmpty()) { ImmutableList.Builder<Snippet> parameterSnippets = ImmutableList.builder(); for (DependencyRequest dependency : binding.dependencies()) { parameterSnippets.add(frameworkTypeUsageStatement( Snippet.format(fields.get(dependency.bindingKey()).name()), dependency.kind())); } final boolean wrapWithFuture = false; // since submitToExecutor will create the future Snippet invocationSnippet = getInvocationSnippet(wrapWithFuture, binding, parameterSnippets.build()); TypeName callableReturnType = returnsFuture ? futureTypeName : providedTypeName; Snippet throwsClause = getThrowsClause(binding.thrownTypes()); Snippet callableSnippet = Snippet.format( Joiner.on('\n').join("new %1$s<%2$s>() {", " @Override public %2$s call() %3$s{", " return %4$s;", " }", "}"), ClassName.fromClass(Callable.class), callableReturnType, throwsClause, invocationSnippet); getMethodWriter.body().addSnippet("%s future = %s.submitToExecutor(%s, executor);", ParameterizedTypeName.create(ClassName.fromClass(ListenableFuture.class), callableReturnType), ClassName.fromClass(Producers.class), callableSnippet); getMethodWriter.body().addSnippet("return %s;", returnsFuture ? Snippet.format("%s.dereference(future)", ClassName.fromClass(Futures.class)) : "future"); } else { final Snippet futureSnippet; final Snippet transformSnippet; if (asyncDependencies.size() == 1) { DependencyRequest asyncDependency = Iterables.getOnlyElement(asyncDependencies); futureSnippet = Snippet.format("%s", fields.get(asyncDependency.bindingKey()).name() + "Future"); String argName = asyncDependency.requestElement().getSimpleName().toString(); ImmutableList.Builder<Snippet> parameterSnippets = ImmutableList.builder(); for (DependencyRequest dependency : binding.dependencies()) { // We really want to compare instances here, because asyncDependency is an element in the // set binding.dependencies(). if (dependency == asyncDependency) { parameterSnippets.add(Snippet.format("%s", argName)); } else { parameterSnippets.add(frameworkTypeUsageStatement( Snippet.format(fields.get(dependency.bindingKey()).name()), dependency.kind())); } } boolean wrapWithFuture = !returnsFuture; // only wrap if we don't already have a future Snippet invocationSnippet = getInvocationSnippet(wrapWithFuture, binding, parameterSnippets.build()); Snippet throwsClause = getThrowsClause(binding.thrownTypes()); transformSnippet = Snippet.format( Joiner.on('\n').join("new %1$s<%2$s, %3$s>() {", " @Override public %4$s apply(%2$s %5$s) %6$s{", " return %7$s;", " }", "}"), ClassName.fromClass(AsyncFunction.class), asyncDependencyType(asyncDependency), providedTypeName, futureTypeName, argName, throwsClause, invocationSnippet); } else { futureSnippet = Snippet.format("%s.<%s>allAsList(%s)", ClassName.fromClass(Futures.class), ClassName.fromClass(Object.class), Joiner.on(",").join(FluentIterable .from(asyncDependencies).transform(new Function<DependencyRequest, String>() { @Override public String apply(DependencyRequest dependency) { return fields.get(dependency.bindingKey()).name() + "Future"; } }))); ImmutableList<Snippet> parameterSnippets = getParameterSnippets(binding, fields, "args"); boolean wrapWithFuture = !returnsFuture; // only wrap if we don't already have a future Snippet invocationSnippet = getInvocationSnippet(wrapWithFuture, binding, parameterSnippets); ParameterizedTypeName listOfObject = ParameterizedTypeName.create(ClassName.fromClass(List.class), ClassName.fromClass(Object.class)); Snippet throwsClause = getThrowsClause(binding.thrownTypes()); transformSnippet = Snippet.format( Joiner.on('\n').join("new %1$s<%2$s, %3$s>() {", " @SuppressWarnings(\"unchecked\") // safe by specification", " @Override public %4$s apply(%2$s args) %5$s{", " return %6$s;", " }", "}"), ClassName.fromClass(AsyncFunction.class), listOfObject, providedTypeName, futureTypeName, throwsClause, invocationSnippet); } getMethodWriter.body().addSnippet("return %s.%s(%s, %s, executor);", ClassName.fromClass(Futures.class), "transform", futureSnippet, transformSnippet); } // TODO(gak): write a sensible toString return ImmutableSet.of(writer); }
From source file:com.facebook.buck.versions.AsyncVersionedTargetGraphBuilder.java
@Override @SuppressWarnings("PMD") public TargetGraph build() throws TimeoutException, InterruptedException, VersionException { LOG.debug("Starting version target graph transformation (nodes %d)", unversionedTargetGraphAndBuildTargets.getTargetGraph().getNodes().size()); long start = System.currentTimeMillis(); ImmutableSet<VersionTargetGraphKey> rootKeys = RichStream .from(unversionedTargetGraphAndBuildTargets.getTargetGraph() .getAll(unversionedTargetGraphAndBuildTargets.getBuildTargets())) .map(ImmutableVersionTargetGraphKey::of).collect(ImmutableSet.toImmutableSet()); ImmutableMap<VersionTargetGraphKey, Future<TargetNode<?>>> results = asyncTransformationEngine .computeAll(rootKeys);/*from w ww .ja va 2 s. c o m*/ // Wait for actions to complete. for (Future<TargetNode<?>> futures : results.values()) { try { futures.get(timeout, timeUnit); } catch (ExecutionException e) { Throwable rootCause = Throwables.getRootCause(e); Throwables.throwIfInstanceOf(rootCause, VersionException.class); Throwables.throwIfInstanceOf(rootCause, TimeoutException.class); Throwables.throwIfInstanceOf(rootCause, RuntimeException.class); throw new IllegalStateException( String.format("Unexpected exception: %s: %s", e.getClass(), e.getMessage()), e); } } asyncTransformationEngine.close(); versionInfoAsyncTransformationEngine.close(); long end = System.currentTimeMillis(); VersionedTargetGraph graph = versionedTargetGraphTransformer.targetGraphBuilder.build(); LOG.debug("Finished version target graph transformation in %.2f (nodes %d, roots: %d)", (end - start) / 1000.0, graph.getSize(), versionedTargetGraphTransformer.roots.get()); return graph; }
From source file:org.glowroot.transaction.AdviceCache.java
@EnsuresNonNull({ "reweavableAdvisors", "reweavableConfigVersions", "allAdvisors" }) public void updateAdvisors(/*>>>@UnknownInitialization(AdviceCache.class) AdviceCache this,*/ List<InstrumentationConfig> reweavableConfigs, boolean cleanTmpDir) throws Exception { ImmutableMap<Advice, LazyDefinedClass> advisors = AdviceGenerator.createAdvisors(reweavableConfigs, null); if (instrumentation == null) { // this is for tests that don't run with javaagent container ClassLoader loader = Thread.currentThread().getContextClassLoader(); checkNotNull(loader, "Context class loader must be set"); ClassLoaders.defineClassesInClassLoader(advisors.values(), loader); } else {/* www .j a v a 2s .c om*/ File generatedJarDir = new File(dataDir, "tmp"); if (cleanTmpDir) { ClassLoaders.createDirectoryOrCleanPreviousContentsWithPrefix(generatedJarDir, "config-pointcuts"); } if (!advisors.isEmpty()) { String suffix = ""; int count = jarFileCounter.incrementAndGet(); if (count > 1) { suffix = "-" + count; } File jarFile = new File(generatedJarDir, "config-pointcuts" + suffix + ".jar"); ClassLoaders.defineClassesInBootstrapClassLoader(advisors.values(), instrumentation, jarFile); } } reweavableAdvisors = advisors.keySet().asList(); reweavableConfigVersions = createReweavableConfigVersions(reweavableConfigs); allAdvisors = ImmutableList.copyOf(Iterables.concat(pluginAdvisors, reweavableAdvisors)); }
From source file:com.facebook.buck.features.python.CxxPythonExtensionDescription.java
private ImmutableList<Arg> getExtensionArgs(BuildTarget target, ProjectFilesystem projectFilesystem, ActionGraphBuilder graphBuilder, SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder, CellPathResolver cellRoots, CxxPlatform cxxPlatform, CxxPythonExtensionDescriptionArg args, ImmutableSet<BuildRule> deps) { ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder(); CxxFlags.getFlagsWithMacrosWithPlatformMacroExpansion(args.getLinkerFlags(), args.getPlatformLinkerFlags(), cxxPlatform).stream()/*ww w .ja v a 2 s . com*/ .map(f -> CxxDescriptionEnhancer.toStringWithMacrosArgs(target, cellRoots, graphBuilder, cxxPlatform, f)) .forEach(argsBuilder::add); // Embed a origin-relative library path into the binary so it can find the shared libraries. argsBuilder.addAll(StringArg.from(Linkers.iXlinker("-rpath", String.format("%s/", cxxPlatform.getLd().resolve(graphBuilder).libOrigin())))); // Add object files into the args. ImmutableMap<CxxPreprocessAndCompile, SourcePath> picObjects = requireCxxObjects(target, projectFilesystem, graphBuilder, pathResolver, ruleFinder, cellRoots, cxxPlatform, args, deps); argsBuilder.addAll(SourcePathArg.from(picObjects.values())); return argsBuilder.build(); }
From source file:org.glowroot.agent.impl.AdviceCache.java
@EnsuresNonNull({ "reweavableAdvisors", "reweavableConfigVersions", "allAdvisors" }) public void updateAdvisors(/*>>>@UnknownInitialization(AdviceCache.class) AdviceCache this,*/ List<InstrumentationConfig> reweavableConfigs, boolean cleanTmpDir) throws Exception { ImmutableMap<Advice, LazyDefinedClass> advisors = AdviceGenerator.createAdvisors(reweavableConfigs, null, true);/* w w w.j a v a 2 s .co m*/ if (instrumentation == null) { // this is for tests that don't run with javaagent container ClassLoader loader = AdviceCache.class.getClassLoader(); checkNotNull(loader); ClassLoaders.defineClassesInClassLoader(advisors.values(), loader); } else { File generatedJarDir = new File(baseDir, "tmp"); if (cleanTmpDir) { ClassLoaders.createDirectoryOrCleanPreviousContentsWithPrefix(generatedJarDir, "config-pointcuts"); } if (!advisors.isEmpty()) { String suffix = ""; int count = jarFileCounter.incrementAndGet(); if (count > 1) { suffix = "-" + count; } File jarFile = new File(generatedJarDir, "config-pointcuts" + suffix + ".jar"); ClassLoaders.defineClassesInBootstrapClassLoader(advisors.values(), instrumentation, jarFile); } } reweavableAdvisors = advisors.keySet().asList(); reweavableConfigVersions = createReweavableConfigVersions(reweavableConfigs); allAdvisors = ImmutableList.copyOf(Iterables.concat(pluginAdvisors, reweavableAdvisors)); }
From source file:com.google.devtools.build.android.AndroidResourceClassWriter.java
private List<FieldInitializer> getStyleableInitializers(Map<String, Integer> attrAssignments, Collection<String> styleableFields) throws AttrLookupException { ImmutableList.Builder<FieldInitializer> initList = ImmutableList.builder(); for (String field : styleableFields) { Set<String> attrs = styleableAttrs.get(field).keySet(); ImmutableMap.Builder<String, Integer> arrayInitValues = ImmutableMap.builder(); for (String attr : attrs) { Integer attrId = attrAssignments.get(attr); if (attrId == null) { // It should be a framework resource, otherwise we don't know about the resource. if (!attr.startsWith(NORMALIZED_ANDROID_PREFIX)) { throw new AttrLookupException("App attribute not found: " + attr); }//from ww w .jav a 2s . com String attrWithoutPrefix = attr.substring(NORMALIZED_ANDROID_PREFIX.length()); attrId = androidIdProvider.getAttrId(attrWithoutPrefix); } arrayInitValues.put(attr, attrId); } // The styleable array should be sorted by ID value. // Make sure that if we have android: framework attributes, their IDs are listed first. ImmutableMap<String, Integer> arrayInitMap = arrayInitValues .orderEntriesByValue(Ordering.<Integer>natural()).build(); initList.add(new IntArrayFieldInitializer(field, arrayInitMap.values())); int index = 0; for (String attr : arrayInitMap.keySet()) { initList.add(new IntFieldInitializer(field + "_" + attr, index)); ++index; } } return initList.build(); }
From source file:io.druid.indexing.overlord.setup.FillCapacityWorkerSelectStrategy.java
@Override public Optional<ImmutableZkWorker> findWorkerForTask(final RemoteTaskRunnerConfig config, final ImmutableMap<String, ImmutableZkWorker> zkWorkers, final Task task) { TreeSet<ImmutableZkWorker> sortedWorkers = Sets.newTreeSet(new Comparator<ImmutableZkWorker>() { @Override/*from w w w .j av a 2 s. c o m*/ public int compare(ImmutableZkWorker zkWorker, ImmutableZkWorker zkWorker2) { int retVal = Ints.compare(zkWorker2.getCurrCapacityUsed(), zkWorker.getCurrCapacityUsed()); if (retVal == 0) { retVal = zkWorker.getWorker().getHost().compareTo(zkWorker2.getWorker().getHost()); } return retVal; } }); sortedWorkers.addAll(zkWorkers.values()); final String minWorkerVer = config.getMinWorkerVersion(); for (ImmutableZkWorker zkWorker : sortedWorkers) { if (zkWorker.canRunTask(task) && zkWorker.isValidVersion(minWorkerVer)) { return Optional.of(zkWorker); } } return Optional.absent(); }
From source file:io.divolte.server.Server.java
Server(final ValidatedConfiguration vc, final IncomingRequestListener listener) { host = vc.configuration().global.server.host; port = vc.configuration().global.server.port; // First thing we need to do is load all the schemas: the sinks need these, but they come from the // mappings.//from ww w.j av a 2s. c o m final SchemaRegistry schemaRegistry = new SchemaRegistry(vc); // Build a set of referenced sinks. These are the only ones we need to instantiate. final ImmutableSet<String> referencedSinkNames = vc.configuration().mappings.values().stream() .flatMap(mc -> mc.sinks.stream()).collect(ImmutableSet.toImmutableSet()); // Instantiate the active sinks: // - As a practical matter, unreferenced sinks have no associated schema, which means they // can't be initialized. // - This is also where we check whether HDFS and Kafka are globally enabled/disabled. logger.debug("Initializing active sinks..."); sinks = vc.configuration().sinks.entrySet().stream() .filter(sink -> referencedSinkNames.contains(sink.getKey())) .filter(sink -> vc.configuration().global.hdfs.enabled || !(sink.getValue() instanceof HdfsSinkConfiguration)) .filter(sink -> vc.configuration().global.gcs.enabled || !(sink.getValue() instanceof GoogleCloudStorageSinkConfiguration)) .filter(sink -> vc.configuration().global.kafka.enabled || !(sink.getValue() instanceof KafkaSinkConfiguration)) .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, sink -> sink.getValue().getFactory().create(vc, sink.getKey(), schemaRegistry))); logger.info("Initialized sinks: {}", sinks.keySet()); logger.debug("Initializing mappings..."); incomingRequestProcessingPool = new IncomingRequestProcessingPool(vc, schemaRegistry, sinks, listener); logger.debug("Initializing sources..."); // Now instantiate all the sources. We do this in parallel because instantiation can be quite slow. final ImmutableMap<String, HttpSource> sources = vc.configuration().sources.entrySet().parallelStream() .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, source -> source.getValue().createSource(vc, source.getKey(), incomingRequestProcessingPool))); logger.debug("Attaching sources: {}", sources.keySet()); // Once all created we can attach them to the server. This has to be done sequentially. PathHandler pathHandler = new PathHandler(); for (final HttpSource source : sources.values()) { pathHandler = source.attachToPathHandler(pathHandler); } logger.info("Initialized sources: {}", sources.keySet()); pathHandler.addExactPath("/ping", PingHandler::handlePingRequest); if (vc.configuration().global.server.serveStaticResources) { // Catch-all handler; must be last if present. // XXX: Our static resources assume the default 'browser' endpoint. pathHandler.addPrefixPath("/", createStaticResourceHandler()); } final SetHeaderHandler headerHandler = new SetHeaderHandler(pathHandler, Headers.SERVER_STRING, "divolte"); final HttpHandler canonicalPathHandler = new CanonicalPathHandler(headerHandler); final GracefulShutdownHandler rootHandler = new GracefulShutdownHandler( vc.configuration().global.server.useXForwardedFor ? new ProxyAdjacentPeerAddressHandler(canonicalPathHandler) : canonicalPathHandler); shutdownHandler = rootHandler; undertow = Undertow.builder().addHttpListener(port, host.orElse(null)) .setHandler(vc.configuration().global.server.debugRequests ? new RequestDumpingHandler(rootHandler) : rootHandler) .build(); }