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

The following examples show how to use com.google.common.collect.ImmutableSetMultimap. 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: LuckPerms   Source File: ImmutableContextSetImpl.java    License: MIT License 6 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof ContextSet)) return false;
    final ContextSet that = (ContextSet) o;

    // fast(er) path for ImmutableContextSet comparisons
    if (that instanceof ImmutableContextSetImpl) {
        ImmutableContextSetImpl immutableThat = (ImmutableContextSetImpl) that;
        if (this.hashCode != immutableThat.hashCode) return false;
    }

    final Multimap<String, String> thatBacking;
    if (that instanceof AbstractContextSet) {
        thatBacking = ((AbstractContextSet) that).backing();
    } else {
        Map<String, Set<String>> thatMap = that.toMap();
        ImmutableSetMultimap.Builder<String, String> thatBuilder = ImmutableSetMultimap.builder();
        for (Map.Entry<String, Set<String>> e : thatMap.entrySet()) {
            thatBuilder.putAll(e.getKey(), e.getValue());
        }
        thatBacking = thatBuilder.build();
    }

    return backing().equals(thatBacking);
}
 
Example 2
Source Project: copybara   Source File: GerritDestination.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ImmutableSetMultimap<String, String> describe(@Nullable Glob originFiles) {
  ImmutableSetMultimap.Builder<String, String> builder =
      new ImmutableSetMultimap.Builder<>();
  if (submit) {
    return gitDestination.describe(originFiles);
  }
  for (Entry<String, String> entry : gitDestination.describe(originFiles).entries()) {
    if (entry.getKey().equals("type")) {
      continue;
    }
    builder.put(entry);
  }
  return builder
      .put("type", getType())
      .build();
}
 
Example 3
Source Project: cloud-opensource-java   Source File: SymbolProblem.java    License: Apache License 2.0 6 votes vote down vote up
public static String formatSymbolProblems(
    ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems) {
  StringBuilder output = new StringBuilder();

  symbolProblems
      .asMap()
      .forEach(
          (problem, classFiles) -> {
            int referenceCount = classFiles.size();
            output.append(
                String.format(
                    "%s;\n  referenced by %d class file%s\n",
                    problem, referenceCount, referenceCount > 1 ? "s" : ""));
            classFiles.forEach(
                classFile -> {
                  output.append("    " + classFile.getBinaryName());
                  output.append(" (" + classFile.getClassPathEntry() + ")\n");
                });
          });

  return output.toString();
}
 
Example 4
Source Project: cloud-opensource-java   Source File: LinkageCheckerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFindInvalidReferences_constructorInAbstractClass() throws IOException {
  List<ClassPathEntry> paths = ImmutableList.of(guavaJar);
  LinkageChecker linkageChecker = LinkageChecker.create(paths);

  SymbolReferences.Builder builder = new SymbolReferences.Builder();
  builder.addMethodReference(
      new ClassFile(paths.get(0), LinkageCheckerTest.class.getName()),
      new MethodSymbol(
          "com.google.common.collect.LinkedHashMultimapGwtSerializationDependencies",
          "<init>",
          "(Ljava/util/Map;)V",
          false));

  ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems =
      linkageChecker.cloneWith(builder.build()).findSymbolProblems();

  Truth.assertThat(symbolProblems).isEmpty();
}
 
Example 5
Source Project: bazel   Source File: MultimapCodec.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ImmutableMultimap<K, V> deserialize(
    DeserializationContext context, CodedInputStream codedIn)
    throws SerializationException, IOException {
  ImmutableMultimap.Builder<K, V> result;
  if (codedIn.readBool()) {
    result = ImmutableListMultimap.builder();
  } else {
    result = ImmutableSetMultimap.builder();
  }
  int length = codedIn.readInt32();
  for (int i = 0; i < length; i++) {
    K key = context.deserialize(codedIn);
    Collection<V> values = context.deserialize(codedIn);
    result.putAll(key, values);
  }
  return result.build();
}
 
