Java Code Examples for com.google.common.collect.Iterables#getOnlyElement()

The following examples show how to use com.google.common.collect.Iterables#getOnlyElement() . 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: ApiConfigAnnotationReaderTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testParameterAnnotations() throws Exception {
  @Api
  class Endpoint {
    @SuppressWarnings("unused")
    public void method(@Named("foo") @Nullable @DefaultValue("4") int foo) {}
  }

  ApiConfig config = createConfig(Endpoint.class);
  annotationReader.loadEndpointClass(serviceContext, Endpoint.class, config);
  annotationReader.loadEndpointMethods(serviceContext, Endpoint.class,
      config.getApiClassConfig().getMethods());

  ApiMethodConfig methodConfig =
      Iterables.getOnlyElement(config.getApiClassConfig().getMethods().values());
  ApiParameterConfig parameterConfig =
      Iterables.getOnlyElement(methodConfig.getParameterConfigs());
  validateParameter(parameterConfig, "foo", true, "4", int.class, null, int.class);
}
 
Example 2
Source File: ErrorCodes.java    From selenium with Apache License 2.0 6 votes vote down vote up
public String toState(Integer status) {
  if (status == null) {
    return toState(UNHANDLED_ERROR);
  }

  if (SUCCESS == status) {
    return SUCCESS_STRING;
  }

  Set<String> possibleMatches = KNOWN_ERRORS.stream()
    .filter(knownError -> knownError.getJsonCode() == status)
    .filter(KnownError::isCanonicalForW3C)
    .map(KnownError::getW3cCode)
    .collect(Collectors.toSet());

  return Iterables.getOnlyElement(possibleMatches, "unhandled error");
}
 
Example 3
Source File: GlobTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void emptyIncludeListIsReportedAsAWarning() throws Exception {
  Path buildFile = root.getChild("BUCK");
  FileSystemUtils.writeContentAsLatin1(buildFile, "txts = glob([])");
  assertThat(
      assertEvaluate(buildFile).moduleLookup("txts"),
      equalTo(SkylarkList.createImmutable(ImmutableList.of())));
  Event event = Iterables.getOnlyElement(eventHandler);
  assertThat(event.getKind(), is(EventKind.WARNING));
  assertThat(event.getLocation(), notNullValue());
  assertThat(
      event.getMessage(),
      is(
          "glob's 'include' attribute is empty. "
              + "Such calls are expensive and unnecessary. "
              + "Please use an empty list ([]) instead."));
}
 
Example 4
Source File: RuntimeEntityResolver.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static ClassMemberKey<?> restoreMissingDescriptor(
    ClassMemberKey<?> classMemberKey,
    int round,
    Table<Integer, ClassMemberKey<?>, Set<ClassMemberKey<?>>> missingDescriptorLookupRepo) {
  Set<ClassMemberKey<?>> restoredClassMemberKey =
      missingDescriptorLookupRepo.get(round, classMemberKey);
  if (restoredClassMemberKey == null || restoredClassMemberKey.isEmpty()) {
    throw new IllegalStateException(
        String.format(
            "Unable to find class member (%s). Please check its presence.", classMemberKey));
  } else if (restoredClassMemberKey.size() > 1) {
    throw new IllegalStateException(
        String.format(
            "Class Member (%s) has same-name overloaded members: (%s) \n"
                + "Please specify a descriptor to disambiguate overloaded method request.",
            classMemberKey, restoredClassMemberKey));
  }
  return Iterables.getOnlyElement(restoredClassMemberKey);
}
 
