com.google.common.collect.SortedSetMultimap Java Examples

The following examples show how to use com.google.common.collect.SortedSetMultimap. 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: MultithreadedTableProvider.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public Set<String> initializeFromV1Offsets(Map<String, String> offsets) throws StageException {
  // v1 offsets map qualified table names to offset column positions
  LOG.info("Upgrading offsets from v1 to v2; logging current offsets now");
  offsets.forEach((t, v) -> LOG.info("{} -> {}", t, v));

  final Set<String> offsetKeysToRemove = new HashSet<>();
  SortedSetMultimap<TableContext, TableRuntimeContext> v1Offsets = TableRuntimeContext.initializeAndUpgradeFromV1Offsets(
      tableContextMap,
      offsets,
      offsetKeysToRemove
  );
  generateInitialPartitionsInSharedQueue(true, v1Offsets, null);

  initializeMaxPartitionWithDataPerTable(offsets);
  return offsetKeysToRemove;
}
 
Example #2
Source File: HtmlReport.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
private List<Map<String, String>> fillKnowBugTable(Set<BugDescription> allKnownBugs, Set<BugDescription> reproducedBugs) {
    SortedSetMultimap<Category, String> reproducedMap = toMultimap(reproducedBugs);
    SortedSetMultimap<Category, String> notReproducedMap = toMultimap(Sets.difference(allKnownBugs, reproducedBugs));

    List<Category> allKeys = Stream.concat(reproducedMap.keySet().stream(), notReproducedMap.keySet().stream())
            .distinct().sorted()
            .collect(Collectors.toList());

    List<Map<String, String>> rows = new ArrayList<>(allKeys.size());
    for (Category category : allKeys) {
        Set<String> reproducedSet = ObjectUtils.defaultIfNull(reproducedMap.get(category), Collections.emptySet());
        Set<String> notReproducedSet = ObjectUtils.defaultIfNull(notReproducedMap.get(category), Collections.emptySet());

        Map<String, String> row = new HashMap<>();
        row.put(BUG_CATEGORY_COLUMN_NAME, category.toString());
        row.put(REPRODUCED_COLUMN_NAME, String.join(", ", reproducedSet));
        row.put(NOT_REPRODUCED_COLUMN_NAME, String.join(", ", notReproducedSet));

        rows.add(row);
    }
    return rows;
}
 
Example #3
Source File: RelStructuredTypeFlattener.java    From Bats with Apache License 2.0 5 votes vote down vote up
public void updateRelInMap(SortedSetMultimap<RelNode, CorrelationId> mapRefRelToCorVar) {
    for (RelNode rel : Lists.newArrayList(mapRefRelToCorVar.keySet())) {
        if (oldToNewRelMap.containsKey(rel)) {
            SortedSet<CorrelationId> corVarSet = mapRefRelToCorVar.removeAll(rel);
            mapRefRelToCorVar.putAll(oldToNewRelMap.get(rel), corVarSet);
        }
    }
}
 
Example #4
Source File: RelStructuredTypeFlattener.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void updateRelInMap(
    SortedSetMultimap<RelNode, CorrelationId> mapRefRelToCorVar) {
  for (RelNode rel : Lists.newArrayList(mapRefRelToCorVar.keySet())) {
    if (oldToNewRelMap.containsKey(rel)) {
      SortedSet<CorrelationId> corVarSet =
          mapRefRelToCorVar.removeAll(rel);
      mapRefRelToCorVar.putAll(oldToNewRelMap.get(rel), corVarSet);
    }
  }
}
 
Example #5
Source File: RelDecorrelator.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a CorelMap with given contents. */
public static CorelMap of(
    SortedSetMultimap<RelNode, CorRef> mapRefRelToCorVar,
    SortedMap<CorrelationId, RelNode> mapCorToCorRel,
    Map<RexFieldAccess, CorRef> mapFieldAccessToCorVar) {
  return new CorelMap(mapRefRelToCorVar, mapCorToCorRel,
      mapFieldAccessToCorVar);
}
 
Example #6
Source File: MultithreadedTableProvider.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public void initializeFromV2Offsets(
    Map<String, String> offsets,
    Map<String, String> newCommitOffsets
) throws StageException {
  final Set<TableContext> excludeTables = new HashSet<>();
  SortedSetMultimap<TableContext, TableRuntimeContext> v2Offsets = TableRuntimeContext.buildPartitionsFromStoredV2Offsets(
      tableContextMap,
      offsets,
      excludeTables,
      newCommitOffsets
  );
  handlePartitioningTurnedOffOrOn(v2Offsets);
  generateInitialPartitionsInSharedQueue(true, v2Offsets, excludeTables);
  initializeMaxPartitionWithDataPerTable(newCommitOffsets);
}
 
