com.google.common.collect.TreeMultimap Java Examples

The following examples show how to use com.google.common.collect.TreeMultimap. 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: VariableScopeExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Return a multimap containing all the (local) variables of the given
 * scope.
 * 
 * @param cu
 * @return Multimap<Snippet, VariableName>
 */
public static Multimap<Scope, String> getScopeSnippets(final ASTNode cu) {
	final VariableScopeFinder scopeFinder = new VariableScopeFinder();
	cu.accept(scopeFinder);

	final Multimap<Scope, String> scopes = TreeMultimap.create();
	for (final Entry<ASTNode, Variable> variable : scopeFinder.variableScopes
			.entries()) {
		final int astNodeType = variable.getKey().getNodeType();
		final int astNodeParentType;
		if (variable.getKey().getParent() == null) {
			astNodeParentType = -1;
		} else {
			astNodeParentType = variable.getKey().getParent().getNodeType();
		}
		scopes.put(
				new Scope(variable.getKey().toString(),
						variable.getValue().scope,
						variable.getValue().type, astNodeType,
						astNodeParentType), variable.getValue().name);
	}

	return scopes;

}
 
Example #2
Source File: EntityUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Encodes dimensions multimap to filter strings.
 *
 * @param filters dimensions multimap
 * @return filter string fragments
 */
public static List<String> encodeDimensions(Multimap<String, String> filters) {
  List<String> output = new ArrayList<>();

  Multimap<String, String> sorted = TreeMultimap.create(filters);
  for(Map.Entry<String, String> entry : sorted.entries()) {
    String operator = "=";
    String value = entry.getValue();

    // check for exclusion case
    for (Map.Entry<String, String> prefix : FILTER_TO_OPERATOR.entrySet()) {
      if (entry.getValue().startsWith(prefix.getKey())) {
        operator = prefix.getValue();
        value = entry.getValue().substring(prefix.getKey().length());
        break;
      }
    }

    output.add(EntityUtils.encodeURNComponent(String.format("%s%s%s", entry.getKey(), operator, value)));
  }

  return output;
}
 
Example #3
Source File: MethodScopeExtractor.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
public static Multimap<Scope, String> getScopeSnippets(final ASTNode node,
		final boolean methodAsRoots) {
	final ScopeFinder scopeFinder = new ScopeFinder(methodAsRoots);
	node.accept(scopeFinder);

	final Multimap<Scope, String> scopes = TreeMultimap.create();
	for (final Entry<ASTNode, Method> method : scopeFinder.methods
			.entries()) {
		scopes.put(new Scope(method.getKey().toString(),
				method.getValue().type, METHOD_CALL, 0, 0), method
				.getValue().name);
	}

	return scopes;

}
 
Example #4
Source File: RocksDBMapMutationSet.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
@Override
public void addAll(TreeMultimap<ByteString, ByteString> map)
{
  try(WriteBatch batch = new WriteBatch())
  {
    byte b[]=new byte[0];

    for(Map.Entry<ByteString, ByteString> me : map.entries())
    {
      ByteString w = getDBKey(me.getKey(), me.getValue());
      batch.put(w.toByteArray(), b);
    }

    db.write(jdb.getWriteOption(), batch);
  }
  catch(RocksDBException e)
  {
    throw new RuntimeException(e);
  }

}
 
Example #5
Source File: Intersection.java    From datawave with Apache License 2.0 6 votes vote down vote up
static TreeMultimap<String,IndexStream> nextAll(String key, Collection<IndexStream> streams) {
    TreeMultimap<String,IndexStream> newChildren = TreeMultimap.create(Ordering.natural(), Ordering.arbitrary());
    for (IndexStream itr : streams) {
        if (!isDay(key) && isDay(key(itr.peek()))) {
            newChildren.put(itr.peek().first(), itr);
        } else {
            itr.next();
            if (itr.hasNext()) {
                newChildren.put(itr.peek().first(), itr);
            } else {
                return TreeMultimap.create(Ordering.natural(), Ordering.arbitrary());
            }
        }
    }
    return newChildren;
}
 