Example 5
Source File: LatticeSuggesterTest.java    From Quicksql with MIT License 6 votes vote down vote up
@Test public void testExpressionInJoin() throws Exception {
  final Tester t = new Tester().foodmart().withEvolve(true);

  final String q0 = "select\n"
      + "  \"fname\" || ' ' || \"lname\" as \"full_name\",\n"
      + "  count(*) as c,\n"
      + "  avg(\"total_children\" - \"num_children_at_home\")\n"
      + "from \"customer\" join \"sales_fact_1997\" using (\"customer_id\")\n"
      + "group by \"fname\", \"lname\"";
  final String l0 = "sales_fact_1997 (customer:customer_id)"
      + ":[COUNT(), AVG($f2)]";
  t.addQuery(q0);
  assertThat(t.s.latticeMap.size(), is(1));
  assertThat(Iterables.getOnlyElement(t.s.latticeMap.keySet()),
      is(l0));
  final Lattice lattice = Iterables.getOnlyElement(t.s.latticeMap.values());
  final List<Lattice.DerivedColumn> derivedColumns = lattice.columns.stream()
      .filter(c -> c instanceof Lattice.DerivedColumn)
      .map(c -> (Lattice.DerivedColumn) c)
      .collect(Collectors.toList());
  assertThat(derivedColumns.size(), is(2));
  final List<String> tables = ImmutableList.of("customer");
  assertThat(derivedColumns.get(0).tables, is(tables));
  assertThat(derivedColumns.get(1).tables, is(tables));
}
 
Example 6
Source File: EntitiesYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testEntitySpecInUnmatchedConfig() throws Exception {
    String yaml =
            "services:\n"+
            "- serviceType: org.apache.brooklyn.core.test.entity.TestEntity\n"+
            "  brooklyn.config:\n"+
            "   key.does.not.match:\n"+
            "     $brooklyn:entitySpec:\n"+
            "       type: org.apache.brooklyn.core.test.entity.TestEntity\n"+
            "       brooklyn.config:\n"+
            "         test.confName: inchildspec\n";
    
    Application app = (Application) createStartWaitAndLogApplication(yaml);
    TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());
    Object entitySpecOrSupplier = entity.config().getBag().getStringKey("key.does.not.match");
    if (BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_PERSIST_ENTITY_SPEC_AS_SUPPLIER)) {
        Asserts.assertInstanceOf(entitySpecOrSupplier, DeferredSupplier.class);
        entitySpecOrSupplier = entity.config().get(ConfigKeys.newConfigKey(Object.class, "key.does.not.match"));
    }
    EntitySpec<?> entitySpec = (EntitySpec<?>) entitySpecOrSupplier;
    assertEquals(entitySpec.getType(), TestEntity.class);
    assertEquals(entitySpec.getConfig(), ImmutableMap.of(TestEntity.CONF_NAME, "inchildspec"));
}
 
Example 7
Source File: CatalogOsgiYamlTemplateTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddCatalogItemOsgi() throws Exception {
    RegisteredType item = makeItem("t1", SIMPLE_ENTITY_TYPE);
    Assert.assertTrue(RegisteredTypePredicates.IS_APPLICATION.apply(item), "item: "+item);
    String yaml = RegisteredTypes.getImplementationDataStringForSpec(item);
    Assert.assertTrue(yaml.indexOf("sample comment")>=0,
        "YAML did not include original comments; it was:\n"+yaml);
    Assert.assertFalse(yaml.indexOf("description")>=0,
        "YAML included metadata which should have been excluded; it was:\n"+yaml);

    // Confirm can deploy an app using this template catalog item
    Entity app = createAndStartApplication(
            "services:",
            "- type: t1");
    waitForApplicationTasks(app);
    
    Entity entity = Iterables.getOnlyElement(app.getChildren());
    assertEquals(entity.getEntityType().getName(), SIMPLE_ENTITY_TYPE);
    
    deleteCatalogEntity("t1");
}
 
