类com.google.common.collect.ImmutableList源码实例Demo

下面列出了怎么用com.google.common.collect.ImmutableList的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: bundletool   文件: D8DexMergerTest.java
@Test
public void inputDexFileDoesNotExist_throws() throws Exception {
  Path nonExistentDex = tmpDir.resolve("classes-non-existing.dex");

  IllegalArgumentException exception =
      assertThrows(
          IllegalArgumentException.class,
          () ->
              new D8DexMerger()
                  .merge(
                      ImmutableList.of(nonExistentDex),
                      outputDir,
                      NO_MAIN_DEX_LIST,
                      /* isDebuggable= */ false,
                      /* minSdkVersion= */ ANDROID_K_API_VERSION));

  assertThat(exception).hasMessageThat().contains("was not found");
}
 
@Test
@DisabledProofTest
void verifyProof_MultiEntryMapDoesNotContain() {
  runTestWithView(database::createFork, (map) -> {
    List<MapEntry<HashCode, String>> entries = createMapEntries();
    putAll(map, entries);

    byte[] allOnes = new byte[PROOF_MAP_KEY_SIZE];
    Arrays.fill(allOnes, UnsignedBytes.checkedCast(0xFF));

    List<HashCode> otherKeys = ImmutableList.of(
        HashCode.fromBytes(allOnes),  // [11…1]
        createProofKey("PK1001"),
        createProofKey("PK1002"),
        createProofKey("PK100500")
    );

    for (HashCode key : otherKeys) {
      assertThat(map, provesThatAbsent(key));
    }
  });
}
 
源代码3 项目: nexus-public   文件: UpgradeManagerTest.java
@Test
public void testPrivateUpgrades() {

  List<Checkpoint> checkpoints = ImmutableList.of(
      new org.sonatype.nexus.upgrade.example.CheckpointFoo()
  );

  List<Upgrade> upgrades = ImmutableList.of(
      new org.sonatype.nexus.upgrade.example.UpgradePrivateModel_1_1(Providers.of(mock(DatabaseInstance.class)))
  );

  UpgradeManager upgradeManager = createUpgradeManager(checkpoints, upgrades);

  List<Upgrade> plan = upgradeManager.selectUpgrades(ImmutableMap.of(), false);

  assertThat(plan, contains(
      instanceOf(org.sonatype.nexus.upgrade.example.UpgradePrivateModel_1_1.class)
  ));
}
 
源代码4 项目: bazel   文件: BlazeOptionHandlerTest.java
@Test
public void testParseOptions_explicitConfig() {
  optionHandler.parseOptions(
      ImmutableList.of(
          "c0",
          "--default_override=0:c0=--test_multiple_string=rc",
          "--default_override=0:c0:conf=--test_multiple_string=config",
          "--rc_source=/somewhere/.blazerc",
          "--test_multiple_string=explicit",
          "--config=conf"),
      eventHandler);
  assertThat(eventHandler.getEvents()).isEmpty();
  assertThat(parser.getResidue()).isEmpty();
  assertThat(optionHandler.getRcfileNotes())
      .containsExactly(
          "Reading rc options for 'c0' from /somewhere/.blazerc:\n"
              + "  'c0' options: --test_multiple_string=rc",
          "Found applicable config definition c0:conf in file /somewhere/.blazerc: "
              + "--test_multiple_string=config");

  // "config" is expanded from --config=conf, which occurs last.
  TestOptions options = parser.getOptions(TestOptions.class);
  assertThat(options).isNotNull();
  assertThat(options.testMultipleString).containsExactly("rc", "explicit", "config").inOrder();
}
 
@Test
public void testDoublyNestedList() throws Exception {
  ObjectNode additionalProperties = Json.createObjectNode();
  ObjectNode parent = Json.readObjectNode("{\n" //
      + "  \"payload\": [[[0],[1]],[[2]]]\n" //
      + "}\n");
  List<Field> bqFields = ImmutableList.of(Field.newBuilder("payload", LegacySQLTypeName.RECORD, //
      Field.newBuilder("list", LegacySQLTypeName.RECORD, //
          Field.newBuilder("list", LegacySQLTypeName.INTEGER).setMode(Mode.REPEATED).build()) //
          .setMode(Mode.REPEATED).build() //
  ).setMode(Mode.REPEATED).build()); //
  Map<String, Object> expected = Json.readMap("{\"payload\":[" //
      + "{\"list\":[{\"list\":[0]},{\"list\":[1]}]}," //
      + "{\"list\":[{\"list\":[2]}]}" //
      + "]}");
  TRANSFORM.transformForBqSchema(parent, bqFields, additionalProperties);
  assertEquals(expected, Json.asMap(parent));
}
 
