method2testcases
stringlengths 118
6.63k
|
---|
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public int size() { int size = 0; if (root==null){ return 0; } if (root.getLeft()==null && root.getRight()==null){ return 1; } if (root.getLeft()!=null){ size+= 1+size(root.getLeft()); } if (root.getRight()!=null){ size+= 1+size(root.getRight()); } return size; } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testSize() { assertEquals("Size of new tree not 0", 0, tree.size()); tree.add(20, "S"); assertEquals("Size after 1 insert wrong", 1, tree.size()); tree.remove(20); assertEquals("Size after last remove not 0", 0, tree.size()); for (int i = 0; i < 10 ; i++) { tree.add(i + i, "S"); } assertEquals("Size after multiple inserts wrong", 10, tree.size()); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public K min() { opsCount++; if (root==null){ return null; } else { return min(root,root.key); } } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testMin() { assertNull("Empty tree min was not null", tree.min()); tree.add(20, "LD"); assertEquals("One element tree min wrong", (Integer) 20, tree.min()); tree.add(30, "df"); tree.add(15, "kjd"); tree.add(10, "kjdf"); tree.add(5, "kdjf"); tree.add(1, "esd"); assertEquals("Multi-element tree min wrong", (Integer) 1, tree.min()); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public K max() { opsCount++; if (root==null){ return null; } else { return max(root,root.key); } } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testMax() { assertNull("Empty tree max was not null", tree.max()); tree.add(20, "SS"); assertEquals("One element tree max wrong", (Integer) 20, tree.max()); tree.add(30, "SS"); tree.add(35, "LL"); tree.add(40, "JJ"); tree.add(37, "df"); tree.add(36, "wer"); assertEquals("Multi-element tree max wrong", (Integer) 40, tree.max()); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public V find(K key) { opsCount++; if (root==null){ return null; } else if (key.compareTo(root.key)==0){ return root.data; } else if (key.compareTo(root.key)<0){ return find(root.getLeft(),key); } else{ return find(root.getRight(),key); } } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testFind() { assertNull(tree.find(40)); tree.add(20, "s"); tree.add(10, "c"); assertEquals("s", tree.find(20)); assertEquals("c", tree.find(10)); tree.add(30, "x"); assertEquals("x", tree.find(30)); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public int height() { if (root==null){ return -1; } else { return root.getHeight(); } } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testHeight() { assertEquals("Height of empty tree wrong", -1, tree.height()); tree.add(20, "lk"); assertEquals("Height wrong for 1 entry", 0, tree.height()); tree.add(1, "lkd"); assertEquals("Height wrong for 2 entry", 1, tree.height()); tree.add(5, "ksjdf"); tree.add(28, "skdjf"); tree.add(32, "sd"); tree.add(30, "d"); tree.add(40, "zz"); assertEquals("Height wrong for mult entries", 3, tree.height()); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public K root() { if (root==null){ return null; } else{ return root.key; } } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testRoot() { assertNull(tree.root()); tree.add(20, "dd"); assertEquals((Integer) 20, tree.root()); tree.remove(20); assertNull(tree.root()); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public List<K> preorderTraversal() { List<K> keyList = new ArrayList<K>(); preorderTraversal(root,keyList); return keyList; } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testPreorderTraversal() { List<Integer> list = tree.preorderTraversal(); assertTrue(list.isEmpty()); tree.add(13, "sdf"); tree.add(9, "wer"); tree.add(16,"sdxv"); tree.add(5, "wer"); tree.add(10, "sdf"); tree.add(1, "werf"); tree.add(6, "pk"); tree.add(14, "nn"); tree.add(26, "dd"); list = tree.preorderTraversal(); System.out.println("Pre: " + list.toString()); assertEquals("Wrong number of elements", 9 , list.size()); assertEquals("First element wrong", (Integer) 13, list.get(0) ); assertEquals((Integer) 9,list.get(1)); assertEquals((Integer) 5 , list.get(2)); assertEquals((Integer) 26, list.get(8)); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public List<K> postorderTraversal() { List<K> keyList = new ArrayList<K>(); postorderTraversal(root,keyList); return keyList; } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testPostorderTraversal() { List<Integer> list = tree.postorderTraversal(); assertTrue(list.isEmpty()); tree.add(13, "sdf"); tree.add(9, "wer"); tree.add(16,"sdxv"); tree.add(5, "wer"); tree.add(10, "sdf"); tree.add(1, "werf"); tree.add(6, "pk"); tree.add(14, "nn"); tree.add(26, "dd"); list = tree.postorderTraversal(); System.out.println("Post: " + list.toString()); assertEquals("Wrong number of elements", 9 , list.size()); assertEquals("First element wrong", (Integer) 1, list.get(0) ); assertEquals((Integer) 6,list.get(1)); assertEquals((Integer) 5, list.get(2)); assertEquals((Integer) 13, list.get(8)); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public List<K> inorderTraversal() { List<K> keyList = new ArrayList<K>(); inorderTraversal(root,keyList); return keyList; } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testInorderTraversal() { List<Integer> list = tree.inorderTraversal(); assertTrue(list.isEmpty()); tree.add(13, "sdf"); tree.add(9, "wer"); tree.add(16,"sdxv"); tree.add(5, "wer"); tree.add(10, "sdf"); tree.add(1, "werf"); tree.add(6, "pk"); tree.add(14, "nn"); tree.add(26, "dd"); list = tree.inorderTraversal(); System.out.println("In: " + list.toString()); assertEquals("Wrong number of elements", 9 , list.size()); assertEquals("First element wrong", (Integer) 1, list.get(0) ); assertEquals((Integer) 5,list.get(1)); assertEquals((Integer) 6, list.get(2)); assertEquals((Integer) 26, list.get(8)); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public List<K> levelorderTraversal() { List<K> keyList = new ArrayList<K>(); return levelorderTraversal(root,keyList); } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testLevelorderTraversal() { List<Integer> list = tree.levelorderTraversal(); assertTrue(list.isEmpty()); tree.add(13, "sdf"); tree.add(9, "wer"); tree.add(16,"sdxv"); tree.add(5, "wer"); tree.add(10, "sdf"); tree.add(1, "werf"); tree.add(6, "pk"); tree.add(14, "nn"); tree.add(26, "dd"); list = tree.levelorderTraversal(); System.out.println("Level: " + list.toString()); assertEquals("Wrong number of elements", 9 , list.size()); assertEquals("First element wrong", (Integer) 13, list.get(0) ); assertEquals((Integer) 9,list.get(1)); assertEquals((Integer) 16, list.get(2)); assertEquals((Integer) 6, list.get(8)); } |
### Question:
SparseArray2DImpl implements ISparseArray2D<T> { @Override public List<T> getRowFor(int row) throws ArrayIndexOutOfBoundsException { if (row>this.row || row<0){ throw new ArrayIndexOutOfBoundsException(); } ArrayList<T> list = new ArrayList<T>(); IndexNode current = rowLinkedList.head; while (current!=null){ if (row==current.index){ ArrayNode<T> currentNode = current.head; while (currentNode!=null){ list.add(currentNode.data); currentNode = currentNode.nextCol; } current = current.next; } else{ current = current.next; } } return list ; } SparseArray2DImpl(int row, int column); @Override void putAt(int row, int col, T value); @Override T removeAt(int row, int col); @Override T getAt(int row, int col); @Override List<T> getRowFor(int row); @Override List<T> getColumnFor(int col); }### Answer:
@Test public void testGetRowFor() { try { array.getRowFor(10001); assertTrue("You failed to detect row out of bounds", false); } catch (ArrayIndexOutOfBoundsException ae) { assertTrue(true); } List<String> list = array.getRowFor(100); assertTrue("You failed to return an empty list for an empty array", list.isEmpty()); array.putAt(10, 100, "C"); array.putAt(10, 150, "L"); array.putAt(30, 150, "D"); array.putAt(90, 150, "Z"); array.putAt(30, 100, "O"); array.putAt(30, 200, "T"); list = array.getRowFor(30); assertEquals("Returned row count incorrect", 3, list.size()); assertEquals("First row item wrong", "O", list.get(0)); assertEquals("Second row item wrong", "D", list.get(1)); assertEquals("Third row item wrong", "T", list.get(2)); list = array.getRowFor(1000); assertTrue("You failed to return an empty list for empty row", list.isEmpty()); } |
### Question:
SparseArray2DImpl implements ISparseArray2D<T> { @Override public void putAt(int row, int col, T value) throws ArrayIndexOutOfBoundsException { if (row>this.row || col>column){ throw new ArrayIndexOutOfBoundsException(); } else{ IndexNode rowNode = checkForIndex(rowLinkedList,row); IndexNode colNode = checkForIndex(colLinkedList, col); if (rowNode==null){ rowLinkedList.add(row); rowNode = checkForIndex(rowLinkedList,row); } if (colNode==null){ colLinkedList.add(col); colNode = checkForIndex(colLinkedList, col); } ArrayNode<T> arrayNode = insertInRow(row,col,value,rowNode); insertInCol(row,col,colNode,arrayNode); } } SparseArray2DImpl(int row, int column); @Override void putAt(int row, int col, T value); @Override T removeAt(int row, int col); @Override T getAt(int row, int col); @Override List<T> getRowFor(int row); @Override List<T> getColumnFor(int col); }### Answer:
@Test public void testPutAt() { try { array.putAt(10001, 1, "K"); assertTrue("Failed to detect row out of bounds", false); } catch (ArrayIndexOutOfBoundsException ae) { assertTrue(true); } try { array.putAt(1, 10001, "K"); assertTrue("Failed to detect col out of bounds", false); } catch (ArrayIndexOutOfBoundsException ae) { assertTrue(true); } array.putAt(10, 100, "C"); array.putAt(30, 140, "D"); assertEquals("Returned element is wrong", "C", array.getAt(10, 100)); assertEquals("Returned element is wrong", "D", array.getAt(30, 140)); array.putAt(10, 100, "Z"); assertEquals("The overwritten value of a cell is wrong", array.getAt(10, 100), "Z"); } |
### Question:
SparseArray2DImpl implements ISparseArray2D<T> { @Override public T removeAt(int row, int col) throws ArrayIndexOutOfBoundsException { if (row>this.row || row<1 || col>column || col<1){ throw new ArrayIndexOutOfBoundsException(); } else if (isEmpty()==true){ return null; } else{ T returnValue = removeFromRow(row,col); removeFromCol(row,col); return returnValue; } } SparseArray2DImpl(int row, int column); @Override void putAt(int row, int col, T value); @Override T removeAt(int row, int col); @Override T getAt(int row, int col); @Override List<T> getRowFor(int row); @Override List<T> getColumnFor(int col); }### Answer:
@Test public void testRemoveAt() { try { array.removeAt(10001, 1); assertTrue("Failed to detect row out of bounds", false); } catch (ArrayIndexOutOfBoundsException ae) { assertTrue(true); } try { array.removeAt(1, 10001); assertTrue("Failed to detect col out of bounds", false); } catch (ArrayIndexOutOfBoundsException ae) { assertTrue(true); } array.putAt(10, 100, "C"); array.putAt(30, 140, "D"); array.putAt(10, 150, "L"); array.putAt(30, 150, "E"); array.putAt(7, 7, "T"); assertEquals("Removed element from non-existent cell not null", null, array.removeAt(5, 5)); assertEquals("Removed element wrong", "C", array.removeAt(10, 100)); assertEquals("Removed element wrong", "L", array.removeAt(10, 150)); List<String> list = array.getRowFor(10); assertTrue(list.isEmpty()); list = array.getColumnFor(100); assertTrue(list.isEmpty()); list = array.getColumnFor(150); assertTrue(list.size() == 1); assertTrue(list.contains("E")); assertEquals("Single element row, col remove wrong", "T", array.removeAt(7, 7)); list = array.getRowFor(7); assertTrue(list.isEmpty()); list = array.getColumnFor(7); assertTrue(list.isEmpty()); } |
### Question:
CircularArraySequence implements Sequence { @Override public void append(Object element) { if (backingArray[rear] != null && rear!=backingArray.length-1){ backingArray[rear+1] = (T)element; rear+=1; fillCount +=1; if (fullCheck()==true){ regrow(); } } else if(backingArray[rear] !=null && rear==backingArray.length-1){ rear = 0; backingArray[rear] = (T)element; fillCount+=1; if (fullCheck()==true){ regrow(); } } else if(backingArray[rear] == null){ backingArray[rear] = (T)element; rear+=1; fillCount+=1; if (fullCheck()==true){ regrow(); } } } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testAppend() { assertTrue("Your sequence was not empty when created", seq.isEmpty()); seq.append("a"); assertFalse("Your sequence claims its empty after appending something", seq.isEmpty()); assertEquals("The head of your sequence was not the thing appended on first append", "a", seq.peekHead()); seq.append("b"); assertEquals("The last of your sequence was not the thing appended on second append", "b", seq.peekLast()); assertEquals("The head of your sequence modified on the second append", "a", seq.peekHead()); seq.append("c"); seq.append("d"); assertEquals("The head of your sequence modified after multiple appends", "a", seq.peekHead()); assertEquals("The last of your sequence was not the last thing appended", "d", seq.peekLast()); } |
### Question:
CircularArraySequence implements Sequence { @Override public Sequence<T> concat(Sequence seq) { CircularArraySequence<T> sequence1 = new CircularArraySequence<T>(this); CircularArraySequence<T> sequence2 = new CircularArraySequence<T>((CircularArraySequence<T>)seq); boolean halt = false; int index = sequence2.front; while (halt == false){ if (index == backingArray.length){ index = 0; } if (index == sequence2.rear){ halt = true; } else{ sequence1.append(sequence2.backingArray[index]); index += 1; } } return sequence1; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testConcat() { seq.append("a"); seq.append("b"); seq.append("c"); Sequence<String> seq2 = new CircularArraySequence<String>(10); seq2.append("x"); seq2.append("y"); Sequence<String> seq3 = seq.concat(seq2); assertEquals(5, seq3.length()); assertEquals("a", seq3.peekHead()); assertEquals("y", seq3.peekLast()); } |
### Question:
CircularArraySequence implements Sequence { @Override public Sequence front() { CircularArraySequence<T> tempSequence = new CircularArraySequence<T>(this); boolean halt = false; int index = front; while (halt == false){ if (index == backingArray.length){ index = 0; } if (index == rear){ halt = true; } if(backingArray[index] == null){ if (index == 0){ tempSequence.backingArray[backingArray.length-1] = null; tempSequence.fillCount -=1; tempSequence.rear = tempSequence.backingArray.length-1; } else{ tempSequence.backingArray[index-1] = null; tempSequence.fillCount-=1; tempSequence.rear-=1; } } index+=1; } return tempSequence; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testFront() { Sequence<String> seq2 = seq.front(); assertTrue("Front of empty seq did not return empty", seq2.isEmpty()); seq.append("a"); seq.append("b"); seq.append("c"); seq.append("d"); seq.append("e"); Sequence<String> seq1 = seq.front(); assertEquals("Length of the sequence after taking front was wrong", 4 , seq1.length()); assertEquals("Head of the front sequence wrong", "a", seq1.peekHead()); assertEquals("Last element of front sequence wrong", "d", seq1.peekLast()); assertEquals("Original sequence length wrong", 5, seq.length()); assertEquals("Original sequence head wrong = don't modify the original when taking front", "a", seq.peekHead()); assertEquals("Original sequence last element wrong, don't modify the original", "e", seq.peekLast()); } |
### Question:
CircularArraySequence implements Sequence { @Override public Object head() { CircularArraySequence<T> tempSequence = new CircularArraySequence<T>(this); T firstObj = null; if (front == 0 || backingArray[front]==null){ if (backingArray[front]==null){ firstObj = null; } else{ firstObj = tempSequence.backingArray[front]; backingArray[front] = null; front+=1; fillCount-=1; } } else if (front == backingArray.length-1){ firstObj = tempSequence.backingArray[backingArray.length-1]; backingArray[backingArray.length-1] = null; front = 0; fillCount-=1; } else{ firstObj = tempSequence.backingArray[front]; backingArray[front] = null; front+=1; fillCount-=1; } return firstObj; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testHead() { assertTrue("New sequence not reporting its empty", seq.isEmpty()); assertEquals("Head of the new sequence not null", null, seq.head()); seq.append("a"); assertEquals("Head returned incorrect when one element", "a", seq.head()); assertEquals("Head returned incorrect when no element", null, seq.head()); seq.append("s"); seq.append("r"); seq.append("t"); seq.append("i"); assertEquals("Head returned incorrect value after several appends", "s", seq.head()); seq.last(); assertEquals("After removing last element, the head changed", "r", seq.head()); } |
### Question:
CircularArraySequence implements Sequence { @Override public boolean isEmpty() { if (fillCount>0){ return false; } return true; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testIsEmpty() { assertTrue(seq.isEmpty()); seq.append("A"); assertFalse(seq.isEmpty()); seq.last(); assertTrue(seq.isEmpty()); } |
### Question:
SemiStructureTokenizer extends Tokenizer { private void setStructireInfo(Reader input) { SemistructuredFormulaParser formulaParser = new SemistructuredFormulaParser(input); try { ChemSubStructure structure = formulaParser.parse(); Stack<DFSStackEntry> stack = new Stack<DFSStackEntry>(); stack.push(new DFSStackEntry(structure,1)); while (!stack.isEmpty()) { DFSStackEntry currentEntry = stack.pop(); ChemSubStructure current = currentEntry.subStructure; int multiplier = currentEntry.multiplier; if (current instanceof Element) { mapFragmentsChains(((Element) current).subFormula, multiplier); } else if (current instanceof ElementaryGroup) { mapFragmentsChains(((ElementaryGroup) current).subFormula, multiplier); } else if (current instanceof Group) { ChemSubStructure containedSubStructure = ((Group)current).containedSubStructure; stack.push(new DFSStackEntry(containedSubStructure, multiplier)); } else if (current instanceof Term) { Term asTerm = ((Term)current); stack.push(new DFSStackEntry(asTerm.subStrucure, multiplier * asTerm.multiplier)); } else if (current instanceof Formula) { for (ChemSubStructure subStructure : ((Formula) current).subStructures) { stack.push(new DFSStackEntry(subStructure, multiplier) ); } } } currentIterator = fragmentsCounts.entrySet().iterator(); currentCount = 0; } catch (ParseException e) { throw new RuntimeException(e); } } protected SemiStructureTokenizer(Reader input); protected SemiStructureTokenizer(AttributeFactory factory, Reader input); @Override final boolean incrementToken(); }### Answer:
@Test public void testSetStructireInfo() { Reader reader = new StringReader("C2H5OH"); SemiStructureTokenizer tokenizer = new SemiStructureTokenizer(reader); assertTrue(tokenizer.fragmentsCounts.containsKey("C")); assertTrue(tokenizer.fragmentsCounts.containsKey("C-C")); assertTrue(tokenizer.fragmentsCounts.containsKey("O")); assertEquals(tokenizer.fragmentsCounts.size(),3); } |
### Question:
SemiStructureTokenizer extends Tokenizer { @Override final public boolean incrementToken() throws IOException { if (currentEntry == null) { currentEntry = currentIterator.next(); currentCount = 0; String result = String.format("%s_%d", currentEntry.getKey(), currentCount); termAtt.setEmpty().append(result); return true; } else { if (currentCount < currentEntry.getValue()) { String result = String.format("%s_%d", currentEntry.getKey(), ++currentCount); termAtt.setEmpty().append(result); return true; } else if (currentIterator.hasNext()) { Map.Entry<String, Integer> currentEntry = currentIterator.next(); currentCount = 0; String result = String.format("%s_%d", currentEntry.getKey(), currentCount); termAtt.setEmpty().append(result); return true; } else { return false; } } } protected SemiStructureTokenizer(Reader input); protected SemiStructureTokenizer(AttributeFactory factory, Reader input); @Override final boolean incrementToken(); }### Answer:
@Test public void testIncrementToken() throws Exception { } |
### Question:
OperationJoin { public OperationJoin setOperations(Operation... ops) { if (ops.length == 0) { throw new IllegalArgumentException("At least one operation to join expected"); } if (this.operationIterator != null) { throw new IllegalStateException(ERROR_MSG_OPERATIONS_ALREADY_SET); } for (Operation op : ops) { prepareOperation(op); } this.operationIterator = this.operations.values().iterator(); return this; } private OperationJoin(); static OperationJoin create(); static OperationJoin create(Operation... ops); static OperationJoin create(Collection<Operation> ops); static OperationJoin create(Stream<Operation> ops); OperationJoin setOperations(Operation... ops); OperationJoin setOperations(Collection<Operation> ops); OperationJoin setOperations(Stream<Operation> ops); void sendWith(ServiceRequestSender sender, int batchSize); void sendWith(ServiceRequestSender sender); OperationJoin setCompletion(JoinedCompletionHandler joinedCompletion); boolean isEmpty(); Collection<Operation> getOperations(); Map<Long, Throwable> getFailures(); Operation getOperation(long id); static final String ERROR_MSG_BATCH_LIMIT_VIOLATED; static final String ERROR_MSG_INVALID_BATCH_SIZE; static final String ERROR_MSG_OPERATIONS_ALREADY_SET; }### Answer:
@Test public void testSetOperations() throws Throwable { OperationJoin operationJoin = OperationJoin.create(); Operation op1 = createServiceOperation(this.services.get(0)); Operation op2 = createServiceOperation(this.services.get(1)); Operation op3 = createServiceOperation(this.services.get(2)); host.testStart(1); operationJoin .setOperations(op1, op2, op3) .setCompletion((ops, exs) -> { if (exs != null) { host.failIteration(exs.values().iterator().next()); } else { host.completeIteration(); } }).sendWith(host); host.testWait(); } |
### Question:
FactoryService extends StatelessService { protected String buildDefaultChildSelfLink() { return getHost().nextUUID(); } FactoryService(Class<? extends ServiceDocument> childServiceDocumentType); static FactoryService create(Class<? extends Service> childServiceType,
ServiceOption... options); static FactoryService create(Class<? extends Service> childServiceType,
Class<? extends ServiceDocument> childServiceDocumentType, ServiceOption... options); static FactoryService createIdempotent(Class<? extends Service> childServiceType); static FactoryService createIdempotent(Class<? extends Service> childServiceType,
Class<? extends ServiceDocument> childServiceDocumentType); void setSelfQueryResultLimit(int limit); int getSelfQueryResultLimit(); void setUseBodyForSelfLink(boolean useBody); boolean hasChildOption(ServiceOption option); @Override void handleStart(Operation startPost); @Override void authorizeRequest(Operation op); @Override void handleRequest(Operation op); @Override void handleRequest(Operation op, OperationProcessingStage opProcessingStage); @Override void handleStop(Operation op); @Override void handleGet(Operation get); void completeGetWithQuery(Operation op, EnumSet<ServiceOption> caps); @Override void handleOptions(Operation op); @Override void handlePost(Operation op); @Override void toggleOption(ServiceOption option, boolean enable); @Override String getPeerNodeSelectorPath(); @Override void setPeerNodeSelectorPath(String link); @Override URI getUri(); @Override ServiceDocument getDocumentTemplate(); @Override void handleConfigurationRequest(Operation request); @Override void handleNodeGroupMaintenance(Operation maintOp); abstract Service createServiceInstance(); static final String PROPERTY_NAME_MAX_SYNCH_RETRY_COUNT; static final int MAX_SYNCH_RETRY_COUNT; static final Integer SELF_QUERY_RESULT_LIMIT; }### Answer:
@Test public void buildChildSelfLink() throws Throwable { SomeFactoryService f = new SomeFactoryService(); f = (SomeFactoryService) this.host.startServiceAndWait(f, UUID.randomUUID().toString(), null); String idHash = Utils.computeHash(this.host.getId()); assertTrue(f.buildDefaultChildSelfLink().startsWith(idHash)); long s = System.nanoTime(); for (int i = 0; i < this.iterationCount; i++) { assertTrue(f.buildDefaultChildSelfLink() != null); } long e = System.nanoTime(); double thpt = (double) this.iterationCount / (e - s); thpt *= TimeUnit.SECONDS.toNanos(1); this.host.log("throughput (calls/sec) %f", thpt); s = System.nanoTime(); for (int i = 0; i < this.iterationCount; i++) { assertTrue(UUID.randomUUID().toString() != null); } e = System.nanoTime(); thpt = (double) this.iterationCount / (e - s); thpt *= TimeUnit.SECONDS.toNanos(1); this.host.log("UUID.randomUUID().toString() throughput (calls/sec) %f", thpt); } |
### Question:
QueryTaskClientHelper { public QueryTaskClientHelper<T> setBaseUri(URI baseUri) { assertNotNull(baseUri, "'baseUri' must not be null."); this.baseUri = baseUri; return this; } private QueryTaskClientHelper(Class<T> type); static QueryTaskClientHelper<T> create(Class<T> type); QueryTaskClientHelper<T> setDocumentLink(String documentSelfLink); QueryTaskClientHelper<T> setUpdatedDocumentSince(long documentSinceUpdateTimeMicros,
String documentSelfLink); QueryTaskClientHelper<T> setUpdatedSince(long documentSinceUpdateTimeMicros); QueryTaskClientHelper<T> sendWith(ServiceHost serviceHost); QueryTaskClientHelper<T> sendWith(Service service); QueryTaskClientHelper<T> setQueryTask(QueryTask queryTask); QueryTaskClientHelper<T> setBaseUri(URI baseUri); QueryTaskClientHelper<T> setFactoryPath(String factoryPath); QueryTaskClientHelper<T> setResultHandler(ResultHandler<T> resultHandler); static long getDefaultQueryExpiration(); QueryElementResult<T> result(Object json, long count); static QueryElementResult<S> resultLink(
String selfLink, long count); static QueryElementResult<S> countResult(
long count); static QueryElementResult<S> noResult(); static final long QUERY_RETRIEVAL_RETRY_INTERVAL_MILLIS; static final long DEFAULT_EXPIRATION_TIME_IN_MICROS; static final Integer DEFAULT_QUERY_RESULT_LIMIT; }### Answer:
@Test public void testQueryDocumentWithBaseUri() throws Throwable { try { this.queryHelper.setBaseUri(null); fail("IllegalArgumentException expected with null base URI."); } catch (IllegalArgumentException e) { } this.minimalTestStates = queryDocumentWithBaseUri("testLink"); assertEquals(0, this.minimalTestStates.size()); MinimalTestServiceState minimalTestState = new MinimalTestServiceState(); minimalTestState.id = this.idValue1; minimalTestState = doPost(minimalTestState); this.minimalTestStates = queryDocumentWithBaseUri(minimalTestState.documentSelfLink); assertEquals(1, this.minimalTestStates.size()); assertEquals(minimalTestState.documentSelfLink, this.minimalTestStates.get(0).documentSelfLink); assertEquals(this.idValue1, this.minimalTestStates.get(0).id); delete(minimalTestState); this.minimalTestStates = queryDocumentWithBaseUri(minimalTestState.documentSelfLink); assertEquals(0, this.minimalTestStates.size()); } |
### Question:
QueryTaskClientHelper { public QueryTaskClientHelper<T> setFactoryPath(String factoryPath) { assertNotNull(factoryPath, "'factoryPath' must not be null."); this.factoryPath = factoryPath; return this; } private QueryTaskClientHelper(Class<T> type); static QueryTaskClientHelper<T> create(Class<T> type); QueryTaskClientHelper<T> setDocumentLink(String documentSelfLink); QueryTaskClientHelper<T> setUpdatedDocumentSince(long documentSinceUpdateTimeMicros,
String documentSelfLink); QueryTaskClientHelper<T> setUpdatedSince(long documentSinceUpdateTimeMicros); QueryTaskClientHelper<T> sendWith(ServiceHost serviceHost); QueryTaskClientHelper<T> sendWith(Service service); QueryTaskClientHelper<T> setQueryTask(QueryTask queryTask); QueryTaskClientHelper<T> setBaseUri(URI baseUri); QueryTaskClientHelper<T> setFactoryPath(String factoryPath); QueryTaskClientHelper<T> setResultHandler(ResultHandler<T> resultHandler); static long getDefaultQueryExpiration(); QueryElementResult<T> result(Object json, long count); static QueryElementResult<S> resultLink(
String selfLink, long count); static QueryElementResult<S> countResult(
long count); static QueryElementResult<S> noResult(); static final long QUERY_RETRIEVAL_RETRY_INTERVAL_MILLIS; static final long DEFAULT_EXPIRATION_TIME_IN_MICROS; static final Integer DEFAULT_QUERY_RESULT_LIMIT; }### Answer:
@Test public void testQueryDocumentWithFactoryPath() throws Throwable { try { this.queryHelper.setFactoryPath(null); fail("IllegalArgumentException expected with null factoryPath."); } catch (IllegalArgumentException e) { } this.minimalTestStates = queryDocumentWithFactoryPath("testLink"); assertEquals(0, this.minimalTestStates.size()); MinimalTestServiceState minimalTestState = new MinimalTestServiceState(); minimalTestState.id = this.idValue1; minimalTestState = doPost(minimalTestState); this.minimalTestStates = queryDocumentWithFactoryPath(minimalTestState.documentSelfLink); assertEquals(1, this.minimalTestStates.size()); assertEquals(minimalTestState.documentSelfLink, this.minimalTestStates.get(0).documentSelfLink); assertEquals(this.idValue1, this.minimalTestStates.get(0).id); delete(minimalTestState); this.minimalTestStates = queryDocumentWithFactoryPath(minimalTestState.documentSelfLink); assertEquals(0, this.minimalTestStates.size()); } |
### Question:
QueryTaskClientHelper { public static <T extends ServiceDocument> QueryTaskClientHelper<T> create(Class<T> type) { return new QueryTaskClientHelper<T>(type); } private QueryTaskClientHelper(Class<T> type); static QueryTaskClientHelper<T> create(Class<T> type); QueryTaskClientHelper<T> setDocumentLink(String documentSelfLink); QueryTaskClientHelper<T> setUpdatedDocumentSince(long documentSinceUpdateTimeMicros,
String documentSelfLink); QueryTaskClientHelper<T> setUpdatedSince(long documentSinceUpdateTimeMicros); QueryTaskClientHelper<T> sendWith(ServiceHost serviceHost); QueryTaskClientHelper<T> sendWith(Service service); QueryTaskClientHelper<T> setQueryTask(QueryTask queryTask); QueryTaskClientHelper<T> setBaseUri(URI baseUri); QueryTaskClientHelper<T> setFactoryPath(String factoryPath); QueryTaskClientHelper<T> setResultHandler(ResultHandler<T> resultHandler); static long getDefaultQueryExpiration(); QueryElementResult<T> result(Object json, long count); static QueryElementResult<S> resultLink(
String selfLink, long count); static QueryElementResult<S> countResult(
long count); static QueryElementResult<S> noResult(); static final long QUERY_RETRIEVAL_RETRY_INTERVAL_MILLIS; static final long DEFAULT_EXPIRATION_TIME_IN_MICROS; static final Integer DEFAULT_QUERY_RESULT_LIMIT; }### Answer:
@Test public void testCountQuery() throws Throwable { int numberOfServices = 20; this.services = this.host.doThroughputServiceStart(numberOfServices, MinimalTestService.class, this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.PERSISTENCE), null); Query query = Builder.create().addKindFieldClause(MinimalTestServiceState.class).build(); QueryTask q = QueryTask.Builder.createDirectTask() .addOption(QueryOption.COUNT) .setQuery(query).build(); List<Long> results = new ArrayList<>(); query(q, (r, e) -> { if (e != null) { this.host.failIteration(e); } else if (!r.hasResult()) { this.host.completeIteration(); } else { results.add(r.getCount()); } }); assertEquals(1, results.size()); assertEquals(20, results.get(0).intValue()); } |
### Question:
SynchronizationTaskService extends TaskService<SynchronizationTaskService.State> { public static SynchronizationTaskService create(Supplier<Service> childServiceInstantiator) { if (childServiceInstantiator.get() == null) { throw new IllegalArgumentException( "childServiceInstantiator created null child service"); } SynchronizationTaskService taskService = new SynchronizationTaskService(); taskService.childServiceInstantiator = childServiceInstantiator; return taskService; } SynchronizationTaskService(); static SynchronizationTaskService create(Supplier<Service> childServiceInstantiator); @Override void handleStart(Operation post); @Override void handlePut(Operation put); State validatePutRequest(State currentTask, Operation put); @Override void handlePatch(Operation patch); void handleSubStage(State task); static final String FACTORY_LINK; static final String STAT_NAME_CHILD_SYNCH_RETRY_COUNT; static final String STAT_NAME_SYNCH_RETRY_COUNT; static final int MAX_CHILD_SYNCH_RETRY_COUNT; }### Answer:
@Test public void cacheUpdateAfterSynchronization() throws Throwable { setUpMultiNode(); for (VerificationHost host : this.host.getInProcessHostMap().values()) { host.setServiceCacheClearDelayMicros(TimeUnit.MINUTES.toMicros(3)); } this.host.setNodeGroupQuorum(this.nodeCount - 1); this.host.waitForNodeGroupConvergence(); List<ExampleServiceState> exampleStates = this.host.createExampleServices( this.host.getPeerHost(), this.serviceCount, null, ExampleService.FACTORY_LINK); Map<String, ExampleServiceState> exampleStatesMap = exampleStates.stream().collect(Collectors.toMap(s -> s.documentSelfLink, s -> s)); VerificationHost hostToStop = this.host.getPeerHost(); this.host.stopHost(hostToStop); this.host.waitForNodeUnavailable(ServiceUriPaths.DEFAULT_NODE_GROUP, this.host.getInProcessHostMap().values(), hostToStop); this.host.waitForNodeGroupConvergence(this.host.getPeerCount()); VerificationHost peer = this.host.getPeerHost(); this.host.waitForReplicatedFactoryChildServiceConvergence( this.host.getNodeGroupToFactoryMap(ExampleService.FACTORY_LINK), exampleStatesMap, this.exampleStateConvergenceChecker, exampleStatesMap.size(), 0, this.nodeCount - 1); List<Operation> ops = new ArrayList<>(); for (ExampleServiceState s : exampleStates) { Operation op = Operation.createGet(peer, s.documentSelfLink); ops.add(op); } List<ExampleServiceState> newExampleStates = this.host.getTestRequestSender().sendAndWait(ops, ExampleServiceState.class); Map<String, ExampleServiceState> newExampleStatesMap = newExampleStates.stream().collect(Collectors.toMap(s -> s.documentSelfLink, s -> s)); for (ExampleServiceState s : exampleStates) { ExampleServiceState ns = newExampleStatesMap.get(s.documentSelfLink); if (ns.documentEpoch > s.documentEpoch) { ServiceHost newOwner = this.host.getInProcessHostMap().values().stream().filter(h -> h.getId().equals(ns.documentOwner)).iterator().next(); QueryTask.Query query = QueryTask.Query.Builder.create() .addKindFieldClause(ExampleServiceState.class) .addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK, s.documentSelfLink) .build(); QueryTask task = QueryTask.Builder.createDirectTask() .setQuery(query) .addOption(QueryTask.QuerySpecification.QueryOption.EXPAND_CONTENT) .build(); Operation op = Operation.createPost(newOwner, ServiceUriPaths.CORE_LOCAL_QUERY_TASKS) .setBody(task); task = this.host.getTestRequestSender().sendAndWait(op, QueryTask.class); ServiceDocumentQueryResult result = task.results; assertEquals(1, result.documentCount.longValue()); ExampleServiceState nsFromIndex = Utils.fromJson(result.documents.values().iterator().next(), ExampleServiceState.class); assertFalse(ns.documentVersion < nsFromIndex.documentVersion); } } } |
### Question:
OperationProcessingChain { public static OperationProcessingChain create(Filter... filters) { OperationProcessingChain opProcessingChain = new OperationProcessingChain(); for (Filter filter : filters) { filter.init(); opProcessingChain.filters.add(filter); } return opProcessingChain; } private OperationProcessingChain(); OperationProcessingContext createContext(ServiceHost host); OperationProcessingChain setLogLevel(Level logLevel); OperationProcessingChain toggleLogging(boolean loggingEnabled); OperationProcessingChain setLogFilter(Predicate<Operation> logFilter); static OperationProcessingChain create(Filter... filters); void close(); void processRequest(Operation op, OperationProcessingContext context,
Consumer<Operation> operationConsumer); void resumeProcessingRequest(Operation op, OperationProcessingContext context,
FilterReturnCode filterReturnCode, Throwable e); }### Answer:
@Test public void testCounterServiceWithOperationFilters() throws Throwable { Service counterService = createCounterService(); OperationProcessingChain opProcessingChain = OperationProcessingChain.create( new OperationLogger()); counterService.setOperationProcessingChain(opProcessingChain); for (int i = 0; i < COUNT; i++) { incrementCounter(false); } int counter = getCounter(); assertEquals(COUNT, counter); this.host.setOperationTimeOutMicros(TimeUnit.MILLISECONDS.toMicros(250)); opProcessingChain = OperationProcessingChain.create( new OperationLogger(), new OperationPatchDropper()); counterService.setOperationProcessingChain(opProcessingChain); incrementCounter(true); counter = getCounter(); assertEquals(COUNT, counter); }
@Test public void testCounterServiceJumpOperationProcessingStage() throws Throwable { Service counterService = createCounterService(); OperationProcessingChain opProcessingChain = OperationProcessingChain.create( new OperationLogger(), new OperationNextFiltersBypasser(counterService), new OperationPatchDropper()); counterService.setOperationProcessingChain(opProcessingChain); for (int i = 0; i < COUNT; i++) { incrementCounter(false); } int counter = getCounter(); assertEquals(COUNT, counter); } |
### Question:
NettyHttpServiceClient implements ServiceClient { @Override public void send(Operation op) { sendRequest(op); } static ServiceClient create(String userAgent,
ExecutorService executor,
ScheduledExecutorService scheduledExecutor); static ServiceClient create(String userAgent,
ExecutorService executor,
ScheduledExecutorService scheduledExecutor,
ServiceHost host); @Override void start(); @Override void stop(); ServiceClient setHttpProxy(URI proxy); @Override void send(Operation op); @Override void sendRequest(Operation op); @Override void handleMaintenance(Operation op); @Override ServiceClient setPendingRequestQueueLimit(int limit); @Override int getPendingRequestQueueLimit(); @Override ServiceClient setConnectionLimitPerTag(String tag, int limit); @Override int getConnectionLimitPerTag(String tag); ServiceClient setHttp2SslContext(SslContext context); SslContext getHttp2SslContext(); @Override ServiceClient setSSLContext(SSLContext context); @Override SSLContext getSSLContext(); NettyChannelPool getChannelPool(); NettyChannelPool getHttp2ChannelPool(); NettyChannelPool getSslChannelPool(); NettyChannelContext getInUseHttp2SslContext(String tag, String host, int port); NettyChannelContext getInUseHttp2Context(String tag, String host, int port); @Override ConnectionPoolMetrics getConnectionPoolMetrics(boolean http2); @Override ConnectionPoolMetrics getConnectionPoolMetricsPerTag(String tag); int getInUseContextCount(String tag, String host, int port); void clearCookieJar(); @Override int getRequestPayloadSizeLimit(); @Override ServiceClient setRequestPayloadSizeLimit(int limit); static final int DEFAULT_CONNECTIONS_PER_HOST; static final Logger LOGGER; }### Answer:
@Test public void httpsFailure() throws Throwable { List<Service> services = this.host.doThroughputServiceStart(10, MinimalTestService.class, this.host.buildMinimalTestState(), null, null); List<URI> uris = new ArrayList<>(); for (Service s : services) { URI u = UriUtils.extendUri(this.host.getSecureUri(), s.getSelfLink()); uris.add(u); } this.host.getServiceState(null, MinimalTestServiceState.class, uris); this.host.testStart(uris.size()); for (URI u : uris) { MinimalTestServiceState body = (MinimalTestServiceState) this.host .buildMinimalTestState(); body.id = MinimalTestService.STRING_MARKER_FAIL_WITH_PLAIN_TEXT_RESPONSE; Operation put = Operation.createPatch(u).setBody(body) .setCompletion((o, e) -> { this.host.completeIteration(); }); this.host.send(put); } this.host.testWait(); } |
### Question:
BasicAuthenticationService extends StatelessService { protected long getExpirationTime(AuthenticationRequest authRequest) { long expirationTimeSeconds = authRequest.sessionExpirationSeconds != null ? authRequest.sessionExpirationSeconds : AUTH_TOKEN_EXPIRATION_SECONDS; if (this.UPPER_SESSION_LIMIT_SECONDS != null && expirationTimeSeconds > this.UPPER_SESSION_LIMIT_SECONDS) { expirationTimeSeconds = this.UPPER_SESSION_LIMIT_SECONDS; } return Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(expirationTimeSeconds)); } BasicAuthenticationService(); @Override void authorizeRequest(Operation op); @Override boolean queueRequest(Operation op); @Override void handlePost(Operation op); static final String SELF_LINK; static final String AUTH_TOKEN_EXPIRATION_MICROS_PROPERTY; static final String UPPER_SESSION_LIMIT_SECONDS_PROPERTY; }### Answer:
@Test public void testGetExpirationTime() throws Throwable { BasicAuthenticationService basicAuthenticationService = new BasicAuthenticationService(); AuthenticationRequest authRequest = new AuthenticationRequest(); authRequest.sessionExpirationSeconds = null; long expectedSec = Instant.now().getEpochSecond() + BasicAuthenticationService.AUTH_TOKEN_EXPIRATION_SECONDS; long result = basicAuthenticationService.getExpirationTime(authRequest); assertEquals(expectedSec, TimeUnit.MICROSECONDS.toSeconds(result)); authRequest.sessionExpirationSeconds = (long) 0; result = basicAuthenticationService.getExpirationTime(authRequest); expectedSec = Instant.now().getEpochSecond(); assertEquals(expectedSec, TimeUnit.MICROSECONDS.toSeconds(result)); authRequest.sessionExpirationSeconds = (long) -1; result = basicAuthenticationService.getExpirationTime(authRequest); expectedSec = Instant.now().getEpochSecond() - 1; assertEquals(expectedSec, TimeUnit.MICROSECONDS.toSeconds(result)); authRequest.sessionExpirationSeconds = UPPER_SESSION_LIMIT - 1; result = basicAuthenticationService.getExpirationTime(authRequest); expectedSec = Instant.now().getEpochSecond() + UPPER_SESSION_LIMIT - 1; assertEquals(expectedSec, TimeUnit.MICROSECONDS.toSeconds(result)); authRequest.sessionExpirationSeconds = UPPER_SESSION_LIMIT; result = basicAuthenticationService.getExpirationTime(authRequest); expectedSec = Instant.now().getEpochSecond() + UPPER_SESSION_LIMIT; assertEquals(expectedSec, TimeUnit.MICROSECONDS.toSeconds(result)); authRequest.sessionExpirationSeconds = UPPER_SESSION_LIMIT + 1; result = basicAuthenticationService.getExpirationTime(authRequest); expectedSec = Instant.now().getEpochSecond() + UPPER_SESSION_LIMIT; assertEquals(expectedSec, TimeUnit.MICROSECONDS.toSeconds(result)); } |
### Question:
ServiceDocument { public void copyTo(ServiceDocument target) { target.documentEpoch = this.documentEpoch; target.documentDescription = this.documentDescription; target.documentOwner = this.documentOwner; target.documentSourceLink = this.documentSourceLink; target.documentVersion = this.documentVersion; target.documentKind = this.documentKind; target.documentSelfLink = this.documentSelfLink; target.documentUpdateTimeMicros = this.documentUpdateTimeMicros; target.documentUpdateAction = this.documentUpdateAction; target.documentExpirationTimeMicros = this.documentExpirationTimeMicros; target.documentAuthPrincipalLink = this.documentAuthPrincipalLink; } void copyTo(ServiceDocument target); static boolean isDeleted(ServiceDocument document); static EnumSet<DocumentRelationship> compare(ServiceDocument stateA,
ServiceDocument stateB,
ServiceDocumentDescription desc,
long timeEpsilon); static boolean equals(ServiceDocumentDescription description,
ServiceDocument currentDocument, ServiceDocument newDocument); static boolean isBuiltInDocumentField(String name); static boolean isAutoMergeEnabledByDefaultForField(String name); static boolean isBuiltInSignatureExcludedDocumentField(String name); static boolean isBuiltInInfrastructureDocumentField(String name); static boolean isBuiltInNonIndexedDocumentField(String name); static boolean isBuiltInDocumentFieldWithNullExampleValue(String name); static boolean isLink(String name); static boolean isLinks(String name); static final String FIELD_NAME_SELF_LINK; static final String FIELD_NAME_VERSION; static final String FIELD_NAME_EPOCH; static final String FIELD_NAME_KIND; static final String FIELD_NAME_UPDATE_TIME_MICROS; static final String FIELD_NAME_UPDATE_ACTION; static final String FIELD_NAME_DESCRIPTION; static final String FIELD_NAME_OWNER; static final String FIELD_NAME_SOURCE_LINK; static final String FIELD_NAME_EXPIRATION_TIME_MICROS; static final String FIELD_NAME_AUTH_PRINCIPAL_LINK; static final String FIELD_NAME_SUFFIX_LINK; static final String FIELD_NAME_SUFFIX_LINKS; static final String FIELD_NAME_SUFFIX_ADDRESS; public ServiceDocumentDescription documentDescription; public long documentVersion; public Long documentEpoch; public String documentKind; public String documentSelfLink; public long documentUpdateTimeMicros; public String documentUpdateAction; public long documentExpirationTimeMicros; public String documentOwner; public String documentSourceLink; public String documentAuthPrincipalLink; }### Answer:
@Test public void copyTo() throws Throwable { assertEquals(25, ServiceDocument.class.getFields().length); ServiceDocument one = new ServiceDocument(); one.documentAuthPrincipalLink = UUID.randomUUID().toString(); one.documentDescription = null; one.documentEpoch = Utils.getNowMicrosUtc(); one.documentExpirationTimeMicros = Utils.getNowMicrosUtc(); one.documentKind = UUID.randomUUID().toString(); one.documentOwner = UUID.randomUUID().toString(); one.documentSelfLink = UUID.randomUUID().toString(); one.documentSourceLink = UUID.randomUUID().toString(); one.documentUpdateAction = UUID.randomUUID().toString(); one.documentUpdateTimeMicros = Utils.getNowMicrosUtc(); one.documentVersion = Utils.getNowMicrosUtc(); ServiceDocument two = new ServiceDocument(); one.copyTo(two); assertEquals(one.documentAuthPrincipalLink, two.documentAuthPrincipalLink); assertEquals(one.documentDescription, two.documentDescription); assertEquals(one.documentEpoch, two.documentEpoch); assertEquals(one.documentExpirationTimeMicros, two.documentExpirationTimeMicros); assertEquals(one.documentKind, two.documentKind); assertEquals(one.documentOwner, two.documentOwner); assertEquals(one.documentSelfLink, two.documentSelfLink); assertEquals(one.documentSourceLink, two.documentSourceLink); assertEquals(one.documentUpdateAction, two.documentUpdateAction); assertEquals(one.documentUpdateTimeMicros, two.documentUpdateTimeMicros); assertEquals(one.documentVersion, two.documentVersion); } |
### Question:
ServiceDocument { public static boolean equals(ServiceDocumentDescription description, ServiceDocument currentDocument, ServiceDocument newDocument) { if (currentDocument == null || newDocument == null) { throw new IllegalArgumentException( "Null Service documents cannot be checked for equality."); } try { String currentSignature = Utils.computeSignature(currentDocument, description); String newSignature = Utils.computeSignature(newDocument, description); return currentSignature.equals(newSignature); } catch (Exception e) { if (e instanceof IllegalArgumentException) { throw (IllegalArgumentException) e; } return false; } } void copyTo(ServiceDocument target); static boolean isDeleted(ServiceDocument document); static EnumSet<DocumentRelationship> compare(ServiceDocument stateA,
ServiceDocument stateB,
ServiceDocumentDescription desc,
long timeEpsilon); static boolean equals(ServiceDocumentDescription description,
ServiceDocument currentDocument, ServiceDocument newDocument); static boolean isBuiltInDocumentField(String name); static boolean isAutoMergeEnabledByDefaultForField(String name); static boolean isBuiltInSignatureExcludedDocumentField(String name); static boolean isBuiltInInfrastructureDocumentField(String name); static boolean isBuiltInNonIndexedDocumentField(String name); static boolean isBuiltInDocumentFieldWithNullExampleValue(String name); static boolean isLink(String name); static boolean isLinks(String name); static final String FIELD_NAME_SELF_LINK; static final String FIELD_NAME_VERSION; static final String FIELD_NAME_EPOCH; static final String FIELD_NAME_KIND; static final String FIELD_NAME_UPDATE_TIME_MICROS; static final String FIELD_NAME_UPDATE_ACTION; static final String FIELD_NAME_DESCRIPTION; static final String FIELD_NAME_OWNER; static final String FIELD_NAME_SOURCE_LINK; static final String FIELD_NAME_EXPIRATION_TIME_MICROS; static final String FIELD_NAME_AUTH_PRINCIPAL_LINK; static final String FIELD_NAME_SUFFIX_LINK; static final String FIELD_NAME_SUFFIX_LINKS; static final String FIELD_NAME_SUFFIX_ADDRESS; public ServiceDocumentDescription documentDescription; public long documentVersion; public Long documentEpoch; public String documentKind; public String documentSelfLink; public long documentUpdateTimeMicros; public String documentUpdateAction; public long documentExpirationTimeMicros; public String documentOwner; public String documentSourceLink; public String documentAuthPrincipalLink; }### Answer:
@Test public void equals() throws Throwable { ServiceDocumentDescription description = TestUtils.buildStateDescription( ComparableServiceState.class, null); ComparableServiceState initialState = new ComparableServiceState(); initialState.name = UUID.randomUUID().toString(); initialState.counter = 5L; initialState.booleanValue = false; ComparableServiceState modifiedState = new ComparableServiceState(); modifiedState.name = initialState.name; modifiedState.counter = initialState.counter; modifiedState.booleanValue = initialState.booleanValue; boolean value = ServiceDocument.equals(description, initialState, modifiedState); assertTrue(value); initialState = new ComparableServiceState(); initialState.name = UUID.randomUUID().toString(); initialState.counter = 5L; initialState.booleanValue = false; modifiedState = new ComparableServiceState(); modifiedState.name = initialState.name; modifiedState.counter = 10L; modifiedState.booleanValue = initialState.booleanValue; value = ServiceDocument.equals(description, initialState, modifiedState); assertFalse(value); initialState = new ComparableServiceState(); initialState.name = UUID.randomUUID().toString(); initialState.counter = 5L; initialState.booleanValue = false; modifiedState = new ComparableServiceState(); modifiedState.name = initialState.name; modifiedState.counter = initialState.counter; modifiedState.booleanValue = true; value = ServiceDocument.equals(description, initialState, modifiedState); assertFalse(value); initialState = new ComparableServiceState(); initialState.documentOwner = UUID.randomUUID().toString(); initialState.counter = 10L; modifiedState = new ComparableServiceState(); modifiedState.documentOwner = UUID.randomUUID().toString(); modifiedState.counter = 10L; value = ServiceDocument.equals(description, initialState, modifiedState); assertEquals(true, value); } |
### Question:
MixAll { public static boolean compareAndIncreaseOnly(final AtomicLong target, final long value) { long prev = target.get(); while (value > prev) { boolean updated = target.compareAndSet(prev, value); if (updated) return true; prev = target.get(); } return false; } static String getWSAddr(); static String getRetryTopic(final String consumerGroup); static boolean isSysConsumerGroup(final String consumerGroup); static boolean isSystemTopic(final String topic); static String getDLQTopic(final String consumerGroup); static String brokerVIPChannel(final boolean isChange, final String brokerAddr); static long getPID(); static long createBrokerId(final String ip, final int port); static void string2File(final String str, final String fileName); static void string2FileNotSafe(final String str, final String fileName); static String file2String(final String fileName); static String file2String(final File file); static String file2String(final URL url); static String findClassPath(Class<?> c); static void printObjectProperties(final Logger log, final Object object); static void printObjectProperties(final Logger log, final Object object, final boolean onlyImportantField); static String properties2String(final Properties properties); static Properties string2Properties(final String str); static Properties object2Properties(final Object object); static void properties2Object(final Properties p, final Object object); static boolean isPropertiesEqual(final Properties p1, final Properties p2); static List<String> getLocalInetAddress(); static boolean isLocalAddr(String address); static boolean compareAndIncreaseOnly(final AtomicLong target, final long value); static String localhostName(); static String humanReadableByteCount(long bytes, boolean si); Set<String> list2Set(List<String> values); List<String> set2List(Set<String> values); static final String ROCKETMQ_HOME_ENV; static final String ROCKETMQ_HOME_PROPERTY; static final String NAMESRV_ADDR_ENV; static final String NAMESRV_ADDR_PROPERTY; static final String MESSAGE_COMPRESS_LEVEL; static final String DEFAULT_NAMESRV_ADDR_LOOKUP; static final String WS_DOMAIN_NAME; static final String WS_DOMAIN_SUBGROUP; static final String DEFAULT_TOPIC; static final String BENCHMARK_TOPIC; static final String DEFAULT_PRODUCER_GROUP; static final String DEFAULT_CONSUMER_GROUP; static final String TOOLS_CONSUMER_GROUP; static final String FILTERSRV_CONSUMER_GROUP; static final String MONITOR_CONSUMER_GROUP; static final String CLIENT_INNER_PRODUCER_GROUP; static final String SELF_TEST_PRODUCER_GROUP; static final String SELF_TEST_CONSUMER_GROUP; static final String SELF_TEST_TOPIC; static final String OFFSET_MOVED_EVENT; static final String ONS_HTTP_PROXY_GROUP; static final String CID_ONSAPI_PERMISSION_GROUP; static final String CID_ONSAPI_OWNER_GROUP; static final String CID_ONSAPI_PULL_GROUP; static final String CID_RMQ_SYS_PREFIX; static final List<String> LOCAL_INET_ADDRESS; static final String LOCALHOST; static final String DEFAULT_CHARSET; static final long MASTER_ID; static final long CURRENT_JVM_PID; static final String RETRY_GROUP_TOPIC_PREFIX; static final String DLQ_GROUP_TOPIC_PREFIX; static final String SYSTEM_TOPIC_PREFIX; static final String UNIQUE_MSG_QUERY_FLAG; static final String DEFAULT_TRACE_REGION_ID; static final String CONSUME_CONTEXT_TYPE; }### Answer:
@Test public void testCompareAndIncreaseOnly() { AtomicLong target = new AtomicLong(5); assertThat(MixAll.compareAndIncreaseOnly(target, 6)).isTrue(); assertThat(target.get()).isEqualTo(6); assertThat(MixAll.compareAndIncreaseOnly(target, 4)).isFalse(); assertThat(target.get()).isEqualTo(6); } |
### Question:
MixAll { public static void string2File(final String str, final String fileName) throws IOException { String tmpFile = fileName + ".tmp"; string2FileNotSafe(str, tmpFile); String bakFile = fileName + ".bak"; String prevContent = file2String(fileName); if (prevContent != null) { string2FileNotSafe(prevContent, bakFile); } File file = new File(fileName); file.delete(); file = new File(tmpFile); file.renameTo(new File(fileName)); } static String getWSAddr(); static String getRetryTopic(final String consumerGroup); static boolean isSysConsumerGroup(final String consumerGroup); static boolean isSystemTopic(final String topic); static String getDLQTopic(final String consumerGroup); static String brokerVIPChannel(final boolean isChange, final String brokerAddr); static long getPID(); static long createBrokerId(final String ip, final int port); static void string2File(final String str, final String fileName); static void string2FileNotSafe(final String str, final String fileName); static String file2String(final String fileName); static String file2String(final File file); static String file2String(final URL url); static String findClassPath(Class<?> c); static void printObjectProperties(final Logger log, final Object object); static void printObjectProperties(final Logger log, final Object object, final boolean onlyImportantField); static String properties2String(final Properties properties); static Properties string2Properties(final String str); static Properties object2Properties(final Object object); static void properties2Object(final Properties p, final Object object); static boolean isPropertiesEqual(final Properties p1, final Properties p2); static List<String> getLocalInetAddress(); static boolean isLocalAddr(String address); static boolean compareAndIncreaseOnly(final AtomicLong target, final long value); static String localhostName(); static String humanReadableByteCount(long bytes, boolean si); Set<String> list2Set(List<String> values); List<String> set2List(Set<String> values); static final String ROCKETMQ_HOME_ENV; static final String ROCKETMQ_HOME_PROPERTY; static final String NAMESRV_ADDR_ENV; static final String NAMESRV_ADDR_PROPERTY; static final String MESSAGE_COMPRESS_LEVEL; static final String DEFAULT_NAMESRV_ADDR_LOOKUP; static final String WS_DOMAIN_NAME; static final String WS_DOMAIN_SUBGROUP; static final String DEFAULT_TOPIC; static final String BENCHMARK_TOPIC; static final String DEFAULT_PRODUCER_GROUP; static final String DEFAULT_CONSUMER_GROUP; static final String TOOLS_CONSUMER_GROUP; static final String FILTERSRV_CONSUMER_GROUP; static final String MONITOR_CONSUMER_GROUP; static final String CLIENT_INNER_PRODUCER_GROUP; static final String SELF_TEST_PRODUCER_GROUP; static final String SELF_TEST_CONSUMER_GROUP; static final String SELF_TEST_TOPIC; static final String OFFSET_MOVED_EVENT; static final String ONS_HTTP_PROXY_GROUP; static final String CID_ONSAPI_PERMISSION_GROUP; static final String CID_ONSAPI_OWNER_GROUP; static final String CID_ONSAPI_PULL_GROUP; static final String CID_RMQ_SYS_PREFIX; static final List<String> LOCAL_INET_ADDRESS; static final String LOCALHOST; static final String DEFAULT_CHARSET; static final long MASTER_ID; static final long CURRENT_JVM_PID; static final String RETRY_GROUP_TOPIC_PREFIX; static final String DLQ_GROUP_TOPIC_PREFIX; static final String SYSTEM_TOPIC_PREFIX; static final String UNIQUE_MSG_QUERY_FLAG; static final String DEFAULT_TRACE_REGION_ID; static final String CONSUME_CONTEXT_TYPE; }### Answer:
@Test public void testString2File() throws IOException { String fileName = System.getProperty("java.io.tmpdir") + File.separator + "MixAllTest" + System.currentTimeMillis(); MixAll.string2File("MixAll_testString2File", fileName); assertThat(MixAll.file2String(fileName)).isEqualTo("MixAll_testString2File"); } |
### Question:
CommandUtil { public static Set<String> fetchMasterAddrByClusterName(final MQAdminExt adminExt, final String clusterName) throws InterruptedException, RemotingConnectException, RemotingTimeoutException, RemotingSendRequestException, MQBrokerException { Set<String> masterSet = new HashSet<String>(); ClusterInfo clusterInfoSerializeWrapper = adminExt.examineBrokerClusterInfo(); Set<String> brokerNameSet = clusterInfoSerializeWrapper.getClusterAddrTable().get(clusterName); if (brokerNameSet != null) { for (String brokerName : brokerNameSet) { BrokerData brokerData = clusterInfoSerializeWrapper.getBrokerAddrTable().get(brokerName); if (brokerData != null) { String addr = brokerData.getBrokerAddrs().get(MixAll.MASTER_ID); if (addr != null) { masterSet.add(addr); } } } } else { System.out .printf("[error] Make sure the specified clusterName exists or the nameserver which connected is correct."); } return masterSet; } static Map<String/*master addr*/, List<String>/*slave addr*/> fetchMasterAndSlaveDistinguish(
final MQAdminExt adminExt, final String clusterName); static Set<String> fetchMasterAddrByClusterName(final MQAdminExt adminExt, final String clusterName); static Set<String> fetchMasterAndSlaveAddrByClusterName(final MQAdminExt adminExt, final String clusterName); static Set<String> fetchBrokerNameByClusterName(final MQAdminExt adminExt, final String clusterName); static String fetchBrokerNameByAddr(final MQAdminExt adminExt, final String addr); }### Answer:
@Test public void testFetchMasterAddrByClusterName() throws InterruptedException, MQBrokerException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException { Set<String> result = CommandUtil.fetchMasterAddrByClusterName(defaultMQAdminExtImpl, "default-cluster"); assertThat(result.size()).isEqualTo(0); } |
### Question:
CommandUtil { public static Set<String> fetchBrokerNameByClusterName(final MQAdminExt adminExt, final String clusterName) throws Exception { ClusterInfo clusterInfoSerializeWrapper = adminExt.examineBrokerClusterInfo(); Set<String> brokerNameSet = clusterInfoSerializeWrapper.getClusterAddrTable().get(clusterName); if (brokerNameSet.isEmpty()) { throw new Exception( "Make sure the specified clusterName exists or the nameserver which connected is correct."); } return brokerNameSet; } static Map<String/*master addr*/, List<String>/*slave addr*/> fetchMasterAndSlaveDistinguish(
final MQAdminExt adminExt, final String clusterName); static Set<String> fetchMasterAddrByClusterName(final MQAdminExt adminExt, final String clusterName); static Set<String> fetchMasterAndSlaveAddrByClusterName(final MQAdminExt adminExt, final String clusterName); static Set<String> fetchBrokerNameByClusterName(final MQAdminExt adminExt, final String clusterName); static String fetchBrokerNameByAddr(final MQAdminExt adminExt, final String addr); }### Answer:
@Test public void testFetchBrokerNameByClusterName() throws Exception { Set<String> result = CommandUtil.fetchBrokerNameByClusterName(defaultMQAdminExtImpl, "default-cluster"); assertThat(result.contains("default-broker")).isTrue(); assertThat(result.contains("default-broker-one")).isTrue(); assertThat(result.size()).isEqualTo(2); } |
### Question:
Validators { public static void checkTopic(String topic) throws MQClientException { if (UtilAll.isBlank(topic)) { throw new MQClientException("The specified topic is blank", null); } if (!regularExpressionMatcher(topic, PATTERN)) { throw new MQClientException(String.format( "The specified topic[%s] contains illegal characters, allowing only %s", topic, VALID_PATTERN_STR), null); } if (topic.length() > CHARACTER_MAX_LENGTH) { throw new MQClientException("The specified topic is longer than topic max length 255.", null); } if (topic.equals(MixAll.DEFAULT_TOPIC)) { throw new MQClientException( String.format("The topic[%s] is conflict with default topic.", topic), null); } } static String getGroupWithRegularExpression(String origin, String patternStr); static void checkGroup(String group); static boolean regularExpressionMatcher(String origin, Pattern pattern); static void checkMessage(Message msg, DefaultMQProducer defaultMQProducer); static void checkTopic(String topic); static final String VALID_PATTERN_STR; static final Pattern PATTERN; static final int CHARACTER_MAX_LENGTH; }### Answer:
@Test public void testCheckTopic_Success() throws MQClientException { Validators.checkTopic("Hello"); Validators.checkTopic("%RETRY%Hello"); Validators.checkTopic("_%RETRY%Hello"); Validators.checkTopic("-%RETRY%Hello"); Validators.checkTopic("223-%RETRY%Hello"); }
@Test public void testCheckTopic_HasIllegalCharacters() { String illegalTopic = "TOPIC&*^"; try { Validators.checkTopic(illegalTopic); failBecauseExceptionWasNotThrown(MQClientException.class); } catch (MQClientException e) { assertThat(e).hasMessageStartingWith(String.format("The specified topic[%s] contains illegal characters, allowing only %s", illegalTopic, Validators.VALID_PATTERN_STR)); } }
@Test public void testCheckTopic_UseDefaultTopic() { String defaultTopic = MixAll.DEFAULT_TOPIC; try { Validators.checkTopic(defaultTopic); failBecauseExceptionWasNotThrown(MQClientException.class); } catch (MQClientException e) { assertThat(e).hasMessageStartingWith(String.format("The topic[%s] is conflict with default topic.", defaultTopic)); } }
@Test public void testCheckTopic_BlankTopic() { String blankTopic = ""; try { Validators.checkTopic(blankTopic); failBecauseExceptionWasNotThrown(MQClientException.class); } catch (MQClientException e) { assertThat(e).hasMessageStartingWith("The specified topic is blank"); } }
@Test public void testCheckTopic_TooLongTopic() { String tooLongTopic = StringUtils.rightPad("TooLongTopic", Validators.CHARACTER_MAX_LENGTH + 1, "_"); assertThat(tooLongTopic.length()).isGreaterThan(Validators.CHARACTER_MAX_LENGTH); try { Validators.checkTopic(tooLongTopic); failBecauseExceptionWasNotThrown(MQClientException.class); } catch (MQClientException e) { assertThat(e).hasMessageStartingWith("The specified topic is longer than topic max length 255."); } } |
### Question:
MQClientInstance { public boolean registerProducer(final String group, final DefaultMQProducerImpl producer) { if (null == group || null == producer) { return false; } MQProducerInner prev = this.producerTable.putIfAbsent(group, producer); if (prev != null) { log.warn("the producer group[{}] exist already.", group); return false; } return true; } MQClientInstance(ClientConfig clientConfig, int instanceIndex, String clientId); MQClientInstance(ClientConfig clientConfig, int instanceIndex, String clientId, RPCHook rpcHook); static TopicPublishInfo topicRouteData2TopicPublishInfo(final String topic, final TopicRouteData route); static Set<MessageQueue> topicRouteData2TopicSubscribeInfo(final String topic, final TopicRouteData route); void start(); String getClientId(); void updateTopicRouteInfoFromNameServer(); void checkClientInBroker(); void sendHeartbeatToAllBrokerWithLock(); void adjustThreadPool(); boolean updateTopicRouteInfoFromNameServer(final String topic); boolean updateTopicRouteInfoFromNameServer(final String topic, boolean isDefault, DefaultMQProducer defaultMQProducer); void shutdown(); boolean registerConsumer(final String group, final MQConsumerInner consumer); void unregisterConsumer(final String group); boolean registerProducer(final String group, final DefaultMQProducerImpl producer); void unregisterProducer(final String group); boolean registerAdminExt(final String group, final MQAdminExtInner admin); void unregisterAdminExt(final String group); void rebalanceImmediately(); void doRebalance(); MQProducerInner selectProducer(final String group); MQConsumerInner selectConsumer(final String group); FindBrokerResult findBrokerAddressInAdmin(final String brokerName); String findBrokerAddressInPublish(final String brokerName); FindBrokerResult findBrokerAddressInSubscribe(//
final String brokerName, //
final long brokerId, //
final boolean onlyThisBroker//
); int findBrokerVersion(String brokerName, String brokerAddr); List<String> findConsumerIdList(final String topic, final String group); String findBrokerAddrByTopic(final String topic); void resetOffset(String topic, String group, Map<MessageQueue, Long> offsetTable); Map<MessageQueue, Long> getConsumerStatus(String topic, String group); TopicRouteData getAnExistTopicRouteData(final String topic); MQClientAPIImpl getMQClientAPIImpl(); MQAdminImpl getMQAdminImpl(); long getBootTimestamp(); ScheduledExecutorService getScheduledExecutorService(); PullMessageService getPullMessageService(); DefaultMQProducer getDefaultMQProducer(); ConcurrentMap<String, TopicRouteData> getTopicRouteTable(); ConsumeMessageDirectlyResult consumeMessageDirectly(final MessageExt msg, //
final String consumerGroup, //
final String brokerName); ConsumerRunningInfo consumerRunningInfo(final String consumerGroup); ConsumerStatsManager getConsumerStatsManager(); NettyClientConfig getNettyClientConfig(); }### Answer:
@Test public void testRegisterProducer() { boolean flag = mqClientInstance.registerProducer(group, mock(DefaultMQProducerImpl.class)); assertThat(flag).isTrue(); flag = mqClientInstance.registerProducer(group, mock(DefaultMQProducerImpl.class)); assertThat(flag).isFalse(); mqClientInstance.unregisterProducer(group); flag = mqClientInstance.registerProducer(group, mock(DefaultMQProducerImpl.class)); assertThat(flag).isTrue(); } |
### Question:
MQClientInstance { public boolean registerConsumer(final String group, final MQConsumerInner consumer) { if (null == group || null == consumer) { return false; } MQConsumerInner prev = this.consumerTable.putIfAbsent(group, consumer); if (prev != null) { log.warn("the consumer group[" + group + "] exist already."); return false; } return true; } MQClientInstance(ClientConfig clientConfig, int instanceIndex, String clientId); MQClientInstance(ClientConfig clientConfig, int instanceIndex, String clientId, RPCHook rpcHook); static TopicPublishInfo topicRouteData2TopicPublishInfo(final String topic, final TopicRouteData route); static Set<MessageQueue> topicRouteData2TopicSubscribeInfo(final String topic, final TopicRouteData route); void start(); String getClientId(); void updateTopicRouteInfoFromNameServer(); void checkClientInBroker(); void sendHeartbeatToAllBrokerWithLock(); void adjustThreadPool(); boolean updateTopicRouteInfoFromNameServer(final String topic); boolean updateTopicRouteInfoFromNameServer(final String topic, boolean isDefault, DefaultMQProducer defaultMQProducer); void shutdown(); boolean registerConsumer(final String group, final MQConsumerInner consumer); void unregisterConsumer(final String group); boolean registerProducer(final String group, final DefaultMQProducerImpl producer); void unregisterProducer(final String group); boolean registerAdminExt(final String group, final MQAdminExtInner admin); void unregisterAdminExt(final String group); void rebalanceImmediately(); void doRebalance(); MQProducerInner selectProducer(final String group); MQConsumerInner selectConsumer(final String group); FindBrokerResult findBrokerAddressInAdmin(final String brokerName); String findBrokerAddressInPublish(final String brokerName); FindBrokerResult findBrokerAddressInSubscribe(//
final String brokerName, //
final long brokerId, //
final boolean onlyThisBroker//
); int findBrokerVersion(String brokerName, String brokerAddr); List<String> findConsumerIdList(final String topic, final String group); String findBrokerAddrByTopic(final String topic); void resetOffset(String topic, String group, Map<MessageQueue, Long> offsetTable); Map<MessageQueue, Long> getConsumerStatus(String topic, String group); TopicRouteData getAnExistTopicRouteData(final String topic); MQClientAPIImpl getMQClientAPIImpl(); MQAdminImpl getMQAdminImpl(); long getBootTimestamp(); ScheduledExecutorService getScheduledExecutorService(); PullMessageService getPullMessageService(); DefaultMQProducer getDefaultMQProducer(); ConcurrentMap<String, TopicRouteData> getTopicRouteTable(); ConsumeMessageDirectlyResult consumeMessageDirectly(final MessageExt msg, //
final String consumerGroup, //
final String brokerName); ConsumerRunningInfo consumerRunningInfo(final String consumerGroup); ConsumerStatsManager getConsumerStatsManager(); NettyClientConfig getNettyClientConfig(); }### Answer:
@Test public void testRegisterConsumer() throws RemotingException, InterruptedException, MQBrokerException { boolean flag = mqClientInstance.registerConsumer(group, mock(MQConsumerInner.class)); assertThat(flag).isTrue(); flag = mqClientInstance.registerConsumer(group, mock(MQConsumerInner.class)); assertThat(flag).isFalse(); mqClientInstance.unregisterConsumer(group); flag = mqClientInstance.registerConsumer(group, mock(MQConsumerInner.class)); assertThat(flag).isTrue(); } |
### Question:
MQClientInstance { public boolean registerAdminExt(final String group, final MQAdminExtInner admin) { if (null == group || null == admin) { return false; } MQAdminExtInner prev = this.adminExtTable.putIfAbsent(group, admin); if (prev != null) { log.warn("the admin group[{}] exist already.", group); return false; } return true; } MQClientInstance(ClientConfig clientConfig, int instanceIndex, String clientId); MQClientInstance(ClientConfig clientConfig, int instanceIndex, String clientId, RPCHook rpcHook); static TopicPublishInfo topicRouteData2TopicPublishInfo(final String topic, final TopicRouteData route); static Set<MessageQueue> topicRouteData2TopicSubscribeInfo(final String topic, final TopicRouteData route); void start(); String getClientId(); void updateTopicRouteInfoFromNameServer(); void checkClientInBroker(); void sendHeartbeatToAllBrokerWithLock(); void adjustThreadPool(); boolean updateTopicRouteInfoFromNameServer(final String topic); boolean updateTopicRouteInfoFromNameServer(final String topic, boolean isDefault, DefaultMQProducer defaultMQProducer); void shutdown(); boolean registerConsumer(final String group, final MQConsumerInner consumer); void unregisterConsumer(final String group); boolean registerProducer(final String group, final DefaultMQProducerImpl producer); void unregisterProducer(final String group); boolean registerAdminExt(final String group, final MQAdminExtInner admin); void unregisterAdminExt(final String group); void rebalanceImmediately(); void doRebalance(); MQProducerInner selectProducer(final String group); MQConsumerInner selectConsumer(final String group); FindBrokerResult findBrokerAddressInAdmin(final String brokerName); String findBrokerAddressInPublish(final String brokerName); FindBrokerResult findBrokerAddressInSubscribe(//
final String brokerName, //
final long brokerId, //
final boolean onlyThisBroker//
); int findBrokerVersion(String brokerName, String brokerAddr); List<String> findConsumerIdList(final String topic, final String group); String findBrokerAddrByTopic(final String topic); void resetOffset(String topic, String group, Map<MessageQueue, Long> offsetTable); Map<MessageQueue, Long> getConsumerStatus(String topic, String group); TopicRouteData getAnExistTopicRouteData(final String topic); MQClientAPIImpl getMQClientAPIImpl(); MQAdminImpl getMQAdminImpl(); long getBootTimestamp(); ScheduledExecutorService getScheduledExecutorService(); PullMessageService getPullMessageService(); DefaultMQProducer getDefaultMQProducer(); ConcurrentMap<String, TopicRouteData> getTopicRouteTable(); ConsumeMessageDirectlyResult consumeMessageDirectly(final MessageExt msg, //
final String consumerGroup, //
final String brokerName); ConsumerRunningInfo consumerRunningInfo(final String consumerGroup); ConsumerStatsManager getConsumerStatsManager(); NettyClientConfig getNettyClientConfig(); }### Answer:
@Test public void testRegisterAdminExt() { boolean flag = mqClientInstance.registerAdminExt(group, mock(MQAdminExtInner.class)); assertThat(flag).isTrue(); flag = mqClientInstance.registerAdminExt(group, mock(MQAdminExtInner.class)); assertThat(flag).isFalse(); mqClientInstance.unregisterAdminExt(group); flag = mqClientInstance.registerAdminExt(group, mock(MQAdminExtInner.class)); assertThat(flag).isTrue(); } |
### Question:
RemotingCommand { public static byte[] markProtocolType(int source, SerializeType type) { byte[] result = new byte[4]; result[0] = type.getCode(); result[1] = (byte) ((source >> 16) & 0xFF); result[2] = (byte) ((source >> 8) & 0xFF); result[3] = (byte) (source & 0xFF); return result; } protected RemotingCommand(); static RemotingCommand createRequestCommand(int code, CommandCustomHeader customHeader); static RemotingCommand createResponseCommand(Class<? extends CommandCustomHeader> classHeader); static RemotingCommand createResponseCommand(int code, String remark,
Class<? extends CommandCustomHeader> classHeader); static RemotingCommand createResponseCommand(int code, String remark); static RemotingCommand decode(final byte[] array); static RemotingCommand decode(final ByteBuffer byteBuffer); static int getHeaderLength(int length); static SerializeType getProtocolType(int source); static int createNewRequestId(); static SerializeType getSerializeTypeConfigInThisServer(); static byte[] markProtocolType(int source, SerializeType type); void markResponseType(); CommandCustomHeader readCustomHeader(); void writeCustomHeader(CommandCustomHeader customHeader); CommandCustomHeader decodeCommandCustomHeader(
Class<? extends CommandCustomHeader> classHeader); ByteBuffer encode(); void makeCustomHeaderToNet(); ByteBuffer encodeHeader(); ByteBuffer encodeHeader(final int bodyLength); void markOnewayRPC(); @JSONField(serialize = false) boolean isOnewayRPC(); int getCode(); void setCode(int code); @JSONField(serialize = false) RemotingCommandType getType(); @JSONField(serialize = false) boolean isResponseType(); LanguageCode getLanguage(); void setLanguage(LanguageCode language); int getVersion(); void setVersion(int version); int getOpaque(); void setOpaque(int opaque); int getFlag(); void setFlag(int flag); String getRemark(); void setRemark(String remark); byte[] getBody(); void setBody(byte[] body); HashMap<String, String> getExtFields(); void setExtFields(HashMap<String, String> extFields); void addExtField(String key, String value); @Override String toString(); SerializeType getSerializeTypeCurrentRPC(); void setSerializeTypeCurrentRPC(SerializeType serializeTypeCurrentRPC); static final String SERIALIZE_TYPE_PROPERTY; static final String SERIALIZE_TYPE_ENV; static final String REMOTING_VERSION_KEY; }### Answer:
@Test public void testMarkProtocolType_JSONProtocolType() { int source = 261; SerializeType type = SerializeType.JSON; byte[] result = RemotingCommand.markProtocolType(source, type); assertThat(result).isEqualTo(new byte[]{0, 0, 1, 5}); }
@Test public void testMarkProtocolType_ROCKETMQProtocolType() { int source = 16777215; SerializeType type = SerializeType.ROCKETMQ; byte[] result = RemotingCommand.markProtocolType(source, type); assertThat(result).isEqualTo(new byte[]{1, -1, -1, -1}); }
@Test public void testMarkProtocolType_JSONProtocolType() { int source = 261; SerializeType type = SerializeType.JSON; byte[] result = RemotingCommand.markProtocolType(source, type); assertThat(result).isEqualTo(new byte[] {0, 0, 1, 5}); }
@Test public void testMarkProtocolType_ROCKETMQProtocolType() { int source = 16777215; SerializeType type = SerializeType.ROCKETMQ; byte[] result = RemotingCommand.markProtocolType(source, type); assertThat(result).isEqualTo(new byte[] {1, -1, -1, -1}); } |
### Question:
RemotingCommand { public static RemotingCommand createResponseCommand(Class<? extends CommandCustomHeader> classHeader) { return createResponseCommand(RemotingSysResponseCode.SYSTEM_ERROR, "not set any response code", classHeader); } protected RemotingCommand(); static RemotingCommand createRequestCommand(int code, CommandCustomHeader customHeader); static RemotingCommand createResponseCommand(Class<? extends CommandCustomHeader> classHeader); static RemotingCommand createResponseCommand(int code, String remark,
Class<? extends CommandCustomHeader> classHeader); static RemotingCommand createResponseCommand(int code, String remark); static RemotingCommand decode(final byte[] array); static RemotingCommand decode(final ByteBuffer byteBuffer); static int getHeaderLength(int length); static SerializeType getProtocolType(int source); static int createNewRequestId(); static SerializeType getSerializeTypeConfigInThisServer(); static byte[] markProtocolType(int source, SerializeType type); void markResponseType(); CommandCustomHeader readCustomHeader(); void writeCustomHeader(CommandCustomHeader customHeader); CommandCustomHeader decodeCommandCustomHeader(
Class<? extends CommandCustomHeader> classHeader); ByteBuffer encode(); void makeCustomHeaderToNet(); ByteBuffer encodeHeader(); ByteBuffer encodeHeader(final int bodyLength); void markOnewayRPC(); @JSONField(serialize = false) boolean isOnewayRPC(); int getCode(); void setCode(int code); @JSONField(serialize = false) RemotingCommandType getType(); @JSONField(serialize = false) boolean isResponseType(); LanguageCode getLanguage(); void setLanguage(LanguageCode language); int getVersion(); void setVersion(int version); int getOpaque(); void setOpaque(int opaque); int getFlag(); void setFlag(int flag); String getRemark(); void setRemark(String remark); byte[] getBody(); void setBody(byte[] body); HashMap<String, String> getExtFields(); void setExtFields(HashMap<String, String> extFields); void addExtField(String key, String value); @Override String toString(); SerializeType getSerializeTypeCurrentRPC(); void setSerializeTypeCurrentRPC(SerializeType serializeTypeCurrentRPC); static final String SERIALIZE_TYPE_PROPERTY; static final String SERIALIZE_TYPE_ENV; static final String REMOTING_VERSION_KEY; }### Answer:
@Test public void testCreateResponseCommand_FailToCreateCommand() { System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, "2333"); int code = RemotingSysResponseCode.SUCCESS; String remark = "Sample remark"; RemotingCommand cmd = RemotingCommand.createResponseCommand(code ,remark, CommandCustomHeader.class); assertThat(cmd).isNull(); }
@Test public void testCreateResponseCommand_FailToCreateCommand() { System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, "2333"); int code = RemotingSysResponseCode.SUCCESS; String remark = "Sample remark"; RemotingCommand cmd = RemotingCommand.createResponseCommand(code, remark, CommandCustomHeader.class); assertThat(cmd).isNull(); } |
### Question:
RouteInfoManager { public byte[] getAllClusterInfo() { ClusterInfo clusterInfoSerializeWrapper = new ClusterInfo(); clusterInfoSerializeWrapper.setBrokerAddrTable(this.brokerAddrTable); clusterInfoSerializeWrapper.setClusterAddrTable(this.clusterAddrTable); return clusterInfoSerializeWrapper.encode(); } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testGetAllClusterInfo() { byte[] clusterInfo = routeInfoManager.getAllClusterInfo(); assertThat(clusterInfo).isNotNull(); } |
### Question:
RouteInfoManager { public byte[] getAllTopicList() { TopicList topicList = new TopicList(); try { try { this.lock.readLock().lockInterruptibly(); topicList.getTopicList().addAll(this.topicQueueTable.keySet()); } finally { this.lock.readLock().unlock(); } } catch (Exception e) { log.error("getAllTopicList Exception", e); } return topicList.encode(); } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testGetAllTopicList() { byte[] topicInfo = routeInfoManager.getAllTopicList(); Assert.assertTrue(topicInfo != null); assertThat(topicInfo).isNotNull(); } |
### Question:
RouteInfoManager { public int wipeWritePermOfBrokerByLock(final String brokerName) { try { try { this.lock.writeLock().lockInterruptibly(); return wipeWritePermOfBroker(brokerName); } finally { this.lock.writeLock().unlock(); } } catch (Exception e) { log.error("wipeWritePermOfBrokerByLock Exception", e); } return 0; } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testWipeWritePermOfBrokerByLock() { int result = routeInfoManager.wipeWritePermOfBrokerByLock("default-broker"); assertThat(result).isEqualTo(0); } |
### Question:
RouteInfoManager { public TopicRouteData pickupTopicRouteData(final String topic) { TopicRouteData topicRouteData = new TopicRouteData(); boolean foundQueueData = false; boolean foundBrokerData = false; Set<String> brokerNameSet = new HashSet<String>(); List<BrokerData> brokerDataList = new LinkedList<BrokerData>(); topicRouteData.setBrokerDatas(brokerDataList); HashMap<String, List<String>> filterServerMap = new HashMap<String, List<String>>(); topicRouteData.setFilterServerTable(filterServerMap); try { try { this.lock.readLock().lockInterruptibly(); List<QueueData> queueDataList = this.topicQueueTable.get(topic); if (queueDataList != null) { topicRouteData.setQueueDatas(queueDataList); foundQueueData = true; Iterator<QueueData> it = queueDataList.iterator(); while (it.hasNext()) { QueueData qd = it.next(); brokerNameSet.add(qd.getBrokerName()); } for (String brokerName : brokerNameSet) { BrokerData brokerData = this.brokerAddrTable.get(brokerName); if (null != brokerData) { BrokerData brokerDataClone = new BrokerData(brokerData.getCluster(), brokerData.getBrokerName(), (HashMap<Long, String>) brokerData .getBrokerAddrs().clone()); brokerDataList.add(brokerDataClone); foundBrokerData = true; for (final String brokerAddr : brokerDataClone.getBrokerAddrs().values()) { List<String> filterServerList = this.filterServerTable.get(brokerAddr); filterServerMap.put(brokerAddr, filterServerList); } } } } } finally { this.lock.readLock().unlock(); } } catch (Exception e) { log.error("pickupTopicRouteData Exception", e); } if (log.isDebugEnabled()) { log.debug("pickupTopicRouteData {} {}", topic, topicRouteData); } if (foundBrokerData && foundQueueData) { return topicRouteData; } return null; } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testPickupTopicRouteData() { TopicRouteData result = routeInfoManager.pickupTopicRouteData("unit_test"); assertThat(result).isNull(); } |
### Question:
RouteInfoManager { public byte[] getSystemTopicList() { TopicList topicList = new TopicList(); try { try { this.lock.readLock().lockInterruptibly(); for (Map.Entry<String, Set<String>> entry : clusterAddrTable.entrySet()) { topicList.getTopicList().add(entry.getKey()); topicList.getTopicList().addAll(entry.getValue()); } if (brokerAddrTable != null && !brokerAddrTable.isEmpty()) { Iterator<String> it = brokerAddrTable.keySet().iterator(); while (it.hasNext()) { BrokerData bd = brokerAddrTable.get(it.next()); HashMap<Long, String> brokerAddrs = bd.getBrokerAddrs(); if (brokerAddrs != null && !brokerAddrs.isEmpty()) { Iterator<Long> it2 = brokerAddrs.keySet().iterator(); topicList.setBrokerAddr(brokerAddrs.get(it2.next())); break; } } } } finally { this.lock.readLock().unlock(); } } catch (Exception e) { log.error("getAllTopicList Exception", e); } return topicList.encode(); } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testGetSystemTopicList() { byte[] topicList = routeInfoManager.getSystemTopicList(); assertThat(topicList).isNotNull(); } |
### Question:
RouteInfoManager { public byte[] getTopicsByCluster(String cluster) { TopicList topicList = new TopicList(); try { try { this.lock.readLock().lockInterruptibly(); Set<String> brokerNameSet = this.clusterAddrTable.get(cluster); for (String brokerName : brokerNameSet) { Iterator<Entry<String, List<QueueData>>> topicTableIt = this.topicQueueTable.entrySet().iterator(); while (topicTableIt.hasNext()) { Entry<String, List<QueueData>> topicEntry = topicTableIt.next(); String topic = topicEntry.getKey(); List<QueueData> queueDatas = topicEntry.getValue(); for (QueueData queueData : queueDatas) { if (brokerName.equals(queueData.getBrokerName())) { topicList.getTopicList().add(topic); break; } } } } } finally { this.lock.readLock().unlock(); } } catch (Exception e) { log.error("getAllTopicList Exception", e); } return topicList.encode(); } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testGetTopicsByCluster() { byte[] topicList = routeInfoManager.getTopicsByCluster("default-cluster"); assertThat(topicList).isNotNull(); } |
### Question:
RouteInfoManager { public byte[] getUnitTopics() { TopicList topicList = new TopicList(); try { try { this.lock.readLock().lockInterruptibly(); Iterator<Entry<String, List<QueueData>>> topicTableIt = this.topicQueueTable.entrySet().iterator(); while (topicTableIt.hasNext()) { Entry<String, List<QueueData>> topicEntry = topicTableIt.next(); String topic = topicEntry.getKey(); List<QueueData> queueDatas = topicEntry.getValue(); if (queueDatas != null && queueDatas.size() > 0 && TopicSysFlag.hasUnitFlag(queueDatas.get(0).getTopicSynFlag())) { topicList.getTopicList().add(topic); } } } finally { this.lock.readLock().unlock(); } } catch (Exception e) { log.error("getAllTopicList Exception", e); } return topicList.encode(); } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testGetUnitTopics() { byte[] topicList = routeInfoManager.getUnitTopics(); assertThat(topicList).isNotNull(); } |
### Question:
RouteInfoManager { public byte[] getHasUnitSubTopicList() { TopicList topicList = new TopicList(); try { try { this.lock.readLock().lockInterruptibly(); Iterator<Entry<String, List<QueueData>>> topicTableIt = this.topicQueueTable.entrySet().iterator(); while (topicTableIt.hasNext()) { Entry<String, List<QueueData>> topicEntry = topicTableIt.next(); String topic = topicEntry.getKey(); List<QueueData> queueDatas = topicEntry.getValue(); if (queueDatas != null && queueDatas.size() > 0 && TopicSysFlag.hasUnitSubFlag(queueDatas.get(0).getTopicSynFlag())) { topicList.getTopicList().add(topic); } } } finally { this.lock.readLock().unlock(); } } catch (Exception e) { log.error("getAllTopicList Exception", e); } return topicList.encode(); } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testGetHasUnitSubTopicList() { byte[] topicList = routeInfoManager.getHasUnitSubTopicList(); assertThat(topicList).isNotNull(); } |
### Question:
RouteInfoManager { public byte[] getHasUnitSubUnUnitTopicList() { TopicList topicList = new TopicList(); try { try { this.lock.readLock().lockInterruptibly(); Iterator<Entry<String, List<QueueData>>> topicTableIt = this.topicQueueTable.entrySet().iterator(); while (topicTableIt.hasNext()) { Entry<String, List<QueueData>> topicEntry = topicTableIt.next(); String topic = topicEntry.getKey(); List<QueueData> queueDatas = topicEntry.getValue(); if (queueDatas != null && queueDatas.size() > 0 && !TopicSysFlag.hasUnitFlag(queueDatas.get(0).getTopicSynFlag()) && TopicSysFlag.hasUnitSubFlag(queueDatas.get(0).getTopicSynFlag())) { topicList.getTopicList().add(topic); } } } finally { this.lock.readLock().unlock(); } } catch (Exception e) { log.error("getAllTopicList Exception", e); } return topicList.encode(); } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testGetHasUnitSubUnUnitTopicList() { byte[] topicList = routeInfoManager.getHasUnitSubUnUnitTopicList(); assertThat(topicList).isNotNull(); } |
### Question:
KVConfigManager { public void putKVConfig(final String namespace, final String key, final String value) { try { this.lock.writeLock().lockInterruptibly(); try { HashMap<String, String> kvTable = this.configTable.get(namespace); if (null == kvTable) { kvTable = new HashMap<String, String>(); this.configTable.put(namespace, kvTable); log.info("putKVConfig create new Namespace {}", namespace); } final String prev = kvTable.put(key, value); if (null != prev) { log.info("putKVConfig update config item, Namespace: {} Key: {} Value: {}", namespace, key, value); } else { log.info("putKVConfig create new config item, Namespace: {} Key: {} Value: {}", namespace, key, value); } } finally { this.lock.writeLock().unlock(); } } catch (InterruptedException e) { log.error("putKVConfig InterruptedException", e); } this.persist(); } KVConfigManager(NamesrvController namesrvController); void load(); void putKVConfig(final String namespace, final String key, final String value); void persist(); void deleteKVConfig(final String namespace, final String key); byte[] getKVListByNamespace(final String namespace); String getKVConfig(final String namespace, final String key); void printAllPeriodically(); }### Answer:
@Test public void testPutKVConfig() { kvConfigManager.load(); kvConfigManager.putKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, "UnitTest", "test"); byte[] kvConfig = kvConfigManager.getKVListByNamespace(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG); assertThat(kvConfig).isNotNull(); String value = kvConfigManager.getKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, "UnitTest"); assertThat(value).isEqualTo("test"); }
@Test public void testPutKVConfig() { kvConfigManager.putKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, "UnitTest", "test"); byte[] kvConfig = kvConfigManager.getKVListByNamespace(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG); assertThat(kvConfig).isNotNull(); String value = kvConfigManager.getKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, "UnitTest"); assertThat(value).isEqualTo("test"); } |
### Question:
DefaultPromise implements Promise<V> { @Override public boolean isCancelled() { return state.isCancelledState(); } DefaultPromise(); @Override boolean cancel(final boolean mayInterruptIfRunning); @Override boolean isCancelled(); @Override boolean isDone(); @Override V get(); @Override V get(final long timeout); @Override boolean set(final V value); @Override boolean setFailure(final Throwable cause); @Override void addListener(final PromiseListener<V> listener); @Override Throwable getThrowable(); }### Answer:
@Test public void testIsCancelled() throws Exception { assertThat(promise.isCancelled()).isEqualTo(false); } |
### Question:
DefaultPromise implements Promise<V> { @Override public boolean isDone() { return state.isDoneState(); } DefaultPromise(); @Override boolean cancel(final boolean mayInterruptIfRunning); @Override boolean isCancelled(); @Override boolean isDone(); @Override V get(); @Override V get(final long timeout); @Override boolean set(final V value); @Override boolean setFailure(final Throwable cause); @Override void addListener(final PromiseListener<V> listener); @Override Throwable getThrowable(); }### Answer:
@Test public void testIsDone() throws Exception { assertThat(promise.isDone()).isEqualTo(false); promise.set("Done"); assertThat(promise.isDone()).isEqualTo(true); } |
### Question:
DefaultPromise implements Promise<V> { @Override public V get() { return result; } DefaultPromise(); @Override boolean cancel(final boolean mayInterruptIfRunning); @Override boolean isCancelled(); @Override boolean isDone(); @Override V get(); @Override V get(final long timeout); @Override boolean set(final V value); @Override boolean setFailure(final Throwable cause); @Override void addListener(final PromiseListener<V> listener); @Override Throwable getThrowable(); }### Answer:
@Test public void testGet() throws Exception { promise.set("Done"); assertThat(promise.get()).isEqualTo("Done"); }
@Test public void testGet_WithTimeout() throws Exception { try { promise.get(100); failBecauseExceptionWasNotThrown(OMSRuntimeException.class); } catch (OMSRuntimeException e) { assertThat(e).hasMessageContaining("Get request result is timeout or interrupted"); } } |
### Question:
DefaultPromise implements Promise<V> { @Override public void addListener(final PromiseListener<V> listener) { if (listener == null) { throw new NullPointerException("FutureListener is null"); } boolean notifyNow = false; synchronized (lock) { if (!isDoing()) { notifyNow = true; } else { if (promiseListenerList == null) { promiseListenerList = new ArrayList<>(); } promiseListenerList.add(listener); } } if (notifyNow) { notifyListener(listener); } } DefaultPromise(); @Override boolean cancel(final boolean mayInterruptIfRunning); @Override boolean isCancelled(); @Override boolean isDone(); @Override V get(); @Override V get(final long timeout); @Override boolean set(final V value); @Override boolean setFailure(final Throwable cause); @Override void addListener(final PromiseListener<V> listener); @Override Throwable getThrowable(); }### Answer:
@Test public void testAddListener() throws Exception { promise.addListener(new PromiseListener<String>() { @Override public void operationCompleted(final Promise<String> promise) { assertThat(promise.get()).isEqualTo("Done"); } @Override public void operationFailed(final Promise<String> promise) { } }); promise.set("Done"); } |
### Question:
DefaultPromise implements Promise<V> { @Override public Throwable getThrowable() { return exception; } DefaultPromise(); @Override boolean cancel(final boolean mayInterruptIfRunning); @Override boolean isCancelled(); @Override boolean isDone(); @Override V get(); @Override V get(final long timeout); @Override boolean set(final V value); @Override boolean setFailure(final Throwable cause); @Override void addListener(final PromiseListener<V> listener); @Override Throwable getThrowable(); }### Answer:
@Test public void getThrowable() throws Exception { assertThat(promise.getThrowable()).isNull(); Throwable exception = new OMSRuntimeException("-1", "Test Error"); promise.setFailure(exception); assertThat(promise.getThrowable()).isEqualTo(exception); } |
### Question:
PushConsumerImpl implements PushConsumer { @Override public PushConsumer attachQueue(final String queueName, final MessageListener listener) { this.subscribeTable.put(queueName, listener); try { this.rocketmqPushConsumer.subscribe(queueName, "*"); } catch (MQClientException e) { throw new OMSRuntimeException("-1", String.format("RocketMQ push consumer can't attach to %s.", queueName)); } return this; } PushConsumerImpl(final KeyValue properties); @Override KeyValue properties(); @Override void resume(); @Override void suspend(); @Override boolean isSuspended(); @Override PushConsumer attachQueue(final String queueName, final MessageListener listener); @Override synchronized void startup(); @Override synchronized void shutdown(); }### Answer:
@Test public void testConsumeMessage() { final byte[] testBody = new byte[] {'a', 'b'}; MessageExt consumedMsg = new MessageExt(); consumedMsg.setMsgId("NewMsgId"); consumedMsg.setBody(testBody); consumedMsg.putUserProperty(NonStandardKeys.MESSAGE_DESTINATION, "TOPIC"); consumedMsg.setTopic("HELLO_QUEUE"); consumer.attachQueue("HELLO_QUEUE", new MessageListener() { @Override public void onMessage(final Message message, final ReceivedMessageContext context) { assertThat(message.headers().getString(MessageHeader.MESSAGE_ID)).isEqualTo("NewMsgId"); assertThat(((BytesMessage) message).getBody()).isEqualTo(testBody); context.ack(); } }); ((MessageListenerConcurrently) rocketmqPushConsumer .getMessageListener()).consumeMessage(Collections.singletonList(consumedMsg), null); } |
### Question:
LocalMessageCache implements ServiceLifecycle { long nextPullOffset(MessageQueue remoteQueue) { if (!pullOffsetTable.containsKey(remoteQueue)) { try { pullOffsetTable.putIfAbsent(remoteQueue, rocketmqPullConsumer.fetchConsumeOffset(remoteQueue, false)); } catch (MQClientException e) { log.error("A error occurred in fetch consume offset process.", e); } } return pullOffsetTable.get(remoteQueue); } LocalMessageCache(final DefaultMQPullConsumer rocketmqPullConsumer, final ClientConfig clientConfig); @Override void startup(); @Override void shutdown(); }### Answer:
@Test public void testNextPullOffset() throws Exception { MessageQueue messageQueue = new MessageQueue(); when(rocketmqPullConsume.fetchConsumeOffset(any(MessageQueue.class), anyBoolean())) .thenReturn(123L); assertThat(localMessageCache.nextPullOffset(new MessageQueue())).isEqualTo(123L); } |
### Question:
LocalMessageCache implements ServiceLifecycle { void submitConsumeRequest(ConsumeRequest consumeRequest) { try { consumeRequestCache.put(consumeRequest); } catch (InterruptedException ignore) { } } LocalMessageCache(final DefaultMQPullConsumer rocketmqPullConsumer, final ClientConfig clientConfig); @Override void startup(); @Override void shutdown(); }### Answer:
@Test public void testSubmitConsumeRequest() throws Exception { byte [] body = new byte[]{'1', '2', '3'}; MessageExt consumedMsg = new MessageExt(); consumedMsg.setMsgId("NewMsgId"); consumedMsg.setBody(body); consumedMsg.putUserProperty(NonStandardKeys.MESSAGE_DESTINATION, "TOPIC"); consumedMsg.setTopic("HELLO_QUEUE"); when(consumeRequest.getMessageExt()).thenReturn(consumedMsg); localMessageCache.submitConsumeRequest(consumeRequest); assertThat(localMessageCache.poll()).isEqualTo(consumedMsg); }
@Test public void testSubmitConsumeRequest() throws Exception { byte[] body = new byte[] {'1', '2', '3'}; MessageExt consumedMsg = new MessageExt(); consumedMsg.setMsgId("NewMsgId"); consumedMsg.setBody(body); consumedMsg.putUserProperty(NonStandardKeys.MESSAGE_DESTINATION, "TOPIC"); consumedMsg.setTopic("HELLO_QUEUE"); when(consumeRequest.getMessageExt()).thenReturn(consumedMsg); localMessageCache.submitConsumeRequest(consumeRequest); assertThat(localMessageCache.poll()).isEqualTo(consumedMsg); } |
### Question:
PullConsumerImpl implements PullConsumer { @Override public Message poll() { MessageExt rmqMsg = localMessageCache.poll(); return rmqMsg == null ? null : OMSUtil.msgConvert(rmqMsg); } PullConsumerImpl(final String queueName, final KeyValue properties); @Override KeyValue properties(); @Override Message poll(); @Override Message poll(final KeyValue properties); @Override void ack(final String messageId); @Override void ack(final String messageId, final KeyValue properties); @Override synchronized void startup(); @Override synchronized void shutdown(); }### Answer:
@Test public void testPoll() { final byte[] testBody = new byte[] {'a', 'b'}; MessageExt consumedMsg = new MessageExt(); consumedMsg.setMsgId("NewMsgId"); consumedMsg.setBody(testBody); consumedMsg.putUserProperty(NonStandardKeys.MESSAGE_DESTINATION, "TOPIC"); consumedMsg.setTopic(queueName); when(localMessageCache.poll()).thenReturn(consumedMsg); Message message = consumer.poll(); assertThat(message.headers().getString(MessageHeader.MESSAGE_ID)).isEqualTo("NewMsgId"); assertThat(((BytesMessage) message).getBody()).isEqualTo(testBody); }
@Test public void testPoll_WithTimeout() { Message message = consumer.poll(); assertThat(message).isNull(); message = consumer.poll(OMS.newKeyValue().put(PropertyKeys.OPERATION_TIMEOUT, 100)); assertThat(message).isNull(); } |
### Question:
SequenceProducerImpl extends AbstractOMSProducer implements SequenceProducer { @Override public synchronized void rollback() { msgCacheQueue.clear(); } SequenceProducerImpl(final KeyValue properties); @Override KeyValue properties(); @Override void send(final Message message); @Override void send(final Message message, final KeyValue properties); @Override synchronized void commit(); @Override synchronized void rollback(); }### Answer:
@Test public void testRollback() { when(rocketmqProducer.getMaxMessageSize()).thenReturn(1024); final BytesMessage message = producer.createBytesMessageToTopic("HELLO_TOPIC", new byte[] {'a'}); producer.send(message); producer.rollback(); producer.commit(); assertThat(message.headers().getString(MessageHeader.MESSAGE_ID)).isEqualTo(null); } |
### Question:
ProducerImpl extends AbstractOMSProducer implements Producer { @Override public SendResult send(final Message message) { return send(message, this.rocketmqProducer.getSendMsgTimeout()); } ProducerImpl(final KeyValue properties); @Override KeyValue properties(); @Override SendResult send(final Message message); @Override SendResult send(final Message message, final KeyValue properties); @Override Promise<SendResult> sendAsync(final Message message); @Override Promise<SendResult> sendAsync(final Message message, final KeyValue properties); @Override void sendOneway(final Message message); @Override void sendOneway(final Message message, final KeyValue properties); }### Answer:
@Test public void testSend_OK() throws InterruptedException, RemotingException, MQClientException, MQBrokerException { SendResult sendResult = new SendResult(); sendResult.setMsgId("TestMsgID"); sendResult.setSendStatus(SendStatus.SEND_OK); when(rocketmqProducer.send(any(Message.class), anyLong())).thenReturn(sendResult); io.openmessaging.SendResult omsResult = producer.send(producer.createBytesMessageToTopic("HELLO_TOPIC", new byte[] {'a'})); assertThat(omsResult.messageId()).isEqualTo("TestMsgID"); }
@Test public void testSend_Not_OK() throws InterruptedException, RemotingException, MQClientException, MQBrokerException { SendResult sendResult = new SendResult(); sendResult.setSendStatus(SendStatus.FLUSH_DISK_TIMEOUT); when(rocketmqProducer.send(any(Message.class), anyLong())).thenReturn(sendResult); try { producer.send(producer.createBytesMessageToTopic("HELLO_TOPIC", new byte[] {'a'})); failBecauseExceptionWasNotThrown(OMSRuntimeException.class); } catch (Exception e) { assertThat(e).hasMessageContaining("Send message to RocketMQ broker failed."); } }
@Test public void testSend_WithException() throws InterruptedException, RemotingException, MQClientException, MQBrokerException { when(rocketmqProducer.send(any(Message.class), anyLong())).thenThrow(MQClientException.class); try { producer.send(producer.createBytesMessageToTopic("HELLO_TOPIC", new byte[] {'a'})); failBecauseExceptionWasNotThrown(OMSRuntimeException.class); } catch (Exception e) { assertThat(e).hasMessageContaining("Send message to RocketMQ broker failed."); } } |
### Question:
BeanUtils { public static <T> T populate(final Properties properties, final Class<T> clazz) { T obj = null; try { obj = clazz.newInstance(); return populate(properties, obj); } catch (Throwable e) { log.warn("Error occurs !", e); } return obj; } static T populate(final Properties properties, final Class<T> clazz); static T populate(final KeyValue properties, final Class<T> clazz); static Class<?> getMethodClass(Class<?> clazz, String methodName); static void setProperties(Class<?> clazz, Object obj, String methodName,
Object value); static T populate(final Properties properties, final T obj); static T populate(final KeyValue properties, final T obj); }### Answer:
@Test public void testPopulate_ExistObj() { CustomizedConfig config = new CustomizedConfig(); config.setOmsConsumerId("NewConsumerId"); Assert.assertEquals(config.getOmsConsumerId(), "NewConsumerId"); config = BeanUtils.populate(properties, config); Assert.assertEquals(config.getRmqMaxRedeliveryTimes(), 120); Assert.assertEquals(config.getStringTest(), "kaka"); Assert.assertEquals(config.getRmqConsumerGroup(), "Default_Consumer_Group"); Assert.assertEquals(config.getRmqMessageConsumeTimeout(), 101); Assert.assertEquals(config.getLongTest(), 1234567890L); Assert.assertEquals(config.getDoubleTest(), 10.234, 0.000001); }
@Test public void testPopulate() { CustomizedConfig config = BeanUtils.populate(properties, CustomizedConfig.class); Assert.assertEquals(config.getRmqMaxRedeliveryTimes(), 120); Assert.assertEquals(config.getStringTest(), "kaka"); Assert.assertEquals(config.getRmqConsumerGroup(), "Default_Consumer_Group"); Assert.assertEquals(config.getRmqMessageConsumeTimeout(), 101); Assert.assertEquals(config.getLongTest(), 1234567890L); Assert.assertEquals(config.getDoubleTest(), 10.234, 0.000001); }
@Test public void testPopulate_ExistObj() { CustomizedConfig config = new CustomizedConfig(); config.setConsumerId("NewConsumerId"); Assert.assertEquals(config.getConsumerId(), "NewConsumerId"); config = BeanUtils.populate(properties, config); Assert.assertEquals(config.getRmqMaxRedeliveryTimes(), 120); Assert.assertEquals(config.getStringTest(), "kaka"); Assert.assertEquals(config.getRmqConsumerGroup(), "Default_Consumer_Group"); Assert.assertEquals(config.getRmqMessageConsumeTimeout(), 101); Assert.assertEquals(config.getLongTest(), 1234567890L); Assert.assertEquals(config.getDoubleTest(), 10.234, 0.000001); } |
### Question:
GetBrokerConfigCommand implements SubCommand { @Override public void execute(final CommandLine commandLine, final Options options, final RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { if (commandLine.hasOption('b')) { String brokerAddr = commandLine.getOptionValue('b').trim(); defaultMQAdminExt.start(); getAndPrint(defaultMQAdminExt, String.format("============%s============\n", brokerAddr), brokerAddr); } else if (commandLine.hasOption('c')) { String clusterName = commandLine.getOptionValue('c').trim(); defaultMQAdminExt.start(); Map<String, List<String>> masterAndSlaveMap = CommandUtil.fetchMasterAndSlaveDistinguish(defaultMQAdminExt, clusterName); for (String masterAddr : masterAndSlaveMap.keySet()) { getAndPrint( defaultMQAdminExt, String.format("============Master: %s============\n", masterAddr), masterAddr ); for (String slaveAddr : masterAndSlaveMap.get(masterAddr)) { getAndPrint( defaultMQAdminExt, String.format("============My Master: %s=====Slave: %s============\n", masterAddr, slaveAddr), slaveAddr ); } } } } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(final Options options); @Override void execute(final CommandLine commandLine, final Options options, final RPCHook rpcHook); }### Answer:
@Ignore @Test public void testExecute() throws SubCommandException { GetBrokerConfigCommand cmd = new GetBrokerConfigCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); cmd.execute(commandLine, options, null); } |
### Question:
BrokerConsumeStatsSubCommad implements SubCommand { @Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { defaultMQAdminExt.start(); String brokerAddr = commandLine.getOptionValue('b').trim(); boolean isOrder = false; long timeoutMillis = 50000; long diffLevel = 0; if (commandLine.hasOption('o')) { isOrder = Boolean.parseBoolean(commandLine.getOptionValue('o').trim()); } if (commandLine.hasOption('t')) { timeoutMillis = Long.parseLong(commandLine.getOptionValue('t').trim()); } if (commandLine.hasOption('l')) { diffLevel = Long.parseLong(commandLine.getOptionValue('l').trim()); } ConsumeStatsList consumeStatsList = defaultMQAdminExt.fetchConsumeStatsInBroker(brokerAddr, isOrder, timeoutMillis); System.out.printf("%-32s %-32s %-32s %-4s %-20s %-20s %-20s %s%n", "#Topic", "#Group", "#Broker Name", "#QID", "#Broker Offset", "#Consumer Offset", "#Diff", "#LastTime"); for (Map<String, List<ConsumeStats>> map : consumeStatsList.getConsumeStatsList()) { for (Map.Entry<String, List<ConsumeStats>> entry : map.entrySet()) { String group = entry.getKey(); List<ConsumeStats> consumeStatsArray = entry.getValue(); for (ConsumeStats consumeStats : consumeStatsArray) { List<MessageQueue> mqList = new LinkedList<MessageQueue>(); mqList.addAll(consumeStats.getOffsetTable().keySet()); Collections.sort(mqList); for (MessageQueue mq : mqList) { OffsetWrapper offsetWrapper = consumeStats.getOffsetTable().get(mq); long diff = offsetWrapper.getBrokerOffset() - offsetWrapper.getConsumerOffset(); if (diff < diffLevel) { continue; } String lastTime = "-"; try { lastTime = UtilAll.formatDate(new Date(offsetWrapper.getLastTimestamp()), UtilAll.YYYY_MM_DD_HH_MM_SS); } catch (Exception ignored) { } if (offsetWrapper.getLastTimestamp() > 0) System.out.printf("%-32s %-32s %-32s %-4d %-20d %-20d %-20d %s%n", UtilAll.frontStringAtLeast(mq.getTopic(), 32), group, UtilAll.frontStringAtLeast(mq.getBrokerName(), 32), mq.getQueueId(), offsetWrapper.getBrokerOffset(), offsetWrapper.getConsumerOffset(), diff, lastTime ); } } } } System.out.printf("%nDiff Total: %d%n", consumeStatsList.getTotalDiff()); } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(CommandLine commandLine, Options options, RPCHook rpcHook); }### Answer:
@Ignore @Test public void testExecute() throws SubCommandException { BrokerConsumeStatsSubCommad cmd = new BrokerConsumeStatsSubCommad(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-b 127.0.0.1:10911", "-t 3000", "-l 5", "-o true"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); cmd.execute(commandLine, options, null); } |
### Question:
SendMsgStatusCommand implements SubCommand { @Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException { final DefaultMQProducer producer = new DefaultMQProducer("PID_SMSC", rpcHook); producer.setInstanceName("PID_SMSC_" + System.currentTimeMillis()); try { producer.start(); String brokerName = commandLine.getOptionValue('b').trim(); int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s')) : 128; int count = commandLine.hasOption('c') ? Integer.parseInt(commandLine.getOptionValue('c')) : 50; producer.send(buildMessage(brokerName, 16)); for (int i = 0; i < count; i++) { long begin = System.currentTimeMillis(); SendResult result = producer.send(buildMessage(brokerName, messageSize)); System.out.printf("rt:" + (System.currentTimeMillis() - begin) + "ms, SendResult=" + result); } } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { producer.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(CommandLine commandLine, Options options, RPCHook rpcHook); }### Answer:
@Test public void testExecute() { SendMsgStatusCommand cmd = new SendMsgStatusCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-b 127.0.0.1:10911", "-s 1024 -c 10"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); } |
### Question:
ConsumerStatusSubCommand implements SubCommand { @Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { defaultMQAdminExt.start(); String group = commandLine.getOptionValue('g').trim(); ConsumerConnection cc = defaultMQAdminExt.examineConsumerConnectionInfo(group); boolean jstack = commandLine.hasOption('s'); if (!commandLine.hasOption('i')) { int i = 1; long now = System.currentTimeMillis(); final TreeMap<String, ConsumerRunningInfo> criTable = new TreeMap<String, ConsumerRunningInfo>(); for (Connection conn : cc.getConnectionSet()) { try { ConsumerRunningInfo consumerRunningInfo = defaultMQAdminExt.getConsumerRunningInfo(group, conn.getClientId(), jstack); if (consumerRunningInfo != null) { criTable.put(conn.getClientId(), consumerRunningInfo); String filePath = now + "/" + conn.getClientId(); MixAll.string2FileNotSafe(consumerRunningInfo.formatString(), filePath); System.out.printf("%03d %-40s %-20s %s%n", i++, conn.getClientId(), MQVersion.getVersionDesc(conn.getVersion()), filePath); } } catch (Exception e) { e.printStackTrace(); } } if (!criTable.isEmpty()) { boolean subSame = ConsumerRunningInfo.analyzeSubscription(criTable); boolean rebalanceOK = subSame && ConsumerRunningInfo.analyzeRebalance(criTable); if (subSame) { System.out.printf("%n%nSame subscription in the same group of consumer"); System.out.printf("%n%nRebalance %s%n", rebalanceOK ? "OK" : "Failed"); Iterator<Entry<String, ConsumerRunningInfo>> it = criTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, ConsumerRunningInfo> next = it.next(); String result = ConsumerRunningInfo.analyzeProcessQueue(next.getKey(), next.getValue()); if (result.length() > 0) { System.out.printf(result); } } } else { System.out.printf("%n%nWARN: Different subscription in the same group of consumer!!!"); } } } else { String clientId = commandLine.getOptionValue('i').trim(); ConsumerRunningInfo consumerRunningInfo = defaultMQAdminExt.getConsumerRunningInfo(group, clientId, jstack); if (consumerRunningInfo != null) { System.out.printf("%s", consumerRunningInfo.formatString()); } } } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } } static void main(String[] args); @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(CommandLine commandLine, Options options, RPCHook rpcHook); }### Answer:
@Ignore @Test public void testExecute() throws SubCommandException { ConsumerStatusSubCommand cmd = new ConsumerStatusSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-g default-group", "-i cid_one"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); cmd.execute(commandLine, options, null); } |
### Question:
GetNamesrvConfigCommand implements SubCommand { @Override public void execute(final CommandLine commandLine, final Options options, final RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { String servers = commandLine.getOptionValue('n'); List<String> serverList = null; if (servers != null && servers.length() > 0) { String[] serverArray = servers.trim().split(";"); if (serverArray.length > 0) { serverList = Arrays.asList(serverArray); } } defaultMQAdminExt.start(); Map<String, Properties> nameServerConfigs = defaultMQAdminExt.getNameServerConfig(serverList); for (String server : nameServerConfigs.keySet()) { System.out.printf("============%s============\n", server); for (Object key : nameServerConfigs.get(server).keySet()) { System.out.printf("%-50s= %s\n", key, nameServerConfigs.get(server).get(key)); } } } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(final Options options); @Override void execute(final CommandLine commandLine, final Options options, final RPCHook rpcHook); }### Answer:
@Test public void testExecute() throws SubCommandException { GetNamesrvConfigCommand cmd = new GetNamesrvConfigCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); cmd.execute(commandLine, options, null); } |
### Question:
UpdateTopicPermSubCommand implements SubCommand { @Override public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { defaultMQAdminExt.start(); TopicConfig topicConfig = new TopicConfig(); String topic = commandLine.getOptionValue('t').trim(); TopicRouteData topicRouteData = defaultMQAdminExt.examineTopicRouteInfo(topic); assert topicRouteData != null; List<QueueData> queueDatas = topicRouteData.getQueueDatas(); assert queueDatas != null && queueDatas.size() > 0; QueueData queueData = queueDatas.get(0); topicConfig.setTopicName(topic); topicConfig.setWriteQueueNums(queueData.getWriteQueueNums()); topicConfig.setReadQueueNums(queueData.getReadQueueNums()); topicConfig.setPerm(queueData.getPerm()); topicConfig.setTopicSysFlag(queueData.getTopicSynFlag()); int perm = Integer.parseInt(commandLine.getOptionValue('p').trim()); int oldPerm = topicConfig.getPerm(); if (perm == oldPerm) { System.out.printf("new perm equals to the old one!%n"); return; } topicConfig.setPerm(perm); if (commandLine.hasOption('b')) { String addr = commandLine.getOptionValue('b').trim(); defaultMQAdminExt.createAndUpdateTopicConfig(addr, topicConfig); System.out.printf("update topic perm from %s to %s in %s success.%n", oldPerm, perm, addr); System.out.printf("%s%n", topicConfig); return; } else if (commandLine.hasOption('c')) { String clusterName = commandLine.getOptionValue('c').trim(); Set<String> masterSet = CommandUtil.fetchMasterAddrByClusterName(defaultMQAdminExt, clusterName); for (String addr : masterSet) { defaultMQAdminExt.createAndUpdateTopicConfig(addr, topicConfig); System.out.printf("update topic perm from %s to %s in %s success.%n", oldPerm, perm, addr); } return; } ServerUtil.printCommandLineHelp("mqadmin " + this.commandName(), options); } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook); }### Answer:
@Test public void testExecute() { UpdateTopicPermSubCommand cmd = new UpdateTopicPermSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster", "-t unit-test", "-p 6"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); assertThat(commandLine.getOptionValue('b').trim()).isEqualTo("127.0.0.1:10911"); assertThat(commandLine.getOptionValue('c').trim()).isEqualTo("default-cluster"); assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test"); assertThat(commandLine.getOptionValue('p').trim()).isEqualTo("6"); } |
### Question:
TopicRouteSubCommand implements SubCommand { @Override public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { defaultMQAdminExt.start(); String topic = commandLine.getOptionValue('t').trim(); TopicRouteData topicRouteData = defaultMQAdminExt.examineTopicRouteInfo(topic); String json = topicRouteData.toJson(true); System.out.printf("%s%n", json); } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook); }### Answer:
@Test public void testExecute() { TopicRouteSubCommand cmd = new TopicRouteSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-t unit-test"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test"); } |
### Question:
TopicClusterSubCommand implements SubCommand { @Override public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); String topic = commandLine.getOptionValue('t').trim(); try { defaultMQAdminExt.start(); Set<String> clusters = defaultMQAdminExt.getTopicClusterList(topic); for (String value : clusters) { System.out.printf("%s%n", value); } } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook); }### Answer:
@Test public void testExecute() { TopicClusterSubCommand cmd = new TopicClusterSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-t unit-test"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test"); } |
### Question:
TopicStatusSubCommand implements SubCommand { @Override public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { defaultMQAdminExt.start(); String topic = commandLine.getOptionValue('t').trim(); TopicStatsTable topicStatsTable = defaultMQAdminExt.examineTopicStats(topic); List<MessageQueue> mqList = new LinkedList<MessageQueue>(); mqList.addAll(topicStatsTable.getOffsetTable().keySet()); Collections.sort(mqList); System.out.printf("%-32s %-4s %-20s %-20s %s%n", "#Broker Name", "#QID", "#Min Offset", "#Max Offset", "#Last Updated" ); for (MessageQueue mq : mqList) { TopicOffset topicOffset = topicStatsTable.getOffsetTable().get(mq); String humanTimestamp = ""; if (topicOffset.getLastUpdateTimestamp() > 0) { humanTimestamp = UtilAll.timeMillisToHumanString2(topicOffset.getLastUpdateTimestamp()); } System.out.printf("%-32s %-4d %-20d %-20d %s%n", UtilAll.frontStringAtLeast(mq.getBrokerName(), 32), mq.getQueueId(), topicOffset.getMinOffset(), topicOffset.getMaxOffset(), humanTimestamp ); } } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook); }### Answer:
@Test public void testExecute() { TopicStatusSubCommand cmd = new TopicStatusSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-t unit-test"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test"); } |
### Question:
UpdateOrderConfCommand implements SubCommand { @Override public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { String topic = commandLine.getOptionValue('t').trim(); String type = commandLine.getOptionValue('m').trim(); if ("get".equals(type)) { defaultMQAdminExt.start(); String orderConf = defaultMQAdminExt.getKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, topic); System.out.printf("get orderConf success. topic=[%s], orderConf=[%s] ", topic, orderConf); return; } else if ("put".equals(type)) { defaultMQAdminExt.start(); String orderConf = ""; if (commandLine.hasOption('v')) { orderConf = commandLine.getOptionValue('v').trim(); } if (UtilAll.isBlank(orderConf)) { throw new Exception("please set orderConf with option -v."); } defaultMQAdminExt.createOrUpdateOrderConf(topic, orderConf, true); System.out.printf("update orderConf success. topic=[%s], orderConf=[%s]", topic, orderConf.toString()); return; } else if ("delete".equals(type)) { defaultMQAdminExt.start(); defaultMQAdminExt.deleteKvConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG, topic); System.out.printf("delete orderConf success. topic=[%s]", topic); return; } ServerUtil.printCommandLineHelp("mqadmin " + this.commandName(), options); } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook); }### Answer:
@Test public void testExecute() { UpdateOrderConfCommand cmd = new UpdateOrderConfCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-t unit-test", "-v default-broker:8", "-m post"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); assertThat(commandLine.getOptionValue('t').trim()).isEqualTo("unit-test"); assertThat(commandLine.getOptionValue('v').trim()).isEqualTo("default-broker:8"); assertThat(commandLine.getOptionValue('m').trim()).isEqualTo("post"); } |
### Question:
ConsumerFilterManager extends ConfigManager { public void register(final String consumerGroup, final Collection<SubscriptionData> subList) { for (SubscriptionData subscriptionData : subList) { register( subscriptionData.getTopic(), consumerGroup, subscriptionData.getSubString(), subscriptionData.getExpressionType(), subscriptionData.getSubVersion() ); } Collection<ConsumerFilterData> groupFilterData = getByGroup(consumerGroup); Iterator<ConsumerFilterData> iterator = groupFilterData.iterator(); while (iterator.hasNext()) { ConsumerFilterData filterData = iterator.next(); boolean exist = false; for (SubscriptionData subscriptionData : subList) { if (subscriptionData.getTopic().equals(filterData.getTopic())) { exist = true; break; } } if (!exist && !filterData.isDead()) { filterData.setDeadTime(System.currentTimeMillis()); log.info("Consumer filter changed: {}, make illegal topic dead:{}", consumerGroup, filterData); } } } ConsumerFilterManager(); ConsumerFilterManager(BrokerController brokerController); static ConsumerFilterData build(final String topic, final String consumerGroup,
final String expression, final String type,
final long clientVersion); void register(final String consumerGroup, final Collection<SubscriptionData> subList); boolean register(final String topic, final String consumerGroup, final String expression,
final String type, final long clientVersion); void unRegister(final String consumerGroup); ConsumerFilterData get(final String topic, final String consumerGroup); Collection<ConsumerFilterData> getByGroup(final String consumerGroup); final Collection<ConsumerFilterData> get(final String topic); BloomFilter getBloomFilter(); @Override String encode(); @Override String configFilePath(); @Override void decode(final String jsonString); @Override String encode(final boolean prettyFormat); void clean(); ConcurrentMap<String, FilterDataMapByTopic> getFilterDataByTopic(); void setFilterDataByTopic(final ConcurrentHashMap<String, FilterDataMapByTopic> filterDataByTopic); }### Answer:
@Test public void testRegister() { ConsumerFilterManager filterManager = gen(10, 10); ConsumerFilterData filterData = filterManager.get("topic9", "CID_9"); assertThat(filterData).isNotNull(); assertThat(filterData.isDead()).isFalse(); assertThat(filterManager.register( "topic9", "CID_9", "a is not null", ExpressionType.SQL92, System.currentTimeMillis() + 1000 )).isTrue(); ConsumerFilterData newFilter = filterManager.get("topic9", "CID_9"); assertThat(newFilter).isNotEqualTo(filterData); assertThat(filterManager.register( "topic9", "CID_9", "a is null", ExpressionType.SQL92, newFilter.getClientVersion() )).isFalse(); ConsumerFilterData filterData1 = filterManager.get("topic9", "CID_9"); assertThat(newFilter).isEqualTo(filterData1); } |
### Question:
ConsumerFilterManager extends ConfigManager { public void unRegister(final String consumerGroup) { for (String topic : filterDataByTopic.keySet()) { this.filterDataByTopic.get(topic).unRegister(consumerGroup); } } ConsumerFilterManager(); ConsumerFilterManager(BrokerController brokerController); static ConsumerFilterData build(final String topic, final String consumerGroup,
final String expression, final String type,
final long clientVersion); void register(final String consumerGroup, final Collection<SubscriptionData> subList); boolean register(final String topic, final String consumerGroup, final String expression,
final String type, final long clientVersion); void unRegister(final String consumerGroup); ConsumerFilterData get(final String topic, final String consumerGroup); Collection<ConsumerFilterData> getByGroup(final String consumerGroup); final Collection<ConsumerFilterData> get(final String topic); BloomFilter getBloomFilter(); @Override String encode(); @Override String configFilePath(); @Override void decode(final String jsonString); @Override String encode(final boolean prettyFormat); void clean(); ConcurrentMap<String, FilterDataMapByTopic> getFilterDataByTopic(); void setFilterDataByTopic(final ConcurrentHashMap<String, FilterDataMapByTopic> filterDataByTopic); }### Answer:
@Test public void testUnregister() { ConsumerFilterManager filterManager = gen(10, 10); ConsumerFilterData filterData = filterManager.get("topic9", "CID_9"); assertThat(filterData).isNotNull(); assertThat(filterData.isDead()).isFalse(); filterManager.unRegister("CID_9"); assertThat(filterData.isDead()).isTrue(); } |
### Question:
ConsumerFilterManager extends ConfigManager { public ConsumerFilterData get(final String topic, final String consumerGroup) { if (!this.filterDataByTopic.containsKey(topic)) { return null; } if (this.filterDataByTopic.get(topic).getGroupFilterData().isEmpty()) { return null; } return this.filterDataByTopic.get(topic).getGroupFilterData().get(consumerGroup); } ConsumerFilterManager(); ConsumerFilterManager(BrokerController brokerController); static ConsumerFilterData build(final String topic, final String consumerGroup,
final String expression, final String type,
final long clientVersion); void register(final String consumerGroup, final Collection<SubscriptionData> subList); boolean register(final String topic, final String consumerGroup, final String expression,
final String type, final long clientVersion); void unRegister(final String consumerGroup); ConsumerFilterData get(final String topic, final String consumerGroup); Collection<ConsumerFilterData> getByGroup(final String consumerGroup); final Collection<ConsumerFilterData> get(final String topic); BloomFilter getBloomFilter(); @Override String encode(); @Override String configFilePath(); @Override void decode(final String jsonString); @Override String encode(final boolean prettyFormat); void clean(); ConcurrentMap<String, FilterDataMapByTopic> getFilterDataByTopic(); void setFilterDataByTopic(final ConcurrentHashMap<String, FilterDataMapByTopic> filterDataByTopic); }### Answer:
@Test public void testPersist() { ConsumerFilterManager filterManager = gen(10, 10); try { filterManager.persist(); ConsumerFilterData filterData = filterManager.get("topic9", "CID_9"); assertThat(filterData).isNotNull(); assertThat(filterData.isDead()).isFalse(); ConsumerFilterManager loadFilter = new ConsumerFilterManager(); assertThat(loadFilter.load()).isTrue(); filterData = loadFilter.get("topic9", "CID_9"); assertThat(filterData).isNotNull(); assertThat(filterData.isDead()).isTrue(); assertThat(filterData.getCompiledExpression()).isNotNull(); } finally { deleteDirectory("./unit_test"); } }
@Test public void testPersist_clean() { ConsumerFilterManager filterManager = gen(10, 10); String topic = "topic9"; for (int i = 0; i < 10; i++) { String cid = "CID_" + i; ConsumerFilterData filterData = filterManager.get(topic, cid); assertThat(filterData).isNotNull(); assertThat(filterData.isDead()).isFalse(); filterData.setBornTime(System.currentTimeMillis() - 26 * 60 * 60 * 1000); filterData.setDeadTime(System.currentTimeMillis() - 25 * 60 * 60 * 1000); } try { filterManager.persist(); ConsumerFilterManager loadFilter = new ConsumerFilterManager(); assertThat(loadFilter.load()).isTrue(); ConsumerFilterData filterData = loadFilter.get(topic, "CID_9"); assertThat(filterData).isNull(); Collection<ConsumerFilterData> topicData = loadFilter.get(topic); assertThat(topicData).isNullOrEmpty(); } finally { deleteDirectory("./unit_test"); } } |
### Question:
ProducerManager { public void scanNotActiveChannel() { try { if (this.groupChannelLock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { try { for (final Map.Entry<String, HashMap<Channel, ClientChannelInfo>> entry : this.groupChannelTable .entrySet()) { final String group = entry.getKey(); final HashMap<Channel, ClientChannelInfo> chlMap = entry.getValue(); Iterator<Entry<Channel, ClientChannelInfo>> it = chlMap.entrySet().iterator(); while (it.hasNext()) { Entry<Channel, ClientChannelInfo> item = it.next(); final ClientChannelInfo info = item.getValue(); long diff = System.currentTimeMillis() - info.getLastUpdateTimestamp(); if (diff > CHANNEL_EXPIRED_TIMEOUT) { it.remove(); log.warn( "SCAN: remove expired channel[{}] from ProducerManager groupChannelTable, producer group name: {}", RemotingHelper.parseChannelRemoteAddr(info.getChannel()), group); RemotingUtil.closeChannel(info.getChannel()); } } } } finally { this.groupChannelLock.unlock(); } } else { log.warn("ProducerManager scanNotActiveChannel lock timeout"); } } catch (InterruptedException e) { log.error("", e); } } ProducerManager(); HashMap<String, HashMap<Channel, ClientChannelInfo>> getGroupChannelTable(); void scanNotActiveChannel(); void doChannelCloseEvent(final String remoteAddr, final Channel channel); void registerProducer(final String group, final ClientChannelInfo clientChannelInfo); void unregisterProducer(final String group, final ClientChannelInfo clientChannelInfo); }### Answer:
@Test public void scanNotActiveChannel() throws Exception { producerManager.registerProducer(group, clientInfo); assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNotNull(); Field field = ProducerManager.class.getDeclaredField("CHANNEL_EXPIRED_TIMEOUT"); field.setAccessible(true); long CHANNEL_EXPIRED_TIMEOUT = field.getLong(producerManager); clientInfo.setLastUpdateTimestamp(System.currentTimeMillis() - CHANNEL_EXPIRED_TIMEOUT - 10); when(channel.close()).thenReturn(mock(ChannelFuture.class)); producerManager.scanNotActiveChannel(); assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNull(); } |
### Question:
ProducerManager { public void doChannelCloseEvent(final String remoteAddr, final Channel channel) { if (channel != null) { try { if (this.groupChannelLock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { try { for (final Map.Entry<String, HashMap<Channel, ClientChannelInfo>> entry : this.groupChannelTable .entrySet()) { final String group = entry.getKey(); final HashMap<Channel, ClientChannelInfo> clientChannelInfoTable = entry.getValue(); final ClientChannelInfo clientChannelInfo = clientChannelInfoTable.remove(channel); if (clientChannelInfo != null) { log.info( "NETTY EVENT: remove channel[{}][{}] from ProducerManager groupChannelTable, producer group: {}", clientChannelInfo.toString(), remoteAddr, group); } } } finally { this.groupChannelLock.unlock(); } } else { log.warn("ProducerManager doChannelCloseEvent lock timeout"); } } catch (InterruptedException e) { log.error("", e); } } } ProducerManager(); HashMap<String, HashMap<Channel, ClientChannelInfo>> getGroupChannelTable(); void scanNotActiveChannel(); void doChannelCloseEvent(final String remoteAddr, final Channel channel); void registerProducer(final String group, final ClientChannelInfo clientChannelInfo); void unregisterProducer(final String group, final ClientChannelInfo clientChannelInfo); }### Answer:
@Test public void doChannelCloseEvent() throws Exception { producerManager.registerProducer(group, clientInfo); assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNotNull(); producerManager.doChannelCloseEvent("127.0.0.1", channel); assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNull(); } |
### Question:
ProducerManager { public void registerProducer(final String group, final ClientChannelInfo clientChannelInfo) { try { ClientChannelInfo clientChannelInfoFound = null; if (this.groupChannelLock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { try { HashMap<Channel, ClientChannelInfo> channelTable = this.groupChannelTable.get(group); if (null == channelTable) { channelTable = new HashMap<>(); this.groupChannelTable.put(group, channelTable); } clientChannelInfoFound = channelTable.get(clientChannelInfo.getChannel()); if (null == clientChannelInfoFound) { channelTable.put(clientChannelInfo.getChannel(), clientChannelInfo); log.info("new producer connected, group: {} channel: {}", group, clientChannelInfo.toString()); } } finally { this.groupChannelLock.unlock(); } if (clientChannelInfoFound != null) { clientChannelInfoFound.setLastUpdateTimestamp(System.currentTimeMillis()); } } else { log.warn("ProducerManager registerProducer lock timeout"); } } catch (InterruptedException e) { log.error("", e); } } ProducerManager(); HashMap<String, HashMap<Channel, ClientChannelInfo>> getGroupChannelTable(); void scanNotActiveChannel(); void doChannelCloseEvent(final String remoteAddr, final Channel channel); void registerProducer(final String group, final ClientChannelInfo clientChannelInfo); void unregisterProducer(final String group, final ClientChannelInfo clientChannelInfo); }### Answer:
@Test public void testRegisterProducer() throws Exception { producerManager.registerProducer(group, clientInfo); HashMap<Channel, ClientChannelInfo> channelMap = producerManager.getGroupChannelTable().get(group); assertThat(channelMap).isNotNull(); assertThat(channelMap.get(channel)).isEqualTo(clientInfo); } |
### Question:
ProducerManager { public void unregisterProducer(final String group, final ClientChannelInfo clientChannelInfo) { try { if (this.groupChannelLock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { try { HashMap<Channel, ClientChannelInfo> channelTable = this.groupChannelTable.get(group); if (null != channelTable && !channelTable.isEmpty()) { ClientChannelInfo old = channelTable.remove(clientChannelInfo.getChannel()); if (old != null) { log.info("unregister a producer[{}] from groupChannelTable {}", group, clientChannelInfo.toString()); } if (channelTable.isEmpty()) { this.groupChannelTable.remove(group); log.info("unregister a producer group[{}] from groupChannelTable", group); } } } finally { this.groupChannelLock.unlock(); } } else { log.warn("ProducerManager unregisterProducer lock timeout"); } } catch (InterruptedException e) { log.error("", e); } } ProducerManager(); HashMap<String, HashMap<Channel, ClientChannelInfo>> getGroupChannelTable(); void scanNotActiveChannel(); void doChannelCloseEvent(final String remoteAddr, final Channel channel); void registerProducer(final String group, final ClientChannelInfo clientChannelInfo); void unregisterProducer(final String group, final ClientChannelInfo clientChannelInfo); }### Answer:
@Test public void unregisterProducer() throws Exception { producerManager.registerProducer(group, clientInfo); HashMap<Channel, ClientChannelInfo> channelMap = producerManager.getGroupChannelTable().get(group); assertThat(channelMap).isNotNull(); assertThat(channelMap.get(channel)).isEqualTo(clientInfo); producerManager.unregisterProducer(group, clientInfo); channelMap = producerManager.getGroupChannelTable().get(group); assertThat(channelMap).isNull(); } |
### Question:
SendMessageProcessor extends AbstractSendMessageProcessor implements NettyRequestProcessor { @Override public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { SendMessageContext mqtraceContext; switch (request.getCode()) { case RequestCode.CONSUMER_SEND_MSG_BACK: return this.consumerSendMsgBack(ctx, request); default: SendMessageRequestHeader requestHeader = parseRequestHeader(request); if (requestHeader == null) { return null; } mqtraceContext = buildMsgContext(ctx, requestHeader); this.executeSendMessageHookBefore(ctx, request, mqtraceContext); RemotingCommand response; if (requestHeader.isBatch()) { response = this.sendBatchMessage(ctx, request, mqtraceContext, requestHeader); } else { response = this.sendMessage(ctx, request, mqtraceContext, requestHeader); } this.executeSendMessageHookAfter(response, mqtraceContext); return response; } } SendMessageProcessor(final BrokerController brokerController); @Override RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request); @Override boolean rejectRequest(); boolean hasConsumeMessageHook(); void executeConsumeMessageHookAfter(final ConsumeMessageContext context); SocketAddress getStoreHost(); void registerConsumeMessageHook(List<ConsumeMessageHook> consumeMessageHookList); }### Answer:
@Test public void testProcessRequest() throws RemotingCommandException { when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK))); assertPutResult(ResponseCode.SUCCESS); }
@Test public void testProcessRequest_WithMsgBack() throws RemotingCommandException { when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK))); final RemotingCommand request = createSendMsgBackCommand(RequestCode.CONSUMER_SEND_MSG_BACK); sendMessageProcessor = new SendMessageProcessor(brokerController); final RemotingCommand response = sendMessageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull(); assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS); } |
### Question:
ClientManageProcessor implements NettyRequestProcessor { @Override public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { switch (request.getCode()) { case RequestCode.HEART_BEAT: return this.heartBeat(ctx, request); case RequestCode.UNREGISTER_CLIENT: return this.unregisterClient(ctx, request); case RequestCode.CHECK_CLIENT_CONFIG: return this.checkClientConfig(ctx, request); default: break; } return null; } ClientManageProcessor(final BrokerController brokerController); @Override RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request); @Override boolean rejectRequest(); RemotingCommand heartBeat(ChannelHandlerContext ctx, RemotingCommand request); RemotingCommand unregisterClient(ChannelHandlerContext ctx, RemotingCommand request); RemotingCommand checkClientConfig(ChannelHandlerContext ctx, RemotingCommand request); }### Answer:
@Test public void processRequest_UnRegisterProducer() throws Exception { brokerController.getProducerManager().registerProducer(group, clientChannelInfo); HashMap<Channel, ClientChannelInfo> channelMap = brokerController.getProducerManager().getGroupChannelTable().get(group); assertThat(channelMap).isNotNull(); assertThat(channelMap.get(channel)).isEqualTo(clientChannelInfo); RemotingCommand request = createUnRegisterProducerCommand(); RemotingCommand response = clientManageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull(); assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS); channelMap = brokerController.getProducerManager().getGroupChannelTable().get(group); assertThat(channelMap).isNull(); }
@Test public void processRequest_UnRegisterConsumer() throws RemotingCommandException { ConsumerGroupInfo consumerGroupInfo = brokerController.getConsumerManager().getConsumerGroupInfo(group); assertThat(consumerGroupInfo).isNotNull(); RemotingCommand request = createUnRegisterConsumerCommand(); RemotingCommand response = clientManageProcessor.processRequest(handlerContext, request); assertThat(response).isNotNull(); assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS); consumerGroupInfo = brokerController.getConsumerManager().getConsumerGroupInfo(group); assertThat(consumerGroupInfo).isNull(); } |
### Question:
BrokerStartup { private static void properties2SystemEnv(Properties properties) { if (properties == null) { return; } String rmqAddressServerDomain = properties.getProperty("rmqAddressServerDomain", MixAll.WS_DOMAIN_NAME); String rmqAddressServerSubGroup = properties.getProperty("rmqAddressServerSubGroup", MixAll.WS_DOMAIN_SUBGROUP); System.setProperty("rocketmq.namesrv.domain", rmqAddressServerDomain); System.setProperty("rocketmq.namesrv.domain.subgroup", rmqAddressServerSubGroup); } static void main(String[] args); static BrokerController start(BrokerController controller); static BrokerController createBrokerController(String[] args); static Options buildCommandlineOptions(final Options options); static Properties properties; static CommandLine commandLine; static String configFile; static Logger log; }### Answer:
@Test public void testProperties2SystemEnv() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Properties properties = new Properties(); Class<BrokerStartup> clazz = BrokerStartup.class; Method method = clazz.getDeclaredMethod("properties2SystemEnv", Properties.class); method.setAccessible(true); System.setProperty("rocketmq.namesrv.domain", "value"); method.invoke(null, properties); Assert.assertEquals("value", System.getProperty("rocketmq.namesrv.domain")); } |
### Question:
MappedFile extends ReferenceResource { public SelectMappedBufferResult selectMappedBuffer(int pos, int size) { int readPosition = getReadPosition(); if ((pos + size) <= readPosition) { if (this.hold()) { ByteBuffer byteBuffer = this.mappedByteBuffer.slice(); byteBuffer.position(pos); ByteBuffer byteBufferNew = byteBuffer.slice(); byteBufferNew.limit(size); return new SelectMappedBufferResult(this.fileFromOffset + pos, byteBufferNew, size, this); } else { log.warn("matched, but hold failed, request pos: " + pos + ", fileFromOffset: " + this.fileFromOffset); } } else { log.warn("selectMappedBuffer request pos invalid, request pos: " + pos + ", size: " + size + ", fileFromOffset: " + this.fileFromOffset); } return null; } MappedFile(); MappedFile(final String fileName, final int fileSize); MappedFile(final String fileName, final int fileSize, final TransientStorePool transientStorePool); static void ensureDirOK(final String dirName); static void clean(final ByteBuffer buffer); static int getTotalMappedFiles(); static long getTotalMappedVirtualMemory(); void init(final String fileName, final int fileSize, final TransientStorePool transientStorePool); long getLastModifiedTimestamp(); int getFileSize(); FileChannel getFileChannel(); AppendMessageResult appendMessage(final MessageExtBrokerInner msg, final AppendMessageCallback cb); AppendMessageResult appendMessages(final MessageExtBatch messageExtBatch, final AppendMessageCallback cb); AppendMessageResult appendMessagesInner(final MessageExt messageExt, final AppendMessageCallback cb); long getFileFromOffset(); boolean appendMessage(final byte[] data); boolean appendMessage(final byte[] data, final int offset, final int length); int flush(final int flushLeastPages); int commit(final int commitLeastPages); int getFlushedPosition(); void setFlushedPosition(int pos); boolean isFull(); SelectMappedBufferResult selectMappedBuffer(int pos, int size); SelectMappedBufferResult selectMappedBuffer(int pos); @Override boolean cleanup(final long currentRef); boolean destroy(final long intervalForcibly); int getWrotePosition(); void setWrotePosition(int pos); int getReadPosition(); void setCommittedPosition(int pos); void warmMappedFile(FlushDiskType type, int pages); String getFileName(); MappedByteBuffer getMappedByteBuffer(); ByteBuffer sliceByteBuffer(); long getStoreTimestamp(); boolean isFirstCreateInQueue(); void setFirstCreateInQueue(boolean firstCreateInQueue); void mlock(); void munlock(); @Override String toString(); static final int OS_PAGE_SIZE; }### Answer:
@Test public void testSelectMappedBuffer() throws IOException { MappedFile mappedFile = new MappedFile("target/unit_test_store/MappedFileTest/000", 1024 * 64); boolean result = mappedFile.appendMessage(storeMessage.getBytes()); assertThat(result).isTrue(); SelectMappedBufferResult selectMappedBufferResult = mappedFile.selectMappedBuffer(0); byte[] data = new byte[storeMessage.length()]; selectMappedBufferResult.getByteBuffer().get(data); String readString = new String(data); assertThat(readString).isEqualTo(storeMessage); mappedFile.shutdown(1000); assertThat(mappedFile.isAvailable()).isFalse(); selectMappedBufferResult.release(); assertThat(mappedFile.isCleanupOver()).isTrue(); assertThat(mappedFile.destroy(1000)).isTrue(); } |
### Question:
ConsumeQueueExt { public long put(final CqExtUnit cqExtUnit) { final int retryTimes = 3; try { int size = cqExtUnit.calcUnitSize(); if (size > CqExtUnit.MAX_EXT_UNIT_SIZE) { log.error("Size of cq ext unit is greater than {}, {}", CqExtUnit.MAX_EXT_UNIT_SIZE, cqExtUnit); return 1; } if (this.mappedFileQueue.getMaxOffset() + size > MAX_REAL_OFFSET) { log.warn("Capacity of ext is maximum!{}, {}", this.mappedFileQueue.getMaxOffset(), size); return 1; } if (this.tempContainer == null || this.tempContainer.capacity() < size) { this.tempContainer = ByteBuffer.allocate(size); } for (int i = 0; i < retryTimes; i++) { MappedFile mappedFile = this.mappedFileQueue.getLastMappedFile(); if (mappedFile == null || mappedFile.isFull()) { mappedFile = this.mappedFileQueue.getLastMappedFile(0); } if (mappedFile == null) { log.error("Create mapped file when save consume queue extend, {}", cqExtUnit); continue; } final int wrotePosition = mappedFile.getWrotePosition(); final int blankSize = this.mappedFileSize - wrotePosition - END_BLANK_DATA_LENGTH; if (size > blankSize) { fullFillToEnd(mappedFile, wrotePosition); log.info("No enough space(need:{}, has:{}) of file {}, so fill to end", size, blankSize, mappedFile.getFileName()); continue; } if (mappedFile.appendMessage(cqExtUnit.write(this.tempContainer), 0, size)) { return decorate(wrotePosition + mappedFile.getFileFromOffset()); } } } catch (Throwable e) { log.error("Save consume queue extend error, " + cqExtUnit, e); } return 1; } ConsumeQueueExt(final String topic,
final int queueId,
final String storePath,
final int mappedFileSize,
final int bitMapLength); boolean isExtAddr(final long address); long unDecorate(final long address); long decorate(final long offset); CqExtUnit get(final long address); boolean get(final long address, final CqExtUnit cqExtUnit); long put(final CqExtUnit cqExtUnit); boolean load(); void checkSelf(); void recover(); void truncateByMinAddress(final long minAddress); void truncateByMaxAddress(final long maxAddress); boolean flush(final int flushLeastPages); void destroy(); long getMaxAddress(); long getMinAddress(); static final int END_BLANK_DATA_LENGTH; static final long MAX_ADDR; static final long MAX_REAL_OFFSET; }### Answer:
@Test public void testPut() { ConsumeQueueExt consumeQueueExt = genExt(); try { putSth(consumeQueueExt, true, false, unitCount); } finally { consumeQueueExt.destroy(); deleteDirectory(storePath); } } |
### Question:
ConsumeQueueExt { public CqExtUnit get(final long address) { CqExtUnit cqExtUnit = new CqExtUnit(); if (get(address, cqExtUnit)) { return cqExtUnit; } return null; } ConsumeQueueExt(final String topic,
final int queueId,
final String storePath,
final int mappedFileSize,
final int bitMapLength); boolean isExtAddr(final long address); long unDecorate(final long address); long decorate(final long offset); CqExtUnit get(final long address); boolean get(final long address, final CqExtUnit cqExtUnit); long put(final CqExtUnit cqExtUnit); boolean load(); void checkSelf(); void recover(); void truncateByMinAddress(final long minAddress); void truncateByMaxAddress(final long maxAddress); boolean flush(final int flushLeastPages); void destroy(); long getMaxAddress(); long getMinAddress(); static final int END_BLANK_DATA_LENGTH; static final long MAX_ADDR; static final long MAX_REAL_OFFSET; }### Answer:
@Test public void testGet() { ConsumeQueueExt consumeQueueExt = genExt(); putSth(consumeQueueExt, false, false, unitCount); try { long addr = consumeQueueExt.decorate(0); ConsumeQueueExt.CqExtUnit unit = new ConsumeQueueExt.CqExtUnit(); while (true) { boolean ret = consumeQueueExt.get(addr, unit); if (!ret) { break; } assertThat(unit.getSize()).isGreaterThanOrEqualTo(ConsumeQueueExt.CqExtUnit.MIN_EXT_UNIT_SIZE); addr += unit.getSize(); } } finally { consumeQueueExt.destroy(); deleteDirectory(storePath); } } |
### Question:
IndexFile { public boolean putKey(final String key, final long phyOffset, final long storeTimestamp) { if (this.indexHeader.getIndexCount() < this.indexNum) { int keyHash = indexKeyHashMethod(key); int slotPos = keyHash % this.hashSlotNum; int absSlotPos = IndexHeader.INDEX_HEADER_SIZE + slotPos * hashSlotSize; FileLock fileLock = null; try { int slotValue = this.mappedByteBuffer.getInt(absSlotPos); if (slotValue <= invalidIndex || slotValue > this.indexHeader.getIndexCount()) { slotValue = invalidIndex; } long timeDiff = storeTimestamp - this.indexHeader.getBeginTimestamp(); timeDiff = timeDiff / 1000; if (this.indexHeader.getBeginTimestamp() <= 0) { timeDiff = 0; } else if (timeDiff > Integer.MAX_VALUE) { timeDiff = Integer.MAX_VALUE; } else if (timeDiff < 0) { timeDiff = 0; } int absIndexPos = IndexHeader.INDEX_HEADER_SIZE + this.hashSlotNum * hashSlotSize + this.indexHeader.getIndexCount() * indexSize; this.mappedByteBuffer.putInt(absIndexPos, keyHash); this.mappedByteBuffer.putLong(absIndexPos + 4, phyOffset); this.mappedByteBuffer.putInt(absIndexPos + 4 + 8, (int) timeDiff); this.mappedByteBuffer.putInt(absIndexPos + 4 + 8 + 4, slotValue); this.mappedByteBuffer.putInt(absSlotPos, this.indexHeader.getIndexCount()); if (this.indexHeader.getIndexCount() <= 1) { this.indexHeader.setBeginPhyOffset(phyOffset); this.indexHeader.setBeginTimestamp(storeTimestamp); } this.indexHeader.incHashSlotCount(); this.indexHeader.incIndexCount(); this.indexHeader.setEndPhyOffset(phyOffset); this.indexHeader.setEndTimestamp(storeTimestamp); return true; } catch (Exception e) { log.error("putKey exception, Key: " + key + " KeyHashCode: " + key.hashCode(), e); } finally { if (fileLock != null) { try { fileLock.release(); } catch (IOException e) { e.printStackTrace(); } } } } else { log.warn("Over index file capacity: index count = " + this.indexHeader.getIndexCount() + "; index max num = " + this.indexNum); } return false; } IndexFile(final String fileName, final int hashSlotNum, final int indexNum,
final long endPhyOffset, final long endTimestamp); String getFileName(); void load(); void flush(); boolean isWriteFull(); boolean destroy(final long intervalForcibly); boolean putKey(final String key, final long phyOffset, final long storeTimestamp); int indexKeyHashMethod(final String key); long getBeginTimestamp(); long getEndTimestamp(); long getEndPhyOffset(); boolean isTimeMatched(final long begin, final long end); void selectPhyOffset(final List<Long> phyOffsets, final String key, final int maxNum,
final long begin, final long end, boolean lock); }### Answer:
@Test public void testPutKey() throws Exception { IndexFile indexFile = new IndexFile("100", HASH_SLOT_NUM, INDEX_NUM, 0, 0); for (long i = 0; i < (INDEX_NUM - 1); i++) { boolean putResult = indexFile.putKey(Long.toString(i), i, System.currentTimeMillis()); assertThat(putResult).isTrue(); } boolean putResult = indexFile.putKey(Long.toString(400), 400, System.currentTimeMillis()); assertThat(putResult).isFalse(); indexFile.destroy(0); } |
### Question:
IndexFile { public void selectPhyOffset(final List<Long> phyOffsets, final String key, final int maxNum, final long begin, final long end, boolean lock) { if (this.mappedFile.hold()) { int keyHash = indexKeyHashMethod(key); int slotPos = keyHash % this.hashSlotNum; int absSlotPos = IndexHeader.INDEX_HEADER_SIZE + slotPos * hashSlotSize; FileLock fileLock = null; try { if (lock) { } int slotValue = this.mappedByteBuffer.getInt(absSlotPos); if (slotValue <= invalidIndex || slotValue > this.indexHeader.getIndexCount() || this.indexHeader.getIndexCount() <= 1) { } else { for (int nextIndexToRead = slotValue;;) { if (phyOffsets.size() >= maxNum) { break; } int absIndexPos = IndexHeader.INDEX_HEADER_SIZE + this.hashSlotNum * hashSlotSize + nextIndexToRead * indexSize; int keyHashRead = this.mappedByteBuffer.getInt(absIndexPos); long phyOffsetRead = this.mappedByteBuffer.getLong(absIndexPos + 4); long timeDiff = (long) this.mappedByteBuffer.getInt(absIndexPos + 4 + 8); int prevIndexRead = this.mappedByteBuffer.getInt(absIndexPos + 4 + 8 + 4); if (timeDiff < 0) { break; } timeDiff *= 1000L; long timeRead = this.indexHeader.getBeginTimestamp() + timeDiff; boolean timeMatched = (timeRead >= begin) && (timeRead <= end); if (keyHash == keyHashRead && timeMatched) { phyOffsets.add(phyOffsetRead); } if (prevIndexRead <= invalidIndex || prevIndexRead > this.indexHeader.getIndexCount() || prevIndexRead == nextIndexToRead || timeRead < begin) { break; } nextIndexToRead = prevIndexRead; } } } catch (Exception e) { log.error("selectPhyOffset exception ", e); } finally { if (fileLock != null) { try { fileLock.release(); } catch (IOException e) { e.printStackTrace(); } } this.mappedFile.release(); } } } IndexFile(final String fileName, final int hashSlotNum, final int indexNum,
final long endPhyOffset, final long endTimestamp); String getFileName(); void load(); void flush(); boolean isWriteFull(); boolean destroy(final long intervalForcibly); boolean putKey(final String key, final long phyOffset, final long storeTimestamp); int indexKeyHashMethod(final String key); long getBeginTimestamp(); long getEndTimestamp(); long getEndPhyOffset(); boolean isTimeMatched(final long begin, final long end); void selectPhyOffset(final List<Long> phyOffsets, final String key, final int maxNum,
final long begin, final long end, boolean lock); }### Answer:
@Test public void testSelectPhyOffset() throws Exception { IndexFile indexFile = new IndexFile("200", HASH_SLOT_NUM, INDEX_NUM, 0, 0); for (long i = 0; i < (INDEX_NUM - 1); i++) { boolean putResult = indexFile.putKey(Long.toString(i), i, System.currentTimeMillis()); assertThat(putResult).isTrue(); } boolean putResult = indexFile.putKey(Long.toString(400), 400, System.currentTimeMillis()); assertThat(putResult).isFalse(); final List<Long> phyOffsets = new ArrayList<Long>(); indexFile.selectPhyOffset(phyOffsets, "60", 10, 0, Long.MAX_VALUE, true); assertThat(phyOffsets).isNotEmpty(); assertThat(phyOffsets.size()).isEqualTo(1); indexFile.destroy(0); } |
### Question:
FilterAPI { public static SubscriptionData buildSubscriptionData(final String consumerGroup, String topic, String subString) throws Exception { SubscriptionData subscriptionData = new SubscriptionData(); subscriptionData.setTopic(topic); subscriptionData.setSubString(subString); if (null == subString || subString.equals(SubscriptionData.SUB_ALL) || subString.length() == 0) { subscriptionData.setSubString(SubscriptionData.SUB_ALL); } else { String[] tags = subString.split("\\|\\|"); if (tags.length > 0) { for (String tag : tags) { if (tag.length() > 0) { String trimString = tag.trim(); if (trimString.length() > 0) { subscriptionData.getTagsSet().add(trimString); subscriptionData.getCodeSet().add(trimString.hashCode()); } } } } else { throw new Exception("subString split error"); } } return subscriptionData; } static URL classFile(final String className); static String simpleClassName(final String className); static SubscriptionData buildSubscriptionData(final String consumerGroup, String topic,
String subString); static SubscriptionData build(final String topic, final String subString,
final String type); }### Answer:
@Test public void testBuildSubscriptionData() throws Exception { SubscriptionData subscriptionData = FilterAPI.buildSubscriptionData(group, topic, subString); assertThat(subscriptionData.getTopic()).isEqualTo(topic); assertThat(subscriptionData.getSubString()).isEqualTo(subString); String [] tags = subString.split("\\|\\|"); Set<String> tagSet = new HashSet<String>(); for (String tag : tags) { tagSet.add(tag.trim()); } assertThat(subscriptionData.getTagsSet()).isEqualTo(tagSet); } |
### Question:
FilterAPI { public static SubscriptionData build(final String topic, final String subString, final String type) throws Exception { if (ExpressionType.TAG.equals(type) || type == null) { return buildSubscriptionData(null, topic, subString); } if (subString == null || subString.length() < 1) { throw new IllegalArgumentException("Expression can't be null! " + type); } SubscriptionData subscriptionData = new SubscriptionData(); subscriptionData.setTopic(topic); subscriptionData.setSubString(subString); subscriptionData.setExpressionType(type); return subscriptionData; } static URL classFile(final String className); static String simpleClassName(final String className); static SubscriptionData buildSubscriptionData(final String consumerGroup, String topic,
String subString); static SubscriptionData build(final String topic, final String subString,
final String type); }### Answer:
@Test public void testBuildTagSome() { try { SubscriptionData subscriptionData = FilterAPI.build( "TOPIC", "A || B", ExpressionType.TAG ); assertThat(subscriptionData).isNotNull(); assertThat(subscriptionData.getTopic()).isEqualTo("TOPIC"); assertThat(subscriptionData.getSubString()).isEqualTo("A || B"); assertThat(ExpressionType.isTagType(subscriptionData.getExpressionType())).isTrue(); assertThat(subscriptionData.getTagsSet()).isNotNull(); assertThat(subscriptionData.getTagsSet()).containsExactly("A", "B"); } catch (Exception e) { e.printStackTrace(); assertThat(Boolean.FALSE).isTrue(); } }
@Test public void testBuildSQL() { try { SubscriptionData subscriptionData = FilterAPI.build( "TOPIC", "a is not null", ExpressionType.SQL92 ); assertThat(subscriptionData).isNotNull(); assertThat(subscriptionData.getTopic()).isEqualTo("TOPIC"); assertThat(subscriptionData.getExpressionType()).isEqualTo(ExpressionType.SQL92); } catch (Exception e) { e.printStackTrace(); assertThat(Boolean.FALSE).isTrue(); } }
@Test public void testBuildSQLWithNullSubString() { try { FilterAPI.build( "TOPIC", null, ExpressionType.SQL92 ); assertThat(Boolean.FALSE).isTrue(); } catch (Exception e) { e.printStackTrace(); } } |
### Question:
DataVersion extends RemotingSerializable { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DataVersion that = (DataVersion) o; if (timestamp != that.timestamp) { return false; } if (counter != null && that.counter != null) { return counter.longValue() == that.counter.longValue(); } return (null == counter) && (null == that.counter); } void assignNewOne(final DataVersion dataVersion); void nextVersion(); long getTimestamp(); void setTimestamp(long timestamp); AtomicLong getCounter(); void setCounter(AtomicLong counter); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testEquals() { DataVersion dataVersion = new DataVersion(); DataVersion other = new DataVersion(); other.setTimestamp(dataVersion.getTimestamp()); Assert.assertTrue(dataVersion.equals(other)); } |
### Question:
UtilAll { public static String currentStackTrace() { StringBuilder sb = new StringBuilder(); StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); for (StackTraceElement ste : stackTrace) { sb.append("\n\t"); sb.append(ste.toString()); } return sb.toString(); } static int getPid(); static String currentStackTrace(); static String offset2FileName(final long offset); static long computeEclipseTimeMilliseconds(final long beginTime); static boolean isItTimeToDo(final String when); static String timeMillisToHumanString(); static String timeMillisToHumanString(final long t); static long computNextMorningTimeMillis(); static long computNextMinutesTimeMillis(); static long computNextHourTimeMillis(); static long computNextHalfHourTimeMillis(); static String timeMillisToHumanString2(final long t); static String timeMillisToHumanString3(final long t); static double getDiskPartitionSpaceUsedPercent(final String path); static int crc32(byte[] array); static int crc32(byte[] array, int offset, int length); static String bytes2string(byte[] src); static byte[] string2bytes(String hexString); static byte[] uncompress(final byte[] src); static byte[] compress(final byte[] src, final int level); static int asInt(String str, int defaultValue); static long asLong(String str, long defaultValue); static String formatDate(Date date, String pattern); static Date parseDate(String date, String pattern); static String responseCode2String(final int code); static String frontStringAtLeast(final String str, final int size); static boolean isBlank(String str); static String jstack(); static String jstack(Map<Thread, StackTraceElement[]> map); static boolean isInternalIP(byte[] ip); static String ipToIPv4Str(byte[] ip); static byte[] getIP(); static final String YYYY_MM_DD_HH_MM_SS; static final String YYYY_MM_DD_HH_MM_SS_SSS; static final String YYYYMMDDHHMMSS; }### Answer:
@Test public void testCurrentStackTrace() { String currentStackTrace = UtilAll.currentStackTrace(); assertThat(currentStackTrace).contains("UtilAll.currentStackTrace"); assertThat(currentStackTrace).contains("UtilAllTest.testCurrentStackTrace("); } |
### Question:
UtilAll { public static int getPid() { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String name = runtime.getName(); try { return Integer.parseInt(name.substring(0, name.indexOf('@'))); } catch (Exception e) { return -1; } } static int getPid(); static String currentStackTrace(); static String offset2FileName(final long offset); static long computeEclipseTimeMilliseconds(final long beginTime); static boolean isItTimeToDo(final String when); static String timeMillisToHumanString(); static String timeMillisToHumanString(final long t); static long computNextMorningTimeMillis(); static long computNextMinutesTimeMillis(); static long computNextHourTimeMillis(); static long computNextHalfHourTimeMillis(); static String timeMillisToHumanString2(final long t); static String timeMillisToHumanString3(final long t); static double getDiskPartitionSpaceUsedPercent(final String path); static int crc32(byte[] array); static int crc32(byte[] array, int offset, int length); static String bytes2string(byte[] src); static byte[] string2bytes(String hexString); static byte[] uncompress(final byte[] src); static byte[] compress(final byte[] src, final int level); static int asInt(String str, int defaultValue); static long asLong(String str, long defaultValue); static String formatDate(Date date, String pattern); static Date parseDate(String date, String pattern); static String responseCode2String(final int code); static String frontStringAtLeast(final String str, final int size); static boolean isBlank(String str); static String jstack(); static String jstack(Map<Thread, StackTraceElement[]> map); static boolean isInternalIP(byte[] ip); static String ipToIPv4Str(byte[] ip); static byte[] getIP(); static final String YYYY_MM_DD_HH_MM_SS; static final String YYYY_MM_DD_HH_MM_SS_SSS; static final String YYYYMMDDHHMMSS; }### Answer:
@Test public void testGetPid() { assertThat(UtilAll.getPid()).isGreaterThan(0); } |
### Question:
UtilAll { public static double getDiskPartitionSpaceUsedPercent(final String path) { if (null == path || path.isEmpty()) return -1; try { File file = new File(path); if (!file.exists()) return -1; long totalSpace = file.getTotalSpace(); if (totalSpace > 0) { long freeSpace = file.getFreeSpace(); long usedSpace = totalSpace - freeSpace; return usedSpace / (double) totalSpace; } } catch (Exception e) { return -1; } return -1; } static int getPid(); static String currentStackTrace(); static String offset2FileName(final long offset); static long computeEclipseTimeMilliseconds(final long beginTime); static boolean isItTimeToDo(final String when); static String timeMillisToHumanString(); static String timeMillisToHumanString(final long t); static long computNextMorningTimeMillis(); static long computNextMinutesTimeMillis(); static long computNextHourTimeMillis(); static long computNextHalfHourTimeMillis(); static String timeMillisToHumanString2(final long t); static String timeMillisToHumanString3(final long t); static double getDiskPartitionSpaceUsedPercent(final String path); static int crc32(byte[] array); static int crc32(byte[] array, int offset, int length); static String bytes2string(byte[] src); static byte[] string2bytes(String hexString); static byte[] uncompress(final byte[] src); static byte[] compress(final byte[] src, final int level); static int asInt(String str, int defaultValue); static long asLong(String str, long defaultValue); static String formatDate(Date date, String pattern); static Date parseDate(String date, String pattern); static String responseCode2String(final int code); static String frontStringAtLeast(final String str, final int size); static boolean isBlank(String str); static String jstack(); static String jstack(Map<Thread, StackTraceElement[]> map); static boolean isInternalIP(byte[] ip); static String ipToIPv4Str(byte[] ip); static byte[] getIP(); static final String YYYY_MM_DD_HH_MM_SS; static final String YYYY_MM_DD_HH_MM_SS_SSS; static final String YYYYMMDDHHMMSS; }### Answer:
@Test public void testGetDiskPartitionSpaceUsedPercent() { String tmpDir = System.getProperty("java.io.tmpdir"); assertThat(UtilAll.getDiskPartitionSpaceUsedPercent(null)).isCloseTo(-1, within(0.000001)); assertThat(UtilAll.getDiskPartitionSpaceUsedPercent("")).isCloseTo(-1, within(0.000001)); assertThat(UtilAll.getDiskPartitionSpaceUsedPercent("nonExistingPath")).isCloseTo(-1, within(0.000001)); assertThat(UtilAll.getDiskPartitionSpaceUsedPercent(tmpDir)).isNotCloseTo(-1, within(0.000001)); } |
### Question:
UtilAll { public static boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return false; } } return true; } static int getPid(); static String currentStackTrace(); static String offset2FileName(final long offset); static long computeEclipseTimeMilliseconds(final long beginTime); static boolean isItTimeToDo(final String when); static String timeMillisToHumanString(); static String timeMillisToHumanString(final long t); static long computNextMorningTimeMillis(); static long computNextMinutesTimeMillis(); static long computNextHourTimeMillis(); static long computNextHalfHourTimeMillis(); static String timeMillisToHumanString2(final long t); static String timeMillisToHumanString3(final long t); static double getDiskPartitionSpaceUsedPercent(final String path); static int crc32(byte[] array); static int crc32(byte[] array, int offset, int length); static String bytes2string(byte[] src); static byte[] string2bytes(String hexString); static byte[] uncompress(final byte[] src); static byte[] compress(final byte[] src, final int level); static int asInt(String str, int defaultValue); static long asLong(String str, long defaultValue); static String formatDate(Date date, String pattern); static Date parseDate(String date, String pattern); static String responseCode2String(final int code); static String frontStringAtLeast(final String str, final int size); static boolean isBlank(String str); static String jstack(); static String jstack(Map<Thread, StackTraceElement[]> map); static boolean isInternalIP(byte[] ip); static String ipToIPv4Str(byte[] ip); static byte[] getIP(); static final String YYYY_MM_DD_HH_MM_SS; static final String YYYY_MM_DD_HH_MM_SS_SSS; static final String YYYYMMDDHHMMSS; }### Answer:
@Test public void testIsBlank() { assertThat(UtilAll.isBlank("Hello ")).isFalse(); assertThat(UtilAll.isBlank(" Hello")).isFalse(); assertThat(UtilAll.isBlank("He llo")).isFalse(); assertThat(UtilAll.isBlank(" ")).isTrue(); assertThat(UtilAll.isBlank("Hello")).isFalse(); } |
### Question:
MixAll { public static String brokerVIPChannel(final boolean isChange, final String brokerAddr) { if (isChange) { String[] ipAndPort = brokerAddr.split(":"); String brokerAddrNew = ipAndPort[0] + ":" + (Integer.parseInt(ipAndPort[1]) - 2); return brokerAddrNew; } else { return brokerAddr; } } static String getWSAddr(); static String getRetryTopic(final String consumerGroup); static boolean isSysConsumerGroup(final String consumerGroup); static boolean isSystemTopic(final String topic); static String getDLQTopic(final String consumerGroup); static String brokerVIPChannel(final boolean isChange, final String brokerAddr); static long getPID(); static long createBrokerId(final String ip, final int port); static void string2File(final String str, final String fileName); static void string2FileNotSafe(final String str, final String fileName); static String file2String(final String fileName); static String file2String(final File file); static String file2String(final URL url); static String findClassPath(Class<?> c); static void printObjectProperties(final Logger log, final Object object); static void printObjectProperties(final Logger log, final Object object, final boolean onlyImportantField); static String properties2String(final Properties properties); static Properties string2Properties(final String str); static Properties object2Properties(final Object object); static void properties2Object(final Properties p, final Object object); static boolean isPropertiesEqual(final Properties p1, final Properties p2); static List<String> getLocalInetAddress(); static boolean isLocalAddr(String address); static boolean compareAndIncreaseOnly(final AtomicLong target, final long value); static String localhostName(); static String humanReadableByteCount(long bytes, boolean si); Set<String> list2Set(List<String> values); List<String> set2List(Set<String> values); static final String ROCKETMQ_HOME_ENV; static final String ROCKETMQ_HOME_PROPERTY; static final String NAMESRV_ADDR_ENV; static final String NAMESRV_ADDR_PROPERTY; static final String MESSAGE_COMPRESS_LEVEL; static final String DEFAULT_NAMESRV_ADDR_LOOKUP; static final String WS_DOMAIN_NAME; static final String WS_DOMAIN_SUBGROUP; static final String DEFAULT_TOPIC; static final String BENCHMARK_TOPIC; static final String DEFAULT_PRODUCER_GROUP; static final String DEFAULT_CONSUMER_GROUP; static final String TOOLS_CONSUMER_GROUP; static final String FILTERSRV_CONSUMER_GROUP; static final String MONITOR_CONSUMER_GROUP; static final String CLIENT_INNER_PRODUCER_GROUP; static final String SELF_TEST_PRODUCER_GROUP; static final String SELF_TEST_CONSUMER_GROUP; static final String SELF_TEST_TOPIC; static final String OFFSET_MOVED_EVENT; static final String ONS_HTTP_PROXY_GROUP; static final String CID_ONSAPI_PERMISSION_GROUP; static final String CID_ONSAPI_OWNER_GROUP; static final String CID_ONSAPI_PULL_GROUP; static final String CID_RMQ_SYS_PREFIX; static final List<String> LOCAL_INET_ADDRESS; static final String LOCALHOST; static final String DEFAULT_CHARSET; static final long MASTER_ID; static final long CURRENT_JVM_PID; static final String RETRY_GROUP_TOPIC_PREFIX; static final String DLQ_GROUP_TOPIC_PREFIX; static final String SYSTEM_TOPIC_PREFIX; static final String UNIQUE_MSG_QUERY_FLAG; static final String DEFAULT_TRACE_REGION_ID; static final String CONSUME_CONTEXT_TYPE; }### Answer:
@Test public void testBrokerVIPChannel() { assertThat(MixAll.brokerVIPChannel(true, "127.0.0.1:10911")).isEqualTo("127.0.0.1:10909"); } |
### Question:
CommandUtil { public static Map<String, List<String>> fetchMasterAndSlaveDistinguish( final MQAdminExt adminExt, final String clusterName) throws InterruptedException, RemotingConnectException, RemotingTimeoutException, RemotingSendRequestException, MQBrokerException { Map<String, List<String>> masterAndSlaveMap = new HashMap<String, List<String>>(4); ClusterInfo clusterInfoSerializeWrapper = adminExt.examineBrokerClusterInfo(); Set<String> brokerNameSet = clusterInfoSerializeWrapper.getClusterAddrTable().get(clusterName); if (brokerNameSet == null) { System.out .printf("[error] Make sure the specified clusterName exists or the nameserver which connected is correct."); return masterAndSlaveMap; } for (String brokerName : brokerNameSet) { BrokerData brokerData = clusterInfoSerializeWrapper.getBrokerAddrTable().get(brokerName); if (brokerData == null || brokerData.getBrokerAddrs() == null) { continue; } String masterAddr = brokerData.getBrokerAddrs().get(MixAll.MASTER_ID); masterAndSlaveMap.put(masterAddr, new ArrayList<String>()); for (Long id : brokerData.getBrokerAddrs().keySet()) { if (brokerData.getBrokerAddrs().get(id) == null || id.longValue() == MixAll.MASTER_ID) { continue; } masterAndSlaveMap.get(masterAddr).add(brokerData.getBrokerAddrs().get(id)); } } return masterAndSlaveMap; } static Map<String/*master addr*/, List<String>/*slave addr*/> fetchMasterAndSlaveDistinguish(
final MQAdminExt adminExt, final String clusterName); static Set<String> fetchMasterAddrByClusterName(final MQAdminExt adminExt, final String clusterName); static Set<String> fetchMasterAndSlaveAddrByClusterName(final MQAdminExt adminExt, final String clusterName); static Set<String> fetchBrokerNameByClusterName(final MQAdminExt adminExt, final String clusterName); static String fetchBrokerNameByAddr(final MQAdminExt adminExt, final String addr); }### Answer:
@Test public void testFetchMasterAndSlaveDistinguish() throws InterruptedException, MQBrokerException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException { Map<String, List<String>> result = CommandUtil.fetchMasterAndSlaveDistinguish(defaultMQAdminExtImpl, "default-cluster"); assertThat(result.get(null).get(0)).isEqualTo("127.0.0.1:10911"); } |
### Question:
Condition implements Internal<Condition<S, T>, T> { public S invoke(Action action) { if (isSourceChainUpdateAccepted()) Invoker.invoke(action); return sourceProxy.owner(); } private Condition(S source, Predicate<T> predicate, boolean negateExpression); S then(Consumer<T> action); S invoke(Action action); Optional<R> thenMap(Function<T, R> mapper); Optional<R> thenTo(@NonNull R item); Optional<R> thenTo(@NonNull Callable<R> itemCallable); Logger<Condition<S, T>, T> log(Object tag); @Override Proxy<Condition<S, T>, T> access(); }### Answer:
@Test public void whenNotWithTruePredicateThenDoNotInvokeAction() { final boolean[] result = {false}; new Chain<>(new TestClass(), chainConfiguration) .apply(new Consumer<TestClass>() { @Override public void accept(@NonNull TestClass testClass) throws Exception { testClass.setText("!"); } }) .whenNot(new Predicate<TestClass>() { @Override public boolean test(@NonNull TestClass testClass) throws Exception { return testClass.text.equals("!"); } }) .invoke(new Action() { @Override public void run() throws Exception { result[0] = true; } }) .call(); assertFalse(result[0]); }
@Test public void whenNotWithFalsePredicateThenInvokeAction() { final boolean[] result = {false}; TestClass testClass = new Chain<>(new TestClass(), chainConfiguration) .apply(new Consumer<TestClass>() { @Override public void accept(@NonNull TestClass testClass) throws Exception { testClass.setText("!"); } }) .whenNot(new Predicate<TestClass>() { @Override public boolean test(@NonNull TestClass testClass) throws Exception { return false; } }) .invoke(new Action() { @Override public void run() throws Exception { result[0] = true; } }) .call(); assertTrue(result[0]); }
@Test(expected = UnsupportedOperationException.class) public void invokeActionWithExceptionThenThrowException() { new Chain<>(new TestClass(), chainConfiguration) .apply(new Consumer<TestClass>() { @Override public void accept(@NonNull TestClass testClass) throws Exception { testClass.setText("!"); } }) .when(new Predicate<TestClass>() { @Override public boolean test(@NonNull TestClass testClass) throws Exception { return testClass.text.equals("!"); } }) .invoke(new Action() { @Override public void run() throws Exception { throw new UnsupportedOperationException(); } }) .call(); }
@Test public void whenWithTruePredicateThenInvokeAction() { final boolean[] result = {false}; new Chain<>(new TestClass(), chainConfiguration) .apply(new Consumer<TestClass>() { @Override public void accept(@NonNull TestClass testClass) throws Exception { testClass.setText("!"); } }) .when(new Predicate<TestClass>() { @Override public boolean test(@NonNull TestClass testClass) throws Exception { return testClass.text.equals("!"); } }) .invoke(new Action() { @Override public void run() throws Exception { result[0] = true; } }) .call(); assertTrue(result[0]); }
@Test public void whenWithFalsePredicateThenDoNotInvokeAction() { final boolean[] result = {false}; TestClass testClass = new Chain<>(new TestClass(), chainConfiguration) .apply(new Consumer<TestClass>() { @Override public void accept(@NonNull TestClass testClass) throws Exception { testClass.setText("!"); } }) .when(new Predicate<TestClass>() { @Override public boolean test(@NonNull TestClass testClass) throws Exception { return false; } }) .invoke(new Action() { @Override public void run() throws Exception { result[0] = true; } }) .call(); assertFalse(result[0]); } |
### Question:
Condition implements Internal<Condition<S, T>, T> { public <R> Optional<R> thenMap(Function<T, R> mapper) { if (isSourceChainUpdateAccepted()) { return new Optional<>(Invoker.invoke(mapper, sourceProxy.getItem()), sourceProxy.getConfiguration()); } else { return new Optional<>(null, sourceProxy.getConfiguration()); } } private Condition(S source, Predicate<T> predicate, boolean negateExpression); S then(Consumer<T> action); S invoke(Action action); Optional<R> thenMap(Function<T, R> mapper); Optional<R> thenTo(@NonNull R item); Optional<R> thenTo(@NonNull Callable<R> itemCallable); Logger<Condition<S, T>, T> log(Object tag); @Override Proxy<Condition<S, T>, T> access(); }### Answer:
@Test public void thenMapWithValidConditionThenReturnAnOptionalContainingMappedValue() { TestClassTwo result = new Chain<>(new TestClass(), chainConfiguration) .when(new Predicate<TestClass>() { @Override public boolean test(TestClass testClass) throws Exception { return true; } }) .thenMap(new Function<TestClass, TestClassTwo>() { @Override public TestClassTwo apply(TestClass testClass) throws Exception { return new TestClassTwo("1"); } }) .defaultIfEmpty(new TestClassTwo("2")) .call(); assertEquals("1", result.text); }
@Test public void thenMapWithInvalidConditionThenReturnAnOptionalContainingNull() { TestClassTwo result = new Chain<>(new TestClass(), chainConfiguration) .when(new Predicate<TestClass>() { @Override public boolean test(TestClass testClass) throws Exception { return false; } }) .thenMap(new Function<TestClass, TestClassTwo>() { @Override public TestClassTwo apply(TestClass testClass) throws Exception { return new TestClassTwo("1"); } }) .defaultIfEmpty(new TestClassTwo("2")) .call(); assertEquals("2", result.text); }
@Test(expected = UnsupportedOperationException.class) public void thenMapWithExceptionThenThrowException() { new Chain<>(new TestClass(), chainConfiguration) .when(new Predicate<TestClass>() { @Override public boolean test(TestClass testClass) throws Exception { return true; } }) .thenMap(new Function<TestClass, TestClassTwo>() { @Override public TestClassTwo apply(TestClass testClass) throws Exception { throw new UnsupportedOperationException(); } }); } |
### Question:
Condition implements Internal<Condition<S, T>, T> { public <R> Optional<R> thenTo(@NonNull R item) { if (isSourceChainUpdateAccepted()) { return new Optional<>(item, sourceProxy.getConfiguration()); } else { return new Optional<>(null, sourceProxy.getConfiguration()); } } private Condition(S source, Predicate<T> predicate, boolean negateExpression); S then(Consumer<T> action); S invoke(Action action); Optional<R> thenMap(Function<T, R> mapper); Optional<R> thenTo(@NonNull R item); Optional<R> thenTo(@NonNull Callable<R> itemCallable); Logger<Condition<S, T>, T> log(Object tag); @Override Proxy<Condition<S, T>, T> access(); }### Answer:
@Test public void thenToItemWithValidConditionThenReturnAnOptionalContainingItem() { TestClassTwo result = new Chain<>(new TestClass(), chainConfiguration) .when(new Predicate<TestClass>() { @Override public boolean test(TestClass testClass) throws Exception { return true; } }) .thenTo(new TestClassTwo("1")) .defaultIfEmpty(new TestClassTwo("2")) .call(); assertEquals("1", result.text); }
@Test public void thenToItemWithInvalidConditionThenReturnAnOptionalContainingNull() { TestClassTwo result = new Chain<>(new TestClass(), chainConfiguration) .when(new Predicate<TestClass>() { @Override public boolean test(TestClass testClass) throws Exception { return false; } }) .thenTo(new TestClassTwo("1")) .defaultIfEmpty(new TestClassTwo("2")) .call(); assertEquals("2", result.text); }
@Test public void thenToCallableWithValidConditionThenReturnAnOptionalContainingMappedValue() { TestClassTwo result = new Chain<>(new TestClass(), chainConfiguration) .when(new Predicate<TestClass>() { @Override public boolean test(TestClass testClass) throws Exception { return true; } }) .thenTo(new Callable<TestClassTwo>() { @Override public TestClassTwo call() throws Exception { return new TestClassTwo("1"); } }) .defaultIfEmpty(new TestClassTwo("2")) .call(); assertEquals("1", result.text); }
@Test public void thenToCallableWithInvalidConditionThenReturnAnOptionalContainingNull() { TestClassTwo result = new Chain<>(new TestClass(), chainConfiguration) .when(new Predicate<TestClass>() { @Override public boolean test(TestClass testClass) throws Exception { return false; } }) .thenTo(new Callable<TestClassTwo>() { @Override public TestClassTwo call() throws Exception { return new TestClassTwo("1"); } }) .defaultIfEmpty(new TestClassTwo("2")) .call(); assertEquals("2", result.text); }
@Test(expected = UnsupportedOperationException.class) public void thenToCallableWithExceptionThenThrowException() { new Chain<>(new TestClass(), chainConfiguration) .when(new Predicate<TestClass>() { @Override public boolean test(TestClass testClass) throws Exception { return true; } }) .thenTo(new Callable<TestClassTwo>() { @Override public TestClassTwo call() throws Exception { throw new UnsupportedOperationException(); } }); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.