Java Code Examples for com.google.common.collect.ImmutableSet.size()

The following are Jave code examples for showing how to use size() of the com.google.common.collect.ImmutableSet class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: BUILD_file_generator   File: ProjectClassToRuleResolver.java   View Source Code Vote up 6 votes
/**
 * Identifies and logs all unresolved class names. Then computes the percentage of unresolved
 * classes. If more than a certain threshold are unresolved, then it will throw an
 * IllegalStateException.
 */
private void handleUnresolvedClasses(
    ImmutableSet<String> projectClasses, Set<String> resolvedClasses) {
  Set<String> unresolvedClasses = Sets.difference(projectClasses, resolvedClasses);
  if (unresolvedClasses.isEmpty() || projectClasses.isEmpty()) {
    return;
  }

  logger.severe(
      String.format(
          "Unresolved class names = {\n\t%s\n}", Joiner.on("\n\t").join(unresolvedClasses)));

  if (UNRESOLVED_THRESHOLD * projectClasses.size() < unresolvedClasses.size()) {
    throw new IllegalStateException(
        String.format(
            "BUILD File Generator failed to map over %.0f percent of class names. "
                + "Check your white list and content roots",
            UNRESOLVED_THRESHOLD * 100));
  }
}
 
Example 2
Project: GitHub   File: Proto.java   View Source Code Vote up 6 votes
@Value.Lazy
List<TypeElement> includedTypes() {
  Optional<IncludeMirror> includes = include();

  ImmutableList<TypeMirror> typeMirrors = includes.isPresent()
      ? ImmutableList.copyOf(includes.get().valueMirror())
      : ImmutableList.<TypeMirror>of();

  FluentIterable<TypeElement> typeElements = FluentIterable.from(typeMirrors)
      .filter(DeclaredType.class)
      .transform(DeclatedTypeToElement.FUNCTION);

  ImmutableSet<String> uniqueTypeNames = typeElements
      .filter(IsPublic.PREDICATE)
      .transform(ElementToName.FUNCTION)
      .toSet();

  if (uniqueTypeNames.size() != typeMirrors.size()) {
    report().annotationNamed(IncludeMirror.simpleName())
        .warning("Some types were ignored, non-supported for inclusion: duplicates,"
            + " non declared reference types, non-public");
  }

  return typeElements.toList();
}
 
Example 3
Project: GitHub   File: Proto.java   View Source Code Vote up 6 votes
@Value.Lazy
List<TypeElement> builderIncludedTypes() {
  Optional<FIncludeMirror> includes = builderInclude();

  ImmutableList<TypeMirror> typeMirrors = includes.isPresent()
      ? ImmutableList.copyOf(includes.get().valueMirror())
      : ImmutableList.<TypeMirror>of();

  FluentIterable<TypeElement> typeElements = FluentIterable.from(typeMirrors)
      .filter(DeclaredType.class)
      .transform(DeclatedTypeToElement.FUNCTION);

  ImmutableSet<String> uniqueTypeNames = typeElements
      .filter(IsPublic.PREDICATE)
      .transform(ElementToName.FUNCTION)
      .toSet();

  if (uniqueTypeNames.size() != typeMirrors.size()) {
    report().annotationNamed(IncludeMirror.simpleName())
        .warning("Some types were ignored, non-supported for inclusion: duplicates,"
            + " non declared reference types, non-public");
  }

  return typeElements.toList();
}
 