源代码6 项目: batfish   文件: InterfaceNoMatchMessages.java
@Override
public List<String> visitInterfaceGroupInterfaceAstNode(
    InterfaceGroupInterfaceAstNode interfaceGroupInterfaceAstNode) {
  Optional<ReferenceBook> refBook =
      _referenceLibrary.getReferenceBook(interfaceGroupInterfaceAstNode.getReferenceBook());
  if (refBook.isPresent()) {
    if (refBook.get().getInterfaceGroups().stream()
        .anyMatch(
            r ->
                r.getName()
                    .equalsIgnoreCase(interfaceGroupInterfaceAstNode.getInterfaceGroup()))) {
      return ImmutableList.of();
    } else {
      return ImmutableList.of(
          getErrorMessageMissingGroup(
              interfaceGroupInterfaceAstNode.getInterfaceGroup(),
              "Interface group",
              interfaceGroupInterfaceAstNode.getReferenceBook(),
              "reference book"));
    }
  } else {
    return ImmutableList.of(
        getErrorMessageMissingBook(
            interfaceGroupInterfaceAstNode.getReferenceBook(), "Reference book"));
  }
}
 
源代码7 项目: turbine   文件: BytecodeBinder.java
static Type bindTy(Sig.TySig sig, Function<String, TyVarSymbol> scope) {
  switch (sig.kind()) {
    case BASE_TY_SIG:
      return Type.PrimTy.create(((Sig.BaseTySig) sig).type(), ImmutableList.of());
    case CLASS_TY_SIG:
      return bindClassTy((Sig.ClassTySig) sig, scope);
    case TY_VAR_SIG:
      return Type.TyVar.create(scope.apply(((Sig.TyVarSig) sig).name()), ImmutableList.of());
    case ARRAY_TY_SIG:
      return bindArrayTy((Sig.ArrayTySig) sig, scope);
    case WILD_TY_SIG:
      return wildTy((WildTySig) sig, scope);
    case VOID_TY_SIG:
      return Type.VOID;
  }
  throw new AssertionError(sig.kind());
}
 
@Test
public void testThrottleAppliesAfterRebind() throws Exception {
    DynamicCluster cluster = origApp.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure(DynamicCluster.MAX_CONCURRENT_CHILD_COMMANDS, 1)
            .configure(DynamicCluster.INITIAL_SIZE, 1)
            .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(DynamicClusterTest.ThrowOnAsyncStartEntity.class))
                    .configure(DynamicClusterTest.ThrowOnAsyncStartEntity.COUNTER, new AtomicInteger()));
    app().start(ImmutableList.of(origApp.newLocalhostProvisioningLocation()));
    EntityAsserts.assertAttributeEquals(cluster, DynamicCluster.GROUP_SIZE, 1);

    rebind(RebindOptions.create().terminateOrigManagementContext(true));
    cluster = Entities.descendants(app(), DynamicCluster.class).iterator().next();
    cluster.resize(10);
    EntityAsserts.assertAttributeEqualsEventually(cluster, DynamicCluster.GROUP_SIZE, 10);
    EntityAsserts.assertAttributeEquals(cluster, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
}
 
源代码9 项目: presto-hbase-connector   文件: HBaseTable.java
public HBaseTable(String schemaName, HTableDescriptor tabDesc, HBaseConfig config) {
    this.hTableDescriptor = Objects.requireNonNull(tabDesc, "tabDesc is null");
    Objects.requireNonNull(schemaName, "schemaName is null");
    ImmutableList<ColumnMetadata> tableMeta = null;
    try {
        String tableName = tabDesc.getNameAsString() != null && tabDesc.getNameAsString().contains(":") ?
                tabDesc.getNameAsString().split(":")[1] : tabDesc.getNameAsString();
        tableMeta = Utils.getColumnMetaFromJson(schemaName, tableName, config.getMetaDir());
        if (tableMeta == null || tableMeta.size() <= 0) {
            logger.error("OOPS! Table meta info cannot be NULL, table name=" + tabDesc.getNameAsString());
            throw new Exception("Cannot find meta info of table " + tabDesc.getNameAsString() + ".");
        }
    } catch (Exception e) {
        logger.error(e, e.getMessage());
    }
    this.columnsMetadata = tableMeta;
}
 