Example #6
Source File: MetadataDictionaryUtil.java    From emissary with Apache License 2.0 6 votes vote down vote up
/**
 * Read each line of input, tokenize them into key/value pairs, perform a lookup/transformation of the keys via the
 * MetadataDictionary where applicable, and return the results as a map.
 * 
 * @param input the bytes to convert
 * @param output a ByteArrayOutputStream to write failed parse attempts to
 * @return a Map containing each line converted to a key/value pair and sorted alphabetically by key
 * @throws IOException If there is some I/O problem.
 */
public Map<String, Collection<String>> convertLinesToMap(final byte[] input, final ByteArrayOutputStream output) throws IOException {
    final TreeMultimap<String, String> kv = TreeMultimap.create();
    final LineTokenizer ltok = new LineTokenizer(input, this.charset);

    // Look at each line for a key value and run it through the dictionary
    while (ltok.hasMoreTokens()) {
        final String line = ltok.nextToken();
        final int pos = line.indexOf(SEP);
        if (pos == -1) {
            output.write(line.getBytes());
            output.write('\n');
            this.logger.debug("Found no key/value pair on line " + line);
        } else {
            final String key = line.substring(0, pos);
            final String value = line.substring(pos + 1);
            final String nkey = this.dict.map(this.servicePrefix + key);
            kv.put(nkey, value.trim());
            this.logger.debug("Mapped key " + key + " to " + nkey + ": " + value);
        }
    }
    return new TreeMap<>(kv.asMap());
}
 
Example #7
Source File: AggregateMultiProjectTaskReportModel.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void build() {
    groups = TreeMultimap.create(new Comparator<String>() {
        public int compare(String string1, String string2) {
            return string1.compareToIgnoreCase(string2);
        }
    }, new Comparator<TaskDetails>() {
        public int compare(TaskDetails task1, TaskDetails task2) {
            return task1.getPath().compareTo(task2.getPath());
        }
    });
    for (TaskReportModel project : projects) {
        for (String group : project.getGroups()) {
            for (final TaskDetails task : project.getTasksForGroup(group)) {
                groups.put(group, mergeTasksWithSameName ? new MergedTaskDetails(task) : task);
            }
        }
    }
}
 
Example #8
Source File: WalletUtil.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
public static Collection<AddressSpecHash> getAddressesByAge(WalletDatabase db, NetworkParams params)
{
  TreeMultimap<Long, AddressSpecHash> age_map = TreeMultimap.create();
  for(AddressSpec spec : db.getAddressesList())
  {
    String addr = AddressUtil.getAddressString(spec, params);
    long tm = 0;
    if (db.getAddressCreateTimeMap().containsKey(addr))
    {
      tm = db.getAddressCreateTimeMap().get(addr);
    }
    age_map.put(tm, AddressUtil.getHashForSpec(spec));

  }

  return age_map.values();

}
 
Example #9
Source File: NegationFilterTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void testContains() throws Throwable {
    List<String> filterSet1 = Lists.newArrayList("a", "b");
    Itr<String> f1 = new Itr<>(filterSet1);
    List<String> filterSet2 = Lists.newArrayList("a", "b", "c", "d", "e", "f");
    Itr<String> f2 = new Itr<>(filterSet2);
    TreeMultimap<String,NestedIterator<String>> mmap = TreeMultimap.create(Util.keyComparator(), Util.hashComparator());
    mmap.put(f1.next(), f1);
    mmap.put("c", f2);
    
    assertTrue(NegationFilter.isFiltered("c", mmap, Util.keyTransformer()));
    // even though filterSet1 is outside the bounds, the contains check doesn't move anything, this is expected and good
    assertEquals(2, mmap.keySet().size());
    Iterator<String> i = mmap.keySet().iterator();
    assertEquals("a", i.next());
    assertEquals("c", i.next());
    assertFalse(i.hasNext());
    assertEquals(2, mmap.values().size());
}
 
Example #10
Source File: ExpressionFormatter.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public String visitObjectLiteral(ObjectLiteral node, Void context) {
    StringBuilder builder = new StringBuilder("{");
    boolean first = true;
    TreeMultimap<String, Expression> sorted = TreeMultimap.create(
            Ordering.natural().nullsLast(),
            Ordering.usingToString().nullsLast()
    );
    sorted.putAll(node.values());
    for (Map.Entry<String, Expression> entry : sorted.entries()) {
        if (!first) {
            builder.append(", ");
        } else {
            first = false;
        }
        builder.append(formatIdentifier(entry.getKey()))
               .append("= ")
               .append(entry.getValue().accept(this, context));

    }
    return builder.append("}").toString();
}
 