Example #7
Source File: TableRuntimeContext.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public static SortedSetMultimap<TableContext, TableRuntimeContext> initializeAndUpgradeFromV1Offsets(
    Map<String, TableContext> tableContextMap,
    Map<String, String> offsets,
    Set<String> offsetKeysToRemove
) throws StageException {
  SortedSetMultimap<TableContext, TableRuntimeContext> returnMap = buildSortedPartitionMap();

  for (Map.Entry<String, TableContext> tableEntry : tableContextMap.entrySet()) {
    final String tableName = tableEntry.getKey();
    final TableContext tableContext = tableEntry.getValue();

    Map<String, String> startingOffsets;
    String offsetValue = null;
    Map<String, String> storedOffsets = null;
    if (offsets.containsKey(tableName)) {
      offsetValue = offsets.remove(tableName);
      storedOffsets = OffsetQueryUtil.validateStoredAndSpecifiedOffset(tableContext, offsetValue);

      offsetKeysToRemove.add(tableName);

      startingOffsets = OffsetQueryUtil.getOffsetsFromSourceKeyRepresentation(offsetValue);
      tableContext.getOffsetColumnToStartOffset().putAll(startingOffsets);
    }

    final TableRuntimeContext partition = createInitialPartition(tableContext, storedOffsets);
    returnMap.put(tableContext, partition);

    if (offsetValue != null) {
      offsets.put(partition.getOffsetKey(), offsetValue);
    }
  }

  return returnMap;
}
 
Example #8
Source File: SageApplication.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
private static ListMultimap<Chromosome, GenomeRegion> readPanel(@NotNull final String panelBed) throws IOException {
    final ListMultimap<Chromosome, GenomeRegion> panel = ArrayListMultimap.create();
    if (!panelBed.isEmpty()) {
        LOGGER.info("Reading bed file: {}", panelBed);
        SortedSetMultimap<String, GenomeRegion> bed = BEDFileLoader.fromBedFile(panelBed);
        for (String contig : bed.keySet()) {
            if (HumanChromosome.contains(contig)) {
                panel.putAll(HumanChromosome.fromString(contig), bed.get(contig));
            }
        }
    }

    return panel;
}
 
Example #9
Source File: BEDFileLoaderTest.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void verifyStartIsOneBased() throws IOException {
    final String bedFile = BED_FILE_BASE_PATH + File.separator + VALID_BED;
    final SortedSetMultimap<String, GenomeRegion> regions = BEDFileLoader.fromBedFile(bedFile);
    assertEquals(1, regions.get("1").first().start());
    assertEquals(1, regions.get("1").first().end());
}
 
Example #10
Source File: HmfGenePanelSupplierTest.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void allRegionsAreSortedCorrectly() {
    final SortedSetMultimap<String, HmfTranscriptRegion> geneRegions = HmfGenePanelSupplier.allGenesPerChromosomeMap37();
    for (final String chromosome : geneRegions.keySet()) {
        long start = 0;
        for (final HmfTranscriptRegion hmfTranscriptRegion : geneRegions.get(chromosome)) {
            assertTrue(hmfTranscriptRegion.start() >= start);
            start = hmfTranscriptRegion.start();
        }
    }
}
 
Example #11
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 #12
Source File: BEDFileLoader.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
public static SortedSetMultimap<String, GenomeRegion> fromBedFile(@NotNull String bedFile) throws IOException {
    final SortedSetMultimap<String, GenomeRegion> regionMap = TreeMultimap.create();

    String prevChromosome = null;
    GenomeRegion prevRegion = null;
    try (final AbstractFeatureReader<BEDFeature, LineIterator> reader = getFeatureReader(bedFile, new BEDCodec(), false)) {
        for (final BEDFeature bedFeature : reader.iterator()) {
            final String chromosome = bedFeature.getContig();
            final long start = bedFeature.getStart();
            final long end = bedFeature.getEnd();

            if (end < start) {
                LOGGER.warn("Invalid genome region found in chromosome {}: start={}, end={}", chromosome, start, end);
            } else {
                final GenomeRegion region = GenomeRegions.create(chromosome, start, end);
                if (prevRegion != null && chromosome.equals(prevChromosome) && prevRegion.end() >= start) {
                    LOGGER.warn("BED file is not sorted, please fix! Current={}, Previous={}", region, prevRegion);
                } else {
                    regionMap.put(chromosome, region);
                    prevChromosome = chromosome;
                    prevRegion = region;
                }
            }
        }
    }

    return regionMap;
}
 