@Inject
public RepositoryAdminPrivilegeDescriptor(final RepositoryManager repositoryManager, final List<Format> formats) {
  super(TYPE, repositoryManager, formats);
  this.formFields = ImmutableList.of(
      new StringTextFormField(
          P_FORMAT,
          messages.format(),
          messages.formatHelp(),
          FormField.MANDATORY
      ),
      new RepositoryCombobox(
          P_REPOSITORY,
          messages.repository(),
          messages.repositoryHelp(),
          true
      ).includeAnEntryForAllRepositories(),
      new StringTextFormField(
          P_ACTIONS,
          messages.actions(),
          messages.actionsHelp(),
          FormField.MANDATORY
      )
  );
}
 
源代码11 项目: client-java   文件: KeyRangeUtils.java
/**
 * Merge SORTED potential discrete ranges into no more than {@code splitNum} large range.
 *
 * @param ranges the sorted range list to merge
 * @param splitNum upper bound of number of ranges to merge into
 * @return the minimal range which encloses all ranges in this range list.
 */
public static List<KeyRange> mergeSortedRanges(List<KeyRange> ranges, int splitNum) {
  if (splitNum <= 0) {
    throw new RuntimeException("Cannot split ranges by non-positive integer");
  }
  if (ranges == null || ranges.isEmpty() || ranges.size() <= splitNum) {
    return ranges;
  }
  // use ceil for split step
  int step = (ranges.size() + splitNum - 1) / splitNum;
  ImmutableList.Builder<KeyRange> rangeBuilder = ImmutableList.builder();
  for (int i = 0, nowPos = 0; i < splitNum; i++) {
    int nextPos = Math.min(nowPos + step - 1, ranges.size() - 1);
    KeyRange first = ranges.get(nowPos);
    KeyRange last = ranges.get(nextPos);

    Key lowerMin = toRawKey(first.getStart(), true);
    Key upperMax = toRawKey(last.getEnd(), false);

    rangeBuilder.add(makeCoprocRange(lowerMin.toByteString(), upperMax.toByteString()));
    nowPos = nowPos + step;
  }
  return rangeBuilder.build();
}
 
源代码12 项目: buck   文件: NativeLinkables.java
/**
 * Collect all the shared libraries generated by {@link NativeLinkable}s found by transitively
 * traversing all unbroken dependency chains of {@link NativeLinkable} objects found via the
 * passed in {@link NativeLinkable} roots.
 *
 * @param alwaysIncludeRoots whether to include shared libraries from roots, even if they prefer
 *     static linkage.
 * @return a mapping of library name to the library {@link SourcePath}.
 */
public static ImmutableSortedMap<String, SourcePath> getTransitiveSharedLibraries(
    ActionGraphBuilder graphBuilder,
    Iterable<? extends NativeLinkable> roots,
    boolean alwaysIncludeRoots) {
  ImmutableSet<BuildTarget> rootTargets =
      RichStream.from(roots).map(l -> l.getBuildTarget()).toImmutableSet();

  ImmutableList<? extends NativeLinkable> nativeLinkables =
      getTransitiveNativeLinkables(graphBuilder, roots);

  SharedLibrariesBuilder builder = new SharedLibrariesBuilder();
  builder.addAll(
      graphBuilder,
      nativeLinkables.stream()
          .filter(
              e ->
                  e.getPreferredLinkage() != NativeLinkableGroup.Linkage.STATIC
                      || (alwaysIncludeRoots && rootTargets.contains(e.getBuildTarget())))
          .collect(Collectors.toList()));
  return builder.build();
}
 