Example #11
Source File: MethodScopeExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static Multimap<Scope, String> getScopeSnippets(final ASTNode node,
		final boolean methodAsRoots) {
	final ScopeFinder scopeFinder = new ScopeFinder(methodAsRoots);
	node.accept(scopeFinder);

	final Multimap<Scope, String> scopes = TreeMultimap.create();
	for (final Entry<ASTNode, Method> method : scopeFinder.methods
			.entries()) {
		scopes.put(new Scope(method.getKey().toString(),
				method.getValue().type, METHOD_CALL, 0, 0), method
				.getValue().name);
	}

	return scopes;

}
 
Example #12
Source File: TreeMapStore.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Constructor
 */
public TreeMapStore() {
    /*
     * For the start times index, the "key comparator" will compare the
     * start times as longs directly. This is the primary comparator for its
     * tree map.
     *
     * The secondary "value" comparator will check the end times first, and
     * in the event of a tie, defer to the ISegment's Comparable
     * implementation, a.k.a. its natural ordering.
     */
    fStartTimesIndex = TreeMultimap.create(Comparator.<Long>naturalOrder(),
            Comparator.comparingLong(E::getEnd).thenComparing(Function.identity()));

    fSize = 0;
}
 
Example #13
Source File: ASTClassInfoPrinter.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public static void main(String... args) {
  // Clear saved state for new calls.
  tree = TreeMultimap.create();
  astLookup = Sets.newHashSet();
  ClassPath cp = null;
  try {
    cp = ClassPath.from(ClassLoader.getSystemClassLoader());
  } catch (IOException e) {
    ErrorUtil.error(e.getMessage());
    System.exit(1);
  }
  for (ClassInfo c : cp.getTopLevelClasses("org.eclipse.jdt.core.dom")){
    astLookup.add(c.getSimpleName());
  }
  for (ClassInfo ci : cp.getTopLevelClasses("com.google.devtools.j2objc.ast")) {
    // Ignore package-info and JUnit tests.
    if (ci.getSimpleName().equals("package-info") || TestCase.class.isAssignableFrom(ci.load())) {
      continue;
    }
    walkSuperclassHierarchy(ci.load());
  }
  // Print hierarchy descending from Object.
  printClassHierarchy("Object", "");
}
 
Example #14
Source File: VariableScopeExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Return a multimap containing all the (local) variables of the given
 * scope.
 * 
 * @param cu
 * @return Multimap<Snippet, VariableName>
 */
public static Multimap<Scope, String> getScopeSnippets(final ASTNode cu) {
	final VariableScopeFinder scopeFinder = new VariableScopeFinder();
	cu.accept(scopeFinder);

	final Multimap<Scope, String> scopes = TreeMultimap.create();
	for (final Entry<ASTNode, Variable> variable : scopeFinder.variableScopes
			.entries()) {
		final int astNodeType = variable.getKey().getNodeType();
		final int astNodeParentType;
		if (variable.getKey().getParent() == null) {
			astNodeParentType = -1;
		} else {
			astNodeParentType = variable.getKey().getParent().getNodeType();
		}
		scopes.put(
				new Scope(variable.getKey().toString(),
						variable.getValue().scope,
						variable.getValue().type, astNodeType,
						astNodeParentType), variable.getValue().name);
	}

	return scopes;

}
 
Example #15
Source File: NegationFilterTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Throwable {
    List<String> filterSet1 = Lists.newArrayList("a", "b", "c", "q", "r", "s");
    Itr<String> f1 = new Itr<>(filterSet1);
    List<String> filterSet2 = Lists.newArrayList("a", "b", "c", "d", "e", "f");
    Itr<String> f2 = new Itr<>(filterSet2);
    TreeMultimap<String,NestedIterator<String>> mmap = TreeMultimap.create(Util.keyComparator(), Util.hashComparator());
    mmap.put(f1.next(), f1);
    mmap.put(f2.next(), f2);
    
    assertTrue(NegationFilter.isFiltered("e", mmap, Util.keyTransformer()));
    assertEquals(2, mmap.keySet().size());
    assertNotEquals(null, mmap.get("e"));
    assertNotEquals(null, mmap.get("q"));
    assertEquals(2, mmap.values().size());
}
 