Example #13
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 #14
Source File: SliceCycleArchCondition.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private SortedSetMultimap<Slice, Dependency> targetsOf(Slice slice,
        ClassesToSlicesMapping classesToSlicesMapping, DescribedPredicate<Dependency> predicate) {
    SortedSetMultimap<Slice, Dependency> result = hashKeys().treeSetValues().build();
    for (Dependency dependency : Guava.Iterables.filter(slice.getDependenciesFromSelf(), predicate)) {
        if (classesToSlicesMapping.containsKey(dependency.getTargetClass())) {
            result.put(classesToSlicesMapping.get(dependency.getTargetClass()), dependency);
        }
    }
    return result;
}
 
Example #15
Source File: ReportUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/** Creates a histogram of the given collections */
static public <E extends Comparable<E>, T extends Comparable<T>> Multimap<T, E> getHistogram(Collection<E> elems,
		Function<E, T> pivot) {

	final SortedSetMultimap<T, E> histogram = TreeMultimap.create();
	for (E elem : elems) {
		T t = pivot.apply(elem);
		histogram.put(t, elem);
	}
	return histogram;
}
 
Example #16
Source File: HtmlReport.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private SortedSetMultimap<Category, String> toMultimap(Set<BugDescription> bugSet) {
    SortedSetMultimap<Category, String> bugMap = SortedSetMultimapBuilder.hashKeys().treeSetValues().build();
    for (BugDescription bugDescription : bugSet) {
        bugMap.put(bugDescription.getCategories(), bugDescription.getSubject().toUpperCase());
    }
    return bugMap;
}
 
Example #17
Source File: RelStructuredTypeFlattener.java    From Quicksql with MIT License 5 votes vote down vote up
public void updateRelInMap(
    SortedSetMultimap<RelNode, CorrelationId> mapRefRelToCorVar) {
  for (RelNode rel : Lists.newArrayList(mapRefRelToCorVar.keySet())) {
    if (oldToNewRelMap.containsKey(rel)) {
      SortedSet<CorrelationId> corVarSet =
          mapRefRelToCorVar.removeAll(rel);
      mapRefRelToCorVar.putAll(oldToNewRelMap.get(rel), corVarSet);
    }
  }
}
 
Example #18
Source File: RelDecorrelator.java    From Quicksql with MIT License 5 votes vote down vote up
/** Creates a CorelMap with given contents. */
public static CorelMap of(
    SortedSetMultimap<RelNode, CorRef> mapRefRelToCorVar,
    SortedMap<CorrelationId, RelNode> mapCorToCorRel,
    Map<RexFieldAccess, CorRef> mapFieldAccessToCorVar) {
  return new CorelMap(mapRefRelToCorVar, mapCorToCorRel,
      mapFieldAccessToCorVar);
}
 
Example #19
Source File: RelDecorrelator.java    From flink with Apache License 2.0 5 votes vote down vote up
/** Creates a CorelMap with given contents. */
public static CorelMap of(
    SortedSetMultimap<RelNode, CorRef> mapRefRelToCorVar,
    SortedMap<CorrelationId, RelNode> mapCorToCorRel,
    Map<RexFieldAccess, CorRef> mapFieldAccessToCorVar) {
  return new CorelMap(mapRefRelToCorVar, mapCorToCorRel,
      mapFieldAccessToCorVar);
}
 
Example #20
Source File: SliceCycleArchCondition.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private SliceDependencies(Slice slice, ClassesToSlicesMapping classesToSlicesMapping, DescribedPredicate<Dependency> predicate) {
    SortedSetMultimap<Slice, Dependency> targetSlicesWithDependencies = targetsOf(slice, classesToSlicesMapping, predicate);
    ImmutableSet.Builder<Edge<Slice, Dependency>> edgeBuilder = ImmutableSet.builder();
    for (Map.Entry<Slice, SortedSet<Dependency>> entry : sortedEntries(targetSlicesWithDependencies)) {
        edgeBuilder.add(new Edge<>(slice, entry.getKey(), entry.getValue()));
    }
    this.edges = edgeBuilder.build();
}
 
Example #21
Source File: RelDecorrelator.java    From flink with Apache License 2.0 5 votes vote down vote up
/** Creates a CorelMap with given contents. */
public static CorelMap of(
    SortedSetMultimap<RelNode, CorRef> mapRefRelToCorVar,
    SortedMap<CorrelationId, RelNode> mapCorToCorRel,
    Map<RexFieldAccess, CorRef> mapFieldAccessToCorVar) {
  return new CorelMap(mapRefRelToCorVar, mapCorToCorRel,
      mapFieldAccessToCorVar);
}
 
