com.google.common.collect.ImmutableSet Java Examples

The following examples show how to use com.google.common.collect.ImmutableSet. 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 check out the related API usage on the sidebar.
Example #1
Source File: DomainUpdateFlowTest.java    From nomulus with 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 #2
Source File: Settings.java    From ScoreboardStats with 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 #3
Source File: DomainBase.java    From nomulus with 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 #4
Source File: ConflictingContainerRemovingDockerComposeShould.java    From docker-compose-rule with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: TestSSPMetadataCache.java    From samza with 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 #6
Source File: PathPainterTopovMessageHandler.java    From onos with 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 #7
Source File: EntityPersistenceTest.java    From holdmail with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSaveRecipients() {

    MessageEntity entity = buildBasicEntity();

    String email1 = "[email protected]";
    String email2 = "derp@somedomaincom";

    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 #8
Source File: TestTransformers.java    From arcusplatform with 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 #9
Source File: RequiredConfigFragmentsTest.java    From bazel with 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 #10
Source File: YamlInstanceConfigurationTest.java    From breakerbox with 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 #11
Source File: BuildCommand.java    From buck with 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 #12
Source File: TestCommonNodeLabelsManager.java    From hadoop with 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 #13
Source File: UsersTest.java    From hugegraph with 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 #14
Source File: ConfigSettingSelectableTest.java    From buck with 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 #15
Source File: BiCacheTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Test
public void testIdenticalKeysDifferentValues() {
  biCache.put(KEY_1, 1);
  biCache.put(KEY_1, 2);
  assertEquals(Optional.of(2), biCache.get(KEY_1));
  assertEquals(ImmutableSet.of(), biCache.getByValue(1));
  assertEquals(ImmutableSet.of(KEY_1), biCache.getByValue(2));
  assertEquals(1L, statsProvider.getLongValue(CACHE_SIZE_STAT_NAME));
}
 
Example #16
Source File: GenruleBinary.java    From buck with Apache License 2.0 5 votes vote down vote up
protected GenruleBinary(
    BuildTarget buildTarget,
    ProjectFilesystem projectFilesystem,
    SandboxExecutionStrategy sandboxExecutionStrategy,
    BuildRuleResolver resolver,
    SourceSet srcs,
    Optional<Arg> cmd,
    Optional<Arg> bash,
    Optional<Arg> cmdExe,
    Optional<String> type,
    Optional<String> out,
    Optional<ImmutableMap<String, ImmutableSet<String>>> outs,
    boolean isCacheable,
    Optional<String> environmentExpansionSeparator,
    Optional<AndroidTools> androidTools,
    boolean executeRemotely) {
  super(
      buildTarget,
      projectFilesystem,
      resolver,
      sandboxExecutionStrategy,
      srcs,
      cmd,
      bash,
      cmdExe,
      type,
      out,
      outs,
      false,
      isCacheable,
      environmentExpansionSeparator,
      androidTools,
      executeRemotely);
}
 
Example #17
Source File: HostNib.java    From onos with 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 #18
Source File: OpenstackSwitchingIcmpHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private Set<Subnet> routableSubnets(Router osRouter, String osSubnetId) {
    Set<Subnet> osSubnets = osRouterService.routerInterfaces(osRouter.getId())
            .stream()
            .filter(iface -> !Objects.equals(iface.getSubnetId(), osSubnetId))
            .map(iface -> osNetworkService.subnet(iface.getSubnetId()))
            .collect(Collectors.toSet());
    return ImmutableSet.copyOf(osSubnets);
}
 
Example #19
Source File: DescriptorValidatorImpl.java    From cm_ext with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> validate(T descriptor) {
  Set<ConstraintViolation<T>> constraintViolations;
  constraintViolations = getViolations(descriptor);

  ImmutableSet.Builder<String> violations = ImmutableSet.builder();
  for (ConstraintViolation<T> violation : constraintViolations) {
    String message = violation.getMessage();
    String relativePath = violation.getPropertyPath().toString();
    violations.add(String.format(ERROR_FORMAT, errorPrefix, relativePath, message));
  }
  return violations.build();
}
 
Example #20
Source File: ToInterfaceLinkLocationSpecifierTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
/** Do we resolve non empty sets properly? */
@Test
public void resolveNonEmptySet() {
  LocationSpecifier inner =
      new MockLocationSpecifier(
          ImmutableSet.of(
              new InterfaceLocation("foo1", "bar1"), new InterfaceLinkLocation("foo2", "bar2")));
  assertThat(
      new ToInterfaceLinkLocationSpecifier(inner).resolve(_mockContext),
      equalTo(
          ImmutableSet.of(
              new InterfaceLinkLocation("foo1", "bar1"),
              new InterfaceLinkLocation("foo2", "bar2"))));
}
 
Example #21
Source File: EdgesAnswererTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testVxlanEdgeToRows() {
  NetworkConfigurations nc = buildVxlanNetworkConfigurations();
  Map<String, Configuration> configurations = nc.getMap();
  Set<String> includeNodes = configurations.keySet();
  Set<String> includeRemoteNodes = configurations.keySet();
  VxlanNode node1 = VxlanNode.builder().setHostname(VXLAN_NODE1).setVni(VXLAN_VNI).build();
  VxlanNode node2 = VxlanNode.builder().setHostname(VXLAN_NODE2).setVni(VXLAN_VNI).build();

  // no filter
  assertThat(
      vxlanEdgeToRows(nc, includeNodes, includeRemoteNodes, EndpointPair.unordered(node1, node2))
          .collect(ImmutableList.toImmutableList()),
      containsInAnyOrder(vxlanEdgeToRow(nc, node1, node2), vxlanEdgeToRow(nc, node2, node1)));
  // only node1 in node position
  assertThat(
      vxlanEdgeToRows(
              nc,
              ImmutableSet.of(VXLAN_NODE1),
              includeRemoteNodes,
              EndpointPair.unordered(node1, node2))
          .collect(ImmutableList.toImmutableList()),
      containsInAnyOrder(vxlanEdgeToRow(nc, node1, node2)));
  // only node1 in remoteNode position
  assertThat(
      vxlanEdgeToRows(
              nc,
              includeNodes,
              ImmutableSet.of(VXLAN_NODE1),
              EndpointPair.unordered(node1, node2))
          .collect(ImmutableList.toImmutableList()),
      containsInAnyOrder(vxlanEdgeToRow(nc, node2, node1)));
}
 
Example #22
Source File: ReadLockIT.java    From fluo with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteCausesReadLockToFail() throws Exception {
  try (Transaction tx = client.newTransaction()) {
    setAlias(tx, "node1", "bob");
    setAlias(tx, "node2", "joe");
    tx.commit();
  }

  TestTransaction tx1 = new TestTransaction(env);
  setAlias(tx1, "node2", "jojo");

  TestTransaction tx2 = new TestTransaction(env);

  addEdge(tx2, "node1", "node2");

  tx1.commit();
  tx1.close();

  Assert.assertEquals(0, getDerivedEdges().size());

  try {
    tx2.commit();
    Assert.fail("Expected exception");
  } catch (CommitException ce) {
    // expected
  }

  // ensure the failed read lock on node1 is cleaned up
  try (Transaction tx = client.newTransaction()) {
    setAlias(tx, "node1", "fred");
    tx.commit();
  }

  try (Transaction tx = client.newTransaction()) {
    addEdge(tx, "node1", "node2");
    tx.commit();
  }

  Assert.assertEquals(ImmutableSet.of("fred:jojo", "jojo:fred"), getDerivedEdges());
}
 
Example #23
Source File: TargetSpecResolverTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveTargetSpecsPreservesOrder() throws Exception {
  BuildTarget foo = BuildTargetFactory.newInstance("//foo:foo");
  Path buckFile = cellRoot.resolve("foo/BUCK");
  Files.createDirectories(buckFile.getParent());
  Files.write(buckFile, "genrule(name='foo', out='foo', cmd='foo')".getBytes(UTF_8));

  BuildTarget bar = BuildTargetFactory.newInstance("//bar:bar");
  buckFile = cellRoot.resolve("bar/BUCK");
  Files.createDirectories(buckFile.getParent());
  Files.write(buckFile, "genrule(name='bar', out='bar', cmd='bar')".getBytes(UTF_8));

  ImmutableList<ImmutableSet<BuildTarget>> targets =
      resolve(
          ImmutableList.of(
              TargetNodePredicateSpec.of(
                  BuildFileSpec.fromRecursivePath(
                      CellRelativePath.of(
                          cell.getRootCell().getCanonicalName(), ForwardRelativePath.of("bar")))),
              TargetNodePredicateSpec.of(
                  BuildFileSpec.fromRecursivePath(
                      CellRelativePath.of(
                          cell.getRootCell().getCanonicalName(),
                          ForwardRelativePath.of("foo"))))));
  assertThat(targets, equalTo(ImmutableList.of(ImmutableSet.of(bar), ImmutableSet.of(foo))));

  targets =
      resolve(
          ImmutableList.of(
              TargetNodePredicateSpec.of(
                  BuildFileSpec.fromRecursivePath(
                      CellRelativePath.of(
                          cell.getRootCell().getCanonicalName(), ForwardRelativePath.of("foo")))),
              TargetNodePredicateSpec.of(
                  BuildFileSpec.fromRecursivePath(
                      CellRelativePath.of(
                          cell.getRootCell().getCanonicalName(),
                          ForwardRelativePath.of("bar"))))));
  assertThat(targets, equalTo(ImmutableList.of(ImmutableSet.of(foo), ImmutableSet.of(bar))));
}
 
Example #24
Source File: MorePosixFilePermissions.java    From buck with 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 #25
Source File: JsonToRowCast.java    From presto with Apache License 2.0 5 votes vote down vote up
private JsonToRowCast()
{
    super(OperatorType.CAST,
            ImmutableList.of(
                    // this is technically a recursive constraint for cast, but TypeRegistry.canCast has explicit handling for json to row cast
                    new TypeVariableConstraint("T", false, false, "row", ImmutableSet.of(), ImmutableSet.of(JSON.getTypeSignature()))),
            ImmutableList.of(),
            new TypeSignature("T"),
            ImmutableList.of(JSON.getTypeSignature()),
            true);
}
 
Example #26
Source File: FxSingleTradeCalculationFunction.java    From Strata with 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 #27
Source File: EdgeManager.java    From onos with 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();
}
 
