下面列出了com.google.common.collect.Sets#newHashSet ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public Set<String> variableFeatures(final Set<ASTNode> boundNodesOfVariable) {
// Find the declaration and extract features
final Set<String> features = Sets.newHashSet();
for (final ASTNode node : boundNodesOfVariable) {
if (!(node.getParent() instanceof VariableDeclaration)) {
continue;
}
getDeclarationFeatures(features, node);
if (activeFeatures
.contains(AvailableFeatures.IMPLEMENTOR_VOCABULARY)) {
JavaFeatureExtractor.addImplementorVocab(node, features);
}
break;
}
return features;
}
/**
* If a Server receives a SUBSCRIBE packet that contains multiple Topic Filters it MUST handle that packet as if it
* had received a sequence of multiple SUBSCRIBE packets.
* <p>
* This means we can delete subscribes to a topic, that are in sequence before another subscribe to the same topic.
*
* @param msg a SUBSCRIBE message
* @return the cleaned subscriptions
*/
@NotNull
private Set<Topic> getCleanedSubscriptions(final SUBSCRIBE msg) {
final List<Topic> topics = msg.getTopics();
final int size = topics.size();
if (size < 2) {
return Sets.newHashSet(topics);
}
final HashSet<Topic> cleanedTopics = Sets.newHashSetWithExpectedSize(size);
// we expect the topics to be mostly different
for (final Topic topic : topics) {
if (!cleanedTopics.add(topic)) {
cleanedTopics.remove(topic);
cleanedTopics.add(topic);
}
}
return cleanedTopics;
}
@Override
public AnswerKey apply(AnswerKey input) {
final Set<Response> existingResponses = Sets.newHashSet(input.allResponses());
final ImmutableSet.Builder<AssessedResponse> newAssessedResponses = ImmutableSet.builder();
newAssessedResponses.addAll(input.annotatedResponses());
for (final AssessedResponse assessedResponse : input.annotatedResponses()) {
if (assessedResponse.assessment().realis().isPresent()) {
final Response responseWithAssessedRealis = assessedResponse.response()
.withRealis(assessedResponse.assessment().realis().get());
if (!existingResponses.contains(responseWithAssessedRealis)) {
newAssessedResponses.add(AssessedResponse.of(
responseWithAssessedRealis, assessedResponse.assessment()));
existingResponses.add(responseWithAssessedRealis);
}
}
}
return AnswerKey.from(input.docId(), newAssessedResponses.build(), input.unannotatedResponses(),
input.corefAnnotation());
}
@Test
public void testProjectWithMissingFilterColumn() {
Iterable<Record> results = IcebergGenerics.read(sharedTable)
.where(Expressions.greaterThanOrEqual("id", 1))
.where(Expressions.lessThan("id", 21))
.select("data").build();
Set<String> expected = Sets.newHashSet();
for (Record record : concat(file1Records, file2Records, file3Records)) {
Long id = (Long) record.getField("id");
if (id >= 1 && id < 21) {
expected.add(record.getField("data").toString());
}
}
results.forEach(record ->
Assert.assertEquals("Record should have two projected fields", 2, record.size()));
Assert.assertEquals("Should project correct rows",
expected,
Sets.newHashSet(transform(results, record -> record.getField("data").toString())));
}
@Test
public void testGetAllProgramsInAttributesAndDataElements()
{
ProgramTrackedEntityAttributeDimensionItem ptaA = new ProgramTrackedEntityAttributeDimensionItem( prA, atA );
ProgramDataElementDimensionItem pdeA = new ProgramDataElementDimensionItem( prB, deA );
DataQueryParams params = DataQueryParams.newBuilder()
.withProgramAttributes( Lists.newArrayList( ptaA ) )
.withProgramDataElements( Lists.newArrayList( pdeA ) )
.withPeriods( Lists.newArrayList( peA, peB ) )
.withOrganisationUnits( Lists.newArrayList( ouA, ouB ) )
.build();
Set<Program> expected = Sets.newHashSet( prA, prB );
assertEquals( expected, params.getProgramsInAttributesAndDataElements() );
}
@Test
public void testAddDeleteGroups() throws Exception {
String roleName = "test-groups";
String grantor = "g1";
long seqId = sentryStore.createSentryRole(roleName).getSequenceId();
Set<TSentryGroup> groups = Sets.newHashSet();
TSentryGroup group = new TSentryGroup();
group.setGroupName("test-groups-g1");
groups.add(group);
group = new TSentryGroup();
group.setGroupName("test-groups-g2");
groups.add(group);
assertEquals(seqId + 1, sentryStore.alterSentryRoleAddGroups(grantor,
roleName, groups).getSequenceId());
assertEquals(seqId + 2, sentryStore.alterSentryRoleDeleteGroups(roleName, groups)
.getSequenceId());
MSentryRole role = sentryStore.getMSentryRoleByName(roleName);
assertEquals(Collections.emptySet(), role.getGroups());
}
private ImmutableSet<TargetIdeInfo> targetsForSourceFilesImpl(
ImmutableMultimap<TargetKey, TargetKey> rdepsMap, Collection<File> sourceFiles) {
ImmutableSet.Builder<TargetIdeInfo> result = ImmutableSet.builder();
Set<TargetKey> roots =
sourceFiles.stream()
.flatMap(f -> rootsMap.get(f).stream())
.collect(ImmutableSet.toImmutableSet());
Queue<TargetKey> todo = Queues.newArrayDeque();
todo.addAll(roots);
Set<TargetKey> seen = Sets.newHashSet();
while (!todo.isEmpty()) {
TargetKey targetKey = todo.remove();
if (!seen.add(targetKey)) {
continue;
}
TargetIdeInfo target = targetMap.get(targetKey);
if (filter.test(target)) {
result.add(target);
}
todo.addAll(rdepsMap.get(targetKey));
}
return result.build();
}
/**
* Creates or replaces a piece of content in the data store. Overwrites the old
* version of the content, if it exists. Expects a literal JSON representation
* of the object.
*/
@PUT
@Path ("{table}/{key}")
@Consumes (MediaType.APPLICATION_JSON)
@RequiresPermissions ("sor|update|{table}")
@Timed (name = "bv.emodb.sor.DataStoreResource1.replace", absolute = true)
@ApiOperation (value = "Creates or replaces a piece of content in the data store.",
notes = "Creates or replaces a piece of content in the data store. Overwrites the old\n" +
" version of the content, if it exists. Expects a literal JSON representation\n" +
" of the object.",
response = SuccessResponse.class
)
public SuccessResponse replace(@PathParam ("table") String table,
@PathParam ("key") String key,
@QueryParam ("changeId") TimeUUIDParam changeIdParam,
Map<String, Object> json,
@QueryParam ("audit") AuditParam auditParam,
@QueryParam ("consistency") @DefaultValue ("STRONG") WriteConsistencyParam consistency,
@QueryParam ("tag") List<String> tags,
@QueryParam ("debug") BooleanParam debug,
@Authenticated Subject subject) {
Set<String> tagsSet = (tags == null) ? ImmutableSet.<String>of() : Sets.newHashSet(tags);
return doUpdate(table, key, changeIdParam, Deltas.literal(json), auditParam, consistency, debug, false, subject, tagsSet);
}
/**
* Tests a simple topology where two egress points share some path segments
* and some path segments are not shared.
*/
@Test
public void testTwoEgressCompilation() {
FilteredConnectPoint ingress =
new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1));
FilteredConnectPoint egressOne =
new FilteredConnectPoint(new ConnectPoint(DID_4, PORT_2));
FilteredConnectPoint egressTwo =
new FilteredConnectPoint(new ConnectPoint(DID_5, PORT_2));
Set<FilteredConnectPoint> egress = Sets.newHashSet(egressOne, egressTwo);
SinglePointToMultiPointIntent intent = makeIntent(ingress, egress);
assertThat(intent, is(notNullValue()));
final String[] hops = {S2, S3};
SinglePointToMultiPointIntentCompiler compiler = makeCompiler(hops);
assertThat(compiler, is(notNullValue()));
List<Intent> result = compiler.compile(intent, null);
assertThat(result, is(notNullValue()));
assertThat(result, hasSize(1));
Intent resultIntent = result.get(0);
assertThat(resultIntent instanceof LinkCollectionIntent, is(true));
if (resultIntent instanceof LinkCollectionIntent) {
LinkCollectionIntent linkIntent = (LinkCollectionIntent) resultIntent;
assertThat(linkIntent.links(), hasSize(4));
assertThat(linkIntent.links(), linksHasPath(S1, S2));
assertThat(linkIntent.links(), linksHasPath(S2, S3));
assertThat(linkIntent.links(), linksHasPath(S3, S4));
assertThat(linkIntent.links(), linksHasPath(S3, S5));
}
assertThat("key is inherited", resultIntent.key(), is(intent.key()));
}
/**
* Sets up BGP speakers.
*
* @return configured BGP speakers as a map from speaker name to speaker
*/
private Set<BgpConfig.BgpSpeakerConfig> setUpBgpSpeakers() {
BgpConfig.BgpSpeakerConfig speaker1 = new BgpConfig.BgpSpeakerConfig(
Optional.empty(),
NO_VLAN, s1Eth100,
Collections.singleton(IpAddress.valueOf("192.168.10.1")));
BgpConfig.BgpSpeakerConfig speaker2 = new BgpConfig.BgpSpeakerConfig(
Optional.empty(),
NO_VLAN, s1Eth100,
Sets.newHashSet(IpAddress.valueOf("192.168.20.1"),
IpAddress.valueOf("192.168.30.1")));
BgpConfig.BgpSpeakerConfig speaker3 = new BgpConfig.BgpSpeakerConfig(
Optional.empty(),
VLAN30, s3Eth100,
Sets.newHashSet(IpAddress.valueOf("192.168.40.1"),
IpAddress.valueOf("192.168.50.1")));
Set<BgpConfig.BgpSpeakerConfig> bgpSpeakers = Sets.newHashSet();
bgpSpeakers.add(speaker1);
bgpSpeakers.add(speaker2);
bgpSpeakers.add(speaker3);
return bgpSpeakers;
}
@Override
public void waveletUpdate(ReadableWaveletData wavelet, DeltaSequence deltas) {
Set<ParticipantId> currentAndNewParticipants = Sets.newHashSet(wavelet.getParticipants());
for (TransformedWaveletDelta delta : deltas) {
// Participants added or removed in this delta get the whole delta.
for (WaveletOperation op : delta) {
if (op instanceof AddParticipant) {
ParticipantId p = ((AddParticipant) op).getParticipantId();
currentAndNewParticipants.add(p);
}
}
}
// Robot should receive also deltas that contain AddParticipant ops.
// EventGenerator will take care to filter out events before the add.
for (ParticipantId participant : currentAndNewParticipants) {
RobotName robotName = RobotName.fromAddress(participant.getAddress());
if (robotName == null) {
// Not a valid robot name, next.
continue;
}
ParticipantId robotId = ParticipantId.ofUnsafe(robotName.toEmailAddress());
AccountData account;
try {
account = accountStore.getAccount(robotId);
} catch (PersistenceException e) {
LOG.severe("Failed to retrieve the account data for " + robotId.getAddress(), e);
continue;
}
if (account != null && account.isRobot()) {
RobotAccountData robotAccount = account.asRobot();
if (robotAccount.isVerified()) {
Robot robot = getOrCreateRobot(robotName, robotAccount);
updateRobot(robot, wavelet, deltas);
}
}
}
}
private Set<ArtifactCoordinates> getSnapshotsFromManagement(Profile profile, PomPropertyResolver propertyResolver) {
this.log.debug("\t\tChecking managed plugins of profile '" + profile.getId() + "'");
BuildBase build = profile.getBuild();
if (build != null) {
PluginManagement pluginManagement = build.getPluginManagement();
if (pluginManagement != null) {
Collection<Plugin> snapshots = Collections2.filter(pluginManagement.getPlugins(),
new IsSnapshotPlugin(propertyResolver));
return Sets.newHashSet(Collections2.transform(snapshots, PluginToCoordinates.INSTANCE));
}
}
return Collections.emptySet();
}
static private Set<String> splitClassNames(String classNames) {
if (classNames.startsWith("[")) {
classNames = classNames.replace("[", "");
classNames = classNames.replace("]", "");
return Sets.newHashSet(classNames.split("\\^"));
} else {
return Sets.newHashSet(classNames);
}
}
@Test
public void importOptionsTest2() {
Set<String> extensionsList = Sets.newHashSet("loadFoo", "loadBar");
ImportOptions options = new ImportOptions(Boolean.FALSE);
options.setExtensions(extensionsList);
assertEquals(Boolean.FALSE, options.isThrowExceptionIfExtensionNotFound());
assertEquals(Boolean.FALSE, options.withNoExtension());
assertEquals(2, (int) options.getExtensions().map(Set::size).orElse(-1));
}
public void addTermInfo(TermInfo info/* , Set<ColumnVisibility> columnVisibilities */) throws IOException {
if (!isCompatible(info)) {
throw new IllegalArgumentException("Attempting to add term info for " + info.fieldName + "=" + info.fieldValue + ", " + info.date
+ " to the summary for " + fieldName + "=" + fieldValue + ", " + date);
}
// Merge the columnVisibilities
// Do not count the record if we can't parse its ColumnVisibility
Set<ColumnVisibility> columnVisibilities = columnVisibilitiesMap.get(info.datatype);
if (columnVisibilities == null) {
columnVisibilities = Sets.newHashSet();
}
try {
if (info.vis.getExpression().length != 0) {
columnVisibilities.add(info.vis);
}
MutableLong count = summary.get(info.datatype);
if (count == null) {
summary.put(info.datatype, new MutableLong(info.count));
columnVisibilitiesMap.put(info.datatype, columnVisibilities);
} else {
count.add(info.count);
}
} catch (Exception e) {
// We want to stop the scan when we cannot properly combine ColumnVisibility
String message = "Error parsing ColumnVisibility of key";
log.error(message, e);
throw new IOException(message, e);
}
}
public void run() throws IOException {
NavApiCient client = NavigatorPlugin.fromConfigFile(configPath)
.getClient();
String cursorMark = null;
List<Map<String, Object>> results = null;
ResultsBatch<Map<String, Object>> rb;
FileWriter writer = new FileWriter(DEFAULT_FILENAME);
do {
MetadataQuery mq = new MetadataQuery(query, BATCH_SIZE, cursorMark);
rb = client.getEntityBatch(mq);
results = rb.getResults();
cursorMark = rb.getCursorMark();
// extract out all the entityIds for which to download
// lineage for
Set<String> entityIds = Sets.newHashSet();
for (Map<String, Object> entities : results) {
entityIds.add((String) entities.get(IDENTITY));
}
if (entityIds.size() > 0) {
fetchAndWriteLineage(entityIds, writer, client.getConfig());
}
} while (results.size() != 0);
writer.flush();
writer.close();
}
private Set<TimelineEntityGroupId> createTimelineEntityGroupIds(TezDAGID dagId) {
ApplicationId appId = dagId.getApplicationId();
HashSet<TimelineEntityGroupId> groupIds = Sets.newHashSet(
TimelineEntityGroupId.newInstance(appId, dagId.toString()));
for (int numGroupsPerDag : allNumGroupsPerDag) {
groupIds.add(TimelineEntityGroupId.newInstance(appId, dagId.getGroupId(numGroupsPerDag)));
}
return groupIds;
}
@Test(dataProvider = "subscriptionType")
public void testPartitionedNonPersistentTopicWithTcpLookup(SubscriptionType type) throws Exception {
log.info("-- Starting {} test --", methodName);
final int numPartitions = 5;
final String topic = "non-persistent://my-property/my-ns/partitioned-topic";
admin.topics().createPartitionedTopic(topic, numPartitions);
PulsarClient client = PulsarClient.builder()
.serviceUrl(pulsar.getBrokerServiceUrl())
.statsInterval(0, TimeUnit.SECONDS)
.build();
Consumer<byte[]> consumer = client.newConsumer().topic(topic).subscriptionName("subscriber-1")
.subscriptionType(type).subscribe();
Producer<byte[]> producer = pulsarClient.newProducer().topic(topic)
.enableBatching(false)
.messageRoutingMode(MessageRoutingMode.SinglePartition)
.create();
// Ensure all partitions exist
for (int i = 0; i < numPartitions; i++) {
TopicName partition = TopicName.get(topic).getPartition(i);
assertNotNull(pulsar.getBrokerService().getTopicReference(partition.toString()));
}
int totalProduceMsg = 500;
for (int i = 0; i < totalProduceMsg; i++) {
String message = "my-message-" + i;
producer.send(message.getBytes());
Thread.sleep(10);
}
Message<?> msg = null;
Set<String> messageSet = Sets.newHashSet();
for (int i = 0; i < totalProduceMsg; i++) {
msg = consumer.receive(1, TimeUnit.SECONDS);
if (msg != null) {
consumer.acknowledge(msg);
String receivedMessage = new String(msg.getData());
log.debug("Received message: [{}]", receivedMessage);
String expectedMessage = "my-message-" + i;
testMessageOrderAndDuplicates(messageSet, receivedMessage, expectedMessage);
} else {
break;
}
}
assertEquals(messageSet.size(), totalProduceMsg);
producer.close();
consumer.close();
log.info("-- Exiting {} test --", methodName);
client.close();
}
@Test
public void testPropertyRead() throws Exception {
FlumeConfiguration configuration = provider.getFlumeConfiguration();
Assert.assertNotNull(configuration);
/*
* Test the known errors in the file
*/
List<String> expected = Lists.newArrayList();
expected.add("host5 CONFIG_ERROR");
expected.add("host5 INVALID_PROPERTY");
expected.add("host4 CONFIG_ERROR");
expected.add("host4 CONFIG_ERROR");
expected.add("host4 PROPERTY_VALUE_NULL");
expected.add("host4 PROPERTY_VALUE_NULL");
expected.add("host4 PROPERTY_VALUE_NULL");
expected.add("host4 AGENT_CONFIGURATION_INVALID");
expected.add("ch2 ATTRS_MISSING");
expected.add("host3 CONFIG_ERROR");
expected.add("host3 PROPERTY_VALUE_NULL");
expected.add("host3 AGENT_CONFIGURATION_INVALID");
expected.add("host2 PROPERTY_VALUE_NULL");
expected.add("host2 AGENT_CONFIGURATION_INVALID");
List<String> actual = Lists.newArrayList();
for (FlumeConfigurationError error : configuration.getConfigurationErrors()) {
actual.add(error.getComponentName() + " " + error.getErrorType().toString());
}
Collections.sort(expected);
Collections.sort(actual);
Assert.assertEquals(expected, actual);
AgentConfiguration agentConfiguration =
configuration.getConfigurationFor("host1");
Assert.assertNotNull(agentConfiguration);
LOGGER.info(agentConfiguration.getPrevalidationConfig());
LOGGER.info(agentConfiguration.getPostvalidationConfig());
Set<String> sources = Sets.newHashSet("source1");
Set<String> sinks = Sets.newHashSet("sink1");
Set<String> channels = Sets.newHashSet("channel1");
Assert.assertEquals(sources, agentConfiguration.getSourceSet());
Assert.assertEquals(sinks, agentConfiguration.getSinkSet());
Assert.assertEquals(channels, agentConfiguration.getChannelSet());
}
@Override
default Set<String> sectionNames() {
return Sets.newHashSet("author", "chain", "state", "system");
}