method2testcases
stringlengths
118
6.63k
### Question: RopeUtils { public static <T extends StreamElement> long addWeightsOfRightLeaningParentNodes(Node<T> child) { if (child == null) { throw new IllegalStateException("child node can't be null"); } if (child.parent == null) { return 0; } return (child.isRightNode() ? child.parent.weight : 0) + addWeightsOfRightLeaningParentNodes(child.parent); } static long addWeightsOfRightLeaningChildNodes(Node<T> x); static long addWeightsOfRightLeaningParentNodes(Node<T> child); static void adjustWeightOfLeftLeaningParents(Node<T> startNode, long weight); static long characterCount(Node<T> x); static void collectLeafNodes(Node<T> x, Queue<Node<T>> queue); static Node<T> concat(List<Node<T>> orphans); static Node<T> concat(Node<T> left, Node<T> right); static void cutLeftNode(Node<T> x, List<Node<T>> orphans); static void cutRightNode(Node<T> x, List<Node<T>> orphans); static Node<T> findRoot(Node<T> child); static Node<T> findSearchNode(Node<T> x, long weight, Node<T> root); static NodeIndex<T> index(long characterPosition, Node<T> x, long disp); static boolean intersects(long start, long end, long start2, long end2); static Node<T> rebalance(Node<T> x); }### Answer: @Test public void addWeightsOfRightLeaningParentNodesChainedRight() throws Exception { Node<InvariantSpan> right2 = new Node<>(new InvariantSpan(1, 3, documentHash)); Node<InvariantSpan> right = new Node.Builder<InvariantSpan>(1).right(right2).build(); new Node.Builder<InvariantSpan>(1).right(right).build(); assertEquals(2, RopeUtils.addWeightsOfRightLeaningParentNodes(right2)); } @Test public void addWeightsOfRightLeaningParentNodesLeftNodeChild() throws Exception { Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 1, documentHash)); new Node.Builder<InvariantSpan>(1).left(left).build(); assertEquals(0, RopeUtils.addWeightsOfRightLeaningParentNodes(left)); } @Test(expected = IllegalStateException.class) public void addWeightsOfRightLeaningParentNodesNull() throws Exception { RopeUtils.addWeightsOfRightLeaningParentNodes(null); } @Test public void addWeightsOfRightLeaningParentNodesNullParent() throws Exception { Node<InvariantSpan> x = new Node<>(new InvariantSpan(1, 1, documentHash)); assertEquals(0, RopeUtils.addWeightsOfRightLeaningParentNodes(x)); } @Test public void addWeightsOfRightLeaningParentNodesRightNodeChild() throws Exception { Node<InvariantSpan> right = new Node<>(new InvariantSpan(1, 1, documentHash)); new Node.Builder<InvariantSpan>(1).right(right).build(); assertEquals(1, RopeUtils.addWeightsOfRightLeaningParentNodes(right)); }
### Question: RopeUtils { public static <T extends StreamElement> long characterCount(Node<T> x) { if (x == null) { return 0; } if (x.isLeaf()) { return x.value.getWidth(); } return x.weight + addWeightsOfRightLeaningChildNodes(x); } static long addWeightsOfRightLeaningChildNodes(Node<T> x); static long addWeightsOfRightLeaningParentNodes(Node<T> child); static void adjustWeightOfLeftLeaningParents(Node<T> startNode, long weight); static long characterCount(Node<T> x); static void collectLeafNodes(Node<T> x, Queue<Node<T>> queue); static Node<T> concat(List<Node<T>> orphans); static Node<T> concat(Node<T> left, Node<T> right); static void cutLeftNode(Node<T> x, List<Node<T>> orphans); static void cutRightNode(Node<T> x, List<Node<T>> orphans); static Node<T> findRoot(Node<T> child); static Node<T> findSearchNode(Node<T> x, long weight, Node<T> root); static NodeIndex<T> index(long characterPosition, Node<T> x, long disp); static boolean intersects(long start, long end, long start2, long end2); static Node<T> rebalance(Node<T> x); }### Answer: @Test public void characterCount() throws Exception { Node<InvariantSpan> right = new Node<>(new InvariantSpan(1, 10, documentHash)); Node<InvariantSpan> right2 = new Node<>(new InvariantSpan(1, 20, documentHash)); right.right = right2; Node<InvariantSpan> x = new Node.Builder<InvariantSpan>(10).right(right).build(); assertEquals(40, RopeUtils.characterCount(x)); } @Test public void characterCountLeafNode() throws Exception { assertEquals(3, RopeUtils.characterCount(new Node<>(new InvariantSpan(1, 3, documentHash)))); } @Test public void characterCountNullNode() throws Exception { assertEquals(0, RopeUtils.characterCount(null)); }
### Question: ApplyOverlayOp extends Op { @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ApplyOverlayOp other = (ApplyOverlayOp) obj; if (!linkTypes.equals(other.linkTypes)) return false; if (!variantSpan.equals(other.variantSpan)) return false; return true; } ApplyOverlayOp(DataInputStream dis); ApplyOverlayOp(VariantSpan variantSpan, Set<Integer> linkTypes); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final Set<Integer> linkTypes; final VariantSpan variantSpan; }### Answer: @Test public void equalsTrue() throws Exception { ApplyOverlayOp op1 = new ApplyOverlayOp(new VariantSpan(1, 100), Sets.newHashSet(1, 10)); ApplyOverlayOp op2 = new ApplyOverlayOp(new VariantSpan(1, 100), Sets.newHashSet(1, 10)); assertTrue(op1.equals(op2)); assertTrue(op2.equals(op1)); } @Test public void equalsVariantsFalse() throws Exception { ApplyOverlayOp op1 = new ApplyOverlayOp(new VariantSpan(1, 100), Sets.newHashSet(1, 10)); ApplyOverlayOp op2 = new ApplyOverlayOp(new VariantSpan(2, 100), Sets.newHashSet(1, 10)); assertFalse(op1.equals(op2)); assertFalse(op2.equals(op1)); } @Test public void equalsLinkTypesFalse() throws Exception { ApplyOverlayOp op1 = new ApplyOverlayOp(new VariantSpan(1, 100), Sets.newHashSet(1)); ApplyOverlayOp op2 = new ApplyOverlayOp(new VariantSpan(1, 100), Sets.newHashSet(1, 10)); assertFalse(op1.equals(op2)); assertFalse(op2.equals(op1)); }
### Question: RopeUtils { public static <T extends StreamElement> Node<T> concat(List<Node<T>> orphans) { Iterator<Node<T>> it = orphans.iterator(); Node<T> orphan = it.next(); while (it.hasNext()) { orphan = RopeUtils.concat(orphan, it.next()); } return orphan; } static long addWeightsOfRightLeaningChildNodes(Node<T> x); static long addWeightsOfRightLeaningParentNodes(Node<T> child); static void adjustWeightOfLeftLeaningParents(Node<T> startNode, long weight); static long characterCount(Node<T> x); static void collectLeafNodes(Node<T> x, Queue<Node<T>> queue); static Node<T> concat(List<Node<T>> orphans); static Node<T> concat(Node<T> left, Node<T> right); static void cutLeftNode(Node<T> x, List<Node<T>> orphans); static void cutRightNode(Node<T> x, List<Node<T>> orphans); static Node<T> findRoot(Node<T> child); static Node<T> findSearchNode(Node<T> x, long weight, Node<T> root); static NodeIndex<T> index(long characterPosition, Node<T> x, long disp); static boolean intersects(long start, long end, long start2, long end2); static Node<T> rebalance(Node<T> x); }### Answer: @Test public void concatLeft() throws Exception { Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 10, documentHash)); Node<InvariantSpan> parent = RopeUtils.concat(left, null); assertEquals(10, parent.weight); assertNotNull(left.parent); } @Test public void concatNullLeftNullRight() throws Exception { assertEquals(0, RopeUtils.concat(null, null).weight); } @Test public void concatRight() throws Exception { Node<InvariantSpan> right = new Node<>(new InvariantSpan(1, 10, documentHash)); Node<InvariantSpan> parent = RopeUtils.concat(null, right); assertEquals(0, parent.weight); assertNotNull(right.parent); }
### Question: RopeUtils { public static <T extends StreamElement> Node<T> findSearchNode(Node<T> x, long weight, Node<T> root) { if (root == null) { throw new IllegalArgumentException("root is null"); } if (x == null) { return root; } if (x.weight > weight) { return x; } return findSearchNode(x.parent, weight, root); } static long addWeightsOfRightLeaningChildNodes(Node<T> x); static long addWeightsOfRightLeaningParentNodes(Node<T> child); static void adjustWeightOfLeftLeaningParents(Node<T> startNode, long weight); static long characterCount(Node<T> x); static void collectLeafNodes(Node<T> x, Queue<Node<T>> queue); static Node<T> concat(List<Node<T>> orphans); static Node<T> concat(Node<T> left, Node<T> right); static void cutLeftNode(Node<T> x, List<Node<T>> orphans); static void cutRightNode(Node<T> x, List<Node<T>> orphans); static Node<T> findRoot(Node<T> child); static Node<T> findSearchNode(Node<T> x, long weight, Node<T> root); static NodeIndex<T> index(long characterPosition, Node<T> x, long disp); static boolean intersects(long start, long end, long start2, long end2); static Node<T> rebalance(Node<T> x); }### Answer: @Test public void findSearchNode() throws Exception { }
### Question: DefaultOulipoMachine implements OulipoMachine { @Override public InvariantSpan append(String text) throws IOException, MalformedSpanException { return iStream.append(text); } DefaultOulipoMachine(StreamLoader stream, RemoteFileManager remoteFileManager, String documentHash, Key privateKey); static DefaultOulipoMachine createWritableMachine(StreamLoader loader, RemoteFileManager remoteFileManager, String documentHash); @Override InvariantSpan append(String text); @Override void applyOverlays(VariantSpan variantSpan, Set<Overlay> links); @Override void copyVariant(long to, VariantSpan variantSpan); @Override void deleteVariant(VariantSpan variantSpan); @Override void flush(); @Override String getDocumentHash(); @Override List<Invariant> getInvariants(); @Override List<Invariant> getInvariants(VariantSpan variantSpan); @Override String getText(InvariantSpan invariantSpan); @Override List<VariantSpan> getVariantSpans(InvariantSpan invariantSpan); @Override Invariant index(long characterPosition); @Override void insert(long to, String text); @Override void insertEncrypted(long to, String text); @Override void loadDocument(String hash); @Override void moveVariant(long to, VariantSpan variantSpan); @Override void putInvariant(long to, Invariant invariant); @Override void putOverlay(long to, OverlayStream overlayStream); @Override void swapVariants(VariantSpan v1, VariantSpan v2); @Override void toggleOverlay(VariantSpan variantSpan, Overlay link); }### Answer: @Test public void append() throws Exception { DefaultOulipoMachine som = DefaultOulipoMachine.createWritableMachine(streamLoader, new MockRemoteFileManager(), documentHash); InvariantSpan span = som.append("Hello"); assertEquals(span.getStart(), 1); assertEquals(span.getWidth(), 5); span = som.append("World"); assertEquals(span.getStart(), 6); assertEquals(span.getWidth(), 5); }
### Question: DefaultOulipoMachine implements OulipoMachine { @Override public String getText(InvariantSpan invariantSpan) throws IOException { assertSpanNotNull(invariantSpan); return iStream.getText(invariantSpan); } DefaultOulipoMachine(StreamLoader stream, RemoteFileManager remoteFileManager, String documentHash, Key privateKey); static DefaultOulipoMachine createWritableMachine(StreamLoader loader, RemoteFileManager remoteFileManager, String documentHash); @Override InvariantSpan append(String text); @Override void applyOverlays(VariantSpan variantSpan, Set<Overlay> links); @Override void copyVariant(long to, VariantSpan variantSpan); @Override void deleteVariant(VariantSpan variantSpan); @Override void flush(); @Override String getDocumentHash(); @Override List<Invariant> getInvariants(); @Override List<Invariant> getInvariants(VariantSpan variantSpan); @Override String getText(InvariantSpan invariantSpan); @Override List<VariantSpan> getVariantSpans(InvariantSpan invariantSpan); @Override Invariant index(long characterPosition); @Override void insert(long to, String text); @Override void insertEncrypted(long to, String text); @Override void loadDocument(String hash); @Override void moveVariant(long to, VariantSpan variantSpan); @Override void putInvariant(long to, Invariant invariant); @Override void putOverlay(long to, OverlayStream overlayStream); @Override void swapVariants(VariantSpan v1, VariantSpan v2); @Override void toggleOverlay(VariantSpan variantSpan, Overlay link); }### Answer: @Test public void getText() throws Exception { DefaultOulipoMachine som = DefaultOulipoMachine.createWritableMachine(streamLoader, new MockRemoteFileManager(), documentHash); som.append("Hello"); som.append("World"); String result = som.getText(new InvariantSpan(5, 5, documentHash)); assertEquals("oWorl", result); }
### Question: DefaultOulipoMachine implements OulipoMachine { @Override public void moveVariant(long to, VariantSpan variantSpan) throws MalformedSpanException, IOException { assertGreaterThanZero(to); assertSpanNotNull(variantSpan); vStream.move(to, variantSpan); oStream.move(to, variantSpan); if (writeDocFile) { documentBuilder.moveVariant(to, variantSpan); } } DefaultOulipoMachine(StreamLoader stream, RemoteFileManager remoteFileManager, String documentHash, Key privateKey); static DefaultOulipoMachine createWritableMachine(StreamLoader loader, RemoteFileManager remoteFileManager, String documentHash); @Override InvariantSpan append(String text); @Override void applyOverlays(VariantSpan variantSpan, Set<Overlay> links); @Override void copyVariant(long to, VariantSpan variantSpan); @Override void deleteVariant(VariantSpan variantSpan); @Override void flush(); @Override String getDocumentHash(); @Override List<Invariant> getInvariants(); @Override List<Invariant> getInvariants(VariantSpan variantSpan); @Override String getText(InvariantSpan invariantSpan); @Override List<VariantSpan> getVariantSpans(InvariantSpan invariantSpan); @Override Invariant index(long characterPosition); @Override void insert(long to, String text); @Override void insertEncrypted(long to, String text); @Override void loadDocument(String hash); @Override void moveVariant(long to, VariantSpan variantSpan); @Override void putInvariant(long to, Invariant invariant); @Override void putOverlay(long to, OverlayStream overlayStream); @Override void swapVariants(VariantSpan v1, VariantSpan v2); @Override void toggleOverlay(VariantSpan variantSpan, Overlay link); }### Answer: @Test public void moveVariant() throws Exception { DefaultOulipoMachine machine = DefaultOulipoMachine.createWritableMachine(streamLoader, new MockRemoteFileManager(), documentHash); machine.insert(1, "My first document"); assertEquals("My first document", getText(machine)); machine.moveVariant(1, new VariantSpan(4, 6)); assertEquals("first My document", getText(machine)); }
### Question: ApplyOverlayOp extends Op { @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + linkTypes.hashCode(); result = prime * result + variantSpan.hashCode(); return result; } ApplyOverlayOp(DataInputStream dis); ApplyOverlayOp(VariantSpan variantSpan, Set<Integer> linkTypes); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final Set<Integer> linkTypes; final VariantSpan variantSpan; }### Answer: @Test public void hashTrue() throws Exception { ApplyOverlayOp op1 = new ApplyOverlayOp(new VariantSpan(1, 100), Sets.newHashSet(1, 10)); ApplyOverlayOp op2 = new ApplyOverlayOp(new VariantSpan(1, 100), Sets.newHashSet(1, 10)); assertEquals(op1.hashCode(), op2.hashCode()); ; }
### Question: SwapVariantOp extends Op { @Override public byte[] encode() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(os)) { dos.writeByte(Op.SWAP); dos.writeLong(v1.start); dos.writeLong(v1.width); dos.writeLong(v2.start); dos.writeLong(v2.width); } os.flush(); return os.toByteArray(); } SwapVariantOp(DataInputStream dis); SwapVariantOp(VariantSpan v1, VariantSpan v2); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final VariantSpan v1; final VariantSpan v2; }### Answer: @Test public void encodeDecode() throws Exception { SwapVariantOp op = new SwapVariantOp(new VariantSpan(100, 1), new VariantSpan(200, 1)); byte[] data = op.encode(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); assertEquals(Op.SWAP, dis.readByte()); SwapVariantOp decoded = new SwapVariantOp(dis); assertEquals(op, decoded); }
### Question: SwapVariantOp extends Op { @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; SwapVariantOp other = (SwapVariantOp) obj; if (!v1.equals(other.v1)) return false; if (!v2.equals(other.v2)) return false; return true; } SwapVariantOp(DataInputStream dis); SwapVariantOp(VariantSpan v1, VariantSpan v2); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final VariantSpan v1; final VariantSpan v2; }### Answer: @Test public void equalsFalse() throws Exception { SwapVariantOp op1 = new SwapVariantOp(new VariantSpan(100, 1), new VariantSpan(200, 1)); SwapVariantOp op2 = new SwapVariantOp(new VariantSpan(100, 10), new VariantSpan(200, 1)); assertFalse(op1.equals(op2)); assertFalse(op2.equals(op1)); }
### Question: SwapVariantOp extends Op { @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + v1.hashCode(); result = prime * result + v2.hashCode(); return result; } SwapVariantOp(DataInputStream dis); SwapVariantOp(VariantSpan v1, VariantSpan v2); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final VariantSpan v1; final VariantSpan v2; }### Answer: @Test public void hashFalse() throws Exception { SwapVariantOp op1 = new SwapVariantOp(new VariantSpan(100, 10), new VariantSpan(200, 1)); SwapVariantOp op2 = new SwapVariantOp(new VariantSpan(100, 1), new VariantSpan(200, 1)); assertFalse(op1.hashCode() == op2.hashCode()); ; } @Test public void hashTrue() throws Exception { SwapVariantOp op1 = new SwapVariantOp(new VariantSpan(100, 1), new VariantSpan(200, 1)); SwapVariantOp op2 = new SwapVariantOp(new VariantSpan(100, 1), new VariantSpan(200, 1)); assertEquals(op1.hashCode(), op2.hashCode()); ; }
### Question: PutOverlayMediaOp extends Op { @Override public byte[] encode() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(os)) { dos.writeByte(Op.PUT_OVERLAY_MEDIA); dos.writeLong(to); dos.writeInt(hash); dos.writeInt(linkTypes.size()); for (Integer i : linkTypes) { dos.writeInt(i); } } os.flush(); return os.toByteArray(); } PutOverlayMediaOp(DataInputStream dis); PutOverlayMediaOp(long to, int hash, Set<Integer> linkTypes); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final int hash; final Set<Integer> linkTypes; final long to; }### Answer: @Test public void encodeDecode() throws Exception { PutOverlayMediaOp op = new PutOverlayMediaOp(1, 1, Sets.newSet(10, 5)); byte[] data = op.encode(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); assertEquals(Op.PUT_OVERLAY_MEDIA, dis.readByte()); PutOverlayMediaOp decoded = new PutOverlayMediaOp(dis); assertEquals(op, decoded); }
### Question: PutOverlayMediaOp extends Op { @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; PutOverlayMediaOp other = (PutOverlayMediaOp) obj; if (hash != other.hash) return false; if (!linkTypes.equals(other.linkTypes)) return false; if (to != other.to) return false; return true; } PutOverlayMediaOp(DataInputStream dis); PutOverlayMediaOp(long to, int hash, Set<Integer> linkTypes); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final int hash; final Set<Integer> linkTypes; final long to; }### Answer: @Test public void equalsFalse() throws Exception { PutOverlayMediaOp op1 = new PutOverlayMediaOp(1, 1, Sets.newSet(10, 5)); PutOverlayMediaOp op2 = new PutOverlayMediaOp(2, 1, Sets.newSet(10, 5)); assertFalse(op1.equals(op2)); assertFalse(op2.equals(op1)); }
### Question: PutOverlayMediaOp extends Op { @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + hash; result = prime * result + ((linkTypes == null) ? 0 : linkTypes.hashCode()); result = prime * result + (int) (to ^ (to >>> 32)); return result; } PutOverlayMediaOp(DataInputStream dis); PutOverlayMediaOp(long to, int hash, Set<Integer> linkTypes); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final int hash; final Set<Integer> linkTypes; final long to; }### Answer: @Test public void hashFalse() throws Exception { PutOverlayMediaOp op1 = new PutOverlayMediaOp(1, 1, Sets.newSet(10, 5)); PutOverlayMediaOp op2 = new PutOverlayMediaOp(2, 1, Sets.newSet(10, 5)); assertFalse(op1.hashCode() == op2.hashCode()); } @Test public void hashTrue() throws Exception { PutOverlayMediaOp op1 = new PutOverlayMediaOp(1, 0, Sets.newSet(10, 5)); PutOverlayMediaOp op2 = new PutOverlayMediaOp(1, 0, Sets.newSet(10, 5)); assertEquals(op1.hashCode(), op2.hashCode()); ; }
### Question: StorageService { public <T> void delete(String id, Class<T> clazz) throws StorageException { if (Strings.isNullOrEmpty(id)) { throw new IllegalArgumentException("Id is null"); } if (clazz == null) { throw new IllegalArgumentException("Class is null"); } String key = id + "!" + clazz.getName(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); db.delete(bytes(key + "!" + field.getName())); } } protected StorageService(DB db); StorageService(String name); void close(); void delete(String id, Class<T> clazz); byte[] get(byte[] key); Collection<T> getAll(Class<T> clazz); T load(String id, Class<T> clazz); void put(byte[] key, byte[] value); void save(Object entity); }### Answer: @Test public void delete() throws Exception { TestObject to1 = new TestObject("1", "456"); TestObject to2 = new TestObject("2", "abc"); TestObject to3 = new TestObject("3", "xyz"); service.save(to1); service.save(to2); service.save(to3); service.delete("1", TestObject.class); service.delete("3", TestObject.class); Collection<TestObject> results = service.getAll(TestObject.class); assertEquals(1, results.size()); assertFalse(results.contains(to1)); assertTrue(results.contains(to2)); assertFalse(results.contains(to3)); }
### Question: DeleteVariantOp extends Op { @Override public byte[] encode() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(os)) { dos.writeByte(Op.DELETE); dos.writeLong(variantSpan.start); dos.writeLong(variantSpan.width); } os.flush(); return os.toByteArray(); } DeleteVariantOp(DataInputStream dis); DeleteVariantOp(VariantSpan variantSpan); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final VariantSpan variantSpan; }### Answer: @Test public void encode() throws Exception { DeleteVariantOp op = new DeleteVariantOp(new VariantSpan(1, 100)); byte[] data = op.encode(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); assertEquals(Op.DELETE, dis.read()); assertEquals(1, dis.readLong()); assertEquals(100, dis.readLong()); }
### Question: DeleteVariantOp extends Op { @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; DeleteVariantOp other = (DeleteVariantOp) obj; if (!variantSpan.equals(other.variantSpan)) return false; return true; } DeleteVariantOp(DataInputStream dis); DeleteVariantOp(VariantSpan variantSpan); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final VariantSpan variantSpan; }### Answer: @Test public void equalsVariantsFalse() throws Exception { DeleteVariantOp op1 = new DeleteVariantOp(new VariantSpan(1, 100)); DeleteVariantOp op2 = new DeleteVariantOp(new VariantSpan(2, 100)); assertFalse(op1.equals(op2)); assertFalse(op2.equals(op1)); }
### Question: DeleteVariantOp extends Op { @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + variantSpan.hashCode(); return result; } DeleteVariantOp(DataInputStream dis); DeleteVariantOp(VariantSpan variantSpan); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final VariantSpan variantSpan; }### Answer: @Test public void hashFalse() throws Exception { DeleteVariantOp op1 = new DeleteVariantOp(new VariantSpan(1, 100)); DeleteVariantOp op2 = new DeleteVariantOp(new VariantSpan(2, 100)); assertFalse(op1.hashCode() == op2.hashCode()); ; } @Test public void hashTrue() throws Exception { DeleteVariantOp op1 = new DeleteVariantOp(new VariantSpan(1, 100)); DeleteVariantOp op2 = new DeleteVariantOp(new VariantSpan(1, 100)); assertEquals(op1.hashCode(), op2.hashCode()); ; }
### Question: CopyVariantOp extends Op { @Override public byte[] encode() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(os)) { dos.writeByte(Op.COPY); dos.writeLong(to); dos.writeLong(variantSpan.start); dos.writeLong(variantSpan.width); } os.flush(); return os.toByteArray(); } CopyVariantOp(DataInputStream dis); CopyVariantOp(long to, VariantSpan variantSpan); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final long to; final VariantSpan variantSpan; }### Answer: @Test public void encodeDecode() throws Exception { CopyVariantOp op = new CopyVariantOp(100, new VariantSpan(50, 75)); byte[] data = op.encode(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); assertEquals(Op.COPY, dis.readByte()); CopyVariantOp decoded = new CopyVariantOp(dis); assertEquals(op, decoded); }
### Question: CopyVariantOp extends Op { @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; CopyVariantOp other = (CopyVariantOp) obj; if (to != other.to) return false; if (!variantSpan.equals(other.variantSpan)) return false; return true; } CopyVariantOp(DataInputStream dis); CopyVariantOp(long to, VariantSpan variantSpan); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final long to; final VariantSpan variantSpan; }### Answer: @Test public void equalsPositionsFalse() throws Exception { CopyVariantOp op1 = new CopyVariantOp(1, new VariantSpan(1, 100)); CopyVariantOp op2 = new CopyVariantOp(2, new VariantSpan(1, 100)); assertFalse(op1.equals(op2)); assertFalse(op2.equals(op1)); } @Test public void equalsVariantsFalse() throws Exception { CopyVariantOp op1 = new CopyVariantOp(1, new VariantSpan(1, 100)); CopyVariantOp op2 = new CopyVariantOp(1, new VariantSpan(2, 100)); assertFalse(op1.equals(op2)); assertFalse(op2.equals(op1)); }
### Question: CopyVariantOp extends Op { @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (int) (to ^ (to >>> 32)); result = prime * result + variantSpan.hashCode(); return result; } CopyVariantOp(DataInputStream dis); CopyVariantOp(long to, VariantSpan variantSpan); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final long to; final VariantSpan variantSpan; }### Answer: @Test public void hashTrue() throws Exception { CopyVariantOp op1 = new CopyVariantOp(1, new VariantSpan(1, 100)); CopyVariantOp op2 = new CopyVariantOp(1, new VariantSpan(1, 100)); assertEquals(op1.hashCode(), op2.hashCode()); ; }
### Question: MoveVariantOp extends Op { @Override public byte[] encode() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(os)) { dos.writeByte(Op.MOVE); dos.writeLong(to); dos.writeLong(variantSpan.start); dos.writeLong(variantSpan.width); } os.flush(); return os.toByteArray(); } MoveVariantOp(DataInputStream dis); MoveVariantOp(long to, VariantSpan variantSpan); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final long to; final VariantSpan variantSpan; }### Answer: @Test public void encodeDecode() throws Exception { MoveVariantOp op = new MoveVariantOp(100, new VariantSpan(50, 75)); byte[] data = op.encode(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); assertEquals(Op.MOVE, dis.readByte()); MoveVariantOp decoded = new MoveVariantOp(dis); assertEquals(op, decoded); }
### Question: StorageService { public <T> Collection<T> getAll(Class<T> clazz) throws ClassNotFoundException, StorageException, IOException { List<T> c = new ArrayList<>(); Map<String, String> ids = new HashMap<>(); try (DBIterator it = db.iterator()) { it.seekToFirst(); String prevId = null; while (it.hasNext()) { String key = new String(it.next().getKey()); String[] tokens = key.split("!"); String id = tokens[0]; String className = tokens[1]; if (!id.equals(prevId)) { if (clazz.getName().equals(className)) { ids.put(id, className); } prevId = id; } } for (Map.Entry<String, String> id : ids.entrySet()) { T o = (T) load(id.getKey(), Class.forName(id.getValue())); c.add(o); } } return c; } protected StorageService(DB db); StorageService(String name); void close(); void delete(String id, Class<T> clazz); byte[] get(byte[] key); Collection<T> getAll(Class<T> clazz); T load(String id, Class<T> clazz); void put(byte[] key, byte[] value); void save(Object entity); }### Answer: @Test public void getAll() throws Exception { TestObject to1 = new TestObject("1", "456"); TestObject to2 = new TestObject("2", "abc"); TestObject to3 = new TestObject("3", "xyz"); service.save(to1); service.save(to2); service.save(to3); Collection<TestObject> results = service.getAll(TestObject.class); assertEquals(3, results.size()); assertTrue(results.contains(to1)); assertTrue(results.contains(to2)); assertTrue(results.contains(to3)); }
### Question: MoveVariantOp extends Op { @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; MoveVariantOp other = (MoveVariantOp) obj; if (to != other.to) return false; if (!variantSpan.equals(other.variantSpan)) return false; return true; } MoveVariantOp(DataInputStream dis); MoveVariantOp(long to, VariantSpan variantSpan); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final long to; final VariantSpan variantSpan; }### Answer: @Test public void equalsVariantsFalse() throws Exception { MoveVariantOp op1 = new MoveVariantOp(1, new VariantSpan(1, 100)); MoveVariantOp op2 = new MoveVariantOp(1, new VariantSpan(2, 100)); assertFalse(op1.equals(op2)); assertFalse(op2.equals(op1)); }
### Question: MoveVariantOp extends Op { @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (int) (to ^ (to >>> 32)); result = prime * result + variantSpan.hashCode(); return result; } MoveVariantOp(DataInputStream dis); MoveVariantOp(long to, VariantSpan variantSpan); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final long to; final VariantSpan variantSpan; }### Answer: @Test public void hashFalse() throws Exception { MoveVariantOp op1 = new MoveVariantOp(1, new VariantSpan(1, 100)); MoveVariantOp op2 = new MoveVariantOp(1, new VariantSpan(2, 100)); assertFalse(op1.hashCode() == op2.hashCode()); ; } @Test public void hashFalse2() throws Exception { MoveVariantOp op1 = new MoveVariantOp(1, new VariantSpan(1, 100)); MoveVariantOp op2 = new MoveVariantOp(2, new VariantSpan(1, 100)); assertFalse(op1.hashCode() == op2.hashCode()); ; } @Test public void hashTrue() throws Exception { MoveVariantOp op1 = new MoveVariantOp(1, new VariantSpan(1, 100)); MoveVariantOp op2 = new MoveVariantOp(1, new VariantSpan(1, 100)); assertEquals(op1.hashCode(), op2.hashCode()); ; }
### Question: PutInvariantSpanOp extends Op { @Override public byte[] encode() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(os)) { dos.writeByte(Op.PUT_INVARIANT_SPAN); dos.writeLong(to); dos.writeLong(invariantStart); dos.writeLong(width); dos.writeInt(ripIndex); } os.flush(); return os.toByteArray(); } PutInvariantSpanOp(DataInputStream dis); PutInvariantSpanOp(long to, long invariantStart, long width, int ripIndex); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final long invariantStart; final int ripIndex; final long to; final long width; }### Answer: @Test public void encodeDecode() throws Exception { PutInvariantSpanOp op = new PutInvariantSpanOp(100, 50, 1, 0); byte[] data = op.encode(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); assertEquals(Op.PUT_INVARIANT_SPAN, dis.readByte()); PutInvariantSpanOp decoded = new PutInvariantSpanOp(dis); assertEquals(op, decoded); }
### Question: PutInvariantSpanOp extends Op { @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; PutInvariantSpanOp other = (PutInvariantSpanOp) obj; if (ripIndex != other.ripIndex) return false; if (invariantStart != other.invariantStart) return false; if (to != other.to) return false; if (width != other.width) return false; return true; } PutInvariantSpanOp(DataInputStream dis); PutInvariantSpanOp(long to, long invariantStart, long width, int ripIndex); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final long invariantStart; final int ripIndex; final long to; final long width; }### Answer: @Test public void equalsFalse() throws Exception { PutInvariantSpanOp op1 = new PutInvariantSpanOp(100, 50, 1, 0); PutInvariantSpanOp op2 = new PutInvariantSpanOp(101, 50, 1, 0); assertFalse(op1.equals(op2)); assertFalse(op2.equals(op1)); }
### Question: PutInvariantSpanOp extends Op { @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ripIndex; result = prime * result + (int) (invariantStart ^ (invariantStart >>> 32)); result = prime * result + (int) (to ^ (to >>> 32)); result = prime * result + (int) (width ^ (width >>> 32)); return result; } PutInvariantSpanOp(DataInputStream dis); PutInvariantSpanOp(long to, long invariantStart, long width, int ripIndex); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final long invariantStart; final int ripIndex; final long to; final long width; }### Answer: @Test public void hashFalse() throws Exception { PutInvariantSpanOp op1 = new PutInvariantSpanOp(100, 50, 1, 0); PutInvariantSpanOp op2 = new PutInvariantSpanOp(101, 50, 1, 0); assertFalse(op1.hashCode() == op2.hashCode()); ; } @Test public void hashTrue() throws Exception { PutInvariantSpanOp op1 = new PutInvariantSpanOp(100, 50, 1, 0); PutInvariantSpanOp op2 = new PutInvariantSpanOp(100, 50, 1, 0); assertEquals(op1.hashCode(), op2.hashCode()); ; }
### Question: PutInvariantMediaOp extends Op { @Override public byte[] encode() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(os)) { dos.writeByte(Op.PUT_INVARIANT_MEDIA); dos.writeLong(to); dos.writeInt(ripIndex); } os.flush(); return os.toByteArray(); } PutInvariantMediaOp(DataInputStream dis); PutInvariantMediaOp(long to, int ripIndex); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final int ripIndex; final long to; }### Answer: @Test public void encodeDecode() throws Exception { PutInvariantMediaOp op = new PutInvariantMediaOp(100, 1); byte[] data = op.encode(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); assertEquals(Op.PUT_INVARIANT_MEDIA, dis.readByte()); PutInvariantMediaOp decoded = new PutInvariantMediaOp(dis); assertEquals(op, decoded); }
### Question: PutInvariantMediaOp extends Op { @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; PutInvariantMediaOp other = (PutInvariantMediaOp) obj; if (ripIndex != other.ripIndex) return false; if (to != other.to) return false; return true; } PutInvariantMediaOp(DataInputStream dis); PutInvariantMediaOp(long to, int ripIndex); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final int ripIndex; final long to; }### Answer: @Test public void equalsFalse() throws Exception { PutInvariantMediaOp op1 = new PutInvariantMediaOp(1, 2); PutInvariantMediaOp op2 = new PutInvariantMediaOp(2, 2); assertFalse(op1.equals(op2)); assertFalse(op2.equals(op1)); }
### Question: DocumentFile { public String getInvariantStream() { return invariantStream; } private DocumentFile(); static org.oulipo.streams.Compiler<DocumentFile> compiler(); static Decompiler<DocumentFile> decompiler(); Map<Integer, String> get(); String getDocumentHash(); String getEncyptedInvariantStream(); String getGenesisHash(); String getHashPreviousBlock(); String getInvariantStream(); int getMajorVersion(); int getMinorVersion(); List<Op> getOps(); Overlay getOverlay(int overlayIndex); Map<Integer, Overlay> getOverlayPool(); Set<Overlay> getOverlays(Set<Integer> indicies); String getString(int stringPoolIndex); long getTimestamp(); boolean hasEncryptedInvariantStream(); boolean hasGenesisHash(); boolean hasHashPreviousBlock(); boolean hasInvariantStream(); int operationCount(); int overlayPoolSize(); int stringPoolSize(); static final byte[] MAGIC; }### Answer: @Test public void addText() throws Exception { DocumentFile.Builder builder = new DocumentFile.Builder("fakeHash"); builder.appendText("Xanadu"); builder.appendText("Green"); DocumentFile file = builder.build(); assertEquals("XanaduGreen", file.getInvariantStream()); }
### Question: PutInvariantMediaOp extends Op { @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ripIndex; result = prime * result + (int) (to ^ (to >>> 32)); return result; } PutInvariantMediaOp(DataInputStream dis); PutInvariantMediaOp(long to, int ripIndex); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final int ripIndex; final long to; }### Answer: @Test public void hashFalse() throws Exception { PutInvariantMediaOp op1 = new PutInvariantMediaOp(1, 2); PutInvariantMediaOp op2 = new PutInvariantMediaOp(2, 2); assertFalse(op1.hashCode() == op2.hashCode()); ; } @Test public void hashTrue() throws Exception { PutInvariantMediaOp op1 = new PutInvariantMediaOp(1, 2); PutInvariantMediaOp op2 = new PutInvariantMediaOp(1, 2); assertEquals(op1.hashCode(), op2.hashCode()); ; }
### Question: PutOverlayOp extends Op { @Override public byte[] encode() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(os)) { dos.writeByte(Op.PUT_OVERLAY); dos.writeLong(variantSpan.start); dos.writeLong(variantSpan.width); dos.writeInt(linkTypes.size()); for (Integer i : linkTypes) { dos.writeInt(i); } } os.flush(); return os.toByteArray(); } PutOverlayOp(DataInputStream dis); PutOverlayOp(VariantSpan variantSpan, Set<Integer> linkTypes); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); final Set<Integer> linkTypes; final VariantSpan variantSpan; }### Answer: @Test public void encodeDecode() throws Exception { PutOverlayOp op = new PutOverlayOp(new VariantSpan(100, 1), Sets.newSet(10, 5)); byte[] data = op.encode(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); assertEquals(Op.PUT_OVERLAY, dis.readByte()); PutOverlayOp decoded = new PutOverlayOp(dis); assertEquals(op, decoded); }
### Question: VariantSpan { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; VariantSpan other = (VariantSpan) obj; if (documentHash == null) { if (other.documentHash != null) return false; } else if (!documentHash.equals(other.documentHash)) return false; if (start != other.start) return false; if (width != other.width) return false; return true; } private VariantSpan(); VariantSpan(DataInputStream dis); VariantSpan(long start, long width); VariantSpan(long start, long width, String documentHash); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); public String documentHash; public long start; public long width; }### Answer: @Test public void homeNoMatch() throws Exception { assertFalse(new VariantSpan(1, 9, "fakeHash").equals(new VariantSpan(1, 10))); } @Test public void startNoMatch() throws MalformedSpanException { assertFalse(new VariantSpan(1, 10).equals(new VariantSpan(2, 10))); } @Test public void widthNoMatch() throws MalformedSpanException { assertFalse(new VariantSpan(1, 9).equals(new VariantSpan(1, 10))); }
### Question: InvariantSpan implements Invariant { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; InvariantSpan other = (InvariantSpan) obj; if (documentHash == null) { if (other.documentHash != null) return false; } else if (!documentHash.equals(other.documentHash)) return false; if (start != other.start) return false; if (width != other.width) return false; return true; } InvariantSpan(); InvariantSpan(long start, long width, String documentHash); @Override InvariantSpan copy(); @Override boolean equals(Object obj); String getDocumentHash(); long getStart(); @Override long getWidth(); @Override int hashCode(); boolean hashDocumentHash(); void setStart(long start); @Override void setWidth(long width); @Override StreamElementPartition<InvariantSpan> split(long leftPartitionWidth); @Override String toString(); }### Answer: @Test public void inequality() throws Exception { InvariantSpan s1 = new InvariantSpan(10, 60, "ted: InvariantSpan s2 = new InvariantSpan(10, 50, "ted: assertFalse(s1.equals(s2)); }
### Question: InvariantSpan implements Invariant { @Override public StreamElementPartition<InvariantSpan> split(long leftPartitionWidth) throws MalformedSpanException { if (leftPartitionWidth < 1) { throw new IndexOutOfBoundsException( "Partition width must be greater than 0, partitionWidth = " + leftPartitionWidth); } if (width <= leftPartitionWidth) { throw new IndexOutOfBoundsException("Width of left partition is greater than or equal to span: span width =" + width + ", partitionWidth = " + leftPartitionWidth); } return new StreamElementPartition<InvariantSpan>(new InvariantSpan(start, leftPartitionWidth, documentHash), new InvariantSpan(start + leftPartitionWidth, width - leftPartitionWidth, documentHash)); } InvariantSpan(); InvariantSpan(long start, long width, String documentHash); @Override InvariantSpan copy(); @Override boolean equals(Object obj); String getDocumentHash(); long getStart(); @Override long getWidth(); @Override int hashCode(); boolean hashDocumentHash(); void setStart(long start); @Override void setWidth(long width); @Override StreamElementPartition<InvariantSpan> split(long leftPartitionWidth); @Override String toString(); }### Answer: @Test public void split() throws Exception { InvariantSpan span = new InvariantSpan(1, 4, documentHash); StreamElementPartition<InvariantSpan> result = span.split(1); assertEquals(new InvariantSpan(1, 1, documentHash), result.getLeft()); assertEquals(new InvariantSpan(2, 3, documentHash), result.getRight()); } @Test public void splitEnd() throws Exception { InvariantSpan span = new InvariantSpan(1, 4, documentHash); StreamElementPartition<InvariantSpan> part = span.split(3); assertEquals(new InvariantSpan(1, 3, documentHash), part.getLeft()); assertEquals(new InvariantSpan(4, 1, documentHash), part.getRight()); } @Test(expected = IndexOutOfBoundsException.class) public void splitOverUpperBound() throws Exception { InvariantSpan span = new InvariantSpan(100, 10, documentHash); span.split(15); } @Test(expected = IndexOutOfBoundsException.class) public void splitStart() throws Exception { InvariantSpan span = new InvariantSpan(1, 4, documentHash); span.split(0); }
### Question: DocumentFile { public String getHashPreviousBlock() { return hashPreviousBlock; } private DocumentFile(); static org.oulipo.streams.Compiler<DocumentFile> compiler(); static Decompiler<DocumentFile> decompiler(); Map<Integer, String> get(); String getDocumentHash(); String getEncyptedInvariantStream(); String getGenesisHash(); String getHashPreviousBlock(); String getInvariantStream(); int getMajorVersion(); int getMinorVersion(); List<Op> getOps(); Overlay getOverlay(int overlayIndex); Map<Integer, Overlay> getOverlayPool(); Set<Overlay> getOverlays(Set<Integer> indicies); String getString(int stringPoolIndex); long getTimestamp(); boolean hasEncryptedInvariantStream(); boolean hasGenesisHash(); boolean hasHashPreviousBlock(); boolean hasInvariantStream(); int operationCount(); int overlayPoolSize(); int stringPoolSize(); static final byte[] MAGIC; }### Answer: @Test public void hashBlock() throws Exception { DocumentFile.Builder builder = new DocumentFile.Builder("fakeHash"); builder.previousHashBlock("sadasdsad"); DocumentFile file = builder.build(); assertEquals("sadasdsad", file.getHashPreviousBlock()); }
### Question: Node { public boolean isRoot() { return parent == null; } Node(long weight); Node(T value); long characterCount(); boolean isLeaf(); boolean isRightNode(); boolean isRoot(); Node<T> split(long leftPartitionWidth); @Override String toString(); public boolean isRed; public Node<T> left; public Node<T> parent; public Node<T> right; public String tag; final T value; public long weight; }### Answer: @Test public void root() throws Exception { assertTrue(new Node<InvariantSpan>(10).isRoot()); }
### Question: Node { public Node<T> split(long leftPartitionWidth) throws MalformedSpanException { if (leftPartitionWidth < 1) { throw new IllegalArgumentException("leftPartitionWidth must be greater than 0"); } if (!isLeaf()) { throw new MalformedSpanException("Can only split a leaf node"); } Node<T> parent = new Node<T>(leftPartitionWidth); StreamElementPartition<T> spans = (StreamElementPartition<T>) value.split(leftPartitionWidth); parent.left = new Node<T>(spans.getLeft()); parent.right = new Node<T>(spans.getRight()); parent.left.parent = parent; parent.right.parent = parent; if (parent.weight != leftPartitionWidth) { throw new IllegalStateException("node weight must equal variant position cutpoint"); } return parent; } Node(long weight); Node(T value); long characterCount(); boolean isLeaf(); boolean isRightNode(); boolean isRoot(); Node<T> split(long leftPartitionWidth); @Override String toString(); public boolean isRed; public Node<T> left; public Node<T> parent; public Node<T> right; public String tag; final T value; public long weight; }### Answer: @Test public void simpleSplit() throws Exception { Node<InvariantSpan> node = new Node<InvariantSpan>(new InvariantSpan(1, 10, documentHash)); Node<InvariantSpan> result = node.split(5); assertNotNull(result.left); assertNotNull(result.right); assertEquals(new InvariantSpan(1, 5, documentHash), result.left.value); assertEquals(new InvariantSpan(6, 5, documentHash), result.right.value); } @Test public void split13() throws Exception { Node<InvariantSpan> result = getK().split(2); assertEquals(new InvariantSpan(300, 2, documentHash), result.left.value); assertEquals(new InvariantSpan(302, 2, documentHash), result.right.value); } @Test(expected = MalformedSpanException.class) public void splitBranch() throws Exception { new Node<InvariantSpan>(10).split(5); } @Test public void splitEdge() throws Exception { Node<InvariantSpan> result = getE().split(4); assertEquals(new InvariantSpan(100, 4, documentHash), result.left.value); assertEquals(new InvariantSpan(104, 2, documentHash), result.right.value); } @Test public void splitF() throws Exception { Node<InvariantSpan> result = getF().split(2); assertEquals(new InvariantSpan(200, 2, documentHash), result.left.value); assertEquals(new InvariantSpan(202, 1, documentHash), result.right.value); } @Test public void splitMinEdge() throws Exception { Node<InvariantSpan> result = getE().split(1); assertEquals(new InvariantSpan(100, 1, documentHash), result.left.value); assertEquals(new InvariantSpan(101, 5, documentHash), result.right.value); } @Test(expected = IllegalArgumentException.class) public void splitNegative() throws Exception { Node<InvariantSpan> node = new Node<InvariantSpan>(new InvariantSpan(1, 10, documentHash)); node.split(-1); }
### Question: FileInvariantStream implements InvariantStream { @Override public InvariantSpan append(String text) throws IOException, MalformedSpanException { if (Strings.isNullOrEmpty(text)) { throw new MalformedSpanException("No text - span length is 0"); } FileLock lock = channel.lock(); try { InvariantSpan span = new InvariantSpan(channel.position() + 1, text.length(), documentHash); buffer.clear(); buffer.put(text.getBytes()); buffer.flip(); while (buffer.hasRemaining()) { channel.write(buffer); } channel.force(true); return span; } finally { lock.release(); } } FileInvariantStream(File file, File encryptedFile, String documentHash, Key key); @Override InvariantSpan append(String text); @Override String getText(InvariantSpan ispan); }### Answer: @Test public void streamLoadable() throws Exception { File file = new File("target/streams-junit/FileInvariantStream-" + System.currentTimeMillis() + ".txt"); InvariantStream stream = new FileInvariantStream(file, null, "fakeHash", null); stream.append("Hello"); stream.append("Xanadu"); }
### Question: DocumentFileCompiler implements Compiler<DocumentFile> { @Override public String compileEncrypted(DocumentFile doc, ECKey ecKey, Key key) throws Exception { if (ecKey == null) { throw new IllegalArgumentException("ECKey is null"); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream os = new DataOutputStream(baos); String publicKeyHash = URLDecoder.decode(ecKey.toAddress(MainNetParams.get()).toString(), "UTF-8"); os.write(DocumentFile.MAGIC); os.writeShort(0); os.writeUTF(publicKeyHash); os.writeUTF(doc.hasGenesisHash() ? doc.getGenesisHash() : ""); os.writeUTF(doc.hasHashPreviousBlock() ? doc.getHashPreviousBlock() : ""); os.writeInt(doc.getMajorVersion()); os.writeInt(doc.getMinorVersion()); os.writeLong(System.currentTimeMillis()); os.writeInt(doc.stringPoolSize()); for (Map.Entry<Integer, String> entry : doc.getStringPool().entrySet()) { os.writeInt(entry.getKey()); os.writeUTF(entry.getValue()); } os.writeInt(doc.overlayPoolSize()); for (Map.Entry<Integer, Overlay> entry : doc.getOverlayPool().entrySet()) { os.writeInt(entry.getKey()); os.write(entry.getValue().encode()); } os.writeUTF(doc.hasInvariantStream() ? doc.getInvariantStream() : ""); os.writeUTF(doc.hasEncryptedInvariantStream() ? encrypt(doc.getEncyptedInvariantStream(), key) : ""); os.writeInt(doc.operationCount()); for (Op op : doc.getOps()) { os.write(op.encode()); } String message = base64Url().encode(baos.toByteArray()); String signature64 = ecKey.signMessage(message); return message + "." + publicKeyHash + "." + signature64; } static DocumentFileCompiler createInstance(); @Override String compileEncrypted(DocumentFile doc, ECKey ecKey, Key key); }### Answer: @Test public void addEncryptedTextCompile() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2056); KeyPair pair = keyGen.generateKeyPair(); DocumentFile.Builder builder = new DocumentFile.Builder("fakeHash"); builder.appendEncryptedText("Xanadu"); builder.appendEncryptedText("Green"); DocumentFile file = builder.build(); String compiledDocument = DocumentFile.compiler().compileEncrypted(file, new ECKey(), pair.getPublic()); DocumentFile result = DocumentFile.decompiler().decompileEncrypted("fakehash", compiledDocument.getBytes(), pair.getPrivate()); assertEquals("XanaduGreen", result.getEncyptedInvariantStream()); }
### Question: ToggleOverlayOp extends Op { @Override public byte[] encode() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(os)) { dos.writeByte(Op.TOGGLE_OVERLAY); dos.writeLong(variantSpan.start); dos.writeLong(variantSpan.width); dos.writeInt(linkTypeIndex); } os.flush(); return os.toByteArray(); } ToggleOverlayOp(DataInputStream dis); ToggleOverlayOp(VariantSpan variantSpan, int linkTypeIndex); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final int linkTypeIndex; final VariantSpan variantSpan; }### Answer: @Test public void encodeDecode() throws Exception { ToggleOverlayOp op = new ToggleOverlayOp(new VariantSpan(100, 1), 10); byte[] data = op.encode(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); assertEquals(Op.TOGGLE_OVERLAY, dis.readByte()); ToggleOverlayOp decoded = new ToggleOverlayOp(dis); assertEquals(op, decoded); }
### Question: ApplyOverlayOp extends Op { @Override public byte[] encode() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(os)) { dos.writeByte(Op.APPLY_OVERLAY); dos.writeLong(variantSpan.start); dos.writeLong(variantSpan.width); dos.writeInt(linkTypes.size()); for (Integer i : linkTypes) { if (i < 0) { throw new IOException("Tumbler pool index must be 0 or greater: " + i); } dos.writeInt(i); } } os.flush(); return os.toByteArray(); } ApplyOverlayOp(DataInputStream dis); ApplyOverlayOp(VariantSpan variantSpan, Set<Integer> linkTypes); @Override byte[] encode(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); final Set<Integer> linkTypes; final VariantSpan variantSpan; }### Answer: @Test public void encode() throws Exception { ApplyOverlayOp op = new ApplyOverlayOp(new VariantSpan(1, 100), Sets.newHashSet(1, 10)); byte[] data = op.encode(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); assertEquals(Op.APPLY_OVERLAY, dis.read()); assertEquals(1, dis.readLong()); assertEquals(100, dis.readLong()); assertEquals(2, dis.readInt()); assertEquals(1, dis.readInt()); assertEquals(10, dis.readInt()); } @Test public void encodeDecode() throws Exception { ApplyOverlayOp op = new ApplyOverlayOp(new VariantSpan(1, 100), Sets.newHashSet(1, 10)); byte[] data = op.encode(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); assertEquals(Op.APPLY_OVERLAY, dis.readByte()); ApplyOverlayOp decoded = new ApplyOverlayOp(dis); assertEquals(op, decoded); }
### Question: RopeVariantStream implements VariantStream<T> { @Override public void copy(long characterPosition, VariantSpan variantSpan) throws MalformedSpanException, IOException { putElements(characterPosition, getStreamElements(variantSpan)); } RopeVariantStream(String documentHash); RopeVariantStream(String documentHash, Node<T> root); @Override void copy(long characterPosition, VariantSpan variantSpan); @Override void delete(VariantSpan variantSpan); @Override String getDocumentHash(); @Override List<T> getStreamElements(); @Override List<T> getStreamElements(VariantSpan variantSpan); @Override List<VariantSpan> getVariantSpans(InvariantSpan targetSpan); @Override T index(long characterPosition); @Override void move(long to, VariantSpan v1); @Override void put(long characterPosition, T val); @Override void rebalance(); void save(OutputStream os); @Override void swap(VariantSpan v1, VariantSpan v2); @Override void toggleOverlay(VariantSpan variantSpan, Overlay linkType); }### Answer: @Test public void copy() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash, getA()); stream.copy(2, new VariantSpan(12, 3)); List<InvariantSpan> spans = stream.getStreamElements(); assertEquals(new InvariantSpan(100, 1, documentHash), spans.get(0)); assertEquals(new InvariantSpan(301, 3, documentHash), spans.get(1)); assertEquals(new InvariantSpan(200, 3, documentHash), spans.get(3)); assertEquals(new InvariantSpan(250, 2, documentHash), spans.get(4)); assertEquals(new InvariantSpan(300, 4, documentHash), spans.get(5)); assertEquals(new InvariantSpan(350, 1, documentHash), spans.get(6)); assertEquals(new InvariantSpan(360, 6, documentHash), spans.get(7)); }
### Question: RopeVariantStream implements VariantStream<T> { @Override public void delete(VariantSpan variantSpan) throws MalformedSpanException { if (variantSpan == null) { throw new MalformedSpanException("Variant span is null for delete operation"); } deleteRange(variantSpan); } RopeVariantStream(String documentHash); RopeVariantStream(String documentHash, Node<T> root); @Override void copy(long characterPosition, VariantSpan variantSpan); @Override void delete(VariantSpan variantSpan); @Override String getDocumentHash(); @Override List<T> getStreamElements(); @Override List<T> getStreamElements(VariantSpan variantSpan); @Override List<VariantSpan> getVariantSpans(InvariantSpan targetSpan); @Override T index(long characterPosition); @Override void move(long to, VariantSpan v1); @Override void put(long characterPosition, T val); @Override void rebalance(); void save(OutputStream os); @Override void swap(VariantSpan v1, VariantSpan v2); @Override void toggleOverlay(VariantSpan variantSpan, Overlay linkType); }### Answer: @Test public void delete() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash, getA()); stream.delete(new VariantSpan(12, 4)); List<InvariantSpan> spans = stream.getStreamElements(); assertEquals(new InvariantSpan(100, 6, documentHash), spans.get(0)); assertEquals(new InvariantSpan(200, 3, documentHash), spans.get(1)); assertEquals(new InvariantSpan(250, 2, documentHash), spans.get(2)); assertEquals(new InvariantSpan(350, 1, documentHash), spans.get(3)); assertEquals(new InvariantSpan(360, 6, documentHash), spans.get(4)); assertEquals(5, spans.size()); }
### Question: RopeVariantStream implements VariantStream<T> { @Override public List<VariantSpan> getVariantSpans(InvariantSpan targetSpan) throws MalformedSpanException { long index = 1; List<VariantSpan> vspans = new ArrayList<>(); List<T> spans = getStreamElements(); for (int i = 0; i < spans.size(); i++) { T element = spans.get(i); long targetStart = targetSpan.getStart(); long targetEnd = targetStart + targetSpan.getWidth(); if (!(element instanceof InvariantSpan)) { continue; } InvariantSpan span = (InvariantSpan) element; long start = span.getStart(); long end = start + span.getWidth(); if (RopeUtils.intersects(start, end, targetStart, targetEnd)) { long a = Math.max(0, targetStart - start); long b = Math.max(0, end - targetEnd); VariantSpan vs = new VariantSpan(index + a, span.getWidth() - b - a); vs.documentHash = documentHash; vspans.add(vs); } index += span.getWidth(); } return vspans; } RopeVariantStream(String documentHash); RopeVariantStream(String documentHash, Node<T> root); @Override void copy(long characterPosition, VariantSpan variantSpan); @Override void delete(VariantSpan variantSpan); @Override String getDocumentHash(); @Override List<T> getStreamElements(); @Override List<T> getStreamElements(VariantSpan variantSpan); @Override List<VariantSpan> getVariantSpans(InvariantSpan targetSpan); @Override T index(long characterPosition); @Override void move(long to, VariantSpan v1); @Override void put(long characterPosition, T val); @Override void rebalance(); void save(OutputStream os); @Override void swap(VariantSpan v1, VariantSpan v2); @Override void toggleOverlay(VariantSpan variantSpan, Overlay linkType); }### Answer: @Test public void getVariantSpansTwoIntersect() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash); List<InvariantSpan> spans = Arrays.asList(new InvariantSpan(7, 5, documentHash), new InvariantSpan(4, 3, documentHash), new InvariantSpan(1, 3, documentHash)); stream.putElements(1, spans); List<VariantSpan> result = stream.getVariantSpans(new InvariantSpan(2, 5, documentHash)); assertEquals(2, result.size()); assertEquals(new VariantSpan(6, 3, documentHash), result.get(0)); assertEquals(new VariantSpan(10, 2, documentHash), result.get(1)); } @Test public void getVariantSpansTwoIntersect2() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash); List<InvariantSpan> spans = Arrays.asList(new InvariantSpan(7, 5, documentHash), new InvariantSpan(4, 3, documentHash), new InvariantSpan(1, 3, documentHash)); stream.putElements(1, spans); List<VariantSpan> result = stream.getVariantSpans(new InvariantSpan(1, 4, documentHash)); assertEquals(2, result.size()); assertEquals(new VariantSpan(6, 1, documentHash), result.get(0)); assertEquals(new VariantSpan(9, 3, documentHash), result.get(1)); }
### Question: RopeVariantStream implements VariantStream<T> { @Override public T index(long characterPosition) { if (root == null) { throw new IllegalStateException("Stream is empty"); } return RopeUtils.index(characterPosition, root, 0).node.value; } RopeVariantStream(String documentHash); RopeVariantStream(String documentHash, Node<T> root); @Override void copy(long characterPosition, VariantSpan variantSpan); @Override void delete(VariantSpan variantSpan); @Override String getDocumentHash(); @Override List<T> getStreamElements(); @Override List<T> getStreamElements(VariantSpan variantSpan); @Override List<VariantSpan> getVariantSpans(InvariantSpan targetSpan); @Override T index(long characterPosition); @Override void move(long to, VariantSpan v1); @Override void put(long characterPosition, T val); @Override void rebalance(); void save(OutputStream os); @Override void swap(VariantSpan v1, VariantSpan v2); @Override void toggleOverlay(VariantSpan variantSpan, Overlay linkType); }### Answer: @Test public void index() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash, getA()); InvariantSpan span = stream.index(12); assertEquals(new InvariantSpan(300, 4, documentHash), span); } @Test public void index11() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash, getA()); InvariantSpan span = stream.index(11); assertEquals(new InvariantSpan(250, 2, documentHash), span); span = stream.index(10); assertEquals(new InvariantSpan(250, 2, documentHash), span); } @Test(expected = IndexOutOfBoundsException.class) public void indexNull() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash, getA()); InvariantSpan span = stream.index(100); assertNull(span); }
### Question: RopeVariantStream implements VariantStream<T> { @Override public void put(long characterPosition, T val) throws MalformedSpanException { if (val == null) { throw new IllegalArgumentException("invariant span is null"); } if (characterPosition < 1) { throw new IndexOutOfBoundsException("put position must be greater than 0"); } if (val.getWidth() < 1) { throw new MalformedSpanException("invariant span must have a width greater than 0"); } insert(characterPosition, new Node<T>(val)); } RopeVariantStream(String documentHash); RopeVariantStream(String documentHash, Node<T> root); @Override void copy(long characterPosition, VariantSpan variantSpan); @Override void delete(VariantSpan variantSpan); @Override String getDocumentHash(); @Override List<T> getStreamElements(); @Override List<T> getStreamElements(VariantSpan variantSpan); @Override List<VariantSpan> getVariantSpans(InvariantSpan targetSpan); @Override T index(long characterPosition); @Override void move(long to, VariantSpan v1); @Override void put(long characterPosition, T val); @Override void rebalance(); void save(OutputStream os); @Override void swap(VariantSpan v1, VariantSpan v2); @Override void toggleOverlay(VariantSpan variantSpan, Overlay linkType); }### Answer: @Test public void put() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash, getA()); stream.put(12, new InvariantSpan(500, 34, documentHash)); List<InvariantSpan> spans = stream.getStreamElements(); assertEquals(new InvariantSpan(100, 6, documentHash), spans.get(0)); assertEquals(new InvariantSpan(200, 3, documentHash), spans.get(1)); assertEquals(new InvariantSpan(250, 2, documentHash), spans.get(2)); assertEquals(new InvariantSpan(500, 34, documentHash), spans.get(3)); assertEquals(new InvariantSpan(300, 4, documentHash), spans.get(4)); assertEquals(new InvariantSpan(350, 1, documentHash), spans.get(5)); assertEquals(new InvariantSpan(360, 6, documentHash), spans.get(6)); }
### Question: RopeVariantStream implements VariantStream<T> { @Override public void swap(VariantSpan v1, VariantSpan v2) throws MalformedSpanException { Node<T> from = deleteRange(v1); from.parent = null; long startV2 = v2.start - v1.width; Node<T> to = deleteRange(new VariantSpan(startV2, v2.width)); to.parent = null; insert(v1.start, to); insert(v2.start, from); } RopeVariantStream(String documentHash); RopeVariantStream(String documentHash, Node<T> root); @Override void copy(long characterPosition, VariantSpan variantSpan); @Override void delete(VariantSpan variantSpan); @Override String getDocumentHash(); @Override List<T> getStreamElements(); @Override List<T> getStreamElements(VariantSpan variantSpan); @Override List<VariantSpan> getVariantSpans(InvariantSpan targetSpan); @Override T index(long characterPosition); @Override void move(long to, VariantSpan v1); @Override void put(long characterPosition, T val); @Override void rebalance(); void save(OutputStream os); @Override void swap(VariantSpan v1, VariantSpan v2); @Override void toggleOverlay(VariantSpan variantSpan, Overlay linkType); }### Answer: @Test public void swap() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash, getA()); stream.swap(new VariantSpan(1, 3), new VariantSpan(12, 3)); List<InvariantSpan> spans = stream.getStreamElements(); assertEquals(new InvariantSpan(300, 3, documentHash), spans.get(0)); assertEquals(new InvariantSpan(103, 3, documentHash), spans.get(1)); assertEquals(new InvariantSpan(200, 3, documentHash), spans.get(2)); assertEquals(new InvariantSpan(250, 2, documentHash), spans.get(3)); assertEquals(new InvariantSpan(100, 3, documentHash), spans.get(4)); assertEquals(new InvariantSpan(303, 1, documentHash), spans.get(5)); assertEquals(new InvariantSpan(350, 1, documentHash), spans.get(6)); assertEquals(new InvariantSpan(360, 6, documentHash), spans.get(7)); assertEquals(8, spans.size()); }
### Question: SlotKeySerDes { protected static Granularity granularityFromSlotKey(String s) { String field = s.split(",", -1)[0]; for (Granularity g : Granularity.granularities()) if (g.name().startsWith(field)) return g; return null; } static SlotKey deserialize(String stateStr); String serialize(SlotKey slotKey); String serialize(Granularity gran, int slot, int shard); }### Answer: @Test public void testGranularityFromSlotKey() { Granularity expected = Granularity.MIN_5; Granularity myGranularity = SlotKeySerDes.granularityFromSlotKey(SlotKey.of(expected, 1, 1).toString()); Assert.assertNotNull(myGranularity); Assert.assertEquals(myGranularity, expected); myGranularity = SlotKeySerDes.granularityFromSlotKey("FULL"); Assert.assertNull(myGranularity); }
### Question: Emitter { public Emitter once(final String event, final Listener<T> fn) { Listener on = new Listener<T>() { @Override public void call(T... args) { Emitter.this.off(event, this); fn.call(args); } }; this.onceCallbacks.put(fn, on); this.on(event, on); return this; } Emitter on(String event, Listener fn); Emitter once(final String event, final Listener<T> fn); Emitter off(); Emitter off(String event); Emitter off(String event, Listener fn); Future emit(String event, T... args); List<Listener> listeners(String event); boolean hasListeners(String event); }### Answer: @Test public void testOnce() { emitter.once(testEventName, listener); emitter.emit(testEventName, new RollupEvent(null, null, "payload1", "gran", 0)); Assert.assertEquals(store.size(), 1); store.clear(); emitter.emit(testEventName, new RollupEvent(null, null, "payload1", "gran", 0)); Assert.assertEquals(store.size(), 0); }
### Question: Emitter { public Emitter on(String event, Listener fn) { ConcurrentLinkedQueue<Listener> callbacks = this.callbacks.get(event); if (callbacks == null) { callbacks = new ConcurrentLinkedQueue<Listener>(); ConcurrentLinkedQueue<Listener> _callbacks = this.callbacks.putIfAbsent(event, callbacks); if (_callbacks != null) { callbacks = _callbacks; } } callbacks.add(fn); return this; } Emitter on(String event, Listener fn); Emitter once(final String event, final Listener<T> fn); Emitter off(); Emitter off(String event); Emitter off(String event, Listener fn); Future emit(String event, T... args); List<Listener> listeners(String event); boolean hasListeners(String event); }### Answer: @Test public void testOn() { emitter.on(testEventName, listener); Assert.assertEquals(0, store.size()); emitter.emit(testEventName, event1); Assert.assertEquals(1, store.size()); Assert.assertSame(event1, store.get(0)); emitter.emit(testEventName, event2); Assert.assertEquals(2, store.size()); Assert.assertSame(event1, store.get(0)); Assert.assertSame(event2, store.get(1)); }
### Question: RollupEvent { public Locator getLocator() { return locator; } RollupEvent(Locator loc, Rollup rollup, String unit, String gran, long ts); Rollup getRollup(); Locator getLocator(); String getUnit(); String getGranularityName(); long getTimestamp(); void setUnit(String unit); }### Answer: @Test public void locatorGetsSetInConstructor() { Assert.assertSame(locator, event.getLocator()); }
### Question: RollupEvent { public Rollup getRollup() { return rollup; } RollupEvent(Locator loc, Rollup rollup, String unit, String gran, long ts); Rollup getRollup(); Locator getLocator(); String getUnit(); String getGranularityName(); long getTimestamp(); void setUnit(String unit); }### Answer: @Test public void rollupGetsSetInConstructor() { Assert.assertSame(rollup, event.getRollup()); }
### Question: RollupEvent { public String getUnit() { return unit; } RollupEvent(Locator loc, Rollup rollup, String unit, String gran, long ts); Rollup getRollup(); Locator getLocator(); String getUnit(); String getGranularityName(); long getTimestamp(); void setUnit(String unit); }### Answer: @Test public void unitGetsSetInConstructor() { Assert.assertEquals(unit, event.getUnit()); }
### Question: RollupEvent { public String getGranularityName() { return granularityName; } RollupEvent(Locator loc, Rollup rollup, String unit, String gran, long ts); Rollup getRollup(); Locator getLocator(); String getUnit(); String getGranularityName(); long getTimestamp(); void setUnit(String unit); }### Answer: @Test public void granularityGetsSetInConstructor() { Assert.assertEquals(granularity, event.getGranularityName()); }
### Question: RetryNTimes implements RetryPolicy { @Override public RetryDecision onWriteTimeout(Statement stmnt, ConsistencyLevel cl, WriteType wt, int requiredResponses, int receivedResponses, int wTime) { if (wTime < writeAttempts) { LOG.info(String.format("Retrying on WriteTimeout: stmnt %s, " + "consistency %s, writeType %s, requiredResponse %d, " + "receivedResponse %d, rTime %d", stmnt, cl, wt.toString(), requiredResponses, receivedResponses, wTime)); return RetryDecision.retry(cl); } return RetryDecision.rethrow(); } RetryNTimes(int readAttempts, int writeAttempts, int unavailableAttempts); @Override RetryDecision onReadTimeout(Statement stmnt, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataReceived, int rTime); @Override RetryDecision onWriteTimeout(Statement stmnt, ConsistencyLevel cl, WriteType wt, int requiredResponses, int receivedResponses, int wTime); @Override RetryDecision onUnavailable(Statement stmnt, ConsistencyLevel cl, int requiredResponses, int receivedResponses, int uTime); @Override RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry); @Override void init(Cluster cluster); @Override void close(); }### Answer: @Test public void firstTimeRetryOnWriteTimeout_shouldRetry() throws Exception { RetryNTimes retryPolicy = new RetryNTimes(3, 3, 3); Statement mockStatement = mock( Statement.class ); RetryPolicy.RetryDecision retryResult = retryPolicy.onWriteTimeout(mockStatement, ConsistencyLevel.LOCAL_ONE, WriteType.BATCH, 1, 0, 0); RetryPolicy.RetryDecision retryExpected = RetryPolicy.RetryDecision.retry(ConsistencyLevel.LOCAL_ONE); assertRetryDecisionEquals(retryExpected, retryResult); } @Test public void maxTimeRetryOnWriteTimeout_shouldRethrow() throws Exception { RetryNTimes retryPolicy = new RetryNTimes(3, 3, 3); Statement mockStatement = mock( Statement.class ); RetryPolicy.RetryDecision retryResult = retryPolicy.onWriteTimeout(mockStatement, ConsistencyLevel.LOCAL_ONE, WriteType.BATCH, 1, 0, 3); RetryPolicy.RetryDecision retryExpected = RetryPolicy.RetryDecision.rethrow(); assertRetryDecisionEquals(retryExpected, retryResult); }
### Question: RollupEvent { public long getTimestamp() { return timestamp; } RollupEvent(Locator loc, Rollup rollup, String unit, String gran, long ts); Rollup getRollup(); Locator getLocator(); String getUnit(); String getGranularityName(); long getTimestamp(); void setUnit(String unit); }### Answer: @Test public void timestampGetsSetInConstructor() { Assert.assertEquals(timestamp, event.getTimestamp()); }
### Question: Granularity { public Granularity coarser() throws GranularityException { if (this == LAST) throw new GranularityException("Nothing coarser than " + name()); return granularities[index + 1]; } private Granularity(String cf, int milliseconds, int numSlots, String shortName); String name(); String shortName(); int milliseconds(); int numSlots(); Granularity coarser(); Granularity finer(); boolean isCoarser(Granularity other); long snapMillis(long millis); int slot(long millis); int slotFromFinerSlot(int finerSlot); Range deriveRange(int slot, long referenceMillis); static Granularity granularityFromPointsInInterval(String tenantid, long from, long to, int points); static Granularity granularityFromPointsInInterval(String tenantid, long from, long to, int points, String algorithm, long assumedIntervalMillis); static Granularity granularityFromPointsInInterval(String tenantid, long from, long to, int points, String algorithm, long assumedIntervalMillis, Clock ttlComparisonClock); @Override int hashCode(); @Override boolean equals(Object obj); static Granularity[] granularities(); static Granularity[] rollupGranularities(); static Granularity fromString(String s); static Granularity getRollupGranularity(String s); @Override String toString(); static final int MILLISECONDS_IN_SLOT; static final Granularity FULL; static final Granularity MIN_5; static final Granularity MIN_20; static final Granularity MIN_60; static final Granularity MIN_240; static final Granularity MIN_1440; static final Granularity LAST; static final int MAX_NUM_SLOTS; }### Answer: @Test public void coarserReturnsCoarser() throws GranularityException { Assert.assertSame(Granularity.MIN_5, Granularity.FULL.coarser()); Assert.assertSame(Granularity.MIN_20, Granularity.MIN_5.coarser()); Assert.assertSame(Granularity.MIN_60, Granularity.MIN_20.coarser()); Assert.assertSame(Granularity.MIN_240, Granularity.MIN_60.coarser()); Assert.assertSame(Granularity.MIN_1440, Granularity.MIN_240.coarser()); } @Test(expected = GranularityException.class) public void testTooCoarse() throws Exception { Granularity.MIN_1440.coarser(); }
### Question: Granularity { public Granularity finer() throws GranularityException { if (this == FULL) throw new GranularityException("Nothing finer than " + name()); return granularities[index - 1]; } private Granularity(String cf, int milliseconds, int numSlots, String shortName); String name(); String shortName(); int milliseconds(); int numSlots(); Granularity coarser(); Granularity finer(); boolean isCoarser(Granularity other); long snapMillis(long millis); int slot(long millis); int slotFromFinerSlot(int finerSlot); Range deriveRange(int slot, long referenceMillis); static Granularity granularityFromPointsInInterval(String tenantid, long from, long to, int points); static Granularity granularityFromPointsInInterval(String tenantid, long from, long to, int points, String algorithm, long assumedIntervalMillis); static Granularity granularityFromPointsInInterval(String tenantid, long from, long to, int points, String algorithm, long assumedIntervalMillis, Clock ttlComparisonClock); @Override int hashCode(); @Override boolean equals(Object obj); static Granularity[] granularities(); static Granularity[] rollupGranularities(); static Granularity fromString(String s); static Granularity getRollupGranularity(String s); @Override String toString(); static final int MILLISECONDS_IN_SLOT; static final Granularity FULL; static final Granularity MIN_5; static final Granularity MIN_20; static final Granularity MIN_60; static final Granularity MIN_240; static final Granularity MIN_1440; static final Granularity LAST; static final int MAX_NUM_SLOTS; }### Answer: @Test public void finerReturnsFiner() throws GranularityException { Assert.assertSame(Granularity.FULL, Granularity.MIN_5.finer()); Assert.assertSame(Granularity.MIN_5, Granularity.MIN_20.finer()); Assert.assertSame(Granularity.MIN_20, Granularity.MIN_60.finer()); Assert.assertSame(Granularity.MIN_60, Granularity.MIN_240.finer()); Assert.assertSame(Granularity.MIN_240, Granularity.MIN_1440.finer()); } @Test(expected = GranularityException.class) public void testTooFine() throws Exception { Granularity.FULL.finer(); }
### Question: RetryNTimes implements RetryPolicy { @Override public RetryDecision onUnavailable(Statement stmnt, ConsistencyLevel cl, int requiredResponses, int receivedResponses, int uTime) { if (uTime < unavailableAttempts) { LOG.info(String.format("Retrying on unavailable: stmnt %s, consistency %s, " + "requiredResponse %d, receivedResponse %d, rTime %d", stmnt, cl, requiredResponses, receivedResponses, uTime)); return RetryDecision.retry(ConsistencyLevel.ONE); } return RetryDecision.rethrow(); } RetryNTimes(int readAttempts, int writeAttempts, int unavailableAttempts); @Override RetryDecision onReadTimeout(Statement stmnt, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataReceived, int rTime); @Override RetryDecision onWriteTimeout(Statement stmnt, ConsistencyLevel cl, WriteType wt, int requiredResponses, int receivedResponses, int wTime); @Override RetryDecision onUnavailable(Statement stmnt, ConsistencyLevel cl, int requiredResponses, int receivedResponses, int uTime); @Override RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry); @Override void init(Cluster cluster); @Override void close(); }### Answer: @Test public void firstTimeRetryOnUnavailable_shouldRetry() throws Exception { RetryNTimes retryPolicy = new RetryNTimes(3, 3, 3); Statement mockStatement = mock( Statement.class ); RetryPolicy.RetryDecision retryResult = retryPolicy.onUnavailable(mockStatement, ConsistencyLevel.LOCAL_ONE, 1, 0, 0); RetryPolicy.RetryDecision retryExpected = RetryPolicy.RetryDecision.retry(ConsistencyLevel.ONE); assertRetryDecisionEquals(retryExpected, retryResult); } @Test public void maxTimeRetryOnUnavailable_shouldRethrow() throws Exception { RetryNTimes retryPolicy = new RetryNTimes(3, 3, 3); Statement mockStatement = mock( Statement.class ); RetryPolicy.RetryDecision retryResult = retryPolicy.onUnavailable(mockStatement, ConsistencyLevel.LOCAL_ONE, 1, 0, 3); RetryPolicy.RetryDecision retryExpected = RetryPolicy.RetryDecision.rethrow(); assertRetryDecisionEquals(retryExpected, retryResult); }
### Question: RollupTypeCacher extends FunctionWithThreadPool<MetricsCollection, Void> { @Override public Void apply(final MetricsCollection input) throws Exception { getThreadPool().submit(new Runnable() { @Override public void run() { recordWithTimer(input); } }); return null; } RollupTypeCacher(ThreadPoolExecutor executor, MetadataCache cache); @Override Void apply(final MetricsCollection input); }### Answer: @Test public void testCacher() throws Exception { MetricsCollection collection = createTestData(); MetadataCache rollupTypeCache = mock(MetadataCache.class); ThreadPoolExecutor tpe = new ThreadPoolBuilder().withName("rtc test").build(); RollupTypeCacher rollupTypeCacher = new RollupTypeCacher(tpe, rollupTypeCache); rollupTypeCacher.apply(collection); while (tpe.getCompletedTaskCount() < 1) { Thread.sleep(1); } verifyZeroInteractions(rollupTypeCache); } @Test public void testCacherDoesCacheRollupTypeForPreAggregatedMetrics() throws Exception { MetricsCollection collection = createPreaggregatedTestMetrics(); MetadataCache rollupTypeCache = mock(MetadataCache.class); ThreadPoolExecutor tpe = new ThreadPoolBuilder().withName("rtc test").build(); RollupTypeCacher rollupTypeCacher = new RollupTypeCacher(tpe, rollupTypeCache); rollupTypeCacher.apply(collection); while (tpe.getCompletedTaskCount() < 1) { Thread.sleep(1); } for (IMetric m : collection.toMetrics()) { verify(rollupTypeCache).put(m.getLocator(), cacheKey, m.getRollupType().toString()); } }
### Question: TypeAndUnitProcessor extends FunctionWithThreadPool<MetricsCollection, Void> { @Override public Void apply(final MetricsCollection input) throws Exception { getThreadPool().submit(new Callable<MetricsCollection>() { public MetricsCollection call() throws Exception { Collection<IncomingMetricException> problems = metricMetadataAnalyzer.scanMetrics(input.toMetrics()); for (IncomingMetricException problem : problems) getLogger().warn(problem.getMessage()); return input; } }); return null; } TypeAndUnitProcessor(ThreadPoolExecutor threadPool, IncomingMetricMetadataAnalyzer metricMetadataAnalyzer); @Override Void apply(final MetricsCollection input); }### Answer: @Test public void test() throws Exception { MetricsCollection collection = createTestData(); IncomingMetricMetadataAnalyzer metricMetadataAnalyzer = mock(IncomingMetricMetadataAnalyzer.class); ThreadPoolExecutor tpe = new ThreadPoolBuilder().withName("rtc test").build(); TypeAndUnitProcessor typeAndUnitProcessor = new TypeAndUnitProcessor( tpe, metricMetadataAnalyzer); typeAndUnitProcessor.apply(collection); while (tpe.getCompletedTaskCount() < 1) { Thread.sleep(1); } verify(metricMetadataAnalyzer).scanMetrics(collection.toMetrics()); }
### Question: RollupService implements Runnable, RollupServiceMBean { final void poll() { Timer.Context timer = polltimer.time(); context.scheduleEligibleSlots(rollupDelayMillis, rollupDelayForMetricsWithShortDelay, rollupWaitForMetricsWithLongDelay); timer.stop(); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void pollSchedulesEligibleSlots() { service.poll(); verify(context).scheduleEligibleSlots(anyLong(), anyLong(), anyLong()); verifyNoMoreInteractions(context); verifyZeroInteractions(shardStateManager); verifyZeroInteractions(locatorFetchExecutors); verifyZeroInteractions(rollupReadExecutors); verifyZeroInteractions(rollupWriteExecutors); }
### Question: RollupService implements Runnable, RollupServiceMBean { public synchronized void setServerTime(long millis) { log.info("Manually setting server time to {} {}", millis, new java.util.Date(millis)); context.setCurrentTimeMillis(millis); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void setServerTimeSetsContextTime() { service.setServerTime(1234L); verify(context).setCurrentTimeMillis(anyLong()); verifyNoMoreInteractions(context); verifyZeroInteractions(shardStateManager); verifyZeroInteractions(locatorFetchExecutors); verifyZeroInteractions(rollupReadExecutors); verifyZeroInteractions(rollupWriteExecutors); }
### Question: SlotKeySerDes { protected static int slotFromSlotKey(String s) { return Integer.parseInt(s.split(",", -1)[1]); } static SlotKey deserialize(String stateStr); String serialize(SlotKey slotKey); String serialize(Granularity gran, int slot, int shard); }### Answer: @Test public void testSlotFromSlotKey() { int expectedSlot = 1; int slot = SlotKeySerDes.slotFromSlotKey(SlotKey.of(Granularity.MIN_5, expectedSlot, 10).toString()); Assert.assertEquals(expectedSlot, slot); }
### Question: GlobPattern { public Pattern compiled() { return compiled; } GlobPattern(String globPattern); Pattern compiled(); static Pattern compile(String globPattern); boolean matches(CharSequence s); void set(String glob); boolean hasWildcard(); }### Answer: @Test public void testGlobMatchingAnyChar() { String glob = "*"; String expectedRegex = ".*"; GlobPattern pattern = new GlobPattern(glob); Assert.assertEquals(expectedRegex, pattern.compiled().toString()); } @Test public void testEmptyGlob() { String glob = ""; String expectedRegex = ""; GlobPattern pattern = new GlobPattern(glob); Assert.assertEquals(expectedRegex, pattern.compiled().toString()); } @Test public void testGlobWithWildcards1() { String glob = "foo.bar$1.(cat).baz|qux.dog+"; String expectedRegex = "foo\\.bar\\$1\\.\\(cat\\)\\.baz\\|qux\\.dog\\+"; GlobPattern pattern = new GlobPattern(glob); Assert.assertEquals(expectedRegex, pattern.compiled().toString()); } @Test public void testMetricNameGlob() { String glob = "foo.bar.*"; String expectedRegex = "foo\\.bar\\..*"; GlobPattern pattern = new GlobPattern(glob); Assert.assertEquals(expectedRegex, pattern.compiled().toString()); } @Test public void testMetricNameGlobWithWildCards() { String glob = "f*.bar.*"; String expectedRegex = "f.*\\.bar\\..*"; GlobPattern pattern = new GlobPattern(glob); Assert.assertEquals(expectedRegex, pattern.compiled().toString()); } @Test public void testMetricNameWithMatchingSingleChar() { String glob = "foo?"; String expectedRegex = "foo."; GlobPattern pattern = new GlobPattern(glob); Assert.assertEquals(expectedRegex, pattern.compiled().toString()); } @Test public void testMetricNameWithMatchingAnyChar() { String glob = "foo*"; String expectedRegex = "foo.*"; GlobPattern pattern = new GlobPattern(glob); Assert.assertEquals(expectedRegex, pattern.compiled().toString()); } @Test public void testMetricNameWithGlobSyntax() { String glob = "foo.{*}"; String expectedRegex = "foo\\.(.*)"; GlobPattern pattern = new GlobPattern(glob); Assert.assertEquals(expectedRegex, pattern.compiled().toString()); } @Test public void testVariousGlobSyntax2() { String glob = "[!abc]oo.*]"; String expectedRegex = "[^abc]oo\\..*]"; GlobPattern pattern = new GlobPattern(glob); Assert.assertEquals(expectedRegex, pattern.compiled().toString()); } @Test public void testMetricNameWithVariousGlobSyntax() { String glob = "foo.[bz]*.*"; String expectedRegex = "foo\\.[bz].*\\..*"; GlobPattern pattern = new GlobPattern(glob); Assert.assertEquals(expectedRegex, pattern.compiled().toString()); } @Test public void testMetricNameGlobWithoutWildCard() { String glob = "foo.bar"; String expectedRegex = "foo\\.bar"; GlobPattern pattern = new GlobPattern(glob); Assert.assertEquals(expectedRegex, pattern.compiled().toString()); }
### Question: RollupService implements Runnable, RollupServiceMBean { public synchronized long getServerTime() { return context.getCurrentTimeMillis(); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void getServerTimeGetsContextTime() { long expected = 1234L; doReturn(expected).when(context).getCurrentTimeMillis(); long actual = service.getServerTime(); assertEquals(expected, actual); verify(context).getCurrentTimeMillis(); verifyNoMoreInteractions(context); verifyZeroInteractions(shardStateManager); verifyZeroInteractions(locatorFetchExecutors); verifyZeroInteractions(rollupReadExecutors); verifyZeroInteractions(rollupWriteExecutors); }
### Question: SafetyTtlProvider implements TenantTtlProvider { @Override public Optional<TimeValue> getTTL(String tenantId, Granularity gran, RollupType rollupType) { return getSafeTTL(gran, rollupType); } SafetyTtlProvider(); @Override Optional<TimeValue> getTTL(String tenantId, Granularity gran, RollupType rollupType); Optional<TimeValue> getSafeTTL(Granularity gran, RollupType rollupType); }### Answer: @Test public void testAlwaysPresent() { Assert.assertTrue(ttlProvider.getTTL("test", Granularity.FULL, RollupType.NOT_A_ROLLUP).isPresent()); }
### Question: LocatorCache { public synchronized void setLocatorCurrentInBatchLayer(Locator loc) { getOrCreateInsertedLocatorEntry(loc).setBatchCurrent(); } protected LocatorCache(long expireAfterAccessDuration, TimeUnit expireAfterAccessTimeUnit, long expireAfterWriteDuration, TimeUnit expireAfterWriteTimeUnit); static LocatorCache getInstance(); @VisibleForTesting static LocatorCache getInstance(long expireAfterAccessDuration, TimeUnit expireAfterAccessTimeUnit, long expireAfterWriteDuration, TimeUnit expireAfterWriteTimeUnit); long getCurrentLocatorCount(); long getCurrentDelayedLocatorCount(); synchronized boolean isLocatorCurrentInBatchLayer(Locator loc); synchronized boolean isLocatorCurrentInDiscoveryLayer(Locator loc); synchronized boolean isLocatorCurrentInTokenDiscoveryLayer(Locator loc); synchronized boolean isDelayedLocatorForASlotCurrent(int slot, Locator locator); synchronized void setLocatorCurrentInBatchLayer(Locator loc); synchronized void setLocatorCurrentInDiscoveryLayer(Locator loc); synchronized void setLocatorCurrentInTokenDiscoveryLayer(Locator loc); synchronized void setDelayedLocatorForASlotCurrent(int slot, Locator locator); @VisibleForTesting synchronized void resetCache(); @VisibleForTesting synchronized void resetInsertedLocatorsCache(); }### Answer: @Test public void testSetLocatorCurrentInBatchLayer() throws InterruptedException { locatorCache.setLocatorCurrentInBatchLayer(LOCATOR); assertTrue("locator not stored in cache", locatorCache.isLocatorCurrentInBatchLayer(LOCATOR)); Thread.sleep(2000L); assertTrue("locator not expired from cache", !locatorCache.isLocatorCurrentInBatchLayer(LOCATOR)); }
### Question: LocatorCache { public synchronized boolean isLocatorCurrentInBatchLayer(Locator loc) { LocatorCacheEntry entry = insertedLocators.getIfPresent(loc.toString()); return entry != null && entry.isBatchCurrent(); } protected LocatorCache(long expireAfterAccessDuration, TimeUnit expireAfterAccessTimeUnit, long expireAfterWriteDuration, TimeUnit expireAfterWriteTimeUnit); static LocatorCache getInstance(); @VisibleForTesting static LocatorCache getInstance(long expireAfterAccessDuration, TimeUnit expireAfterAccessTimeUnit, long expireAfterWriteDuration, TimeUnit expireAfterWriteTimeUnit); long getCurrentLocatorCount(); long getCurrentDelayedLocatorCount(); synchronized boolean isLocatorCurrentInBatchLayer(Locator loc); synchronized boolean isLocatorCurrentInDiscoveryLayer(Locator loc); synchronized boolean isLocatorCurrentInTokenDiscoveryLayer(Locator loc); synchronized boolean isDelayedLocatorForASlotCurrent(int slot, Locator locator); synchronized void setLocatorCurrentInBatchLayer(Locator loc); synchronized void setLocatorCurrentInDiscoveryLayer(Locator loc); synchronized void setLocatorCurrentInTokenDiscoveryLayer(Locator loc); synchronized void setDelayedLocatorForASlotCurrent(int slot, Locator locator); @VisibleForTesting synchronized void resetCache(); @VisibleForTesting synchronized void resetInsertedLocatorsCache(); }### Answer: @Test public void testIsLocatorCurrentInBatchLayer() throws InterruptedException { assertTrue("locator which was never set is present in cache", !locatorCache.isLocatorCurrentInBatchLayer(LOCATOR)); locatorCache.setLocatorCurrentInBatchLayer(LOCATOR); assertTrue("locator not stored in cache", locatorCache.isLocatorCurrentInBatchLayer(LOCATOR)); }
### Question: LocatorCache { public synchronized void setLocatorCurrentInDiscoveryLayer(Locator loc) { getOrCreateInsertedLocatorEntry(loc).setDiscoveryCurrent(); } protected LocatorCache(long expireAfterAccessDuration, TimeUnit expireAfterAccessTimeUnit, long expireAfterWriteDuration, TimeUnit expireAfterWriteTimeUnit); static LocatorCache getInstance(); @VisibleForTesting static LocatorCache getInstance(long expireAfterAccessDuration, TimeUnit expireAfterAccessTimeUnit, long expireAfterWriteDuration, TimeUnit expireAfterWriteTimeUnit); long getCurrentLocatorCount(); long getCurrentDelayedLocatorCount(); synchronized boolean isLocatorCurrentInBatchLayer(Locator loc); synchronized boolean isLocatorCurrentInDiscoveryLayer(Locator loc); synchronized boolean isLocatorCurrentInTokenDiscoveryLayer(Locator loc); synchronized boolean isDelayedLocatorForASlotCurrent(int slot, Locator locator); synchronized void setLocatorCurrentInBatchLayer(Locator loc); synchronized void setLocatorCurrentInDiscoveryLayer(Locator loc); synchronized void setLocatorCurrentInTokenDiscoveryLayer(Locator loc); synchronized void setDelayedLocatorForASlotCurrent(int slot, Locator locator); @VisibleForTesting synchronized void resetCache(); @VisibleForTesting synchronized void resetInsertedLocatorsCache(); }### Answer: @Test public void testSetLocatorCurrentInDiscoveryLayer() throws InterruptedException { locatorCache.setLocatorCurrentInDiscoveryLayer(LOCATOR); assertTrue("locator not stored in cache", locatorCache.isLocatorCurrentInDiscoveryLayer(LOCATOR)); Thread.sleep(2000L); assertTrue("locator not expired from cache", !locatorCache.isLocatorCurrentInDiscoveryLayer(LOCATOR)); }
### Question: LocatorCache { public synchronized boolean isLocatorCurrentInDiscoveryLayer(Locator loc) { LocatorCacheEntry entry = insertedLocators.getIfPresent(loc.toString()); return entry != null && entry.isDiscoveryCurrent(); } protected LocatorCache(long expireAfterAccessDuration, TimeUnit expireAfterAccessTimeUnit, long expireAfterWriteDuration, TimeUnit expireAfterWriteTimeUnit); static LocatorCache getInstance(); @VisibleForTesting static LocatorCache getInstance(long expireAfterAccessDuration, TimeUnit expireAfterAccessTimeUnit, long expireAfterWriteDuration, TimeUnit expireAfterWriteTimeUnit); long getCurrentLocatorCount(); long getCurrentDelayedLocatorCount(); synchronized boolean isLocatorCurrentInBatchLayer(Locator loc); synchronized boolean isLocatorCurrentInDiscoveryLayer(Locator loc); synchronized boolean isLocatorCurrentInTokenDiscoveryLayer(Locator loc); synchronized boolean isDelayedLocatorForASlotCurrent(int slot, Locator locator); synchronized void setLocatorCurrentInBatchLayer(Locator loc); synchronized void setLocatorCurrentInDiscoveryLayer(Locator loc); synchronized void setLocatorCurrentInTokenDiscoveryLayer(Locator loc); synchronized void setDelayedLocatorForASlotCurrent(int slot, Locator locator); @VisibleForTesting synchronized void resetCache(); @VisibleForTesting synchronized void resetInsertedLocatorsCache(); }### Answer: @Test public void testIsLocatorCurrentInDiscoveryLayer() throws InterruptedException { assertTrue("locator which was never set is present in cache", !locatorCache.isLocatorCurrentInDiscoveryLayer(LOCATOR)); locatorCache.setLocatorCurrentInDiscoveryLayer(LOCATOR); assertTrue("locator not stored in cache", locatorCache.isLocatorCurrentInDiscoveryLayer(LOCATOR)); }
### Question: RollupService implements Runnable, RollupServiceMBean { public synchronized boolean getKeepingServerTime() { return keepingServerTime; } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void getKeepingServerTimeGetsKeepingServerTime() { assertEquals(true, service.getKeepingServerTime()); }
### Question: ConfigTtlProvider implements TenantTtlProvider { @Override public Optional<TimeValue> getTTL(String tenantId, Granularity gran, RollupType rollupType) { final TimeValue ttl = ttlMapper.get(gran, rollupType); if (ttl == null) { log.trace("No valid TTL entry for granularity: {}, rollup type: {}" + " in config. Resorting to safe TTL values.", gran.name(), rollupType.name()); return Optional.absent(); } return Optional.of(ttl); } @VisibleForTesting ConfigTtlProvider(); static ConfigTtlProvider getInstance(); @Override Optional<TimeValue> getTTL(String tenantId, Granularity gran, RollupType rollupType); TimeValue getConfigTTLForIngestion(); boolean areTTLsForced(); }### Answer: @Test public void testConfigTtl_invalid() { Assert.assertFalse(ttlProvider.getTTL("acBar", Granularity.FULL, RollupType.SET).isPresent()); }
### Question: CombinedTtlProvider implements TenantTtlProvider { @Override public Optional<TimeValue> getTTL(String tenantId, Granularity gran, RollupType rollupType) { Optional<TimeValue> primaryValue = primary.getTTL(tenantId, gran, rollupType); Optional<TimeValue> safetyValue = safety.getTTL(tenantId, gran, rollupType); return getTimeValue(primaryValue, safetyValue); } @VisibleForTesting CombinedTtlProvider(ConfigTtlProvider primary, SafetyTtlProvider safety); static CombinedTtlProvider getInstance(); @Override Optional<TimeValue> getTTL(String tenantId, Granularity gran, RollupType rollupType); long getFinalTTL(String tenantid, Granularity gran); }### Answer: @Test public void testGetTTL() throws Exception { assertTrue(combinedProvider.getTTL("foo", Granularity.FULL, RollupType.BF_BASIC).isPresent()); assertTrue(combinedProvider.getTTL("foo", Granularity.MIN_5, RollupType.BF_BASIC).isPresent()); assertFalse(configProvider.getTTL("foo", Granularity.MIN_5, RollupType.BF_BASIC).isPresent()); assertEquals(combinedProvider.getTTL("foo", Granularity.MIN_5, RollupType.BF_BASIC).get(), SafetyTtlProvider.getInstance().getTTL("foo", Granularity.MIN_5, RollupType.BF_BASIC).get()); }
### Question: Metric implements IMetric { public void setTtl(TimeValue ttl) { if (!isValidTTL(ttl.toSeconds())) { throw new InvalidDataException("TTL supplied for metric is invalid. Required: 0 < ttl < " + Integer.MAX_VALUE + ", provided: " + ttl.toSeconds()); } ttlInSeconds = (int) ttl.toSeconds(); } Metric(Locator locator, Object metricValue, long collectionTime, TimeValue ttl, String unit); Locator getLocator(); Object getMetricValue(); int getTtlInSeconds(); long getCollectionTime(); String getUnit(); void setTtl(TimeValue ttl); void setTtlInSeconds(int ttlInSeconds); RollupType getRollupType(); @Override String toString(); @Override boolean equals(Object o); }### Answer: @Test public void testTTL() { Locator locator = Locator.createLocatorFromPathComponents("tenantId", "metricName"); Metric metric = new Metric(locator, 134891734L, System.currentTimeMillis(), new TimeValue(5, TimeUnit.HOURS), "Unknown"); try { metric.setTtl(new TimeValue(Long.MAX_VALUE, TimeUnit.SECONDS)); fail(); } catch (Exception e) { Assert.assertTrue(e instanceof RuntimeException); } }
### Question: Locator implements Comparable<Locator> { public String toString() { return stringRep; } Locator(); private Locator(String fullyQualifiedMetricName); @Override int hashCode(); @Override boolean equals(Object obj); String toString(); String getTenantId(); String getMetricName(); boolean equals(Locator other); static Locator createLocatorFromPathComponents(String tenantId, String... parts); static Locator createLocatorFromDbKey(String fullyQualifiedMetricName); @Override int compareTo(Locator o); static final String METRIC_TOKEN_SEPARATOR; static final String METRIC_TOKEN_SEPARATOR_REGEX; }### Answer: @Test public void publicConstructorDoesNotSetStringRepresentation() { Locator locator = new Locator(); assertNotNull(locator); assertNull(locator.toString()); }
### Question: Locator implements Comparable<Locator> { public String getTenantId() { return this.tenantId; } Locator(); private Locator(String fullyQualifiedMetricName); @Override int hashCode(); @Override boolean equals(Object obj); String toString(); String getTenantId(); String getMetricName(); boolean equals(Locator other); static Locator createLocatorFromPathComponents(String tenantId, String... parts); static Locator createLocatorFromDbKey(String fullyQualifiedMetricName); @Override int compareTo(Locator o); static final String METRIC_TOKEN_SEPARATOR; static final String METRIC_TOKEN_SEPARATOR_REGEX; }### Answer: @Test public void publicConstructorDoesNotSetTenant() { Locator locator = new Locator(); assertNotNull(locator); assertNull(locator.getTenantId()); }
### Question: Locator implements Comparable<Locator> { public String getMetricName() { return this.metricName; } Locator(); private Locator(String fullyQualifiedMetricName); @Override int hashCode(); @Override boolean equals(Object obj); String toString(); String getTenantId(); String getMetricName(); boolean equals(Locator other); static Locator createLocatorFromPathComponents(String tenantId, String... parts); static Locator createLocatorFromDbKey(String fullyQualifiedMetricName); @Override int compareTo(Locator o); static final String METRIC_TOKEN_SEPARATOR; static final String METRIC_TOKEN_SEPARATOR_REGEX; }### Answer: @Test public void publicConstructorDoesNotSetMetricName() { Locator locator = new Locator(); assertNotNull(locator); assertNull(locator.getMetricName()); }
### Question: Locator implements Comparable<Locator> { protected boolean isValidDBKey(String dbKey, String delim) { return dbKey.contains(delim); } Locator(); private Locator(String fullyQualifiedMetricName); @Override int hashCode(); @Override boolean equals(Object obj); String toString(); String getTenantId(); String getMetricName(); boolean equals(Locator other); static Locator createLocatorFromPathComponents(String tenantId, String... parts); static Locator createLocatorFromDbKey(String fullyQualifiedMetricName); @Override int compareTo(Locator o); static final String METRIC_TOKEN_SEPARATOR; static final String METRIC_TOKEN_SEPARATOR_REGEX; }### Answer: @Test(expected = NullPointerException.class) public void isValidDBKeyThrowsExceptionOnNullDbKey() { Locator locator = new Locator(); locator.isValidDBKey(null, "a"); } @Test(expected = NullPointerException.class) public void isValidDBKeyThrowsExceptionOnNullDelim() { Locator locator = new Locator(); locator.isValidDBKey("a.b.c", null); } @Test public void isValidDBKeyUndelimitedStringReturnsFalse() { Locator locator = new Locator(); assertFalse(locator.isValidDBKey("abc", ".")); } @Test public void isValidDBKeyDelimiterIsNormalCharInDbKeyReturnsTrue() { Locator locator = new Locator(); assertTrue(locator.isValidDBKey("abc", "b")); } @Test public void isValidDBKeyDbKeyContainsDelimiterReturnsTrue() { Locator locator = new Locator(); assertTrue(locator.isValidDBKey("a.b.c", ".")); } @Test public void isValidDBKeyEmptyDbKeyReturnsFalse() { Locator locator = new Locator(); assertFalse(locator.isValidDBKey("", ".")); } @Test public void isValidDBKeyEmptyDelimiterReturnsTrue() { Locator locator = new Locator(); assertTrue(locator.isValidDBKey("a.b.c", "")); } @Test public void isValidDBKeyMultiCharDelimiterReturnsTrue() { Locator locator = new Locator(); assertTrue(locator.isValidDBKey("a.b.c", ".b.")); }
### Question: RollupService implements Runnable, RollupServiceMBean { public synchronized long getPollerPeriod() { return pollerPeriod; } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void getPollerPeriodGetsPollerPeriod() { assertEquals(0, service.getPollerPeriod()); }
### Question: Locator implements Comparable<Locator> { @Override public int hashCode() { return stringRep == null ? 0 : stringRep.hashCode(); } Locator(); private Locator(String fullyQualifiedMetricName); @Override int hashCode(); @Override boolean equals(Object obj); String toString(); String getTenantId(); String getMetricName(); boolean equals(Locator other); static Locator createLocatorFromPathComponents(String tenantId, String... parts); static Locator createLocatorFromDbKey(String fullyQualifiedMetricName); @Override int compareTo(Locator o); static final String METRIC_TOKEN_SEPARATOR; static final String METRIC_TOKEN_SEPARATOR_REGEX; }### Answer: @Test public void hashCodeNullReturnsZero() { Locator locator = new Locator(); assertEquals(0, locator.hashCode()); }
### Question: Locator implements Comparable<Locator> { @Override public boolean equals(Object obj) { return obj != null && obj instanceof Locator && obj.hashCode() == this.hashCode(); } Locator(); private Locator(String fullyQualifiedMetricName); @Override int hashCode(); @Override boolean equals(Object obj); String toString(); String getTenantId(); String getMetricName(); boolean equals(Locator other); static Locator createLocatorFromPathComponents(String tenantId, String... parts); static Locator createLocatorFromDbKey(String fullyQualifiedMetricName); @Override int compareTo(Locator o); static final String METRIC_TOKEN_SEPARATOR; static final String METRIC_TOKEN_SEPARATOR_REGEX; }### Answer: @Test public void equalsNullReturnsFalse() { Locator locator = new Locator(); assertFalse(locator.equals((Object)null)); } @Test public void equalsNonLocatorReturnsFalse() { Locator locator = new Locator(); assertFalse(locator.equals(new Object())); } @Test public void equalsBothUninitializedReturnsTrue() { Locator locator = new Locator(); Locator other = new Locator(); assertTrue(locator.equals((Object)other)); }
### Question: Points { public Class getDataClass() { if (points.size() == 0) throw new IllegalStateException(""); return points.values().iterator().next().data.getClass(); } Points(); void add(Point<T> point); Map<Long, Point<T>> getPoints(); boolean isEmpty(); Class getDataClass(); }### Answer: @Test(expected=IllegalStateException.class) public void getDataClassOnEmptyObjectThrowsException() { Points<SimpleNumber> points = new Points<SimpleNumber>(); Class actual = points.getDataClass(); }
### Question: AbstractRollupStat { public boolean isFloatingPoint() { return this.isFloatingPoint; } AbstractRollupStat(); boolean isFloatingPoint(); double toDouble(); long toLong(); @Override boolean equals(Object otherObject); void setLongValue(long value); void setDoubleValue(double value); abstract byte getStatType(); String toString(); static void set(AbstractRollupStat stat, Number value); }### Answer: @Test public void newlyCreatedObjectIsNotFloatingPoint() { SimpleStat stat = new SimpleStat(); assertFalse(stat.isFloatingPoint()); }
### Question: RollupService implements Runnable, RollupServiceMBean { public synchronized int getScheduledSlotCheckCount() { return context.getScheduledCount(); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void getScheduledSlotCheckCountGetsCount() { int expected = 3; doReturn(expected).when(context).getScheduledCount(); int actual = service.getScheduledSlotCheckCount(); assertEquals(expected, actual); verify(context).getScheduledCount(); verifyNoMoreInteractions(context); }
### Question: AbstractRollupStat { @Override public boolean equals(Object otherObject) { if (!(otherObject instanceof AbstractRollupStat)) { return false; } AbstractRollupStat other = (AbstractRollupStat)otherObject; if (this.isFloatingPoint != other.isFloatingPoint()) { return false; } if (this.isFloatingPoint) { return this.toDouble() == other.toDouble(); } else { return this.toLong() == other.toLong(); } } AbstractRollupStat(); boolean isFloatingPoint(); double toDouble(); long toLong(); @Override boolean equals(Object otherObject); void setLongValue(long value); void setDoubleValue(double value); abstract byte getStatType(); String toString(); static void set(AbstractRollupStat stat, Number value); }### Answer: @Test public void statsAreEqualIfTheirLongNumericalValuesAreEqual() { SimpleStat a = new SimpleStat(123L); SimpleStat b = new SimpleStat(123L); assertTrue(a.equals(b)); assertTrue(b.equals(a)); } @Test public void statsAreNotEqualIfTheirLongNumericalValuesAreNotEqual() { SimpleStat a = new SimpleStat(123L); SimpleStat b = new SimpleStat(124L); assertFalse(a.equals(b)); assertFalse(b.equals(a)); } @Test public void statsAreEqualIfTheirDoubleNumericalValuesAreEqual() { SimpleStat a = new SimpleStat(123.45d); SimpleStat b = new SimpleStat(123.45d); assertTrue(a.equals(b)); assertTrue(b.equals(a)); } @Test public void statsAreNotEqualIfTheirDoubleNumericalValuesAreNotEqual() { SimpleStat a = new SimpleStat(123.45d); SimpleStat b = new SimpleStat(123.7d); assertFalse(a.equals(b)); assertFalse(b.equals(a)); } @Test public void floatingPointAndNonFloatingPointAreNotEqual() { SimpleStat a = new SimpleStat(123L); SimpleStat b = new SimpleStat(123.45d); assertFalse(a.equals(b)); assertFalse(b.equals(a)); } @Test public void differentSubtypesAreEqualIfTheirLongNumericalValuesAreEqual() { MinValue min = new MinValue(123L); MaxValue max = new MaxValue(123L); assertTrue(min.equals(max)); assertTrue(max.equals(min)); } @Test public void differentSubtypesAreNotEqualIfTheirLongNumericalValuesAreNotEqual() { MinValue min = new MinValue(123L); MaxValue max = new MaxValue(124L); assertFalse(min.equals(max)); assertFalse(max.equals(min)); } @Test public void differentSubtypesAreEqualIfTheirDoubleNumericalValuesAreEqual() { MinValue min = new MinValue(123.45d); MaxValue max = new MaxValue(123.45d); assertTrue(min.equals(max)); assertTrue(max.equals(min)); } @Test public void differentSubtypesAreNotEqualIfTheirDoubleNumericalValuesAreNotEqual() { MinValue min = new MinValue(123.45d); MaxValue max = new MaxValue(123.7d); assertFalse(min.equals(max)); assertFalse(max.equals(min)); } @Test public void notEqualToOtherNonStatTypes() { SimpleStat stat = new SimpleStat(); String other = "something"; assertFalse(stat.equals(other)); assertFalse(other.equals(stat)); }
### Question: RollupService implements Runnable, RollupServiceMBean { public synchronized int getSlotCheckConcurrency() { return locatorFetchExecutors.getMaximumPoolSize(); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void testGetSlotCheckConcurrency() { int expected = 12; doReturn(expected).when(locatorFetchExecutors).getMaximumPoolSize(); int actual = service.getSlotCheckConcurrency(); assertEquals(expected, actual); verify(locatorFetchExecutors).getMaximumPoolSize(); verifyNoMoreInteractions(locatorFetchExecutors); }
### Question: BasicRollup extends BaseRollup implements IBaseRollup { public static BasicRollup buildRollupFromRawSamples(Points<SimpleNumber> input) throws IOException { final BasicRollup basicRollup = new BasicRollup(); basicRollup.computeFromSimpleMetrics(input); return basicRollup; } BasicRollup(); @Override boolean equals(Object other); double getSum(); String toString(); void setSum(double s); static BasicRollup buildRollupFromRawSamples(Points<SimpleNumber> input); static BasicRollup buildRollupFromRollups(Points<BasicRollup> input); @Override RollupType getRollupType(); }### Answer: @Test public void buildRollupFromRawSamples() throws IOException { BasicRollup rollup = createFromPoints( 5 ); assertEquals( "count is equal", 5, rollup.getCount() ); assertEquals( "average is equal", 30L, rollup.getAverage().toLong() ); assertEquals( "variance is equal", 200, rollup.getVariance().toDouble(), EPSILON ); assertEquals( "minValue is equal", 10, rollup.getMinValue().toLong() ); assertEquals( "maxValue is equal", 50, rollup.getMaxValue().toLong() ); assertEquals( "sum is equal", 150, rollup.getSum(), EPSILON ); }
### Question: BasicRollup extends BaseRollup implements IBaseRollup { public static BasicRollup buildRollupFromRollups(Points<BasicRollup> input) throws IOException { final BasicRollup basicRollup = new BasicRollup(); basicRollup.computeFromRollups(input); return basicRollup; } BasicRollup(); @Override boolean equals(Object other); double getSum(); String toString(); void setSum(double s); static BasicRollup buildRollupFromRawSamples(Points<SimpleNumber> input); static BasicRollup buildRollupFromRollups(Points<BasicRollup> input); @Override RollupType getRollupType(); }### Answer: @Test public void buildRollupFromRollups() throws IOException { Points<BasicRollup> rollups = new Points<BasicRollup>() {{ add( new Points.Point<BasicRollup>( 1, createFromPoints( 1 ) ) ); add( new Points.Point<BasicRollup>( 2, createFromPoints( 2 ) ) ); add( new Points.Point<BasicRollup>( 3, createFromPoints( 3 ) ) ); }}; BasicRollup rollup = BasicRollup.buildRollupFromRollups( rollups ); assertEquals( "count is equal", 6, rollup.getCount() ); assertEquals( "average is equal", 16L, rollup.getAverage().toLong() ); assertEquals( "variance is equal", 55.55, rollup.getVariance().toDouble(), EPSILON ); assertEquals( "minValue is equal", 10, rollup.getMinValue().toLong() ); assertEquals( "maxValue is equal", 30, rollup.getMaxValue().toLong() ); assertEquals( "sum is equal", 100, rollup.getSum(), EPSILON ); }
### Question: RollupService implements Runnable, RollupServiceMBean { public synchronized void setSlotCheckConcurrency(int i) { locatorFetchExecutors.setCorePoolSize(i); locatorFetchExecutors.setMaximumPoolSize(i); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void testSetSlotCheckConcurrency() { service.setSlotCheckConcurrency(3); verify(locatorFetchExecutors).setCorePoolSize(anyInt()); verify(locatorFetchExecutors).setMaximumPoolSize(anyInt()); verifyNoMoreInteractions(locatorFetchExecutors); }
### Question: RollupService implements Runnable, RollupServiceMBean { public synchronized int getRollupConcurrency() { return rollupReadExecutors.getMaximumPoolSize(); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void testGetRollupConcurrency() { int expected = 12; doReturn(expected).when(rollupReadExecutors).getMaximumPoolSize(); int actual = service.getRollupConcurrency(); assertEquals(expected, actual); verify(rollupReadExecutors).getMaximumPoolSize(); verifyNoMoreInteractions(rollupReadExecutors); }
### Question: MinValue extends AbstractRollupStat { @Override public byte getStatType() { return Constants.MIN; } MinValue(); @SuppressWarnings("unused") // used by Jackson MinValue(long value); @SuppressWarnings("unused") // used by Jackson MinValue(double value); @Override byte getStatType(); }### Answer: @Test public void returnsTheCorrectStatType() { assertEquals(Constants.MIN, min.getStatType()); }
### Question: RollupService implements Runnable, RollupServiceMBean { public synchronized void setRollupConcurrency(int i) { rollupReadExecutors.setCorePoolSize(i); rollupReadExecutors.setMaximumPoolSize(i); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void testSetRollupConcurrency() { service.setRollupConcurrency(3); verify(rollupReadExecutors).setCorePoolSize(anyInt()); verify(rollupReadExecutors).setMaximumPoolSize(anyInt()); verifyNoMoreInteractions(rollupReadExecutors); }
### Question: RollupService implements Runnable, RollupServiceMBean { public synchronized int getQueuedRollupCount() { return rollupReadExecutors.getQueue().size(); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void getQueuedRollupCountReturnsQueueSize() { BlockingQueue<Runnable> queue = mock(BlockingQueue.class); int expected1 = 123; int expected2 = 45; when(queue.size()).thenReturn(expected1).thenReturn(expected2); when(rollupReadExecutors.getQueue()).thenReturn(queue); int count = service.getQueuedRollupCount(); assertEquals(expected1, count); count = service.getQueuedRollupCount(); assertEquals(expected2, count); }
### Question: MaxValue extends AbstractRollupStat { @Override public byte getStatType() { return Constants.MAX; } MaxValue(); @SuppressWarnings("unused") // used by Jackson MaxValue(long value); @SuppressWarnings("unused") // used by Jackson MaxValue(double value); @Override byte getStatType(); }### Answer: @Test public void returnsTheCorrectStatType() { assertEquals(Constants.MAX, max.getStatType()); }
### Question: Token { public static List<Token> getTokens(Locator locator) { if (StringUtils.isEmpty(locator.getMetricName()) || StringUtils.isEmpty(locator.getTenantId())) return new ArrayList<>(); String[] tokens = locator.getMetricName().split(Locator.METRIC_TOKEN_SEPARATOR_REGEX); return IntStream.range(0, tokens.length) .mapToObj(index -> new Token(locator, tokens, index)) .collect(toList()); } Token(Locator locator, String[] tokens, int level); @Override boolean equals(Object o); @Override int hashCode(); String getId(); Locator getLocator(); String getToken(); String getParent(); boolean isLeaf(); static List<Token> getTokens(Locator locator); static Stream<Token> getUniqueTokens(Stream<Locator> locators); @Override String toString(); static final String LEAF_NODE_SUFFIX; static final String SEPARATOR; }### Answer: @Test public void testGetTokensHappyCase() { String tenantID = "111111"; String metricName = "a.b.c.d"; Locator locator = Locator.createLocatorFromPathComponents(tenantID, metricName); String[] expectedTokens = new String[] {"a", "b", "c", "d"}; String[] expectedParents = new String[] { "", "a", "a.b", "a.b.c"}; String[] expectedIds = new String[] { tenantID + ":" + "a", tenantID + ":" + "a.b", tenantID + ":" + "a.b.c", tenantID + ":" + "a.b.c.d:$"}; List<Token> tokens = Token.getTokens(locator); verifyTokenInfos(tenantID, expectedTokens, expectedParents, expectedIds, tokens); } @Test public void testGetTokensForMetricWithOneToken() { String tenantID = "111111"; String metricName = "a"; Locator locator = Locator.createLocatorFromPathComponents(tenantID, metricName); String[] expectedTokens = new String[] {"a"}; String[] expectedParents = new String[] {""}; String[] expectedIds = new String[] {tenantID + ":" + "a:$"}; List<Token> tokens = Token.getTokens(locator); verifyTokenInfos(tenantID, expectedTokens, expectedParents, expectedIds, tokens); } @Test public void testGetTokensWithEmptyTokenInBetween() { String tenantID = "111111"; String metricName = "ingest00.HeaderNormalization.header-normalization..*_GET.count"; Locator locator = Locator.createLocatorFromPathComponents(tenantID, metricName); String[] expectedTokens = new String[] {"ingest00", "HeaderNormalization", "header-normalization", "", "*_GET", "count"}; String[] expectedParents = new String[] { "", "ingest00", "ingest00.HeaderNormalization", "ingest00.HeaderNormalization.header-normalization", "ingest00.HeaderNormalization.header-normalization.", "ingest00.HeaderNormalization.header-normalization..*_GET"}; String[] expectedIds = new String[] { tenantID + ":" + "ingest00", tenantID + ":" + "ingest00.HeaderNormalization", tenantID + ":" + "ingest00.HeaderNormalization.header-normalization", tenantID + ":" + "ingest00.HeaderNormalization.header-normalization.", tenantID + ":" + "ingest00.HeaderNormalization.header-normalization..*_GET", tenantID + ":" + "ingest00.HeaderNormalization.header-normalization..*_GET.count:$"}; List<Token> tokens = Token.getTokens(locator); verifyTokenInfos(tenantID, expectedTokens, expectedParents, expectedIds, tokens); } @Test public void testGetTokensForMetricNoTokens() { String tenantID = "111111"; String metricName = ""; Locator locator = Locator.createLocatorFromPathComponents(tenantID, metricName); List<Token> tokens = Token.getTokens(locator); assertEquals("Total number of tokens invalid", 0, tokens.size()); }
### Question: RollupService implements Runnable, RollupServiceMBean { public synchronized int getInFlightRollupCount() { return rollupReadExecutors.getActiveCount(); } RollupService(ScheduleContext context); @VisibleForTesting RollupService(ScheduleContext context, ShardStateManager shardStateManager, ThreadPoolExecutor locatorFetchExecutors, ThreadPoolExecutor rollupReadExecutors, ThreadPoolExecutor rollupWriteExecutors, long rollupDelayMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay, long pollerPeriod, long configRefreshInterval); void initializeGauges(); void forcePoll(); void run(); synchronized void setServerTime(long millis); synchronized long getServerTime(); synchronized void setKeepingServerTime(boolean b); synchronized boolean getKeepingServerTime(); synchronized void setPollerPeriod(long l); synchronized long getPollerPeriod(); synchronized int getScheduledSlotCheckCount(); synchronized int getSecondsSinceLastSlotCheck(); synchronized int getSlotCheckConcurrency(); synchronized void setSlotCheckConcurrency(int i); synchronized int getRollupConcurrency(); synchronized void setRollupConcurrency(int i); synchronized int getQueuedRollupCount(); synchronized int getInFlightRollupCount(); synchronized boolean getActive(); synchronized void setActive(boolean b); void addShard(Integer shard); void removeShard(Integer shard); Collection<Integer> getManagedShards(); synchronized Collection<Integer> getRecentlyScheduledShards(); synchronized Collection<String> getOldestUnrolledSlotPerGranularity(int shard); }### Answer: @Test public void testGetInFlightRollupCount() { int expected1 = 123; int expected2 = 45; when(rollupReadExecutors.getActiveCount()) .thenReturn(expected1) .thenReturn(expected2); int count = service.getInFlightRollupCount(); assertEquals(expected1, count); count = service.getInFlightRollupCount(); assertEquals(expected2, count); }