Example 6
Source Project: nomulus   Source File: RdeStagingMapperTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void beforeEach() {
  // Two real registrars have been created by AppEngineRule, named "New Registrar" and "The
  // Registrar". Create one included registrar (external_monitoring) and two excluded ones.
  Registrar monitoringRegistrar =
      persistNewRegistrar("monitoring", "monitoring", Registrar.Type.MONITORING, null);
  Registrar testRegistrar = persistNewRegistrar("test", "test", Registrar.Type.TEST, null);
  Registrar externalMonitoringRegistrar =
      persistNewRegistrar(
          "externalmonitor", "external_monitoring", Registrar.Type.EXTERNAL_MONITORING, 9997L);

  // Set Registrar states which are required for reporting.
  tm().transact(
          () ->
              tm().saveNewOrUpdateAll(
                      ImmutableList.of(
                          externalMonitoringRegistrar.asBuilder().setState(State.ACTIVE).build(),
                          testRegistrar.asBuilder().setState(State.ACTIVE).build(),
                          monitoringRegistrar.asBuilder().setState(State.ACTIVE).build())));

  rdeStagingMapper =
      new RdeStagingMapper(ValidationMode.STRICT, ImmutableSetMultimap.of("1", pendingDeposit));
  rdeStagingMapper.setContext(context);
}
 
Example 7
Source Project: grakn   Source File: RoleInferenceIT.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Test //missing role is ambiguous without cardinality constraints
public void testRoleInference_RoleHierarchyInvolved() {
    Transaction tx = genericSchemaSession.transaction(Transaction.Type.WRITE);
    ReasonerQueryFactory reasonerQueryFactory = ((TestTransactionProvider.TestTransaction)tx).reasonerQueryFactory();

    String relationString = "{ ($p, subRole2: $gc) isa binary; };";
    String relationString2 = "{ (subRole1: $gp, $p) isa binary; };";
    RelationAtom relation = (RelationAtom) reasonerQueryFactory.atomic(conjunction(relationString)).getAtom();
    RelationAtom relation2 = (RelationAtom) reasonerQueryFactory.atomic(conjunction(relationString2)).getAtom();
    Multimap<Role, Variable> roleMap = roleSetMap(relation.getRoleVarMap());
    Multimap<Role, Variable> roleMap2 = roleSetMap(relation2.getRoleVarMap());

    ImmutableSetMultimap<Role, Variable> correctRoleMap = ImmutableSetMultimap.of(
            tx.getRole("role"), new Variable("p"),
            tx.getRole("subRole2"), new Variable("gc"));
    ImmutableSetMultimap<Role, Variable> correctRoleMap2 = ImmutableSetMultimap.of(
            tx.getRole("role"), new Variable("p"),
            tx.getRole("subRole1"), new Variable("gp"));
    assertEquals(correctRoleMap, roleMap);
    assertEquals(correctRoleMap2, roleMap2);
    tx.close();
}
 
Example 8
Source Project: grakn   Source File: RoleInferenceIT.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testRoleInference_TypedTernaryRelationWithMetaRoles_MetaRolesShouldBeOverwritten(){
    Transaction tx = roleInferenceSetSession.transaction(Transaction.Type.WRITE);
    ReasonerQueryFactory reasonerQueryFactory = ((TestTransactionProvider.TestTransaction)tx).reasonerQueryFactory();

    String patternString = "{ (role: $x, role: $y, role: $z); $x isa entity1; $y isa entity2; $z isa entity3; };";
    String patternString2 = "{ (role: $x, role: $y, role: $z) isa ternary; $x isa entity1; $y isa entity2; $z isa entity3; };";

    ImmutableSetMultimap<Role, Variable> correctRoleMap = ImmutableSetMultimap.of(
            tx.getRole("role1"), new Variable("x"),
            tx.getRole("role2"), new Variable("y"),
            tx.getRole("role3"), new Variable("z"));
    roleInference(patternString, correctRoleMap, reasonerQueryFactory);
    roleInference(patternString2, correctRoleMap, reasonerQueryFactory);
    tx.close();
}
 
