下面列出了怎么用com.google.common.collect.MoreCollectors的API类实例代码及写法,或者点击链接到github查看源代码。
private OperatorStats searchScanFilterAndProjectOperatorStats(QueryId queryId, String tableName)
{
DistributedQueryRunner runner = (DistributedQueryRunner) getQueryRunner();
Plan plan = runner.getQueryPlan(queryId);
PlanNodeId nodeId = PlanNodeSearcher.searchFrom(plan.getRoot())
.where(node -> {
if (!(node instanceof ProjectNode)) {
return false;
}
ProjectNode projectNode = (ProjectNode) node;
FilterNode filterNode = (FilterNode) projectNode.getSource();
TableScanNode tableScanNode = (TableScanNode) filterNode.getSource();
return tableName.equals(tableScanNode.getTable().getConnectorHandle().toString());
})
.findOnlyElement()
.getId();
return runner.getCoordinator()
.getQueryManager()
.getFullQueryInfo(queryId)
.getQueryStats()
.getOperatorSummaries()
.stream()
.filter(summary -> nodeId.equals(summary.getPlanNodeId()))
.collect(MoreCollectors.onlyElement());
}
private MethodDescriptor resolveMethodReferenceTarget(ExpressionMethodReference expression) {
IMethodBinding methodBinding = expression.resolveMethodBinding();
if (methodBinding == null) {
// JDT did not resolve the method binding but it was not a compilation error. This situation
// seems to happen only for method references on array objects.
checkArgument(expression.getExpression().resolveTypeBinding().isArray());
// Array methods are provided by java.lang.Object and are matched here by name. This is safe
// because there is only a handful of method in java.lang.Object and if methods are added
// in the future they will be caught be the MoreCollectors.onlyElement. Resolving the target
// correctly if there were many overloads is extra complexity that can be left out until
// it is really needed.
String targetMethodName = expression.getName().getIdentifier();
return TypeDescriptors.get().javaLangObject.getMethodDescriptors().stream()
.filter(m -> m.getName().equals(targetMethodName))
.collect(MoreCollectors.onlyElement());
}
return JdtUtils.createMethodDescriptor(methodBinding);
}
private static MethodDescriptor getPrimaryConstructorDescriptor(final Type type) {
if (type.getConstructors().isEmpty()) {
return type.getDeclaration()
.getDeclaredMethodDescriptors()
.stream()
.filter(MethodDescriptor::isConstructor)
.collect(MoreCollectors.onlyElement());
}
ImmutableList<Method> superDelegatingConstructors =
type.getConstructors()
.stream()
.filter(Predicates.not(AstUtils::hasThisCall))
.collect(ImmutableList.toImmutableList());
return superDelegatingConstructors.size() != 1
? null
: superDelegatingConstructors.get(0).getDescriptor();
}
private Optional<String> dockerContainerFromSpawn(Spawn spawn) throws ExecException {
Platform platform =
PlatformUtils.getPlatformProto(spawn, cmdEnv.getOptions().getOptions(RemoteOptions.class));
if (platform != null) {
try {
return platform
.getPropertiesList()
.stream()
.filter(p -> p.getName().equals(CONTAINER_IMAGE_ENTRY_NAME))
.map(p -> p.getValue())
.filter(r -> r.startsWith(DOCKER_IMAGE_PREFIX))
.map(r -> r.substring(DOCKER_IMAGE_PREFIX.length()))
.collect(MoreCollectors.toOptional());
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
String.format(
"Platform %s contained multiple container-image entries, but only one is allowed.",
spawn.getExecutionPlatform().label()),
e);
}
} else {
return Optional.empty();
}
}
private static Optional<Method> getRemoveInputFunction(Class<?> clazz, Method inputFunction)
{
// Only include methods which take the same parameters as the corresponding input function
return FunctionsParserHelper.findPublicStaticMethodsWithAnnotation(clazz, RemoveInputFunction.class).stream()
.filter(method -> Arrays.equals(method.getParameterTypes(), inputFunction.getParameterTypes()))
.filter(method -> Arrays.deepEquals(method.getParameterAnnotations(), inputFunction.getParameterAnnotations()))
.collect(MoreCollectors.toOptional());
}
private static Optional<AbiAlias> getAbi(VariantTargeting variantTargeting) {
if (variantTargeting.getAbiTargeting().getValueList().isEmpty()) {
return Optional.empty();
}
return Optional.of(
variantTargeting
.getAbiTargeting()
.getValueList()
.stream()
// For now we only support one value in AbiTargeting.
.collect(MoreCollectors.onlyElement())
.getAlias());
}
private static Optional<TextureCompressionFormatAlias> getTextureCompressionFormat(
VariantTargeting variantTargeting) {
if (variantTargeting.getTextureCompressionFormatTargeting().getValueList().isEmpty()) {
return Optional.empty();
}
return Optional.of(
variantTargeting.getTextureCompressionFormatTargeting().getValueList().stream()
// For now we only support one value in TextureCompressionFormatTargeting.
.collect(MoreCollectors.onlyElement())
.getAlias());
}
private static ImmutableSet<AbiAlias> getMultiAbi(VariantTargeting variantTargeting) {
if (variantTargeting.getMultiAbiTargeting().getValueList().isEmpty()) {
return ImmutableSet.of();
}
return variantTargeting.getMultiAbiTargeting().getValueList().stream()
// For now we only support one value in MultiAbiTargeting.
.collect(MoreCollectors.onlyElement())
.getAbiList()
.stream()
.map(Abi::getAlias)
.collect(toImmutableSet());
}
/** Returns the single declared constructor fo this class. */
@Memoized
public MethodDescriptor getSingleConstructor() {
return getDeclaredMethodDescriptors()
.stream()
.filter(MethodDescriptor::isConstructor)
.collect(MoreCollectors.onlyElement());
}
protected Map<String, String> getLocalTestMergeeManifests(ConfiguredTarget target)
throws Exception {
return getMergeeManifests(
collectRunfiles(target).toList().stream()
.filter(
(artifact) ->
artifact.getFilename().equals("AndroidManifest.xml")
&& artifact.getOwnerLabel().equals(target.getLabel()))
.collect(MoreCollectors.onlyElement()));
}
public <T extends Postable> T findPostOnce(Class<T> clazz) {
return storedErrors
.getPosts()
.stream()
.filter(clazz::isInstance)
.map(clazz::cast)
.collect(MoreCollectors.onlyElement());
}
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1);
Optional<Integer> number = numbers
.stream()
.map(e -> e * 2)
.collect(MoreCollectors.toOptional());
}
@Test
public void toOptionalTest() {
List<Integer> numbers = Arrays.asList(1);
Optional<Integer> number = numbers
.stream()
.map(e -> e * 2)
.collect(MoreCollectors.toOptional());
Assert.assertEquals(number.get(), new Integer(2));
}
@Test
public void onlyElementTest() {
List<Integer> numbers = Arrays.asList(1);
Integer number = numbers
.stream()
.map(e -> e * 2)
.collect(MoreCollectors.onlyElement());
Assert.assertEquals(number, new Integer(2));
}
/**
* Returns the superconstructor method that should be the target of the implicit super() call.
*
* <p>Note: Implicit super constructor calls are inserted when no explicit call to super() or
* this() appear in the constructor (JLS 8.8.7). Such call, super() with no parameters, is treated
* as if written by the user and is subject to standard overloading rules (JLS 15.12.2.1 to
* 15.12.2.6). JLS 15.12.2 describes how the match should be made. The rules are rather complex
* but they become simpler when the method is not an instance method, and boil down to finding the
* most specific overload.
*
* <p>Since the implicit method call has no parameters the only other possible match apart of the
* 0-parameter constructor is the 1-parameter varargs which could have many overloads.
*
* <p>So far this is the only place where J2CL explicitly resolves the target overloaded method,
* all other cases are resolved by the frontend.
*/
private static MethodDescriptor getDefaultSuperConstructorTarget(
DeclaredTypeDescriptor typeDescriptor) {
DeclaredTypeDescriptor superTypeDescriptor = typeDescriptor.getSuperTypeDescriptor();
if (typeDescriptor.isEnum()) {
// Enum is special, in subclasses the constructors have two implicit parameters
// (name and ordinal) which are omitted. But when looking at the methods in the Enum class,
// those parameters are explicit.
// Anyway, the super class here is always Enum, which does not have a varargs constructor,
// so we can dispatch to the implicit super constructor as before.
// The anonymous inner enum values ARE NOT handled here since they are created with an
// explicit super call to the target provided by the frontend..
return AstUtils.createImplicitConstructorDescriptor(superTypeDescriptor);
}
// Get all possible targets of an implicit super() call. The targets can either be a
// parameterless constructor or if there is no parameterless constructor a varargs constructor
// that can be called with no parameters.
Optional<MethodDescriptor> superContructor =
superTypeDescriptor.getMethodDescriptors().stream()
.filter(MethodDescriptor::isConstructor)
.filter(m -> m.isVisibleFrom(typeDescriptor))
.filter(m -> m.getParameterDescriptors().isEmpty())
.collect(MoreCollectors.toOptional());
if (superContructor.isPresent()) {
return superContructor.get();
}
// If no 0-argument constructor find a 1-argument varargs constructor. There might be more than
// 1 varargs constructor, if so apply the more specific overload rule. At this point there
// should be no ambiguity and a more specific overload is guaranteed, This is because at this
// point type checking succeed in the frontend and if there were any ambiguity the compile would
// have produced an error already.
superContructor =
superTypeDescriptor.getMethodDescriptors().stream()
.filter(MethodDescriptor::isConstructor)
.filter(m -> m.isVisibleFrom(typeDescriptor))
.filter(m -> m.getParameterDescriptors().size() == 1)
.filter(m -> Iterables.getOnlyElement(m.getParameterDescriptors()).isVarargs())
.min(InsertExplicitSuperCalls::getParameterSpecificityComparator);
if (superContructor.isPresent()) {
return superContructor.get();
}
// No appropriate constructor found, it must be the implicit constructor.
checkState(
superTypeDescriptor.getMethodDescriptors().stream()
.noneMatch(MethodDescriptor::isConstructor));
return AstUtils.createImplicitConstructorDescriptor(superTypeDescriptor);
}
private static Method getJsConstructor(Type type) {
return type.getMethods().stream()
.filter(method -> method.getDescriptor().isJsConstructor())
.collect(MoreCollectors.onlyElement());
}
@Test
public void testRunTestOnce() throws Exception {
ExecutionOptions executionOptions = ExecutionOptions.DEFAULTS;
Path tmpDirRoot = TestStrategy.getTmpRoot(rootDirectory, outputBase, executionOptions);
BinTools binTools = BinTools.forUnitTesting(directories, analysisMock.getEmbeddedTools());
TestedStandaloneTestStrategy standaloneTestStrategy =
new TestedStandaloneTestStrategy(executionOptions, binTools, tmpDirRoot);
// setup a test action
scratch.file("standalone/simple_test.sh", "this does not get executed, it is mocked out");
scratch.file(
"standalone/BUILD",
"sh_test(",
" name = \"simple_test\",",
" size = \"small\",",
" srcs = [\"simple_test.sh\"],",
")");
TestRunnerAction testRunnerAction = getTestAction("//standalone:simple_test");
SpawnResult expectedSpawnResult =
new SpawnResult.Builder()
.setStatus(Status.SUCCESS)
.setWallTime(Duration.ofMillis(10))
.setRunnerName("test")
.build();
when(spawnStrategy.beginExecution(any(), any()))
.thenReturn(SpawnContinuation.immediate(expectedSpawnResult));
ActionExecutionContext actionExecutionContext =
new FakeActionExecutionContext(createTempOutErr(tmpDirRoot), spawnStrategy, binTools);
// actual StandaloneTestStrategy execution
List<SpawnResult> spawnResults =
execute(testRunnerAction, actionExecutionContext, standaloneTestStrategy);
assertThat(spawnResults).contains(expectedSpawnResult);
TestResult result = standaloneTestStrategy.postedResult;
assertThat(result).isNotNull();
assertThat(result.isCached()).isFalse();
assertThat(result.getTestAction()).isSameInstanceAs(testRunnerAction);
assertThat(result.getData().getTestPassed()).isTrue();
assertThat(result.getData().getRemotelyCached()).isFalse();
assertThat(result.getData().getIsRemoteStrategy()).isFalse();
assertThat(result.getData().getRunDurationMillis()).isEqualTo(10);
assertThat(result.getData().getTestTimesList()).containsExactly(10L);
TestAttempt attempt =
storedEvents
.getPosts()
.stream()
.filter(TestAttempt.class::isInstance)
.map(TestAttempt.class::cast)
.collect(MoreCollectors.onlyElement());
assertThat(attempt.getExecutionInfo().getStrategy()).isEqualTo("test");
assertThat(attempt.getExecutionInfo().getHostname()).isEqualTo("");
}
@Test
public void testRunTestRemotely() throws Exception {
ExecutionOptions executionOptions = ExecutionOptions.DEFAULTS;
Path tmpDirRoot = TestStrategy.getTmpRoot(rootDirectory, outputBase, executionOptions);
BinTools binTools = BinTools.forUnitTesting(directories, analysisMock.getEmbeddedTools());
TestedStandaloneTestStrategy standaloneTestStrategy =
new TestedStandaloneTestStrategy(executionOptions, binTools, tmpDirRoot);
// setup a test action
scratch.file("standalone/simple_test.sh", "this does not get executed, it is mocked out");
scratch.file(
"standalone/BUILD",
"sh_test(",
" name = \"simple_test\",",
" size = \"small\",",
" srcs = [\"simple_test.sh\"],",
")");
TestRunnerAction testRunnerAction = getTestAction("//standalone:simple_test");
SpawnResult expectedSpawnResult =
new SpawnResult.Builder()
.setStatus(Status.SUCCESS)
.setWallTime(Duration.ofMillis(10))
.setRunnerName("remote")
.setExecutorHostname("a-remote-host")
.build();
when(spawnStrategy.beginExecution(any(), any()))
.thenReturn(SpawnContinuation.immediate(expectedSpawnResult));
ActionExecutionContext actionExecutionContext =
new FakeActionExecutionContext(createTempOutErr(tmpDirRoot), spawnStrategy, binTools);
// actual StandaloneTestStrategy execution
List<SpawnResult> spawnResults =
execute(testRunnerAction, actionExecutionContext, standaloneTestStrategy);
assertThat(spawnResults).contains(expectedSpawnResult);
TestResult result = standaloneTestStrategy.postedResult;
assertThat(result).isNotNull();
assertThat(result.isCached()).isFalse();
assertThat(result.getTestAction()).isSameInstanceAs(testRunnerAction);
assertThat(result.getData().getTestPassed()).isTrue();
assertThat(result.getData().getRemotelyCached()).isFalse();
assertThat(result.getData().getIsRemoteStrategy()).isTrue();
assertThat(result.getData().getRunDurationMillis()).isEqualTo(10);
assertThat(result.getData().getTestTimesList()).containsExactly(10L);
TestAttempt attempt =
storedEvents
.getPosts()
.stream()
.filter(TestAttempt.class::isInstance)
.map(TestAttempt.class::cast)
.collect(MoreCollectors.onlyElement());
assertThat(attempt.getStatus()).isEqualTo(TestStatus.PASSED);
assertThat(attempt.getExecutionInfo().getStrategy()).isEqualTo("remote");
assertThat(attempt.getExecutionInfo().getHostname()).isEqualTo("a-remote-host");
}
@Test
public void testRunRemotelyCachedTest() throws Exception {
ExecutionOptions executionOptions = ExecutionOptions.DEFAULTS;
Path tmpDirRoot = TestStrategy.getTmpRoot(rootDirectory, outputBase, executionOptions);
BinTools binTools = BinTools.forUnitTesting(directories, analysisMock.getEmbeddedTools());
TestedStandaloneTestStrategy standaloneTestStrategy =
new TestedStandaloneTestStrategy(executionOptions, binTools, tmpDirRoot);
// setup a test action
scratch.file("standalone/simple_test.sh", "this does not get executed, it is mocked out");
scratch.file(
"standalone/BUILD",
"sh_test(",
" name = \"simple_test\",",
" size = \"small\",",
" srcs = [\"simple_test.sh\"],",
")");
TestRunnerAction testRunnerAction = getTestAction("//standalone:simple_test");
SpawnResult expectedSpawnResult =
new SpawnResult.Builder()
.setStatus(Status.SUCCESS)
.setCacheHit(true)
.setWallTime(Duration.ofMillis(10))
.setRunnerName("remote cache")
.build();
when(spawnStrategy.beginExecution(any(), any()))
.thenReturn(SpawnContinuation.immediate(expectedSpawnResult));
ActionExecutionContext actionExecutionContext =
new FakeActionExecutionContext(createTempOutErr(tmpDirRoot), spawnStrategy, binTools);
// actual StandaloneTestStrategy execution
List<SpawnResult> spawnResults =
execute(testRunnerAction, actionExecutionContext, standaloneTestStrategy);
// check that the rigged SpawnResult was returned
assertThat(spawnResults).contains(expectedSpawnResult);
TestResult result = standaloneTestStrategy.postedResult;
assertThat(result).isNotNull();
assertThat(result.isCached()).isFalse();
assertThat(result.getTestAction()).isSameInstanceAs(testRunnerAction);
assertThat(result.getData().getTestPassed()).isTrue();
assertThat(result.getData().getRemotelyCached()).isTrue();
assertThat(result.getData().getIsRemoteStrategy()).isFalse();
assertThat(result.getData().getRunDurationMillis()).isEqualTo(10);
assertThat(result.getData().getTestTimesList()).containsExactly(10L);
TestAttempt attempt =
storedEvents
.getPosts()
.stream()
.filter(TestAttempt.class::isInstance)
.map(TestAttempt.class::cast)
.collect(MoreCollectors.onlyElement());
assertThat(attempt.getExecutionInfo().getStrategy()).isEqualTo("remote cache");
assertThat(attempt.getExecutionInfo().getHostname()).isEqualTo("");
}
@Test
public void correctToolFilesUsed() throws Exception {
scratch.file(
"a/BUILD",
"cc_toolchain_alias(name = 'a')",
"cc_library(name = 'l', srcs = ['l.c'])",
"cc_library(name = 'asm', srcs = ['a.s'])",
"cc_library(name = 'preprocessed-asm', srcs = ['a.S'])");
getAnalysisMock()
.ccSupport()
.setupCcToolchainConfig(
mockToolsConfig,
CcToolchainConfig.builder().withFeatures(CppRuleClasses.SUPPORTS_DYNAMIC_LINKER));
useConfiguration("--incompatible_use_specific_tool_files");
ConfiguredTarget target = getConfiguredTarget("//a:a");
CcToolchainProvider toolchainProvider =
(CcToolchainProvider) target.get(ToolchainInfo.PROVIDER);
// Check that the mock toolchain tool file sets are an antichain, so that our subset assertions
// below are meaningful.
ImmutableList<Set<Artifact>> fileGroups =
ImmutableList.of(
toolchainProvider.getArFiles().toSet(),
toolchainProvider.getLinkerFiles().toSet(),
toolchainProvider.getCompilerFiles().toSet(),
toolchainProvider.getAsFiles().toSet(),
toolchainProvider.getAllFiles().toSet());
for (int i = 0; i < fileGroups.size(); i++) {
assertThat(fileGroups.get(i)).isNotEmpty();
for (int j = 0; j < fileGroups.size(); j++) {
if (i == j) {
continue;
}
Set<Artifact> one = fileGroups.get(i);
Set<Artifact> two = fileGroups.get(j);
assertWithMessage(String.format("%s should not contain %s", one, two))
.that(one.containsAll(two))
.isFalse();
}
}
assertThat(
Sets.difference(
toolchainProvider.getArFiles().toSet(), toolchainProvider.getLinkerFiles().toSet()))
.isNotEmpty();
assertThat(
Sets.difference(
toolchainProvider.getLinkerFiles().toSet(), toolchainProvider.getArFiles().toSet()))
.isNotEmpty();
RuleConfiguredTarget libTarget = (RuleConfiguredTarget) getConfiguredTarget("//a:l");
Artifact staticLib =
getOutputGroup(libTarget, "archive").toList().stream()
.collect(MoreCollectors.onlyElement());
ActionAnalysisMetadata staticAction = getGeneratingAction(staticLib);
assertThat(staticAction.getInputs().toList())
.containsAtLeastElementsIn(toolchainProvider.getArFiles().toList());
Artifact dynamicLib =
getOutputGroup(libTarget, "dynamic_library").toList().stream()
.collect(MoreCollectors.onlyElement());
ActionAnalysisMetadata dynamicAction = getGeneratingAction(dynamicLib);
assertThat(dynamicAction.getInputs().toList())
.containsAtLeastElementsIn(toolchainProvider.getLinkerFiles().toList());
ActionAnalysisMetadata cCompileAction =
libTarget.getActions().stream()
.filter((a) -> a.getMnemonic().equals("CppCompile"))
.collect(MoreCollectors.onlyElement());
assertThat(cCompileAction.getInputs().toList())
.containsAtLeastElementsIn(toolchainProvider.getCompilerFiles().toList());
ActionAnalysisMetadata asmAction =
((RuleConfiguredTarget) getConfiguredTarget("//a:asm"))
.getActions().stream()
.filter((a) -> a.getMnemonic().equals("CppCompile"))
.collect(MoreCollectors.onlyElement());
assertThat(asmAction.getInputs().toList())
.containsAtLeastElementsIn(toolchainProvider.getAsFiles().toList());
ActionAnalysisMetadata preprocessedAsmAction =
((RuleConfiguredTarget) getConfiguredTarget("//a:preprocessed-asm"))
.getActions().stream()
.filter((a) -> a.getMnemonic().equals("CppCompile"))
.collect(MoreCollectors.onlyElement());
assertThat(preprocessedAsmAction.getInputs().toList())
.containsAtLeastElementsIn(toolchainProvider.getCompilerFiles().toList());
}
/**
* Returns the option with the given name from the given class.
*
* <p>The preferred way of using this method is as the initializer for a static final field in the
* options class which defines the option. This reduces the possibility that another contributor
* might change the name of the option without realizing it's used by name elsewhere.
*
* @throws IllegalArgumentException if there are two or more options with that name.
* @throws java.util.NoSuchElementException if there are no options with that name.
*/
public static OptionDefinition getOptionDefinitionByName(
Class<? extends OptionsBase> optionsClass, String optionName) {
return getOptionDefinitions(optionsClass).stream()
.filter(definition -> definition.getOptionName().equals(optionName))
.collect(MoreCollectors.onlyElement());
}