Example 4
Project: tac-kbp-eal   File: ResponseMapping.java   View Source Code Vote up 6 votes
public static CorpusEventLinking apply(CorpusEventLinking corpusEventLinking,
    final SystemOutputStore2016 transformedStore) throws IOException {
  final ImmutableSet.Builder<DocEventFrameReference> retainedHoppersB = ImmutableSet.builder();
  for (final Symbol docid : transformedStore.docIDs()) {
    for (final String hopperID : transformedStore.read(docid).linking().responseSetIds().get()
        .keySet()) {
      retainedHoppersB.add(DocEventFrameReference.of(docid, hopperID));
    }
  }
  final ImmutableSet<DocEventFrameReference> retainedHoppers = retainedHoppersB.build();
  final CorpusEventLinking.Builder ret = CorpusEventLinking.builder();
  for (final CorpusEventFrame ref : corpusEventLinking.corpusEventFrames()) {
    final ImmutableSet<DocEventFrameReference> retainedComponents =
        Sets.intersection(ref.docEventFrames(), retainedHoppers).immutableCopy();
    if (retainedComponents.size() > 0) {
      ret.addCorpusEventFrames(CorpusEventFrame.of(ref.id(), retainedComponents));
      if(retainedComponents.size() != ref.docEventFrames().size()) {
        log.debug("Deleting from {} doc event frame refs", ref.id(),
            Sets.difference(ref.docEventFrames(), retainedHoppers));
      }
    } else {
      log.info("Deleting corpus event frame {}", ref.id());
    }
  }
  return ret.build();
}
 
Example 5
Project: java-monitoring-client-library   File: StackdriverWriter.java   View Source Code Vote up 5 votes
@VisibleForTesting
static ImmutableList<LabelDescriptor> encodeLabelDescriptors(
    ImmutableSet<com.google.monitoring.metrics.LabelDescriptor> labelDescriptors) {
  List<LabelDescriptor> stackDriverLabelDescriptors = new ArrayList<>(labelDescriptors.size());

  for (com.google.monitoring.metrics.LabelDescriptor labelDescriptor : labelDescriptors) {
    stackDriverLabelDescriptors.add(
        new LabelDescriptor()
            .setKey(labelDescriptor.name())
            .setDescription(labelDescriptor.description())
            .setValueType(LABEL_VALUE_TYPE));
  }

  return ImmutableList.copyOf(stackDriverLabelDescriptors);
}
 
Example 6
Project: tac-kbp-eal   File: LinkingStoreSource.java   View Source Code Vote up 5 votes
@Override
protected void handleResponseSetIDs(final ResponseLinking.Builder responseLinking,
    final ImmutableSet<ResponseSet> responseSets,
    final ImmutableMap<String, ResponseSet> responseIDs,
    final Optional<ImmutableMap.Builder<String, String>> foreignLinkingIdToLocal)
    throws IOException {
  if (responseSets.size() == responseIDs.size()) {
    responseLinking.responseSetIds(ImmutableBiMap.copyOf(responseIDs));
    responseLinking.build();
  } else if (responseSets.size() > responseIDs.size() || !foreignLinkingIdToLocal.isPresent()) {
    throw new IOException("Read " + responseSets.size() + " response sets but "
        + responseIDs.size() + " ID assignments");
  } else {
    log.warn(
        "Warning - converting ResponseSet IDs and saving them, this is almost definitely an error!");
    final ImmutableMultimap<ResponseSet, String> responseSetToIds =
        responseIDs.asMultimap().inverse();
    final LaxImmutableMapBuilder<String, ResponseSet> idsMapB =
        MapUtils.immutableMapBuilderAllowingSameEntryTwice();

    for (final Map.Entry<ResponseSet, Collection<String>> setAndIds : responseSetToIds.asMap()
        .entrySet()) {

      final Collection<String> ids = setAndIds.getValue();
      final String selectedID =
          checkNotNull(getFirst(usingToString().immutableSortedCopy(ids), null));
      for (final String oldId : ids) {
        log.debug("Selecting id {} for cluster {}", selectedID, oldId);
        foreignLinkingIdToLocal.get().put(oldId, selectedID);
        idsMapB.put(selectedID, responseIDs.get(oldId));
      }
    }
    responseLinking.responseSetIds(ImmutableBiMap.copyOf(idsMapB.build()));
  }
}
 