Example 9
Source Project: bazel   Source File: ZipFilterActionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void testZipEntryFilter_ErrorOnMismatch() throws Exception {
  ZipFilterEntryFilter filter =
      new ZipFilterEntryFilter(
          ".*R.class.*",
          ImmutableSetMultimap.of("foo.class", 1L, "baz.class", 2L),
          ImmutableMap.of("foo.class", 1L, "bar.class", 2L, "baz.class", 3L, "res/R.class", 4L),
          HashMismatchCheckMode.ERROR);
  filter.accept("foo.class", callback);
  callback.assertOp(FilterOperation.SKIP);
  filter.accept("bar.class", callback);
  callback.assertOp(FilterOperation.COPY);
  filter.accept("res/R.class", callback);
  callback.assertOp(FilterOperation.SKIP);
  filter.accept("baz.class", callback);
  assertThat(filter.sawErrors()).isTrue();
}
 
Example 10
Source Project: gwt-jackson   Source File: MultimapGwtTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testDeserialization() {
    String input = "{" +
            "\"multimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"immutableMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"immutableSetMultimap\":{\"foo\":[3]}," +
            "\"immutableListMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"setMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"hashMultimap\":{\"foo\":[3]}," +
            "\"linkedHashMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"sortedSetMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"treeMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"listMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}," +
            "\"arrayListMultimap\":{\"foo\":[3,2,5]}," +
            "\"linkedListMultimap\":{\"foo\":[3,2,5],\"bar\":[4]}" +
            "}";

    BeanWithMultimapTypes result = BeanWithMultimapTypesMapper.INSTANCE.read( input );
    assertNotNull( result );

    ImmutableListMultimap<String, Integer> expectedOrderedKeysAndValues = ImmutableListMultimap
            .of( "foo", 3, "bar", 4, "foo", 2, "foo", 5 );
    ImmutableSetMultimap<String, Integer> expectedNonOrdered = ImmutableSetMultimap.of( "foo", 3 );

    assertEquals( LinkedHashMultimap.create( expectedOrderedKeysAndValues ), result.multimap );
    assertEquals( ImmutableMultimap.copyOf( expectedOrderedKeysAndValues ), result.immutableMultimap );
    assertEquals( expectedOrderedKeysAndValues, result.immutableListMultimap );
    assertEquals( LinkedHashMultimap.create( expectedOrderedKeysAndValues ), result.setMultimap );
    assertEquals( LinkedHashMultimap.create( expectedOrderedKeysAndValues ), result.linkedHashMultimap );
    assertEquals( LinkedListMultimap.create( expectedOrderedKeysAndValues ), result.listMultimap );
    assertEquals( LinkedListMultimap.create( expectedOrderedKeysAndValues ), result.linkedListMultimap );

    assertEquals( TreeMultimap.create( expectedOrderedKeysAndValues ), result.sortedSetMultimap );
    assertEquals( TreeMultimap.create( expectedOrderedKeysAndValues ), result.treeMultimap );

    assertEquals( expectedNonOrdered, result.immutableSetMultimap );
    assertEquals( HashMultimap.create( expectedNonOrdered ), result.hashMultimap );

    assertEquals( ArrayListMultimap.create( ImmutableListMultimap.of( "foo", 3, "foo", 2, "foo", 5 ) ), result.arrayListMultimap );
}
 