Example #22
Source File: MultithreadedTableProvider.java    From datacollector with Apache License 2.0 4 votes vote down vote up
/**
 * Checks whether any tables have had partitioning turned off or not, and updates the partition map appropriately
 *
 * @param reconstructedPartitions the reconstructed partitions (may be modified)
 */
private void handlePartitioningTurnedOffOrOn(
    SortedSetMultimap<TableContext, TableRuntimeContext> reconstructedPartitions
) {

  for (TableContext tableContext : reconstructedPartitions.keySet()) {
    final SortedSet<TableRuntimeContext> partitions = reconstructedPartitions.get(tableContext);
    final TableRuntimeContext lastPartition = partitions.last();
    final TableContext sourceTableContext = lastPartition.getSourceTableContext();
    Utils.checkState(
        sourceTableContext.equals(tableContext),
        String.format(
            "Source table context for %s should match TableContext map key of %s",
            lastPartition.getDescription(),
            tableContext.getQualifiedName()
        )
    );

    final boolean partitioningTurnedOff = lastPartition.isPartitioned()
        && sourceTableContext.getPartitioningMode() == PartitioningMode.DISABLED;
    final boolean partitioningTurnedOn = !lastPartition.isPartitioned()
        && sourceTableContext.isPartitionable()
        && sourceTableContext.getPartitioningMode() != PartitioningMode.DISABLED;

    if (!partitioningTurnedOff && !partitioningTurnedOn) {
      continue;
    }

    final Map<String, String> nextStartingOffsets = new HashMap<>();
    final Map<String, String> nextMaxOffsets = new HashMap<>();

    final int newPartitionSequence = lastPartition.getPartitionSequence() > 0 ? lastPartition.getPartitionSequence() + 1 : 1;
    if (partitioningTurnedOff) {
      LOG.info(
          "Table {} has switched from partitioned to non-partitioned; partition sequence {} will be the last (with" +
              " no max offsets)",
          sourceTableContext.getQualifiedName(),
          newPartitionSequence
      );

      lastPartition.getPartitionOffsetStart().forEach(
          (col, off) -> {
            String basedOnStartOffset = lastPartition.generateNextPartitionOffset(col, off);
            nextStartingOffsets.put(col, basedOnStartOffset);
          }
      );

    } else if (partitioningTurnedOn) {

      lastPartition.getPartitionOffsetStart().forEach(
          (col, off) -> {
            String basedOnStoredOffset = lastPartition.getInitialStoredOffsets().get(col);
            nextStartingOffsets.put(col, basedOnStoredOffset);
          }
      );

      nextStartingOffsets.forEach(
          (col, off) -> nextMaxOffsets.put(col, lastPartition.generateNextPartitionOffset(col, off))
      );

      if (!reconstructedPartitions.remove(sourceTableContext, lastPartition)) {
        throw new IllegalStateException(String.format(
            "Failed to remove partition %s for table %s in switching partitioning from off to on",
            lastPartition.getDescription(),
            sourceTableContext.getQualifiedName()
        ));
      }

      LOG.info(
          "Table {} has switched from non-partitioned to partitioned; using last stored offsets as the starting" +
              " offsets for the new partition {}",
          sourceTableContext.getQualifiedName(),
          newPartitionSequence
      );
    }

    final TableRuntimeContext nextPartition = new TableRuntimeContext(
        sourceTableContext,
        lastPartition.isUsingNonIncrementalLoad(),
        (lastPartition.isPartitioned() && !partitioningTurnedOff) || partitioningTurnedOn,
        newPartitionSequence,
        nextStartingOffsets,
        nextMaxOffsets
    );

    reconstructedPartitions.put(sourceTableContext, nextPartition);
  }
}
 