Example 7
Project: tac-kbp-eal   File: LinkingStoreSource.java   View Source Code Vote up 5 votes
private String getEventFrameID(final ResponseSet responseSet,
    final ResponseLinking responseLinking) throws IOException {
  checkArgument(responseLinking.responseSetIds().isPresent(), "Linking does not assign frame "
      + "IDs. These are required for writing in 2016 format.");
  final ImmutableSet<String> ids =
      responseLinking.responseSetIds().get().asMultimap().inverse().get(responseSet);
  if (ids.size() == 1) {
    return ids.asList().get(0);
  } else if (ids.isEmpty()) {
    throw new IOException("No ID found for event frame " + responseSet);
  } else {
    throw new IOException("Multiple IDs found for event frame, should be impossible: "
        + responseSet);
  }
}
 
Example 8
Project: url-classifier   File: AuthorityClassifierBuilder.java   View Source Code Vote up 5 votes
/**
 * Builds a classifier based on previous allow/match decisions.
 * This may be reused after a call to build and subsequent calls to
 * allow/match methods will not affect previously built classifiers.
 */
public AuthorityClassifier build() {
  ImmutableSet<Inet4Address> ipv4Set = ipv4s.build();
  ImmutableSet<Inet6Address> ipv6Set = ipv6s.build();
  ImmutableSet<InternetDomainName> domainNameSet = domainNames.build();
  HostGlobMatcher hostGlobMatcher = new HostGlobMatcher(hostGlobs.build());
  int[] allowedPortsSorted;
  {
    ImmutableSet<Integer> allowedPortIntSet = allowedPorts.build();
    int n = allowedPortIntSet.size();
    allowedPortsSorted = new int[n];
    Iterator<Integer> allowedPortIt = allowedPortIntSet.iterator();
    for (int i = 0; i < n; ++i) {
      allowedPortsSorted[i] = allowedPortIt.next();
    }
    Arrays.sort(allowedPortsSorted);
  }
  Predicate<? super Integer> portClassifier =
      allowedPortsSorted.length == 0  // No exclusion specified
      ? Predicates.alwaysTrue()
      : Predicates.alwaysFalse();
  if (this.allowedPortClassifier != null) {
    portClassifier = this.allowedPortClassifier;
  }
  UserInfoClassifier userInfoClassifier =
      this.allowedUserInfoClassifier != null
      ? this.allowedUserInfoClassifier
      : UserInfoClassifiers.NO_PASSWORD_BUT_USERNAME_IF_ALLOWED_BY_SCHEME;
  return new AuthorityClassifierImpl(
      ipv4Set,
      ipv6Set,
      domainNameSet,
      hostGlobMatcher,
      matchesAnyHost,
      allowedPortsSorted,
      portClassifier,
      userInfoClassifier);
}
 
Example 9
Project: calcite-avatica   File: TestRunner.java   View Source Code Vote up 5 votes
/**
 * Finds all tests to run for the TCK.
 *
 * @return A list of test classes to run.
 */
List<Class<?>> getAllTestClasses() {
  try {
    ClassPath cp = ClassPath.from(getClass().getClassLoader());
    ImmutableSet<ClassInfo> classes =
        cp.getTopLevelClasses("org.apache.calcite.avatica.tck.tests");

    List<Class<?>> testClasses = new ArrayList<>(classes.size());
    for (ClassInfo classInfo : classes) {
      if (classInfo.getSimpleName().equals("package-info")) {
        continue;
      }
      Class<?> clz = Class.forName(classInfo.getName());
      if (Modifier.isAbstract(clz.getModifiers())) {
        // Ignore abstract classes
        continue;
      }
      testClasses.add(clz);
    }

    return testClasses;
  } catch (Exception e) {
    LOG.error("Failed to instantiate test classes", e);
    Unsafe.systemExit(TestRunnerExitCodes.TEST_CASE_INSTANTIATION.ordinal());
    // Unreachable..
    return null;
  }
}
 
Example 10
Project: googles-monorepo-demo   File: MediaType.java   View Source Code Vote up 5 votes
/**
 * Returns an optional charset for the value of the charset parameter if it is specified.
 *
 * @throws IllegalStateException if multiple charset values have been set for this media type
 * @throws IllegalCharsetNameException if a charset value is present, but illegal
 * @throws UnsupportedCharsetException if a charset value is present, but no support is available
 *     in this instance of the Java virtual machine
 */