Example 11
Source Project: bazel   Source File: FileContentProvider.java    License: Apache License 2.0 5 votes vote down vote up
public final ImmutableSetMultimap<Predicate<ClassName>, ClassName> findReferencedTypes(
    ImmutableSet<Predicate<ClassName>> typeFilters) {
  ImmutableSetMultimap.Builder<ClassName, Predicate<ClassName>> collectedTypes =
      ImmutableSetMultimap.builder();
  // Takes an advantage of hit-all-referenced-types ASM Remapper to perform type collection.
  try (S inputStream = get()) {
    ClassReader cr = new ClassReader(inputStream);
    cr.accept(
        new ClassRemapper(
            new ClassWriter(ClassWriter.COMPUTE_FRAMES),
            new Remapper() {
              @Override
              public String map(String internalName) {
                ClassName className = ClassName.create(internalName);
                collectedTypes.putAll(
                    className,
                    typeFilters.stream()
                        .filter(className::acceptTypeFilter)
                        .collect(Collectors.toList()));
                return super.map(internalName);
              }
            }),
        /* parsingOptions= */ 0);
  } catch (IOException e) {
    throw new IOError(e);
  }
  return collectedTypes.build().inverse();
}
 
Example 12
Source Project: nomulus   Source File: ConsoleUiActionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  action.enabled = true;
  action.logoFilename = "logo.png";
  action.productName = "Nomulus";
  action.integrationEmail = "[email protected]";
  action.supportEmail = "[email protected]";
  action.announcementsEmail = "[email protected]";
  action.supportPhoneNumber = "1 (888) 555 0123";
  action.technicalDocsUrl = "http://example.com/technical-docs";
  action.req = request;
  action.response = response;
  action.registrarConsoleMetrics = new RegistrarConsoleMetrics();
  action.userService = UserServiceFactory.getUserService();
  action.xsrfTokenManager = new XsrfTokenManager(new FakeClock(), action.userService);
  action.method = Method.GET;
  action.paramClientId = Optional.empty();
  action.authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false));
  action.analyticsConfig = ImmutableMap.of("googleAnalyticsId", "sampleId");

  action.registrarAccessor =
      AuthenticatedRegistrarAccessor.createForTesting(
          ImmutableSetMultimap.of(
              "TheRegistrar", OWNER,
              "NewRegistrar", OWNER,
              "NewRegistrar", ADMIN,
              "AdminRegistrar", ADMIN));
  RegistrarConsoleMetrics.consoleRequestMetric.reset();
}
 
Example 13
Source Project: presto   Source File: TopologyAwareNodeSelectorFactory.java    License: Apache License 2.0 5 votes vote down vote up
private NodeMap createNodeMap(Optional<CatalogName> catalogName)
{
    Set<InternalNode> nodes = catalogName
            .map(nodeManager::getActiveConnectorNodes)
            .orElseGet(() -> nodeManager.getNodes(ACTIVE));

    Set<String> coordinatorNodeIds = nodeManager.getCoordinators().stream()
            .map(InternalNode::getNodeIdentifier)
            .collect(toImmutableSet());

    ImmutableSetMultimap.Builder<HostAddress, InternalNode> byHostAndPort = ImmutableSetMultimap.builder();
    ImmutableSetMultimap.Builder<InetAddress, InternalNode> byHost = ImmutableSetMultimap.builder();
    ImmutableSetMultimap.Builder<NetworkLocation, InternalNode> workersByNetworkPath = ImmutableSetMultimap.builder();
    for (InternalNode node : nodes) {
        if (includeCoordinator || !coordinatorNodeIds.contains(node.getNodeIdentifier())) {
            NetworkLocation location = networkTopology.locate(node.getHostAndPort());
            for (int i = 0; i <= location.getSegments().size(); i++) {
                workersByNetworkPath.put(location.subLocation(0, i), node);
            }
        }
        try {
            byHostAndPort.put(node.getHostAndPort(), node);

            InetAddress host = InetAddress.getByName(node.getInternalUri().getHost());
            byHost.put(host, node);
        }
        catch (UnknownHostException e) {
            if (inaccessibleNodeLogCache.getIfPresent(node) == null) {
                inaccessibleNodeLogCache.put(node, true);
                LOG.warn(e, "Unable to resolve host name for node: %s", node);
            }
        }
    }

    return new NodeMap(byHostAndPort.build(), byHost.build(), workersByNetworkPath.build(), coordinatorNodeIds);
}
 