源代码13 项目: presto   文件: TestCompactionSetCreator.java
@Test
public void testBucketedTableCompaction()
{
    List<ShardIndexInfo> inputShards = ImmutableList.of(
            shardWithBucket(1),
            shardWithBucket(2),
            shardWithBucket(2),
            shardWithBucket(1),
            shardWithBucket(2),
            shardWithBucket(1));

    long tableId = bucketedTableInfo.getTableId();
    Set<OrganizationSet> actual = compactionSetCreator.createCompactionSets(bucketedTableInfo, inputShards);

    assertEquals(actual.size(), 2);

    Set<OrganizationSet> expected = ImmutableSet.of(
            new OrganizationSet(tableId, extractIndexes(inputShards, 0, 3, 5), OptionalInt.of(1)),
            new OrganizationSet(tableId, extractIndexes(inputShards, 1, 2, 4), OptionalInt.of(2)));
    assertEquals(actual, expected);
}
 
源代码14 项目: batfish   文件: PacketHeaderConstraintsUtil.java
/**
 * Convert {@link PacketHeaderConstraints} to an {@link AclLineMatchExpr}.
 *
 * @param phc the packet header constraints
 * @param srcIpSpace Resolved source IP space
 * @param dstIpSpace Resolved destination IP space
 */
public static AclLineMatchExpr toAclLineMatchExpr(
    PacketHeaderConstraints phc, IpSpace srcIpSpace, IpSpace dstIpSpace) {
  List<AclLineMatchExpr> conjuncts =
      Stream.of(
              matchSrc(srcIpSpace),
              matchDst(dstIpSpace),
              dscpsToAclLineMatchExpr(phc.getDscps()),
              ecnsToAclLineMatchExpr(phc.getEcns()),
              packetLengthToAclLineMatchExpr(phc.getPacketLengths()),
              fragmentOffsetsToAclLineMatchExpr(phc.getFragmentOffsets()),
              ipProtocolsToAclLineMatchExpr(phc.getIpProtocols()),
              icmpCodeToAclLineMatchExpr(phc.getIcmpCodes()),
              icmpTypeToAclLineMatchExpr(phc.getIcmpTypes()),
              srcPortsToAclLineMatchExpr(phc.getSrcPorts()),
              dstPortsToAclLineMatchExpr(phc.getDstPorts()),
              applicationsToAclLineMatchExpr(phc.getApplications()),
              tcpFlagsToAclLineMatchExpr(phc.getTcpFlags()))
          .filter(Objects::nonNull)
          .collect(ImmutableList.toImmutableList());

  return and(conjuncts);
}
 
源代码15 项目: onos   文件: UiExtensionTest.java
@Test
public void withPath() throws IOException {
    viewList = ImmutableList.of(FOO_VIEW);
    ext = new UiExtension.Builder(cl, viewList)
            .resourcePath(CUSTOM)
            .build();

    css = new String(toByteArray(ext.css()));
    assertTrue("incorrect css stream", css.contains("custom-css"));
    js = new String(toByteArray(ext.js()));
    assertTrue("incorrect js stream", js.contains("custom-js"));

    assertEquals("expected 1 view", 1, ext.views().size());
    view = ext.views().get(0);
    assertEquals("wrong view category", OTHER, view.category());
    assertEquals("wrong view id", FOO_ID, view.id());
    assertEquals("wrong view label", FOO_LABEL, view.label());

    assertNull("unexpected message handler factory", ext.messageHandlerFactory());
    assertNull("unexpected topo overlay factory", ext.topoOverlayFactory());
}
 