Example #23
Source File: GetAccountHierarchy.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @throws ApiException if the API request failed with one or more service errors.
 * @throws RemoteException if the API request failed due to other errors.
 */
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
    throws RemoteException {
  // Get the ServicedAccountService.
  ManagedCustomerServiceInterface managedCustomerService =
      adWordsServices.get(session, ManagedCustomerServiceInterface.class);

  // Create selector builder.
  int offset = 0;
  SelectorBuilder selectorBuilder =
      new SelectorBuilder()
          .fields(ManagedCustomerField.CustomerId, ManagedCustomerField.Name)
          .offset(offset)
          .limit(PAGE_SIZE);

  // Get results.
  ManagedCustomerPage page;

  // Map from customerId to customer node.
  Map<Long, ManagedCustomerTreeNode> customerIdToCustomerNode = Maps.newHashMap();

  // Map from each parent customer ID to its set of linked child customer IDs.
  SortedSetMultimap<Long, Long> parentIdToChildIds = TreeMultimap.create();
  do {
    page = managedCustomerService.get(selectorBuilder.build());

    if (page.getEntries() != null) {
      // Create account tree nodes for each customer.
      for (ManagedCustomer customer : page.getEntries()) {
        ManagedCustomerTreeNode node = new ManagedCustomerTreeNode();
        node.account = customer;
        customerIdToCustomerNode.put(customer.getCustomerId(), node);
      }

      // Update the map of parent customer ID to child customer IDs.
      if (page.getLinks() != null) {
        for (ManagedCustomerLink link : page.getLinks()) {
          parentIdToChildIds.put(link.getManagerCustomerId(), link.getClientCustomerId());
        }
      }
    }
    offset += PAGE_SIZE;
    selectorBuilder.increaseOffsetBy(PAGE_SIZE);
  } while (offset < page.getTotalNumEntries());

  // Update the parentNode of each child node, and add each child to the childAccounts
  // of its parentNode.
  for (Entry<Long, Long> parentIdEntry : parentIdToChildIds.entries()) {
    ManagedCustomerTreeNode parentNode = customerIdToCustomerNode.get(parentIdEntry.getKey());
    ManagedCustomerTreeNode childNode = customerIdToCustomerNode.get(parentIdEntry.getValue());
    childNode.parentNode = parentNode;
    parentNode.childAccounts.add(childNode);
  }

  // Find the root account node in the tree.
  ManagedCustomerTreeNode rootNode =
      customerIdToCustomerNode.values().stream()
          .filter(node -> node.parentNode == null)
          .findFirst()
          .orElse(null);

  // Display serviced account graph.
  if (rootNode != null) {
    // Display account tree.
    System.out.println("CustomerId, Name");
    System.out.println(rootNode.toTreeString(0, new StringBuffer()));
  } else {
    System.out.println("No serviced accounts were found.");
  }
}
 