Example 14
Source Project: nomulus   Source File: PendingDepositCheckerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMethod_backloggedTwoDays_onlyWantsLeastRecentDay() {
  clock.setTo(DateTime.parse("2000-01-01TZ"));
  createTldWithEscrowEnabled("lol");
  clock.advanceOneMilli();
  setCursor(Registry.get("lol"), RDE_STAGING, DateTime.parse("1999-12-30TZ"));
  clock.advanceOneMilli();
  assertThat(checker.getTldsAndWatermarksPendingDepositForRdeAndBrda()).isEqualTo(
      ImmutableSetMultimap.of(
          "lol", PendingDeposit.create(
              "lol", DateTime.parse("1999-12-30TZ"), FULL, RDE_STAGING, standardDays(1))));
}
 
Example 15
Source Project: grakn   Source File: RoleInferenceIT.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testRoleInference_TypedBinaryRelation_SingleTypeMissing(){
    Transaction tx = roleInferenceSetSession.transaction(Transaction.Type.WRITE);
    ReasonerQueryFactory reasonerQueryFactory = ((TestTransactionProvider.TestTransaction)tx).reasonerQueryFactory();

    String patternString = "{ ($x, $y); $x isa entity1; };";
    String patternString2 = "{ ($x, $y) isa binary; $x isa entity1; };";

    ImmutableSetMultimap<Role, Variable> correctRoleMap = ImmutableSetMultimap.of(
            tx.getRole("role1"), new Variable("x"),
            tx.getRole("role"), new Variable("y"));
    roleInference(patternString, correctRoleMap, reasonerQueryFactory);
    roleInference(patternString2, correctRoleMap, reasonerQueryFactory);
    tx.close();
}
 
Example 16
@Test //should assign (role : $x, role1: $y, role: $z) which is compatible with 3 ternary rules
public void relationWithUnspecifiedRoles_someRoleplayersTyped(){
    try(Transaction tx = ruleApplicabilitySession.transaction(Transaction.Type.WRITE)) {
        ReasonerQueryFactory reasonerQueryFactory = ((TestTransactionProvider.TestTransaction)tx).reasonerQueryFactory();

        String relationString = "{ ($x, $y, $z);$y isa singleRoleEntity; $z isa twoRoleEntity; };";
        RelationAtom relation = (RelationAtom) reasonerQueryFactory.atomic(conjunction(relationString)).getAtom();
        ImmutableSetMultimap<Role, Variable> roleMap = ImmutableSetMultimap.of(
                tx.getRole("role"), new Variable("x"),
                tx.getRole("someRole"), new Variable("y"),
                tx.getRole("role"), new Variable("z"));
        assertEquals(roleMap, roleSetMap(relation.getRoleVarMap()));
        assertEquals(5, relation.getApplicableRules().count());
    }
}
 
Example 17
Source Project: presto   Source File: HashGenerationOptimizer.java    License: Apache License 2.0 5 votes vote down vote up
public HashComputationSet translate(Function<Symbol, Optional<Symbol>> translator)
{
    ImmutableSetMultimap.Builder<HashComputation, HashComputation> builder = ImmutableSetMultimap.builder();
    for (HashComputation hashComputation : hashes.keySet()) {
        hashComputation.translate(translator)
                .ifPresent(hash -> builder.put(hash, hashComputation));
    }
    return new HashComputationSet(builder.build());
}
 
Example 18
Source Project: dagger2-sample   Source File: BindingGraph.java    License: Apache License 2.0 5 votes vote down vote up
RequestResolver(Optional<RequestResolver> parentResolver,
    Optional<Equivalence.Wrapper<AnnotationMirror>> targetScope,
    ImmutableSetMultimap<Key, ProvisionBinding> explicitProvisionBindings,
    ImmutableSetMultimap<Key, ProductionBinding> explicitProductionBindings) {
  assert parentResolver != null;
  this.parentResolver = parentResolver;
  assert targetScope != null;
  this.targetScope = targetScope;
  assert explicitProvisionBindings != null;
  this.explicitProvisionBindings = explicitProvisionBindings;
  assert explicitProductionBindings != null;
  this.explicitProductionBindings = explicitProductionBindings;
  this.resolvedBindings = Maps.newLinkedHashMap();
}
 