@Test
public void testInverseReferenceAutoUpdate_NonComposite_ManyToMany() throws Exception {
    AtlasEntityType bType = typeRegistry.getEntityTypeByName("B");
    AtlasEntity a1 = new AtlasEntity("A");
    a1.setAttribute(NAME, TestUtils.randomString());
    AtlasEntity a2 = new AtlasEntity("A");
    a2.setAttribute(NAME, TestUtils.randomString());
    AtlasEntity a3 = new AtlasEntity("A");
    a3.setAttribute(NAME, TestUtils.randomString());
    AtlasEntity b1 = new AtlasEntity("B");
    b1.setAttribute(NAME, TestUtils.randomString());
    AtlasEntity b2 = new AtlasEntity("B");
    b2.setAttribute(NAME, TestUtils.randomString());
    AtlasEntitiesWithExtInfo atlasEntitiesWithExtInfo = new AtlasEntitiesWithExtInfo();
    atlasEntitiesWithExtInfo.addEntity(a1);
    atlasEntitiesWithExtInfo.addEntity(a2);
    atlasEntitiesWithExtInfo.addEntity(a3);
    atlasEntitiesWithExtInfo.addEntity(b1);
    atlasEntitiesWithExtInfo.addEntity(b2);
    AtlasEntityStream entityStream = new AtlasEntityStream(atlasEntitiesWithExtInfo);
    EntityMutationResponse response = entityStore.createOrUpdate(entityStream , false);

    AtlasEntity b1ForPartialUpdate = new AtlasEntity("B");
    b1ForPartialUpdate.setAttribute("manyToManyA", ImmutableList.of(AtlasTypeUtil.getAtlasObjectId(a1), AtlasTypeUtil.getAtlasObjectId(a2)));
    init();
    response = entityStore.updateByUniqueAttributes(bType, Collections.<String, Object>singletonMap(NAME, b1.getAttribute(NAME)), new AtlasEntityWithExtInfo(b1ForPartialUpdate));
    List<AtlasEntityHeader> partialUpdatedEntities = response.getPartialUpdatedEntities();
    assertEquals(partialUpdatedEntities.size(), 3);
    AtlasEntitiesWithExtInfo storedEntities = entityStore.getByIds(ImmutableList.of(a1.getGuid(), a2.getGuid(), b1.getGuid()));
    AtlasEntity storedEntity = storedEntities.getEntity(b1.getGuid());
    verifyReferenceList(storedEntity, "manyToManyA", ImmutableList.of(AtlasTypeUtil.getAtlasObjectId(a1), AtlasTypeUtil.getAtlasObjectId(a2)));
    storedEntity = storedEntities.getEntity(a1.getGuid());
    verifyReferenceList(storedEntity, "manyB", ImmutableList.of(AtlasTypeUtil.getAtlasObjectId(b1)));
    storedEntity = storedEntities.getEntity(a2.getGuid());
    verifyReferenceList(storedEntity, "manyB", ImmutableList.of(AtlasTypeUtil.getAtlasObjectId(b1)));
}
 
源代码17 项目: nomulus   文件: TextDiffSubjectTest.java
@Test
public void displayed_sideBySideDiff_hasDiff() throws IOException {
  ImmutableList<String> actual = readAllLinesFromResource(ACTUAL_RESOURCE);
  ImmutableList<String> expected = readAllLinesFromResource(EXPECTED_RESOURCE);
  String diff = Joiner.on('\n').join(readAllLinesFromResource(SIDE_BY_SIDE_DIFF_RESOURCE));
  assertThat(TextDiffSubject.generateSideBySideDiff(expected, actual)).isEqualTo(diff);
}
 
源代码18 项目: bundletool   文件: WearApkLocatorTest.java
private static ModuleSplit createModuleSplit(
    AndroidManifest androidManifest,
    ResourceTable resourceTable,
    ImmutableList<ModuleEntry> entries) {
  return ModuleSplit.builder()
      .setAndroidManifest(androidManifest)
      .setResourceTable(resourceTable)
      .setEntries(entries)
      .setModuleName(BundleModuleName.BASE_MODULE_NAME)
      .setApkTargeting(ApkTargeting.getDefaultInstance())
      .setVariantTargeting(VariantTargeting.getDefaultInstance())
      .setMasterSplit(true)
      .build();
}
 
@Test
public void doesNotFireOnUncorrelated()
{
    tester().assertThat(new TransformCorrelatedScalarAggregationWithProjection(tester().getMetadata()))
            .on(p -> p.correlatedJoin(
                    ImmutableList.of(),
                    p.values(p.symbol("a")),
                    p.values(p.symbol("b"))))
            .doesNotFire();
}
 