Example #16
Source File: OrIterator.java    From datawave with Apache License 2.0 6 votes vote down vote up
/**
 * Allows creators of this iterator to defer creating the sorted mapping of values to iterators until some condition is met. This is intended to let us
 * build the tree of iterators in <code>init()</code> and defer sorting the iterators until after <code>seek()</code> is called.
 */
public void initialize() {
    Comparator<T> keyComp = Util.keyComparator();
    // nestedIteratorComparator will keep a deterministic ordering, unlike hashCodeComparator
    Comparator<NestedIterator<T>> itrComp = Util.nestedIteratorComparator();
    
    transformer = Util.keyTransformer();
    transforms = new HashMap<>();
    
    includeHeads = TreeMultimap.create(keyComp, itrComp);
    initSubtree(includeHeads, includes, transformer, transforms, false);
    
    if (contextIncludes.size() > 0) {
        contextIncludeHeads = TreeMultimap.create(keyComp, itrComp);
        contextIncludeNullHeads = TreeMultimap.create(keyComp, itrComp);
    }
    
    if (contextExcludes.size() > 0) {
        contextExcludeHeads = TreeMultimap.create(keyComp, itrComp);
        contextExcludeNullHeads = TreeMultimap.create(keyComp, itrComp);
    }
    
    next();
}
 
Example #17
Source File: TypenameScopeExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Multimap<Scope, String> getClassnames(final ASTNode node) {
	final ClassnameFinder cf = new ClassnameFinder(methodsAsRoots);
	node.accept(cf);

	final Multimap<Scope, String> classnames = TreeMultimap.create();

	for (final Entry<ASTNode, String> classname : cf.types.entries()) {
		final ASTNode parentNode = classname.getKey();
		final Scope sc = new Scope(
				classname.getKey().toString(),
				parentNode.getNodeType() == ASTNode.METHOD_DECLARATION ? ScopeType.SCOPE_METHOD
						: ScopeType.SCOPE_CLASS, TYPENAME,
				parentNode.getNodeType(), -1);
		classnames.put(sc, classname.getValue());
	}
	return classnames;
}
 
Example #18
Source File: NestedIteratorContextUtil.java    From datawave with Apache License 2.0 6 votes vote down vote up
/**
 * Process moves against the set of sources. Set the context and move each. Will update the headMap with new references except for null responses. A null
 * response indicates that the iterator had no key's left when moving to context
 * 
 * @param context
 * @param sourcesToMove
 * @param headMap
 * @param transformer
 * @param <T>
 * @return non-null Set of null response iterators
 */
private static <T> Set<NestedIterator<T>> processMoves(T context, Set<NestedIterator<T>> sourcesToMove, TreeMultimap<T,NestedIterator<T>> headMap,
                Util.Transformer<T> transformer) {
    Set<NestedIterator<T>> nullSources = new HashSet<>();
    for (NestedIterator<T> contextRequiredIterator : sourcesToMove) {
        contextRequiredIterator.setContext(context);
        T result = contextRequiredIterator.move(context);
        if (result == null) {
            // beyond the end of the iterator
            nullSources.add(contextRequiredIterator);
        } else {
            T transformed = transformer.transform(result);
            headMap.put(transformed, contextRequiredIterator);
        }
    }
    
    return nullSources;
}
 
Example #19
Source File: FilteringSchemaContextProxy.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private static Collection<Module> getImportedModules(final Map<ModuleId, ? extends Module> allModules,
        final Collection<? extends Module> baseModules, final TreeMultimap<String, Module> nameToModulesAll) {

    List<Module> relatedModules = new LinkedList<>();

    for (Module module : baseModules) {
        for (ModuleImport moduleImport : module.getImports()) {
            Optional<Revision> revisionDate = moduleImport.getRevision();
            if (revisionDate.isEmpty()) {
                revisionDate = nameToModulesAll.get(moduleImport.getModuleName()).first().getRevision();
            }

            ModuleId key = new ModuleId(moduleImport.getModuleName(), revisionDate);
            Module importedModule = allModules.get(key);

            Preconditions.checkArgument(importedModule != null,
                    "Invalid schema, cannot find imported module: %s from module: %s, %s, modules:%s", key,
                    module.getQNameModule(), module.getName(), allModules);
            relatedModules.add(importedModule);

            //calling imports recursive
            relatedModules.addAll(getImportedModules(allModules, Collections.singleton(importedModule),
                        nameToModulesAll));
        }
    }

    return relatedModules;
}
 