Example 19
public ImmutableSetMultimap construct(int entries) {
  ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder();
  Object key = newEntry();
  for (int i = 0; i < entries; i++) {
    builder.put(key, newEntry());
  }
  return builder.build();
}
 
Example 20
Source Project: auto   Source File: BasicAnnotationProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
private static <K, V>
    Correspondence<SetMultimap<K, V>, SetMultimap<K, String>> setMultimapValuesByString() {
  return Correspondence.from(
      (actual, expected) ->
          ImmutableSetMultimap.copyOf(transformValues(actual, Object::toString)).equals(expected),
      "is equivalent comparing multimap values by `toString()` to");
}
 
Example 21
/** If a user doesn't have access to any registrars, guess fails. */
@Test
public void testGuessClientIdForUser_noAccess_fails() {
  AuthenticatedRegistrarAccessor registrarAccessor =
      AuthenticatedRegistrarAccessor.createForTesting(ImmutableSetMultimap.of());

  assertThat(assertThrows(RegistrarAccessDeniedException.class, registrarAccessor::guessClientId))
      .hasMessageThat()
      .isEqualTo("TestUserId isn't associated with any registrar");
}
 
Example 22
Source Project: cloud-opensource-java   Source File: LinkageMonitor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a message on {@code snapshotSymbolProblems} that do not exist in {@code
 * baselineProblems}.
 */
@VisibleForTesting
static String messageForNewErrors(
    ImmutableSetMultimap<SymbolProblem, ClassFile> snapshotSymbolProblems,
    Set<SymbolProblem> baselineProblems,
    ClassPathResult classPathResult) {
  Set<SymbolProblem> newProblems =
      Sets.difference(snapshotSymbolProblems.keySet(), baselineProblems);
  StringBuilder message =
      new StringBuilder("Newly introduced problem" + (newProblems.size() > 1 ? "s" : "") + ":\n");
  Builder<ClassPathEntry> problematicJars = ImmutableSet.builder();
  for (SymbolProblem problem : newProblems) {
    message.append(problem + "\n");

    // This is null for ClassNotFound error.
    ClassFile containingClass = problem.getContainingClass();
    if (containingClass != null) {
      problematicJars.add(containingClass.getClassPathEntry());
    }

    for (ClassFile classFile : snapshotSymbolProblems.get(problem)) {
      message.append(
          String.format(
              "  referenced from %s (%s)\n",
              classFile.getBinaryName(), classFile.getClassPathEntry()));
      problematicJars.add(classFile.getClassPathEntry());
    }
  }

  message.append("\n");
  message.append(classPathResult.formatDependencyPaths(problematicJars.build()));

  return message.toString();
}
 
Example 23
Source Project: cloud-opensource-java   Source File: SymbolReferences.java    License: Apache License 2.0 5 votes vote down vote up
private SymbolReferences(
    ImmutableSet<ClassFile> classFiles,
    ImmutableSetMultimap<ClassFile, ClassSymbol> classToClassSymbols,
    ImmutableSetMultimap<ClassFile, MethodSymbol> classToMethodSymbols,
    ImmutableSetMultimap<ClassFile, FieldSymbol> classToFieldSymbols) {
  this.classToClassSymbols = checkNotNull(classToClassSymbols);
  this.classToMethodSymbols = checkNotNull(classToMethodSymbols);
  this.classToFieldSymbols = checkNotNull(classToFieldSymbols);
  this.classFiles = checkNotNull(classFiles);
}
 