@Test
void deletesShouldBeExecutedAfterAllHooksFinish() throws Exception {
    givenUnlimitedQuota();

    CountDownLatch latchForHook1 = new CountDownLatch(1);
    when(preDeletionHook1.notifyDelete(any(PreDeletionHook.DeleteOperation.class)))
        .thenAnswer(invocation -> {
            latchForHook1.countDown();
            return Mono.empty();
        });

    CountDownLatch latchForHook2 = new CountDownLatch(1);
    when(preDeletionHook2.notifyDelete(any(PreDeletionHook.DeleteOperation.class)))
        .thenAnswer(invocation -> {
            latchForHook2.countDown();
            return Mono.empty();
        });

    MessageId messageId = testingData.persist(mailbox1.getMailboxId(), messageUid1, FLAGS, session);
    messageIdManager.delete(messageId, ImmutableList.of(mailbox1.getMailboxId()), session);

    latchForHook1.await();
    latchForHook2.await();

    assertThat(messageIdManager.getMessage(messageId, FetchGroup.MINIMAL, session))
        .isEmpty();
}
 
源代码21 项目: tpcds   文件: WebReturnsRowGenerator.java
@Override
public RowGeneratorResult generateRowAndChildRows(long rowNumber, Session session, RowGenerator parentRowGenerator, RowGenerator childRowGenerator)
{
    RowGeneratorResult salesAndReturnsResult = parentRowGenerator.generateRowAndChildRows(rowNumber, session, null, this);
    if (salesAndReturnsResult.getRowAndChildRows().size() == 2) {
        return new RowGeneratorResult(ImmutableList.of(salesAndReturnsResult.getRowAndChildRows().get(1)), salesAndReturnsResult.shouldEndRow());
    }
    else {
        return new RowGeneratorResult(emptyList(), salesAndReturnsResult.shouldEndRow());  // no return occurred for given sale
    }
}
 
源代码22 项目: onos   文件: OplinkOpticalDeviceDescription.java
@Override
public List<PortDescription> discoverPortDetails() {
    log.debug("Port description to be added for device {}", data().deviceId());
    String reply = netconfGet(handler(), getPortsFilter());
    List<PortDescription> descriptions = parsePorts(reply);
    return ImmutableList.copyOf(descriptions);
}
 
源代码23 项目: hbase-indexer   文件: ColumnBasedIndexerTest.java
@Test
public void testCalculateIndexUpdates_DeleteRow_NoRowFieldDefinedForIndexer() throws IOException {
    KeyValue toDelete = new KeyValue(Bytes.toBytes("_row_"), Bytes.toBytes("_cf_"),
                                     Bytes.toBytes("_qual_"),
                                     0L, Type.Delete);
    RowData eventRowData = createEventRowData("_row_", toDelete);
    
    indexer.calculateIndexUpdates(ImmutableList.of(eventRowData), updateCollector);

    assertTrue(updateCollector.getDeleteQueries().isEmpty());
    assertTrue(updateCollector.getIdsToDelete().isEmpty());
    assertTrue(updateCollector.getDocumentsToAdd().isEmpty());
}
 
@Test
public void testNxos() {
  String n7000 = "boot system bootflash:n7000-s2-dk9.7.2.1.D1.1.bin sup-2 \n";
  String nxos = "boot nxos bootflash:nxos.7.0.3.I4.7.bin \n";
  String rancid = "!RANCID-CONTENT-TYPE: cisco-nx\n";

  for (String fileText : ImmutableList.of(n7000, nxos, rancid)) {
    assertThat(identifyConfigurationFormat(fileText), equalTo(CISCO_NX));
  }
}
 
@Test
public void testInstallDirAndRunDir() throws Exception {
    MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
        .configure(BrooklynConfigKeys.ONBOX_BASE_DIR, "/tmp/brooklyn-foo"));

    entity.start(ImmutableList.of(loc));

    Assert.assertEquals(entity.getAttribute(SoftwareProcess.INSTALL_DIR), "/tmp/brooklyn-foo/installs/MyService");
    Assert.assertEquals(entity.getAttribute(SoftwareProcess.RUN_DIR), "/tmp/brooklyn-foo/apps/"+entity.getApplicationId()+"/entities/MyService_"+entity.getId());
}
 
