IndexUtils { @NotNull public MerkleTree buildMerkleTree(@NotNull Partition partition) { List<IndexElt> elts = indexService.getListByPartition(partition); SortedMap<Long, Block> blocks = elts.stream() .collect(groupingBy(IndexElt::getId)) .values() .stream() .map(groupedElts -> new Block(groupedElts.get(0).getId(), groupedElts.stream() .map(IndexElt::toBlockElt) .sorted(new BlockEltComparator()) .collect(ImmutableList.toImmutableList())) ).collect( toMap( Block::getId, Function.identity(), Utils.throwingMerger(), TreeMap::new ) ); MerkleTree tree = new MerkleTree(indexService.getMinMaxRange(partition), MAX_LEVEL); MerkleTree.fillTree(tree, blocks); tree.calculate(); return tree; }  long getOffset(@NotNull List<IndexElt> elts); @NotNull MerkleTree buildMerkleTree(@NotNull Partition partition);  }
@Test public void buildMerkleTree() { Partition partition = new Partition(42, 42); assertTrue(indexDao.getListById(303277865741324292L).isEmpty()); assertNull(indexDao.getById(303277865741324292L, 1)); IndexElt expected1 = new IndexElt.IndexEltBuilder() .id(303277865741324292L) .type(1) .partition(partition) .offset(0L) .length(128L) .metadata(ImmutableMap.of("key", "value")) .crc(42L) .build(); indexDao.add(expected1); IndexElt expected2 = new IndexElt.IndexEltBuilder() .id(303277865741324292L) .type(2) .partition(partition) .offset(128L) .length(128L) .metadata(ImmutableMap.of("key", "value")) .crc(42L) .build(); indexDao.add(expected2); IndexElt expected3 = new IndexElt.IndexEltBuilder() .id(303277865741324291L) .type(0) .partition(partition) .offset(0L) .length(128L) .metadata(ImmutableMap.of("key", "value")) .crc(42L) .build(); indexDao.add(expected3); MerkleTree merkleTree = indexUtils.buildMerkleTree(partition); assertEquals(merkleTree.getLeafNodes().size(), 2); log.info("{}", merkleTree.getLeafNodes().get(1).getHash()); assertEquals(merkleTree.getLeafNodes().get(1).getHash(), new byte[]{4, 53, 117, -100, -81, -64, 16, 4, 0, 0, 0, 1, 0, 0, 0, 2}); }
@Test public void difference() { Partition partition1 = new Partition(42, 42); IndexElt expected = new IndexElt.IndexEltBuilder() .id(42L) .type(1) .partition(partition1) .offset(0L) .length(128L) .metadata(ImmutableMap.of("key", "value")) .crc(42L) .build(); indexDao.add(expected); Partition partition2 = new Partition(42, 43); IndexElt expected2 = new IndexElt.IndexEltBuilder() .id(43L) .type(1) .partition(partition2) .offset(0L) .length(128L) .metadata(ImmutableMap.of("key", "value")) .crc(42L) .build(); indexDao.add(expected2); MerkleTree merkleTree1 = indexUtils.buildMerkleTree(partition1); MerkleTree merkleTree2 = indexUtils.buildMerkleTree(partition2); assertEquals(MerkleTree.difference(merkleTree1, merkleTree2).get(0).getRange(), Range.openClosed(42L, 43L)); }