Search in sources :

Example 16 with TreeSet

use of java.util.TreeSet in project hbase by apache.

the class TestBaseLoadBalancer method assertRetainedAssignment.

/**
   * Asserts a valid retained assignment plan.
   * <p>
   * Must meet the following conditions:
   * <ul>
   * <li>Every input region has an assignment, and to an online server
   * <li>If a region had an existing assignment to a server with the same
   * address a a currently online server, it will be assigned to it
   * </ul>
   * @param existing
   * @param servers
   * @param assignment
   */
private void assertRetainedAssignment(Map<HRegionInfo, ServerName> existing, List<ServerName> servers, Map<ServerName, List<HRegionInfo>> assignment) {
    // Verify condition 1, every region assigned, and to online server
    Set<ServerName> onlineServerSet = new TreeSet<>(servers);
    Set<HRegionInfo> assignedRegions = new TreeSet<>();
    for (Map.Entry<ServerName, List<HRegionInfo>> a : assignment.entrySet()) {
        assertTrue("Region assigned to server that was not listed as online", onlineServerSet.contains(a.getKey()));
        for (HRegionInfo r : a.getValue()) assignedRegions.add(r);
    }
    assertEquals(existing.size(), assignedRegions.size());
    // Verify condition 2, if server had existing assignment, must have same
    Set<String> onlineHostNames = new TreeSet<>();
    for (ServerName s : servers) {
        onlineHostNames.add(s.getHostname());
    }
    for (Map.Entry<ServerName, List<HRegionInfo>> a : assignment.entrySet()) {
        ServerName assignedTo = a.getKey();
        for (HRegionInfo r : a.getValue()) {
            ServerName address = existing.get(r);
            if (address != null && onlineHostNames.contains(address.getHostname())) {
                // this region was prevously assigned somewhere, and that
                // host is still around, then it should be re-assigned on the
                // same host
                assertEquals(address.getHostname(), assignedTo.getHostname());
            }
        }
    }
}
Also used : HRegionInfo(org.apache.hadoop.hbase.HRegionInfo) TreeSet(java.util.TreeSet) ServerName(org.apache.hadoop.hbase.ServerName) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 17 with TreeSet

use of java.util.TreeSet in project buck by facebook.

the class FineGrainedJavaDependencySuggester method createBuildRuleDefinition.

/**
   * Creates the build rule definition for the {@code namedComponent}.
   */
private String createBuildRuleDefinition(NamedStronglyConnectedComponent namedComponent, Map<String, PathSourcePath> providedSymbolToSrc, Multimap<String, String> providedSymbolToRequiredSymbols, Map<String, NamedStronglyConnectedComponent> namedComponentsIndex, JavaDepsFinder.DependencyInfo dependencyInfo, MutableDirectedGraph<String> symbolsDependencies, String visibilityArg) {
    final TargetNode<?, ?> suggestedNode = graph.get(suggestedTarget);
    SortedSet<String> deps = new TreeSet<>(LOCAL_DEPS_FIRST_COMPARATOR);
    SortedSet<PathSourcePath> srcs = new TreeSet<>();
    for (String providedSymbol : namedComponent.symbols) {
        PathSourcePath src = providedSymbolToSrc.get(providedSymbol);
        srcs.add(src);
        for (String requiredSymbol : providedSymbolToRequiredSymbols.get(providedSymbol)) {
            // First, check to see whether the requiredSymbol is in one of the newly created
            // strongly connected components. If so, add it to the deps so long as it is not the
            // strongly connected component that we are currently exploring.
            NamedStronglyConnectedComponent requiredComponent = namedComponentsIndex.get(requiredSymbol);
            if (requiredComponent != null) {
                if (!requiredComponent.equals(namedComponent)) {
                    deps.add(":" + requiredComponent.name);
                }
                continue;
            }
            Set<TargetNode<?, ?>> depProviders = dependencyInfo.symbolToProviders.get(requiredSymbol);
            if (depProviders == null || depProviders.size() == 0) {
                console.getStdErr().printf("# Suspicious: no provider for '%s'\n", requiredSymbol);
                continue;
            }
            depProviders = FluentIterable.from(depProviders).filter(provider -> provider.isVisibleTo(graph, suggestedNode)).toSet();
            TargetNode<?, ?> depProvider;
            if (depProviders.size() == 1) {
                depProvider = Iterables.getOnlyElement(depProviders);
            } else {
                console.getStdErr().printf("# Suspicious: no lone provider for '%s': [%s]\n", requiredSymbol, Joiner.on(", ").join(depProviders));
                continue;
            }
            if (!depProvider.equals(suggestedNode)) {
                deps.add(depProvider.toString());
            }
        }
        // Find deps within package.
        for (String requiredSymbol : symbolsDependencies.getOutgoingNodesFor(providedSymbol)) {
            NamedStronglyConnectedComponent componentDep = Preconditions.checkNotNull(namedComponentsIndex.get(requiredSymbol));
            if (!componentDep.equals(namedComponent)) {
                deps.add(":" + componentDep.name);
            }
        }
    }
    final Path basePathForSuggestedTarget = suggestedTarget.getBasePath();
    Iterable<String> relativeSrcs = FluentIterable.from(srcs).transform(input -> basePathForSuggestedTarget.relativize(input.getRelativePath()).toString());
    StringBuilder rule = new StringBuilder("\njava_library(\n" + "  name = '" + namedComponent.name + "',\n" + "  srcs = [\n");
    for (String src : relativeSrcs) {
        rule.append(String.format("    '%s',\n", src));
    }
    rule.append("  ],\n" + "  deps = [\n");
    for (String dep : deps) {
        rule.append(String.format("    '%s',\n", dep));
    }
    rule.append("  ],\n" + visibilityArg + ")\n");
    return rule.toString();
}
Also used : SourcePath(com.facebook.buck.rules.SourcePath) Path(java.nio.file.Path) PathSourcePath(com.facebook.buck.rules.PathSourcePath) TargetNode(com.facebook.buck.rules.TargetNode) TreeSet(java.util.TreeSet) PathSourcePath(com.facebook.buck.rules.PathSourcePath)