Example 24
@Test
public void testFindInvalidReferences_selfReferenceFromAbstractClassToInterface()
    throws IOException {
  List<ClassPathEntry> classPath =
      resolveClassPath("com.google.cloud:google-cloud-bigtable:jar:0.66.0-alpha");
  ClassPathEntry httpClientJar =
      classPath.stream()
          .filter(path -> path.getJar().toString().contains("httpclient-4.5.3.jar"))
          .findFirst()
          .get();
  LinkageChecker linkageChecker = LinkageChecker.create(classPath);

  // httpclient-4.5.3 AbstractVerifier has a method reference of
  // 'void verify(String host, String[] cns, String[] subjectAlts)' to itself and its interface
  // X509HostnameVerifier has the method.
  // https://github.com/apache/httpcomponents-client/blob/e2cf733c60f910d17dc5cfc0a77797054a2e322e/httpclient/src/main/java/org/apache/http/conn/ssl/AbstractVerifier.java#L153
  ClassDumper dumper = ClassDumper.create(ImmutableList.of(httpClientJar));

  SymbolReferences symbolReferences = dumper.findSymbolReferences();

  Truth.assertWithMessage(
          "httpclient-4.5.3 shoud not contain GZipInputStreamFactory reference, which is added"
              + " 4.5.4")
      .that(symbolReferences.getClassSymbols(
          new ClassFile(
              httpClientJar, "org.apache.http.client.protocol.ResponseContentEncoding")))
      .doesNotContain(
          new ClassSymbol("org.apache.http.client.entity.GZIPInputStreamFactory"));

  ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems =
      linkageChecker.findSymbolProblems();
  assertEquals(
      "Method references within the same jar file should not be reported",
      0,
      symbolProblems.values().stream()
          .filter(classFile -> httpClientJar.equals(classFile.getClassPathEntry()))
          .count());
}
 
Example 25
Source Project: cloud-opensource-java   Source File: LinkageCheckerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFindClassReferences_innerClass() throws IOException {
  List<ClassPathEntry> paths = ImmutableList.of(firestoreJar);
  LinkageChecker linkageChecker = LinkageChecker.create(paths);

  SymbolReferences.Builder builder = new SymbolReferences.Builder();
  builder.addClassReference(
      new ClassFile(paths.get(0), LinkageCheckerTest.class.getName()),
      // This inner class is defined as public in firestore-v1beta1-0.28.0.jar
      new ClassSymbol("com.google.firestore.v1beta1.FirestoreGrpc$FirestoreStub"));
  ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems =
      linkageChecker.cloneWith(builder.build()).findSymbolProblems();

  Truth.assertThat(symbolProblems).isEmpty();
}
 
Example 26
Source Project: onos   Source File: DefaultTopology.java    License: Apache License 2.0 5 votes vote down vote up
public ClusterIndexes(ImmutableMap<DeviceId, TopologyCluster> clustersByDevice,
                      ImmutableSetMultimap<TopologyCluster, DeviceId> devicesByCluster,
                      ImmutableSetMultimap<TopologyCluster, Link> linksByCluster) {
    this.clustersByDevice = clustersByDevice;
    this.devicesByCluster = devicesByCluster;
    this.linksByCluster = linksByCluster;
}
 
Example 27
public List<PaymentToReconcileRow> getPaymentToReconcileRowsByIds(final Set<PaymentId> paymentIds)
{
	final ImmutableSetMultimap<PaymentId, String> invoiceDocumentNosByPaymentId = getInvoiceDocumentNosByPaymentId(paymentIds);

	return paymentDAO.getByIds(paymentIds)
			.stream()
			.map(record -> toPaymentToReconcileRow(record, invoiceDocumentNosByPaymentId))
			.collect(ImmutableList.toImmutableList());
}
 
Example 28
Source Project: cloud-opensource-java   Source File: LinkageCheckerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFindSymbolProblems_catchesNoClassDefFoundError() throws IOException {
  // SLF4J classes catch NoClassDefFoundError to detect the availability of logger backends
  // the tool should not show errors for such classes.
  List<ClassPathEntry> paths = resolvePaths("org.slf4j:slf4j-api:jar:1.7.21");

  LinkageChecker linkageChecker = LinkageChecker.create(paths);

  ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems =
      linkageChecker.findSymbolProblems();

  Truth.assertThat(symbolProblems).isEmpty();
}
 