public Optional<Charset> charset() {
  ImmutableSet<String> charsetValues = ImmutableSet.copyOf(parameters.get(CHARSET_ATTRIBUTE));
  switch (charsetValues.size()) {
    case 0:
      return Optional.absent();
    case 1:
      return Optional.of(Charset.forName(Iterables.getOnlyElement(charsetValues)));
    default:
      throw new IllegalStateException("Multiple charset values defined: " + charsetValues);
  }
}
 
Example 11
Project: tac-kbp-eal   File: FilterLinkingStore.java   View Source Code Vote up 4 votes
private static void trueMain(String[] argv) throws IOException {
  final Parameters params = Parameters.loadSerifStyle(new File(argv[0]));
  final File inputStore = params.getExistingDirectory("inputStore");
  final File outputStore = params.getCreatableDirectory("outputStore");

  final SystemOutputStore2016 input = SystemOutputStore2016.open(inputStore);
  final SystemOutputStore2016 output = SystemOutputStore2016.openOrCreate(outputStore);
  final ImmutableSet<KBPRealis> linkableRealises =
      ImmutableSet.of(KBPRealis.Actual, KBPRealis.Other);

  final Predicate<Response> realisIsLinkable =
      compose(in(linkableRealises), ResponseFunctions.realis());

  // collect all the surviving filtering
  final ImmutableSet.Builder<DocEventFrameReference> survivingIDsB = ImmutableSet.builder();
  for (final Symbol docID : input.docIDs()) {
    final DocumentSystemOutput2015 oldOutput = input.read(docID);
    final ResponseLinking filtered =
        oldOutput.linking().copyWithFilteredResponses(realisIsLinkable);
    for (final String surviving : filtered.responseSetIds().get().keySet()) {
      survivingIDsB.add(DocEventFrameReference.of(docID, surviving));
    }
    final DocumentSystemOutput2015 newOutput =
        DocumentSystemOutput2015.from(oldOutput.arguments(), filtered);
    output.write(newOutput);
  }
  final ImmutableSet<DocEventFrameReference> survivingFrames = survivingIDsB.build();

  // remove those from the CorpusEventLinking
  final CorpusEventLinking.Builder newCorpusLinkingB = CorpusEventLinking.builder();
  final ImmutableMultimap<CorpusEventFrame, DocEventFrameReference> corpusEventToDocEvent =
      input.readCorpusEventFrames().docEventsToCorpusEvents().inverse();
  for (final CorpusEventFrame cef : corpusEventToDocEvent.keySet()) {
    final ImmutableSet<DocEventFrameReference> survivingDocEvents =
        FluentIterable.from(corpusEventToDocEvent.get(cef)).filter(in(survivingFrames)).toSet();
    if (survivingDocEvents.size() > 0) {
      final CorpusEventFrame res = CorpusEventFrame.of(cef.id(), survivingDocEvents);
      newCorpusLinkingB.addCorpusEventFrames(res);
    }
  }

  output.writeCorpusEventFrames(newCorpusLinkingB.build());
}
 
