Java Code Examples for com.google.common.collect.ImmutableSet

The following examples show how to use com.google.common.collect.ImmutableSet. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: onos   Source File: PathPainterTopovMessageHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void findAndSendPaths(Mode mode) {
    log.debug("src={}; dst={}; mode={}", src, dst, currentMode);
    if (src != null && dst != null) {
        pathIndex = 0;
        ImmutableSet.Builder<Link> builder = ImmutableSet.builder();
        if (mode.equals(Mode.SHORTEST)) {
            paths = ImmutableList.copyOf(pathService.getPaths(src, dst));
            allPathLinks = buildPaths(builder).build();
        } else if (mode.equals(Mode.DISJOINT)) {
            paths = ImmutableList.copyOf(pathService.getDisjointPaths(src, dst));
            allPathLinks = buildDisjointPaths(builder).build();
        } else if (mode.equals(Mode.GEODATA)) {
            paths = ImmutableList.copyOf(pathService.getPaths(src, dst, linkData));
            allPathLinks = buildPaths(builder).build();
        } else {
            log.warn("Unsupported MODE");
        }
    } else {
        paths = ImmutableList.of();
        allPathLinks = ImmutableSet.of();
    }
    hilightAndSendPaths();

}
 
Example 2
@Test
public void retry_specified_number_of_times() throws IOException, InterruptedException {
    String conflictingContainer = "conflictingContainer";
    DockerExecutionException dockerException = new DockerExecutionException(
            "The name \"" + conflictingContainer + "\" is already in use");
    doThrow(dockerException)
            .doThrow(dockerException)
            .doNothing()
            .when(dockerCompose).up();

    ConflictingContainerRemovingDockerCompose conflictingContainerRemovingDockerCompose =
            new ConflictingContainerRemovingDockerCompose(dockerCompose, docker, 3);
    conflictingContainerRemovingDockerCompose.up();

    verify(dockerCompose, times(3)).up();
    verify(docker, times(2)).rm(ImmutableSet.of(conflictingContainer));
}
 
Example 3
Source Project: holdmail   Source File: EntityPersistenceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSaveRecipients() {

    MessageEntity entity = buildBasicEntity();

    String email1 = "[email protected]";
    String email2 = "[email protected]";

    entity.setRecipients(ImmutableSet.of(
            new MessageRecipientEntity(email1),
            new MessageRecipientEntity(email2)));


    long savedEntityId = messageRepository.save(entity).getMessageId();
    MessageEntity loaded = messageRepository.findOne(savedEntityId);

    assertThat(loaded.getRecipients()).hasSize(2);
    asList(email1, email2).forEach(expected ->
        loaded.getRecipients()
              .stream()
              .filter(recip -> expected.equals(recip.getRecipientEmail()))
    .findFirst().orElseThrow(() -> new AssertionFailure("couldn't find email: " + email1)));

}
 
Example 4
Source Project: arcusplatform   Source File: TestTransformers.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testModelToDevice() {
   assertEquals(Optional.empty(), Transformers.modelToDevice(null, true, null, true));
   assertEquals(Optional.empty(), Transformers.modelToDevice(nonDevModel, true, null, true));
   assertEquals(Optional.empty(), Transformers.modelToDevice(allCaps, true, null, true));

   allCaps.setAttribute(DeviceCapability.ATTR_NAME, "foobar");

   GoogleDevice dev = new GoogleDevice();
   dev.setId(allCaps.getAddress().getRepresentation());
   dev.setName(devName.toMap());
   dev.setDeviceInfo(devInfo.toMap());
   dev.setAttributes(ImmutableMap.of(
         Constants.Attributes.ColorTemperature.TEMPERATURE_MIN_K, 2000,
         Constants.Attributes.ColorTemperature.TEMPERATURE_MAX_K, 6500
   ));
   dev.setTraits(ImmutableSet.of(Constants.Trait.BRIGHTNESS, Constants.Trait.COLOR_SPECTRUM, Constants.Trait.COLOR_TEMPERATURE, Constants.Trait.ON_OFF));
   dev.setType(Constants.Type.LIGHT);
   dev.setWillReportState(true);
   dev.setCustomData(ImmutableMap.of(Transformers.PRODUCT_ID, "12345", Transformers.TYPE_HINT, "Light"));

   assertDevice(dev, Transformers.modelToDevice(allCaps, true, null, true).get());
}
 