Example 8
Source File: ActionTemplateExpansionFunctionTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void canGenerateOutputUnderAdditionalDeclaredTree() throws Exception {
  SpecialArtifact inputTree = createAndPopulateTreeArtifact("input", "child");
  SpecialArtifact outputTree = createTreeArtifact("output");
  SpecialArtifact additionalOutputTree = createTreeArtifact("additional_output");

  ActionTemplate<DummyAction> template =
      new TestActionTemplate(inputTree, outputTree) {
        @Override
        public ImmutableList<DummyAction> generateActionsForInputArtifacts(
            ImmutableSet<TreeFileArtifact> inputTreeFileArtifacts,
            ActionLookupKey artifactOwner) {
          TreeFileArtifact input = Iterables.getOnlyElement(inputTreeFileArtifacts);
          return ImmutableList.of(
              new DummyAction(
                  input,
                  TreeFileArtifact.createTemplateExpansionOutput(
                      outputTree, "child", artifactOwner)),
              new DummyAction(
                  input,
                  TreeFileArtifact.createTemplateExpansionOutput(
                      additionalOutputTree, "additional_child", artifactOwner)));
        }

        @Override
        public ImmutableSet<Artifact> getOutputs() {
          return ImmutableSet.of(outputTree, additionalOutputTree);
        }
      };

  evaluate(template);
}
 
Example 9
Source File: J2clTestingProcessingStep.java    From j2cl with Apache License 2.0 5 votes vote down vote up
@Override
public Set<Element> process(
    SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) {
  Element value = Iterables.getOnlyElement(elementsByAnnotation.get(J2clTestInput.class));
  String className =
      MoreApt.getClassNameFromAnnotation(value, J2clTestInput.class, "value").get();
  handleClass(className);
  return ImmutableSet.of();
}
 
Example 10
Source File: MetricNamePrefixedWithServiceNameValidatorTest.java    From cm_ext with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmptyName() {
  setName("");
  List<ConstraintViolation<Object>> validations =
      validator.validate(context, metric, root);
  Assert.assertFalse(validations.isEmpty());
  ConstraintViolation<Object> validation = Iterables.getOnlyElement(
      validations);
  Assert.assertTrue(validation.toString(),
                    validation.getMessage().contains(
                     "does not start with the service name"));
  String path = validation.getPropertyPath().toString();
  Assert.assertEquals(String.format("%s.name", SERVICE_NAME), path);
}
 
Example 11
Source File: KubernetesLocationYamlLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups = {"Live"})
public void testNetcatServer() throws Exception {
    // Runs as root user (hence not `sudo yum install ...`)
    // breaks if shell.env uses attributeWhenReady, so not doing that - see testNetcatServerWithDslInShellEnv()
    String yaml = Joiner.on("\n").join(
            locationYaml,
            "services:",
            "  - type: " + VanillaSoftwareProcess.class.getName(),
            "    brooklyn.parameters:",
            "      - name: netcat.port",
            "        type: port",
            "        default: 8081",
            "    brooklyn.config:",
            "      install.command: |",
            "        yum install -y nc",
            "      launch.command: |",
            "        echo $MESSAGE | nc -l $NETCAT_PORT &",
            "        echo $! > $PID_FILE",
            "      shell.env:",
            "        MESSAGE: mymessage",
            "        NETCAT_PORT: $brooklyn:attributeWhenReady(\"netcat.port\")",
            "    brooklyn.enrichers:",
            "      - type: " + OnPublicNetworkEnricher.class.getName(),
            "        brooklyn.config:",
            "          " + OnPublicNetworkEnricher.SENSORS.getName() + ":",
            "            - netcat.port");

    Entity app = createStartWaitAndLogApplication(yaml);
    VanillaSoftwareProcess entity = Iterables.getOnlyElement(Entities.descendantsAndSelf(app, VanillaSoftwareProcess.class));

    String publicMapped = assertAttributeEventuallyNonNull(entity, Sensors.newStringSensor("netcat.endpoint.mapped.public"));
    HostAndPort publicPort = HostAndPort.fromString(publicMapped);

    assertTrue(Networking.isReachable(publicPort), "publicPort=" + publicPort);
}
 