Example #20
Source File: BidirectionalSlicerTest.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setup() {
    final SortedSetMultimap<String, GenomeRegion> regionMap = TreeMultimap.create();
    regionMap.put("X", GenomeRegions.create("X", 100, 200));
    regionMap.put("X", GenomeRegions.create("X", 300, 400));
    regionMap.put("Y", GenomeRegions.create("Y", 500, 600));

    slicer = new BidirectionalSlicer(regionMap);
}
 
Example #21
Source File: MergeAssets.java    From buck with Apache License 2.0 5 votes vote down vote up
public MergeAssetsStep(
    Path pathToMergedAssets, Optional<Path> pathToBaseApk, TreeMultimap<Path, Path> assets) {
  super("merging_assets");
  this.pathToMergedAssets = pathToMergedAssets;
  this.pathToBaseApk = pathToBaseApk;
  this.assets = assets;
}
 
Example #22
Source File: AllScopeExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Multimap<Scope, String> getFromFile(final File file)
		throws IOException {
	final Multimap<Scope, String> scopes = TreeMultimap.create();
	for (final IScopeExtractor extractor : allExtractors) {
		scopes.putAll(extractor.getFromFile(file));
	}
	return scopes;
}
 
Example #23
Source File: HmfGenePanelSupplier.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
private static SortedSetMultimap<String, HmfTranscriptRegion> toSortedMap(@NotNull List<HmfTranscriptRegion> regions) {
    SortedSetMultimap<String, HmfTranscriptRegion> regionMap = TreeMultimap.create();
    for (HmfTranscriptRegion region : regions) {
        regionMap.put(region.chromosome(), region);
    }

    return regionMap;
}
 
Example #24
Source File: KafkaActorThread.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
public ManagedActorShard(KafkaActorShard actorShard,
                         PersistentActorStore actorStore) {
    this.actorShard = actorShard;
    this.actorCache = shardActorCacheManager.create(actorShard.getKey(), this);
    this.actorStore = actorStore;
    this.scheduledMessages = TreeMultimap.create(Comparator.naturalOrder(), Comparator.naturalOrder());
}
 
Example #25
Source File: AllScopeExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Multimap<Scope, String> getFromString(final String file,
		final ParseType parseType) {
	final Multimap<Scope, String> scopes = TreeMultimap.create();
	for (final IScopeExtractor extractor : allExtractors) {
		scopes.putAll(extractor.getFromString(file, parseType));
	}
	return scopes;
}
 
Example #26
Source File: NegationFilterTest.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmpty() throws Throwable {
    List<String> filterSet1 = Lists.newArrayList("a", "b");
    Itr<String> f1 = new Itr<>(filterSet1);
    List<String> filterSet2 = Lists.newArrayList("a", "b", "c", "d", "e", "f");
    Itr<String> f2 = new Itr<>(filterSet2);
    TreeMultimap<String,NestedIterator<String>> mmap = TreeMultimap.create(Util.keyComparator(), Util.hashComparator());
    mmap.put(f1.next(), f1);
    mmap.put(f2.next(), f2);
    
    assertTrue(NegationFilter.isFiltered("c", mmap, Util.keyTransformer()));
    assertEquals(1, mmap.keySet().size());
    assertEquals("c", mmap.keySet().iterator().next());
    assertEquals(1, mmap.values().size());
}
 