Example 5
Source Project: hugegraph   Source File: UsersTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testListAllAccess() {
    HugeGraph graph = graph();
    UserManager userManager = graph.userManager();

    Id group = userManager.createGroup(makeGroup("group1"));
    Id target1 = userManager.createTarget(makeTarget("graph1", "url1"));
    Id target2 = userManager.createTarget(makeTarget("graph2", "url2"));

    userManager.createAccess(makeAccess(group, target1,
                                        HugePermission.READ));
    userManager.createAccess(makeAccess(group, target2,
                                        HugePermission.READ));

    List<HugeAccess> access = userManager.listAllAccess(-1);
    Assert.assertEquals(2, access.size());
    Assert.assertEquals(ImmutableSet.of(target1, target2),
                        ImmutableSet.of(access.get(0).target(),
                                        access.get(1).target()));

    Assert.assertEquals(0, userManager.listAllAccess(0).size());
    Assert.assertEquals(1, userManager.listAllAccess(1).size());
    Assert.assertEquals(2, userManager.listAllAccess(2).size());
    Assert.assertEquals(2, userManager.listAllAccess(3).size());
}
 
Example 6
Source Project: buck   Source File: BuildCommand.java    License: Apache License 2.0 6 votes vote down vote up
private ImmutableSet<BuildTargetWithOutputs> getBuildTargetsWithOutputsForJustBuild(
    CommandRunnerParams params,
    Optional<TargetConfiguration> targetConfiguration,
    ActionGraphAndBuilder actionGraphAndBuilder,
    String justBuildTarget)
    throws ActionGraphCreationException {
  BuildTargetOutputLabelParser.TargetWithOutputLabel targetWithOutputLabel =
      BuildTargetOutputLabelParser.getBuildTargetNameWithOutputLabel(justBuildTarget);
  BuildTarget explicitTarget =
      params
          .getUnconfiguredBuildTargetFactory()
          .create(
              targetWithOutputLabel.getTargetName(),
              params.getCells().getRootCell().getCellNameResolver())
          // TODO(nga): ignores default_target_platform and configuration detector
          .configure(targetConfiguration.orElse(UnconfiguredTargetConfiguration.INSTANCE));
  Iterable<BuildRule> actionGraphRules =
      Objects.requireNonNull(actionGraphAndBuilder.getActionGraph().getNodes());
  if (!Iterables.any(actionGraphRules, rule -> explicitTarget.equals(rule.getBuildTarget()))) {
    throw new ActionGraphCreationException(
        "Targets specified via `--just-build` must be a subset of action graph.");
  }
  return ImmutableSet.of(
      BuildTargetWithOutputs.of(explicitTarget, targetWithOutputLabel.getOutputLabel()));
}
 
Example 7
Source Project: nomulus   Source File: DomainUpdateFlowTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_superuserClientUpdateProhibited() throws Exception {
  setEppInput("domain_update_add_server_hold_status.xml");
  persistReferencedEntities();
  persistResource(
      persistActiveDomain(getUniqueIdFromCommand())
          .asBuilder()
          .setStatusValues(ImmutableSet.of(StatusValue.CLIENT_UPDATE_PROHIBITED))
          .build());
  clock.advanceOneMilli();
  runFlowAssertResponse(
      CommitMode.LIVE, UserPrivileges.SUPERUSER, loadFile("generic_success_response.xml"));
  assertAboutDomains()
      .that(reloadResourceByForeignKey())
      .hasStatusValue(StatusValue.CLIENT_UPDATE_PROHIBITED)
      .and()
      .hasStatusValue(StatusValue.SERVER_HOLD);
}
 