Example 18 with TreeSet

use of java.util.TreeSet in project buck by facebook.

the class FineGrainedJavaDependencySuggester method suggestRefactoring.

/**
   * Suggests a refactoring by printing it to stdout (with warnings printed to stderr).
   * @throws IllegalArgumentException
   */
void suggestRefactoring() {
    final TargetNode<?, ?> suggestedNode = graph.get(suggestedTarget);
    if (!(suggestedNode.getConstructorArg() instanceof JavaLibraryDescription.Arg)) {
        console.printErrorText(String.format("'%s' does not correspond to a Java rule", suggestedTarget));
        throw new IllegalArgumentException();
    }
    JavaLibraryDescription.Arg arg = (JavaLibraryDescription.Arg) suggestedNode.getConstructorArg();
    JavaFileParser javaFileParser = javaDepsFinder.getJavaFileParser();
    Multimap<String, String> providedSymbolToRequiredSymbols = HashMultimap.create();
    Map<String, PathSourcePath> providedSymbolToSrc = new HashMap<>();
    for (SourcePath src : arg.srcs) {
        extractProvidedSymbolInfoFromSourceFile(src, javaFileParser, providedSymbolToRequiredSymbols, providedSymbolToSrc);
    }
    // Create a MutableDirectedGraph from the providedSymbolToRequiredSymbols.
    MutableDirectedGraph<String> symbolsDependencies = new MutableDirectedGraph<>();
    // dependencies.
    for (String providedSymbol : providedSymbolToSrc.keySet()) {
        // Add a node for the providedSymbol in case it has no edges.
        symbolsDependencies.addNode(providedSymbol);
        for (String requiredSymbol : providedSymbolToRequiredSymbols.get(providedSymbol)) {
            if (providedSymbolToRequiredSymbols.containsKey(requiredSymbol) && !providedSymbol.equals(requiredSymbol)) {
                symbolsDependencies.addEdge(providedSymbol, requiredSymbol);
            }
        }
    }
    // Determine the strongly connected components.
    Set<Set<String>> stronglyConnectedComponents = symbolsDependencies.findStronglyConnectedComponents();
    // Maps a providedSymbol to the component that contains it.
    Map<String, NamedStronglyConnectedComponent> namedComponentsIndex = new TreeMap<>();
    Set<NamedStronglyConnectedComponent> namedComponents = new TreeSet<>();
    for (Set<String> stronglyConnectedComponent : stronglyConnectedComponents) {
        // We just use the first provided symbol in the strongly connected component as the canonical
        // name for the component. Maybe not the best name, but certainly not the worst.
        String name = Iterables.getFirst(stronglyConnectedComponent, /* defaultValue */
        null);
        if (name == null) {
            throw new IllegalStateException("A strongly connected component was created with zero nodes.");
        }
        NamedStronglyConnectedComponent namedComponent = new NamedStronglyConnectedComponent(name, stronglyConnectedComponent);
        namedComponents.add(namedComponent);
        for (String providedSymbol : stronglyConnectedComponent) {
            namedComponentsIndex.put(providedSymbol, namedComponent);
        }
    }
    // Visibility argument.
    StringBuilder visibilityBuilder = new StringBuilder("  visibility = [\n");
    SortedSet<String> visibilities = FluentIterable.from(suggestedNode.getVisibilityPatterns()).transform(VisibilityPattern::getRepresentation).toSortedSet(Ordering.natural());
    for (String visibility : visibilities) {
        visibilityBuilder.append("    '" + visibility + "',\n");
    }
    visibilityBuilder.append("  ],\n");
    String visibilityArg = visibilityBuilder.toString();
    // Print out the new version of the original rule.
    console.getStdOut().printf("java_library(\n" + "  name = '%s',\n" + "  exported_deps = [\n", suggestedTarget.getShortName());
    for (NamedStronglyConnectedComponent namedComponent : namedComponents) {
        console.getStdOut().printf("    ':%s',\n", namedComponent.name);
    }
    console.getStdOut().print("  ],\n" + visibilityArg + ")\n");
    // Print out a rule for each of the strongly connected components.
    JavaDepsFinder.DependencyInfo dependencyInfo = javaDepsFinder.findDependencyInfoForGraph(graph);
    for (NamedStronglyConnectedComponent namedComponent : namedComponents) {
        String buildRuleDefinition = createBuildRuleDefinition(namedComponent, providedSymbolToSrc, providedSymbolToRequiredSymbols, namedComponentsIndex, dependencyInfo, symbolsDependencies, visibilityArg);
        console.getStdOut().print(buildRuleDefinition);
    }
}
Also used : JavaDepsFinder(com.facebook.buck.jvm.java.autodeps.JavaDepsFinder) SortedSet(java.util.SortedSet) TreeSet(java.util.TreeSet) Set(java.util.Set) HashMap(java.util.HashMap) JavaFileParser(com.facebook.buck.jvm.java.JavaFileParser) SourcePath(com.facebook.buck.rules.SourcePath) PathSourcePath(com.facebook.buck.rules.PathSourcePath) TreeSet(java.util.TreeSet) JavaLibraryDescription(com.facebook.buck.jvm.java.JavaLibraryDescription) PathSourcePath(com.facebook.buck.rules.PathSourcePath) TreeMap(java.util.TreeMap) MutableDirectedGraph(com.facebook.buck.graph.MutableDirectedGraph)

