List of usage examples for com.google.common.collect ImmutableSet.Builder addAll
boolean addAll(Collection<? extends E> c);
From source file:org.lanternpowered.server.data.value.AbstractValueContainer.java
@SuppressWarnings("unchecked") @Override// w ww. j a v a2s . co m default Set<ImmutableValue<?>> getValues() { ImmutableSet.Builder<ImmutableValue<?>> values = ImmutableSet.builder(); for (Map.Entry<Key<?>, KeyRegistration> entry : this.getRawValueMap().entrySet()) { Key key = entry.getKey(); Optional<BaseValue> optValue = this.getValue(key); if (optValue.isPresent()) { values.add(ValueHelper.toImmutable(optValue.get())); } } List<DataManipulator<?, ?>> manipulators = this.getRawAdditionalManipulators(); // Custom data is supported by this container if (manipulators != null) { for (DataManipulator<?, ?> dataManipulator : manipulators) { values.addAll(dataManipulator.getValues()); } } return values.build(); }
From source file:com.addthis.hydra.job.spawn.search.JobSearcher.java
/** * Finds among a list of macros those that contain (recursively) a search match and returns their locations. * <p/>/*from w ww. java 2s . c om*/ * A list of macros and the locations where they are included (in a job config or a macro) are provided to this * method, along with the full macro dependency graph and the complete macro search match results. For each macro * in the list, this method looks at the macro itself and all its direct and indirect dependencies; if any has a * search match, the included macro's locations are added to the result set that will be returned. * * @param macroIncludeLocations the macros and their inclusion locations (in a job config or a macro) * @param dependencyGraph the full macro dependency graph * @param macroSearchResults all macros and their search match locations (if any) * @return the inclusion locations from <code>macroIncludeLocations</code> for the macros that have a search match * in itself or one of its dependencies (direct or indirect) */ private Set<TextLocation> getDependencySearchMatches(IncludeLocations macroIncludeLocations, JobMacroGraph dependencyGraph, Map<String, Set<TextLocation>> macroSearchResults) { ImmutableSet.Builder<TextLocation> builder = ImmutableSet.builder(); for (String depMacroName : macroIncludeLocations.dependencies()) { // For each dependency that depMacroName brings in, see if any of THEM have search results. If they do, we // want to link back to the include to depMacroName in the search result. for (String deeperDepName : dependencyGraph.getDependencies(depMacroName)) { Set<TextLocation> depMacroResults = macroSearchResults.getOrDefault(deeperDepName, ImmutableSet.of()); if (!depMacroResults.isEmpty()) { builder.addAll(macroIncludeLocations.locationsFor(depMacroName)); break; } } } return builder.build(); }
From source file:com.facebook.buck.cxx.PrebuiltCxxLibraryDescription.java
private void addDepsFromParam(BuildTarget target, CellPathResolver cellNames, String paramValue, ImmutableSet.Builder<BuildTarget> targets) { try {//from w w w . j av a2 s. com // doesn't matter that the platform expander doesn't do anything. MacroHandler macroHandler = getMacroHandler(Optional.empty()); // Then get the parse time deps. targets.addAll(macroHandler.extractParseTimeDeps(target, cellNames, paramValue)); } catch (MacroException e) { throw new HumanReadableException(e, "%s : %s in \"%s\"", target, e.getMessage(), paramValue); } }
From source file:org.openspotlight.storage.mongodb.MongoStorageSessionImpl.java
private Iterable<StorageNode> internalGetChildren(final Partition partition, final StorageNode node, final String type) throws Exception { final BasicDBObject baseDbObj = new BasicDBObject(); baseDbObj.put(PARENT_ID, node.getKey().getKeyAsString()); final ImmutableSet.Builder<String> names = ImmutableSet.builder(); if (type != null) { names.add(type);/*from w w w .j a v a 2 s .co m*/ } else { names.addAll(getCachedDbForPartition(partition).getCollectionNames()); } final List<Iterable<DBObject>> dbCursors = newLinkedList(); for (final String s : names.build()) { final DBCursor resultAsDbObject = getCachedCollection(partition, s).find(baseDbObj); dbCursors.add(resultAsDbObject); } final IteratorBuilder.SimpleIteratorBuilder<StorageNode, DBObject> b = IteratorBuilder .createIteratorBuilder(); b.withConverter(new IteratorBuilder.Converter<StorageNode, DBObject>() { @Override public StorageNode convert(final DBObject nodeEntry) throws Exception { return convertToNode(partition, nodeEntry); } }); return b.withItems(SLCollections.<DBObject>iterableOfAll(dbCursors)).andBuild(); }
From source file:com.google.devtools.build.lib.rules.objc.CompilationSupport.java
/** * Registers an action to create an archive artifact by fully (statically) linking all transitive * dependencies of this rule *except* for dependencies given in {@code avoidsDeps}. * * @param objcProvider provides all compiling and linking information to create this artifact * @param outputArchive the output artifact for this action * @param avoidsDeps list of providers with dependencies that should not be linked into the output * artifact/*from ww w . j av a 2s . co m*/ */ public CompilationSupport registerFullyLinkActionWithAvoids(ObjcProvider objcProvider, Artifact outputArchive, Iterable<ObjcProvider> avoidsDeps) throws InterruptedException { ImmutableSet.Builder<Artifact> avoidsDepsArtifacts = ImmutableSet.builder(); for (ObjcProvider avoidsProvider : avoidsDeps) { avoidsDepsArtifacts.addAll(avoidsProvider.getObjcLibraries()) .addAll(avoidsProvider.get(IMPORTED_LIBRARY)).addAll(avoidsProvider.getCcLibraries()); } ImmutableList<Artifact> depsArtifacts = ImmutableList.<Artifact>builder() .addAll(objcProvider.getObjcLibraries()).addAll(objcProvider.get(IMPORTED_LIBRARY)) .addAll(objcProvider.getCcLibraries()).build(); Iterable<Artifact> inputArtifacts = Iterables.filter(depsArtifacts, Predicates.not(Predicates.in(avoidsDepsArtifacts.build()))); return registerFullyLinkAction(objcProvider, inputArtifacts, outputArchive); }
From source file:org.graylog2.alerts.StaticEmailAlertSender.java
@Override public void sendEmails(Stream stream, AlertCondition.CheckResult checkResult, List<Message> backlog) throws TransportConfigurationException, EmailException { if (!configuration.isEnabled()) { throw new TransportConfigurationException( "Email transport is not enabled in server configuration file!"); }// ww w. j a v a 2 s .c om if (stream.getAlertReceivers() == null || stream.getAlertReceivers().isEmpty()) { throw new RuntimeException("Stream [" + stream + "] has no alert receivers."); } final ImmutableSet.Builder<String> recipientsBuilder = ImmutableSet.builder(); // Send emails to subscribed users. final List<String> userNames = stream.getAlertReceivers().get("users"); if (userNames != null) { for (String username : userNames) { final User user = userService.load(username); if (user != null && !isNullOrEmpty(user.getEmail())) { // LDAP users might have multiple email addresses defined. // See: https://github.com/Graylog2/graylog2-server/issues/1439 final Iterable<String> addresses = Splitter.on(",").omitEmptyStrings().trimResults() .split(user.getEmail()); recipientsBuilder.addAll(addresses); } } } // Send emails to directly subscribed email addresses. if (stream.getAlertReceivers().get("emails") != null) { for (String email : stream.getAlertReceivers().get("emails")) { if (!email.isEmpty()) { recipientsBuilder.add(email); } } } final Set<String> recipients = recipientsBuilder.build(); if (recipients.size() == 0) { final Notification notification = notificationService.buildNow().addNode(nodeId.toString()) .addType(Notification.Type.GENERIC).addSeverity(Notification.Severity.NORMAL) .addDetail("title", "Stream \"" + stream.getTitle() + "\" is alerted, but no recipients have been defined!") .addDetail("description", "To fix this, go to the alerting configuration of the stream and add at least one alert recipient."); notificationService.publishIfFirst(notification); } for (String email : recipients) { sendEmail(email, stream, checkResult, backlog); } }
From source file:com.facebook.buck.parser.ParserNg.java
/** * @return a set of {@link BuildTarget} objects that this {@link TargetNodeSpec} refers to. *//*from ww w.j a va 2 s .c o m*/ private ImmutableSet<BuildTarget> resolveTargetSpec(PerBuildState state, Cell cell, TargetNodeSpec spec) throws BuildFileParseException, BuildTargetException, IOException, InterruptedException { ImmutableSet.Builder<BuildTarget> targets = ImmutableSet.builder(); // Iterate over the build files the given target node spec returns. for (Path buildFile : spec.getBuildFileSpec().findBuildFiles(cell)) { // Format a proper error message for non-existent build files. if (!cell.getFilesystem().isFile(buildFile)) { throw new MissingBuildFileException(spec, cell.getFilesystem().getRootPath().relativize(buildFile)); } // Build up a list of all target nodes from the build file. ImmutableSet<TargetNode<?>> nodes = state.getAllTargetNodes(cell, buildFile); // Call back into the target node spec to filter the relevant build targets. targets.addAll(spec.filter(nodes)); } return targets.build(); }
From source file:org.voltcore.messaging.HostMessenger.java
@Override public void notifyOfHosts(int yourHostId, int[] hosts, SocketChannel[] sockets, InetSocketAddress listeningAddresses[]) throws Exception { m_localHostId = yourHostId;//from w ww .j a v a 2s . c o m long agreementHSId = getHSIdForLocalSite(AGREEMENT_SITE_ID); /* * Construct the set of agreement sites based on all the hosts that are connected */ HashSet<Long> agreementSites = new HashSet<Long>(); agreementSites.add(agreementHSId); m_network.start();//network must be running for register to work for (int ii = 0; ii < hosts.length; ii++) { System.out.println(yourHostId + " Notified of host " + hosts[ii]); agreementSites.add(CoreUtils.getHSIdFromHostAndSite(hosts[ii], AGREEMENT_SITE_ID)); prepSocketChannel(sockets[ii]); ForeignHost fhost = null; try { fhost = new ForeignHost(this, hosts[ii], sockets[ii], m_config.deadHostTimeout, listeningAddresses[ii]); fhost.register(this); putForeignHost(hosts[ii], fhost); } catch (java.io.IOException e) { org.voltdb.VoltDB.crashLocalVoltDB("", true, e); } } /* * Create the local agreement site. It knows that it is recovering because the number of * prexisting sites is > 0 */ SiteMailbox sm = new SiteMailbox(this, agreementHSId); createMailbox(agreementHSId, sm); m_agreementSite = new AgreementSite(agreementHSId, agreementSites, yourHostId, sm, new InetSocketAddress(m_config.zkInterface.split(":")[0], Integer.parseInt(m_config.zkInterface.split(":")[1])), m_config.backwardsTimeForgivenessWindow, m_failedHostsCallback); /* * Now that the agreement site mailbox has been created it is safe * to enable read */ for (ForeignHost fh : m_foreignHosts.values()) { fh.enableRead(); } m_agreementSite.start(); /* * Do the usual thing of waiting for the agreement site * to join the cluster and creating the client */ ImmutableSet.Builder<Long> verbotenThreadBuilder = ImmutableSet.<Long>builder(); verbotenThreadBuilder.addAll(m_network.getThreadIds()); verbotenThreadBuilder.addAll(m_agreementSite.getThreadIds()); m_agreementSite.waitForRecovery(); m_zk = org.voltcore.zk.ZKUtil.getClient(m_config.zkInterface, 60 * 1000, verbotenThreadBuilder.build()); if (m_zk == null) { throw new Exception("Timed out trying to connect local ZooKeeper instance"); } /* * Publish the address of this node to ZK as seen by the leader * Also allows waitForGroupJoin to know the number of nodes in the cluster */ byte hostInfoBytes[]; if (m_config.internalInterface.isEmpty()) { InetSocketAddress addr = new InetSocketAddress(m_joiner.m_reportedInternalInterface, m_config.internalPort); hostInfoBytes = addr.toString().getBytes("UTF-8"); } else { InetSocketAddress addr = new InetSocketAddress(m_config.internalInterface, m_config.internalPort); hostInfoBytes = addr.toString().getBytes("UTF-8"); } m_zk.create(CoreZK.hosts_host + getHostId(), hostInfoBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); }
From source file:org.elasticsearch.gateway.GatewayMetaState.java
@Override public void clusterChanged(ClusterChangedEvent event) { Set<String> relevantIndices = new HashSet<>(); final ClusterState state = event.state(); if (state.blocks().disableStatePersistence()) { // reset the current metadata, we need to start fresh... this.previousMetaData = null; previouslyWrittenIndices = ImmutableSet.of(); return;//from w w w . j a v a2 s .c o m } MetaData newMetaData = state.metaData(); // we don't check if metaData changed, since we might be called several times and we need to check dangling... boolean success = true; // write the state if this node is a master eligible node or if it is a data node and has shards allocated on it if (state.nodes().localNode().masterNode() || state.nodes().localNode().dataNode()) { if (previousMetaData == null) { try { // we determine if or if not we write meta data on data only nodes by looking at the shard routing // and only write if a shard of this index is allocated on this node // however, closed indices do not appear in the shard routing. if the meta data for a closed index is // updated it will therefore not be written in case the list of previouslyWrittenIndices is empty (because state // persistence was disabled or the node was restarted), see getRelevantIndicesOnDataOnlyNode(). // we therefore have to check here if we have shards on disk and add their indices to the previouslyWrittenIndices list if (isDataOnlyNode(state)) { ImmutableSet.Builder<String> previouslyWrittenIndicesBuilder = ImmutableSet.builder(); for (IndexMetaData indexMetaData : newMetaData) { IndexMetaData indexMetaDataOnDisk = null; if (indexMetaData.state().equals(IndexMetaData.State.CLOSE)) { indexMetaDataOnDisk = metaStateService.loadIndexState(indexMetaData.index()); } if (indexMetaDataOnDisk != null) { previouslyWrittenIndicesBuilder.add(indexMetaDataOnDisk.index()); } } previouslyWrittenIndices = previouslyWrittenIndicesBuilder.addAll(previouslyWrittenIndices) .build(); } } catch (Throwable e) { success = false; } } // check if the global state changed? if (previousMetaData == null || !MetaData.isGlobalStateEquals(previousMetaData, newMetaData)) { try { metaStateService.writeGlobalState("changed", newMetaData); } catch (Throwable e) { success = false; } } Iterable<IndexMetaWriteInfo> writeInfo; relevantIndices = getRelevantIndices(event.state(), previouslyWrittenIndices); writeInfo = resolveStatesToBeWritten(previouslyWrittenIndices, relevantIndices, previousMetaData, event.state().metaData()); // check and write changes in indices for (IndexMetaWriteInfo indexMetaWrite : writeInfo) { try { metaStateService.writeIndex(indexMetaWrite.reason, indexMetaWrite.newMetaData, indexMetaWrite.previousMetaData); } catch (Throwable e) { success = false; } } } danglingIndicesState.processDanglingIndices(newMetaData); if (success) { previousMetaData = newMetaData; ImmutableSet.Builder<String> builder = ImmutableSet.builder(); previouslyWrittenIndices = builder.addAll(relevantIndices).build(); } }
From source file:com.facebook.buck.android.AndroidBinary.java
@Override public List<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) { ImmutableList.Builder<Step> steps = ImmutableList.builder(); final AndroidTransitiveDependencies transitiveDependencies = findTransitiveDependencies(); // Create the .dex files if we aren't doing pre-dexing. AndroidDexTransitiveDependencies dexTransitiveDependencies = findDexTransitiveDependencies(); Path signedApkPath = getSignedApkPath(); DexFilesInfo dexFilesInfo = addFinalDxSteps(context, transitiveDependencies, dexTransitiveDependencies, filteredResourcesProvider.getResDirectories(), buildableContext, steps); /////*w ww . j a v a 2 s . c o m*/ // BE VERY CAREFUL adding any code below here. // Any inputs to apkbuilder must be reflected in the hash returned by getAbiKeyForDeps. //// // Copy the transitive closure of files in native_libs to a single directory, if any. ImmutableSet<Path> nativeLibraryDirectories; if (!transitiveDependencies.nativeLibsDirectories.isEmpty()) { Path pathForNativeLibs = getPathForNativeLibs(); Path libSubdirectory = pathForNativeLibs.resolve("lib"); steps.add(new MakeCleanDirectoryStep(libSubdirectory)); for (Path nativeLibDir : transitiveDependencies.nativeLibsDirectories) { copyNativeLibrary(nativeLibDir, libSubdirectory, cpuFilters, steps); } nativeLibraryDirectories = ImmutableSet.of(libSubdirectory); } else { nativeLibraryDirectories = ImmutableSet.of(); } // If non-english strings are to be stored as assets, pass them to ApkBuilder. ImmutableSet.Builder<Path> zipFiles = ImmutableSet.builder(); zipFiles.addAll(dexFilesInfo.secondaryDexZips); if (packageStringAssets.isPresent()) { final Path pathToStringAssetsZip = packageStringAssets.get().getPathToStringAssetsZip(); zipFiles.add(pathToStringAssetsZip); // TODO(natthu): Remove this check once we figure out what's exactly causing APKs missing // string assets zip sometimes. steps.add(new AbstractExecutionStep("check_string_assets_zip_exists") { @Override public int execute(ExecutionContext context) { if (!context.getProjectFilesystem().exists(pathToStringAssetsZip)) { context.postEvent( LogEvent.severe("Zip file containing non-english strings was not created: %s", pathToStringAssetsZip)); return 1; } return 0; } }); } ApkBuilderStep apkBuilderCommand = new ApkBuilderStep(aaptPackageResources.getResourceApkPath(), getSignedApkPath(), dexFilesInfo.primaryDexPath, /* javaResourcesDirectories */ ImmutableSet.<String>of(), nativeLibraryDirectories, zipFiles.build(), dexTransitiveDependencies.pathsToThirdPartyJars, keystore.getPathToStore(), keystore.getPathToPropertiesFile(), /* debugMode */ false); steps.add(apkBuilderCommand); Path apkToAlign; // Optionally, compress the resources file in the .apk. if (this.isCompressResources()) { Path compressedApkPath = getCompressedResourcesApkPath(); apkToAlign = compressedApkPath; RepackZipEntriesStep arscComp = new RepackZipEntriesStep(signedApkPath, compressedApkPath, ImmutableSet.of("resources.arsc")); steps.add(arscComp); } else { apkToAlign = signedApkPath; } Path apkPath = getApkPath(); ZipalignStep zipalign = new ZipalignStep(apkToAlign, apkPath); steps.add(zipalign); // Inform the user where the APK can be found. EchoStep success = new EchoStep( String.format("built APK for %s at %s", getBuildTarget().getFullyQualifiedName(), apkPath)); steps.add(success); buildableContext.recordArtifact(getApkPath()); return steps.build(); }