Example 8
Source Project: bazel   Source File: RequiredConfigFragmentsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void provideDirectRequiredFragmentsMode() throws Exception {
  useConfiguration("--include_config_fragments_provider=direct");
  scratch.file(
      "a/BUILD",
      "config_setting(name = 'config', values = {'start_end_lib': '1'})",
      "py_library(name = 'pylib', srcs = ['pylib.py'])",
      "cc_library(name = 'a', srcs = ['A.cc'], data = [':pylib'])");

  ImmutableSet<String> ccLibDirectFragments =
      getConfiguredTarget("//a:a")
          .getProvider(RequiredConfigFragmentsProvider.class)
          .getRequiredConfigFragments();
  assertThat(ccLibDirectFragments).contains("CppConfiguration");
  assertThat(ccLibDirectFragments).doesNotContain("PythonConfiguration");

  ImmutableSet<String> configSettingDirectFragments =
      getConfiguredTarget("//a:config")
          .getProvider(RequiredConfigFragmentsProvider.class)
          .getRequiredConfigFragments();
  assertThat(configSettingDirectFragments).contains("CppOptions");
}
 
Example 9
Source Project: buck   Source File: ConfigSettingSelectableTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void refinesReturnsTrueWithSameValues() {
  ImmutableMap<String, String> values = ImmutableMap.of("a", "b");

  ConfigSettingSelectable configSetting1 =
      new ConfigSettingSelectable(
          buildTarget("//a:b"),
          values,
          ImmutableSet.of(
              constraintValue("//a:x", "//a:xc"), constraintValue("//a:y", "//a:yc")));

  ConfigSettingSelectable configSetting2 =
      new ConfigSettingSelectable(
          buildTarget("//a:c"), values, ImmutableSet.of(constraintValue("//a:x", "//a:xc")));

  assertTrue(configSetting1.refines(configSetting2));
}
 
Example 10
Source Project: samza   Source File: TestSSPMetadataCache.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Given that the admin throws an exception when trying to get the metadata after a successful fetch, getMetadata
 * should propagate the exception.
 */
@Test(expected = SamzaException.class)
public void testGetMetadataExceptionAfterSuccessfulFetch() {
  SystemStreamPartition ssp = buildSSP(0);
  SSPMetadataCache cache = buildSSPMetadataCache(ImmutableSet.of(ssp));

  // do a successful fetch first
  when(clock.currentTimeMillis()).thenReturn(10L);
  when(systemAdmin.getSSPMetadata(ImmutableSet.of(ssp))).thenReturn(ImmutableMap.of(ssp, sspMetadata(1)));
  cache.getMetadata(ssp);

  // throw an exception on the next fetch
  when(clock.currentTimeMillis()).thenReturn(11 + CACHE_TTL.toMillis());
  when(systemAdmin.getSSPMetadata(ImmutableSet.of(ssp))).thenThrow(new SamzaException());
  cache.getMetadata(ssp);
}
 
Example 11
Source Project: nomulus   Source File: DomainBase.java    License: Apache License 2.0 6 votes vote down vote up
@PostLoad
void postLoad() {
  // Reconstitute the contact list.
  ImmutableSet.Builder<DesignatedContact> contactsBuilder =
      new ImmutableSet.Builder<DesignatedContact>();

  if (registrantContact != null) {
    contactsBuilder.add(
        DesignatedContact.create(DesignatedContact.Type.REGISTRANT, registrantContact));
  }
  if (billingContact != null) {
    contactsBuilder.add(DesignatedContact.create(DesignatedContact.Type.BILLING, billingContact));
  }
  if (techContact != null) {
    contactsBuilder.add(DesignatedContact.create(DesignatedContact.Type.TECH, techContact));
  }
  if (adminContact != null) {
    contactsBuilder.add(DesignatedContact.create(DesignatedContact.Type.ADMIN, adminContact));
  }

  allContacts = contactsBuilder.build();
}
 
Example 12
Source Project: ScoreboardStats   Source File: Settings.java    License: MIT License 6 votes vote down vote up
/**
 * Load the configuration file in memory and convert it into simple variables
 */