Example 19 with TreeSet

use of java.util.TreeSet in project pinot by linkedin.

the class PinotRestletApplication method attachRoutesForClass.

protected void attachRoutesForClass(Router router, Class<? extends ServerResource> clazz) {
    TreeSet<String> pathsOrderedByLength = new TreeSet<String>(ComparatorUtils.chainedComparator(new Comparator<String>() {

        @Override
        public int compare(String left, String right) {
            int leftLength = left.length();
            int rightLength = right.length();
            return leftLength < rightLength ? -1 : (leftLength == rightLength ? 0 : 1);
        }
    }, ComparatorUtils.NATURAL_COMPARATOR));
    for (Method method : clazz.getDeclaredMethods()) {
        Annotation annotationInstance = method.getAnnotation(Paths.class);
        if (annotationInstance != null) {
            pathsOrderedByLength.addAll(Arrays.asList(((Paths) annotationInstance).value()));
        }
    }
    for (String routePath : pathsOrderedByLength) {
        LOGGER.info("Attaching route {} -> {}", routePath, clazz.getSimpleName());
        attachRoute(router, routePath, clazz);
    }
}
Also used : TreeSet(java.util.TreeSet) Method(java.lang.reflect.Method) Paths(com.linkedin.pinot.common.restlet.swagger.Paths) Annotation(java.lang.annotation.Annotation) Comparator(java.util.Comparator)

Example 20 with TreeSet

use of java.util.TreeSet in project pinot by linkedin.

the class MultipleOrEqualitiesToInClauseFilterQueryTreeOptimizer method collectChildOperators.

private boolean collectChildOperators(FilterQueryTree filterQueryTree, Map<String, Set<String>> columnToValues, List<FilterQueryTree> nonEqualityOperators) {
    boolean containsDuplicates = false;
    for (FilterQueryTree childQueryTree : filterQueryTree.getChildren()) {
        if (childQueryTree.getOperator() == FilterOperator.EQUALITY || childQueryTree.getOperator() == FilterOperator.IN) {
            List<String> childValues = valueDoubleTabListToElements(childQueryTree.getValue());
            if (!columnToValues.containsKey(childQueryTree.getColumn())) {
                TreeSet<String> value = new TreeSet<>(childValues);
                columnToValues.put(childQueryTree.getColumn(), value);
                if (!containsDuplicates && value.size() != childValues.size()) {
                    containsDuplicates = true;
                }
            } else {
                Set<String> currentValues = columnToValues.get(childQueryTree.getColumn());
                for (String childValue : childValues) {
                    if (!containsDuplicates && currentValues.contains(childValue)) {
                        containsDuplicates = true;
                    } else {
                        currentValues.add(childValue);
                    }
                }
            }
        } else {
            nonEqualityOperators.add(childQueryTree);
        }
    }
    return containsDuplicates;
}
Also used : FilterQueryTree(com.linkedin.pinot.common.utils.request.FilterQueryTree) TreeSet(java.util.TreeSet)

Aggregations

TreeSet (java.util.TreeSet)3795 ArrayList (java.util.ArrayList)835 Test (org.junit.Test)544 HashMap (java.util.HashMap)502 HashSet (java.util.HashSet)430 Set (java.util.Set)424 Map (java.util.Map)405 IOException (java.io.IOException)378 File (java.io.File)341 List (java.util.List)323 TreeMap (java.util.TreeMap)229 Iterator (java.util.Iterator)189 SortedSet (java.util.SortedSet)186 LinkedList (java.util.LinkedList)110 LinkedHashSet (java.util.LinkedHashSet)106 Date (java.util.Date)94 Collection (java.util.Collection)92 Comparator (java.util.Comparator)85 Test (org.testng.annotations.Test)81 Text (org.apache.hadoop.io.Text)79