Example #24
Source File: MergeAndroidResourcesStepTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void testGenerateRDotJavaForWithStyleables() throws DuplicateResourceException {
  RDotTxtEntryBuilder entriesBuilder = new RDotTxtEntryBuilder();

  // Merge everything into the same package space.
  String sharedPackageName = "com.facebook.abc";
  entriesBuilder.add(
      new RDotTxtFile(
          sharedPackageName,
          "a-R.txt",
          ImmutableList.of(
              "int attr android_layout 0x010100f2",
              "int attr buttonPanelSideLayout 0x7f01003a",
              "int attr listLayout 0x7f01003b",
              "int[] styleable AlertDialog { 0x7f01003a, 0x7f01003b, 0x010100f2 }",
              "int styleable AlertDialog_android_layout 2",
              "int styleable AlertDialog_buttonPanelSideLayout 0",
              "int styleable AlertDialog_multiChoiceItemLayout 1")));
  entriesBuilder.add(
      new RDotTxtFile(
          sharedPackageName,
          "b-R.txt",
          ImmutableList.of(
              "int id a1 0x7f010001",
              "int id a2 0x7f010002",
              "int attr android_layout_gravity 0x7f078008",
              "int attr background 0x7f078009",
              "int attr backgroundSplit 0x7f078008",
              "int attr backgroundStacked 0x7f078010",
              "int attr layout_heightPercent 0x7f078012",
              "int[] styleable ActionBar {  }",
              "int styleable ActionBar_background 10",
              "int styleable ActionBar_backgroundSplit 12",
              "int styleable ActionBar_backgroundStacked 11",
              "int[] styleable ActionBarLayout { 0x7f060008 }",
              "int styleable ActionBarLayout_android_layout 0",
              "int styleable ActionBarLayout_android_layout_gravity 1",
              "int[] styleable PercentLayout_Layout { }",
              "int styleable PercentLayout_Layout_layout_aspectRatio 9",
              "int styleable PercentLayout_Layout_layout_heightPercent 1")));

  SortedSetMultimap<String, RDotTxtEntry> packageNameToResources =
      MergeAndroidResourcesStep.sortSymbols(
          entriesBuilder.buildFilePathToPackageNameSet(),
          Optional.empty(),
          ImmutableMap.of(),
          Optional.empty(),
          /* bannedDuplicateResourceTypes */ EnumSet.noneOf(RType.class),
          ImmutableSet.of(),
          entriesBuilder.getProjectFilesystem(),
          false);

  assertEquals(23, packageNameToResources.size());

  ArrayList<RDotTxtEntry> resources =
      new ArrayList<>(packageNameToResources.get(sharedPackageName));
  assertEquals(23, resources.size());

  System.out.println(resources);

  ImmutableList<RDotTxtEntry> fakeRDotTxtEntryWithIDS =
      ImmutableList.of(
          FakeEntry.createWithId(INT, ATTR, "android_layout_gravity", "0x07f01005"),
          FakeEntry.createWithId(INT, ATTR, "background", "0x07f01006"),
          FakeEntry.createWithId(INT, ATTR, "backgroundSplit", "0x07f01007"),
          FakeEntry.createWithId(INT, ATTR, "backgroundStacked", "0x07f01008"),
          FakeEntry.createWithId(INT, ATTR, "buttonPanelSideLayout", "0x07f01001"),
          FakeEntry.createWithId(INT, ATTR, "layout_heightPercent", "0x07f01009"),
          FakeEntry.createWithId(INT, ATTR, "listLayout", "0x07f01002"),
          FakeEntry.createWithId(INT, ID, "a1", "0x07f01003"),
          FakeEntry.createWithId(INT, ID, "a2", "0x07f01004"),
          FakeEntry.createWithId(
              INT_ARRAY, STYLEABLE, "ActionBar", "{ 0x07f01006,0x07f01007,0x07f01008 }"),
          FakeEntry.createWithId(INT, STYLEABLE, "ActionBar_background", "0"),
          FakeEntry.createWithId(INT, STYLEABLE, "ActionBar_backgroundSplit", "1"),
          FakeEntry.createWithId(INT, STYLEABLE, "ActionBar_backgroundStacked", "2"),
          FakeEntry.createWithId(
              INT_ARRAY, STYLEABLE, "ActionBarLayout", "{ 0x010100f2,0x07f01005 }"),
          FakeEntry.createWithId(INT, STYLEABLE, "ActionBarLayout_android_layout", "0"),
          FakeEntry.createWithId(INT, STYLEABLE, "ActionBarLayout_android_layout_gravity", "1"),
          FakeEntry.createWithId(
              INT_ARRAY, STYLEABLE, "AlertDialog", "{ 0x010100f2,0x07f01001,0x7f01003b }"),
          FakeEntry.createWithId(INT, STYLEABLE, "AlertDialog_android_layout", "0"),
          FakeEntry.createWithId(INT, STYLEABLE, "AlertDialog_buttonPanelSideLayout", "1"),
          FakeEntry.createWithId(INT, STYLEABLE, "AlertDialog_multiChoiceItemLayout", "2"),
          FakeEntry.createWithId(
              INT_ARRAY, STYLEABLE, "PercentLayout_Layout", "{ 0x00000000,0x07f01009 }"),
          FakeEntry.createWithId(INT, STYLEABLE, "PercentLayout_Layout_layout_aspectRatio", "0"),
          FakeEntry.createWithId(
              INT, STYLEABLE, "PercentLayout_Layout_layout_heightPercent", "1"));

  assertEquals(createTestingFakesWithIds(resources), fakeRDotTxtEntryWithIDS);
}
 
Example #25
Source File: MergeAndroidResourcesStepTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void testGenerateRDotJavaForMultipleSymbolsFiles() throws DuplicateResourceException {
  RDotTxtEntryBuilder entriesBuilder = new RDotTxtEntryBuilder();

  // Merge everything into the same package space.
  String sharedPackageName = "com.facebook.abc";
  entriesBuilder.add(
      new RDotTxtFile(
          sharedPackageName,
          "a-R.txt",
          ImmutableList.of(
              "int id a1 0x7f010001", "int id a2 0x7f010002", "int string a1 0x7f020001")));

  entriesBuilder.add(
      new RDotTxtFile(
          sharedPackageName,
          "b-R.txt",
          ImmutableList.of(
              "int id b1 0x7f010001", "int id b2 0x7f010002", "int string a1 0x7f020001")));

  entriesBuilder.add(
      new RDotTxtFile(
          sharedPackageName,
          "c-R.txt",
          ImmutableList.of("int attr c1 0x7f010001", "int[] styleable c1 { 0x7f010001 }")));

  SortedSetMultimap<String, RDotTxtEntry> packageNameToResources =
      MergeAndroidResourcesStep.sortSymbols(
          entriesBuilder.buildFilePathToPackageNameSet(),
          Optional.empty(),
          ImmutableMap.of(),
          Optional.empty(),
          /* bannedDuplicateResourceTypes */ EnumSet.noneOf(RType.class),
          ImmutableSet.of(),
          entriesBuilder.getProjectFilesystem(),
          false);

  assertEquals(1, packageNameToResources.keySet().size());
  SortedSet<RDotTxtEntry> resources = packageNameToResources.get(sharedPackageName);
  assertEquals(7, resources.size());

  Set<String> uniqueEntries = new HashSet<>();
  for (RDotTxtEntry resource : resources) {
    if (!resource.type.equals(STYLEABLE)) {
      assertFalse(
          "Duplicate ids should be fixed by renumerate=true; duplicate was: " + resource.idValue,
          uniqueEntries.contains(resource.idValue));
      uniqueEntries.add(resource.idValue);
    }
  }

  assertEquals(6, uniqueEntries.size());

  // All good, no need to further test whether we can write the Java file correctly...
}
 