@Override
public void loadConfig() {
    super.loadConfig();

    //This set only changes after another call to loadConfig so this set can be immutable
    disabledWorlds = ImmutableSet.copyOf(config.getStringList("disabled-disabledWorlds"));

    tempTitle = trimLength(tempTitle, 32);

    String title = config.getString("Scoreboard.Title");
    mainScoreboard = new SidebarConfig(trimLength(title, 32));
    //Load all normal scoreboard variables
    loadItems(config.getConfigurationSection("Scoreboard.Items"));

    //temp-scoreboard
    tempScoreboard = tempScoreboard && pvpStats;
    topItems = checkItems(topItems);
    topType = topType.replace("%", "");
}
 
Example 13
Source Project: hadoop   Source File: TestCommonNodeLabelsManager.java    License: Apache License 2.0 6 votes vote down vote up
@Test(timeout = 5000)
public void testRemovelabelWithNodes() throws Exception {
  mgr.addToCluserNodeLabels(toSet("p1", "p2", "p3"));
  mgr.replaceLabelsOnNode(ImmutableMap.of(toNodeId("n1"), toSet("p1")));
  mgr.replaceLabelsOnNode(ImmutableMap.of(toNodeId("n2"), toSet("p2")));
  mgr.replaceLabelsOnNode(ImmutableMap.of(toNodeId("n3"), toSet("p3")));

  mgr.removeFromClusterNodeLabels(ImmutableSet.of("p1"));
  assertMapEquals(mgr.getNodeLabels(),
      ImmutableMap.of(toNodeId("n2"), toSet("p2"), toNodeId("n3"), toSet("p3")));
  assertCollectionEquals(mgr.lastRemovedlabels, Arrays.asList("p1"));

  mgr.removeFromClusterNodeLabels(ImmutableSet.of("p2", "p3"));
  Assert.assertTrue(mgr.getNodeLabels().isEmpty());
  Assert.assertTrue(mgr.getClusterNodeLabels().isEmpty());
  assertCollectionEquals(mgr.lastRemovedlabels, Arrays.asList("p2", "p3"));
}
 
Example 14
Source Project: breakerbox   Source File: YamlInstanceConfigurationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void multipleClusters() throws Exception {
    final YamlInstanceConfiguration configuration = configFactory.build(
            new File(Resources.getResource("turbineConfigurations/multipleClusters.yml").toURI()));
    assertThat(configuration.getClusters()).isEqualTo(ImmutableMap.of(
            "one", new YamlInstanceConfiguration.Cluster(
                    ImmutableSet.of(HostAndPort.fromParts("localhost", 1234), HostAndPort.fromParts("localhost", 5678)),
                    ImmutableSet.of("two")),
            "two", new YamlInstanceConfiguration.Cluster(
                    ImmutableSet.of(HostAndPort.fromParts("localhost", 4321), HostAndPort.fromParts("localhost", 9876)),
                    ImmutableSet.of("one")),
            "three", YamlInstanceConfiguration.Cluster.withClusters("one", "two")));
    assertThat(configuration.getAllInstances()).isEqualTo(
            ImmutableSet.of(
                    new Instance("localhost:1234", "one", true), new Instance("localhost:5678", "one", true),
                    new Instance("localhost:4321", "one", true), new Instance("localhost:9876", "one", true),
                    new Instance("localhost:4321", "two", true), new Instance("localhost:9876", "two", true),
                    new Instance("localhost:1234", "two", true), new Instance("localhost:5678", "two", true),
                    new Instance("localhost:4321", "three", true), new Instance("localhost:9876", "three", true),
                    new Instance("localhost:1234", "three", true), new Instance("localhost:5678", "three", true)));
}
 
Example 15
Source Project: nomulus   Source File: TimeOfYearTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_getInstancesInRange_closedOpen() {
  DateTime startDate = DateTime.parse("2012-05-01T00:00:00Z");
  DateTime endDate = DateTime.parse("2016-05-01T00:00:00Z");
  TimeOfYear timeOfYear = TimeOfYear.fromDateTime(DateTime.parse("2012-05-01T00:00:00Z"));
  ImmutableSet<DateTime> expected = ImmutableSet.of(
      DateTime.parse("2012-05-01T00:00:00Z"),
      DateTime.parse("2013-05-01T00:00:00Z"),
      DateTime.parse("2014-05-01T00:00:00Z"),
      DateTime.parse("2015-05-01T00:00:00Z"));
  assertThat(timeOfYear.getInstancesInRange(Range.closedOpen(startDate, endDate)))
      .containsExactlyElementsIn(expected);
}
 
