Search in sources :

Example 1 with SetMultimap

use of com.google.common.collect.SetMultimap in project checkstyle by checkstyle.

the class TranslationCheck method checkFilesForConsistencyRegardingTheirKeys.

/**
     * Compares th the specified key set with the key sets of the given translation files (arranged
     * in a map). All missing keys are reported.
     * @param fileKeys a Map from translation files to their key sets.
     * @param keysThatMustExist the set of keys to compare with.
     */
private void checkFilesForConsistencyRegardingTheirKeys(SetMultimap<File, String> fileKeys, Set<String> keysThatMustExist) {
    for (File currentFile : fileKeys.keySet()) {
        final MessageDispatcher dispatcher = getMessageDispatcher();
        final String path = currentFile.getPath();
        dispatcher.fireFileStarted(path);
        final Set<String> currentFileKeys = fileKeys.get(currentFile);
        final Set<String> missingKeys = keysThatMustExist.stream().filter(e -> !currentFileKeys.contains(e)).collect(Collectors.toSet());
        if (!missingKeys.isEmpty()) {
            for (Object key : missingKeys) {
                log(0, MSG_KEY, key);
            }
        }
        fireErrors(path);
        dispatcher.fireFileFinished(path);
    }
}
Also used : Arrays(java.util.Arrays) SortedSet(java.util.SortedSet) LocalizedMessage(com.puppycrawl.tools.checkstyle.api.LocalizedMessage) CommonUtils(com.puppycrawl.tools.checkstyle.utils.CommonUtils) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) Matcher(java.util.regex.Matcher) HashMultimap(com.google.common.collect.HashMultimap) Locale(java.util.Locale) Closeables(com.google.common.io.Closeables) MessageDispatcher(com.puppycrawl.tools.checkstyle.api.MessageDispatcher) Definitions(com.puppycrawl.tools.checkstyle.Definitions) Properties(java.util.Properties) AbstractFileSetCheck(com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck) Set(java.util.Set) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Collectors(java.util.stream.Collectors) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) SetMultimap(com.google.common.collect.SetMultimap) List(java.util.List) Optional(java.util.Optional) Log(org.apache.commons.logging.Log) Pattern(java.util.regex.Pattern) LogFactory(org.apache.commons.logging.LogFactory) Collections(java.util.Collections) InputStream(java.io.InputStream) MessageDispatcher(com.puppycrawl.tools.checkstyle.api.MessageDispatcher) File(java.io.File)

Example 2 with SetMultimap

use of com.google.common.collect.SetMultimap in project buck by facebook.

the class OwnersReport method generateOwnersReport.

@VisibleForTesting
static OwnersReport generateOwnersReport(Cell rootCell, TargetNode<?, ?> targetNode, Iterable<String> filePaths) {
    // Process arguments assuming they are all relative file paths.
    Set<Path> inputs = Sets.newHashSet();
    Set<String> nonExistentInputs = Sets.newHashSet();
    Set<String> nonFileInputs = Sets.newHashSet();
    for (String filePath : filePaths) {
        Path file = rootCell.getFilesystem().getPathForRelativePath(filePath);
        if (!Files.exists(file)) {
            nonExistentInputs.add(filePath);
        } else if (!Files.isRegularFile(file)) {
            nonFileInputs.add(filePath);
        } else {
            inputs.add(rootCell.getFilesystem().getPath(filePath));
        }
    }
    // Try to find owners for each valid and existing file.
    Set<Path> inputsWithNoOwners = Sets.newHashSet(inputs);
    SetMultimap<TargetNode<?, ?>, Path> owners = TreeMultimap.create();
    for (final Path commandInput : inputs) {
        Predicate<Path> startsWith = input -> !commandInput.equals(input) && commandInput.startsWith(input);
        Set<Path> ruleInputs = targetNode.getInputs();
        if (ruleInputs.contains(commandInput) || FluentIterable.from(ruleInputs).anyMatch(startsWith)) {
            inputsWithNoOwners.remove(commandInput);
            owners.put(targetNode, commandInput);
        }
    }
    return new OwnersReport(owners, inputsWithNoOwners, nonExistentInputs, nonFileInputs);
}
Also used : Path(java.nio.file.Path) BuckEventBus(com.facebook.buck.event.BuckEventBus) BuildFileTree(com.facebook.buck.model.BuildFileTree) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) ImmutableList(com.google.common.collect.ImmutableList) FluentIterable(com.google.common.collect.FluentIterable) TreeMultimap(com.google.common.collect.TreeMultimap) Map(java.util.Map) BuildFileParseException(com.facebook.buck.json.BuildFileParseException) Cell(com.facebook.buck.rules.Cell) Path(java.nio.file.Path) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) Parser(com.facebook.buck.parser.Parser) ImmutableSet(com.google.common.collect.ImmutableSet) Files(java.nio.file.Files) TargetNode(com.facebook.buck.rules.TargetNode) Set(java.util.Set) IOException(java.io.IOException) Console(com.facebook.buck.util.Console) Maps(com.google.common.collect.Maps) SetMultimap(com.google.common.collect.SetMultimap) Sets(com.google.common.collect.Sets) MorePaths(com.facebook.buck.io.MorePaths) Predicate(com.google.common.base.Predicate) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) TargetNode(com.facebook.buck.rules.TargetNode) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 3 with SetMultimap