Example 12
Source File: CatalogYamlEntityTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testLaunchApplicationChildWithCatalogReferencingOtherCatalog() throws Exception {
    String referencedSymbolicName = "my.catalog.app.id.child.referenced";
    String referrerSymbolicName = "my.catalog.app.id.child.referring";

    addCatalogEntity(IdAndVersion.of(referencedSymbolicName, TEST_VERSION), TestEntity.class.getName());

    addCatalogItems(
            "brooklyn.catalog:",
            "  id: " + referrerSymbolicName,
            "  version: " + TEST_VERSION,
            "  itemType: entity",
            "  item:",
            "    services:",
            "    - type: " + BasicEntity.class.getName(),
            "      brooklyn.children:",
            "      - type: " + ver(referencedSymbolicName, TEST_VERSION));

    Entity app = createAndStartApplication(
            "services:",
            "- type: "+BasicEntity.class.getName(),
            "  brooklyn.children:",
            "  - type: " + ver(referrerSymbolicName));

    Entity child = Iterables.getOnlyElement(app.getChildren());
    assertEquals(child.getEntityType().getName(), BasicEntity.class.getName());
    Entity grandChild = Iterables.getOnlyElement(child.getChildren());
    assertEquals(grandChild.getEntityType().getName(), BasicEntity.class.getName());
    Entity grandGrandChild = Iterables.getOnlyElement(grandChild.getChildren());
    assertEquals(grandGrandChild.getEntityType().getName(), TestEntity.class.getName());

    deleteCatalogEntity(referencedSymbolicName);
    deleteCatalogEntity(referrerSymbolicName);
}
 
Example 13
Source File: ConfigParametersYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigParameterConstraintParsing() throws Exception {
    addCatalogItems(
            "brooklyn.catalog:",
            "  itemType: entity",
            "  items:",
            "  - id: entity-with-keys",
            "    item:",
            "      type: "+TestEntity.class.getName(),
            "      brooklyn.parameters:",
            "      - name: testRequired",
            "        type: String",
            "        constraints:",
            "        - or:",
            "           - regex: val1",
            "           - regex: val2");
    
    String yaml = Joiner.on("\n").join(
            "services:",
            "- type: entity-with-keys",
            "  brooklyn.config:",
            "    testRequired: val1");

    Entity app = createStartWaitAndLogApplication(yaml);
    TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());
    assertKeyEquals(entity, "testRequired", null, String.class, null, "val1");
    
    Predicate<?> constraint = entity.getEntityType().getConfigKey("testRequired").getConstraint();
    assertEquals(constraint.toString(), "Predicates.or(matchesRegex(\"val1\"),matchesRegex(\"val2\"))");

    // Rebind, and then check again that the config key is listed
    Entity newApp = rebind();
    TestEntity newEntity = (TestEntity) Iterables.getOnlyElement(newApp.getChildren());
    assertKeyEquals(newEntity, "testRequired", null, String.class, null, "val1");
    
    Predicate<?> newConstraint = newEntity.getEntityType().getConfigKey("testRequired").getConstraint();
    assertEquals(newConstraint.toString(), "Predicates.or(matchesRegex(\"val1\"),matchesRegex(\"val2\"))");
}
 
Example 14
Source File: CatalogYamlEntityTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testLaunchApplicationReferencingCatalog() throws Exception {
    String symbolicName = "myitem";
    addCatalogEntity(IdAndVersion.of(symbolicName, TEST_VERSION), TestEntity.class.getName());

    Entity app = createAndStartApplication(
            "services:",
            "- type: "+ver(symbolicName, TEST_VERSION));

    Entity entity = Iterables.getOnlyElement(app.getChildren());
    assertEquals(entity.getEntityType().getName(), TestEntity.class.getName());

    deleteCatalogEntity(symbolicName);
}
 
Example 15
Source File: A_ModuleGenerator.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
@Test
public void createsClassPathEntryForResolvedDependency() throws MojoExecutionException {
    addResolvedArtifact(mavenProject);

    Iterable<Module> modules = objectUnderTest.getModulesFor(singleton(mavenProject));

    assertThat(modules, is(Matchers.<Module>iterableWithSize(1)));
    Module module = Iterables.getOnlyElement(modules);
    assertThat(module.getClassPath(), is(Matchers.<File>iterableWithSize(1)));
}
 