Example 12
Project: tac-kbp-eal   File: ResponseMapping.java   View Source Code Vote up 4 votes
public ResponseLinking apply(ResponseLinking responseLinking) {
  final Function<Response, Response> responseMapping = MapUtils.asFunction(replacedResponses,
      Functions.<Response>identity());
  final Predicate<Response> notDeleted = not(in(deletedResponses));

  final ImmutableSet.Builder<ResponseSet> newResponseSetsB = ImmutableSet.builder();
  final ImmutableMap.Builder<ResponseSet, ResponseSet> oldResponseSetToNewB = ImmutableMap.builder();
  for (final ResponseSet responseSet : responseLinking.responseSets()) {
    final ImmutableSet<Response> filteredResponses = FluentIterable.from(responseSet)
        .filter(notDeleted)
        .transform(responseMapping).toSet();
    if (!filteredResponses.isEmpty()) {
      final ResponseSet derived = ResponseSet.from(filteredResponses);
      newResponseSetsB.add(derived);
      oldResponseSetToNewB.put(responseSet, derived);
    }
  }

  final ImmutableSet<ResponseSet> newResponseSets = newResponseSetsB.build();
  final Predicate<Response> notLinked = not(in(ImmutableSet.copyOf(
      Iterables.concat(newResponseSets))));
  final ImmutableSet<Response> newIncompletes =
      FluentIterable.from(responseLinking.incompleteResponses())
          .filter(notDeleted)
          .transform(responseMapping)
          .filter(notLinked)
          .toSet();

  final Optional<ImmutableBiMap<String, ResponseSet>> newResponseSetIDMap;
  if (responseLinking.responseSetIds().isPresent()) {
    final BiMap<String, ResponseSet> responseSetIDs = responseLinking.responseSetIds().get();
    final ImmutableMap<ResponseSet, ResponseSet> oldResponseSetToNew = oldResponseSetToNewB.build();
    final Multimap<ResponseSet, ResponseSet> newResponseToOld = oldResponseSetToNew.asMultimap().inverse();
    final ImmutableBiMap.Builder<String, ResponseSet> newResponseSetIDMapB =
        ImmutableBiMap.builder();
    // since response sets may lose responses and no longer be unique, we choose the earliest alphabetical ID
    for(final ResponseSet nu: newResponseToOld.keySet()) {
      final ImmutableSet.Builder<String> candidateIDsB = ImmutableSet.builder();
      for(final ResponseSet old: newResponseToOld.get(nu)) {
        candidateIDsB.add(responseSetIDs.inverse().get(old));
      }
      final ImmutableSet<String> candidateIDs = candidateIDsB.build();
      final String newID = Ordering.natural().sortedCopy(candidateIDs).get(0);
      if(candidateIDs.size() > 1) {
        // only log if we're converting multiple sets.
        log.debug("Collapsing response sets {} to {}", candidateIDs, newID);
      }
      newResponseSetIDMapB.put(newID, nu);
    }
    newResponseSetIDMap = Optional.of(newResponseSetIDMapB.build());
  } else {
    newResponseSetIDMap = Optional.absent();
  }

  return ResponseLinking.builder().docID(responseLinking.docID())
      .responseSets(newResponseSets).incompleteResponses(newIncompletes)
      .responseSetIds(newResponseSetIDMap).build();
}
 
Example 13
Project: flow-platform   File: ClassUtil.java   View Source Code Vote up 4 votes
/**
 * Load jar from specific path
 *
 * @param loader specific class loader
 * @param packageName scan package name
 * @param classNameFilter nullable, class name filter, simplelly using contains
 * @param annotationFilter nullable, annotation type filter
 * @return set of classes or null when get error
 */
public static Set<Class<?>> load(
    final ClassLoader loader,
    final String packageName,
    final Set<String> classNameFilter,
    final Set<Class<? extends Annotation>> annotationFilter) {

    ClassPath classPath;
    try {
        classPath = ClassPath.from(loader);
    } catch (IOException e) {
        return null;
    }

    ImmutableSet<ClassInfo> classSet = classPath.getTopLevelClassesRecursive(packageName);
    Set<Class<?>> classes = new HashSet<>(classSet.size());

    for (ClassInfo classInfo : classSet) {
        try {
            Class<?> aClass = classInfo.load();

            // check class name by filter
            if (classNameFilter != null) {
                for (String filter : classNameFilter) {
                    if (aClass.toString().contains(filter)) {
                        classes.add(aClass);
                    }
                }
            }

            // check annotation type by filter
            if (annotationFilter != null) {
                Annotation[] annotations = aClass.getAnnotations();
                for (Annotation annotation : annotations) {
                    for (Class<?> targetType : annotationFilter) {
                        if (annotation.annotationType().equals(targetType)) {
                            classes.add(aClass);
                        }
                    }
                }
            }

            // add class if not filter defined
            if (classNameFilter == null && annotationFilter == null) {
                classes.add(aClass);
            }

        } catch (NoClassDefFoundError ignore) {
            // no class found
        }
    }

    return classes;
}