use of com.google.common.collect.SetMultimap in project github-version-statistics by centic9.

the class SplitStats method main.

public static void main(String[] args) throws IOException {
    List<String> lines = FileUtils.readLines(new File("stats.json"), "UTF-8");
    // collect all to combine
    Map<String, SetMultimap<String, String>> byDate = new HashMap<>();
    for (String line : lines) {
        Holder holder = JSONWriter.mapper.readValue(line, Holder.class);
        SetMultimap<String, String> existing = byDate.get(holder.getDate());
        if (existing != null) {
            existing.putAll(holder.getVersions());
        } else {
            byDate.put(holder.getDate(), holder.getVersions());
        }
    }
    for (Entry<String, SetMultimap<String, String>> entry : byDate.entrySet()) {
        JSONWriter.write(entry.getKey(), entry.getValue());
    }
}
Also used : SetMultimap(com.google.common.collect.SetMultimap) HashMap(java.util.HashMap) Holder(org.dstadler.github.JSONWriter.Holder) File(java.io.File)

Example 4 with SetMultimap

use of com.google.common.collect.SetMultimap in project records-management by Alfresco.

the class PublicAPITestUtil method testPublicAPIConsistency.

/**
 * Check the consistency of the public API exposed from the given package. For each class in the package that is
 * annotated {@link AlfrescoPublicApi}, check that no exposed methods (or fields, constructors, etc.) use
 * non-public-API classes from Alfresco.
 *
 * @param basePackageName The package to check classes within.
 * @param knownBadReferences Any references that would cause this test to fail, but which we don't want to change.
 *            The keys should be public API classes within our code and the values should be the non-public-API
 *            class that is being referenced.
 */
