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

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

源代码1 项目: onos   文件: PathPainterTopovMessageHandler.java
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();

}
 
@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));
}
 
源代码3 项目: holdmail   文件: EntityPersistenceTest.java
@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)));

}
 
源代码4 项目: arcusplatform   文件: TestTransformers.java
@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());
}
 
源代码5 项目: hugegraph   文件: UsersTest.java
@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());
}
 
源代码6 项目: buck   文件: BuildCommand.java
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()));
}
 
源代码7 项目: nomulus   文件: DomainUpdateFlowTest.java
@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);
}
 
源代码8 项目: bazel   文件: RequiredConfigFragmentsTest.java
@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");
}
 
源代码9 项目: buck   文件: ConfigSettingSelectableTest.java
@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));
}
 
源代码10 项目: samza   文件: TestSSPMetadataCache.java
/**
 * 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);
}
 
源代码11 项目: nomulus   文件: DomainBase.java
@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();
}
 
源代码12 项目: ScoreboardStats   文件: Settings.java
/**
 * 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("%", "");
}
 
源代码13 项目: hadoop   文件: TestCommonNodeLabelsManager.java
@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"));
}
 
源代码14 项目: breakerbox   文件: YamlInstanceConfigurationTest.java
@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)));
}
 
源代码15 项目: nomulus   文件: TimeOfYearTest.java
@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);
}
 
源代码16 项目: presto   文件: SymbolsExtractor.java
public static Set<Symbol> extractUnique(PlanNode node)
{
    ImmutableSet.Builder<Symbol> uniqueSymbols = ImmutableSet.builder();
    extractExpressions(node).forEach(expression -> uniqueSymbols.addAll(extractUnique(expression)));

    return uniqueSymbols.build();
}
 
源代码17 项目: arcusplatform   文件: TestVoicePredicates.java
@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));
}
 
源代码18 项目: yangtools   文件: BitIsSetXPathFunctionTest.java
@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);
}
 
源代码19 项目: buck   文件: CxxIncludePaths.java
/**
 * 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());
}
 
源代码20 项目: buck   文件: HybridGlobberTest.java
@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")));
}
 
源代码21 项目: arcusplatform   文件: SmartHomeSkillV3Handler.java
@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;
}
 
源代码22 项目: nomulus   文件: ContactUpdateFlowTest.java
@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();
}
 
源代码23 项目: bazel   文件: BuildView.java
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());
  }
}
 
源代码24 项目: Strata   文件: Swap.java
@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());
}
 
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();
}
 
源代码26 项目: buck   文件: MorePosixFilePermissions.java
/** 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();
}
 
源代码27 项目: armeria   文件: GrpcServiceBuilder.java
/**
 * 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;
}
 
源代码28 项目: Strata   文件: FxSingleTradeCalculationFunction.java
@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);
}
 
源代码29 项目: onos   文件: HostNib.java
/**
 * 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();
}
 
源代码30 项目: onos   文件: EdgeManager.java
@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();
}
 
 同包方法