下面列出了com.google.common.collect.MoreCollectors#com.google.common.collect.Sets 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public Matcher<E> build() {
final Set<String> predicateSymbolsNotInGraph =
Sets.newTreeSet(symbolPredicates.keySet());
predicateSymbolsNotInGraph.removeAll(automaton.symbolNames);
if (!predicateSymbolsNotInGraph.isEmpty()) {
throw new IllegalArgumentException("not all predicate symbols ["
+ predicateSymbolsNotInGraph + "] are in graph ["
+ automaton.symbolNames + "]");
}
final ImmutableMap.Builder<String, Predicate<MemoryFactory.Memory<E>>> builder =
ImmutableMap.builder();
for (String symbolName : automaton.symbolNames) {
// If a symbol does not have a predicate, it defaults to true.
// By convention, "STRT" is used for the start symbol, but it could be
// anything.
builder.put(symbolName,
symbolPredicates.getOrDefault(symbolName, e -> true));
}
return new Matcher<>(automaton, builder.build());
}
/**
* Finds any issues associated with the changeset
* e.g. a commit message could be "TICKET-123 fix all the things" and be associated with TICKET-123 in JIRA
* @param changeSetEntry entry
* @return issues representing the change
*/
public static Collection<BlueIssue> resolve(ChangeLogSet.Entry changeSetEntry) {
LinkedHashSet<BlueIssue> allIssues = Sets.newLinkedHashSet();
for (BlueIssueFactory factory : ExtensionList.lookup(BlueIssueFactory.class)) {
try {
Collection<BlueIssue> issues = factory.getIssues(changeSetEntry);
if (issues == null) {
continue;
}
allIssues.addAll(issues);
} catch (Exception e) {
LOGGER.log(Level.WARNING,"Unable to fetch issues for changeSetEntry " + e.getMessage(), e);
}
}
return allIssues;
}
private AnswerKey makeAnswerKeyFromCorrectAndIncorrect(final ImmutableSet<Response> correct,
final ImmutableSet<Response> incorrect, final CorefAnnotation coref) {
final ImmutableSet.Builder<AssessedResponse> correctAssessedResponses = ImmutableSet.builder();
for (final Response correctResponse : correct) {
correctAssessedResponses.add(
AssessedResponse.assessCorrectly(correctResponse, FillerMentionType.NAME));
}
final ImmutableSet.Builder<AssessedResponse> incorrectAssessedResponses =
ImmutableSet.builder();
for (final Response incorrectResponse : incorrect) {
incorrectAssessedResponses
.add(AssessedResponse.assessWithIncorrectEventType(incorrectResponse));
}
return AnswerKey.from(DOC, Sets.union(correctAssessedResponses.build(),
incorrectAssessedResponses.build()), ImmutableSet.<Response>of(), coref);
}
public static String compare(Object[] a, Object[] b, int flags, Map<String, Integer> handle)
{
boolean ordered = (flags & UNORDERED) == 0;
if (a.length != b.length)
{
return ".length:" + a.length + "!=" + b.length;
}
if (!ordered)
{
Set<Object> setA = Sets.newHashSet(a);
Set<Object> setB = Sets.newHashSet(b);
return compare(setA, setB, flags, handle);
}
for (int i = 0; i < a.length; i++)
{
String cmp = compare(a[i], b[i], flags, handle);
if (cmp != null)
return "[" + i + "]" + cmp;
}
return null;
}
@Test
public void testBuildSubToParentEdOrgCache() {
EntityToEdOrgCache cache = new EntityToEdOrgCache();
cache.addEntry("lea-1", "school-1");
cache.addEntry("lea-1", "school-2");
cache.addEntry("lea-1", "school-3");
cache.addEntry("lea-2", "school-4");
cache.addEntry("lea-2", "school-5");
cache.addEntry("lea-3", "school-6");
Map<String, Collection<String>> result = helper.buildSubToParentEdOrgCache(cache);
Assert.assertEquals(6, result.keySet().size());
Assert.assertEquals(Sets.newHashSet("lea-1"), result.get("school-1"));
Assert.assertEquals(Sets.newHashSet("lea-1"), result.get("school-2"));
Assert.assertEquals(Sets.newHashSet("lea-1"), result.get("school-3"));
Assert.assertEquals(Sets.newHashSet("lea-2"), result.get("school-4"));
Assert.assertEquals(Sets.newHashSet("lea-2"), result.get("school-5"));
Assert.assertEquals(Sets.newHashSet("lea-3"), result.get("school-6"));
}
@Test(expected = NotAvailableException.class)
public void should_create_unix_local_host() {
// when: create host
AgentHost host = new LocalUnixAgentHost();
host.setName("test-host");
host.setTags(Sets.newHashSet("local", "test"));
agentHostService.createOrUpdate(host);
// then:
Assert.assertNotNull(host.getId());
Assert.assertEquals(AgentHost.Type.LocalUnixSocket, host.getType());
Assert.assertEquals(1, agentHostService.list().size());
Assert.assertEquals(host, agentHostService.list().get(0));
// when: create other
AgentHost another = new LocalUnixAgentHost();
another.setName("test-host-failure");
another.setTags(Sets.newHashSet("local", "test"));
agentHostService.createOrUpdate(another);
}
/**
* {@inheritDoc}
*/
@Override
public void setApplicationsForCommand(
@NotBlank final String id,
@NotNull final List<@NotBlank String> applicationIds
) throws NotFoundException, PreconditionFailedException {
log.debug("[setApplicationsForCommand] Called to set {} for {}", applicationIds, id);
if (Sets.newHashSet(applicationIds).size() != applicationIds.size()) {
throw new PreconditionFailedException("Duplicate application id in " + applicationIds);
}
final CommandEntity commandEntity = this.commandRepository
.getCommandAndApplications(id)
.orElseThrow(() -> new NotFoundException("No command with id " + id + " exists"));
final List<ApplicationEntity> applicationEntities = Lists.newArrayList();
for (final String applicationId : applicationIds) {
applicationEntities.add(
this.applicationRepository
.getApplicationAndCommands(applicationId)
.orElseThrow(() -> new NotFoundException("No application with id " + applicationId + " exists"))
);
}
commandEntity.setApplications(applicationEntities);
}
public Matcher<E> build() {
final Set<String> predicateSymbolsNotInGraph =
Sets.newTreeSet(symbolPredicates.keySet());
predicateSymbolsNotInGraph.removeAll(automaton.symbolNames);
if (!predicateSymbolsNotInGraph.isEmpty()) {
throw new IllegalArgumentException("not all predicate symbols ["
+ predicateSymbolsNotInGraph + "] are in graph ["
+ automaton.symbolNames + "]");
}
final ImmutableMap.Builder<String, Predicate<MemoryFactory.Memory<E>>> builder =
ImmutableMap.builder();
for (String symbolName : automaton.symbolNames) {
// If a symbol does not have a predicate, it defaults to true.
// By convention, "STRT" is used for the start symbol, but it could be
// anything.
builder.put(symbolName,
symbolPredicates.getOrDefault(symbolName, e -> true));
}
return new Matcher<>(automaton, builder.build());
}
/**
* Starts the job setup and launch process once the thread is activated.
*/
@Override
public void run() {
final long start = System.nanoTime();
final Set<Tag> tags = Sets.newHashSet();
try {
this.jobSubmitterService.submitJob(
this.jobRequest,
this.cluster,
this.command,
this.applications,
this.memory
);
MetricsUtils.addSuccessTags(tags);
} catch (final GenieException e) {
log.error("Unable to submit job due to exception: {}", e.getMessage(), e);
MetricsUtils.addFailureTagsWithException(tags, e);
} catch (final Throwable t) {
MetricsUtils.addFailureTagsWithException(tags, t);
throw t;
} finally {
this.registry.timer(JOB_SUBMIT_TIMER_NAME, tags).record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
}
@Action(semantics = SemanticsOf.SAFE, restrictTo = RestrictTo.PROTOTYPING)
public List<BadTarget> findBadCommandTargets() {
Set<String> badObjectTypes = Sets.newTreeSet();
List<Map<String, Object>> rows = isisJdoSupport
.executeSql("select distinct(substring(target, 1, charindex(':', target)-1)) as objectType from isiscommand.Command order by 1");
for (Map<String, Object> row : rows) {
String targetStr = (String) row.get("objectType");
addIfBad(badObjectTypes, targetStr);
}
return Lists.newArrayList(
FluentIterable.from(badObjectTypes)
.transform(x -> new BadTarget(x))
.toList());
}
@Override
public ControllerServiceEntity updateControllerService(final Revision revision, final ControllerServiceDTO controllerServiceDTO) {
// get the component, ensure we have access to it, and perform the update request
final ControllerServiceNode controllerService = controllerServiceDAO.getControllerService(controllerServiceDTO.getId());
final RevisionUpdate<ControllerServiceDTO> snapshot = updateComponent(revision,
controllerService,
() -> controllerServiceDAO.updateControllerService(controllerServiceDTO),
cs -> {
final ControllerServiceDTO dto = dtoFactory.createControllerServiceDto(cs);
final ControllerServiceReference ref = controllerService.getReferences();
final ControllerServiceReferencingComponentsEntity referencingComponentsEntity =
createControllerServiceReferencingComponentsEntity(ref, Sets.newHashSet(controllerService.getIdentifier()));
dto.setReferencingComponents(referencingComponentsEntity.getControllerServiceReferencingComponents());
return dto;
});
final PermissionsDTO permissions = dtoFactory.createPermissionsDto(controllerService);
final List<BulletinDTO> bulletins = dtoFactory.createBulletinDtos(bulletinRepository.findBulletinsForSource(controllerServiceDTO.getId()));
final List<BulletinEntity> bulletinEntities = bulletins.stream().map(bulletin -> entityFactory.createBulletinEntity(bulletin, permissions.getCanRead())).collect(Collectors.toList());
return entityFactory.createControllerServiceEntity(snapshot.getComponent(), dtoFactory.createRevisionDTO(snapshot.getLastModification()), permissions, bulletinEntities);
}
@Test
public final void testGenerateCuboids() {
Column [] columns = new Column[3];
columns[0] = new Column("col1", Type.INT4);
columns[1] = new Column("col2", Type.INT8);
columns[2] = new Column("col3", Type.FLOAT4);
List<Column[]> cube = LogicalPlanner.generateCuboids(columns);
assertEquals(((int)Math.pow(2, numCubeColumns)), cube.size());
Set<Set<Column>> cuboids = Sets.newHashSet();
for (Column [] cols : cube) {
cuboids.add(Sets.newHashSet(cols));
}
for (Set<Column> result : testGenerateCuboidsResult) {
assertTrue(cuboids.contains(result));
}
}
@Override
public EntitySet merge(Collection<? extends Entity> entities) {
checkNotNullArgument(entities, "entity collection is null");
List<Entity> managedList = new ArrayList<>(entities.size());
disableListeners = true;
try {
Set<Entity> merged = Sets.newIdentityHashSet();
for (Entity entity : entities) {
Entity managed = internalMerge(entity, merged, true);
managedList.add(managed);
}
} finally {
disableListeners = false;
}
return EntitySet.of(managedList);
}
@Override
public void onMatch(@Nonnull PlannerRuleCall call) {
final LogicalTypeFilterExpression typeFilter = call.get(root);
final RecordQueryPlan child = call.get(childMatcher);
Set<String> childRecordTypes = RecordTypesProperty.evaluate(call.getContext(), child);
Set<String> filterRecordTypes = Sets.newHashSet(typeFilter.getRecordTypes());
if (filterRecordTypes.containsAll(childRecordTypes)) {
// type filter is completely redundant, so remove it entirely
call.yield(call.ref(child));
} else {
// otherwise, keep a filter on record types which the child might produce and are included in the filter
Set<String> unsatisfiedTypeFilters = Sets.intersection(filterRecordTypes, childRecordTypes);
call.yield(GroupExpressionRef.of(new RecordQueryTypeFilterPlan(child, unsatisfiedTypeFilters)));
}
}
/**
* 测试请求 and tag 与消息 tag 不一致的情况
*/
@Test
public void testAndTagNotMatches() throws Exception {
String tag1 = "tag1";
String tag2 = "tag2";
String tag3 = "tag3";
PullRequest request = TestToolBox.createDefaultPullRequest();
request.setFilters(Lists.newArrayList(new TagPullFilter(TagType.AND, Sets.newHashSet(tag1, tag2, tag3))));
BaseMessage message = TestToolBox.createDefaultMessage();
message.addTag(tag1);
message.addTag(tag2);
Buffer buffer = TestToolBox.messageToBuffer(message);
TagPullMessageFilter filter = Mockito.spy(TagPullMessageFilter.class);
boolean match = filter.match(request, buffer);
assertFalse(match);
}
private void visitFunction(NodeTraversal t, Node n) {
FunctionType funType = n.getJSType().toMaybeFunctionType();
if (funType != null && !funType.isConstructor()) {
return;
}
Node nodeToInsertAfter = findNodeToInsertAfter(n);
nodeToInsertAfter = addMarker(funType, nodeToInsertAfter, null);
TreeSet<ObjectType> stuff = Sets.newTreeSet(ALPHA);
Iterables.addAll(stuff, funType.getAllImplementedInterfaces());
for (ObjectType interfaceType : stuff) {
nodeToInsertAfter =
addMarker(funType, nodeToInsertAfter, interfaceType);
}
}
public AllowAllToken(String host,
boolean rememberMe,
String userName,
Iterable<String> groups,
String defaultSchema,
Duration queryTimeout,
String accessLevel)
{
this.host = host;
this.rememberMe = rememberMe;
this.userName = userName;
this.groups = Sets.newHashSet(groups);
this.defaultSchema = defaultSchema;
this.queryTimeout = queryTimeout;
this.accessLevel = accessLevel;
}
private void updateNamespace(
AllPropertiesMessageSource source, String namespace, Set<String> messageIds) {
Map<String, L10nString> toUpdate =
localizationService
.getExistingMessages(namespace, messageIds)
.collect(toMap(L10nString::getMessageID, identity()));
Map<String, L10nString> toAdd =
Sets.difference(messageIds, toUpdate.keySet()).stream()
.map(msgId -> createL10nString(namespace, msgId))
.collect(toMap(L10nString::getMessageID, identity()));
Map<String, L10nString> all =
Maps.asMap(messageIds, messageID -> toUpdate.getOrDefault(messageID, toAdd.get(messageID)));
all.forEach(
(messageID, l10nString) -> updateFromSource(source, namespace, messageID, l10nString));
localizationService.store(toUpdate.values(), toAdd.values());
}
@Test
public void should_update_agent_resource() throws Throwable {
Agent agent = createAgent("hello.agent", Sets.newHashSet("test"), StatusCode.OK);
Agent.Resource resource = new Agent.Resource()
.setCpu(1)
.setFreeDisk(2)
.setTotalDisk(5)
.setFreeMemory(4)
.setTotalMemory(20);
ResponseMessage message = mockMvcHelper.expectSuccessAndReturnClass(post("/agents/resource")
.header(AgentAuth.HeaderAgentToken, agent.getToken())
.content(objectMapper.writeValueAsBytes(resource))
.contentType(MediaType.APPLICATION_JSON), ResponseMessage.class);
Assert.assertEquals(StatusCode.OK, message.getCode());
}
@Override
public boolean isValid(Collection<?> list, ConstraintValidatorContext context) {
if (list != null) {
Set<Object> seenSoFar = Sets.newHashSet();
for (Object obj : list) {
Object value = propertyValue(obj, uniqueField.value());
if ((value == null) && this.skipNulls) {
continue;
}
if (seenSoFar.contains(value)) {
addViolation(context, uniqueField.value());
return false;
}
seenSoFar.add(value);
}
}
return true;
}
@SuppressWarnings("deprecation")
protected List<String> getClassPath() {
Set<String> classPath = Sets.newLinkedHashSet();
classPath.add(project.getBuild().getSourceDirectory());
try {
classPath.addAll(project.getCompileClasspathElements());
} catch (DependencyResolutionRequiredException e) {
throw new WrappedException(e);
}
addDependencies(classPath, project.getCompileArtifacts());
classPath.remove(project.getBuild().getOutputDirectory());
return newArrayList(filter(classPath, FILE_EXISTS));
}
/**
* Returns true if two arrays of SPDX elements contain equivalent elements
* @param elementsA
* @param elementsB
* @return
*/
public static boolean elementsEquivalent(RdfModelObject[] elementsA,
RdfModelObject[] elementsB) {
if (elementsA == null) {
return elementsB == null;
}
if (elementsB == null) {
return false;
}
if (elementsA.length != elementsB.length) {
return false;
}
Set<Integer> matchedIndexes = Sets.newHashSet();
for (int i = 0; i < elementsA.length; i++) {
boolean found = false;
for (int j = 0; j < elementsB.length; j++) {
if (!matchedIndexes.contains(j) &&
elementsA[i].equivalent(elementsB[j])) {
found = true;
matchedIndexes.add(j);
break;
}
}
if (!found) {
return false;
}
}
return true;
}
/**
* Loads the table data from the path and writes it to the output stream. Returns the set of UUIDs associated with
* the table, just like {@link #loadAndSerialize(long, java.io.OutputStream)}.
*/
private Set<Long> loadFromNode(String path, OutputStream out)
throws KeeperException.NoNodeException {
try {
// Get the cached representation of this table
byte[] data = _curator.getData().forPath(path);
DataInputStream in = new DataInputStream(new ByteArrayInputStream(data));
int uuidCountOrExceptionCode = in.readInt();
// A negative first integer indicates an exception condition.
if (uuidCountOrExceptionCode < 0) {
String exceptionJson = new String(data, 4, data.length - 4, Charsets.UTF_8);
switch (uuidCountOrExceptionCode) {
case UNKNOWN_TABLE:
throw JsonHelper.fromJson(exceptionJson, UnknownTableException.class);
case DROPPED_TABLE:
throw JsonHelper.fromJson(exceptionJson, DroppedTableException.class);
}
}
// Load the UUIDs for this table
Set<Long> uuids = Sets.newHashSet();
for (int i=0; i < uuidCountOrExceptionCode; i++) {
uuids.add(in.readLong());
}
// Copy the remaining bytes as the content
ByteStreams.copy(in, out);
return uuids;
} catch (Throwable t) {
Throwables.propagateIfInstanceOf(t, KeeperException.NoNodeException.class);
throw Throwables.propagate(t);
}
}
@Test
public void testHasNoStreamingStep() {
Set<Step> steps = Sets.newHashSet();
BatchStep step1 = new BatchStep("step1");
BatchStep step2 = new BatchStep("step2");
step1.configure(ConfigFactory.empty());
step2.configure(ConfigFactory.empty());
steps.add(step1);
steps.add(step2);
assertFalse(StepUtils.hasStreamingStep(steps));
}
public static Predicate<BuildTarget> containsFlavors(FlavorDomain<?> domain) {
return input -> {
ImmutableSet<Flavor> flavorSet =
Sets.intersection(domain.getFlavors(), input.getFlavors().getSet()).immutableCopy();
return !flavorSet.isEmpty();
};
}
public MetricDefinitionFixture() {
serviceMetricNames = Sets.newHashSet();
serviceMetrics = Lists.newArrayList();
rolesMetricsNames = Maps.newHashMap();
rolesMetrics = Maps.newHashMap();
entitiesMetricsNames = Maps.newHashMap();
additionalServiceEntityTypesMetrics = Maps.newHashMap();
}
@Test
public void testNoContext() throws Exception {
// ok
service.noContext(new Model(null, null, "sample"));
Assert.assertTrue(service.lastCallGroups.length == 0);
try {
// default group
service.noContext(new Model(null, null, null));
} catch (ConstraintViolationException ex) {
Set<String> props = PropFunction.convert(ex.getConstraintViolations());
Assert.assertEquals(1, props.size());
Assert.assertEquals(Sets.newHashSet("def"), props);
}
}
private Set<Integer> getLeadPartitions(PartitionedLeaderService partitionedLeaderService) {
Set<Integer> leadPartitions = Sets.newLinkedHashSet();
for (Integer partition : partitionedLeaderService.getLeadingPartitions()) {
// Don't just take the service's word for it; double check that the service is actually in the execution body
Service uncastDelegate = partitionedLeaderService.getPartitionLeaderServices().get(partition).getCurrentDelegateService().orNull();
TestLeaderService delegate = uncastDelegate != null && uncastDelegate instanceof TestLeaderService ?
(TestLeaderService) uncastDelegate : null;
if (delegate != null && delegate.inBody) {
leadPartitions.add(delegate.partition);
}
}
return leadPartitions;
}
@Test
public void listArticleVoters() throws Exception {
assertEquals(0, service.listArticleVoters(voter, Collections.emptyList()).size());
service.voteArticle(UP, articleId, voter, EMPTY, 100);
Article a2 = savedArticle(zoneInfo, savedAccountCitizen("author2"), "title vote");
service.voteArticle(UP, a2.getArticleId(), voter, EMPTY, 200);
Set<FlakeId> actual = service.listArticleVoters(voter, asList(articleId, a2.getArticleId()))
.stream()
.map(ArticleVoter::getArticleId)
.collect(Collectors.toSet());
assertEquals(Sets.newHashSet(articleId, a2.getArticleId()), actual);
}
@Test(timeOut = 30_000)
public void testTransactionStartedBeforeNonOverlapFenceCommits() throws Exception {
long startTsTx1 = tsoClient.getNewStartTimestamp().get();
tsoClient.getFence(7).get();
try {
tsoClient.commit(startTsTx1, Sets.newHashSet(c1, c2)).get();
} catch (ExecutionException ee) {
Assert.fail("TX should successfully commit"); }
}