Example #28
Source File: GrpcServiceBuilder.java    From armeria with 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 #29
Source File: SetMessagesUpdateProcessor.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void addMessageIdNotFoundToResponse(MessageId messageId, SetMessagesResponse.Builder builder) {
    builder.notUpdated(ImmutableMap.of(messageId,
            SetError.builder()
                    .type(SetError.Type.NOT_FOUND)
                    .properties(ImmutableSet.of(MessageProperties.MessageProperty.id))
                    .description("message not found")
                    .build()));
}
 
Example #30
Source File: YangInstanceIdentifierTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAugmentationIdentifier() {

    final AugmentationIdentifier node1 = new AugmentationIdentifier(ImmutableSet.of(NODENAME1, NODENAME2));
    assertEquals("getPossibleChildNames", ImmutableSet.of(NODENAME1, NODENAME2), node1.getPossibleChildNames());
    final AugmentationIdentifier node2 = new AugmentationIdentifier(ImmutableSet.of(NODENAME2, NODENAME1));
    final AugmentationIdentifier node3 = new AugmentationIdentifier(ImmutableSet.of(NODENAME1, NODENAME3));
    final AugmentationIdentifier node4 = new AugmentationIdentifier(ImmutableSet.of(NODENAME1, NODENAME2,
                NODENAME3));
    final NodeIdentifier node5 = new NodeIdentifier(NODENAME3);

    assertEquals("hashCode", node1.hashCode(), node2.hashCode());

    assertTrue("equals", node1.equals(node1));
    assertTrue("equals", node1.equals(node2));
    assertFalse("equals", node1.equals(node3));
    assertFalse("equals", node1.equals(new AugmentationIdentifier(ImmutableSet.of(NODENAME1))));
    assertFalse("equals", node1.equals(new Object()));

    assertEquals("compareTo", -1, node1.compareTo(node5));
    assertEquals("compareTo", 0, node1.compareTo(node2));
    assertEquals("compareTo", 0, node1.compareTo(node2));
    assertEquals("compareTo", 1, node1.compareTo(node4));
    assertEquals("compareTo", -1, node4.compareTo(node1));

    // for code coverage
    assertNotNull(node1.toString());
    assertNotNull(node1.toRelativeString(node5));
}