Example 16
Source Project: presto   Source File: SymbolsExtractor.java    License: Apache License 2.0 5 votes vote down vote up
public static Set<Symbol> extractUnique(PlanNode node)
{
    ImmutableSet.Builder<Symbol> uniqueSymbols = ImmutableSet.builder();
    extractExpressions(node).forEach(expression -> uniqueSymbols.addAll(extractUnique(expression)));

    return uniqueSymbols.build();
}
 
Example 17
Source Project: arcusplatform   Source File: TestVoicePredicates.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsJammed() {
   Model m = new SimpleModel();
   assertFalse(VoicePredicates.isLockJammed(m));

   m.setAttribute(Capability.ATTR_CAPS, ImmutableSet.of(DoorLockCapability.NAMESPACE, DeviceAdvancedCapability.NAMESPACE));
   assertFalse(VoicePredicates.isLockJammed(m));

   m.setAttribute(DeviceAdvancedCapability.ATTR_ERRORS, ImmutableMap.of("some_error", "foo"));
   assertFalse(VoicePredicates.isLockJammed(m));

   m.setAttribute(DeviceAdvancedCapability.ATTR_ERRORS, ImmutableMap.of("WARN_JAM", "jammed"));
   assertTrue(VoicePredicates.isLockJammed(m));
}
 
Example 18
@Test
public void testBitIsSetFunction() throws Exception {
    final Set<String> setOfBits = ImmutableSet.of("UP", "PROMISCUOUS");

    final SchemaContext schemaContext = YangParserTestUtils.parseYangResources(BitIsSetXPathFunctionTest.class,
            "/yang-xpath-functions-test/bit-is-set-function/foo.yang");
    assertNotNull(schemaContext);

    final XPathSchemaContext jaxenSchemaContext = SCHEMA_CONTEXT_FACTORY.createContext(schemaContext);
    final XPathDocument jaxenDocument = jaxenSchemaContext.createDocument(buildMyContainerNode(setOfBits));

    final BiMap<String, QNameModule> converterBiMap = HashBiMap.create();
    converterBiMap.put("foo-prefix", FOO_MODULE);

    final NormalizedNodeContextSupport normalizedNodeContextSupport = NormalizedNodeContextSupport.create(
            (JaxenDocument) jaxenDocument, Maps.asConverter(converterBiMap));

    final NormalizedNodeContext normalizedNodeContext = normalizedNodeContextSupport.createContext(
            buildPathToFlagsLeafNode(setOfBits));

    final Function bitIsSetFunction = normalizedNodeContextSupport.getFunctionContext()
            .getFunction(null, null, "bit-is-set");
    boolean bitIsSetResult = (boolean) bitIsSetFunction.call(normalizedNodeContext, ImmutableList.of("UP"));
    assertTrue(bitIsSetResult);
    bitIsSetResult = (boolean) bitIsSetFunction.call(normalizedNodeContext, ImmutableList.of("PROMISCUOUS"));
    assertTrue(bitIsSetResult);
    bitIsSetResult = (boolean) bitIsSetFunction.call(normalizedNodeContext, ImmutableList.of("DISABLED"));
    assertFalse(bitIsSetResult);
}
 
Example 19
Source Project: buck   Source File: CxxIncludePaths.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Merge all the given {@link CxxIncludePaths}.
 *
 * <p>Combinines their path lists, deduping them (keeping the earlier of the repeated instance).
 */
public static CxxIncludePaths concat(Iterator<CxxIncludePaths> itemIter) {
  ImmutableSet.Builder<CxxHeaders> ipathBuilder = ImmutableSet.builder();
  ImmutableSet.Builder<FrameworkPath> fpathBuilder = ImmutableSet.builder();

  while (itemIter.hasNext()) {
    CxxIncludePaths item = itemIter.next();
    ipathBuilder.addAll(item.getIPaths());
    fpathBuilder.addAll(item.getFPaths());
  }

  return ImmutableCxxIncludePaths.of(ipathBuilder.build(), fpathBuilder.build());
}
 