public static void testPublicAPIConsistency(String basePackageName, SetMultimap<Class<?>, Class<?>> knownBadReferences) {
    Reflections reflections = new Reflections(basePackageName);
    Set<Class<?>> publicAPIClasses = reflections.getTypesAnnotatedWith(AlfrescoPublicApi.class, true);
    SetMultimap<Class<?>, Class<?>> referencedFrom = HashMultimap.create();
    Set<Class<?>> referencedClasses = new HashSet<>();
    for (Class<?> publicAPIClass : publicAPIClasses) {
        Set<Class<?>> referencedClassesFromClass = getReferencedClassesFromClass(publicAPIClass, new HashSet<>());
        referencedClassesFromClass.forEach(clazz -> referencedFrom.put(clazz, publicAPIClass));
        // Remove any references in knownBadReferences and error if an expected reference wasn't found.
        if (knownBadReferences.containsKey(publicAPIClass)) {
            for (Class<?> clazz : knownBadReferences.get(publicAPIClass)) {
                assertTrue("Supplied knownBadReferences expects " + clazz + " to be referenced by " + publicAPIClass + ", but no such error was found", referencedClassesFromClass.remove(clazz));
            }
        }
        referencedClasses.addAll(referencedClassesFromClass);
    }
    List<String> errorMessages = new ArrayList<>();
    for (Class<?> referencedClass : referencedClasses) {
        if (isInAlfresco(referencedClass) && !isPartOfPublicApi(referencedClass)) {
            Set<String> referencerNames = referencedFrom.get(referencedClass).stream().map(c -> c.getName()).collect(Collectors.toSet());
            errorMessages.add(referencedClass.getName() + " <- " + StringUtils.join(referencerNames, ", "));
        }
    }
    if (!errorMessages.isEmpty()) {
        System.out.println("Errors found:");
        System.out.println(StringUtils.join(errorMessages, "\n"));
    }
    assertEquals("Found references to non-public API classes from public API classes.", Collections.emptyList(), errorMessages);
}
Also used : GenericArrayType(java.lang.reflect.GenericArrayType) AlfrescoPublicApi(org.alfresco.api.AlfrescoPublicApi) TypeVariable(java.lang.reflect.TypeVariable) WildcardType(java.lang.reflect.WildcardType) Assert.assertTrue(org.junit.Assert.assertTrue) Set(java.util.Set) Reflections(org.reflections.Reflections) Field(java.lang.reflect.Field) Constructor(java.lang.reflect.Constructor) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) SetMultimap(com.google.common.collect.SetMultimap) Sets(com.google.common.collect.Sets) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) List(java.util.List) HashMultimap(com.google.common.collect.HashMultimap) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Modifier(java.lang.reflect.Modifier) Executable(java.lang.reflect.Executable) Method(java.lang.reflect.Method) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ArrayList(java.util.ArrayList) Reflections(org.reflections.Reflections) HashSet(java.util.HashSet)

Example 5 with SetMultimap

use of com.google.common.collect.SetMultimap in project presto by prestodb.

the class PrestoSparkRddFactory method createTaskSourcesRdd.