源代码26 项目: presto   文件: BenchmarkQueryRunner.java
private List<URI> getAllNodes(URI server)
{
    Request request = prepareGet().setUri(uriBuilderFrom(server).replacePath("/v1/service/presto").build()).build();
    JsonResponseHandler<ServiceDescriptorsRepresentation> responseHandler = createJsonResponseHandler(jsonCodec(ServiceDescriptorsRepresentation.class));
    ServiceDescriptorsRepresentation serviceDescriptors = httpClient.execute(request, responseHandler);

    ImmutableList.Builder<URI> addresses = ImmutableList.builder();
    for (ServiceDescriptor serviceDescriptor : serviceDescriptors.getServiceDescriptors()) {
        String httpUri = serviceDescriptor.getProperties().get("http");
        if (httpUri != null) {
            addresses.add(URI.create(httpUri));
        }
    }
    return addresses.build();
}
 
源代码27 项目: calcite   文件: LatticeSpace.java
Path addPath(List<Step> steps) {
  final ImmutableList<Step> key = ImmutableList.copyOf(steps);
  final Path path = pathMap.get(key);
  if (path != null) {
    return path;
  }
  final Path path2 = new Path(key, pathMap.size());
  pathMap.put(key, path2);
  return path2;
}
 
源代码28 项目: ProjectAres   文件: ListingCommands.java
@Command(
    aliases = "announce",
    usage = "[on|off]",
    desc = "Announce the server to the public listing service",
    min = 0,
    max = 1
)
@CommandPermissions("pgm.listing.announce")
public void announce(CommandContext args, CommandSender sender) throws CommandException, SuggestException {
    listingService.update("on".equals(args.tryString(0, ImmutableList.of("on", "off")).orElse("on")), sender);
}
 
@Test(expected = RuntimeException.class)
public void testDuplicateDelegates() {
  ClassLoaderStageLibraryTask library = new ClassLoaderStageLibraryTask(null, null, new Configuration());

  StageLibraryDefinition stageLib = Mockito.mock(StageLibraryDefinition.class);
  Mockito.when(stageLib.getName()).thenReturn("duplicate-one");

  StageLibraryDelegateDefinitition def = Mockito.mock(StageLibraryDelegateDefinitition.class);
  Mockito.when(def.getLibraryDefinition()).thenReturn(stageLib);
  Mockito.when(def.getExportedInterface()).thenReturn(Runnable.class);

  library.validateDelegates(ImmutableList.of(def, def));
}
 
源代码30 项目: Strata   文件: ScheduleTest.java
@Test
public void test_of_size2_finalStub() {
  Schedule test = Schedule.builder()
      .periods(ImmutableList.of(P3_NORMAL, P4_STUB))
      .frequency(P1M)
      .rollConvention(DAY_17)
      .build();
  assertThat(test.size()).isEqualTo(2);
  assertThat(test.isTerm()).isEqualTo(false);
  assertThat(test.isSinglePeriod()).isEqualTo(false);
  assertThat(test.getFrequency()).isEqualTo(P1M);
  assertThat(test.getRollConvention()).isEqualTo(DAY_17);
  assertThat(test.isEndOfMonthConvention()).isEqualTo(false);
  assertThat(test.getPeriods()).containsExactly(P3_NORMAL, P4_STUB);
  assertThat(test.getPeriod(0)).isEqualTo(P3_NORMAL);
  assertThat(test.getPeriod(1)).isEqualTo(P4_STUB);
  assertThat(test.getStartDate()).isEqualTo(P3_NORMAL.getStartDate());
  assertThat(test.getEndDate()).isEqualTo(P4_STUB.getEndDate());
  assertThat(test.getUnadjustedStartDate()).isEqualTo(P3_NORMAL.getUnadjustedStartDate());
  assertThat(test.getUnadjustedEndDate()).isEqualTo(P4_STUB.getUnadjustedEndDate());
  assertThat(test.getFirstPeriod()).isEqualTo(P3_NORMAL);
  assertThat(test.getLastPeriod()).isEqualTo(P4_STUB);
  assertThat(test.getInitialStub()).isEqualTo(Optional.empty());
  assertThat(test.getFinalStub()).isEqualTo(Optional.of(P4_STUB));
  assertThat(test.getRegularPeriods()).isEqualTo(ImmutableList.of(P3_NORMAL));
  assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> test.getPeriod(2));
  assertThat(test.getUnadjustedDates()).containsExactly(AUG_17, SEP_17, SEP_30);
}
 
 同包方法