下面列出了com.google.common.collect.ImmutableSet#size ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@NotNull
private ListenableFuture<PublishReturnCode> handlePublish(@NotNull final PUBLISH publish, @NotNull final ExecutorService executorService, @Nullable final String sender) {
final ImmutableSet<SubscriberWithIdentifiers> subscribers = topicTree.getSubscribers(publish.getTopic());
if (subscribers.size() < 1) {
return Futures.immediateFuture(PublishReturnCode.NO_MATCHING_SUBSCRIBERS);
}
if (!acknowledgeAfterPersist) {
deliverPublish(subscribers, sender, publish, executorService, null);
return Futures.immediateFuture(PublishReturnCode.DELIVERED);
}
final SettableFuture<PublishReturnCode> returnCodeFuture = SettableFuture.create();
deliverPublish(subscribers, sender, publish, executorService, returnCodeFuture);
return returnCodeFuture;
}
private static ImmutableMultimap<TypeRoleFillerRealis, AssessedResponse> getCorrectEquivClassToAssessedResponse(
final ImmutableMultimap<TypeRoleFillerRealis, AssessedResponse> equivClasses) {
final ImmutableMultimap.Builder<TypeRoleFillerRealis, AssessedResponse> ret = ImmutableMultimap.builder();
for (final Map.Entry<TypeRoleFillerRealis, Collection<AssessedResponse>> entry : equivClasses.asMap().entrySet()) {
final Collection<AssessedResponse> responses = entry.getValue();
// a key equivalence class is correct if anyone found a correct response in that class
final ImmutableSet<AssessedResponse> correctResponses = ImmutableSet.copyOf(FluentIterable.from(responses).filter(AssessedResponse.IsCorrectUpToInexactJustifications));
if(correctResponses.size() >= 1) {
ret.putAll(entry.getKey(), correctResponses);
}
}
return ret.build();
}
/**
* Call {@link com.google.devtools.build.lib.packages.SkylarkExportable#export(Label, String)} on
* any objects that are assigned to
*
* <p>This is primarily used to make sure that {@link SkylarkUserDefinedRule} and {@link
* com.facebook.buck.core.rules.providers.impl.UserDefinedProvider} instances set their name
* properly upon assignment
*
* @param extensionEnv The environment where an exportable variable with the name in {@code stmt}
* is bound
* @param stmt The assignment statement used to lookup the variable in the environment
*/
private void ensureExportedIfExportable(Environment extensionEnv, AssignmentStatement stmt)
throws BuildFileParseException, EvalException {
ImmutableSet<Identifier> identifiers = ValidationEnvironment.boundIdentifiers(stmt.getLHS());
if (identifiers.size() != 1) {
return;
}
String identifier = Iterables.getOnlyElement(identifiers).getName();
Object lookedUp = extensionEnv.moduleLookup(identifier);
if (lookedUp instanceof SkylarkExportable) {
SkylarkExportable exportable = (SkylarkExportable) lookedUp;
if (!exportable.isExported()) {
Label extensionLabel = extensionEnv.getGlobals().getLabel();
if (extensionLabel != null) {
exportable.export(extensionLabel, identifier);
if (lookedUp instanceof SkylarkUserDefinedRule) {
this.buckGlobals
.getKnownUserDefinedRuleTypes()
.addRule((SkylarkUserDefinedRule) exportable);
}
}
}
}
}
private static BundleModule processModule(BundleModule module) {
Optional<NativeLibraries> nativeConfig = module.getNativeConfig();
if (!nativeConfig.isPresent()) {
return module;
}
ImmutableSet<TargetedNativeDirectory> dirsToRemove =
get64BitTargetedNativeDirectories(nativeConfig.get());
if (dirsToRemove.isEmpty()) {
return module;
}
if (dirsToRemove.size() == nativeConfig.get().getDirectoryCount()) {
throw InvalidBundleException.builder()
.withUserMessage(
"Usage of 64-bit native libraries is disabled by the presence of a "
+ "renderscript file, but App Bundle contains only 64-bit native libraries.")
.build();
}
return module.toBuilder()
.setRawEntries(processEntries(module.getEntries(), dirsToRemove))
.setNativeConfig(processTargeting(nativeConfig.get(), dirsToRemove))
.build();
}
@Override
public boolean hasFlavors(
ImmutableSet<Flavor> flavors, TargetConfiguration toolchainTargetConfiguration) {
if (flavors.isEmpty()) {
return true;
}
if (flavors.size() == 1) {
Flavor flavor = flavors.iterator().next();
return flavor.equals(RESOURCES_SYMLINK_TREE_FLAVOR)
|| flavor.equals(ASSETS_SYMLINK_TREE_FLAVOR)
|| flavor.equals(AAPT2_COMPILE_FLAVOR)
|| flavor.equals(ANDROID_RESOURCE_INDEX_FLAVOR);
}
return false;
}
private CurrencyCode getCurrencyCode()
{
if (paymentRow != null)
{
return paymentRow.getOpenAmt().getCurrencyCode();
}
if (!invoiceRows.isEmpty())
{
final ImmutableSet<CurrencyCode> invoiceCurrencyCodes = invoiceRows.stream()
.map(invoiceRow -> invoiceRow.getOpenAmt().getCurrencyCode())
.collect(ImmutableSet.toImmutableSet());
if (invoiceCurrencyCodes.size() != 1)
{
throw new AdempiereException("More than one currency found");
}
else
{
return invoiceCurrencyCodes.iterator().next();
}
}
throw new AdempiereException("Cannot detect currency if no payments and no invoices were specified");
}
private ProcessLayout(final Builder builder)
{
Preconditions.checkNotNull(builder.processId, "processId not set: %s", builder);
processId = builder.processId;
Preconditions.checkNotNull(builder.layoutType, "layoutType not set: %s", builder);
layoutType = builder.layoutType;
caption = TranslatableStrings.nullToEmpty(builder.caption);
description = TranslatableStrings.nullToEmpty(builder.description);
elements = ImmutableList.copyOf(builder.elements);
if (layoutType == PanelLayoutType.SingleOverlayField)
{
final ImmutableSet<BarcodeScannerType> barcodeScannerTypes = this.elements.stream()
.map(DocumentLayoutElementDescriptor::getBarcodeScannerType)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
barcodeScannerType = barcodeScannerTypes.size() == 1 ? barcodeScannerTypes.iterator().next() : null;
}
else
{
barcodeScannerType = null;
}
}
@Value.Lazy
List<TypeElement> includedTypes() {
Optional<IncludeMirror> includes = include();
ImmutableList<TypeMirror> typeMirrors = includes.isPresent()
? ImmutableList.copyOf(includes.get().valueMirror())
: ImmutableList.<TypeMirror>of();
FluentIterable<TypeElement> typeElements = FluentIterable.from(typeMirrors)
.filter(DeclaredType.class)
.transform(DeclatedTypeToElement.FUNCTION);
ImmutableSet<String> uniqueTypeNames = typeElements
.filter(IsPublic.PREDICATE)
.transform(ElementToName.FUNCTION)
.toSet();
if (uniqueTypeNames.size() != typeMirrors.size()) {
report().annotationNamed(IncludeMirror.simpleName())
.warning(About.INCOMPAT,
"Some types were ignored, non-supported for inclusion: duplicates,"
+ " non declared reference types, non-public");
}
return typeElements.toList();
}
Door(Line2D segment, ImmutableSet<Room> rooms, Room disambiguator) {
this.segment = segment;
this.rooms = rooms;
this.disambiguator = rooms.size() == 1 ? disambiguator : null;
for (Room room : rooms) {
room.addDoor(this);
}
}
/**
* Returns an optional charset for the value of the charset parameter if it is specified.
*
* @throws IllegalStateException if multiple charset values have been set for this media type
* @throws IllegalCharsetNameException if a charset value is present, but illegal
* @throws UnsupportedCharsetException if a charset value is present, but no support is available
* in this instance of the Java virtual machine
*/
public Optional<Charset> charset() {
ImmutableSet<String> charsetValues = ImmutableSet.copyOf(parameters.get(CHARSET_ATTRIBUTE));
switch (charsetValues.size()) {
case 0:
return Optional.absent();
case 1:
return Optional.of(Charset.forName(Iterables.getOnlyElement(charsetValues)));
default:
throw new IllegalStateException("Multiple charset values defined: " + charsetValues);
}
}
public Started(
ArtifactCacheEvent.Operation operation,
ImmutableSet<BuildTarget> targets,
ImmutableSet<RuleKey> ruleKeys,
StoreType storeType) {
super(
EventKey.unique(),
CACHE_MODE,
operation,
targets.size() == 1 ? Optional.of(Iterables.getOnlyElement(targets)) : Optional.empty(),
ruleKeys,
ArtifactCacheEvent.InvocationType.SYNCHRONOUS,
storeType);
}
/** Validates that a Provides or Produces method doesn't have multiple qualifiers. */
static void validateMethodQualifiers(ValidationReport.Builder<ExecutableElement> builder,
ExecutableElement methodElement) {
ImmutableSet<? extends AnnotationMirror> qualifiers = getQualifiers(methodElement);
if (qualifiers.size() > 1) {
for (AnnotationMirror qualifier : qualifiers) {
builder.addItem(PROVIDES_OR_PRODUCES_METHOD_MULTIPLE_QUALIFIERS, methodElement, qualifier);
}
}
}
@Override
protected void handleResponseSetIDs(final ResponseLinking.Builder responseLinking,
final ImmutableSet<ResponseSet> responseSets,
final ImmutableMap<String, ResponseSet> responseIDs,
final Optional<ImmutableMap.Builder<String, String>> foreignLinkingIdToLocal)
throws IOException {
if (responseSets.size() == responseIDs.size()) {
responseLinking.responseSetIds(ImmutableBiMap.copyOf(responseIDs));
responseLinking.build();
} else if (responseSets.size() > responseIDs.size() || !foreignLinkingIdToLocal.isPresent()) {
throw new IOException("Read " + responseSets.size() + " response sets but "
+ responseIDs.size() + " ID assignments");
} else {
log.warn(
"Warning - converting ResponseSet IDs and saving them, this is almost definitely an error!");
final ImmutableMultimap<ResponseSet, String> responseSetToIds =
responseIDs.asMultimap().inverse();
final LaxImmutableMapBuilder<String, ResponseSet> idsMapB =
MapUtils.immutableMapBuilderAllowingSameEntryTwice();
for (final Map.Entry<ResponseSet, Collection<String>> setAndIds : responseSetToIds.asMap()
.entrySet()) {
final Collection<String> ids = setAndIds.getValue();
final String selectedID =
checkNotNull(getFirst(usingToString().immutableSortedCopy(ids), null));
for (final String oldId : ids) {
log.debug("Selecting id {} for cluster {}", selectedID, oldId);
foreignLinkingIdToLocal.get().put(oldId, selectedID);
idsMapB.put(selectedID, responseIDs.get(oldId));
}
}
responseLinking.responseSetIds(ImmutableBiMap.copyOf(idsMapB.build()));
}
}
@Override
public ListenableFuture<ImmutableMap<RuleKey, CacheResult>> multiContainsAsync(
ImmutableSet<RuleKey> ruleKeys) {
Map<RuleKey, CacheResult> initialResults = new HashMap<>(ruleKeys.size());
for (RuleKey ruleKey : ruleKeys) {
initialResults.put(ruleKey, CacheResult.miss());
}
ListenableFuture<Map<RuleKey, CacheResult>> cacheResultFuture =
Futures.immediateFuture(initialResults);
for (ArtifactCache nextCache : artifactCaches) {
cacheResultFuture =
Futures.transformAsync(
cacheResultFuture,
mergedResults -> {
ImmutableSet<RuleKey> missingKeys =
mergedResults.entrySet().stream()
.filter(e -> !e.getValue().getType().isSuccess())
.map(Map.Entry::getKey)
.collect(ImmutableSet.toImmutableSet());
if (missingKeys.isEmpty()) {
return Futures.immediateFuture(mergedResults);
}
ListenableFuture<ImmutableMap<RuleKey, CacheResult>> more =
nextCache.multiContainsAsync(missingKeys);
return Futures.transform(
more,
results -> {
mergedResults.putAll(results);
return mergedResults;
},
MoreExecutors.directExecutor());
},
MoreExecutors.directExecutor());
}
return Futures.transform(
cacheResultFuture, ImmutableMap::copyOf, MoreExecutors.directExecutor());
}
/**
* Merge install-time modules into base module, unless they have {@code <dist:removable
* dist:value="true" />} in install-time attribute.
*/
public static AppBundle mergeNonRemovableInstallTimeModules(
AppBundle appBundle, boolean overrideBundleToolVersion) throws IOException {
ImmutableSet<BundleModule> bundleModulesToFuse =
Stream.concat(
Stream.of(appBundle.getBaseModule()),
appBundle.getFeatureModules().values().stream()
.filter(
module ->
shouldMerge(
module, appBundle.getBundleConfig(), overrideBundleToolVersion)))
.collect(toImmutableSet());
// If only base module should be fused there is nothing to do.
if (bundleModulesToFuse.size() == 1) {
return appBundle;
}
BundleModule.Builder mergedBaseModule =
BundleModule.builder()
.setName(BundleModuleName.BASE_MODULE_NAME)
.setBundleConfig(appBundle.getBundleConfig());
mergeApexTable(bundleModulesToFuse).ifPresent(mergedBaseModule::setApexConfig);
mergeAssetsTable(bundleModulesToFuse).ifPresent(mergedBaseModule::setAssetsConfig);
mergeNativeLibraryTable(bundleModulesToFuse).ifPresent(mergedBaseModule::setNativeConfig);
mergeResourceTable(bundleModulesToFuse).ifPresent(mergedBaseModule::setResourceTable);
mergeAndroidManifest(bundleModulesToFuse, mergedBaseModule);
ImmutableList<ModuleEntry> renamedDexEntries =
ModuleSplitsToShardMerger.renameDexFromAllModulesToSingleShard(
getDexEntries(bundleModulesToFuse));
mergedBaseModule
.addEntries(getAllEntriesExceptDexAndSpecial(bundleModulesToFuse))
.addEntries(renamedDexEntries);
return appBundle.toBuilder()
.setRawModules(
Stream.concat(
Stream.of(mergedBaseModule.build()),
appBundle.getModules().values().stream()
.filter(module -> !bundleModulesToFuse.contains(module)))
.collect(toImmutableSet()))
.build();
}
@Override
public ValidationReport<ExecutableElement> validate(ExecutableElement producesMethodElement) {
ValidationReport.Builder<ExecutableElement> builder =
ValidationReport.Builder.about(producesMethodElement);
Produces producesAnnotation = producesMethodElement.getAnnotation(Produces.class);
checkArgument(producesAnnotation != null);
Element enclosingElement = producesMethodElement.getEnclosingElement();
if (!isAnnotationPresent(enclosingElement, ProducerModule.class)) {
builder.addItem(formatModuleErrorMessage(BINDING_METHOD_NOT_IN_MODULE),
producesMethodElement);
}
if (!producesMethodElement.getTypeParameters().isEmpty()) {
builder.addItem(formatErrorMessage(BINDING_METHOD_TYPE_PARAMETER), producesMethodElement);
}
Set<Modifier> modifiers = producesMethodElement.getModifiers();
if (modifiers.contains(PRIVATE)) {
builder.addItem(formatErrorMessage(BINDING_METHOD_PRIVATE), producesMethodElement);
}
if (modifiers.contains(STATIC)) {
// TODO(gak): why not?
builder.addItem(formatErrorMessage(BINDING_METHOD_STATIC), producesMethodElement);
}
if (modifiers.contains(ABSTRACT)) {
builder.addItem(formatErrorMessage(BINDING_METHOD_ABSTRACT), producesMethodElement);
}
TypeMirror returnType = producesMethodElement.getReturnType();
TypeKind returnTypeKind = returnType.getKind();
if (returnTypeKind.equals(VOID)) {
builder.addItem(formatErrorMessage(BINDING_METHOD_MUST_RETURN_A_VALUE),
producesMethodElement);
}
// check mapkey is right
if (!producesAnnotation.type().equals(Produces.Type.MAP)
&& (getMapKeys(producesMethodElement) != null
&& !getMapKeys(producesMethodElement).isEmpty())) {
builder.addItem(formatErrorMessage(BINDING_METHOD_NOT_MAP_HAS_MAP_KEY),
producesMethodElement);
}
ProvidesMethodValidator.validateMethodQualifiers(builder, producesMethodElement);
switch (producesAnnotation.type()) {
case UNIQUE: // fall through
case SET:
validateSingleReturnType(builder, returnType);
break;
case MAP:
validateSingleReturnType(builder, returnType);
ImmutableSet<? extends AnnotationMirror> annotationMirrors =
getMapKeys(producesMethodElement);
switch (annotationMirrors.size()) {
case 0:
builder.addItem(formatErrorMessage(BINDING_METHOD_WITH_NO_MAP_KEY),
producesMethodElement);
break;
case 1:
break;
default:
builder.addItem(formatErrorMessage(BINDING_METHOD_WITH_MULTIPLE_MAP_KEY),
producesMethodElement);
break;
}
break;
case SET_VALUES:
if (returnTypeKind.equals(DECLARED)
&& MoreTypes.isTypeOf(ListenableFuture.class, returnType)) {
DeclaredType declaredReturnType = MoreTypes.asDeclared(returnType);
if (!declaredReturnType.getTypeArguments().isEmpty()) {
validateSetType(builder, Iterables.getOnlyElement(
declaredReturnType.getTypeArguments()));
}
} else {
validateSetType(builder, returnType);
}
break;
default:
throw new AssertionError();
}
return builder.build();
}
public static boolean updateServerOps(
final ServerSideOperations operations,
final String index,
final ServerOpConfig... configs) {
if ((configs != null) && (configs.length > 0)) {
final Map<String, ImmutableSet<ServerOpScope>> iteratorScopes =
operations.listServerOps(index);
for (final ServerOpConfig config : configs) {
boolean mustDelete = false;
boolean exists = false;
final ImmutableSet<ServerOpScope> existingScopes =
iteratorScopes.get(config.getServerOpName());
ImmutableSet<ServerOpScope> configuredScopes;
if (config.getScopes() == null) {
configuredScopes = Sets.immutableEnumSet(EnumSet.allOf(ServerOpScope.class));
} else {
configuredScopes = Sets.immutableEnumSet(config.getScopes());
}
Map<String, String> configuredOptions = null;
if (existingScopes != null) {
if (existingScopes.size() == configuredScopes.size()) {
exists = true;
for (final ServerOpScope s : existingScopes) {
if (!configuredScopes.contains(s)) {
// this iterator exists with the wrong
// scope, we will assume we want to remove
// it and add the new configuration
LOGGER.warn(
"found iterator '"
+ config.getServerOpName()
+ "' missing scope '"
+ s.name()
+ "', removing it and re-attaching");
mustDelete = true;
break;
}
}
}
if (existingScopes.size() > 0) {
// see if the options are the same, if they are not
// the same, apply a merge with the existing options
// and the configured options
final Iterator<ServerOpScope> it = existingScopes.iterator();
while (it.hasNext()) {
final ServerOpScope scope = it.next();
final Map<String, String> existingOptions =
operations.getServerOpOptions(index, config.getServerOpName(), scope);
configuredOptions = config.getOptions(existingOptions);
if (existingOptions == null) {
mustDelete = (configuredOptions == null);
} else if (configuredOptions == null) {
mustDelete = true;
} else {
// neither are null, compare the size of
// the entry sets and check that they
// are equivalent
final Set<Entry<String, String>> existingEntries = existingOptions.entrySet();
final Set<Entry<String, String>> configuredEntries = configuredOptions.entrySet();
if (existingEntries.size() != configuredEntries.size()) {
mustDelete = true;
} else {
mustDelete = (!existingEntries.containsAll(configuredEntries));
}
}
// we found the setting existing in one
// scope, assume the options are the same
// for each scope
break;
}
}
}
if (configuredOptions == null) {
configuredOptions = config.getOptions(new HashMap<String, String>());
}
if (mustDelete) {
operations.updateServerOp(
index,
config.getServerOpPriority(),
config.getServerOpName(),
config.getServerOpClass(),
configuredOptions,
existingScopes,
configuredScopes);
} else if (!exists) {
operations.addServerOp(
index,
config.getServerOpPriority(),
config.getServerOpName(),
config.getServerOpClass(),
configuredOptions,
configuredScopes);
}
}
}
return true;
}
private ImmutableSet<String> outputAttributes() {
// There's no easy way apparently to ensure that an option has not been set
ImmutableSet<String> deprecated = outputAttributesDeprecated.get();
ImmutableSet<String> sane = outputAttributesSane.get();
return sane.size() > deprecated.size() ? sane : deprecated;
}
/**
* Returns the path on disk to the running Core Simulator service, if any. Returns {@code
* Optional.empty()} unless exactly one Core Simulator service is running.
*/
public Optional<Path> getCoreSimulatorServicePath(UserIdFetcher userIdFetcher)
throws IOException, InterruptedException {
ImmutableSet<String> coreSimulatorServiceNames =
getMatchingServiceNames(CORE_SIMULATOR_SERVICE_PATTERN);
if (coreSimulatorServiceNames.size() != 1) {
LOG.debug("Could not get core simulator service name (got %s)", coreSimulatorServiceNames);
return Optional.empty();
}
String coreSimulatorServiceName = Iterables.getOnlyElement(coreSimulatorServiceNames);
ImmutableList<String> launchctlPrintCommand =
ImmutableList.of(
"launchctl",
"print",
String.format("user/%d/%s", userIdFetcher.getUserId(), coreSimulatorServiceName));
LOG.debug(
"Getting status of service %s with %s", coreSimulatorServiceName, launchctlPrintCommand);
ProcessExecutorParams launchctlPrintParams =
ProcessExecutorParams.builder().setCommand(launchctlPrintCommand).build();
ProcessExecutor.Result launchctlPrintResult =
processExecutor.launchAndExecute(launchctlPrintParams);
Optional<Path> result = Optional.empty();
if (launchctlPrintResult.getExitCode() != LAUNCHCTL_EXIT_SUCCESS) {
LOG.error(
launchctlPrintResult.getMessageForUnexpectedResult(launchctlPrintCommand.toString()));
return result;
}
String output =
launchctlPrintResult
.getStdout()
.orElseThrow(() -> new IllegalStateException("stdout should be captured"));
Iterable<String> lines = MoreStrings.lines(output);
for (String line : lines) {
Matcher matcher = LAUNCHCTL_PRINT_PATH_PATTERN.matcher(line);
if (matcher.matches()) {
String path = matcher.group(1);
LOG.debug("Found path of service %s: %s", coreSimulatorServiceName, path);
result = Optional.of(Paths.get(path));
break;
}
}
return result;
}
/**
* Returns an appropriate {@code TypeName} for the given type. If the type is an
* {@code ErrorType}, and if it is a simple-name reference to one of the {@code *Factory}
* classes that we are going to generate, then we return its fully-qualified name. In every other
* case we just return {@code TypeName.get(type)}. Specifically, if it is an {@code ErrorType}
* referencing some other type, or referencing one of the classes we are going to generate but
* using its fully-qualified name, then we leave it as-is. JavaPoet treats {@code TypeName.get(t)}
* the same for {@code ErrorType} as for {@code DeclaredType}, which means that if this is a name
* that will eventually be generated then the code we write that references the type will in fact
* compile.
*
* <p>A simpler alternative would be to defer processing to a later round if we find an
* {@code @AutoFactory} class that references undefined types, under the assumption that something
* else will generate those types in the meanwhile. However, this would fail if for example
* {@code @AutoFactory class Foo} has a constructor parameter of type {@code BarFactory} and
* {@code @AutoFactory class Bar} has a constructor parameter of type {@code FooFactory}. We did
* in fact find instances of this in Google's source base.
*/
private TypeName resolveTypeName(TypeMirror type) {
if (type.getKind() != TypeKind.ERROR) {
return TypeName.get(type);
}
ImmutableSet<PackageAndClass> factoryNames = factoriesBeingCreated.get(type.toString());
if (factoryNames.size() == 1) {
PackageAndClass packageAndClass = Iterables.getOnlyElement(factoryNames);
return ClassName.get(packageAndClass.packageName(), packageAndClass.className());
}
return TypeName.get(type);
}