Example 16
Source File: ExtensionTest.java    From auto with Apache License 2.0 4 votes vote down vote up
@Test
public void oddBuilderContext() {
  JavaFileObject autoValueClass = JavaFileObjects.forSourceLines(
      "foo.bar.Baz",
      "package foo.bar;",
      "",
      "import com.google.auto.value.AutoValue;",
      "import com.google.common.collect.ImmutableList;",
      "",
      "@AutoValue",
      "abstract class Baz {",
      "  abstract String string();",
      "",
      "  @AutoValue.Builder",
      "  abstract static class Builder {",
      "    abstract Builder setString(String x);",
      "    abstract Baz oddBuild();",
      "    Baz build(int butNotReallyBecauseOfThisParameter) {",
      "      return null;",
      "    }",
      "  }",
      "}");
  ContextChecker checker =
      context -> {
        assertThat(context.builder()).isPresent();
        BuilderContext builderContext = context.builder().get();
        assertThat(builderContext.builderMethods()).isEmpty();
        assertThat(builderContext.toBuilderMethods()).isEmpty();
        assertThat(builderContext.buildMethod()).isEmpty();
        assertThat(builderContext.autoBuildMethod().getSimpleName().toString())
            .isEqualTo("oddBuild");

        Map<String, Set<ExecutableElement>> setters = builderContext.setters();
        assertThat(setters.keySet()).containsExactly("string");
        Set<ExecutableElement> thingSetters = setters.get("string");
        assertThat(thingSetters).hasSize(1);
        ExecutableElement thingSetter = Iterables.getOnlyElement(thingSetters);
        assertThat(thingSetter.getSimpleName().toString()).isEqualTo("setString");

        assertThat(builderContext.propertyBuilders()).isEmpty();
      };
  ContextCheckingExtension extension = new ContextCheckingExtension(checker);
  Compilation compilation =
      javac()
          .withProcessors(new AutoValueProcessor(ImmutableList.of(extension)))
          .compile(autoValueClass);
  assertThat(compilation).succeededWithoutWarnings();
}
 
Example 17
Source File: StreamPropertyDerivations.java    From presto with Apache License 2.0 4 votes vote down vote up
@Override
public StreamProperties visitSample(SampleNode node, List<StreamProperties> inputProperties)
{
    return Iterables.getOnlyElement(inputProperties);
}
 
Example 18
Source File: GraknClientIT.java    From grakn with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void testExecutingAQuery_ExplanationsAreReturned() {
    try (GraknClient.Transaction tx = remoteSession.transaction().write()) {
        tx.execute(Graql.define(
                type("name").sub("attribute").value("string"),
                type("content").sub("entity").has("name").plays("contained").plays("container"),
                type("contains").sub("relation").relates("contained").relates("container"),
                type("transitive-location").sub("rule")
                        .when(and(
                                rel("contained", "x").rel("container", "y").isa("contains"),
                                rel("contained", "y").rel("container", "z").isa("contains")
                        ))
                        .then(rel("contained", "x").rel("container", "z").isa("contains"))
        ));
        tx.execute(Graql.insert(
                var("x").isa("content").has("name", "x"),
                var("y").isa("content").has("name", "y"),
                var("z").isa("content").has("name", "z"),
                rel("contained", "x").rel("container", "y").isa("contains"),
                rel("contained", "y").rel("container", "z").isa("contains")
        ));
        tx.commit();
    }
    try (GraknClient.Transaction tx = remoteSession.transaction().write()) {
        List<Pattern> patterns = Lists.newArrayList(
                Graql.var("x").isa("content").has("name", "x"),
                var("z").isa("content").has("name", "z"),
                var("infer").rel("contained", "x").rel("container", "z").isa("contains")
        );
        ConceptMap answer = Iterables.getOnlyElement(tx.execute(Graql.match(patterns).get(), GraknClient.Transaction.Options.explain(true)).get());

        final int ruleStatements = tx.getRule("transitive-location").when().statements().size();

        Set<ConceptMap> deductions = deductions(answer);

        assertEquals(patterns.size() + ruleStatements + 1, deductions.size());
        assertEquals(patterns.size(), answer.explanation().getAnswers().size());
        answer.explanation().getAnswers().stream()
                .filter(a -> a.map().containsKey(var("infer").var()))
                .forEach(a -> assertEquals(1, a.explanation().getAnswers().size()));
        testExplanation(answer);
    }
}
 
