src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
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; } | @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()); } |
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; } | @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()); ; } |
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; } | @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); } |
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; } | @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))); } |
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(); } | @Test public void inequality() throws Exception { InvariantSpan s1 = new InvariantSpan(10, 60, "ted: InvariantSpan s2 = new InvariantSpan(10, 50, "ted: assertFalse(s1.equals(s2)); } |
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(); } | @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); } |
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; } | @Test public void hashBlock() throws Exception { DocumentFile.Builder builder = new DocumentFile.Builder("fakeHash"); builder.previousHashBlock("sadasdsad"); DocumentFile file = builder.build(); assertEquals("sadasdsad", file.getHashPreviousBlock()); } |
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; } | @Test public void root() throws Exception { assertTrue(new Node<InvariantSpan>(10).isRoot()); } |
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; } | @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); } |
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); } | @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"); } |
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); } | @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()); } |
Partitioner { public static <T extends StreamElement> NodePartition<T> createNodePartition(long leftPartitionWidth, Node<T> x) throws MalformedSpanException { if (x == null) { throw new IllegalStateException("Attempting to partition a null node"); } if (leftPartitionWidth < 0) { throw new IndexOutOfBoundsException( "Width of left partition must be non-negative: width = " + leftPartitionWidth); } if (leftPartitionWidth >= x.characterCount()) { return new NodePartition<T>(x, null); } else if (leftPartitionWidth == 0) { return new NodePartition<T>(null, x); } else if (x.isLeaf() && x.isRoot()) { Node<T> split = x.split(leftPartitionWidth); split.left.parent = null; split.right.parent = null; return new NodePartition<T>(split.left, split.right); } else { NodeIndex<T> nodeIndex = RopeUtils.index(leftPartitionWidth, x, 0); if (nodeIndex.displacement > leftPartitionWidth) { throw new IllegalStateException("Width of left partition can't be less than displacement: width = " + leftPartitionWidth + ", Displacement = " + nodeIndex.displacement); } Node<T> indexNode = nodeIndex.node; if (isSplitInMiddle(nodeIndex, leftPartitionWidth)) { Node<T> splitIndexNode = indexNode.split(leftPartitionWidth - nodeIndex.displacement); attachParent(splitIndexNode, indexNode.parent, indexNode.isRightNode()); splitIndexNode.weight = splitIndexNode.left.weight; indexNode = splitIndexNode.left; } List<Node<T>> orphans = pruneIndexNode(indexNode, leftPartitionWidth, nodeIndex.displacement); if (orphans.isEmpty()) { throw new IllegalStateException( "No partition available after cut: partitionWidth = " + leftPartitionWidth); } return new NodePartition<T>(x, RopeUtils.concat(orphans)); } } static NodePartition<T> createNodePartition(long leftPartitionWidth, Node<T> x); static List<Node<S>> pruneIndexNode(Node<S> indexNode, long leftPartitionWidth,
long displacement); } | @Test public void createNodeParitionAlongRightCut() throws Exception { Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 10, documentHash)); Node<InvariantSpan> right = new Node<>(new InvariantSpan(1, 20, documentHash)); Node<InvariantSpan> root = new Node.Builder<InvariantSpan>(10).left(left).right(right).build(); NodePartition<InvariantSpan> part = Partitioner.createNodePartition(10, root); assertEquals(new InvariantSpan(1, 10, documentHash), part.left.left.value); assertEquals(new InvariantSpan(1, 20, documentHash), part.right.value); }
@Test public void createNodePartitionLeafRoot() throws Exception { Node<InvariantSpan> root = new Node<InvariantSpan>(new InvariantSpan(1, 10, documentHash)); NodePartition<InvariantSpan> part = Partitioner.createNodePartition(5, root); assertEquals(new InvariantSpan(1, 5, documentHash), part.left.value); assertEquals(new InvariantSpan(6, 5, documentHash), part.right.value); }
@Test public void createNodePartitionLinearList() throws Exception { Node<InvariantSpan> a = new Node<>(new InvariantSpan(1, 1, documentHash)); Node<InvariantSpan> b = new Node<>(new InvariantSpan(2, 1, documentHash)); Node<InvariantSpan> c = new Node<>(new InvariantSpan(3, 1, documentHash)); Node<InvariantSpan> d = new Node<>(new InvariantSpan(4, 1, documentHash)); Node<InvariantSpan> e = new Node<>(new InvariantSpan(5, 1, documentHash)); Node<InvariantSpan> f = new Node<>(new InvariantSpan(6, 1, documentHash)); Node<InvariantSpan> g = new Node<>(new InvariantSpan(7, 1, documentHash)); Node<InvariantSpan> h = new Node<>(new InvariantSpan(8, 1, documentHash)); Node<InvariantSpan> ab = new Node.Builder<InvariantSpan>(1).left(a).right(b).build(); Node<InvariantSpan> ac = new Node.Builder<InvariantSpan>(2).left(ab).right(c).build(); Node<InvariantSpan> ad = new Node.Builder<InvariantSpan>(3).left(ac).right(d).build(); Node<InvariantSpan> ae = new Node.Builder<InvariantSpan>(4).left(ad).right(e).build(); Node<InvariantSpan> af = new Node.Builder<InvariantSpan>(5).left(ae).right(f).build(); Node<InvariantSpan> ag = new Node.Builder<InvariantSpan>(6).left(af).right(g).build(); Node<InvariantSpan> ah = new Node.Builder<InvariantSpan>(7).left(ag).right(h).build(); NodePartition<InvariantSpan> part = Partitioner.createNodePartition(2, ah); }
@Test public void createNodePartitionMiddle() throws Exception { Node<InvariantSpan> a = new Node<>(new InvariantSpan(1, 1, documentHash)); Node<InvariantSpan> b = new Node<>(new InvariantSpan(2, 1, documentHash)); Node<InvariantSpan> c = new Node<>(new InvariantSpan(3, 1, documentHash)); Node<InvariantSpan> d = new Node<>(new InvariantSpan(4, 1, documentHash)); Node<InvariantSpan> ab = new Node.Builder<InvariantSpan>(1).left(a).right(b).build(); Node<InvariantSpan> abc = new Node.Builder<InvariantSpan>(2).left(ab).right(c).build(); Node<InvariantSpan> abcd = new Node.Builder<InvariantSpan>(3).left(abc).right(d).build(); NodePartition<InvariantSpan> part = Partitioner.createNodePartition(1, abcd); Node<InvariantSpan> leftNode = RopeUtils.index(1, part.left, 0).node; assertEquals(new InvariantSpan(1, 1, documentHash), leftNode.value); assertEquals(new InvariantSpan(2, 1, documentHash), RopeUtils.index(1, part.right, 0).node.value); assertEquals(new InvariantSpan(3, 1, documentHash), RopeUtils.index(2, part.right, 0).node.value); assertEquals(new InvariantSpan(4, 1, documentHash), RopeUtils.index(3, part.right, 0).node.value); }
@Test public void createNodePartitionRootBadPosition() throws Exception { NodePartition<InvariantSpan> part = Partitioner.createNodePartition(0, new Node<InvariantSpan>(new InvariantSpan(1, 10, documentHash))); assertEquals(new InvariantSpan(1, 10, documentHash), part.right.value); assertNull(part.left); }
@Test public void createNodePartitionRootBeyondRangePutLeft() throws Exception { NodePartition<InvariantSpan> part = Partitioner.createNodePartition(12, new Node<InvariantSpan>(new InvariantSpan(1, 10, documentHash))); assertEquals(new InvariantSpan(1, 10, documentHash), part.left.value); assertNull(part.right); }
@Test public void createNodePartitionWithRightLeaningIndexNode() throws Exception { Node<InvariantSpan> a = new Node<>(new InvariantSpan(2, 1, documentHash)); Node<InvariantSpan> b = new Node<>(new InvariantSpan(3, 1, documentHash)); Node<InvariantSpan> c = new Node<>(new InvariantSpan(4, 1, documentHash)); Node<InvariantSpan> ab = new Node.Builder<InvariantSpan>(1).left(a).right(b).build(); Node<InvariantSpan> abc = new Node.Builder<InvariantSpan>(2).left(ab).right(c).build(); NodePartition<InvariantSpan> part = Partitioner.createNodePartition(2, abc); assertEquals(new InvariantSpan(2, 1, documentHash), RopeUtils.index(1, part.left, 0).node.value); assertEquals(new InvariantSpan(3, 1, documentHash), RopeUtils.index(2, part.left, 0).node.value); assertEquals(new InvariantSpan(4, 1, documentHash), RopeUtils.index(3, part.right, 0).node.value); }
@Test public void createPartition() throws Exception { Node<InvariantSpan> A = new Node<InvariantSpan>(2); Node<InvariantSpan> B = new Node<>(1); Node<InvariantSpan> C = new Node<>(new InvariantSpan(4, 1, documentHash)); Node<InvariantSpan> D = new Node<>(new InvariantSpan(2, 1, documentHash)); Node<InvariantSpan> E = new Node<>(new InvariantSpan(3, 1, documentHash)); A.tag = "A"; B.tag = "B"; C.tag = "C"; D.tag = "D"; E.tag = "E"; A.left = B; A.right = C; B.left = D; B.right = E; B.parent = A; C.parent = A; D.parent = B; E.parent = B; NodePartition<InvariantSpan> result = Partitioner.createNodePartition(2, A); }
@Test(expected = IllegalStateException.class) public void partitionNullNode() throws Exception { Partitioner.createNodePartition(2, null); }
@Test(expected = IllegalStateException.class) public void partitionNullRoot() throws Exception { Partitioner.createNodePartition(2, null); } |
Partitioner { public static <S extends StreamElement> List<Node<S>> pruneIndexNode(Node<S> indexNode, long leftPartitionWidth, long displacement) { if (indexNode.isRightNode()) { if (indexNode.parent.parent != null) { if (indexNode.parent.left != null) { displacement -= indexNode.parent.left.weight; indexNode.parent.parent.isRed = false; } return pruneTree(indexNode.parent.parent, 0, leftPartitionWidth, displacement, indexNode.parent.parent.isRightNode()); } return new ArrayList<>(); } else { return pruneTree(indexNode.parent, 0, leftPartitionWidth, displacement, true); } } static NodePartition<T> createNodePartition(long leftPartitionWidth, Node<T> x); static List<Node<S>> pruneIndexNode(Node<S> indexNode, long leftPartitionWidth,
long displacement); } | @Test public void createNodePartitionLinearList2() throws Exception { Node<InvariantSpan> a = new Node<>(new InvariantSpan(1, 1, documentHash)); Node<InvariantSpan> b = new Node<>(new InvariantSpan(2, 1, documentHash)); Node<InvariantSpan> c = new Node<>(new InvariantSpan(3, 1, documentHash)); Node<InvariantSpan> d = new Node<>(new InvariantSpan(4, 1, documentHash)); Node<InvariantSpan> ab = new Node.Builder<InvariantSpan>(1).left(a).right(b).build(); Node<InvariantSpan> ac = new Node.Builder<InvariantSpan>(2).left(ab).right(c).build(); Node<InvariantSpan> ac_dummy = new Node.Builder<InvariantSpan>(3).left(ac).build(); Node<InvariantSpan> ad = new Node.Builder<InvariantSpan>(3).left(ac_dummy).right(d).build(); Node<InvariantSpan> root = new Node.Builder<InvariantSpan>(4).left(ad).build(); NodeIndex<InvariantSpan> e = RopeUtils.index(3, root, 0); List<Node<InvariantSpan>> orphans = Partitioner.pruneIndexNode(e.node, 3, e.displacement); }
@Test public void prune() throws Exception { Node<InvariantSpan> a = new Node<>(new InvariantSpan(300, 4, documentHash)); Node<InvariantSpan> b = new Node<>(new InvariantSpan(350, 1, documentHash)); Node<InvariantSpan> c = new Node<>(new InvariantSpan(360, 1, documentHash)); Node<InvariantSpan> d = new Node<>(new InvariantSpan(361, 5, documentHash)); d.tag = "d"; Node<InvariantSpan> cd = new Node.Builder<InvariantSpan>(1).left(c).right(d).tag("cd").build(); Node<InvariantSpan> bcd = new Node.Builder<InvariantSpan>(1).left(b).right(cd).tag("bcd").build(); Node<InvariantSpan> abcd = new Node.Builder<InvariantSpan>(4).left(a).right(bcd).tag("abcd").build(); NodeIndex<InvariantSpan> cIndex = RopeUtils.index(6, abcd, 0); List<Node<InvariantSpan>> orphans = Partitioner.pruneIndexNode(cIndex.node, 6, cIndex.displacement); assertEquals(1, orphans.size()); assertEquals("d", orphans.get(0).tag); }
@Test public void prune11() throws Exception { Node<InvariantSpan> root = getA(); NodeIndex<InvariantSpan> j = RopeUtils.index(11, root, 0); List<Node<InvariantSpan>> orphans = Partitioner.pruneIndexNode(j.node, 11, j.displacement); assertEquals(2, orphans.size()); assertEquals("K", orphans.get(0).tag); assertEquals("H", orphans.get(1).tag); Node<InvariantSpan> resultRoot = RopeUtils.findRoot(j.node); assertEquals(9, resultRoot.left.weight); assertEquals(11, resultRoot.weight); }
@Test public void prune6() throws Exception { Node<InvariantSpan> root = getA(); NodeIndex<InvariantSpan> e = RopeUtils.index(6, root, 0); List<Node<InvariantSpan>> orphans = Partitioner.pruneIndexNode(e.node, 6, e.displacement); assertEquals(2, orphans.size()); assertEquals("F", orphans.get(0).tag); assertEquals("D", orphans.get(1).tag); assertEquals(6, root.left.weight); assertEquals(6, root.weight); }
@Test public void prune9() throws Exception { Node<InvariantSpan> root = getA(); NodeIndex<InvariantSpan> f = RopeUtils.index(9, root, 0); List<Node<InvariantSpan>> orphans = Partitioner.pruneIndexNode(f.node, 9, f.displacement); assertEquals(1, orphans.size()); assertEquals("D", orphans.get(0).tag); assertEquals(9, root.weight); }
@Test public void pruneNullLeft() throws Exception { Node<InvariantSpan> right = new Node<>(new InvariantSpan(2, 1, documentHash)); new Node.Builder<InvariantSpan>(0).right(right).build(); List<Node<InvariantSpan>> orphans = Partitioner.pruneIndexNode(right, 1, 0); assertEquals(0, orphans.size()); }
@Test public void pruneNullRight() throws Exception { Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 1, documentHash)); new Node.Builder<InvariantSpan>(1).left(left).build(); List<Node<InvariantSpan>> orphans = Partitioner.pruneIndexNode(left, 1, 0); assertEquals(0, orphans.size()); }
@Test public void pruneRight() throws Exception { Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 1, documentHash)); Node<InvariantSpan> right = new Node<>(1); right.left = new Node<InvariantSpan>(new InvariantSpan(50, 1, documentHash)); right.right = new Node<InvariantSpan>(new InvariantSpan(100, 1, documentHash)); right.tag = "RGHT"; new Node.Builder<InvariantSpan>(1).left(left).right(right).build(); List<Node<InvariantSpan>> orphans = Partitioner.pruneIndexNode(left, 1, 0); assertEquals(1, orphans.size()); assertEquals("RGHT", orphans.get(0).tag); }
@Test public void pruneRight2() throws Exception { Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 4, documentHash)); Node<InvariantSpan> right = new Node<>(new InvariantSpan(1, 20, documentHash)); new Node.Builder<InvariantSpan>(4).left(left).right(right).build(); List<Node<InvariantSpan>> orphans = Partitioner.pruneIndexNode(left, 4, 0); assertEquals(1, orphans.size()); assertEquals(new InvariantSpan(1, 20, documentHash), orphans.get(0).value); }
@Test public void pruneRightWithNoChildLeft() throws Exception { Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 1, documentHash)); Node<InvariantSpan> right = new Node<>(1); right.right = new Node<InvariantSpan>(new InvariantSpan(100, 1, documentHash)); right.tag = "RGHT"; new Node.Builder<InvariantSpan>(1).left(left).right(right).build(); List<Node<InvariantSpan>> orphans = Partitioner.pruneIndexNode(left, 1, 0); assertEquals(1, orphans.size()); assertEquals("RGHT", orphans.get(0).tag); assertNull(orphans.get(0).left); assertNotNull(orphans.get(0).right); }
@Test public void pruneSimpleRight() throws Exception { Node<InvariantSpan> left = new Node<>(new InvariantSpan(1, 1, documentHash)); Node<InvariantSpan> right = new Node<>(new InvariantSpan(2, 1, documentHash)); new Node.Builder<InvariantSpan>(1).left(left).right(right).build(); List<Node<InvariantSpan>> orphans = Partitioner.pruneIndexNode(right, 2, 1); assertEquals(0, orphans.size()); } |
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; } | @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); } |
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; } | @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); } |
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); } | @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)); } |
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); } | @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()); } |
RopeVariantStream implements VariantStream<T> { @Override public List<T> getStreamElements() throws MalformedSpanException { List<T> elements = new ArrayList<>(); Iterator<Node<T>> it = getAllLeafNodes(); while (it.hasNext()) { Node<T> node = it.next(); if (node.value != null) { elements.add(node.value); } } return elements; } 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); } | @Test public void getInvariantSpan() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash); List<InvariantSpan> spans = Arrays.asList(new InvariantSpan(1, 11, documentHash)); stream.putElements(1, spans); List<InvariantSpan> results = stream.getStreamElements(new VariantSpan(5, 6)); assertEquals(new InvariantSpan(6, 6, documentHash), results.get(0)); }
@Test public void getInvariantSpansBeyondWidthOk() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash, getA()); List<InvariantSpan> spans = stream.getStreamElements(new VariantSpan(10, 700)); assertEquals(new InvariantSpan(250, 2, documentHash), spans.get(0)); assertEquals(new InvariantSpan(300, 4, documentHash), spans.get(1)); assertEquals(new InvariantSpan(350, 1, documentHash), spans.get(2)); assertEquals(new InvariantSpan(360, 6, documentHash), spans.get(3)); }
@Test public void getInvariantSpansMiddle() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash, getA()); List<InvariantSpan> spans = stream.getStreamElements(new VariantSpan(10, 7)); assertEquals(new InvariantSpan(250, 2, documentHash), spans.get(0)); assertEquals(new InvariantSpan(300, 4, documentHash), spans.get(1)); assertEquals(new InvariantSpan(350, 1, documentHash), spans.get(2)); }
@Test public void getInvariantSpansMiddle2() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash, getA()); List<InvariantSpan> spans = stream.getStreamElements(new VariantSpan(10, 6, documentHash)); assertEquals(new InvariantSpan(250, 2, documentHash), spans.get(0)); assertEquals(new InvariantSpan(300, 4, documentHash), spans.get(1)); }
@Test public void getInvariantSpansRangeEdgeLeft() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash, getA()); List<InvariantSpan> spans = stream.getStreamElements(new VariantSpan(1, 14)); 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(300, 3, documentHash), spans.get(3)); assertEquals(4, spans.size()); }
@Test public void getInvariantSpansSmallWidthLeft() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash, getA()); List<InvariantSpan> spans = stream.getStreamElements(new VariantSpan(1, 1)); assertEquals(new InvariantSpan(100, 1, documentHash), spans.get(0)); }
@Test public void getInvariantSpansSmallWidthRight() throws Exception { VariantStream<InvariantSpan> stream = new RopeVariantStream<>(documentHash, getA()); List<InvariantSpan> spans = stream.getStreamElements(new VariantSpan(21, 1)); assertEquals(new InvariantSpan(365, 1, documentHash), spans.get(0)); }
@Test public void putSpans() 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<InvariantSpan> results = stream.getStreamElements(); assertEquals(results.get(0), spans.get(0)); assertEquals(results.get(1), spans.get(1)); assertEquals(results.get(2), spans.get(2)); } |
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); } | @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)); } |
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); } | @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); } |
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); } | @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)); } |
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); } | @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()); } |
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); } | @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); } |
LocatorFetchRunnable implements Runnable { protected Set<Locator> getLocators(RollupExecutionContext executionContext, boolean isReroll, Granularity delayedMetricsRerollGranularity, Granularity delayedMetricsStorageGranularity) { Set<Locator> locators = new HashSet<Locator>(); if (RECORD_DELAYED_METRICS && isReroll && !getGranularity().isCoarser(delayedMetricsRerollGranularity)) { if (getGranularity().isCoarser(delayedMetricsStorageGranularity)) { for (SlotKey slotKey: parentSlotKey.getChildrenKeys(delayedMetricsStorageGranularity)) { locators.addAll(getDelayedLocators(executionContext, slotKey)); } } else { locators = getDelayedLocators(executionContext, parentSlotKey.extrapolate(delayedMetricsStorageGranularity)); } } else { locators = getLocators(executionContext); } return locators; } LocatorFetchRunnable(ScheduleContext scheduleCtx,
SlotKey destSlotKey,
ExecutorService rollupReadExecutor,
ThreadPoolExecutor rollupWriteExecutor); @VisibleForTesting void initialize(ScheduleContext scheduleCtx,
SlotKey destSlotKey,
ExecutorService rollupReadExecutor,
ThreadPoolExecutor rollupWriteExecutor); void run(); void drainExecutionContext(long waitStart, int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter); void finishExecution(long waitStart, RollupExecutionContext executionContext); int processLocator(int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator); void executeRollupForLocator(RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator); Set<Locator> getDelayedLocators(RollupExecutionContext executionContext, SlotKey slotkey); Set<Locator> getLocators(RollupExecutionContext executionContext); } | @Test public void testGetLocatorsForReRollLowerLevelToStorageGranularity() throws IOException { boolean isReroll = true; SlotKey destSlotKey = SlotKey.of(Granularity.MIN_5, 0, TEST_SHARD); Granularity delayedMetricsRerollGranularity = Granularity.MIN_60; Granularity delayedMetricsStorageGranularity = Granularity.MIN_20; LocatorFetchRunnable lfrunnable = new LocatorFetchRunnable(scheduleCtx, destSlotKey, rollupReadExecutor, rollupWriteExecutor); HashSet<Locator> delayedLocators = new HashSet<Locator>() {{ add(locators.get(0)); }}; when(delayedLocatorIO.getLocators(SlotKey.of(Granularity.MIN_20, 0, TEST_SHARD))).thenReturn(delayedLocators); Set<Locator> locatorsForRollup = lfrunnable.getLocators(executionContext, isReroll, delayedMetricsRerollGranularity, delayedMetricsStorageGranularity); assertEquals(delayedLocators.size(), locatorsForRollup.size()); }
@Test public void testGetLocatorsForReRollSameAsStorageGranularity() throws IOException { boolean isReroll = true; SlotKey destSlotKey = SlotKey.of(Granularity.MIN_20, 0, TEST_SHARD); Granularity delayedMetricsRerollGranularity = Granularity.MIN_60; Granularity delayedMetricsStorageGranularity = Granularity.MIN_20; LocatorFetchRunnable lfrunnable = new LocatorFetchRunnable(scheduleCtx, destSlotKey, rollupReadExecutor, rollupWriteExecutor); HashSet<Locator> delayedLocators = new HashSet<Locator>() {{ add(locators.get(0)); }}; when(delayedLocatorIO.getLocators(SlotKey.of(Granularity.MIN_20, 0, TEST_SHARD))).thenReturn(delayedLocators); Set<Locator> locatorsForRollup = lfrunnable.getLocators(executionContext, isReroll, delayedMetricsRerollGranularity, delayedMetricsStorageGranularity); assertEquals(delayedLocators.size(), locatorsForRollup.size()); }
@Test public void testGetLocatorsForReRollHigherLevelToStorageGranularity() throws IOException { boolean isReroll = true; SlotKey destSlotKey = SlotKey.of(Granularity.MIN_60, 0, TEST_SHARD); Granularity delayedMetricsRerollGranularity = Granularity.MIN_60; Granularity delayedMetricsStorageGranularity = Granularity.MIN_20; LocatorFetchRunnable lfrunnable = new LocatorFetchRunnable(scheduleCtx, destSlotKey, rollupReadExecutor, rollupWriteExecutor); HashSet<Locator> delayedLocators1 = new HashSet<Locator>() {{ add(locators.get(0)); }}; HashSet<Locator> delayedLocators2 = new HashSet<Locator>() {{ add(locators.get(1)); }}; when(delayedLocatorIO.getLocators(SlotKey.of(Granularity.MIN_20, 0, TEST_SHARD))).thenReturn(delayedLocators1); when(delayedLocatorIO.getLocators(SlotKey.of(Granularity.MIN_20, 1, TEST_SHARD))).thenReturn(delayedLocators1); when(delayedLocatorIO.getLocators(SlotKey.of(Granularity.MIN_20, 2, TEST_SHARD))).thenReturn(delayedLocators2); Set<Locator> locatorsForRollup = lfrunnable.getLocators(executionContext, isReroll, delayedMetricsRerollGranularity, delayedMetricsStorageGranularity); assertEquals(delayedLocators1.size() + delayedLocators2.size(), locatorsForRollup.size()); }
@Test public void testGetLocatorsForReRollHigherLevelToRerollGranularity() throws IOException { boolean isReroll = true; SlotKey destSlotKey = SlotKey.of(Granularity.MIN_240, 0, TEST_SHARD); Granularity delayedMetricsRerollGranularity = Granularity.MIN_60; Granularity delayedMetricsStorageGranularity = Granularity.MIN_20; LocatorFetchRunnable lfrunnable = new LocatorFetchRunnable(scheduleCtx, destSlotKey, rollupReadExecutor, rollupWriteExecutor); Set<Locator> locatorsForRollup = lfrunnable.getLocators(executionContext, isReroll, delayedMetricsRerollGranularity, delayedMetricsStorageGranularity); assertEquals(locators.size(), locatorsForRollup.size()); }
@Test public void getLocatorsReturnsLocators() throws IOException { Set<Locator> expected = new HashSet<Locator>(locators); when(locatorIO.getLocators(TEST_SHARD)).thenReturn(locators); Set<Locator> actual = lfr.getLocators(executionContext); verify(locatorIO, times(1)).getLocators(TEST_SHARD); verifyNoMoreInteractions(locatorIO); verifyZeroInteractions(executionContext); Assert.assertEquals(expected, actual); }
@Test public void getLocatorsExceptionYieldsEmptySet() throws IOException { when(locatorIO.getLocators(TEST_SHARD)).thenThrow(new RuntimeException("")); Set<Locator> actual = lfr.getLocators(executionContext); verify(locatorIO, times(1)).getLocators(TEST_SHARD); verifyNoMoreInteractions(locatorIO); verify(executionContext, times(1)).markUnsuccessful(Matchers.<Throwable>any()); verifyNoMoreInteractions(executionContext); assertNotNull(actual); Assert.assertEquals(0, actual.size()); }
@Test public void testGetLocatorsForRegularRollup() throws IOException { boolean isReroll = false; SlotKey destSlotKey = SlotKey.of(Granularity.MIN_20, 0, TEST_SHARD); Granularity delayedMetricsRerollGranularity = Granularity.MIN_20; Granularity delayedMetricsStorageGranularity = Granularity.MIN_20; LocatorFetchRunnable lfrunnable = new LocatorFetchRunnable(scheduleCtx, destSlotKey, rollupReadExecutor, rollupWriteExecutor); when(scheduleCtx.isReroll(any(SlotKey.class))).thenReturn(isReroll); when(locatorIO.getLocators(anyInt())).thenReturn(locators); Set<Locator> locatorsForRollup = lfrunnable.getLocators(executionContext, isReroll, delayedMetricsRerollGranularity, delayedMetricsStorageGranularity); assertEquals(locators.size(), locatorsForRollup.size()); } |
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); } | @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); } |
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); } | @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)); } |
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); } | @Test public void locatorGetsSetInConstructor() { Assert.assertSame(locator, event.getLocator()); } |
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); } | @Test public void rollupGetsSetInConstructor() { Assert.assertSame(rollup, event.getRollup()); } |
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); } | @Test public void unitGetsSetInConstructor() { Assert.assertEquals(unit, event.getUnit()); } |
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); } | @Test public void granularityGetsSetInConstructor() { Assert.assertEquals(granularity, event.getGranularityName()); } |
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(); } | @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); } |
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); } | @Test public void timestampGetsSetInConstructor() { Assert.assertEquals(timestamp, event.getTimestamp()); } |
RollupEventEmitter extends Emitter<RollupEvent> { @Override public Future emit(final String event, final RollupEvent... eventPayload) { Future emitFuture = null; if(eventPayload[0].getRollup() instanceof BasicRollup && super.hasListeners(ROLLUP_EVENT_NAME)) { emitFuture = eventExecutors.submit(new Callable() { @Override public Future call() { if (Util.shouldUseESForUnits()) { final DiscoveryIO discoveryIO = (DiscoveryIO) ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); Lists.transform(Arrays.asList(eventPayload), new Function<RollupEvent, RollupEvent>() { @Override public RollupEvent apply(RollupEvent event) { String unit; try { unit = discoveryIO.search(event.getLocator().getTenantId(), event.getLocator().getMetricName()).get(0).getUnit(); } catch (Exception e) { log.warn("Exception encountered while getting units out of ES : %s", e.getMessage()); unit = Util.UNKNOWN; } event.setUnit(unit); return event; } }); } return RollupEventEmitter.super.emit(event, eventPayload); } }); } return emitFuture; } RollupEventEmitter(); @VisibleForTesting RollupEventEmitter(ExecutorService executor); static RollupEventEmitter getInstance(); @Override Future emit(final String event, final RollupEvent... eventPayload); static final String ROLLUP_EVENT_NAME; } | @Test public void testConcurrentEmission() throws InterruptedException, ExecutionException { emitter.on(testEventName, listener); ThreadPoolExecutor executors = new ThreadPoolBuilder() .withCorePoolSize(2) .withMaxPoolSize(3) .build(); final CountDownLatch startLatch = new CountDownLatch(1); Future<Object> f1 = executors.submit(new Callable<Object>() { @Override public Object call() throws Exception { startLatch.await(); emitter.emit(testEventName, event1); return null; } }); Future<Object> f2 = executors.submit(new Callable<Object>() { @Override public Object call() throws Exception { startLatch.await(); emitter.emit(testEventName, event2); return null; } }); Thread.sleep(1000); Assert.assertTrue(store.isEmpty()); startLatch.countDown(); f1.get(); f2.get(); Assert.assertEquals(store.size(), 2); Assert.assertTrue(store.contains(event1)); Assert.assertTrue(store.contains(event2)); }
@Test public void testUnsubscription() { emitter.on(testEventName, listener); emitter.off(testEventName, listener); Assert.assertFalse(emitter.listeners(testEventName).contains(listener)); store.clear(); emitter.emit(testEventName, new RollupEvent(null, null, "payload3", "gran", 0)); Assert.assertTrue(store.isEmpty()); }
@Test public void testOnce() throws ExecutionException, InterruptedException { emitter.once(testEventName, listener); Future f = emitter.emit(testEventName, event1); f.get(); Assert.assertEquals(store.size(), 1); store.clear(); emitter.emit(testEventName, event2); Assert.assertEquals(store.size(), 0); }
@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)); }
@Test public void offClearsRegularCallbacks() { emitter.on(testEventName, listener); Assert.assertEquals(0, store.size()); emitter.off(); emitter.emit(testEventName, event1); Assert.assertEquals(0, store.size()); }
@Test public void offClearsOnceCallbacks() { emitter.once(testEventName, listener); Assert.assertEquals(0, store.size()); emitter.off(); emitter.emit(testEventName, event1); Assert.assertEquals(0, store.size()); }
@Test public void emitOnlyTriggersForGivenEvent1() { emitter.on(testEventName, listener); emitter.on(testEventName2, listener); Assert.assertEquals(0, store.size()); emitter.emit(testEventName, event1); Assert.assertEquals(1, store.size()); Assert.assertSame(event1, store.get(0)); }
@Test public void emitOnlyTriggersForGivenEvent2() { emitter.on(testEventName, listener); emitter.on(testEventName2, listener); Assert.assertEquals(0, store.size()); emitter.emit(testEventName2, event2); Assert.assertEquals(1, store.size()); Assert.assertSame(event2, store.get(0)); }
@Test public void emitTriggersListenerInSameOrder1() { emitter.on(testEventName, listener); emitter.on(testEventName2, listener); Assert.assertEquals(0, store.size()); emitter.emit(testEventName, event1); emitter.emit(testEventName2, event2); Assert.assertEquals(2, store.size()); Assert.assertSame(event1, store.get(0)); Assert.assertSame(event2, store.get(1)); }
@Test public void emitTriggersListenerInSameOrder2() { emitter.on(testEventName, listener); emitter.on(testEventName2, listener); Assert.assertEquals(0, store.size()); emitter.emit(testEventName2, event2); emitter.emit(testEventName, event1); Assert.assertEquals(2, store.size()); Assert.assertSame(event2, store.get(0)); Assert.assertSame(event1, store.get(1)); }
@Test public void offOnlyClearsForGivenEvent() { emitter.on(testEventName, listener); emitter.on(testEventName2, listener); Assert.assertEquals(0, store.size()); emitter.off(testEventName); emitter.emit(testEventName, event1); emitter.emit(testEventName2, event2); Assert.assertEquals(1, store.size()); Assert.assertSame(event2, store.get(0)); }
@Test public void multipleAttachedListenersShouldAllBeTriggeredByOneEvent() { emitter.on(testEventName, listener); emitter.on(testEventName, listener2); Assert.assertEquals(0, store.size()); Assert.assertEquals(0, store2.size()); emitter.emit(testEventName, event1); Assert.assertEquals(1, store.size()); Assert.assertSame(event1, store.get(0)); Assert.assertEquals(1, store2.size()); Assert.assertSame(event1, store2.get(0)); } |
Granularity { public static Granularity granularityFromPointsInInterval(String tenantid, long from, long to, int points) { return granularityFromPointsInInterval(tenantid, from, to, points, GET_BY_POINTS_SELECTION_ALGORITHM, GET_BY_POINTS_ASSUME_INTERVAL, DEFAULT_TTL_COMPARISON_SOURCE); } 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; } | @Test public void testForCloseness() { int desiredPoints = 10; long start = Calendar.getInstance().getTimeInMillis(); Assert.assertEquals(Granularity.MIN_20, Granularity.granularityFromPointsInInterval("TENANTID1234",start, start + 10000000, desiredPoints)); Assert.assertEquals(Granularity.MIN_5, Granularity.granularityFromPointsInInterval("TENANTID1234",start, start + 1000000, desiredPoints)); Map<Integer, Granularity> expectedGranularities = new HashMap<Integer, Granularity>() {{ put(5000, Granularity.FULL); put(1055, Granularity.FULL); put(1054, Granularity.MIN_5); put(167, Granularity.MIN_5); put(166, Granularity.MIN_20); put(49, Granularity.MIN_20); put(48, Granularity.MIN_60); put(14, Granularity.MIN_60); put(13, Granularity.MIN_240); put(3, Granularity.MIN_240); put(2, Granularity.MIN_1440); put(1, Granularity.MIN_1440); }}; for (Map.Entry<Integer, Granularity> entry : expectedGranularities.entrySet()) { Granularity actual = Granularity.granularityFromPointsInInterval("TENANTID1234",start, start+100000000, entry.getKey()); Assert.assertEquals( String.format("%d points", entry.getKey()), entry.getValue(), actual); } }
@Test public void testCommonPointRequests() { long HOUR = 3600000; long DAY = 24 * HOUR; Assert.assertEquals(Granularity.FULL, Granularity.granularityFromPointsInInterval("TENANTID1234",fromBaseMillis, fromBaseMillis+HOUR, 300)); Assert.assertEquals(Granularity.MIN_5, Granularity.granularityFromPointsInInterval("TENANTID1234",fromBaseMillis, fromBaseMillis+(8 * HOUR), 300)); Assert.assertEquals(Granularity.MIN_5, Granularity.granularityFromPointsInInterval("TENANTID1234",fromBaseMillis, fromBaseMillis+(12 * HOUR), 300)); Assert.assertEquals(Granularity.MIN_5, Granularity.granularityFromPointsInInterval("TENANTID1234",fromBaseMillis, fromBaseMillis+DAY, 300)); Assert.assertEquals(Granularity.MIN_20, Granularity.granularityFromPointsInInterval("TENANTID1234",fromBaseMillis, fromBaseMillis+(7 * DAY), 300)); Assert.assertEquals(Granularity.MIN_240, Granularity.granularityFromPointsInInterval("TENANTID1234",fromBaseMillis, fromBaseMillis+(30 * DAY), 300)); }
@Test(expected = RuntimeException.class) public void testToBeforeFromInterval() { Granularity.granularityFromPointsInInterval("TENANTID1234",fromBaseMillis+10000000, fromBaseMillis+0, 100); }
@Test public void testBadGranularityFromPointsInterval() { try { Granularity.granularityFromPointsInInterval("TENANTID1234",fromBaseMillis+2, fromBaseMillis+1, 3); Assert.fail("Should not have worked"); } catch (RuntimeException e) { Assert.assertEquals("Invalid interval specified for fromPointsInInterval", e.getMessage()); } }
@Test public void granFromPointsLinear100PointsBoundaryBetween5And20() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 48000000, 100, "LINEAR", 1); Assert.assertSame(Granularity.MIN_5, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 48000001, 100, "LINEAR", 1); Assert.assertSame(Granularity.MIN_20, gran); }
@Test public void granFromPointsLinear1000PointsBoundaryBetween5And20() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 480000000L, 1000, "LINEAR", 1); Assert.assertSame(Granularity.MIN_5, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 480000001L, 1000, "LINEAR", 1); Assert.assertSame(Granularity.MIN_20, gran); }
@Test public void granFromPointsLinear10000PointsBoundaryBetween5And20() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 4800000000L, 10000, "LINEAR", 1); Assert.assertNull(gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 4800000001L, 10000, "LINEAR", 1); Assert.assertNull(gran); }
@Test public void granFromPointsLinearBoundaryBetween20And60() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 18000000, 10, "LINEAR", 1); Assert.assertSame(Granularity.MIN_20, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 18000001, 10, "LINEAR", 1); Assert.assertSame(Granularity.MIN_60, gran); }
@Test public void granFromPointsLinearBoundaryBetween60And240() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 57600000, 10, "LINEAR", 1); Assert.assertSame(Granularity.MIN_60, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 57600001, 10, "LINEAR", 1); Assert.assertSame(Granularity.MIN_240, gran); }
@Test public void granFromPointsLinearBoundaryBetween240And1440() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 246857142, 10, "LINEAR", 1); Assert.assertSame(Granularity.MIN_240, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 246857143, 10, "LINEAR", 1); Assert.assertSame(Granularity.MIN_240, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 259199999, 10, "LINEAR", 1); Assert.assertSame(Granularity.MIN_240, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 259200000, 10, "LINEAR", 1); Assert.assertSame(Granularity.MIN_1440, gran); }
@Test(expected = RuntimeException.class) public void granFromPointsWithFromGreaterThanToThrowsException() { Granularity gran = Granularity.granularityFromPointsInInterval("abc123", 10, 5, 10, "LINEAR", 1); }
@Test(expected = RuntimeException.class) public void granFromPointsWithFromEqualToThrowsException() { Granularity gran = Granularity.granularityFromPointsInInterval("abc123", 10, 10, 10, "LINEAR", 1); }
@Test public void granFromPointsLessThanEqual100PointsBoundaryBetween5And20() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 30000000, 100, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_5, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 30000001, 100, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_20, gran); }
@Test public void granFromPointsLessThanEqual1000PointsBoundaryBetween5And20() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 300000000L, 1000, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_5, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 300000001L, 1000, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_20, gran); }
@Test(expected = NullPointerException.class) public void granFromPointsLessThanEqual10000PointsBoundaryBetween5And20() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 3000000000L, 10000, "LESSTHANEQUAL", 1); }
@Test public void granFromPointsLessThanEqualBoundaryBetween20And60() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 12000000, 10, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_20, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 12000001, 10, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_60, gran); }
@Test public void granFromPointsLessThanEqualBoundaryBetween60And240() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 36000000, 10, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_60, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 36000001, 10, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_240, gran); }
@Test public void granFromPointsLessThanEqualBoundaryBetween240And1440() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 144000000, 10, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_240, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 144000001, 10, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_1440, gran); }
@Test public void granFromPointsLessThanEqualWouldBeUpperBoundaryOf1440() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 864000000, 10, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_1440, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 864000001, 10, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_1440, gran); }
@Test public void granFromPointsGeometricBoundaryBetween5And20() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 6000000, 10, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_5, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 6000001, 10, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_20, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 60000000, 100, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_5, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 60000001, 100, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_20, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 600000000, 1000, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_5, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 600000001, 1000, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_20, gran); }
@Test public void granFromPointsGeometricBoundaryBetween20And60() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 20784609, 10, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_20, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 20784610, 10, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_60, gran); }
@Test public void granFromPointsGeometricBoundaryBetween60And240() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 72000000, 10, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_60, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 72000001, 10, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_240, gran); }
@Test public void granFromPointsGeometricBoundaryBetween240And1440() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 352726522, 10, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_240, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 352726523, 10, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_1440, gran); }
@Test public void granFromPointsGeometricWithDefaultClockAndAllGranularitiesSkippedReturnsCoarsest() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 6000000, 10, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_5, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 6000000, 10, "GEOMETRIC", 1); Assert.assertSame(Granularity.MIN_1440, gran); }
@Test public void granFromPointsInvalidAlgorithmDefaultsToGeometric() { Granularity gran; gran = Granularity.granularityFromPointsInInterval("abc123", 0, 48000000, 100, "LINEAR", 1); Assert.assertSame(Granularity.MIN_5, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 48000001, 100, "LINEAR", 1); Assert.assertSame(Granularity.MIN_20, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 30000000, 100, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_5, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 30000001, 100, "LESSTHANEQUAL", 1); Assert.assertSame(Granularity.MIN_20, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 60000000, 100, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_5, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 60000001, 100, "GEOMETRIC", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_20, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 60000000, 100, "INVALID", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_5, gran); gran = Granularity.granularityFromPointsInInterval("abc123", 0, 60000001, 100, "INVALID", 1, alwaysZeroClock); Assert.assertSame(Granularity.MIN_20, gran); } |
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; } | @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(); } |
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; } | @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(); } |
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(); } | @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); } |
Granularity { @Override public boolean equals(Object obj) { if (!(obj instanceof Granularity)) return false; else return obj == this; } 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; } | @Test public void equalsWithSameValueReturnsTrue() { Assert.assertTrue(Granularity.FULL.equals(Granularity.FULL)); Assert.assertTrue(Granularity.MIN_5.equals(Granularity.MIN_5)); Assert.assertTrue(Granularity.MIN_20.equals(Granularity.MIN_20)); Assert.assertTrue(Granularity.MIN_60.equals(Granularity.MIN_60)); Assert.assertTrue(Granularity.MIN_240.equals(Granularity.MIN_240)); Assert.assertTrue(Granularity.MIN_1440.equals(Granularity.MIN_1440)); }
@Test public void equalsWithDifferentValueReturnsFalse() { Assert.assertFalse(Granularity.FULL.equals(Granularity.MIN_5)); Assert.assertFalse(Granularity.FULL.equals(Granularity.MIN_20)); Assert.assertFalse(Granularity.FULL.equals(Granularity.MIN_60)); Assert.assertFalse(Granularity.FULL.equals(Granularity.MIN_240)); Assert.assertFalse(Granularity.FULL.equals(Granularity.MIN_1440)); Assert.assertFalse(Granularity.MIN_5.equals(Granularity.FULL)); Assert.assertFalse(Granularity.MIN_5.equals(Granularity.MIN_20)); Assert.assertFalse(Granularity.MIN_5.equals(Granularity.MIN_60)); Assert.assertFalse(Granularity.MIN_5.equals(Granularity.MIN_240)); Assert.assertFalse(Granularity.MIN_5.equals(Granularity.MIN_1440)); Assert.assertFalse(Granularity.MIN_20.equals(Granularity.FULL)); Assert.assertFalse(Granularity.MIN_20.equals(Granularity.MIN_5)); Assert.assertFalse(Granularity.MIN_20.equals(Granularity.MIN_60)); Assert.assertFalse(Granularity.MIN_20.equals(Granularity.MIN_240)); Assert.assertFalse(Granularity.MIN_20.equals(Granularity.MIN_1440)); Assert.assertFalse(Granularity.MIN_60.equals(Granularity.FULL)); Assert.assertFalse(Granularity.MIN_60.equals(Granularity.MIN_5)); Assert.assertFalse(Granularity.MIN_60.equals(Granularity.MIN_20)); Assert.assertFalse(Granularity.MIN_60.equals(Granularity.MIN_240)); Assert.assertFalse(Granularity.MIN_60.equals(Granularity.MIN_1440)); Assert.assertFalse(Granularity.MIN_240.equals(Granularity.FULL)); Assert.assertFalse(Granularity.MIN_240.equals(Granularity.MIN_5)); Assert.assertFalse(Granularity.MIN_240.equals(Granularity.MIN_20)); Assert.assertFalse(Granularity.MIN_240.equals(Granularity.MIN_60)); Assert.assertFalse(Granularity.MIN_240.equals(Granularity.MIN_1440)); Assert.assertFalse(Granularity.MIN_1440.equals(Granularity.FULL)); Assert.assertFalse(Granularity.MIN_1440.equals(Granularity.MIN_5)); Assert.assertFalse(Granularity.MIN_1440.equals(Granularity.MIN_20)); Assert.assertFalse(Granularity.MIN_1440.equals(Granularity.MIN_60)); Assert.assertFalse(Granularity.MIN_1440.equals(Granularity.MIN_240)); }
@Test public void equalsWithNullReturnsFalse() { Assert.assertFalse(Granularity.FULL.equals(null)); Assert.assertFalse(Granularity.MIN_5.equals(null)); Assert.assertFalse(Granularity.MIN_20.equals(null)); Assert.assertFalse(Granularity.MIN_60.equals(null)); Assert.assertFalse(Granularity.MIN_240.equals(null)); Assert.assertFalse(Granularity.MIN_1440.equals(null)); }
@Test public void equalsWithNonGranularityObjectReturnsFalse() { Assert.assertFalse(Granularity.FULL.equals(new Object())); Assert.assertFalse(Granularity.MIN_5.equals(new Object())); Assert.assertFalse(Granularity.MIN_20.equals(new Object())); Assert.assertFalse(Granularity.MIN_60.equals(new Object())); Assert.assertFalse(Granularity.MIN_240.equals(new Object())); Assert.assertFalse(Granularity.MIN_1440.equals(new Object())); } |
Granularity { public static Granularity fromString(String s) { for (Granularity g : granularities) if (g.name().equals(s) || g.shortName().equals(s)) return g; return null; } 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; } | @Test public void fromStringFull() { String s = "metrics_full"; Granularity gran = Granularity.fromString(s); Assert.assertNotNull(gran); Assert.assertSame(Granularity.FULL, gran); }
@Test public void fromString5m() { String s = "metrics_5m"; Granularity gran = Granularity.fromString(s); Assert.assertNotNull(gran); Assert.assertSame(Granularity.MIN_5, gran); }
@Test public void fromString20m() { String s = "metrics_20m"; Granularity gran = Granularity.fromString(s); Assert.assertNotNull(gran); Assert.assertSame(Granularity.MIN_20, gran); }
@Test public void fromString60m() { String s = "metrics_60m"; Granularity gran = Granularity.fromString(s); Assert.assertNotNull(gran); Assert.assertSame(Granularity.MIN_60, gran); }
@Test public void fromString240m() { String s = "metrics_240m"; Granularity gran = Granularity.fromString(s); Assert.assertSame(Granularity.MIN_240, gran); }
@Test public void fromString1440m() { String s = "metrics_1440m"; Granularity gran = Granularity.fromString(s); Assert.assertNotNull(gran); Assert.assertSame(Granularity.MIN_1440, gran); }
@Test public void fromStringOtherReturnsNull() { String s = "metrics_1990m"; Granularity gran = Granularity.fromString(s); Assert.assertNull(gran); }
@Test public void fromStringFullShortName() { String s = "full"; Granularity gran = Granularity.fromString(s); Assert.assertNotNull(gran); Assert.assertSame(Granularity.FULL, gran); }
@Test public void fromString5mShortName() { String s = "5m"; Granularity gran = Granularity.fromString(s); Assert.assertNotNull(gran); Assert.assertSame(Granularity.MIN_5, gran); }
@Test public void fromString20mShortName() { String s = "20m"; Granularity gran = Granularity.fromString(s); Assert.assertNotNull(gran); Assert.assertSame(Granularity.MIN_20, gran); }
@Test public void fromString60mShortName() { String s = "60m"; Granularity gran = Granularity.fromString(s); Assert.assertNotNull(gran); Assert.assertSame(Granularity.MIN_60, gran); }
@Test public void fromString240mShortName() { String s = "240m"; Granularity gran = Granularity.fromString(s); Assert.assertSame(Granularity.MIN_240, gran); }
@Test public void fromString1440mShortName() { String s = "1440m"; Granularity gran = Granularity.fromString(s); Assert.assertNotNull(gran); Assert.assertSame(Granularity.MIN_1440, gran); }
@Test public void fromStringCaseSensitive() { String s = "METRICS_1440M"; Granularity gran = Granularity.fromString(s); Assert.assertNull(gran); }
@Test public void fromStringNullReturnsNull() { Granularity gran = Granularity.fromString(null); Assert.assertNull(gran); } |
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); } | @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()); } } |
Granularity { public boolean isCoarser(Granularity other) { return indexOf(this) > indexOf(other); } 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; } | @Test public void coarserGranularitiesAreCoarserThanFinerOnes() { Assert.assertFalse(Granularity.FULL.isCoarser(Granularity.MIN_5)); Assert.assertFalse(Granularity.MIN_5.isCoarser(Granularity.MIN_20)); Assert.assertFalse(Granularity.MIN_20.isCoarser(Granularity.MIN_60)); Assert.assertFalse(Granularity.MIN_60.isCoarser(Granularity.MIN_240)); Assert.assertFalse(Granularity.MIN_240.isCoarser(Granularity.MIN_1440)); Assert.assertFalse(Granularity.FULL.isCoarser(Granularity.MIN_20)); Assert.assertFalse(Granularity.FULL.isCoarser(Granularity.MIN_60)); Assert.assertFalse(Granularity.FULL.isCoarser(Granularity.MIN_240)); Assert.assertFalse(Granularity.FULL.isCoarser(Granularity.MIN_1440)); Assert.assertFalse(Granularity.MIN_5.isCoarser(Granularity.MIN_60)); Assert.assertFalse(Granularity.MIN_5.isCoarser(Granularity.MIN_240)); Assert.assertFalse(Granularity.MIN_5.isCoarser(Granularity.MIN_1440)); Assert.assertFalse(Granularity.MIN_20.isCoarser(Granularity.MIN_240)); Assert.assertFalse(Granularity.MIN_20.isCoarser(Granularity.MIN_1440)); Assert.assertFalse(Granularity.MIN_60.isCoarser(Granularity.MIN_1440)); Assert.assertTrue(Granularity.MIN_5.isCoarser(Granularity.FULL)); Assert.assertTrue(Granularity.MIN_20.isCoarser(Granularity.MIN_5)); Assert.assertTrue(Granularity.MIN_60.isCoarser(Granularity.MIN_20)); Assert.assertTrue(Granularity.MIN_240.isCoarser(Granularity.MIN_60)); Assert.assertTrue(Granularity.MIN_1440.isCoarser(Granularity.MIN_240)); Assert.assertTrue(Granularity.MIN_20.isCoarser(Granularity.FULL)); Assert.assertTrue(Granularity.MIN_60.isCoarser(Granularity.FULL)); Assert.assertTrue(Granularity.MIN_60.isCoarser(Granularity.MIN_5)); Assert.assertTrue(Granularity.MIN_240.isCoarser(Granularity.FULL)); Assert.assertTrue(Granularity.MIN_240.isCoarser(Granularity.MIN_5)); Assert.assertTrue(Granularity.MIN_240.isCoarser(Granularity.MIN_20)); Assert.assertTrue(Granularity.MIN_1440.isCoarser(Granularity.FULL)); Assert.assertTrue(Granularity.MIN_1440.isCoarser(Granularity.MIN_5)); Assert.assertTrue(Granularity.MIN_1440.isCoarser(Granularity.MIN_20)); Assert.assertTrue(Granularity.MIN_1440.isCoarser(Granularity.MIN_60)); Assert.assertFalse(Granularity.FULL.isCoarser(Granularity.FULL)); Assert.assertFalse(Granularity.MIN_5.isCoarser(Granularity.MIN_5)); Assert.assertFalse(Granularity.MIN_20.isCoarser(Granularity.MIN_20)); Assert.assertFalse(Granularity.MIN_60.isCoarser(Granularity.MIN_60)); Assert.assertFalse(Granularity.MIN_240.isCoarser(Granularity.MIN_240)); Assert.assertFalse(Granularity.MIN_1440.isCoarser(Granularity.MIN_1440)); }
@Test(expected = NullPointerException.class) public void isCoarserWithNullThrowsException() { Assert.assertFalse(Granularity.FULL.isCoarser(null)); } |
Granularity { public long snapMillis(long millis) { if (this == FULL) return millis; else return (millis / milliseconds) * milliseconds; } 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; } | @Test public void snapMillisOnFullReturnsSameValue() { Assert.assertEquals(1234L, Granularity.FULL.snapMillis(1234L)); Assert.assertEquals(1000L, Granularity.FULL.snapMillis(1000L)); Assert.assertEquals(0L, Granularity.FULL.snapMillis(0L)); Assert.assertEquals(1234567L, Granularity.FULL.snapMillis(1234567L)); }
@Test public void snapMillisOnOtherReturnsSnappedValue() { Assert.assertEquals(0L, Granularity.MIN_5.snapMillis(1234L)); Assert.assertEquals(0L, Granularity.MIN_5.snapMillis(1000L)); Assert.assertEquals(0L, Granularity.MIN_5.snapMillis(0L)); Assert.assertEquals(0L, Granularity.MIN_5.snapMillis(299999L)); Assert.assertEquals(300000L, Granularity.MIN_5.snapMillis(300000L)); Assert.assertEquals(300000L, Granularity.MIN_5.snapMillis(300001L)); Assert.assertEquals(1200000L, Granularity.MIN_5.snapMillis(1234567L)); Assert.assertEquals(0L, Granularity.MIN_20.snapMillis(1234L)); Assert.assertEquals(0L, Granularity.MIN_20.snapMillis(1000L)); Assert.assertEquals(0L, Granularity.MIN_20.snapMillis(0L)); Assert.assertEquals(0L, Granularity.MIN_20.snapMillis(1199999L)); Assert.assertEquals(1200000L, Granularity.MIN_20.snapMillis(1200000)); Assert.assertEquals(1200000L, Granularity.MIN_20.snapMillis(1200001L)); Assert.assertEquals(1200000L, Granularity.MIN_20.snapMillis(1234567L)); Assert.assertEquals(0L, Granularity.MIN_60.snapMillis(1234L)); Assert.assertEquals(0L, Granularity.MIN_60.snapMillis(1000L)); Assert.assertEquals(0L, Granularity.MIN_60.snapMillis(0L)); Assert.assertEquals(0L, Granularity.MIN_60.snapMillis(3599999L)); Assert.assertEquals(3600000L, Granularity.MIN_60.snapMillis(3600000L)); Assert.assertEquals(3600000L, Granularity.MIN_60.snapMillis(3600001L)); Assert.assertEquals(122400000L, Granularity.MIN_60.snapMillis(123456789L)); Assert.assertEquals(0L, Granularity.MIN_240.snapMillis(1234L)); Assert.assertEquals(0L, Granularity.MIN_240.snapMillis(1000L)); Assert.assertEquals(0L, Granularity.MIN_240.snapMillis(0L)); Assert.assertEquals(0L, Granularity.MIN_240.snapMillis(14399999L)); Assert.assertEquals(14400000L, Granularity.MIN_240.snapMillis(14400000L)); Assert.assertEquals(14400000L, Granularity.MIN_240.snapMillis(14400001L)); Assert.assertEquals(115200000L, Granularity.MIN_240.snapMillis(123456789L)); Assert.assertEquals(0L, Granularity.MIN_1440.snapMillis(1234L)); Assert.assertEquals(0L, Granularity.MIN_1440.snapMillis(1000L)); Assert.assertEquals(0L, Granularity.MIN_1440.snapMillis(0L)); Assert.assertEquals(0L, Granularity.MIN_1440.snapMillis(86399999L)); Assert.assertEquals(86400000L, Granularity.MIN_1440.snapMillis(86400000L)); Assert.assertEquals(86400000L, Granularity.MIN_1440.snapMillis(86400001L)); Assert.assertEquals(86400000L, Granularity.MIN_1440.snapMillis(123456789L)); } |
Granularity { static int millisToSlot(long millis) { return (int)((millis % (BASE_SLOTS_PER_GRANULARITY * MILLISECONDS_IN_SLOT)) / MILLISECONDS_IN_SLOT); } 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; } | @Test public void millisToSlotReturnsNumberOfSlotForGivenTime() { Assert.assertEquals(0, Granularity.millisToSlot(0)); Assert.assertEquals(0, Granularity.millisToSlot(1)); Assert.assertEquals(0, Granularity.millisToSlot(299999L)); Assert.assertEquals(1, Granularity.millisToSlot(300000L)); Assert.assertEquals(1, Granularity.millisToSlot(300001L)); Assert.assertEquals(1, Granularity.millisToSlot(599999L)); Assert.assertEquals(2, Granularity.millisToSlot(600000L)); Assert.assertEquals(2, Granularity.millisToSlot(600001L)); Assert.assertEquals(4030, Granularity.millisToSlot(1209299999L)); Assert.assertEquals(4031, Granularity.millisToSlot(1209300000L)); Assert.assertEquals(4031, Granularity.millisToSlot(1209300001L)); Assert.assertEquals(4031, Granularity.millisToSlot(1209599999L)); Assert.assertEquals(0, Granularity.millisToSlot(1209600000L)); }
@Test public void millisToSlotWithNegativeReturnsNegative() { Assert.assertEquals(0, Granularity.millisToSlot(-0)); Assert.assertEquals(0, Granularity.millisToSlot(-1)); Assert.assertEquals(0, Granularity.millisToSlot(-299999L)); Assert.assertEquals(-1, Granularity.millisToSlot(-300000L)); Assert.assertEquals(-1, Granularity.millisToSlot(-300001L)); Assert.assertEquals(-1, Granularity.millisToSlot(-599999L)); Assert.assertEquals(-2, Granularity.millisToSlot(-600000L)); Assert.assertEquals(-2, Granularity.millisToSlot(-600001L)); Assert.assertEquals(-4030, Granularity.millisToSlot(-1209299999L)); Assert.assertEquals(-4031, Granularity.millisToSlot(-1209300000L)); Assert.assertEquals(-4031, Granularity.millisToSlot(-1209300001L)); Assert.assertEquals(-4031, Granularity.millisToSlot(-1209599999L)); Assert.assertEquals(0, Granularity.millisToSlot(-1209600000L)); } |
Granularity { public int slot(long millis) { int fullSlot = millisToSlot(millis); return (numSlots * fullSlot) / BASE_SLOTS_PER_GRANULARITY; } 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; } | @Test public void slotReturnsTheSlotNumber() { Assert.assertEquals(0, Granularity.FULL.slot(1234L)); Assert.assertEquals(0, Granularity.FULL.slot(1000L)); Assert.assertEquals(0, Granularity.FULL.slot(0L)); Assert.assertEquals(0, Granularity.FULL.slot(299999L)); Assert.assertEquals(1, Granularity.FULL.slot(300000L)); Assert.assertEquals(1, Granularity.FULL.slot(300001L)); Assert.assertEquals(4, Granularity.FULL.slot(1234567L)); Assert.assertEquals(4031, Granularity.FULL.slot(1209599999L)); Assert.assertEquals(0, Granularity.FULL.slot(1209600000L)); Assert.assertEquals(0, Granularity.FULL.slot(1209600001L)); Assert.assertEquals(0, Granularity.MIN_5.slot(1234L)); Assert.assertEquals(0, Granularity.MIN_5.slot(1000L)); Assert.assertEquals(0, Granularity.MIN_5.slot(0L)); Assert.assertEquals(0, Granularity.MIN_5.slot(299999L)); Assert.assertEquals(1, Granularity.MIN_5.slot(300000L)); Assert.assertEquals(1, Granularity.MIN_5.slot(300001L)); Assert.assertEquals(4, Granularity.MIN_5.slot(1234567L)); Assert.assertEquals(4031, Granularity.MIN_5.slot(1209599999L)); Assert.assertEquals(0, Granularity.MIN_5.slot(1209600000L)); Assert.assertEquals(0, Granularity.MIN_5.slot(1209600001L)); Assert.assertEquals(0, Granularity.MIN_20.slot(1234L)); Assert.assertEquals(0, Granularity.MIN_20.slot(1000L)); Assert.assertEquals(0, Granularity.MIN_20.slot(0L)); Assert.assertEquals(0, Granularity.MIN_20.slot(1199999L)); Assert.assertEquals(1, Granularity.MIN_20.slot(1200000)); Assert.assertEquals(1, Granularity.MIN_20.slot(1200001L)); Assert.assertEquals(1, Granularity.MIN_20.slot(1234567L)); Assert.assertEquals(102, Granularity.MIN_20.slot(123456789L)); Assert.assertEquals(1007, Granularity.MIN_20.slot(1209599999L)); Assert.assertEquals(0, Granularity.MIN_20.slot(1209600000L)); Assert.assertEquals(0, Granularity.MIN_20.slot(1209600001L)); Assert.assertEquals(0, Granularity.MIN_60.slot(1234L)); Assert.assertEquals(0, Granularity.MIN_60.slot(1000L)); Assert.assertEquals(0, Granularity.MIN_60.slot(0L)); Assert.assertEquals(0, Granularity.MIN_60.slot(3599999L)); Assert.assertEquals(1, Granularity.MIN_60.slot(3600000L)); Assert.assertEquals(1, Granularity.MIN_60.slot(3600001L)); Assert.assertEquals(34, Granularity.MIN_60.slot(123456789L)); Assert.assertEquals(69, Granularity.MIN_60.slot(12345678901L)); Assert.assertEquals(335, Granularity.MIN_60.slot(1209599999L)); Assert.assertEquals(0, Granularity.MIN_60.slot(1209600000L)); Assert.assertEquals(0, Granularity.MIN_60.slot(1209600001L)); Assert.assertEquals(0, Granularity.MIN_240.slot(1234L)); Assert.assertEquals(0, Granularity.MIN_240.slot(1000L)); Assert.assertEquals(0, Granularity.MIN_240.slot(0L)); Assert.assertEquals(0, Granularity.MIN_240.slot(14399999L)); Assert.assertEquals(1, Granularity.MIN_240.slot(14400000L)); Assert.assertEquals(1, Granularity.MIN_240.slot(14400001L)); Assert.assertEquals(8, Granularity.MIN_240.slot(123456789L)); Assert.assertEquals(17, Granularity.MIN_240.slot(12345678901L)); Assert.assertEquals(83, Granularity.MIN_240.slot(1209599999L)); Assert.assertEquals(0, Granularity.MIN_240.slot(1209600000L)); Assert.assertEquals(0, Granularity.MIN_240.slot(1209600001L)); Assert.assertEquals(0, Granularity.MIN_1440.slot(1234L)); Assert.assertEquals(0, Granularity.MIN_1440.slot(1000L)); Assert.assertEquals(0, Granularity.MIN_1440.slot(0L)); Assert.assertEquals(0, Granularity.MIN_1440.slot(86399999L)); Assert.assertEquals(1, Granularity.MIN_1440.slot(86400000L)); Assert.assertEquals(1, Granularity.MIN_1440.slot(86400001L)); Assert.assertEquals(2, Granularity.MIN_1440.slot(12345678901L)); Assert.assertEquals(13, Granularity.MIN_1440.slot(1209599999L)); Assert.assertEquals(0, Granularity.MIN_1440.slot(1209600000L)); Assert.assertEquals(0, Granularity.MIN_1440.slot(1209600001L)); } |
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); } | @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()); } |
Granularity { public Range deriveRange(int slot, long referenceMillis) { referenceMillis = snapMillis(referenceMillis); int refSlot = slot(referenceMillis); int slotDiff = slot > refSlot ? (numSlots() - slot + refSlot) : (refSlot - slot); long rangeStart = referenceMillis - slotDiff * milliseconds(); return new Range(rangeStart, rangeStart + milliseconds() - 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; } | @Test public void deriveRangeFiveMinuteFirstSlot() { Granularity gran = Granularity.MIN_5; Range range; range = gran.deriveRange(0, 0); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(299999, range.getStop()); range = gran.deriveRange(0, 1); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(299999, range.getStop()); range = gran.deriveRange(0, 299999); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(299999, range.getStop()); range = gran.deriveRange(0, 300000); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(299999, range.getStop()); range = gran.deriveRange(0, 300001); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(299999, range.getStop()); }
@Test public void deriveRangeFiveMinuteSecondSlot() { Granularity gran = Granularity.MIN_5; Range range; range = gran.deriveRange(1, 0); Assert.assertEquals(-1209300000, range.getStart()); Assert.assertEquals(-1209000001, range.getStop()); range = gran.deriveRange(1, 1); Assert.assertEquals(-1209300000, range.getStart()); Assert.assertEquals(-1209000001, range.getStop()); range = gran.deriveRange(1, 299999); Assert.assertEquals(-1209300000, range.getStart()); Assert.assertEquals(-1209000001, range.getStop()); range = gran.deriveRange(1, 300000); Assert.assertEquals(300000, range.getStart()); Assert.assertEquals(599999, range.getStop()); range = gran.deriveRange(1, 300001); Assert.assertEquals(300000, range.getStart()); Assert.assertEquals(599999, range.getStop()); range = gran.deriveRange(1, 599999); Assert.assertEquals(300000, range.getStart()); Assert.assertEquals(599999, range.getStop()); range = gran.deriveRange(1, 600000); Assert.assertEquals(300000, range.getStart()); Assert.assertEquals(599999, range.getStop()); range = gran.deriveRange(1, 600001); Assert.assertEquals(300000, range.getStart()); Assert.assertEquals(599999, range.getStop()); }
@Test public void deriveRangeFiveMinuteLastSlot() { Granularity gran = Granularity.MIN_5; Range range; range = gran.deriveRange(3, 0); Assert.assertEquals(-1208700000, range.getStart()); Assert.assertEquals(-1208400001, range.getStop()); range = gran.deriveRange(3, 1); Assert.assertEquals(-1208700000, range.getStart()); Assert.assertEquals(-1208400001, range.getStop()); range = gran.deriveRange(3, 899999); Assert.assertEquals(-1208700000, range.getStart()); Assert.assertEquals(-1208400001, range.getStop()); range = gran.deriveRange(3, 900000); Assert.assertEquals(900000, range.getStart()); Assert.assertEquals(1199999, range.getStop()); range = gran.deriveRange(3, 900001); Assert.assertEquals(900000, range.getStart()); Assert.assertEquals(1199999, range.getStop()); range = gran.deriveRange(3, 1199999); Assert.assertEquals(900000, range.getStart()); Assert.assertEquals(1199999, range.getStop()); range = gran.deriveRange(3, 1200000); Assert.assertEquals(900000, range.getStart()); Assert.assertEquals(1199999, range.getStop()); range = gran.deriveRange(3, 1200001); Assert.assertEquals(900000, range.getStart()); Assert.assertEquals(1199999, range.getStop()); }
@Test public void deriveRangeTwentyMinuteFirstSlot() { Granularity gran = Granularity.MIN_20; Range range; range = gran.deriveRange(0, 0); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(1199999, range.getStop()); range = gran.deriveRange(0, 1); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(1199999, range.getStop()); range = gran.deriveRange(0, 1199999); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(1199999, range.getStop()); range = gran.deriveRange(0, 1200000); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(1199999, range.getStop()); range = gran.deriveRange(0, 1200001); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(1199999, range.getStop()); }
@Test public void deriveRangeTwentyMinuteSecondSlot() { Granularity gran = Granularity.MIN_20; Range range; range = gran.deriveRange(1, 0); Assert.assertEquals(-1208400000, range.getStart()); Assert.assertEquals(-1207200001, range.getStop()); range = gran.deriveRange(1, 1); Assert.assertEquals(-1208400000, range.getStart()); Assert.assertEquals(-1207200001, range.getStop()); range = gran.deriveRange(1, 299999); Assert.assertEquals(-1208400000, range.getStart()); Assert.assertEquals(-1207200001, range.getStop()); range = gran.deriveRange(1, 1200000); Assert.assertEquals(1200000, range.getStart()); Assert.assertEquals(2399999, range.getStop()); range = gran.deriveRange(1, 1200001); Assert.assertEquals(1200000, range.getStart()); Assert.assertEquals(2399999, range.getStop()); range = gran.deriveRange(1, 2399999); Assert.assertEquals(1200000, range.getStart()); Assert.assertEquals(2399999, range.getStop()); range = gran.deriveRange(1, 2400000); Assert.assertEquals(1200000, range.getStart()); Assert.assertEquals(2399999, range.getStop()); range = gran.deriveRange(1, 2400001); Assert.assertEquals(1200000, range.getStart()); Assert.assertEquals(2399999, range.getStop()); }
@Test public void deriveRangeSixtyMinuteFirstSlot() { Granularity gran = Granularity.MIN_60; Range range; range = gran.deriveRange(0, 0); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(3599999, range.getStop()); range = gran.deriveRange(0, 1); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(3599999, range.getStop()); range = gran.deriveRange(0, 3599999); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(3599999, range.getStop()); range = gran.deriveRange(0, 3600000); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(3599999, range.getStop()); range = gran.deriveRange(0, 3600001); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(3599999, range.getStop()); }
@Test public void deriveRangeSixtyMinuteSecondSlot() { Granularity gran = Granularity.MIN_60; Range range; range = gran.deriveRange(1, 0); Assert.assertEquals(-1206000000, range.getStart()); Assert.assertEquals(-1202400001, range.getStop()); range = gran.deriveRange(1, 1); Assert.assertEquals(-1206000000, range.getStart()); Assert.assertEquals(-1202400001, range.getStop()); range = gran.deriveRange(1, 899999); Assert.assertEquals(-1206000000, range.getStart()); Assert.assertEquals(-1202400001, range.getStop()); range = gran.deriveRange(1, 3600000); Assert.assertEquals(3600000, range.getStart()); Assert.assertEquals(7199999, range.getStop()); range = gran.deriveRange(1, 3600001); Assert.assertEquals(3600000, range.getStart()); Assert.assertEquals(7199999, range.getStop()); range = gran.deriveRange(1, 7199999); Assert.assertEquals(3600000, range.getStart()); Assert.assertEquals(7199999, range.getStop()); range = gran.deriveRange(1, 7200000); Assert.assertEquals(3600000, range.getStart()); Assert.assertEquals(7199999, range.getStop()); range = gran.deriveRange(1, 7200001); Assert.assertEquals(3600000, range.getStart()); Assert.assertEquals(7199999, range.getStop()); }
@Test public void deriveRange240MinuteFirstSlot() { Granularity gran = Granularity.MIN_240; Range range; range = gran.deriveRange(0, 0); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(14399999, range.getStop()); range = gran.deriveRange(0, 1); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(14399999, range.getStop()); range = gran.deriveRange(0, 14399999); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(14399999, range.getStop()); range = gran.deriveRange(0, 14400000); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(14399999, range.getStop()); range = gran.deriveRange(0, 14400001); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(14399999, range.getStop()); }
@Test public void deriveRange240MinuteSecondSlot() { Granularity gran = Granularity.MIN_240; Range range; range = gran.deriveRange(1, 0); Assert.assertEquals(-1195200000, range.getStart()); Assert.assertEquals(-1180800001, range.getStop()); range = gran.deriveRange(1, 1); Assert.assertEquals(-1195200000, range.getStart()); Assert.assertEquals(-1180800001, range.getStop()); range = gran.deriveRange(1, 14399999); Assert.assertEquals(-1195200000, range.getStart()); Assert.assertEquals(-1180800001, range.getStop()); range = gran.deriveRange(1, 14400000); Assert.assertEquals(14400000, range.getStart()); Assert.assertEquals(28799999, range.getStop()); range = gran.deriveRange(1, 14400001); Assert.assertEquals(14400000, range.getStart()); Assert.assertEquals(28799999, range.getStop()); range = gran.deriveRange(1, 28799999); Assert.assertEquals(14400000, range.getStart()); Assert.assertEquals(28799999, range.getStop()); range = gran.deriveRange(1, 28800000); Assert.assertEquals(14400000, range.getStart()); Assert.assertEquals(28799999, range.getStop()); range = gran.deriveRange(1, 28800001); Assert.assertEquals(14400000, range.getStart()); Assert.assertEquals(28799999, range.getStop()); }
@Test public void deriveRange1440MinuteFirstSlot() { Granularity gran = Granularity.MIN_1440; Range range; range = gran.deriveRange(0, 0); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(86399999, range.getStop()); range = gran.deriveRange(0, 1); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(86399999, range.getStop()); range = gran.deriveRange(0, 86399999); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(86399999, range.getStop()); range = gran.deriveRange(0, 86400000); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(86399999, range.getStop()); range = gran.deriveRange(0, 86400001); Assert.assertEquals(0, range.getStart()); Assert.assertEquals(86399999, range.getStop()); }
@Test public void deriveRange1440MinuteSecondSlot() { Granularity gran = Granularity.MIN_1440; Range range; range = gran.deriveRange(1, 0); Assert.assertEquals(-1123200000, range.getStart()); Assert.assertEquals(-1036800001, range.getStop()); range = gran.deriveRange(1, 1); Assert.assertEquals(-1123200000, range.getStart()); Assert.assertEquals(-1036800001, range.getStop()); range = gran.deriveRange(1, 86399999); Assert.assertEquals(-1123200000, range.getStart()); Assert.assertEquals(-1036800001, range.getStop()); range = gran.deriveRange(1, 86400000); Assert.assertEquals(86400000, range.getStart()); Assert.assertEquals(172799999, range.getStop()); range = gran.deriveRange(1, 86400001); Assert.assertEquals(86400000, range.getStart()); Assert.assertEquals(172799999, range.getStop()); range = gran.deriveRange(1, 172799999); Assert.assertEquals(86400000, range.getStart()); Assert.assertEquals(172799999, range.getStop()); range = gran.deriveRange(1, 172800000); Assert.assertEquals(86400000, range.getStart()); Assert.assertEquals(172799999, range.getStop()); range = gran.deriveRange(1, 172800001); Assert.assertEquals(86400000, range.getStart()); Assert.assertEquals(172799999, range.getStop()); } |
BatchWriter extends FunctionWithThreadPool<List<List<IMetric>>, ListenableFuture<List<Boolean>>> { @Override public ListenableFuture<List<Boolean>> apply(List<List<IMetric>> input) throws Exception { final long writeStartTime = System.currentTimeMillis(); final Timer.Context actualWriteCtx = writeDurationTimer.time(); final List<ListenableFuture<Boolean>> resultFutures = new ArrayList<ListenableFuture<Boolean>>(); for (List<IMetric> metrics: input) { final int batchId = batchIdGenerator.next(); final List<IMetric> batch = metrics; ListenableFuture<Boolean> futureBatchResult = getThreadPool().submit(new Callable<Boolean>() { public Boolean call() throws Exception { final Timer.Context singleBatchWriteCtx = batchWriteDurationTimer.time(); try { metricsRWDelegator.insertMetrics(batch); final Timer.Context dirtyTimerCtx = slotUpdateTimer.time(); try { for (IMetric metric : batch) { context.update(metric.getCollectionTime(), Util.getShard(metric.getLocator().toString())); } } finally { dirtyTimerCtx.stop(); } return true; } catch (Exception ex) { getLogger().error(ex.getMessage(), ex); getLogger().warn("Did not persist all metrics successfully for batch " + batchId); if ( getLogger().isDebugEnabled() ) { List<String> failedLocators = new ArrayList<String>() {{ for (IMetric metric : batch) { add(metric.getLocator().toString()); } }}; getLogger().debug("Failed batch contains: " + Arrays.toString(failedLocators.toArray())); } return false; } finally { singleBatchWriteCtx.stop(); bufferedMetrics.dec(batch.size()); long now = System.currentTimeMillis(); if ( now - writeStartTime > timeout.toMillis()) { exceededScribeProcessingTime.mark(); getLogger().debug( String.format("Batch write time %d (ms) exceeded timeout %s before persisting " + "all metrics for batch %d", now - writeStartTime, timeout.toString(), batchId)); } } } }); resultFutures.add(futureBatchResult); } ListenableFuture<List<Boolean>> finalFuture = Futures.allAsList(resultFutures); finalFuture.addListener(new Runnable() { @Override public void run() { actualWriteCtx.stop(); } }, MoreExecutors.sameThreadExecutor()); return finalFuture; } BatchWriter(ThreadPoolExecutor threadPool, TimeValue timeout, Counter bufferedMetrics, IngestionContext context); @VisibleForTesting BatchWriter(ThreadPoolExecutor threadPool,
TimeValue timeout, Counter bufferedMetrics,
IngestionContext context,
MetricsRWDelegator metricsRWDelegator); @Override ListenableFuture<List<Boolean>> apply(List<List<IMetric>> input); } | @Test public void testWriter() throws Exception { Counter bufferedMetrics = mock(Counter.class); IngestionContext context = mock(IngestionContext.class); AbstractMetricsRW basicRW = mock(AbstractMetricsRW.class); AbstractMetricsRW preAggrRW = mock(AbstractMetricsRW.class); MetricsRWDelegator metricsRWDelegator = new MetricsRWDelegator(basicRW, preAggrRW); List<List<IMetric>> testdata = createTestData(Metric.class); List<List<IMetric>> pTestdata = createTestData(PreaggregatedMetric.class); List<List<IMetric>> allTestdata = new ArrayList<List<IMetric>>(); allTestdata.addAll(testdata); allTestdata.addAll(pTestdata); BatchWriter batchWriter = new BatchWriter( new ThreadPoolBuilder().build(), timeout, bufferedMetrics, context, metricsRWDelegator ); ListenableFuture<List<Boolean>> futures = batchWriter.apply(allTestdata); List<Boolean> persisteds = futures.get(timeout.getValue(), timeout.getUnit()); Assert.assertTrue(persisteds.size() == (NUM_LISTS * 2)); for (Boolean batchStatus : persisteds) { Assert.assertTrue(batchStatus); } for (List<IMetric> l : testdata) { verify(basicRW).insertMetrics((List<IMetric>)(List<?>)l); } for (List<IMetric> l : pTestdata) { verify(preAggrRW).insertMetrics(l); } for (List<IMetric> l : allTestdata) { Assert.assertTrue(l.size() == METRICS_PER_LIST); for (IMetric m : l) { verify(context).update(m.getCollectionTime(), Util.getShard(m.getLocator().toString())); } } } |
Granularity { public int slotFromFinerSlot(int finerSlot) throws GranularityException { return (finerSlot * numSlots()) / this.finer().numSlots(); } 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; } | @Test public void slotFromFiner() throws GranularityException { Assert.assertEquals(0, Granularity.MIN_5.slotFromFinerSlot(0)); Assert.assertEquals(1, Granularity.MIN_5.slotFromFinerSlot(1)); Assert.assertEquals(4031, Granularity.MIN_5.slotFromFinerSlot(4031)); Assert.assertEquals(4032, Granularity.MIN_5.slotFromFinerSlot(4032)); Assert.assertEquals(0, Granularity.MIN_20.slotFromFinerSlot(0)); Assert.assertEquals(0, Granularity.MIN_20.slotFromFinerSlot(1)); Assert.assertEquals(0, Granularity.MIN_20.slotFromFinerSlot(2)); Assert.assertEquals(0, Granularity.MIN_20.slotFromFinerSlot(3)); Assert.assertEquals(1, Granularity.MIN_20.slotFromFinerSlot(4)); Assert.assertEquals(1006, Granularity.MIN_20.slotFromFinerSlot(4027)); Assert.assertEquals(1007, Granularity.MIN_20.slotFromFinerSlot(4028)); Assert.assertEquals(1007, Granularity.MIN_20.slotFromFinerSlot(4029)); Assert.assertEquals(1007, Granularity.MIN_20.slotFromFinerSlot(4030)); Assert.assertEquals(1007, Granularity.MIN_20.slotFromFinerSlot(4031)); Assert.assertEquals(1008, Granularity.MIN_20.slotFromFinerSlot(4032)); Assert.assertEquals(0, Granularity.MIN_60.slotFromFinerSlot(0)); Assert.assertEquals(0, Granularity.MIN_60.slotFromFinerSlot(1)); Assert.assertEquals(0, Granularity.MIN_60.slotFromFinerSlot(2)); Assert.assertEquals(1, Granularity.MIN_60.slotFromFinerSlot(3)); Assert.assertEquals(1, Granularity.MIN_60.slotFromFinerSlot(4)); Assert.assertEquals(1, Granularity.MIN_60.slotFromFinerSlot(5)); Assert.assertEquals(2, Granularity.MIN_60.slotFromFinerSlot(6)); Assert.assertEquals(333, Granularity.MIN_60.slotFromFinerSlot(1001)); Assert.assertEquals(334, Granularity.MIN_60.slotFromFinerSlot(1002)); Assert.assertEquals(334, Granularity.MIN_60.slotFromFinerSlot(1003)); Assert.assertEquals(334, Granularity.MIN_60.slotFromFinerSlot(1004)); Assert.assertEquals(335, Granularity.MIN_60.slotFromFinerSlot(1005)); Assert.assertEquals(335, Granularity.MIN_60.slotFromFinerSlot(1006)); Assert.assertEquals(335, Granularity.MIN_60.slotFromFinerSlot(1007)); Assert.assertEquals(336, Granularity.MIN_60.slotFromFinerSlot(1008)); Assert.assertEquals(0, Granularity.MIN_240.slotFromFinerSlot(0)); Assert.assertEquals(0, Granularity.MIN_240.slotFromFinerSlot(1)); Assert.assertEquals(0, Granularity.MIN_240.slotFromFinerSlot(2)); Assert.assertEquals(0, Granularity.MIN_240.slotFromFinerSlot(3)); Assert.assertEquals(1, Granularity.MIN_240.slotFromFinerSlot(4)); Assert.assertEquals(1, Granularity.MIN_240.slotFromFinerSlot(5)); Assert.assertEquals(1, Granularity.MIN_240.slotFromFinerSlot(6)); Assert.assertEquals(1, Granularity.MIN_240.slotFromFinerSlot(7)); Assert.assertEquals(2, Granularity.MIN_240.slotFromFinerSlot(8)); Assert.assertEquals(81, Granularity.MIN_240.slotFromFinerSlot(327)); Assert.assertEquals(82, Granularity.MIN_240.slotFromFinerSlot(328)); Assert.assertEquals(82, Granularity.MIN_240.slotFromFinerSlot(329)); Assert.assertEquals(82, Granularity.MIN_240.slotFromFinerSlot(330)); Assert.assertEquals(82, Granularity.MIN_240.slotFromFinerSlot(331)); Assert.assertEquals(83, Granularity.MIN_240.slotFromFinerSlot(332)); Assert.assertEquals(83, Granularity.MIN_240.slotFromFinerSlot(333)); Assert.assertEquals(83, Granularity.MIN_240.slotFromFinerSlot(334)); Assert.assertEquals(83, Granularity.MIN_240.slotFromFinerSlot(335)); Assert.assertEquals(84, Granularity.MIN_240.slotFromFinerSlot(336)); Assert.assertEquals(0, Granularity.MIN_1440.slotFromFinerSlot(0)); Assert.assertEquals(0, Granularity.MIN_1440.slotFromFinerSlot(1)); Assert.assertEquals(0, Granularity.MIN_1440.slotFromFinerSlot(2)); Assert.assertEquals(0, Granularity.MIN_1440.slotFromFinerSlot(3)); Assert.assertEquals(0, Granularity.MIN_1440.slotFromFinerSlot(4)); Assert.assertEquals(0, Granularity.MIN_1440.slotFromFinerSlot(5)); Assert.assertEquals(1, Granularity.MIN_1440.slotFromFinerSlot(6)); Assert.assertEquals(12, Granularity.MIN_1440.slotFromFinerSlot(77)); Assert.assertEquals(13, Granularity.MIN_1440.slotFromFinerSlot(78)); Assert.assertEquals(13, Granularity.MIN_1440.slotFromFinerSlot(79)); Assert.assertEquals(13, Granularity.MIN_1440.slotFromFinerSlot(80)); Assert.assertEquals(13, Granularity.MIN_1440.slotFromFinerSlot(81)); Assert.assertEquals(13, Granularity.MIN_1440.slotFromFinerSlot(82)); Assert.assertEquals(13, Granularity.MIN_1440.slotFromFinerSlot(83)); Assert.assertEquals(14, Granularity.MIN_1440.slotFromFinerSlot(84)); }
@Test(expected = GranularityException.class) public void slotFromFinerWithFullThrowsException() throws GranularityException { Granularity.FULL.slotFromFinerSlot(0); }
@Test public void slotFromFinerDoesNotWrap() throws GranularityException { Assert.assertEquals(4031, Granularity.MIN_20.slotFromFinerSlot(16124)); Assert.assertEquals(4031, Granularity.MIN_20.slotFromFinerSlot(16125)); Assert.assertEquals(4031, Granularity.MIN_20.slotFromFinerSlot(16126)); Assert.assertEquals(4031, Granularity.MIN_20.slotFromFinerSlot(16127)); Assert.assertEquals(4032, Granularity.MIN_20.slotFromFinerSlot(16128)); } |
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); } | @Test public void pollSchedulesEligibleSlots() { service.poll(); verify(context).scheduleEligibleSlots(anyLong(), anyLong(), anyLong()); verifyNoMoreInteractions(context); verifyZeroInteractions(shardStateManager); verifyZeroInteractions(locatorFetchExecutors); verifyZeroInteractions(rollupReadExecutors); verifyZeroInteractions(rollupWriteExecutors); } |
SlotKey { public SlotKey extrapolate(Granularity destGranularity) { if (destGranularity.equals(this.getGranularity())) { return this; } if (!destGranularity.isCoarser(getGranularity())) { throw new IllegalArgumentException("Destination granularity must be coarser than the current granularity"); } int factor = getGranularity().numSlots() / destGranularity.numSlots(); int parentSlot = getSlot() / factor; return SlotKey.of(destGranularity, parentSlot, getShard()); } private SlotKey(Granularity granularity, int slot, int shard); int getShard(); int getSlot(); Granularity getGranularity(); static SlotKey of(Granularity granularity, int slot, int shard); static SlotKey parse(String string); Collection<SlotKey> getChildrenKeys(); Collection<SlotKey> getChildrenKeys(Granularity destGranularity); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); SlotKey extrapolate(Granularity destGranularity); } | @Test public void testExtrapolate() { int shard = 1; assertEquals("Invalid extrapolation - scenario 0", SlotKey.of(Granularity.MIN_5, 1, shard), SlotKey.of(Granularity.FULL, 1, shard).extrapolate(Granularity.MIN_5)); assertEquals("Invalid extrapolation - scenario 1", SlotKey.of(Granularity.MIN_5, 43, shard), SlotKey.of(Granularity.FULL, 43, shard).extrapolate(Granularity.MIN_5)); assertEquals("Invalid extrapolation - scenario 2", SlotKey.of(Granularity.MIN_5, 24, shard), SlotKey.of(Granularity.MIN_5, 24, shard).extrapolate(Granularity.MIN_5)); assertEquals("Invalid extrapolation - scenario 3", SlotKey.of(Granularity.MIN_20, 0, shard), SlotKey.of(Granularity.MIN_5, 0, shard).extrapolate(Granularity.MIN_20)); assertEquals("Invalid extrapolation - scenario 4", SlotKey.of(Granularity.MIN_20, 0, shard), SlotKey.of(Granularity.MIN_5, 3, shard).extrapolate(Granularity.MIN_20)); assertEquals("Invalid extrapolation - scenario 5", SlotKey.of(Granularity.MIN_20, 1, shard), SlotKey.of(Granularity.MIN_5, 4, shard).extrapolate(Granularity.MIN_20)); assertEquals("Invalid extrapolation - scenario 6", SlotKey.of(Granularity.MIN_20, 4032 / 4 - 1, shard), SlotKey.of(Granularity.MIN_5, 4031, shard).extrapolate(Granularity.MIN_20)); assertEquals("Invalid extrapolation - scenario 7", SlotKey.of(Granularity.MIN_60, 0, shard), SlotKey.of(Granularity.MIN_5, 3, shard).extrapolate(Granularity.MIN_60)); assertEquals("Invalid extrapolation - scenario 8", SlotKey.of(Granularity.MIN_60, 0, shard), SlotKey.of(Granularity.MIN_5, 3, shard).extrapolate(Granularity.MIN_60)); assertEquals("Invalid extrapolation - scenario 9", SlotKey.of(Granularity.MIN_60, 1, shard), SlotKey.of(Granularity.MIN_5, 12, shard).extrapolate(Granularity.MIN_60)); assertEquals("Invalid extrapolation - scenario 10", SlotKey.of(Granularity.MIN_60, 4032 / 12 - 1, shard), SlotKey.of(Granularity.MIN_5, 4031, shard).extrapolate(Granularity.MIN_60)); assertEquals("Invalid extrapolation - scenario 11", SlotKey.of(Granularity.MIN_1440, 0, shard), SlotKey.of(Granularity.MIN_5, 3, shard).extrapolate(Granularity.MIN_1440)); assertEquals("Invalid extrapolation - scenario 12", SlotKey.of(Granularity.MIN_1440, 0, shard), SlotKey.of(Granularity.MIN_5, 287, shard).extrapolate(Granularity.MIN_1440)); assertEquals("Invalid extrapolation - scenario 13", SlotKey.of(Granularity.MIN_1440, 1, shard), SlotKey.of(Granularity.MIN_5, 288, shard).extrapolate(Granularity.MIN_1440)); assertEquals("Invalid extrapolation - scenario 14", SlotKey.of(Granularity.MIN_60, 0, shard), SlotKey.of(Granularity.MIN_20, 1, shard).extrapolate(Granularity.MIN_60)); assertEquals("Invalid extrapolation - scenario 15", SlotKey.of(Granularity.MIN_60, 0, shard), SlotKey.of(Granularity.MIN_20, 2, shard).extrapolate(Granularity.MIN_60)); assertEquals("Invalid extrapolation - scenario 16", SlotKey.of(Granularity.MIN_60, 1, shard), SlotKey.of(Granularity.MIN_20, 3, shard).extrapolate(Granularity.MIN_60)); } |
ModuleLoader { public static Object getInstance(Class c, CoreConfig moduleName) { Object moduleInstance = loadedModules.get(moduleName.name().toString()); if (moduleInstance != null) return moduleInstance; List<String> modules = Configuration.getInstance().getListProperty(moduleName); if (modules.isEmpty()) return null; if (modules.size() != 1) { throw new RuntimeException("Cannot load service with more than one "+moduleName+" module"); } String module = modules.get(0); log.info("Loading the module " + module); try { ClassLoader loader = c.getClassLoader(); Class genericClass = loader.loadClass(module); moduleInstance = genericClass.newInstance(); loadedModules.put(moduleName.name().toString(), moduleInstance); log.info("Registering the module " + module); } catch (InstantiationException e) { log.error(String.format("Unable to create instance of %s class for %s", c.getName(), module), e); } catch (IllegalAccessException e) { log.error("Error starting module: " + module, e); } catch (ClassNotFoundException e) { log.error("Unable to locate module: " + module, e); } catch (RuntimeException e) { log.error("Error starting module: " + module, e); } catch (Throwable e) { log.error("Error starting module: " + module, e); } return moduleInstance; } static Object getInstance(Class c, CoreConfig moduleName); @VisibleForTesting static void clearCache(); } | @Test public void singleClassYieldsThatClass() { Configuration.getInstance().setProperty( CoreConfig.DISCOVERY_MODULES, "com.rackspacecloud.blueflood.utils.DummyDiscoveryIO3"); Object loadedModule = ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); Assert.assertNotNull(loadedModule); Assert.assertEquals(DummyDiscoveryIO3.class, loadedModule.getClass()); }
@Test public void singleClassInDifferentPackageYieldsThatClass() { Configuration.getInstance().setProperty( CoreConfig.DISCOVERY_MODULES, "com.rackspacecloud.blueflood.io.DummyDiscoveryIO"); Object loadedModule = ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); Assert.assertNotNull(loadedModule); Assert.assertEquals(DummyDiscoveryIO.class, loadedModule.getClass()); }
@Test public void emptyStringYieldsNull() { Configuration.getInstance().setProperty(CoreConfig.DISCOVERY_MODULES, ""); Object loadedModule = ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); Assert.assertNull(loadedModule); }
@Test(expected=RuntimeException.class) public void multipleClassesCauseAnException() { Configuration.getInstance().setProperty( CoreConfig.DISCOVERY_MODULES, "com.rackspacecloud.blueflood.io.DummyDiscoveryIO,com.rackspacecloud.blueflood.io.DummyDiscoveryIO2"); Object loadedModule = ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); }
@Test public void nonExistentClassYieldsNull() { Configuration.getInstance().setProperty( CoreConfig.DISCOVERY_MODULES, "com.rackspacecloud.blueflood.NonExistentClass"); Object loadedModule = ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); Assert.assertNull(loadedModule); }
@Test public void callingTwiceYieldsTheSameObjectBothTimes() { Configuration.getInstance().setProperty( CoreConfig.DISCOVERY_MODULES, "com.rackspacecloud.blueflood.io.DummyDiscoveryIO"); Object loadedModule1 = ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); Assert.assertNotNull(loadedModule1); Assert.assertEquals(DummyDiscoveryIO.class, loadedModule1.getClass()); Object loadedModule2 = ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); Assert.assertNotNull(loadedModule2); Assert.assertSame(loadedModule1, loadedModule2); }
@Test public void givingDifferentKeysButSameClassYieldsTwoSeparateObjects() { Configuration.getInstance().setProperty( CoreConfig.DISCOVERY_MODULES, "com.rackspacecloud.blueflood.io.DummyDiscoveryIO"); Object loadedModule1 = ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); Assert.assertNotNull(loadedModule1); Assert.assertEquals(DummyDiscoveryIO.class, loadedModule1.getClass()); Assert.assertEquals(DummyDiscoveryIO.class, loadedModule1.getClass()); }
@Test public void callingTwiceWithSameKeyButDifferentClassesYieldsTheSameObjectBothTimes() { Configuration.getInstance().setProperty( CoreConfig.DISCOVERY_MODULES, "com.rackspacecloud.blueflood.io.DummyDiscoveryIO"); Object loadedModule1 = ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); Assert.assertNotNull(loadedModule1); Assert.assertEquals(DummyDiscoveryIO.class, loadedModule1.getClass()); Configuration.getInstance().setProperty( CoreConfig.DISCOVERY_MODULES, "com.rackspacecloud.blueflood.io.DummyDiscoveryIO2"); Object loadedModule2 = ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); Assert.assertNotNull(loadedModule2); Assert.assertSame(loadedModule1, loadedModule2); }
@Test public void specifyingAnInterfaceYieldsNull() { Configuration.getInstance().setProperty( CoreConfig.DISCOVERY_MODULES, "com.rackspacecloud.blueflood.io.DiscoveryIO"); Object loadedModule = ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); Assert.assertNull(loadedModule); }
@Test public void classWithNoParameterlessConstructorYieldsNull() { Configuration.getInstance().setProperty( CoreConfig.DISCOVERY_MODULES, "com.rackspacecloud.blueflood.io.DummyDiscoveryIO4"); Object loadedModule = ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); Assert.assertNull(loadedModule); }
@Test public void packagePrivateClassYieldsNull() { Configuration.getInstance().setProperty( CoreConfig.DISCOVERY_MODULES, "com.rackspacecloud.blueflood.io.DummyDiscoveryIO5"); Object loadedModule = ModuleLoader.getInstance(DiscoveryIO.class, CoreConfig.DISCOVERY_MODULES); Assert.assertNull(loadedModule); } |
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); } | @Test public void setServerTimeSetsContextTime() { service.setServerTime(1234L); verify(context).setCurrentTimeMillis(anyLong()); verifyNoMoreInteractions(context); verifyZeroInteractions(shardStateManager); verifyZeroInteractions(locatorFetchExecutors); verifyZeroInteractions(rollupReadExecutors); verifyZeroInteractions(rollupWriteExecutors); } |
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); } | @Test public void testSlotFromSlotKey() { int expectedSlot = 1; int slot = SlotKeySerDes.slotFromSlotKey(SlotKey.of(Granularity.MIN_5, expectedSlot, 10).toString()); Assert.assertEquals(expectedSlot, slot); } |
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(); } | @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()); } |
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); } | @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); } |
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); } | @Test public void testAlwaysPresent() { Assert.assertTrue(ttlProvider.getTTL("test", Granularity.FULL, RollupType.NOT_A_ROLLUP).isPresent()); } |
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(); } | @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)); } |
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(); } | @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)); } |
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(); } | @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)); } |
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(); } | @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)); } |
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); } | @Test public void getKeepingServerTimeGetsKeepingServerTime() { assertEquals(true, service.getKeepingServerTime()); } |
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(); } | @Test public void testConfigTtl_invalid() { Assert.assertFalse(ttlProvider.getTTL("acBar", Granularity.FULL, RollupType.SET).isPresent()); } |
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); } | @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()); } |
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); } | @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); } } |
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; } | @Test public void publicConstructorDoesNotSetStringRepresentation() { Locator locator = new Locator(); assertNotNull(locator); assertNull(locator.toString()); } |
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; } | @Test public void publicConstructorDoesNotSetTenant() { Locator locator = new Locator(); assertNotNull(locator); assertNull(locator.getTenantId()); } |
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; } | @Test public void publicConstructorDoesNotSetMetricName() { Locator locator = new Locator(); assertNotNull(locator); assertNull(locator.getMetricName()); } |
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; } | @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.")); } |
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); } | @Test public void getPollerPeriodGetsPollerPeriod() { assertEquals(0, service.getPollerPeriod()); } |
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; } | @Test public void hashCodeNullReturnsZero() { Locator locator = new Locator(); assertEquals(0, locator.hashCode()); } |
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; } | @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)); } |
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(); } | @Test(expected=IllegalStateException.class) public void getDataClassOnEmptyObjectThrowsException() { Points<SimpleNumber> points = new Points<SimpleNumber>(); Class actual = points.getDataClass(); } |
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); } | @Test public void newlyCreatedObjectIsNotFloatingPoint() { SimpleStat stat = new SimpleStat(); assertFalse(stat.isFloatingPoint()); } |
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); } | @Test public void getScheduledSlotCheckCountGetsCount() { int expected = 3; doReturn(expected).when(context).getScheduledCount(); int actual = service.getScheduledSlotCheckCount(); assertEquals(expected, actual); verify(context).getScheduledCount(); verifyNoMoreInteractions(context); } |
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); } | @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)); } |
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); } | @Test public void testGetSlotCheckConcurrency() { int expected = 12; doReturn(expected).when(locatorFetchExecutors).getMaximumPoolSize(); int actual = service.getSlotCheckConcurrency(); assertEquals(expected, actual); verify(locatorFetchExecutors).getMaximumPoolSize(); verifyNoMoreInteractions(locatorFetchExecutors); } |
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(); } | @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 ); } |
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(); } | @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 ); } |
MinValue extends AbstractRollupStat { @Override void handleFullResMetric(Object o) throws RuntimeException { if (o instanceof Double) { if (init) { this.setDoubleValue((Double)o); this.init = false; return; } if (!this.isFloatingPoint()) { if ((double)this.toLong() > (Double)o) { this.setDoubleValue((Double)o); } } else { this.setDoubleValue(Math.min(this.toDouble(), (Double)o)); } } else if (o instanceof Long || o instanceof Integer) { Long val; if (o instanceof Integer) { val = ((Integer)o).longValue(); } else { val = (Long)o; } if (init) { this.setLongValue(val); this.init = false; return; } if (this.isFloatingPoint()) { double doubleValOther = val.doubleValue(); if (this.toDouble()> doubleValOther) { this.setLongValue(val); } } else { this.setLongValue(Math.min(this.toLong(), val)); } } else { throw new RuntimeException("Unsuppored type " + o.getClass().getName() +" for min"); } } MinValue(); @SuppressWarnings("unused") // used by Jackson MinValue(long value); @SuppressWarnings("unused") // used by Jackson MinValue(double value); @Override byte getStatType(); } | @Test public void fullResInitialDoubleSetsValue() { min.handleFullResMetric(123.45d); assertTrue(min.isFloatingPoint()); assertEquals(123.45d, min.toDouble(), 0.00001d); }
@Test public void fullResInitialLongSetsValue() { min.handleFullResMetric(123L); assertFalse(min.isFloatingPoint()); assertEquals(123L, min.toLong()); }
@Test public void fullResInitialIntegerSetsValue() { min.handleFullResMetric((int)123); assertFalse(min.isFloatingPoint()); assertEquals(123L, min.toLong()); }
@Test(expected = RuntimeException.class) public void fullResInitialFloatThrowsException() { min.handleFullResMetric(123f); }
@Test public void fullResInitialDoubleThenLesserDouble() { min.handleFullResMetric(123.45d); min.handleFullResMetric(122.45d); assertTrue(min.isFloatingPoint()); assertEquals(122.45d, min.toDouble(), 0.00001d); }
@Test public void fullResInitialDoubleThenGreaterDouble() { min.handleFullResMetric(123.45d); min.handleFullResMetric(124.45d); assertTrue(min.isFloatingPoint()); assertEquals(123.45d, min.toDouble(), 0.00001d); }
@Test public void fullResInitialDoubleThenLesserLong() { min.handleFullResMetric(123.45d); min.handleFullResMetric(122L); assertFalse(min.isFloatingPoint()); assertEquals(122L, min.toLong()); }
@Test public void fullResInitialDoubleThenGreaterLong() { min.handleFullResMetric(123.45d); min.handleFullResMetric(124L); assertTrue(min.isFloatingPoint()); assertEquals(123.45d, min.toDouble(), 0.00001d); }
@Test public void fullResInitialLongThenLesserDouble() { min.handleFullResMetric(123L); min.handleFullResMetric(122.45d); assertTrue(min.isFloatingPoint()); assertEquals(122.45d, min.toDouble(), 0.00001d); }
@Test public void fullResInitialLongThenGreaterDouble() { min.handleFullResMetric(123L); min.handleFullResMetric(124.45d); assertFalse(min.isFloatingPoint()); assertEquals(123L, min.toLong()); }
@Test public void fullResInitialLongThenLesserLong() { min.handleFullResMetric(123L); min.handleFullResMetric(122L); assertFalse(min.isFloatingPoint()); assertEquals(122L, min.toLong()); }
@Test public void fullResInitialLongThenGreaterLong() { min.handleFullResMetric(123L); min.handleFullResMetric(124L); assertFalse(min.isFloatingPoint()); assertEquals(123L, min.toLong()); } |
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); } | @Test public void testSetSlotCheckConcurrency() { service.setSlotCheckConcurrency(3); verify(locatorFetchExecutors).setCorePoolSize(anyInt()); verify(locatorFetchExecutors).setMaximumPoolSize(anyInt()); verifyNoMoreInteractions(locatorFetchExecutors); } |
MinValue extends AbstractRollupStat { @Override void handleRollupMetric(IBaseRollup baseRollup) throws RuntimeException { AbstractRollupStat other = baseRollup.getMinValue(); if (init) { if (other.isFloatingPoint()) { this.setDoubleValue(other.toDouble()); } else { this.setLongValue(other.toLong()); } init = false; return; } if (this.isFloatingPoint() && !other.isFloatingPoint()) { if (this.toDouble() > (double)other.toLong()) { this.setLongValue(other.toLong()); } } else if (this.isFloatingPoint()) { this.setDoubleValue(Math.min(this.toDouble(), other.toDouble())); } else if (other.isFloatingPoint()) { if ((double)this.toLong()> other.toDouble()) { this.setDoubleValue(other.toDouble()); } } else { this.setLongValue(Math.min(this.toLong(), other.toLong())); } } MinValue(); @SuppressWarnings("unused") // used by Jackson MinValue(long value); @SuppressWarnings("unused") // used by Jackson MinValue(double value); @Override byte getStatType(); } | @Test public void rollupInitialFloatingPointSetsValue() { double value = 123.45d; IBaseRollup rollup = mock(IBaseRollup.class); MinValue other = new MinValue(value); doReturn(other).when(rollup).getMinValue(); min.handleRollupMetric(rollup); assertTrue(min.isFloatingPoint()); assertEquals(value, min.toDouble(), 0.00001d); }
@Test public void rollupInitialNonFloatingPointSetsValue() { long value = 123L; IBaseRollup rollup = mock(IBaseRollup.class); MinValue other = new MinValue(value); doReturn(other).when(rollup).getMinValue(); min.handleRollupMetric(rollup); assertFalse(min.isFloatingPoint()); assertEquals(123L, min.toLong()); }
@Test public void rollupInitialDoubleThenLesserDouble() { double value1 = 123.45d; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MinValue(value1)).when(rollup1).getMinValue(); min.handleRollupMetric(rollup1); double value2 = 122.45d; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MinValue(value2)).when(rollup2).getMinValue(); min.handleRollupMetric(rollup2); assertTrue(min.isFloatingPoint()); assertEquals(value2, min.toDouble(), 0.00001d); }
@Test public void rollupInitialDoubleThenGreaterDouble() { double value1 = 123.45d; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MinValue(value1)).when(rollup1).getMinValue(); min.handleRollupMetric(rollup1); double value2 = 124.45d; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MinValue(value2)).when(rollup2).getMinValue(); min.handleRollupMetric(rollup2); assertTrue(min.isFloatingPoint()); assertEquals(value1, min.toDouble(), 0.00001d); }
@Test public void rollupInitialDoubleThenLesserLong() { double value1 = 123.45d; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MinValue(value1)).when(rollup1).getMinValue(); min.handleRollupMetric(rollup1); long value2 = 122L; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MinValue(value2)).when(rollup2).getMinValue(); min.handleRollupMetric(rollup2); assertFalse(min.isFloatingPoint()); assertEquals(value2, min.toLong()); }
@Test public void rollupInitialDoubleThenGreaterLong() { double value1 = 123.45d; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MinValue(value1)).when(rollup1).getMinValue(); min.handleRollupMetric(rollup1); long value2 = 124L; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MinValue(value2)).when(rollup2).getMinValue(); min.handleRollupMetric(rollup2); assertTrue(min.isFloatingPoint()); assertEquals(value1, min.toDouble(), 0.00001d); }
@Test public void rollupInitialLongThenLesserDouble() { long value1 = 123L; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MinValue(value1)).when(rollup1).getMinValue(); min.handleRollupMetric(rollup1); double value2 = 122.45d; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MinValue(value2)).when(rollup2).getMinValue(); min.handleRollupMetric(rollup2); assertTrue(min.isFloatingPoint()); assertEquals(value2, min.toDouble(), 0.00001d); }
@Test public void rollupInitialLongThenGreaterDouble() { long value1 = 123L; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MinValue(value1)).when(rollup1).getMinValue(); min.handleRollupMetric(rollup1); double value2 = 124.45d; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MinValue(value2)).when(rollup2).getMinValue(); min.handleRollupMetric(rollup2); assertFalse(min.isFloatingPoint()); assertEquals(value1, min.toLong()); }
@Test public void rollupInitialLongThenLesserLong() { long value1 = 123L; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MinValue(value1)).when(rollup1).getMinValue(); min.handleRollupMetric(rollup1); long value2 = 122L; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MinValue(value2)).when(rollup2).getMinValue(); min.handleRollupMetric(rollup2); assertFalse(min.isFloatingPoint()); assertEquals(value2, min.toLong()); }
@Test public void rollupInitialLongThenGreaterLong() { long value1 = 123L; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MinValue(value1)).when(rollup1).getMinValue(); min.handleRollupMetric(rollup1); long value2 = 124L; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MinValue(value2)).when(rollup2).getMinValue(); min.handleRollupMetric(rollup2); assertFalse(min.isFloatingPoint()); assertEquals(value1, min.toLong()); } |
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); } | @Test public void testGetRollupConcurrency() { int expected = 12; doReturn(expected).when(rollupReadExecutors).getMaximumPoolSize(); int actual = service.getRollupConcurrency(); assertEquals(expected, actual); verify(rollupReadExecutors).getMaximumPoolSize(); verifyNoMoreInteractions(rollupReadExecutors); } |
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(); } | @Test public void returnsTheCorrectStatType() { assertEquals(Constants.MIN, min.getStatType()); } |
MaxValue extends AbstractRollupStat { @Override void handleFullResMetric(Object o) throws RuntimeException { if (o instanceof Double) { if (init) { this.setDoubleValue((Double)o); this.init = false; return; } if (!this.isFloatingPoint()) { if ((double)this.toLong() < (Double)o) { this.setDoubleValue((Double)o); } } else { this.setDoubleValue(Math.max(this.toDouble(), (Double)o)); } } else if (o instanceof Long || o instanceof Integer) { Long val; if (o instanceof Integer) { val = ((Integer)o).longValue(); } else { val = (Long)o; } if (init) { this.setLongValue(val); this.init = false; return; } if (this.isFloatingPoint()) { double doubleValOther = val.doubleValue(); if (this.toDouble()< doubleValOther) { this.setLongValue(val); } } else { this.setLongValue(Math.max(this.toLong(), val)); } } else { throw new RuntimeException("Unsuppored type " + o.getClass().getName() +" for min"); } } MaxValue(); @SuppressWarnings("unused") // used by Jackson MaxValue(long value); @SuppressWarnings("unused") // used by Jackson MaxValue(double value); @Override byte getStatType(); } | @Test public void fullResInitialDoubleSetsValue() { max.handleFullResMetric(123.45d); assertTrue(max.isFloatingPoint()); assertEquals(123.45d, max.toDouble(), 0.00001d); }
@Test public void fullResInitialLongSetsValue() { max.handleFullResMetric(123L); assertFalse(max.isFloatingPoint()); assertEquals(123L, max.toLong()); }
@Test public void fullResInitialIntegerSetsValue() { max.handleFullResMetric((int)123); assertFalse(max.isFloatingPoint()); assertEquals(123L, max.toLong()); }
@Test(expected = RuntimeException.class) public void fullResInitialFloatThrowsException() { max.handleFullResMetric(123f); }
@Test public void fullResInitialDoubleThenLesserDouble() { max.handleFullResMetric(123.45d); max.handleFullResMetric(122.45d); assertTrue(max.isFloatingPoint()); assertEquals(123.45d, max.toDouble(), 0.00001d); }
@Test public void fullResInitialDoubleThenGreaterDouble() { max.handleFullResMetric(123.45d); max.handleFullResMetric(124.45d); assertTrue(max.isFloatingPoint()); assertEquals(124.45d, max.toDouble(), 0.00001d); }
@Test public void fullResInitialDoubleThenLesserLong() { max.handleFullResMetric(123.45d); max.handleFullResMetric(122L); assertTrue(max.isFloatingPoint()); assertEquals(123.45d, max.toDouble(), 0.00001d); }
@Test public void fullResInitialDoubleThenGreaterLong() { max.handleFullResMetric(123.45d); max.handleFullResMetric(124L); assertFalse(max.isFloatingPoint()); assertEquals(124L, max.toLong()); }
@Test public void fullResInitialLongThenLesserDouble() { max.handleFullResMetric(123L); max.handleFullResMetric(122.45d); assertFalse(max.isFloatingPoint()); assertEquals(123L, max.toLong()); }
@Test public void fullResInitialLongThenGreaterDouble() { max.handleFullResMetric(123L); max.handleFullResMetric(124.45d); assertTrue(max.isFloatingPoint()); assertEquals(124.45d, max.toDouble(), 0.00001d); }
@Test public void fullResInitialLongThenLesserLong() { max.handleFullResMetric(123L); max.handleFullResMetric(122L); assertFalse(max.isFloatingPoint()); assertEquals(123L, max.toLong()); }
@Test public void fullResInitialLongThenGreaterLong() { max.handleFullResMetric(123L); max.handleFullResMetric(124L); assertFalse(max.isFloatingPoint()); assertEquals(124L, max.toLong()); } |
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); } | @Test public void testSetRollupConcurrency() { service.setRollupConcurrency(3); verify(rollupReadExecutors).setCorePoolSize(anyInt()); verify(rollupReadExecutors).setMaximumPoolSize(anyInt()); verifyNoMoreInteractions(rollupReadExecutors); } |
MaxValue extends AbstractRollupStat { @Override void handleRollupMetric(IBaseRollup baseRollup) throws RuntimeException { AbstractRollupStat other = baseRollup.getMaxValue(); if (init) { if (other.isFloatingPoint()) { this.setDoubleValue(other.toDouble()); } else { this.setLongValue(other.toLong()); } this.init = false; return; } if (this.isFloatingPoint() && !other.isFloatingPoint()) { if (this.toDouble() < (double)other.toLong()) { this.setLongValue(other.toLong()); } } else if (this.isFloatingPoint()) { this.setDoubleValue(Math.max(this.toDouble(), other.toDouble())); } else if (other.isFloatingPoint()) { if ((double)this.toLong() < other.toDouble()) { this.setDoubleValue(other.toDouble()); } } else { this.setLongValue(Math.max(this.toLong(), other.toLong())); } } MaxValue(); @SuppressWarnings("unused") // used by Jackson MaxValue(long value); @SuppressWarnings("unused") // used by Jackson MaxValue(double value); @Override byte getStatType(); } | @Test public void rollupInitialFloatingPointSetsValue() { double value = 123.45d; IBaseRollup rollup = mock(IBaseRollup.class); MaxValue other = new MaxValue(value); doReturn(other).when(rollup).getMaxValue(); max.handleRollupMetric(rollup); assertTrue(max.isFloatingPoint()); assertEquals(value, max.toDouble(), 0.00001d); }
@Test public void rollupInitialNonFloatingPointSetsValue() { long value = 123L; IBaseRollup rollup = mock(IBaseRollup.class); MaxValue other = new MaxValue(value); doReturn(other).when(rollup).getMaxValue(); max.handleRollupMetric(rollup); assertFalse(max.isFloatingPoint()); assertEquals(123L, max.toLong()); }
@Test public void rollupInitialDoubleThenLesserDouble() { double value1 = 123.45d; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MaxValue(value1)).when(rollup1).getMaxValue(); max.handleRollupMetric(rollup1); double value2 = 122.45d; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MaxValue(value2)).when(rollup2).getMaxValue(); max.handleRollupMetric(rollup2); assertTrue(max.isFloatingPoint()); assertEquals(value1, max.toDouble(), 0.00001d); }
@Test public void rollupInitialDoubleThenGreaterDouble() { double value1 = 123.45d; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MaxValue(value1)).when(rollup1).getMaxValue(); max.handleRollupMetric(rollup1); double value2 = 124.45d; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MaxValue(value2)).when(rollup2).getMaxValue(); max.handleRollupMetric(rollup2); assertTrue(max.isFloatingPoint()); assertEquals(value2, max.toDouble(), 0.00001d); }
@Test public void rollupInitialDoubleThenLesserLong() { double value1 = 123.45d; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MaxValue(value1)).when(rollup1).getMaxValue(); max.handleRollupMetric(rollup1); long value2 = 122L; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MaxValue(value2)).when(rollup2).getMaxValue(); max.handleRollupMetric(rollup2); assertTrue(max.isFloatingPoint()); assertEquals(value1, max.toDouble(), 0.00001d); }
@Test public void rollupInitialDoubleThenGreaterLong() { double value1 = 123.45d; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MaxValue(value1)).when(rollup1).getMaxValue(); max.handleRollupMetric(rollup1); long value2 = 124L; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MaxValue(value2)).when(rollup2).getMaxValue(); max.handleRollupMetric(rollup2); assertFalse(max.isFloatingPoint()); assertEquals(value2, max.toLong()); }
@Test public void rollupInitialLongThenLesserDouble() { long value1 = 123L; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MaxValue(value1)).when(rollup1).getMaxValue(); max.handleRollupMetric(rollup1); double value2 = 122.45d; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MaxValue(value2)).when(rollup2).getMaxValue(); max.handleRollupMetric(rollup2); assertFalse(max.isFloatingPoint()); assertEquals(value1, max.toLong()); }
@Test public void rollupInitialLongThenGreaterDouble() { long value1 = 123L; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MaxValue(value1)).when(rollup1).getMaxValue(); max.handleRollupMetric(rollup1); double value2 = 124.45d; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MaxValue(value2)).when(rollup2).getMaxValue(); max.handleRollupMetric(rollup2); assertTrue(max.isFloatingPoint()); assertEquals(value2, max.toDouble(), 0.00001d); }
@Test public void rollupInitialLongThenLesserLong() { long value1 = 123L; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MaxValue(value1)).when(rollup1).getMaxValue(); max.handleRollupMetric(rollup1); long value2 = 122L; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MaxValue(value2)).when(rollup2).getMaxValue(); max.handleRollupMetric(rollup2); assertFalse(max.isFloatingPoint()); assertEquals(value1, max.toLong()); }
@Test public void rollupInitialLongThenGreaterLong() { long value1 = 123L; IBaseRollup rollup1 = mock(IBaseRollup.class); doReturn(new MaxValue(value1)).when(rollup1).getMaxValue(); max.handleRollupMetric(rollup1); long value2 = 124L; IBaseRollup rollup2 = mock(IBaseRollup.class); doReturn(new MaxValue(value2)).when(rollup2).getMaxValue(); max.handleRollupMetric(rollup2); assertFalse(max.isFloatingPoint()); assertEquals(value2, max.toLong()); } |
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); } | @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); } |
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(); } | @Test public void returnsTheCorrectStatType() { assertEquals(Constants.MAX, max.getStatType()); } |
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; } | @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()); } |
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); } | @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); } |
SlotKeySerDes { protected static int shardFromSlotKey(String s) { return Integer.parseInt(s.split(",", -1)[2]); } static SlotKey deserialize(String stateStr); String serialize(SlotKey slotKey); String serialize(Granularity gran, int slot, int shard); } | @Test public void testShardFromSlotKey() { int expectedShard = 1; int shard = SlotKeySerDes.shardFromSlotKey(SlotKey.of(Granularity.MIN_5, 10, expectedShard).toString()); Assert.assertEquals(expectedShard, shard); } |
SimpleNumber implements Rollup { public String toString() { switch (type) { case INTEGER: return String.format("%d (int)", value.intValue()); case LONG: return String.format("%d (long)", value.longValue()); case DOUBLE: return String.format("%s (double)", value.toString()); default: return super.toString(); } } SimpleNumber(Object value); @Override Boolean hasData(); Number getValue(); Type getDataType(); String toString(); @Override RollupType getRollupType(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test public void toStringWithIntegerPrintsIntegerString() { SimpleNumber sn = new SimpleNumber(123); assertEquals("123 (int)", sn.toString()); }
@Test public void toStringWithLongPrintsLongString() { SimpleNumber sn = new SimpleNumber(123L); assertEquals("123 (long)", sn.toString()); }
@Test public void toStringWithDoublePrintsDoubleString() { SimpleNumber sn = new SimpleNumber(123.45d); assertEquals("123.45 (double)", sn.toString()); } |
SimpleNumber implements Rollup { @Override public RollupType getRollupType() { return RollupType.NOT_A_ROLLUP; } SimpleNumber(Object value); @Override Boolean hasData(); Number getValue(); Type getDataType(); String toString(); @Override RollupType getRollupType(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test public void rollupTypeIsNotTypical() { SimpleNumber sn = new SimpleNumber(123.45d); assertEquals(RollupType.NOT_A_ROLLUP, sn.getRollupType()); } |
SimpleNumber implements Rollup { @Override public int hashCode() { return value.hashCode(); } SimpleNumber(Object value); @Override Boolean hasData(); Number getValue(); Type getDataType(); String toString(); @Override RollupType getRollupType(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test public void hashCodeIsValuesHashCode() { Double value = 123.45d; SimpleNumber sn = new SimpleNumber(value); assertEquals(value.hashCode(), sn.hashCode()); } |
SimpleNumber implements Rollup { @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof SimpleNumber)) return false; SimpleNumber other = (SimpleNumber)obj; return other.value == this.value || other.value.equals(this.value); } SimpleNumber(Object value); @Override Boolean hasData(); Number getValue(); Type getDataType(); String toString(); @Override RollupType getRollupType(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test public void equalsWithNullReturnsFalse() { SimpleNumber sn = new SimpleNumber(123.45d); assertFalse(sn.equals(null)); }
@Test public void equalsWithOtherTypeReturnsFalse() { SimpleNumber sn = new SimpleNumber(123.45d); assertFalse(sn.equals(Double.valueOf(123.45d))); }
@Test public void equalsWithSimpleNumberOfOtherTypeReturnsFalse() { SimpleNumber sn = new SimpleNumber(123); SimpleNumber other = new SimpleNumber(123L); assertFalse(sn.equals(other)); }
@Test public void equalsWithSimpleNumberOfSameTypeReturnsTrue() { SimpleNumber sn = new SimpleNumber(123); SimpleNumber other = new SimpleNumber(123); assertTrue(sn.equals(other)); }
@Test public void equalsWithSimpleNumberOfSameBoxedValueReturnsTrue() { Integer value = 123; SimpleNumber sn = new SimpleNumber(value); SimpleNumber other = new SimpleNumber(value); assertTrue(sn.equals(other)); } |
RollupService implements Runnable, RollupServiceMBean { public synchronized boolean getActive() { return active; } 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); } | @Test public void getActiveGetsActiveFlag() { assertEquals(true, service.getActive()); } |
Variance extends AbstractRollupStat { @Override public double toDouble() { if (needsCompute) compute(); return super.toDouble(); } Variance(); @SuppressWarnings("unused") // used by Jackson Variance(double value); @Override boolean equals(Object otherObject); @Override boolean isFloatingPoint(); String toString(); @Override double toDouble(); @Override long toLong(); @Override byte getStatType(); } | @Test public void testRollupVariance() throws IOException { int size = TestData.DOUBLE_SRC.length; int GROUPS = 4; int windowSize = size/GROUPS; double[][] input = new double[GROUPS][windowSize]; int count = 0; int i = 0; int j = 0; for (double val : TestData.DOUBLE_SRC) { input[i][j] = val; j++; count++; if (count % windowSize == 0) { i++; j = 0; } } List<BasicRollup> basicRollups = new ArrayList<BasicRollup>(); List<Results> resultsList = new ArrayList<Results>(); for (i = 0; i < GROUPS; i++) { Results r = new Results(); Points<SimpleNumber> inputSlice = new Points<SimpleNumber>(); int timeOffset = 0; for (double val : input[i]) { inputSlice.add(new Points.Point<SimpleNumber>(123456789L + timeOffset++, new SimpleNumber(val))); } BasicRollup basicRollup = BasicRollup.buildRollupFromRawSamples(inputSlice); r.expectedVariance = computeRawVariance(input[i]); r.computedVariance = basicRollup.getVariance().toDouble(); r.expectedAverage = computeRawAverage(input[i]); r.computedAverage = basicRollup.getAverage().toDouble(); basicRollups.add(basicRollup); resultsList.add(r); } for (i = 0; i < GROUPS; i++) { Results result = resultsList.get(i); assertWithinErrorPercent(result.computedAverage, result.expectedAverage); assertWithinErrorPercent(result.computedVariance, result.expectedVariance); } Points<BasicRollup> inputData = new Points<BasicRollup>(); inputData.add(new Points.Point<BasicRollup>(123456789L, basicRollups.get(0))); inputData.add(new Points.Point<BasicRollup>(123456790L, basicRollups.get(1))); BasicRollup basicRollup10min_0 = BasicRollup.buildRollupFromRollups(inputData); assertWithinErrorPercent(basicRollup10min_0.getAverage().toDouble(), computeRawAverage(ArrayUtils.addAll(input[0], input[1]))); assertWithinErrorPercent(basicRollup10min_0.getVariance().toDouble(), computeRawVariance(ArrayUtils.addAll(input[0], input[1]))); inputData = new Points<BasicRollup>(); inputData.add(new Points.Point<BasicRollup>(123456789L, basicRollups.get(2))); inputData.add(new Points.Point<BasicRollup>(123456790L, basicRollups.get(3))); BasicRollup basicRollup10min_1 = BasicRollup.buildRollupFromRollups(inputData); assertWithinErrorPercent(basicRollup10min_1.getAverage().toDouble(), computeRawAverage(ArrayUtils.addAll(input[2], input[3]))); assertWithinErrorPercent(basicRollup10min_1.getVariance().toDouble(), computeRawVariance(ArrayUtils.addAll(input[2], input[3]))); inputData = new Points<BasicRollup>(); inputData.add(new Points.Point<BasicRollup>(123456789L, basicRollup10min_0)); inputData.add(new Points.Point<BasicRollup>(123456790L, basicRollup10min_1)); BasicRollup basicRollup20min_0 = BasicRollup.buildRollupFromRollups(inputData); assertWithinErrorPercent(basicRollup20min_0.getAverage().toDouble(), computeRawAverage(TestData.DOUBLE_SRC)); assertWithinErrorPercent(basicRollup20min_0.getVariance().toDouble(), computeRawVariance(TestData.DOUBLE_SRC)); } |
BluefloodTimerRollup implements Rollup, IBaseRollup { public static double calculatePerSecond(long countA, double countPerSecA, long countB, double countPerSecB) { double totalCount = countA + countB; double totalTime = ((double)countA / countPerSecA) + ((double)countB / countPerSecB); return totalCount / totalTime; } BluefloodTimerRollup(); BluefloodTimerRollup withSum(double sum); BluefloodTimerRollup withCount(long count); BluefloodTimerRollup withCountPS(double count_ps); BluefloodTimerRollup withSampleCount(int sampleCount); BluefloodTimerRollup withMinValue(MinValue min); BluefloodTimerRollup withMinValue(Number num); BluefloodTimerRollup withMaxValue(MaxValue max); BluefloodTimerRollup withMaxValue(Number num); BluefloodTimerRollup withAverage(Average average); BluefloodTimerRollup withAverage(Number average); BluefloodTimerRollup withVariance(Variance variance); BluefloodTimerRollup withVariance(Number variance); Average getAverage(); MaxValue getMaxValue(); MinValue getMinValue(); Variance getVariance(); void setPercentile(String label, Number mean); @Override Boolean hasData(); double getRate(); double getSum(); long getCount(); int getSampleCount(); String toString(); @Override RollupType getRollupType(); boolean equals(Object obj); static Number sum(Collection<Number> numbers); static Number avg(Collection<Number> numbers); static Number max(Collection<Number> numbers); static double calculatePerSecond(long countA, double countPerSecA, long countB, double countPerSecB); Map<String, Percentile> getPercentiles(); static BluefloodTimerRollup buildRollupFromTimerRollups(Points<BluefloodTimerRollup> input); } | @Test public void testCountPerSecondCalculation() { Assert.assertEquals(7.5d, BluefloodTimerRollup.calculatePerSecond(150, 5d, 300, 10d)); } |
BluefloodTimerRollup implements Rollup, IBaseRollup { public BluefloodTimerRollup withSampleCount(int sampleCount) { this.sampleCount = sampleCount; return this; } BluefloodTimerRollup(); BluefloodTimerRollup withSum(double sum); BluefloodTimerRollup withCount(long count); BluefloodTimerRollup withCountPS(double count_ps); BluefloodTimerRollup withSampleCount(int sampleCount); BluefloodTimerRollup withMinValue(MinValue min); BluefloodTimerRollup withMinValue(Number num); BluefloodTimerRollup withMaxValue(MaxValue max); BluefloodTimerRollup withMaxValue(Number num); BluefloodTimerRollup withAverage(Average average); BluefloodTimerRollup withAverage(Number average); BluefloodTimerRollup withVariance(Variance variance); BluefloodTimerRollup withVariance(Number variance); Average getAverage(); MaxValue getMaxValue(); MinValue getMinValue(); Variance getVariance(); void setPercentile(String label, Number mean); @Override Boolean hasData(); double getRate(); double getSum(); long getCount(); int getSampleCount(); String toString(); @Override RollupType getRollupType(); boolean equals(Object obj); static Number sum(Collection<Number> numbers); static Number avg(Collection<Number> numbers); static Number max(Collection<Number> numbers); static double calculatePerSecond(long countA, double countPerSecA, long countB, double countPerSecB); Map<String, Percentile> getPercentiles(); static BluefloodTimerRollup buildRollupFromTimerRollups(Points<BluefloodTimerRollup> input); } | @Test public void testNullVersusZero() throws IOException { final BluefloodTimerRollup timerWithData = new BluefloodTimerRollup() .withSampleCount(1); final BluefloodTimerRollup timerWithoutData = new BluefloodTimerRollup() .withSampleCount(0); Assert.assertNotSame(timerWithData, timerWithoutData); } |
BluefloodTimerRollup implements Rollup, IBaseRollup { public static Number sum(Collection<Number> numbers) { long longSum = 0; double doubleSum = 0d; boolean useDouble = false; for (Number number : numbers) { if (useDouble || number instanceof Double || number instanceof Float) { if (!useDouble) { useDouble = true; doubleSum += longSum; } doubleSum += number.doubleValue(); } else if (number instanceof Long || number instanceof Integer) longSum += number.longValue(); } if (useDouble) return doubleSum; else return longSum; } BluefloodTimerRollup(); BluefloodTimerRollup withSum(double sum); BluefloodTimerRollup withCount(long count); BluefloodTimerRollup withCountPS(double count_ps); BluefloodTimerRollup withSampleCount(int sampleCount); BluefloodTimerRollup withMinValue(MinValue min); BluefloodTimerRollup withMinValue(Number num); BluefloodTimerRollup withMaxValue(MaxValue max); BluefloodTimerRollup withMaxValue(Number num); BluefloodTimerRollup withAverage(Average average); BluefloodTimerRollup withAverage(Number average); BluefloodTimerRollup withVariance(Variance variance); BluefloodTimerRollup withVariance(Number variance); Average getAverage(); MaxValue getMaxValue(); MinValue getMinValue(); Variance getVariance(); void setPercentile(String label, Number mean); @Override Boolean hasData(); double getRate(); double getSum(); long getCount(); int getSampleCount(); String toString(); @Override RollupType getRollupType(); boolean equals(Object obj); static Number sum(Collection<Number> numbers); static Number avg(Collection<Number> numbers); static Number max(Collection<Number> numbers); static double calculatePerSecond(long countA, double countPerSecA, long countB, double countPerSecB); Map<String, Percentile> getPercentiles(); static BluefloodTimerRollup buildRollupFromTimerRollups(Points<BluefloodTimerRollup> input); } | @Test public void testSum() { Assert.assertEquals(6L, BluefloodTimerRollup.sum(longs)); Assert.assertEquals(6.0d, BluefloodTimerRollup.sum(doubles)); Assert.assertEquals(6.0d, BluefloodTimerRollup.sum(mixed)); Assert.assertEquals(6.0d, BluefloodTimerRollup.sum(alsoMixed)); } |
Subsets and Splits