private PrestoSparkTaskSourceRdd createTaskSourcesRdd(PlanFragmentId fragmentId, JavaSparkContext sparkContext, Session session, PartitioningHandle partitioning, List<TableScanNode> tableScans, Map<PlanNodeId, SplitSource> splitSources, Optional<Integer> numberOfShufflePartitions) {
    ListMultimap<Integer, SerializedPrestoSparkTaskSource> taskSourcesMap = ArrayListMultimap.create();
    for (TableScanNode tableScan : tableScans) {
        int totalNumberOfSplits = 0;
        SplitSource splitSource = requireNonNull(splitSources.get(tableScan.getId()), "split source is missing for table scan node with id: " + tableScan.getId());
        try (PrestoSparkSplitAssigner splitAssigner = createSplitAssigner(session, tableScan.getId(), splitSource, partitioning)) {
            while (true) {
                Optional<SetMultimap<Integer, ScheduledSplit>> batch = splitAssigner.getNextBatch();
                if (!batch.isPresent()) {
                    break;
                }
                int numberOfSplitsInCurrentBatch = batch.get().size();
                log.info("Found %s splits for table scan node with id %s", numberOfSplitsInCurrentBatch, tableScan.getId());
                totalNumberOfSplits += numberOfSplitsInCurrentBatch;
                taskSourcesMap.putAll(createTaskSources(tableScan.getId(), batch.get()));
            }
        }
        log.info("Total number of splits for table scan node with id %s: %s", tableScan.getId(), totalNumberOfSplits);
    }
    long allTaskSourcesSerializedSizeInBytes = taskSourcesMap.values().stream().mapToLong(serializedTaskSource -> serializedTaskSource.getBytes().length).sum();
    log.info("Total serialized size of all task sources for fragment %s: %s", fragmentId, DataSize.succinctBytes(allTaskSourcesSerializedSizeInBytes));
    List<List<SerializedPrestoSparkTaskSource>> taskSourcesByPartitionId = new ArrayList<>();
    // If the fragment contains any shuffle inputs, this value will be present
    if (numberOfShufflePartitions.isPresent()) {
        // non bucketed tables match, an empty partition must be inserted if bucket is missing.
        for (int partitionId = 0; partitionId < numberOfShufflePartitions.get(); partitionId++) {
            // Eagerly remove task sources from the map to let GC reclaim the memory
            // If task sources are missing for a partition the removeAll returns an empty list
            taskSourcesByPartitionId.add(requireNonNull(taskSourcesMap.removeAll(partitionId), "taskSources is null"));
        }
    } else {
        taskSourcesByPartitionId.addAll(Multimaps.asMap(taskSourcesMap).values());
    }
    return new PrestoSparkTaskSourceRdd(sparkContext.sc(), taskSourcesByPartitionId);
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) WarningCollector(com.facebook.presto.spi.WarningCollector) JsonCodec(com.facebook.airlift.json.JsonCodec) ListMultimap(com.google.common.collect.ListMultimap) RemoteSourceNode(com.facebook.presto.sql.planner.plan.RemoteSourceNode) PrestoSparkTaskRdd(com.facebook.presto.spark.classloader_interface.PrestoSparkTaskRdd) SplitSourceFactory(com.facebook.presto.sql.planner.SplitSourceFactory) PrestoSparkUtils.serializeZstdCompressed(com.facebook.presto.spark.util.PrestoSparkUtils.serializeZstdCompressed) TableWriteInfo(com.facebook.presto.execution.scheduler.TableWriteInfo) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Sets.difference(com.google.common.collect.Sets.difference) PlanFragment(com.facebook.presto.sql.planner.PlanFragment) MutablePartitionId(com.facebook.presto.spark.classloader_interface.MutablePartitionId) PrestoSparkShuffleStats(com.facebook.presto.spark.classloader_interface.PrestoSparkShuffleStats) Map(java.util.Map) Sets.union(com.google.common.collect.Sets.union) FIXED_BROADCAST_DISTRIBUTION(com.facebook.presto.sql.planner.SystemPartitioningHandle.FIXED_BROADCAST_DISTRIBUTION) SplitSource(com.facebook.presto.split.SplitSource) Broadcast(org.apache.spark.broadcast.Broadcast) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) SplitManager(com.facebook.presto.split.SplitManager) Tuple2(scala.Tuple2) SOURCE_DISTRIBUTION(com.facebook.presto.sql.planner.SystemPartitioningHandle.SOURCE_DISTRIBUTION) Codec(com.facebook.airlift.json.Codec) String.format(java.lang.String.format) PrestoSparkTaskProcessor(com.facebook.presto.spark.classloader_interface.PrestoSparkTaskProcessor) DataSize(io.airlift.units.DataSize) List(java.util.List) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) NOT_SUPPORTED(com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED) PrestoSparkTaskExecutorFactoryProvider(com.facebook.presto.spark.classloader_interface.PrestoSparkTaskExecutorFactoryProvider) SerializedPrestoSparkTaskDescriptor(com.facebook.presto.spark.classloader_interface.SerializedPrestoSparkTaskDescriptor) SerializedTaskInfo(com.facebook.presto.spark.classloader_interface.SerializedTaskInfo) Optional(java.util.Optional) FIXED_HASH_DISTRIBUTION(com.facebook.presto.sql.planner.SystemPartitioningHandle.FIXED_HASH_DISTRIBUTION) RDD(org.apache.spark.rdd.RDD) PrestoSparkUtils.classTag(com.facebook.presto.spark.util.PrestoSparkUtils.classTag) PlanNodeId(com.facebook.presto.spi.plan.PlanNodeId) ARBITRARY_DISTRIBUTION(com.facebook.presto.sql.planner.SystemPartitioningHandle.ARBITRARY_DISTRIBUTION) Logger(com.facebook.airlift.log.Logger) FIXED_ARBITRARY_DISTRIBUTION(com.facebook.presto.sql.planner.SystemPartitioningHandle.FIXED_ARBITRARY_DISTRIBUTION) SINGLE_DISTRIBUTION(com.facebook.presto.sql.planner.SystemPartitioningHandle.SINGLE_DISTRIBUTION) JavaSparkContext(org.apache.spark.api.java.JavaSparkContext) HashMap(java.util.HashMap) PrestoException(com.facebook.presto.spi.PrestoException) Multimaps(com.google.common.collect.Multimaps) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) PrestoSparkTaskSourceRdd(com.facebook.presto.spark.classloader_interface.PrestoSparkTaskSourceRdd) PrestoSparkTaskOutput(com.facebook.presto.spark.classloader_interface.PrestoSparkTaskOutput) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) ScheduledSplit(com.facebook.presto.execution.ScheduledSplit) PlanFragmentId(com.facebook.presto.sql.planner.plan.PlanFragmentId) CloseableSplitSourceProvider(com.facebook.presto.split.CloseableSplitSourceProvider) FIXED_PASSTHROUGH_DISTRIBUTION(com.facebook.presto.sql.planner.SystemPartitioningHandle.FIXED_PASSTHROUGH_DISTRIBUTION) PlanNodeSearcher.searchFrom(com.facebook.presto.sql.planner.optimizations.PlanNodeSearcher.searchFrom) PrestoSparkTaskDescriptor(com.facebook.presto.spark.PrestoSparkTaskDescriptor) SerializedPrestoSparkTaskSource(com.facebook.presto.spark.classloader_interface.SerializedPrestoSparkTaskSource) PrestoSparkMutableRow(com.facebook.presto.spark.classloader_interface.PrestoSparkMutableRow) Session(com.facebook.presto.Session) TaskSource(com.facebook.presto.execution.TaskSource) SCALED_WRITER_DISTRIBUTION(com.facebook.presto.sql.planner.SystemPartitioningHandle.SCALED_WRITER_DISTRIBUTION) CollectionAccumulator(org.apache.spark.util.CollectionAccumulator) JavaPairRDD(org.apache.spark.api.java.JavaPairRDD) SetMultimap(com.google.common.collect.SetMultimap) PlanNode(com.facebook.presto.spi.plan.PlanNode) TableScanNode(com.facebook.presto.spi.plan.TableScanNode) PartitioningHandle(com.facebook.presto.sql.planner.PartitioningHandle) PartitioningProviderManager(com.facebook.presto.sql.planner.PartitioningProviderManager) COORDINATOR_DISTRIBUTION(com.facebook.presto.sql.planner.SystemPartitioningHandle.COORDINATOR_DISTRIBUTION) ArrayList(java.util.ArrayList) SerializedPrestoSparkTaskSource(com.facebook.presto.spark.classloader_interface.SerializedPrestoSparkTaskSource) SetMultimap(com.google.common.collect.SetMultimap) TableScanNode(com.facebook.presto.spi.plan.TableScanNode) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) SplitSource(com.facebook.presto.split.SplitSource) PrestoSparkTaskSourceRdd(com.facebook.presto.spark.classloader_interface.PrestoSparkTaskSourceRdd)

Aggregations

SetMultimap (com.google.common.collect.SetMultimap)22 List (java.util.List)12 Map (java.util.Map)12 Set (java.util.Set)11 HashSet (java.util.HashSet)9 Optional (java.util.Optional)9 ImmutableSet (com.google.common.collect.ImmutableSet)8 ArrayList (java.util.ArrayList)8 Collections (java.util.Collections)8 HashMap (java.util.HashMap)8 HashMultimap (com.google.common.collect.HashMultimap)7 ImmutableMap (com.google.common.collect.ImmutableMap)7 Sets (com.google.common.collect.Sets)6 ImmutableList (com.google.common.collect.ImmutableList)5 ImmutableSetMultimap (com.google.common.collect.ImmutableSetMultimap)5 Maps (com.google.common.collect.Maps)4 Collection (java.util.Collection)4 VisibleForTesting (com.google.common.annotations.VisibleForTesting)3 Preconditions.checkState (com.google.common.base.Preconditions.checkState)3 LinkedHashMultimap (com.google.common.collect.LinkedHashMultimap)3