Example 19
Source File: StarlarkDefinedAspectsTest.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * r0 is a dependency of r1 via two attributes, dep1 and dep2. r1 sends an aspect 'a' along dep1
 * but not along dep2.
 *
 * <p>rcollect depends upon r1 and sends another aspect, 'collector', along its dep dependency.
 * 'collector' wants to see aspect 'a' and propagates along dep1 and dep2. It should be applied
 * both to r0 and to r0+a.
 */
@Test
public void multipleDepsDifferentAspects() throws Exception {
  scratch.file(
      "test/aspect.bzl",
      "PAspect = provider()",
      "PCollector = provider()",
      "def _aspect_impl(target, ctx):",
      "   return [PAspect()]",
      "a = aspect(_aspect_impl, attr_aspects = ['dep'], provides = [PAspect])",
      "def _collector_impl(target, ctx):",
      "   suffix = '+PAspect' if PAspect in target else ''",
      "   result = [str(target.label)+suffix]",
      "   for a in ['dep', 'dep1', 'dep2']:",
      "     if hasattr(ctx.rule.attr, a):",
      "        result += getattr(ctx.rule.attr, a)[PCollector].result",
      "   return [PCollector(result=result)]",
      "collector = aspect(_collector_impl, attr_aspects = ['*'], ",
      "                   required_aspect_providers = [PAspect])",
      "def _rimpl(ctx):",
      "   pass",
      "r0 = rule(_rimpl)",
      "r1 = rule(_rimpl, ",
      "          attrs = {",
      "             'dep1' : attr.label(),",
      "             'dep2' : attr.label(aspects = [a]),",
      "          },",
      ")",
      "def _rcollect_impl(ctx):",
      "    return [ctx.attr.dep[PCollector]]",
      "rcollect = rule(_rcollect_impl,",
      "                attrs = {",
      "                  'dep' : attr.label(aspects = [collector]),",
      "                })");
  scratch.file(
      "test/BUILD",
      "load(':aspect.bzl', 'r0', 'r1', 'rcollect')",
      "r0(name = 'r0')",
      "r1(name = 'r1', dep1 = ':r0', dep2 = ':r0')",
      "rcollect(name = 'rcollect', dep = ':r1')");

  AnalysisResult analysisResult = update(ImmutableList.of(), "//test:rcollect");
  ConfiguredTarget configuredTarget =
      Iterables.getOnlyElement(analysisResult.getTargetsToBuild());
  StarlarkProvider.Key pCollector =
      new StarlarkProvider.Key(
          Label.parseAbsolute("//test:aspect.bzl", ImmutableMap.of()), "PCollector");
  StructImpl pCollectorProvider = (StructImpl) configuredTarget.get(pCollector);
  assertThat((Sequence<?>) pCollectorProvider.getValue("result"))
      .containsExactly("//test:r1", "//test:r0", "//test:r0+PAspect");
}
 
Example 20
Source File: RelationTypeVertex.java    From grakn with GNU Affero General Public License v3.0 4 votes vote down vote up
public InternalRelationType getBaseType() {
    Entry entry = Iterables.getOnlyElement(getRelated(TypeDefinitionCategory.RELATIONTYPE_INDEX, Direction.IN), null);
    if (entry == null) return null;
    return (InternalRelationType) entry.getSchemaType();
}