Example #26
Source File: MergeAndroidResourcesStep.java    From buck with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
void writePerPackageRDotJava(
    SortedSetMultimap<String, RDotTxtEntry> packageToResources, ProjectFilesystem filesystem)
    throws IOException {
  for (String rDotJavaPackage : packageToResources.keySet()) {
    Path outputFile = getPathToRDotJava(rDotJavaPackage);
    filesystem.mkdirs(outputFile.getParent());
    try (ThrowingPrintWriter writer =
        new ThrowingPrintWriter(filesystem.newFileOutputStream(outputFile))) {
      writer.format("package %s;\n\n", rDotJavaPackage);
      writer.format("public class %s {\n", rName);

      ImmutableList.Builder<String> customDrawablesBuilder = ImmutableList.builder();
      ImmutableList.Builder<String> grayscaleImagesBuilder = ImmutableList.builder();
      RType lastType = null;

      for (RDotTxtEntry res : packageToResources.get(rDotJavaPackage)) {
        RType type = res.type;
        if (!type.equals(lastType)) {
          // If the previous type needs to be closed, close it.
          if (lastType != null) {
            writer.println("  }\n");
          }

          // Now start the block for the new type.
          writer.format("  public static class %s {\n", type);
          lastType = type;
        }

        // Write out the resource.
        // Write as an int.
        writer.format(
            "    public static%s%s %s=%s;\n",
            forceFinalResourceIds ? " final " : " ", res.idType, res.name, res.idValue);

        if (type == RType.DRAWABLE && res.customType == RDotTxtEntry.CustomDrawableType.CUSTOM) {
          customDrawablesBuilder.add(res.idValue);
        } else if (type == RType.DRAWABLE
            && res.customType == RDotTxtEntry.CustomDrawableType.GRAYSCALE_IMAGE) {
          grayscaleImagesBuilder.add(res.idValue);
        }
      }

      // If some type was written (e.g., the for loop was entered), then the last type needs to be
      // closed.
      if (lastType != null) {
        writer.println("  }\n");
      }

      ImmutableList<String> customDrawables = customDrawablesBuilder.build();
      if (customDrawables.size() > 0) {
        // Add a new field for the custom drawables.
        writer.format("  public static final int[] custom_drawables = ");
        writer.format("{ %s };\n", Joiner.on(",").join(customDrawables));
        writer.format("\n");
      }

      ImmutableList<String> grayscaleImages = grayscaleImagesBuilder.build();
      if (grayscaleImages.size() > 0) {
        // Add a new field for the custom drawables.
        writer.format("  public static final int[] grayscale_images = ");
        writer.format("{ %s };\n", Joiner.on(",").join(grayscaleImages));
        writer.format("\n");
      }

      // Close the class definition.
      writer.println("}");
    }
  }
}
 
