com.google.common.collect.Sets#newHashSet ( )源码实例Demo

下面列出了com.google.common.collect.Sets#newHashSet ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: api-mining   文件: JavaVariableFeatureExtractor.java
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;
}
 
源代码3 项目: tac-kbp-eal   文件: ExpandFromRealis.java
@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());
}
 
源代码4 项目: iceberg   文件: TestLocalScan.java
@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())));
}
 
源代码5 项目: dhis2-core   文件: DataQueryParamsTest.java
@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() );
}
 
源代码6 项目: incubator-sentry   文件: TestSentryStore.java
@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());
}
 
源代码7 项目: intellij   文件: FilteredTargetMap.java
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();
}
 
源代码8 项目: emodb   文件: DataStoreResource1.java
/**
 * 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()));
}
 
源代码10 项目: onos   文件: PeerConnectivityManagerTest.java
/**
 * 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;
}
 
源代码11 项目: swellrt   文件: RobotsGateway.java
@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);
      }
    }
  }
}
 
源代码12 项目: unleash-maven-plugin   文件: CheckPluginVersions.java
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();
}
 
源代码13 项目: tasmo   文件: Materialization.java
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);
    }
}
 
源代码14 项目: powsybl-core   文件: ImportOptionsTest.java
@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));
}
 
源代码15 项目: datawave   文件: GlobalIndexDateSummaryIterator.java
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);
    }
}
 
源代码16 项目: navigator-sdk   文件: LineageExport.java
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();
}
 
源代码17 项目: tez   文件: TimelineCachePluginImpl.java
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;
}
 
源代码18 项目: pulsar   文件: NonPersistentTopicTest.java
@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());
}
 
源代码20 项目: api   文件: IRpcModule.java
@Override
default Set<String> sectionNames() {
    return Sets.newHashSet("author", "chain", "state", "system");
}