Example 20
Source Project: buck   Source File: HybridGlobberTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void watchmanResultsAreReturnedIfTheyExist() throws Exception {
  WatchmanGlobber watchmanGlobber =
      newGlobber(Optional.of(ImmutableMap.of("files", ImmutableList.of("bar.txt", "foo.txt"))));
  globber = new HybridGlobber(nativeGlobber, watchmanGlobber);
  assertThat(
      globber.run(Collections.singleton("*.txt"), Collections.emptySet(), false),
      equalTo(ImmutableSet.of("bar.txt", "foo.txt")));
}
 
Example 21
Source Project: arcusplatform   Source File: SmartHomeSkillV3Handler.java    License: Apache License 2.0 5 votes vote down vote up
@Inject
public SmartHomeSkillV3Handler(
   ShsConfig config,
   PlatformMessageBus bus,
   @Named(VoiceBridgeConfig.NAME_EXECUTOR) ExecutorService executor,
   VoiceBridgeMetrics metrics,
   PlacePopulationCacheManager populationCacheMgr
) {
   this.config = config;
   this.executor = executor;
   this.busClient = new PlatformBusClient(bus, executor, ImmutableSet.of(AddressMatchers.equals(AlexaUtil.ADDRESS_BRIDGE)));
   this.metrics = metrics;
   this.populationCacheMgr = populationCacheMgr;
}
 
Example 22
Source Project: nomulus   Source File: ContactUpdateFlowTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFailure_serverUpdateProhibited() throws Exception {
  persistResource(
      newContactResource(getUniqueIdFromCommand())
          .asBuilder()
          .setStatusValues(ImmutableSet.of(StatusValue.SERVER_UPDATE_PROHIBITED))
          .build());
  ResourceStatusProhibitsOperationException thrown =
      assertThrows(ResourceStatusProhibitsOperationException.class, this::runFlow);
  assertThat(thrown).hasMessageThat().contains("serverUpdateProhibited");
  assertAboutEppExceptions().that(thrown).marshalsToXml();
}
 
Example 23
Source Project: bazel   Source File: BuildView.java    License: Apache License 2.0 5 votes vote down vote up
private static Pair<ImmutableSet<ConfiguredTarget>, ImmutableSet<ConfiguredTarget>> collectTests(
    TopLevelArtifactContext topLevelOptions,
    @Nullable Iterable<ConfiguredTarget> allTestTargets,
    PackageManager packageManager,
    ExtendedEventHandler eventHandler)
    throws InterruptedException {
  Set<String> outputGroups = topLevelOptions.outputGroups();
  if (!outputGroups.contains(OutputGroupInfo.FILES_TO_COMPILE)
      && !outputGroups.contains(OutputGroupInfo.COMPILATION_PREREQUISITES)
      && allTestTargets != null) {
    final boolean isExclusive = topLevelOptions.runTestsExclusively();
    ImmutableSet.Builder<ConfiguredTarget> targetsToTest = ImmutableSet.builder();
    ImmutableSet.Builder<ConfiguredTarget> targetsToTestExclusive = ImmutableSet.builder();
    for (ConfiguredTarget configuredTarget : allTestTargets) {
      Target target = null;
      try {
        target = packageManager.getTarget(eventHandler, configuredTarget.getLabel());
      } catch (NoSuchTargetException | NoSuchPackageException e) {
        eventHandler.handle(Event.error("Failed to get target when scheduling tests"));
        continue;
      }
      if (target instanceof Rule) {
        if (isExclusive || TargetUtils.isExclusiveTestRule((Rule) target)) {
          targetsToTestExclusive.add(configuredTarget);
        } else {
          targetsToTest.add(configuredTarget);
        }
      }
    }
    return Pair.of(targetsToTest.build(), targetsToTestExclusive.build());
  } else {
    return Pair.of(ImmutableSet.of(), ImmutableSet.of());
  }
}
 