Example #27
Source File: GuavaConfiguration.java    From gwt-jackson with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure() {
    type( Optional.class ).serializer( OptionalJsonSerializer.class ).deserializer( OptionalJsonDeserializer.class );
    type( FluentIterable.class ).serializer( IterableJsonSerializer.class );

    // Immutable Collections
    type( ImmutableCollection.class ).serializer( CollectionJsonSerializer.class )
            .deserializer( ImmutableCollectionJsonDeserializer.class );
    type( ImmutableList.class ).serializer( CollectionJsonSerializer.class ).deserializer( ImmutableListJsonDeserializer.class );
    type( ImmutableSet.class ).serializer( CollectionJsonSerializer.class ).deserializer( ImmutableSetJsonDeserializer.class );
    type( ImmutableSortedSet.class ).serializer( CollectionJsonSerializer.class )
            .deserializer( ImmutableSortedSetJsonDeserializer.class );

    // Immutable Map
    type( ImmutableMap.class ).serializer( MapJsonSerializer.class ).deserializer( ImmutableMapJsonDeserializer.class );
    type( ImmutableSortedMap.class ).serializer( MapJsonSerializer.class ).deserializer( ImmutableSortedMapJsonDeserializer.class );

    // BiMap
    type( BiMap.class ).serializer( MapJsonSerializer.class ).deserializer( BiMapJsonDeserializer.class );
    type( ImmutableBiMap.class ).serializer( MapJsonSerializer.class ).deserializer( ImmutableBiMapJsonDeserializer.class );
    type( HashBiMap.class ).serializer( MapJsonSerializer.class ).deserializer( HashBiMapJsonDeserializer.class );
    type( EnumBiMap.class ).serializer( MapJsonSerializer.class ).deserializer( EnumBiMapJsonDeserializer.class );
    type( EnumHashBiMap.class ).serializer( MapJsonSerializer.class ).deserializer( EnumHashBiMapJsonDeserializer.class );

    // Multiset
    type( Multiset.class ).serializer( CollectionJsonSerializer.class ).deserializer( MultisetJsonDeserializer.class );
    type( HashMultiset.class ).serializer( CollectionJsonSerializer.class ).deserializer( HashMultisetJsonDeserializer.class );
    type( LinkedHashMultiset.class ).serializer( CollectionJsonSerializer.class )
            .deserializer( LinkedHashMultisetJsonDeserializer.class );
    type( SortedMultiset.class ).serializer( CollectionJsonSerializer.class ).deserializer( SortedMultisetJsonDeserializer.class );
    type( TreeMultiset.class ).serializer( CollectionJsonSerializer.class ).deserializer( TreeMultisetJsonDeserializer.class );
    type( ImmutableMultiset.class ).serializer( CollectionJsonSerializer.class )
            .deserializer( ImmutableMultisetJsonDeserializer.class );
    type( EnumMultiset.class ).serializer( CollectionJsonSerializer.class ).deserializer( EnumMultisetJsonDeserializer.class );

    // Multimap
    type( Multimap.class ).serializer( MultimapJsonSerializer.class ).deserializer( MultimapJsonDeserializer.class );

    type( ImmutableMultimap.class ).serializer( MultimapJsonSerializer.class ).deserializer( ImmutableMultimapJsonDeserializer.class );
    type( ImmutableSetMultimap.class ).serializer( MultimapJsonSerializer.class )
            .deserializer( ImmutableSetMultimapJsonDeserializer.class );
    type( ImmutableListMultimap.class ).serializer( MultimapJsonSerializer.class )
            .deserializer( ImmutableListMultimapJsonDeserializer.class );

    type( SetMultimap.class ).serializer( MultimapJsonSerializer.class ).deserializer( SetMultimapJsonDeserializer.class );
    type( HashMultimap.class ).serializer( MultimapJsonSerializer.class ).deserializer( HashMultimapJsonDeserializer.class );
    type( LinkedHashMultimap.class ).serializer( MultimapJsonSerializer.class )
            .deserializer( LinkedHashMultimapJsonDeserializer.class );
    type( SortedSetMultimap.class ).serializer( MultimapJsonSerializer.class ).deserializer( SortedSetMultimapJsonDeserializer.class );
    type( TreeMultimap.class ).serializer( MultimapJsonSerializer.class ).deserializer( TreeMultimapJsonDeserializer.class );

    type( ListMultimap.class ).serializer( MultimapJsonSerializer.class ).deserializer( ListMultimapJsonDeserializer.class );
    type( ArrayListMultimap.class ).serializer( MultimapJsonSerializer.class ).deserializer( ArrayListMultimapJsonDeserializer.class );
    type( LinkedListMultimap.class ).serializer( MultimapJsonSerializer.class )
            .deserializer( LinkedListMultimapJsonDeserializer.class );
}
 
Example #28
Source File: SortedSetMultimapJsonDeserializer.java    From gwt-jackson with Apache License 2.0 4 votes vote down vote up
@Override
protected SortedSetMultimap<K, V> newMultimap() {
    return TreeMultimap.create();
}
 
Example #29
Source File: RelDecorrelator.java    From Bats with Apache License 2.0 4 votes vote down vote up
/** Creates a CorelMap with given contents. */
public static CorelMap of(SortedSetMultimap<RelNode, CorRef> mapRefRelToCorVar,
        SortedMap<CorrelationId, RelNode> mapCorToCorRel, Map<RexFieldAccess, CorRef> mapFieldAccessToCorVar) {
    return new CorelMap(mapRefRelToCorVar, mapCorToCorRel, mapFieldAccessToCorVar);
}
 
Example #30
Source File: SortedBiMultiValMap.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
protected SortedBiMultiValMap(SortedMap<K, V> forwardMap, SortedSetMultimap<V, K> reverseMap)
{
    super(forwardMap, reverseMap);
}