Example #27
Source File: Game.java    From computoser with GNU Affero General Public License v3.0 5 votes vote down vote up
private void calculateResults() {
    TreeMultimap<Integer, String> rankings = TreeMultimap.create();
    for (Player player : players.values()) {

        int score = 0;
        List<Answer> playerAnswers = new ArrayList<>();
        //cannot simply copy the values() of player.getAnswers(), because it is an unordered map (as it needs to be concurrent)
        for (Piece piece : pieces) {
            Answer answer = player.getAnswers().get(piece.getId());
            if (answer.getTempo() > -1) {
                int diff = Math.abs(answer.getTempo() - piece.getTempo());
                if (diff < 3) {
                    score += 15;
                } else {
                    score += 5 / Math.log10(diff);
                }
            }
            if (answer.getMainInstrument() == piece.getMainInstrument()) {
                score += 10;
            }
            if (answer.getMetreNumerator() == piece.getMetreNumerator() && answer.getMetreDenominator() == piece.getMetreDenominator()) {
                score += 10;
            }
            playerAnswers.add(answer);
        }
        results.getScores().put(player.getName(), score);
        rankings.put(score, player.getSession().getId());
    }
    // the ordered player ids
    results.setRanking(new ArrayList<>(rankings.values()));
    Collections.reverse(results.getRanking());
}
 
Example #28
Source File: GuavaTreeMultimapTest.java    From java_in_examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    String INPUT_TEXT = "Hello World! Hello All! Hi World!";
    // Parse text to words and index
    List<String> words = Arrays.asList(INPUT_TEXT.split(" "));
    // Create Multimap
    Multimap<String, Integer> multiMap = TreeMultimap.create();

    // Fill Multimap
    int i = 0;
    for(String word: words) {
        multiMap.put(word, i);
        i++;
    }

    // Print all words
    System.out.println(multiMap); // print {Hello=[0, 2], World!=[1, 5], All!=[3], Hi=[4]}-in natural order
    // Print all unique words
    System.out.println(multiMap.keySet());    // print [Hello, World!, All!, Hi]- in natural order

    // Print all indexes
    System.out.println("Hello = " + multiMap.get("Hello"));    // print [0, 2]
    System.out.println("World = " + multiMap.get("World!"));    // print [1, 5]
    System.out.println("All = " + multiMap.get("All!"));    // print [3]
    System.out.println("Hi = " + multiMap.get("Hi"));    // print [4]
    System.out.println("Empty = " + multiMap.get("Empty"));    // print []

    // Print count all words
    System.out.println(multiMap.size());    //print 6

    // Print count unique words
    System.out.println(multiMap.keySet().size());    //print 4
}
 
Example #29
Source File: DefaultGroupTaskReportModel.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void build(TaskReportModel model) {
    Comparator<String> keyComparator = GUtil.last(GUtil.last(STRING_COMPARATOR, OTHER_GROUP), DEFAULT_GROUP);
    Comparator<TaskDetails> taskComparator = new Comparator<TaskDetails>() {
        public int compare(TaskDetails task1, TaskDetails task2) {
            int diff = STRING_COMPARATOR.compare(task1.getPath().getName(), task2.getPath().getName());
            if (diff != 0) {
                return diff;
            }
            Path parent1 = task1.getPath().getParent();
            Path parent2 = task2.getPath().getParent();
            if (parent1 == null && parent2 != null) {
                return -1;
            }
            if (parent1 != null && parent2 == null) {
                return 1;
            }
            if (parent1 == null) {
                return 0;
            }
            return parent1.compareTo(parent2);
        }
    };
    groups = TreeMultimap.create(keyComparator, taskComparator);
    for (String group : model.getGroups()) {
        groups.putAll(group, model.getTasksForGroup(group));
    }
    String otherGroupName = findOtherGroup(groups.keySet());
    if (otherGroupName != null && groups.keySet().contains(DEFAULT_GROUP)) {
        groups.putAll(otherGroupName, groups.removeAll(DEFAULT_GROUP));
    }
    if (groups.keySet().contains(DEFAULT_GROUP) && groups.keySet().size() > 1) {
        groups.putAll(OTHER_GROUP, groups.removeAll(DEFAULT_GROUP));
    }
}
 
Example #30
Source File: AuditMbrIsolationCommand.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public void reportAbsolutePath(BuildRule instance, String crumbs, Path path) {
  Multimap<String, String> inner =
      absolutePathsRequired.computeIfAbsent(
          path.toString(), ignored -> TreeMultimap.create());
  inner.put(crumbs, instance.getFullyQualifiedName());
}