Example 24
Source Project: Strata   Source File: Swap.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ResolvedSwap resolve(ReferenceData refData) {
  // avoid streams as profiling showed a hotspot
  // most efficient to loop around legs once
  ImmutableList.Builder<ResolvedSwapLeg> resolvedLegs = ImmutableList.builder();
  ImmutableSet.Builder<Currency> currencies = ImmutableSet.builder();
  ImmutableSet.Builder<Index> indices = ImmutableSet.builder();
  for (SwapLeg leg : legs) {
    ResolvedSwapLeg resolvedLeg = leg.resolve(refData);
    resolvedLegs.add(resolvedLeg);
    currencies.add(resolvedLeg.getCurrency());
    leg.collectIndices(indices);
  }
  return new ResolvedSwap(resolvedLegs.build(), currencies.build(), indices.build());
}
 
Example 25
Set<String> getConflictingContainerNames(String output) {
    ImmutableSet.Builder<String> builder = ImmutableSet.builder();
    Matcher matcher = NAME_CONFLICT_PATTERN.matcher(output);
    while (matcher.find()) {
        builder.add(matcher.group(1));
    }
    return builder.build();
}
 
Example 26
Source Project: buck   Source File: MorePosixFilePermissions.java    License: Apache License 2.0 5 votes vote down vote up
/** Convert a unix bit representation (e.g. 0644) into a set of posix file permissions. */
public static ImmutableSet<PosixFilePermission> fromMode(long mode) {
  ImmutableSet.Builder<PosixFilePermission> permissions = ImmutableSet.builder();

  for (int index = 0; index < ORDERED_PERMISSIONS.size(); index++) {
    if ((mode & (1 << index)) != 0) {
      permissions.add(ORDERED_PERMISSIONS.get(index));
    }
  }

  return permissions.build();
}
 
Example 27
Source Project: armeria   Source File: GrpcServiceBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the {@link SerializationFormat}s supported by this server. If not set, defaults to supporting binary
 * protobuf formats. JSON formats are currently very inefficient and not recommended for use in production.
 *
 * <p>TODO(anuraaga): Use faster JSON marshalling.
 */
public GrpcServiceBuilder supportedSerializationFormats(Iterable<SerializationFormat> formats) {
    requireNonNull(formats, "formats");
    for (SerializationFormat format : formats) {
        if (!GrpcSerializationFormats.isGrpc(format)) {
            throw new IllegalArgumentException("Not a gRPC serialization format: " + format);
        }
    }
    supportedSerializationFormats = ImmutableSet.copyOf(formats);
    return this;
}
 
Example 28
Source Project: Strata   Source File: FxSingleTradeCalculationFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FunctionRequirements requirements(
    FxSingleTrade trade,
    Set<Measure> measures,
    CalculationParameters parameters,
    ReferenceData refData) {

  // extract data from product
  ImmutableSet<Currency> currencies = trade.getProduct().getCurrencyPair().toSet();

  // use lookup to build requirements
  RatesMarketDataLookup ratesLookup = parameters.getParameter(RatesMarketDataLookup.class);
  return ratesLookup.requirements(currencies);
}
 
Example 29
Source Project: onos   Source File: HostNib.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the set of hosts whose most recent location is the specified
 * connection point.
 *
 * @param connectPoint connection point
 * @return set of hosts connected to the connection point
 */
public Set<Host> getConnectedHosts(ConnectPoint connectPoint) {
    // TODO extend this method to support matching on auxLocations as well
    Set<Host> connectedHosts = hosts.stream()
            .filter(host -> host.locations().contains(connectPoint))
            .collect(Collectors.toSet());
    return connectedHosts != null ? ImmutableSet.copyOf(connectedHosts) : ImmutableSet.of();
}
 
Example 30
Source Project: onos   Source File: EdgeManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<ConnectPoint> getEdgePoints(DeviceId deviceId) {
    checkPermission(TOPOLOGY_READ);
    ImmutableSet.Builder<ConnectPoint> builder = ImmutableSet.builder();
    Set<ConnectPoint> set = connectionPoints.get(deviceId);
    if (set != null) {
        set.forEach(builder::add);
    }
    return builder.build();
}