Example 29
Source Project: buck   Source File: WorkspaceAndProjectGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add a workspace scheme for each extension bundled with the source target of the workspace.
 *
 * @param projectGraph
 * @param schemeName
 * @param schemeArguments
 * @param schemeConfigsBuilder
 * @param schemeNameToSrcTargetNodeBuilder
 */
private static void addWorkspaceExtensionSchemes(
    TargetGraph projectGraph,
    String schemeName,
    XcodeWorkspaceConfigDescriptionArg schemeArguments,
    ImmutableMap.Builder<String, XcodeWorkspaceConfigDescriptionArg> schemeConfigsBuilder,
    ImmutableSetMultimap.Builder<String, Optional<TargetNode<?>>>
        schemeNameToSrcTargetNodeBuilder) {
  if (!schemeArguments.getSrcTarget().isPresent()) {
    return;
  }

  LOG.debug("Potentially adding extension schemes for %s", schemeName);

  BuildTarget sourceBuildTarget = schemeArguments.getSrcTarget().get();
  TargetNode<?> sourceTargetNode = projectGraph.get(sourceBuildTarget);
  Set<BuildTarget> sourceTargetBuildDeps = sourceTargetNode.getBuildDeps();

  // Filter all of the source target's deps to find the bundled extensions that get an implicit
  // scheme.
  ImmutableSet<BuildTarget> implicitSchemeBuildTargets =
      sourceTargetBuildDeps.stream()
          .filter(t -> shouldIncludeImplicitExtensionSchemeForTargetNode(projectGraph.get(t)))
          .collect(ImmutableSet.toImmutableSet());

  // Create scheme for each bundled extension to allow Xcode to automatically begin debugging them
  // when this scheme it selected.
  implicitSchemeBuildTargets.forEach(
      (buildTarget -> {
        String extensionSchemeName = schemeName + "+" + buildTarget.getShortName();
        TargetNode<?> targetNode = projectGraph.get(buildTarget);

        schemeConfigsBuilder.put(
            extensionSchemeName, createImplicitExtensionWorkspaceArgs(sourceBuildTarget));

        schemeNameToSrcTargetNodeBuilder.put(extensionSchemeName, Optional.of(sourceTargetNode));
        schemeNameToSrcTargetNodeBuilder.put(extensionSchemeName, Optional.of(targetNode));
      }));
}
 
Example 30
Source Project: nomulus   Source File: UpdateRegistrarRdapBaseUrlsAction.java    License: Apache License 2.0 5 votes vote down vote up
private ImmutableSetMultimap<String, String> getRdapBaseUrlsPerIanaId() {
  // All TLDs have the same data, so just keep trying until one works
  // (the expectation is that all / any should work)
  ImmutableList<String> tlds = ImmutableList.sortedCopyOf(Registries.getTldsOfType(TldType.REAL));
  checkArgument(!tlds.isEmpty(), "There must exist at least one REAL TLD.");
  Throwable finalThrowable = null;
  for (String tld : tlds) {
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
    String id;
    try {
      id = loginAndGetId(requestFactory, tld);
    } catch (Throwable e) {
      // Login failures are bad but not unexpected for certain TLDs. We shouldn't store those
      // but rather should only store useful Throwables.
      logger.atWarning().log("Error logging in to MoSAPI server: " + e.getMessage());
      continue;
    }
    try {
      return getRdapBaseUrlsPerIanaIdWithTld(tld, id, requestFactory);
    } catch (Throwable throwable) {
      logger.atWarning().log(
          String.format(
              "Error retrieving RDAP urls with TLD %s: %s", tld, throwable.getMessage()));
      finalThrowable = throwable;
    }
  }
  throw new RuntimeException(
      String.format("Error contacting MosAPI server. Tried TLDs %s", tlds), finalThrowable);
}