method2testcases stringlengths 118 3.08k |
|---|
### Question:
RangeDefinition { public static boolean isDocSpecific(Range range) { return QueryIterator.isDocumentSpecificRange(range); } static boolean isDocSpecific(Range range); static boolean allDocSpecific(Collection<Range> ranges); }### Answer:
@Test public void docSpecificRangeTest() { Range docSpecificRange = new Range(new Key("20190101_0", "dataType\u0000some-doc-id"), false, new Key("20190101_0", "dataType\u0000some-doc-id\u0000"), false); assertTrue(RangeDefinition.isDocSpecific(docSpecificRange)); }
@Test public void shardRangeTest() { Range shardRange = new Range(new Key("20190101_0"), false, new Key("20190101_0\u0000"), false); assertFalse(RangeDefinition.isDocSpecific(shardRange)); }
@Test public void dayRangeTest() { Range dayRange = new Range(new Key("20190101_0"), false, new Key("20190101" + Constants.MAX_UNICODE_STRING), false); assertFalse(RangeDefinition.isDocSpecific(dayRange)); } |
### Question:
AbstractTableConfigHelper implements TableConfigHelper { protected boolean areAggregatorsConfigured(String tableName, List<CombinerConfiguration> aggregators, TableOperations tops) throws TableNotFoundException { boolean aggregatorsConfigured = false; Map<String,String> props = generateInitialTableProperties(); props.putAll(generateAggTableProperties(aggregators)); Iterable<Entry<String,String>> properties; try { properties = tops.getProperties(tableName); } catch (Exception ex) { throw new RuntimeException("Unexpected error checking on aggregators", ex); } for (Entry<String,String> entry : properties) { String key = entry.getKey(); String actualValue = entry.getValue(); String requiredValue = props.remove(key); if (requiredValue != null && !requiredValue.equals(actualValue)) { props.put(key, actualValue); break; } } aggregatorsConfigured = props.isEmpty(); return aggregatorsConfigured; } @Override abstract void setup(String tableName, Configuration config, Logger log); @Override abstract void configure(TableOperations tops); static void setPropertyIfNecessary(String tableName, String propertyName, String propertyValue, TableOperations tops, Logger log); static Map<String,String> generateInitialTableProperties(); static Map<String,String> generateAggTableProperties(List<CombinerConfiguration> aggregators); }### Answer:
@Test public void testAreAggregatorsConfigured() throws AccumuloSecurityException, TableNotFoundException, AccumuloException { AbstractTableConfigHelperTest.logger.info("AbstractTableConfigHelperTest.testAreAggregatorsConfigured() called."); try { AbstractTableConfigHelperTest.TestAbstractTableConfigHelperImpl uut = new AbstractTableConfigHelperTest.TestAbstractTableConfigHelperImpl(); Assert.assertNotNull("AbstractTableConfigHelper.cTor failed to create an instance", uut); uut.parent = this; uut.exposeAreAggregatorsConfigured(); } finally { AbstractTableConfigHelperTest.logger.info("AbstractTableConfigHelperTest.testAreAggregatorsConfigured() completed."); } } |
### Question:
AbstractTableConfigHelper implements TableConfigHelper { protected boolean areLocalityGroupsConfigured(String tableName, Map<String,Set<Text>> newLocalityGroups, TableOperations tops) throws AccumuloException, TableNotFoundException, AccumuloSecurityException { Map<String,Set<Text>> localityGroups = tops.getLocalityGroups(tableName); for (Map.Entry<String,Set<Text>> entry : newLocalityGroups.entrySet()) { Set<Text> families = localityGroups.get(entry.getKey()); if (families == null) { return false; } if (!families.containsAll(entry.getValue())) { return false; } } return true; } @Override abstract void setup(String tableName, Configuration config, Logger log); @Override abstract void configure(TableOperations tops); static void setPropertyIfNecessary(String tableName, String propertyName, String propertyValue, TableOperations tops, Logger log); static Map<String,String> generateInitialTableProperties(); static Map<String,String> generateAggTableProperties(List<CombinerConfiguration> aggregators); }### Answer:
@Test public void testAreLocalityGroupsConfigured() throws AccumuloSecurityException, AccumuloException, TableNotFoundException { AbstractTableConfigHelperTest.logger.info("AbstractTableConfigHelperTest.testAreLocalityGroupsConfigured() called."); try { AbstractTableConfigHelperTest.TestAbstractTableConfigHelperImpl uut = new AbstractTableConfigHelperTest.TestAbstractTableConfigHelperImpl(); Assert.assertNotNull("AbstractTableConfigHelper.cTor failed to create an instance", uut); uut.parent = this; uut.exposeAreLocalityGroupsConfigured(); } finally { AbstractTableConfigHelperTest.logger.info("AbstractTableConfigHelperTest.testAreLocalityGroupsConfigured() completed."); } } |
### Question:
LuceneToJexlControlledQueryParser extends LuceneToJexlQueryParser implements ControlledQueryParser { @Override public void setIncludedValues(Map<String,Set<String>> includedValues) { this.includedValues = includedValues; } LuceneToJexlControlledQueryParser(); @Override QueryNode parse(String query); @Override void setExcludedValues(Map<String,Set<String>> excludedValues); @Override Map<String,Set<String>> getExcludedValues(); @Override void setIncludedValues(Map<String,Set<String>> includedValues); @Override Map<String,Set<String>> getIncludedValues(); }### Answer:
@Test public void testAllowedAnyfieldWithEmptyAllowedFields() throws ParseException { parser = new LuceneToJexlControlledQueryParser(); parser.setAllowAnyField(true); parser.setIncludedValues(ImmutableMap.<String,Set<String>> of()); parser.setAllowedFields(ImmutableSet.<String> of()); parseQuery("unfieldedValue"); }
@Test public void testIncludedFields() throws ParseException { parser = new LuceneToJexlControlledQueryParser(); Set<String> allowedFields = new HashSet<>(); allowedFields.add("FIELD1"); allowedFields.add("FIELD2"); allowedFields.add("FIELD3"); parser.setAllowedFields(allowedFields); Map<String,Set<String>> includedValues = new LinkedHashMap<>(); includedValues.put("FIELD2", Collections.singleton("specialvalue2")); includedValues.put("FIELD3", Collections.singleton("specialvalue3")); parser.setIncludedValues(includedValues); Assert.assertEquals("(FIELD1 == 'value') && ((filter:includeRegex(FIELD2, 'specialvalue2')) || (filter:includeRegex(FIELD3, 'specialvalue3')))", parseQuery("FIELD1:value")); } |
### Question:
LuceneToJexlControlledQueryParser extends LuceneToJexlQueryParser implements ControlledQueryParser { @Override public QueryNode parse(String query) throws ParseException { StringBuilder sb = new StringBuilder(); boolean addedFirstInclude = false; for (Map.Entry<String,Set<String>> entry : includedValues.entrySet()) { String field = entry.getKey(); for (String value : entry.getValue()) { if (addedFirstInclude == true) { sb.append(" OR "); } addedFirstInclude = true; sb.append("#INCLUDE(").append(field).append(", ").append(value).append(")"); } } if (!includedValues.isEmpty() && !excludedValues.isEmpty()) { sb.append(" AND "); } boolean addedFirstExclude = false; for (Map.Entry<String,Set<String>> entry : excludedValues.entrySet()) { String field = entry.getKey(); for (String value : entry.getValue()) { if (addedFirstExclude == true) { sb.append(" AND "); } addedFirstExclude = true; sb.append("#EXCLUDE(").append(field).append(", ").append(value).append(")"); } } if (sb.length() > 0) { query = "(" + query + ")" + " AND (" + sb + ")"; } return super.parse(query); } LuceneToJexlControlledQueryParser(); @Override QueryNode parse(String query); @Override void setExcludedValues(Map<String,Set<String>> excludedValues); @Override Map<String,Set<String>> getExcludedValues(); @Override void setIncludedValues(Map<String,Set<String>> includedValues); @Override Map<String,Set<String>> getIncludedValues(); }### Answer:
@Test public void testTransformsLowerCaseBeforeComparingAgainstAllowed() throws ParseException { parser = new LuceneToJexlControlledQueryParser(); Set<String> allowedFields = new HashSet<>(); allowedFields.add("FIELD1"); allowedFields.add("FIELD2"); allowedFields.add("FIELD3"); parser.setAllowedFields(allowedFields); parser.parse("FIELD1:value field2:value FIELD3:value"); parser.parse("field1:value FIELD2:value field3:value"); } |
### Question:
LuceneToJexlControlledQueryParser extends LuceneToJexlQueryParser implements ControlledQueryParser { @Override public void setExcludedValues(Map<String,Set<String>> excludedValues) { this.excludedValues = excludedValues; } LuceneToJexlControlledQueryParser(); @Override QueryNode parse(String query); @Override void setExcludedValues(Map<String,Set<String>> excludedValues); @Override Map<String,Set<String>> getExcludedValues(); @Override void setIncludedValues(Map<String,Set<String>> includedValues); @Override Map<String,Set<String>> getIncludedValues(); }### Answer:
@Test public void testExcludedValues() throws ParseException { parser = new LuceneToJexlControlledQueryParser(); Set<String> allowedFields = new HashSet<>(); allowedFields.add("FIELD1"); allowedFields.add("FIELD2"); allowedFields.add("FIELD3"); parser.setAllowedFields(allowedFields); Map<String,Set<String>> excludedValues = new LinkedHashMap<>(); excludedValues.put("FIELD2", Collections.singleton("specialvalue2")); excludedValues.put("FIELD3", Collections.singleton("specialvalue3")); parser.setExcludedValues(excludedValues); Assert.assertEquals( "(FIELD1 == 'value') && ((not(filter:includeRegex(FIELD2, 'specialvalue2'))) && (not(filter:includeRegex(FIELD3, 'specialvalue3'))))", parseQuery("FIELD1:value")); } |
### Question:
JexlNodeSet implements Set<JexlNode> { @Override public boolean contains(Object o) { if (o instanceof JexlNode) { String nodeKey = buildKey((JexlNode) o); return nodeMap.containsKey(nodeKey); } return false; } JexlNodeSet(); JexlNodeSet(boolean useSourceNodeForKeys); Collection<JexlNode> getNodes(); Set<String> getNodeKeys(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<JexlNode> iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(JexlNode node); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends JexlNode> collection); @Override boolean retainAll(Collection<?> collection); @Override boolean removeAll(Collection<?> collection); @Override void clear(); String buildKey(JexlNode node); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testContains() { JexlNode node = JexlNodeFactory.buildEQNode("FOO", "bar"); JexlNodeSet nodeSet = new JexlNodeSet(); nodeSet.add(node); assertTrue(nodeSet.contains(node)); assertFalse(nodeSet.contains("a string?!?!")); } |
### Question:
JexlNodeSet implements Set<JexlNode> { @Override public Iterator<JexlNode> iterator() { return Collections.unmodifiableCollection(nodeMap.values()).iterator(); } JexlNodeSet(); JexlNodeSet(boolean useSourceNodeForKeys); Collection<JexlNode> getNodes(); Set<String> getNodeKeys(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<JexlNode> iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(JexlNode node); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends JexlNode> collection); @Override boolean retainAll(Collection<?> collection); @Override boolean removeAll(Collection<?> collection); @Override void clear(); String buildKey(JexlNode node); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testIterator() { JexlNode node = JexlNodeFactory.buildEQNode("FOO", "bar"); JexlNodeSet nodeSet = new JexlNodeSet(); nodeSet.add(node); Iterator<JexlNode> iter = nodeSet.iterator(); assertTrue(iter.hasNext()); JexlNode next = iter.next(); assertEquals(JexlASTHelper.nodeToKey(node), JexlASTHelper.nodeToKey(next)); assertFalse(iter.hasNext()); } |
### Question:
JexlNodeSet implements Set<JexlNode> { @Override public Object[] toArray() { return nodeMap.entrySet().toArray(); } JexlNodeSet(); JexlNodeSet(boolean useSourceNodeForKeys); Collection<JexlNode> getNodes(); Set<String> getNodeKeys(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<JexlNode> iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(JexlNode node); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends JexlNode> collection); @Override boolean retainAll(Collection<?> collection); @Override boolean removeAll(Collection<?> collection); @Override void clear(); String buildKey(JexlNode node); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testToArray2() { JexlNodeSet nodeSet = new JexlNodeSet(); nodeSet.toArray(new Object[0]); } |
### Question:
JexlNodeSet implements Set<JexlNode> { @Override public boolean add(JexlNode node) { String nodeKey = buildKey(node); return directAdd(nodeKey, node); } JexlNodeSet(); JexlNodeSet(boolean useSourceNodeForKeys); Collection<JexlNode> getNodes(); Set<String> getNodeKeys(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<JexlNode> iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(JexlNode node); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends JexlNode> collection); @Override boolean retainAll(Collection<?> collection); @Override boolean removeAll(Collection<?> collection); @Override void clear(); String buildKey(JexlNode node); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testAdd() { JexlNode node1 = JexlNodeFactory.buildEQNode("FOO", "bar"); JexlNode node2 = JexlNodeFactory.buildEQNode("FOO", "bar"); JexlNode node3 = JexlNodeFactory.buildEQNode("FOO2", "bar2"); JexlNodeSet nodeSet = new JexlNodeSet(); assertTrue(nodeSet.add(node1)); assertFalse(nodeSet.add(node2)); assertEquals(1, nodeSet.size()); assertTrue(nodeSet.contains(node1)); assertTrue(nodeSet.contains(node2)); assertFalse(nodeSet.contains(node3)); assertTrue(nodeSet.add(node3)); assertFalse(nodeSet.add(node3)); assertFalse(nodeSet.add(node3)); assertEquals(2, nodeSet.size()); assertTrue(nodeSet.contains(node1)); assertTrue(nodeSet.contains(node2)); assertTrue(nodeSet.contains(node3)); } |
### Question:
JexlNodeSet implements Set<JexlNode> { @Override public boolean remove(Object o) { if (o instanceof JexlNode) { String nodeKey = buildKey((JexlNode) o); return nodeMap.remove(nodeKey, nodeMap.get(nodeKey)); } else if (o instanceof String) { JexlNode node = nodeMap.get(o); return nodeMap.remove(o, node); } return false; } JexlNodeSet(); JexlNodeSet(boolean useSourceNodeForKeys); Collection<JexlNode> getNodes(); Set<String> getNodeKeys(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<JexlNode> iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(JexlNode node); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends JexlNode> collection); @Override boolean retainAll(Collection<?> collection); @Override boolean removeAll(Collection<?> collection); @Override void clear(); String buildKey(JexlNode node); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testRemove() { JexlNode node1 = JexlNodeFactory.buildEQNode("FOO", "bar"); JexlNode node2 = JexlNodeFactory.buildEQNode("FOO2", "bar2"); JexlNodeSet nodeSet = new JexlNodeSet(); nodeSet.add(node1); nodeSet.add(node2); assertEquals(2, nodeSet.size()); assertTrue(nodeSet.contains(node1)); assertTrue(nodeSet.contains(node2)); assertTrue(nodeSet.remove(node2)); assertEquals(1, nodeSet.size()); assertTrue(nodeSet.contains(node1)); assertFalse(nodeSet.contains(node2)); assertTrue(nodeSet.remove(node1)); assertEquals(0, nodeSet.size()); assertFalse(nodeSet.contains(node1)); assertFalse(nodeSet.contains(node2)); assertTrue(nodeSet.isEmpty()); assertFalse(nodeSet.remove("this other thing")); } |
### Question:
JexlNodeSet implements Set<JexlNode> { @Override public boolean containsAll(Collection<?> collection) { if (collection != null) { for (Object o : collection) { if (!contains(o)) { return false; } } return true; } return false; } JexlNodeSet(); JexlNodeSet(boolean useSourceNodeForKeys); Collection<JexlNode> getNodes(); Set<String> getNodeKeys(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<JexlNode> iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(JexlNode node); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends JexlNode> collection); @Override boolean retainAll(Collection<?> collection); @Override boolean removeAll(Collection<?> collection); @Override void clear(); String buildKey(JexlNode node); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testContainsAll() { JexlNode node1 = JexlNodeFactory.buildEQNode("FOO", "bar"); JexlNode node2 = JexlNodeFactory.buildEQNode("FOO2", "bar2"); JexlNode node3 = JexlNodeFactory.buildEQNode("FOO3", "bar3"); JexlNodeSet nodeSet = new JexlNodeSet(); nodeSet.add(node1); nodeSet.add(node2); Collection<JexlNode> nodes = Lists.newArrayList(node1, node2); assertTrue(nodeSet.containsAll(nodes)); nodes = Lists.newArrayList(node2, node3); assertFalse(nodeSet.containsAll(nodes)); nodes = Lists.newArrayList(node3); assertFalse(nodeSet.containsAll(nodes)); assertFalse(nodeSet.containsAll(null)); } |
### Question:
JexlNodeSet implements Set<JexlNode> { @Override public boolean removeAll(Collection<?> collection) { boolean modified = false; if (collection != null) { for (Object o : collection) { if (remove(o)) { modified = true; } } } return modified; } JexlNodeSet(); JexlNodeSet(boolean useSourceNodeForKeys); Collection<JexlNode> getNodes(); Set<String> getNodeKeys(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<JexlNode> iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(JexlNode node); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends JexlNode> collection); @Override boolean retainAll(Collection<?> collection); @Override boolean removeAll(Collection<?> collection); @Override void clear(); String buildKey(JexlNode node); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testRemoveAll() { JexlNode node1 = JexlNodeFactory.buildEQNode("FOO", "bar"); JexlNode node2 = JexlNodeFactory.buildEQNode("FOO2", "bar2"); JexlNode node3 = JexlNodeFactory.buildEQNode("FOO3", "bar3"); Collection<JexlNode> nodes = Lists.newArrayList(node1, node2, node3); Collection<JexlNode> remove = Lists.newArrayList(node1, node3); JexlNodeSet nodeSet = new JexlNodeSet(); nodeSet.addAll(nodes); assertTrue(nodeSet.contains(node1)); assertTrue(nodeSet.contains(node2)); assertTrue(nodeSet.contains(node3)); assertTrue(nodeSet.removeAll(remove)); assertFalse(nodeSet.contains(node1)); assertTrue(nodeSet.contains(node2)); assertFalse(nodeSet.contains(node3)); } |
### Question:
JexlNodeSet implements Set<JexlNode> { @Override public void clear() { this.nodeMap.clear(); } JexlNodeSet(); JexlNodeSet(boolean useSourceNodeForKeys); Collection<JexlNode> getNodes(); Set<String> getNodeKeys(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<JexlNode> iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(JexlNode node); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends JexlNode> collection); @Override boolean retainAll(Collection<?> collection); @Override boolean removeAll(Collection<?> collection); @Override void clear(); String buildKey(JexlNode node); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testClear() { JexlNode node1 = JexlNodeFactory.buildEQNode("FOO", "bar"); JexlNode node2 = JexlNodeFactory.buildEQNode("FOO2", "bar2"); JexlNode node3 = JexlNodeFactory.buildEQNode("FOO3", "bar3"); Collection<JexlNode> nodes = Lists.newArrayList(node1, node2, node3); JexlNodeSet nodeSet = new JexlNodeSet(); nodeSet.addAll(nodes); assertTrue(nodeSet.contains(node1)); assertTrue(nodeSet.contains(node2)); assertTrue(nodeSet.contains(node3)); assertFalse(nodeSet.isEmpty()); nodeSet.clear(); assertFalse(nodeSet.contains(node1)); assertFalse(nodeSet.contains(node2)); assertFalse(nodeSet.contains(node3)); assertTrue(nodeSet.isEmpty()); } |
### Question:
JexlNodeSet implements Set<JexlNode> { @Override public boolean equals(Object o) { if (o == null) return false; if (this == o) return true; if (o instanceof JexlNodeSet) { JexlNodeSet other = (JexlNodeSet) o; if (this.size() != other.size()) return false; return this.nodeMap.keySet().equals(other.nodeMap.keySet()); } return false; } JexlNodeSet(); JexlNodeSet(boolean useSourceNodeForKeys); Collection<JexlNode> getNodes(); Set<String> getNodeKeys(); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<JexlNode> iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(JexlNode node); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends JexlNode> collection); @Override boolean retainAll(Collection<?> collection); @Override boolean removeAll(Collection<?> collection); @Override void clear(); String buildKey(JexlNode node); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testEquals() { JexlNodeSet prime = new JexlNodeSet(); assertFalse(prime.equals(null)); assertTrue(prime.equals(prime)); JexlNodeSet other = new JexlNodeSet(); other.add(JexlNodeFactory.buildEQNode("FOO", "bar")); assertFalse(prime.equals(other)); prime.add(JexlNodeFactory.buildEQNode("FOO", "bar")); assertTrue(prime.equals(other)); } |
### Question:
DateIndexTableConfigHelper extends AbstractTableConfigHelper { @Override public void configure(TableOperations tops) throws AccumuloException, AccumuloSecurityException, TableNotFoundException { configureDateIndexTable(tops); } @Override void setup(String tableName, Configuration config, Logger log); @Override void configure(TableOperations tops); static final String LOCALITY_GROUPS; }### Answer:
@Test(expected = TableNotFoundException.class) public void testConfigureCalledBeforeSetup() throws AccumuloSecurityException, AccumuloException, TableNotFoundException { DateIndexTableConfigHelperTest.logger.info("DateIndexTableConfigHelperTest.testConfigureCalledBeforeSetup called."); try { DateIndexTableConfigHelper uut = new DateIndexTableConfigHelper(); TableOperations tops = mockUpTableOperations(); uut.configure(tops); Assert.fail("DateIndexTableConfigHelper.configure failed to throw expected exception."); } finally { DateIndexTableConfigHelperTest.logger.info("DateIndexTableConfigHelperTest.testConfigureCalledBeforeSetup completed."); } } |
### Question:
AncestorChildExpansionIterator implements SortedKeyValueIterator<Key,Value> { @Override public boolean hasTop() { if (!seeked) { throw new IllegalStateException("cannot hasTop(), iterator has not been seeked"); } if (!initialized) { nextChild(); } return topKey != null; } AncestorChildExpansionIterator(SortedKeyValueIterator<Key,Value> iterator, List<String> children, Equality equality); @Override void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options, IteratorEnvironment env); @Override boolean hasTop(); @Override void next(); @Override void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive); @Override Key getTopKey(); @Override Value getTopValue(); @Override SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env); }### Answer:
@Test(expected = IllegalStateException.class) public void testUninitializedHasTop() { iterator.hasTop(); } |
### Question:
AncestorChildExpansionIterator implements SortedKeyValueIterator<Key,Value> { @Override public Key getTopKey() { if (!seeked) { throw new IllegalStateException("cannot getTopKey(), iterator has not been seeked"); } if (topKey == null) { throw new NoSuchElementException("top key does not exist"); } return topKey; } AncestorChildExpansionIterator(SortedKeyValueIterator<Key,Value> iterator, List<String> children, Equality equality); @Override void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options, IteratorEnvironment env); @Override boolean hasTop(); @Override void next(); @Override void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive); @Override Key getTopKey(); @Override Value getTopValue(); @Override SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env); }### Answer:
@Test(expected = IllegalStateException.class) public void testUninitializedgetTopKey() { iterator.getTopKey(); } |
### Question:
AncestorChildExpansionIterator implements SortedKeyValueIterator<Key,Value> { @Override public Value getTopValue() { if (!seeked) { throw new IllegalStateException("cannot getTopKey(), iterator has not been seeked"); } if (topValue == null) { throw new NoSuchElementException("top value does not exist"); } return topValue; } AncestorChildExpansionIterator(SortedKeyValueIterator<Key,Value> iterator, List<String> children, Equality equality); @Override void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options, IteratorEnvironment env); @Override boolean hasTop(); @Override void next(); @Override void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive); @Override Key getTopKey(); @Override Value getTopValue(); @Override SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env); }### Answer:
@Test(expected = IllegalStateException.class) public void testUninitializedgetTopValue() { iterator.getTopValue(); } |
### Question:
AncestorChildExpansionIterator implements SortedKeyValueIterator<Key,Value> { @Override public void next() throws IOException { if (!seeked) { throw new IllegalStateException("cannot next(), iterator has not been seeked"); } if (initialized && topKey == null) { throw new NoSuchElementException("cannot next(), iterator is empty"); } nextChild(); } AncestorChildExpansionIterator(SortedKeyValueIterator<Key,Value> iterator, List<String> children, Equality equality); @Override void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options, IteratorEnvironment env); @Override boolean hasTop(); @Override void next(); @Override void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive); @Override Key getTopKey(); @Override Value getTopValue(); @Override SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env); }### Answer:
@Test(expected = IllegalStateException.class) public void testUninitializedNext() throws IOException { iterator.next(); } |
### Question:
TupleToRange implements Function<Tuple2<String,IndexInfo>,Iterator<QueryPlan>> { public static boolean isDocumentRange(IndexInfo indexInfo) { return !indexInfo.uids().isEmpty(); } TupleToRange(JexlNode currentNode, ShardQueryConfiguration config); Iterator<QueryPlan> apply(Tuple2<String,IndexInfo> tuple); static boolean isDocumentRange(IndexInfo indexInfo); static boolean isShardRange(String shard); static Iterator<QueryPlan> createDocumentRanges(JexlNode queryNode, String shard, IndexInfo indexMatches, boolean isTldQuery); static Iterator<QueryPlan> createShardRange(JexlNode queryNode, String shard, IndexInfo indexInfo); static Iterator<QueryPlan> createDayRange(JexlNode queryNode, String shard, IndexInfo indexInfo); }### Answer:
@Test public void testIsDocumentRange() { Set<String> docIds = Sets.newHashSet("docId0", "docId1", "docId2"); IndexInfo indexInfo = new IndexInfo(docIds); assertTrue(TupleToRange.isDocumentRange(indexInfo)); IndexInfo otherInfo = new IndexInfo(3L); assertFalse(TupleToRange.isDocumentRange(otherInfo)); } |
### Question:
TupleToRange implements Function<Tuple2<String,IndexInfo>,Iterator<QueryPlan>> { public static boolean isShardRange(String shard) { return shard.indexOf('_') >= 0; } TupleToRange(JexlNode currentNode, ShardQueryConfiguration config); Iterator<QueryPlan> apply(Tuple2<String,IndexInfo> tuple); static boolean isDocumentRange(IndexInfo indexInfo); static boolean isShardRange(String shard); static Iterator<QueryPlan> createDocumentRanges(JexlNode queryNode, String shard, IndexInfo indexMatches, boolean isTldQuery); static Iterator<QueryPlan> createShardRange(JexlNode queryNode, String shard, IndexInfo indexInfo); static Iterator<QueryPlan> createDayRange(JexlNode queryNode, String shard, IndexInfo indexInfo); }### Answer:
@Test public void testIsShardRange() { String shardRange = "20190314_0"; String dayRange = "20190314"; assertTrue(TupleToRange.isShardRange(shardRange)); assertFalse(TupleToRange.isShardRange(dayRange)); } |
### Question:
MetadataTableConfigHelper extends AbstractTableConfigHelper { @Override public void configure(TableOperations tops) throws AccumuloException, AccumuloSecurityException, TableNotFoundException { if (tableName != null) { for (IteratorScope scope : IteratorScope.values()) { setFrequencyCombiner(tops, scope.name()); setCombinerForCountMetadata(tops, scope.name()); setCombinerForEdgeMetadata(tops, scope.name()); } } } @Override void configure(TableOperations tops); @Override void setup(String tableName, Configuration config, Logger log); }### Answer:
@Test public void testConfigureCalledBeforeSetup() throws AccumuloSecurityException, AccumuloException, TableNotFoundException { MetadataTableConfigHelperTest.logger.info("MetadataTableConfigHelperTest.testConfigureCalledBeforeSetup called."); try { WrappedMetadataTableConfigHelper uut = new WrappedMetadataTableConfigHelper(); TableOperations tops = mockUpTableOperations(); uut.configure(tops); Assert.assertTrue("MetadataTableConfigHelper.configure incorrectly populated the Table Properties.", this.tableProperties.isEmpty()); } finally { MetadataTableConfigHelperTest.logger.info("MetadataTableConfigHelperTest.testConfigureCalledBeforeSetup completed."); } } |
### Question:
TupleToRange implements Function<Tuple2<String,IndexInfo>,Iterator<QueryPlan>> { public static Iterator<QueryPlan> createShardRange(JexlNode queryNode, String shard, IndexInfo indexInfo) { JexlNode myNode = queryNode; if (indexInfo.getNode() != null) { myNode = indexInfo.getNode(); } Range range = RangeFactory.createShardRange(shard); if (log.isTraceEnabled() && null != myNode) { log.trace("Building shard " + range + " From " + JexlStringBuildingVisitor.buildQuery(myNode)); } return Collections.singleton(new QueryPlan(myNode, range)).iterator(); } TupleToRange(JexlNode currentNode, ShardQueryConfiguration config); Iterator<QueryPlan> apply(Tuple2<String,IndexInfo> tuple); static boolean isDocumentRange(IndexInfo indexInfo); static boolean isShardRange(String shard); static Iterator<QueryPlan> createDocumentRanges(JexlNode queryNode, String shard, IndexInfo indexMatches, boolean isTldQuery); static Iterator<QueryPlan> createShardRange(JexlNode queryNode, String shard, IndexInfo indexInfo); static Iterator<QueryPlan> createDayRange(JexlNode queryNode, String shard, IndexInfo indexInfo); }### Answer:
@Test public void testGenerateShardRange() { String shard = "20190314_0"; IndexInfo indexInfo = new IndexInfo(-1); indexInfo.applyNode(queryNode); List<Range> expectedRanges = new ArrayList<>(1); expectedRanges.add(makeShardedRange(shard)); Iterator<QueryPlan> ranges = TupleToRange.createShardRange(queryNode, shard, indexInfo); eval(expectedRanges, ranges); } |
### Question:
TupleToRange implements Function<Tuple2<String,IndexInfo>,Iterator<QueryPlan>> { public static Iterator<QueryPlan> createDayRange(JexlNode queryNode, String shard, IndexInfo indexInfo) { JexlNode myNode = queryNode; if (indexInfo.getNode() != null) { myNode = indexInfo.getNode(); } Range range = RangeFactory.createDayRange(shard); if (log.isTraceEnabled()) log.trace("Building day" + range + " from " + (null == myNode ? "NoQueryNode" : JexlStringBuildingVisitor.buildQuery(myNode))); return Collections.singleton(new QueryPlan(myNode, range)).iterator(); } TupleToRange(JexlNode currentNode, ShardQueryConfiguration config); Iterator<QueryPlan> apply(Tuple2<String,IndexInfo> tuple); static boolean isDocumentRange(IndexInfo indexInfo); static boolean isShardRange(String shard); static Iterator<QueryPlan> createDocumentRanges(JexlNode queryNode, String shard, IndexInfo indexMatches, boolean isTldQuery); static Iterator<QueryPlan> createShardRange(JexlNode queryNode, String shard, IndexInfo indexInfo); static Iterator<QueryPlan> createDayRange(JexlNode queryNode, String shard, IndexInfo indexInfo); }### Answer:
@Test public void testGenerateDayRange() { String shard = "20190314"; IndexInfo indexInfo = new IndexInfo(-1); indexInfo.applyNode(queryNode); List<Range> expectedRanges = new ArrayList<>(1); expectedRanges.add(makeDayRange(shard)); Iterator<QueryPlan> ranges = TupleToRange.createDayRange(queryNode, shard, indexInfo); eval(expectedRanges, ranges); } |
### Question:
Intersection implements IndexStream { @Override public boolean hasNext() { return next != null; } Intersection(Iterable<? extends IndexStream> children, UidIntersector uidIntersector); @Override boolean hasNext(); @Override Tuple2<String,IndexInfo> next(); @Override Tuple2<String,IndexInfo> peek(); @Override void remove(); static Builder builder(); @Override StreamContext context(); @Override String getContextDebug(); @Override String toString(); @Override JexlNode currentNode(); }### Answer:
@Test public void testIntersection_DifferentShardStreams() { List<IndexMatch> leftMatches = buildIndexMatches("FIELD", "VALUE", "doc1", "doc2", "doc3"); IndexInfo left = new IndexInfo(leftMatches); left.setNode(JexlNodeFactory.buildEQNode("FIELD", "VALUE")); Tuple2<String,IndexInfo> leftTuple = Tuples.tuple("20190314_0", left); PeekingIterator<Tuple2<String,IndexInfo>> leftIter = Iterators.peekingIterator(Collections.singleton(leftTuple).iterator()); List<IndexMatch> rightMatches = buildIndexMatches("FIELD", "VALUE", "doc2", "doc3", "doc4"); IndexInfo right = new IndexInfo(rightMatches); right.setNode(JexlNodeFactory.buildEQNode("FIELD", "VALUE")); Tuple2<String,IndexInfo> rightTuple = Tuples.tuple("20190314_1", right); PeekingIterator<Tuple2<String,IndexInfo>> rightIter = Iterators.peekingIterator(Collections.singleton(rightTuple).iterator()); IndexStream leftStream = ScannerStream.withData(leftIter, JexlNodeFactory.buildEQNode("FIELD", "VALUE")); IndexStream rightStream = ScannerStream.withData(rightIter, JexlNodeFactory.buildEQNode("FIELD", "VALUE")); List<IndexStream> indexStreams = Lists.newArrayList(leftStream, rightStream); Intersection intersection = new Intersection(indexStreams, new IndexInfo()); assertFalse(intersection.hasNext()); } |
### Question:
Intersection implements IndexStream { @Override public StreamContext context() { return context; } Intersection(Iterable<? extends IndexStream> children, UidIntersector uidIntersector); @Override boolean hasNext(); @Override Tuple2<String,IndexInfo> next(); @Override Tuple2<String,IndexInfo> peek(); @Override void remove(); static Builder builder(); @Override StreamContext context(); @Override String getContextDebug(); @Override String toString(); @Override JexlNode currentNode(); }### Answer:
@Test public void testIntersection_EmptyExceededValueThreshold() throws ParseException { ASTJexlScript script = JexlASTHelper.parseJexlQuery("THIS_FIELD == 20"); ScannerStream scannerStream = ScannerStream.exceededValueThreshold(Collections.emptyIterator(), script); List<? extends IndexStream> iterable = Collections.singletonList(scannerStream); Intersection intersection = new Intersection(iterable, null); assertEquals(IndexStream.StreamContext.ABSENT, intersection.context()); } |
### Question:
IndexMatch implements WritableComparable<IndexMatch> { public void add(JexlNode node) { nodeSet.add(node); } IndexMatch(final String uid); protected IndexMatch(); IndexMatch(final String uid, final JexlNode myNode); IndexMatch(final String uid, final JexlNode myNode, final String shard); IndexMatch(final String uid, final JexlNode myNode, final IndexMatchType type); IndexMatch(Set<JexlNode> nodes, String uid, final IndexMatchType type); String getUid(); JexlNode getNode(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(IndexMatch other); void setType(IndexMatchType type); void set(JexlNode node); void add(JexlNode node); @Override String toString(); @Override void readFields(DataInput in); @Override void write(DataOutput out); }### Answer:
@Test public void testSetOfIndexMatches() { JexlNode node = JexlNodeFactory.buildEQNode("FOO", "bar"); JexlNode otherNode = JexlNodeFactory.buildEQNode("FOO2", "bar2"); IndexMatch match1 = new IndexMatch("uid0"); IndexMatch match2 = new IndexMatch("uid0"); match1.add(node); match2.add(otherNode); Set<IndexMatch> matchSet = new HashSet<>(); matchSet.add(match1); matchSet.add(match2); assertEquals(2, matchSet.size()); Iterator<IndexMatch> matchIter = matchSet.iterator(); assertEquals(Collections.singleton("FOO == 'bar'"), matchIter.next().nodeSet.getNodeKeys()); assertEquals(Collections.singleton("FOO2 == 'bar2'"), matchIter.next().nodeSet.getNodeKeys()); } |
### Question:
IndexMatch implements WritableComparable<IndexMatch> { public String getUid() { return uid; } IndexMatch(final String uid); protected IndexMatch(); IndexMatch(final String uid, final JexlNode myNode); IndexMatch(final String uid, final JexlNode myNode, final String shard); IndexMatch(final String uid, final JexlNode myNode, final IndexMatchType type); IndexMatch(Set<JexlNode> nodes, String uid, final IndexMatchType type); String getUid(); JexlNode getNode(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(IndexMatch other); void setType(IndexMatchType type); void set(JexlNode node); void add(JexlNode node); @Override String toString(); @Override void readFields(DataInput in); @Override void write(DataOutput out); }### Answer:
@Test public void testUidConstructor() { String uid = "uid"; IndexMatch indexMatch = new IndexMatch(uid); assertEquals(uid, indexMatch.getUid()); assertEquals(uid, indexMatch.uid); } |
### Question:
IndexMatch implements WritableComparable<IndexMatch> { public void setType(IndexMatchType type) { this.type = type; } IndexMatch(final String uid); protected IndexMatch(); IndexMatch(final String uid, final JexlNode myNode); IndexMatch(final String uid, final JexlNode myNode, final String shard); IndexMatch(final String uid, final JexlNode myNode, final IndexMatchType type); IndexMatch(Set<JexlNode> nodes, String uid, final IndexMatchType type); String getUid(); JexlNode getNode(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(IndexMatch other); void setType(IndexMatchType type); void set(JexlNode node); void add(JexlNode node); @Override String toString(); @Override void readFields(DataInput in); @Override void write(DataOutput out); }### Answer:
@Test public void testTypeSet() { String uid = "uid"; JexlNode eqNode = JexlNodeFactory.buildEQNode("FIELD", "value"); IndexMatch indexMatch = new IndexMatch(uid, eqNode); assertEquals(IndexMatchType.OR, indexMatch.type); indexMatch.setType(IndexMatchType.AND); assertEquals(IndexMatchType.AND, indexMatch.type); } |
### Question:
IndexMatch implements WritableComparable<IndexMatch> { @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(uid + " - {"); for (String nodeKey : nodeSet.getNodeKeys()) { builder.append(nodeKey).append(" "); } builder.append("}"); return builder.toString(); } IndexMatch(final String uid); protected IndexMatch(); IndexMatch(final String uid, final JexlNode myNode); IndexMatch(final String uid, final JexlNode myNode, final String shard); IndexMatch(final String uid, final JexlNode myNode, final IndexMatchType type); IndexMatch(Set<JexlNode> nodes, String uid, final IndexMatchType type); String getUid(); JexlNode getNode(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(IndexMatch other); void setType(IndexMatchType type); void set(JexlNode node); void add(JexlNode node); @Override String toString(); @Override void readFields(DataInput in); @Override void write(DataOutput out); }### Answer:
@Test public void testToString() { String uid = "uid"; JexlNode eqNode = JexlNodeFactory.buildEQNode("FIELD", "value"); IndexMatch indexMatch = new IndexMatch(uid, eqNode); String expectedString = "uid - {FIELD == 'value' }"; assertEquals(expectedString, indexMatch.toString()); } |
### Question:
IndexMatch implements WritableComparable<IndexMatch> { @Override public boolean equals(Object obj) { if (null == obj) return false; if (obj instanceof IndexMatch) { IndexMatch other = (IndexMatch) obj; if (!uid.equals(other.uid)) return false; return nodeSet.equals(other.nodeSet); } return false; } IndexMatch(final String uid); protected IndexMatch(); IndexMatch(final String uid, final JexlNode myNode); IndexMatch(final String uid, final JexlNode myNode, final String shard); IndexMatch(final String uid, final JexlNode myNode, final IndexMatchType type); IndexMatch(Set<JexlNode> nodes, String uid, final IndexMatchType type); String getUid(); JexlNode getNode(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(IndexMatch other); void setType(IndexMatchType type); void set(JexlNode node); void add(JexlNode node); @Override String toString(); @Override void readFields(DataInput in); @Override void write(DataOutput out); }### Answer:
@Test public void testEquals() { IndexMatch left = new IndexMatch("uid0"); IndexMatch right = new IndexMatch("uid0"); assertEquals(left, right); assertEquals(right, left); assertNotEquals(left, null); } |
### Question:
IndexMatch implements WritableComparable<IndexMatch> { @Override public int hashCode() { return uid.hashCode(); } IndexMatch(final String uid); protected IndexMatch(); IndexMatch(final String uid, final JexlNode myNode); IndexMatch(final String uid, final JexlNode myNode, final String shard); IndexMatch(final String uid, final JexlNode myNode, final IndexMatchType type); IndexMatch(Set<JexlNode> nodes, String uid, final IndexMatchType type); String getUid(); JexlNode getNode(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(IndexMatch other); void setType(IndexMatchType type); void set(JexlNode node); void add(JexlNode node); @Override String toString(); @Override void readFields(DataInput in); @Override void write(DataOutput out); }### Answer:
@Test public void testHashCode() { String uid = "uid"; IndexMatch indexMatch = new IndexMatch(uid); assertEquals(uid.hashCode(), indexMatch.hashCode()); } |
### Question:
CreateUidsIterator implements SortedKeyValueIterator<Key,Value>, OptionDescriber { public static boolean sameShard(Key ref, Key test) { ByteSequence refCq = ref.getColumnQualifierData(); ByteSequence testCq = test.getColumnQualifierData(); if (testCq.length() < refCq.length()) { return false; } for (int i = 0; i < refCq.length(); ++i) { if (refCq.byteAt(i) != testCq.byteAt(i)) { return false; } } return testCq.byteAt(refCq.length()) == 0x00; } @Override void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options, IteratorEnvironment env); @Override boolean hasTop(); @Override void next(); @Override void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive); @Override Key getTopKey(); @Override Value getTopValue(); @Override SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env); IndexInfo getValue(); static boolean sameShard(Key ref, Key test); static Tuple3<Long,Boolean,List<String>> parseUids(Key k, Value v); static String parseDataType(Key k); static int lastNull(ByteSequence bs); static Key makeRootKey(Key k); @Override IteratorOptions describeOptions(); @Override boolean validateOptions(Map<String,String> options); static final String COLLAPSE_UIDS; static final String PARSE_TLD_UIDS; }### Answer:
@Test public void testShardEquals() { assertTrue(CreateUidsIterator.sameShard(new Key("row", "cf", "shard_1"), new Key("row2", "cf2", "shard_1\u0000fds"))); assertFalse(CreateUidsIterator.sameShard(new Key("row", "cf", "shard_1"), new Key("row2", "cf2", "shard_2\u0000fds"))); } |
### Question:
CreateUidsIterator implements SortedKeyValueIterator<Key,Value>, OptionDescriber { public static String parseDataType(Key k) { ByteSequence colq = k.getColumnQualifierData(); return new String(colq.subSequence(lastNull(colq) + 1, colq.length()).toArray()); } @Override void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options, IteratorEnvironment env); @Override boolean hasTop(); @Override void next(); @Override void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive); @Override Key getTopKey(); @Override Value getTopValue(); @Override SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env); IndexInfo getValue(); static boolean sameShard(Key ref, Key test); static Tuple3<Long,Boolean,List<String>> parseUids(Key k, Value v); static String parseDataType(Key k); static int lastNull(ByteSequence bs); static Key makeRootKey(Key k); @Override IteratorOptions describeOptions(); @Override boolean validateOptions(Map<String,String> options); static final String COLLAPSE_UIDS; static final String PARSE_TLD_UIDS; }### Answer:
@Test public void testParseDataType() { assertEquals("datatype", CreateUidsIterator.parseDataType(new Key("row", "cf", "shard_1\u0000datatype"))); } |
### Question:
CreateUidsIterator implements SortedKeyValueIterator<Key,Value>, OptionDescriber { public static int lastNull(ByteSequence bs) { int pos = bs.length(); while (--pos > 0 && bs.byteAt(pos) != 0x00) ; return pos; } @Override void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options, IteratorEnvironment env); @Override boolean hasTop(); @Override void next(); @Override void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive); @Override Key getTopKey(); @Override Value getTopValue(); @Override SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env); IndexInfo getValue(); static boolean sameShard(Key ref, Key test); static Tuple3<Long,Boolean,List<String>> parseUids(Key k, Value v); static String parseDataType(Key k); static int lastNull(ByteSequence bs); static Key makeRootKey(Key k); @Override IteratorOptions describeOptions(); @Override boolean validateOptions(Map<String,String> options); static final String COLLAPSE_UIDS; static final String PARSE_TLD_UIDS; }### Answer:
@Test public void testLastNull() { ArrayByteSequence bs = new ArrayByteSequence("shard_1\u0000datatype".getBytes(Charset.forName("UTF-8"))); assertEquals("shard_1".length(), CreateUidsIterator.lastNull(bs)); } |
### Question:
CreateUidsIterator implements SortedKeyValueIterator<Key,Value>, OptionDescriber { public static Key makeRootKey(Key k) { ByteSequence cq = k.getColumnQualifierData(); ByteSequence strippedCq = cq.subSequence(0, lastNull(cq)); final ByteSequence row = k.getRowData(), cf = k.getColumnFamilyData(), cv = k.getColumnVisibilityData(); return new Key(row.getBackingArray(), row.offset(), row.length(), cf.getBackingArray(), cf.offset(), cf.length(), strippedCq.getBackingArray(), strippedCq.offset(), strippedCq.length(), cv.getBackingArray(), cv.offset(), cv.length(), k.getTimestamp()); } @Override void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options, IteratorEnvironment env); @Override boolean hasTop(); @Override void next(); @Override void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive); @Override Key getTopKey(); @Override Value getTopValue(); @Override SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env); IndexInfo getValue(); static boolean sameShard(Key ref, Key test); static Tuple3<Long,Boolean,List<String>> parseUids(Key k, Value v); static String parseDataType(Key k); static int lastNull(ByteSequence bs); static Key makeRootKey(Key k); @Override IteratorOptions describeOptions(); @Override boolean validateOptions(Map<String,String> options); static final String COLLAPSE_UIDS; static final String PARSE_TLD_UIDS; }### Answer:
@Test public void testMakeRootKey() { Key expectedRootKey = new Key("term", "field", "shard"); Key indexKey = new Key("term", "field", "shard\u0000datatype"); assertEquals(expectedRootKey, CreateUidsIterator.makeRootKey(indexKey)); } |
### Question:
SplitSelectorExtractor implements SelectorExtractor { @Override public List<String> extractSelectors(Query query) throws IllegalArgumentException { List<String> selectorList = new ArrayList<>(); String selectorSeparator = this.separatorCharacter; if (this.separatorParameter != null) { QueryImpl.Parameter parameter = query.findParameter(separatorParameter); if (parameter != null && parameter.getParameterValue() != null) { String value = parameter.getParameterValue(); if (StringUtils.isNotBlank(value) && value.length() == 1) { selectorSeparator = value; } } } String queryStr = query.getQuery(); if (selectorSeparator == null) { selectorList.add(query.getQuery()); } else { String[] querySplit = queryStr.split(selectorSeparator); for (int splitNumber = 0; splitNumber < querySplit.length; splitNumber++) { if (useSplitsList == null || useSplit(useSplitsList, splitNumber)) { String s = querySplit[splitNumber]; selectorList.add(s.trim()); } } } return selectorList; } @Override List<String> extractSelectors(Query query); void setSeparatorCharacter(String separatorCharacter); void setSeparatorParameter(String separatorParameter); void setUseSplits(String useSplits); List<IntRange> parseUseSplitsRanges(String useSplits); boolean useSplit(List<IntRange> useSplitList, int splitNumber); }### Answer:
@Test public void extractSelectorsLuceneQuery1() { SplitSelectorExtractor extractor = new SplitSelectorExtractor(); QueryImpl q = new QueryImpl(); q.setQuery("selector1"); List<String> selectorList = extractor.extractSelectors(q); List<String> expected = Lists.newArrayList("selector1"); Assert.assertEquals(expected, selectorList); } |
### Question:
SnowflakeUID extends UID { @SuppressWarnings("unchecked") public static SnowflakeUID parse(final String s) { return parse(s, -1); } protected SnowflakeUID(); protected SnowflakeUID(final BigInteger rawId, int radix, final String... extras); protected SnowflakeUID(final SnowflakeUID template, final String... extras); @SuppressWarnings({"unchecked", "rawtypes"}) static UIDBuilder<UID> builder(); @Override int compareTo(final UID uid); @Override boolean equals(final Object other); @Override int getTime(); @Override String getBaseUid(); int getMachineId(); int getNodeId(); int getProcessId(); int getRadix(); int getSequenceId(); @Override String getShardedPortion(); int getThreadId(); long getTimestamp(); @Override int hashCode(); @SuppressWarnings("unchecked") static SnowflakeUID parse(final String s); @SuppressWarnings("unchecked") static SnowflakeUID parse(final String s, int maxExtraParts); static SnowflakeUID parse(final String s, int radix, int maxExtraParts); @SuppressWarnings("unchecked") static SnowflakeUID parseBase(final String s); @Override void readFields(final DataInput in); @Override String toString(); String toString(int radix); static final int DEFAULT_RADIX; static final long MAX_TIMESTAMP; static final int MAX_NODE_ID; static final int MAX_PROCESS_ID; static final int MAX_THREAD_ID; static final int MAX_MACHINE_ID; static final int MAX_SEQUENCE_ID; }### Answer:
@Test public void testParse() { UID a = builder.newId(); UID b = UID.parse(a.toString()); assertEquals(a, b); assertEquals(b, a); assertEquals(0, a.compareTo(b)); assertEquals(0, a.compare(a, b)); a = builder.newId("blabla"); b = UID.parse(a.toString()); assertEquals(a, b); assertEquals(b, a); assertEquals(0, a.compareTo(b)); assertEquals(0, a.compare(a, b)); } |
### Question:
CardinalityAggregator extends PropogatingCombiner { @Override public void reset() { if (log.isDebugEnabled()) log.debug("Resetting CardinalityAggregator"); this.propogate = true; } @Override Value reduce(Key key, Iterator<Value> iter); @Override void reset(); static final Value EMPTY_VALUE; }### Answer:
@Test public void testResetPropagate() { agg.reset(); assertTrue(agg.propogateKey()); agg.setPropogate(false); assertFalse(agg.propogateKey()); agg.reset(); assertTrue(agg.propogateKey()); } |
### Question:
HashUID extends UID { public int getTime() { return time; } protected HashUID(); protected HashUID(final byte[] data, final Date time); protected HashUID(final byte[] data, final Date time, final String... extras); protected HashUID(final HashUID template, final String... extras); private HashUID(final String optionalPrefix, int h1, int h2, int time, final String... extras); private HashUID(final String optionalPrefix, int h1, int h2, int time); @SuppressWarnings({"unchecked", "rawtypes"}) static UIDBuilder<UID> builder(); @Override int compareTo(final UID uid); @Override boolean equals(Object other); String getBaseUid(); int getH0(); int getH1(); int getH2(); String getShardedPortion(); int getTime(); @Override int hashCode(); @SuppressWarnings({"unchecked", "rawtypes"}) static UIDBuilder<UID> newBuilder(final Date time); @SuppressWarnings("unchecked") static HashUID parse(String s); @SuppressWarnings("unchecked") static HashUID parse(String s, int maxExtraParts); @SuppressWarnings("unchecked") static HashUID parseBase(String s); void readFields(DataInput in); @Override String toString(); }### Answer:
@Test public void testMiscellaneous() { HashUIDBuilder builder = new HashUIDBuilder(); HashUID result1 = builder.newId((byte[]) null); assertNotNull(result1); HashUID result2 = HashUIDBuilder.newId((HashUID) null, (String) null); assertNull(result2); HashUID result3 = new HashUID(null); assertTrue(result3.getTime() < 0); } |
### Question:
TextUtil { public static void appendNullByte(Text text) { text.append(nullByte, 0, nullByte.length); } static void textAppend(Text text, String string); static void textAppend(Text text, String string, boolean replaceBadChar); static void textAppend(Text t, long s); static void appendNullByte(Text text); static void textAppendNoNull(Text t, String s); static void textAppendNoNull(Text t, String s, boolean replaceBadChar); static byte[] toUtf8(String string); static String fromUtf8(byte[] bytes); }### Answer:
@Test public void testAppendNullByte() { Text text = new Text(new byte[] {1, 2, 3}); TextUtil.appendNullByte(text); Assert.assertEquals(4, text.getLength()); Assert.assertEquals(0, text.getBytes()[3]); } |
### Question:
TextUtil { public static byte[] toUtf8(String string) { ByteBuffer buffer; try { buffer = Text.encode(string, false); } catch (CharacterCodingException cce) { throw new IllegalArgumentException(cce); } byte[] bytes = new byte[buffer.limit()]; System.arraycopy(buffer.array(), 0, bytes, 0, bytes.length); return bytes; } static void textAppend(Text text, String string); static void textAppend(Text text, String string, boolean replaceBadChar); static void textAppend(Text t, long s); static void appendNullByte(Text text); static void textAppendNoNull(Text t, String s); static void textAppendNoNull(Text t, String s, boolean replaceBadChar); static byte[] toUtf8(String string); static String fromUtf8(byte[] bytes); }### Answer:
@Test public void testToUtf8() throws UnsupportedEncodingException { String multiByteCharString = "\u007A\u6C34\uD834\uDD1E"; byte[] utf8 = TextUtil.toUtf8(multiByteCharString); Assert.assertArrayEquals(multiByteCharString.getBytes("UTF-8"), utf8); } |
### Question:
AccumuloArgs { public static Builder newBuilder() { return new Builder(); } String user(); String password(); String instance(); String zookeepers(); String table(); static AccumuloArgs defaults(); static Builder newBuilder(); }### Answer:
@Test public void testNewBuilder() { AccumuloArgs args = AccumuloArgs.newBuilder() .withDefaultTable("defaultTableName") .build(); String[] argv = { "-u", "Bob", "--password", "zekret", "-i", "instance", "-z", "localhost:2181", "-t", "testTable" }; JCommander.newBuilder() .addObject(args) .build() .parse(argv); assertThat(args.user(), is("Bob")); assertThat(args.password(), is("zekret")); assertThat(args.instance(), is("instance")); assertThat(args.zookeepers(), is("localhost:2181")); assertThat(args.table(), is("testTable")); } |
### Question:
FieldAgeOffFilter extends AppliedRule { public void init(FilterOptions options) { init(options, null); } @Override boolean accept(AgeOffPeriod period, Key k, Value v); void init(FilterOptions options); void init(FilterOptions options, IteratorEnvironment iterEnv); @Override boolean isFilterRuleApplied(); static final String OPTION_PREFIX; }### Answer:
@Test public void testIterEnvNotLostOnDeepCopy() { EditableAccumuloConfiguration conf = new EditableAccumuloConfiguration(AccumuloConfiguration.getDefaultConfiguration()); conf.put("table.custom.isindextable", "true"); iterEnv.setConf(conf); long tenSecondsAgo = System.currentTimeMillis() - (10L * ONE_SEC); FieldAgeOffFilter ageOffFilter = new FieldAgeOffFilter(); FilterOptions filterOptions = createFilterOptionsWithPattern(); filterOptions.setTTL(5L); filterOptions.setTTLUnits(AgeOffTtlUnits.SECONDS); filterOptions.setOption("fields", "field_y,field_z\\x00my-uuid"); filterOptions.setOption("field_z\\x00my-uuid.ttl", "2"); filterOptions.setOption("field_y.ttl", "2"); ageOffFilter.init(filterOptions, iterEnv); Assert.assertNotNull("IteratorEnvironment should not be null after init!", ageOffFilter.iterEnv); ageOffFilter = (FieldAgeOffFilter) ageOffFilter.deepCopy(tenSecondsAgo); Assert.assertNotNull("IteratorEnvironment should not be null after deep copy!", ageOffFilter.iterEnv); } |
### Question:
EdgeKeyDecoder { public static STATS_TYPE determineStatsType(Text colFam) { int offset = STATS_BYTES.length + 1; int secondSlashIndex = 0; int numCharsToCheck = Math.min(offset + 1 + STATS_TYPE.getMaxLength(), colFam.getLength()); for (int i = offset; i < numCharsToCheck; i++) { secondSlashIndex = i; if (colFam.getBytes()[i] == COL_SEPARATOR_BYTE) { break; } } int count = (secondSlashIndex > offset ? secondSlashIndex - offset : offset); try { return STATS_TYPE.getStatsType(Text.decode(colFam.getBytes(), offset, count)); } catch (CharacterCodingException e) { throw new RuntimeException("Edge key column encoding exception", e); } } EdgeKeyDecoder(); EdgeKey decode(Key key, EdgeKey.EdgeKeyBuilder builder); static EDGE_FORMAT determineEdgeFormat(Text colFam); static String getYYYYMMDD(Text colQual); static STATS_TYPE determineStatsType(Text colFam); }### Answer:
@Test public void extractsEachStatsType() { for (EdgeKey.STATS_TYPE statsType : EdgeKey.STATS_TYPE.values()) { Assert.assertEquals(statsType, EdgeKeyDecoder.determineStatsType(new Text("STATS/" + statsType.name() + "/CATEGORY"))); Assert.assertEquals(statsType, EdgeKeyDecoder.determineStatsType(new Text("STATS/" + statsType.name() + "/TYPE/RELATIONSHIP/CATEGORY/ATTRIBUTE2"))); Assert.assertEquals(statsType, EdgeKeyDecoder.determineStatsType(new Text("STATS/" + statsType.name() + "/TYPE/RELATIONSHIP/"))); Assert.assertEquals(statsType, EdgeKeyDecoder.determineStatsType(new Text("STATS/" + statsType.name() + "/TYPE/RELATIONSHIP/"))); } }
@Test(expected = EnumConstantNotPresentException.class) public void throwsExceptionForInvalidStatsType() { EdgeKeyDecoder.determineStatsType(new Text("STATS } |
### Question:
EdgeValueHelper { public static void fillHistogramGaps(List<Long> retLong, int desiredLength) { if (retLong.size() != desiredLength) { for (int ii = retLong.size(); ii < desiredLength; ii++) { retLong.add(0l); } } } private EdgeValueHelper(); static List<Long> decodeActivityHistogram(Value value); static List<Long> decodeActivityHistogram(List<Long> hoursList); static List<Long> decodeDurationHistogram(Value value); static List<Long> decodeDurationHistogram(List<Long> durations); static void fillHistogramGaps(List<Long> retLong, int desiredLength); static Long decodeLinkCount(final Value value); static List<Long> getVarLongList(byte[] bytes); static Value encodeActivityHistogram(List<Long> longs); static Value encodeDurationHistogram(List<Long> longs); static List<Long> getLongListForHour(int hour, boolean delete); static byte[] getByteArrayForHour(int hour, boolean delete); static List<Long> getLongListForDuration(int elapsed, boolean deleteRecord); static byte[] getByteArrayForDuration(int elapsed, boolean deleteRecord); static List<Long> initUnitList(int len, int index, boolean delete); static void combineHistogram(List<Long> sourceList, List<Long> combinedList); static final int ACTIVITY_HISTOGRAM_LENGTH; static final int DURATION_HISTOGRAM_LENGTH; }### Answer:
@Test public void testFillHistogramToExactSize() { List<Long> incompleteList = createIncompleteHistogram(); assertEquals(3, incompleteList.size()); EdgeValueHelper.fillHistogramGaps(incompleteList, EdgeValueHelper.DURATION_HISTOGRAM_LENGTH); assertEquals(EdgeValueHelper.DURATION_HISTOGRAM_LENGTH, incompleteList.size()); EdgeValueHelper.fillHistogramGaps(incompleteList, EdgeValueHelper.ACTIVITY_HISTOGRAM_LENGTH); assertEquals(EdgeValueHelper.ACTIVITY_HISTOGRAM_LENGTH, incompleteList.size()); } |
### Question:
EdgeKey { public static EdgeKeyBuilder newBuilder() { return new EdgeKeyBuilder(); } private EdgeKey(EDGE_FORMAT format, STATS_TYPE statsType, String sourceData, String sinkData, String family, String sourceRelationship,
String sinkRelationship, String sourceAttribute1, String sinkAttribute1, String yyyymmdd, String attribute3, String attribute2,
Text colvis, long timestamp, boolean deleted, DATE_TYPE dateType); static EdgeKeyBuilder newBuilder(); static EdgeKeyBuilder newBuilder(EdgeKey edgeKey); static EdgeKeyBuilder newBuilder(EdgeKey.EDGE_FORMAT format); static EdgeKey swapSourceSink(EdgeKey swap); static EdgeKey decode(Key key); static EdgeKey decodeForInternal(Key key); Key encode(); Key encodeLegacyProtobufKey(); Key encodeLegacyAttribute2Key(); Key encodeLegacyKey(); Key getMetadataKey(); static Key getMetadataKey(Key key); EDGE_FORMAT getFormat(); STATS_TYPE getStatsType(); String getSourceData(); String getSinkData(); String getType(); String getRelationship(); String getSourceRelationship(); String getSinkRelationship(); String getAttribute1(); String getSourceAttribute1(); String getSinkAttribute1(); boolean hasAttribute2(); String getAttribute2(); boolean hasAttribute3(); String getAttribute3(); String getYyyymmdd(); DATE_TYPE getDateType(); Text getColvis(); long getTimestamp(); boolean isDeleted(); boolean isStatsKey(); @Override int hashCode(); @Override boolean equals(Object obj); static DATE_TYPE getDateType(Key key); static final char COL_SEPARATOR; static final String COL_SEPARATOR_STR; static final byte COL_SEPARATOR_BYTE; static final char COL_SUB_SEPARATOR; }### Answer:
@Test public void testNewBuilder() { verifyEdgeKey(refBuilder.build()); }
@Test public void testClearFields() { EdgeKeyBuilder anotherBuilder = EdgeKey.newBuilder(); assertNotEquals(refBuilder, anotherBuilder); refBuilder.clearFields(); anotherBuilder.clearFields(); assertEquals(refBuilder, anotherBuilder); } |
### Question:
EdgeKey { public static EdgeKey decode(Key key) { return decode(key, EdgeKey.newBuilder().unescape()); } private EdgeKey(EDGE_FORMAT format, STATS_TYPE statsType, String sourceData, String sinkData, String family, String sourceRelationship,
String sinkRelationship, String sourceAttribute1, String sinkAttribute1, String yyyymmdd, String attribute3, String attribute2,
Text colvis, long timestamp, boolean deleted, DATE_TYPE dateType); static EdgeKeyBuilder newBuilder(); static EdgeKeyBuilder newBuilder(EdgeKey edgeKey); static EdgeKeyBuilder newBuilder(EdgeKey.EDGE_FORMAT format); static EdgeKey swapSourceSink(EdgeKey swap); static EdgeKey decode(Key key); static EdgeKey decodeForInternal(Key key); Key encode(); Key encodeLegacyProtobufKey(); Key encodeLegacyAttribute2Key(); Key encodeLegacyKey(); Key getMetadataKey(); static Key getMetadataKey(Key key); EDGE_FORMAT getFormat(); STATS_TYPE getStatsType(); String getSourceData(); String getSinkData(); String getType(); String getRelationship(); String getSourceRelationship(); String getSinkRelationship(); String getAttribute1(); String getSourceAttribute1(); String getSinkAttribute1(); boolean hasAttribute2(); String getAttribute2(); boolean hasAttribute3(); String getAttribute3(); String getYyyymmdd(); DATE_TYPE getDateType(); Text getColvis(); long getTimestamp(); boolean isDeleted(); boolean isStatsKey(); @Override int hashCode(); @Override boolean equals(Object obj); static DATE_TYPE getDateType(Key key); static final char COL_SEPARATOR; static final String COL_SEPARATOR_STR; static final byte COL_SEPARATOR_BYTE; static final char COL_SUB_SEPARATOR; }### Answer:
@Test(expected = IllegalStateException.class) public void testBlankKey() { Key blankStats = new Key(new Text(""), refStatsBase.getColumnFamily(), refStatsBase.getColumnQualifier(), refStatsBase.getColumnVisibility()); EdgeKey.decode(blankStats); } |
### Question:
EdgeValue { public static EdgeValueBuilder newBuilder() { return new EdgeValueBuilder(); } private EdgeValue(Long count, Integer bitmask, String sourceValue, String sinkValue); private EdgeValue(Long count, Integer bitmask, String sourceValue, String sinkValue, List<Long> hours, List<Long> duration, String loadDate,
String uuidString, boolean hasOnlyUuidString, EdgeData.EdgeValue.UUID uuidObj, Boolean badActivityDate); static EdgeValueBuilder newBuilder(); static EdgeValueBuilder newBuilder(EdgeValue edgeValue); static EdgeValue decode(Value value); Value encode(); static EdgeData.EdgeValue.UUID convertUuidStringToUuidObj(String uuidString); Long getCount(); boolean hasCount(); Integer getBitmask(); boolean hasBitmask(); boolean hasLoadDate(); boolean isHourSet(int hour); String getSourceValue(); String getSinkValue(); List<Long> getHours(); List<Long> getDuration(); String getLoadDate(); EdgeData.EdgeValue.UUID getUuidObject(); String getUuid(); Boolean isBadActivityDate(); void setBadActivityDate(Boolean badActivityDate); boolean badActivityDateSet(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testNewBuilder() throws InvalidProtocolBufferException { EdgeValueBuilder builder = EdgeValue.newBuilder(); builder.setBitmask(1); builder.setCount(42l); EdgeValue eValue = builder.build(); Value value = eValue.encode(); EdgeValue outValue = EdgeValue.decode(value); assertTrue(outValue.hasCount()); assertTrue(outValue.hasBitmask()); assertEquals(42, (long) outValue.getCount()); assertEquals(1, (int) outValue.getBitmask()); builder = EdgeValue.newBuilder(eValue); EdgeValue outValue2 = EdgeValue.decode(builder.build().encode()); assertTrue(outValue2.hasCount()); assertTrue(outValue2.hasBitmask()); assertEquals(42, (long) outValue2.getCount()); assertEquals(1, (int) outValue2.getBitmask()); } |
### Question:
TermWeightPosition implements Comparable<TermWeightPosition> { public static int positionScoreToTermWeightScore(float positionScore) { return Math.round(Math.abs(positionScore * 10000000)); } TermWeightPosition(Builder builder); TermWeightPosition(TermWeightPosition other); TermWeightPosition clone(); static int positionScoreToTermWeightScore(float positionScore); static float termWeightScoreToPositionScore(int termWeightScore); @Override int compareTo(TermWeightPosition o); @Override String toString(); @Override boolean equals(Object o); boolean equals(TermWeightPosition o); int getOffset(); int getLowOffset(); int getPrevSkips(); int getScore(); boolean getZeroOffsetMatch(); static final int DEFAULT_OFFSET; static final int DEFAULT_PREV_SKIPS; static final int DEFAULT_SCORE; static final boolean DEFAULT_ZERO_OFFSET_MATCH; }### Answer:
@Test public void testPositionScoreToTermWeightScore() { Float positionScore = new Float(-.0552721); Integer twScore = TermWeightPosition.positionScoreToTermWeightScore(positionScore); Float result = TermWeightPosition.termWeightScoreToPositionScore(twScore); Assert.assertEquals(result + "!=" + positionScore, positionScore, result); } |
### Question:
StatsJob extends IngestJob { @Override protected Configuration parseArguments(String[] args, Configuration conf) throws ClassNotFoundException, URISyntaxException, IllegalArgumentException { Configuration parseConf = super.parseArguments(args, conf); this.outputMutations = false; this.useMapOnly = false; if (null != parseConf) { parseStatsOptions(args, parseConf); parseConf.setStrings(MultiRFileOutputFormatter.CONFIGURED_TABLE_NAMES, this.outputTableName); this.mapper = StatsHyperLogMapper.class; this.inputFormat = MultiRfileInputformat.class; } return parseConf; } static void main(String[] args); }### Answer:
@Test public void testParseArguments() throws Exception { Assume.assumeTrue(null != System.getenv("DATAWAVE_INGEST_HOME")); log.info("====== testParseArguments ====="); Map<String,Object> mapArgs = new HashMap<>(); mapArgs.put(StatsHyperLogMapper.STATS_MAPPER_INPUT_INTERVAL, 4); mapArgs.put(StatsHyperLogMapper.STATS_MAPPER_OUTPUT_INTERVAL, 8); mapArgs.put(StatsHyperLogMapper.STATS_MAPPER_LOG_LEVEL, "map-log"); mapArgs.put(StatsHyperLogReducer.STATS_REDUCER_VALUE_INTERVAL, 6); mapArgs.put(StatsHyperLogReducer.STATS_MIN_COUNT, 1); mapArgs.put(StatsHyperLogReducer.STATS_REDUCER_COUNTS, Boolean.FALSE); mapArgs.put(StatsHyperLogReducer.STATS_REDUCER_LOG_LEVEL, "red-log"); String[] args = new String[mapArgs.size()]; int n = 0; for (Map.Entry<String,Object> entry : mapArgs.entrySet()) { args[n++] = "-" + entry.getKey() + "=" + entry.getValue(); } args = addRequiredSettings(args); wrapper.parseArguments(args, mapArgs); } |
### Question:
AccumuloIndexAgeDisplay { public String logAgeSummary() { StringBuilder sb = new StringBuilder(); for (int ii = buckets.length - 1; ii >= 0; --ii) { sb.append(String.format("\nIndexes older than %1$-3d %2$-6s %3$10d", buckets[ii], "days:", dataBuckets[ii].size())); } sb.append("\n"); String summary = sb.toString(); log.info(summary); return (summary); } AccumuloIndexAgeDisplay(Instance instance, String tableName, String columns, String userName, PasswordToken password, Integer[] buckets); void setBuckets(Integer[] unsorted); Integer[] getBuckets(); void extractDataFromAccumulo(); String logAgeSummary(); void createAccumuloShellScript(String fileName); static void main(String[] args); }### Answer:
@Test public void assortedDataIntoDefaultBucketLogOutputTest() { loadAssortedData(); completeSetup(new Integer[0]); String expectedLogSummary = getAssortedSimulatedLogOutput(); String actualLogSummary = aiad.logAgeSummary(); Assert.assertEquals(expectedLogSummary, actualLogSummary); }
@Test public void oneHourOldDataIntoDefaultBucketLogOutputTest() { loadOneHourData(); completeSetup(new Integer[0]); String expectedLogSummary = getOneHourSimulatedLogOutput(); String actualLogSummary = aiad.logAgeSummary(); Assert.assertEquals(expectedLogSummary, actualLogSummary); }
@Test public void assortedDataIntoThreeDayBucketLogOutputTest() { loadAssortedData(); completeSetup(new Integer[] {3}); String expectedLogSummary = getAssortedDataThreeDaySimulatedLogOutput(); String actualLogSummary = aiad.logAgeSummary(); Assert.assertEquals(expectedLogSummary, actualLogSummary); } |
### Question:
DataTypeConfigCompare { public CompareResult run(Configuration left, Configuration right) { SortedSet<String> same = new TreeSet<>(); SortedSet<String> diff = new TreeSet<>(); SortedSet<String> leftOnly = new TreeSet<>(); SortedSet<String> rightOnly = new TreeSet<>(); String leftPrefix = getPrefix(left); String rightPrefix = getPrefix(right); for (Map.Entry<String,String> entry : left) { ConfField field = new ConfField(leftPrefix, entry.getKey()); String leftValue = entry.getValue(); String rightValue = right.get(field.getField(rightPrefix)); if (nullSafeEquals(leftValue, rightValue)) { same.add(field.getField()); } else if (rightValue == null) { leftOnly.add(field.getField()); } else { diff.add(field.getField()); } } for (Map.Entry<String,String> entry : right) { ConfField field = new ConfField(rightPrefix, entry.getKey()); if (left.get(field.getField(leftPrefix)) == null) { rightOnly.add(field.getField()); } } return new CompareResult(same, diff, leftOnly, rightOnly); } CompareResult run(Configuration left, Configuration right); static final String PREFIX; }### Answer:
@Test public void shouldDetectSameSettings() { CompareResult result = compare.run(type1Conf, type2Conf); assertTrue(result.getSame().contains("file.input.format")); assertTrue(result.getSame().contains("handler.classes")); }
@Test public void shouldDetectDifferentSettings() { CompareResult result = compare.run(type1Conf, type2Conf); assertTrue(result.getDiff().contains("ingest.helper.class")); }
@Test public void shouldDetectLeftOnlySettings() { CompareResult result = compare.run(type1Conf, type2Conf); assertTrue(result.getLeftOnly().contains("only.type1.value")); }
@Test public void shouldDetectRightOnlySettings() { CompareResult result = compare.run(type1Conf, type2Conf); assertTrue(result.getRightOnly().contains("only.type2.value")); } |
### Question:
AtomKeyValueParser { public Entry toEntry(Abdera abdera, String host, String port) { String id = MessageFormat.format(ENTRY_ID_FORMAT, host, port, this.getCollectionName(), this.getId()); String link = MessageFormat.format(LINK_FORMAT, host, port, this.getUuid()); String title = MessageFormat.format(TITLE_FORMAT, this.getColumnVisibility(), this.getCollectionName(), this.getValue(), this.getUpdated()); Entry entry = abdera.newEntry(); IRI atomId = new IRI(id); entry.setId(atomId.toString()); entry.addLink(link, "alternate"); entry.setTitle(title); entry.setUpdated(this.getUpdated()); return entry; } String getCollectionName(); String getId(); Date getUpdated(); String getColumnVisibility(); String getUuid(); String getValue(); void setValue(String value); Entry toEntry(Abdera abdera, String host, String port); static AtomKeyValueParser parse(Key key, Value value); static String encodeId(String id); static String decodeId(String encodedId); }### Answer:
@Test public void testToEntry() { Abdera abdera = new Abdera(); String host = "hostForTests"; String port = "portForTests"; IRI iri = new IRI("https: Entry entry = kv.toEntry(abdera, host, port); Assert.assertEquals(iri, entry.getId()); Assert.assertEquals("(null) null with null @ null null", entry.getTitle()); Assert.assertNull(entry.getUpdated()); } |
### Question:
DatawaveRoleManager implements RoleManager { public Set<String> getRequiredRoles() { return requiredRoles; } DatawaveRoleManager(); DatawaveRoleManager(Collection<String> requiredRoles); @Override boolean canRunQuery(QueryLogic<?> queryLogic, Principal principal); Set<String> getRequiredRoles(); void setRequiredRoles(Set<String> requiredRoles); }### Answer:
@Test public void testBasicsLoadedConstructor() { drm = new DatawaveRoleManager(getFirstRole()); Set<String> gottenRoles = drm.getRequiredRoles(); Assert.assertTrue(gottenRoles.contains("REQ_ROLE_1")); Assert.assertFalse(gottenRoles.contains("REQ_ROLE_2")); } |
### Question:
DatawaveRoleManager implements RoleManager { @Override public boolean canRunQuery(QueryLogic<?> queryLogic, Principal principal) { if (principal instanceof DatawavePrincipal == false) return false; DatawavePrincipal datawavePrincipal = (DatawavePrincipal) principal; if (requiredRoles != null && !requiredRoles.isEmpty()) { Set<String> usersRoles = new HashSet<>(datawavePrincipal.getPrimaryUser().getRoles()); return usersRoles.containsAll(requiredRoles); } return true; } DatawaveRoleManager(); DatawaveRoleManager(Collection<String> requiredRoles); @Override boolean canRunQuery(QueryLogic<?> queryLogic, Principal principal); Set<String> getRequiredRoles(); void setRequiredRoles(Set<String> requiredRoles); }### Answer:
@Test public void testCanRunQuery() { drm = new DatawaveRoleManager(getFirstRole()); boolean canRun = drm.canRunQuery(null, null); Assert.assertFalse(canRun); p = datawavePrincipal; Assert.assertNotEquals(null, p); drm.setRequiredRoles(null); canRun = drm.canRunQuery(null, p); Assert.assertTrue(canRun); drm.setRequiredRoles(getFirstRole()); canRun = drm.canRunQuery(null, p); Assert.assertTrue(canRun); drm.setRequiredRoles(getAllRoles()); canRun = drm.canRunQuery(null, p); Assert.assertFalse(canRun); createAndSetWithTwoRoles(); p = datawavePrincipal; drm.setRequiredRoles(getFirstRole()); canRun = drm.canRunQuery(null, p); Assert.assertTrue(canRun); } |
### Question:
QueryCacheBean { @RolesAllowed({"Administrator", "JBossAdministrator"}) @JmxManaged public String listRunningQueries() { RunningQueries rq = getRunningQueries(); StringBuilder buf = new StringBuilder(); for (String query : rq.getQueries()) { buf.append(query).append("\n"); } return buf.toString(); } @RolesAllowed({"Administrator", "JBossAdministrator"}) @JmxManaged String listRunningQueries(); @GET @Path("/listRunningQueries") @Produces({"application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "text/html"}) @GZIP @RolesAllowed({"Administrator", "JBossAdministrator"}) RunningQueries getRunningQueries(); @RolesAllowed({"Administrator", "JBossAdministrator"}) @JmxManaged String cancelUserQuery(String id); }### Answer:
@SuppressWarnings({"rawtypes", "unchecked"}) @Test public void testListRunningQueries() throws Exception { expect(altCache.iterator()).andReturn((Iterator<RunningQuery>) new HashMap().values().iterator()); Map<String,Pair<QueryLogic<?>,Connector>> snapshot = new HashMap<>(); snapshot.put("key", this.pair); expect(this.remoteCache.snapshot()).andReturn(snapshot); expect(this.pair.getFirst()).andReturn((QueryLogic) this.logic); PowerMock.replayAll(); QueryCacheBean subject = new QueryCacheBean(); setInternalState(subject, QueryCache.class, altCache); setInternalState(subject, CreatedQueryLogicCacheBean.class, remoteCache); String result1 = subject.listRunningQueries(); PowerMock.verifyAll(); assertNotNull("List of running queries should not be null", result1); } |
### Question:
QueryCacheBean { @RolesAllowed({"Administrator", "JBossAdministrator"}) @JmxManaged public String cancelUserQuery(String id) throws Exception { AbstractRunningQuery arq = cache.get(id); if (arq != null) { try { @SuppressWarnings("unused") VoidResponse response = query.cancel(id); return "Success."; } catch (Exception e) { return "Failed, check log."; } } else { return "No such query: " + id; } } @RolesAllowed({"Administrator", "JBossAdministrator"}) @JmxManaged String listRunningQueries(); @GET @Path("/listRunningQueries") @Produces({"application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "text/html"}) @GZIP @RolesAllowed({"Administrator", "JBossAdministrator"}) RunningQueries getRunningQueries(); @RolesAllowed({"Administrator", "JBossAdministrator"}) @JmxManaged String cancelUserQuery(String id); }### Answer:
@Test public void testCancelUserQuery_CacheReturnsNonRunningQuery() throws Exception { UUID queryId = UUID.randomUUID(); expect(this.altCache.get(queryId.toString())).andReturn(PowerMock.createMock(RunningQuery.class)); PowerMock.replayAll(); QueryCacheBean subject = new QueryCacheBean(); setInternalState(subject, QueryCache.class, altCache); String result1 = subject.cancelUserQuery(queryId.toString()); PowerMock.verifyAll(); assertNotNull("List of running queries should not be null", result1); }
@Test public void testCancelUserQuery_HappyPath() throws Exception { UUID queryId = UUID.randomUUID(); expect(this.altCache.get(queryId.toString())).andReturn(this.query); PowerMock.replayAll(); QueryCacheBean subject = new QueryCacheBean(); setInternalState(subject, QueryCache.class, altCache); String result1 = subject.cancelUserQuery(queryId.toString()); PowerMock.verifyAll(); assertNotNull("List of running queries should not be null", result1); } |
### Question:
QueryCacheBean { @GET @Path("/listRunningQueries") @Produces({"application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "text/html"}) @GZIP @RolesAllowed({"Administrator", "JBossAdministrator"}) public RunningQueries getRunningQueries() { RunningQueries result = new RunningQueries(); for (RunningQuery value : cache) { result.getQueries().add(value.toString()); } for (Entry<String,Pair<QueryLogic<?>,Connector>> entry : qlCache.snapshot().entrySet()) { result.getQueries().add("Identifier: " + entry.getKey() + " Query Logic: " + entry.getValue().getFirst().getClass().getName() + "\n"); } return result; } @RolesAllowed({"Administrator", "JBossAdministrator"}) @JmxManaged String listRunningQueries(); @GET @Path("/listRunningQueries") @Produces({"application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "text/html"}) @GZIP @RolesAllowed({"Administrator", "JBossAdministrator"}) RunningQueries getRunningQueries(); @RolesAllowed({"Administrator", "JBossAdministrator"}) @JmxManaged String cancelUserQuery(String id); }### Answer:
@Test public void testGetRunningQueries() { RunningQueries output = bean.getRunningQueries(); assertEquals(expectedResult, output.getQueries().get(0)); } |
### Question:
MetadataCounterGroup { public void addToCount(long countDelta, String dataType, String rowId, String date) { String hashMapKey = createKey(dataType, rowId, date); CountAndKeyComponents value = counts.get(hashMapKey); if (null == value) { counts.put(hashMapKey, new CountAndKeyComponents(dataType, rowId, date, countDelta)); } else { value.incrementCount(countDelta); } } MetadataCounterGroup(String groupName, Text tableName); MetadataCounterGroup(Text counterIdentifier); void addToCount(long countDelta, String dataType, String rowId, String date); void clear(); Text getColumnFamily(); Collection<CountAndKeyComponents> getEntries(); }### Answer:
@Test public void testCountsDownCorrectly() { MetadataCounterGroup counters = new MetadataCounterGroup(COLUMN_FAMILY); counters.addToCount(-5, dataType, fieldName, date); counters.addToCount(-5, dataType, fieldName, date); assertOneEntryWithExpectedCount(counters, -10); }
@Test public void testCountsUpAndDownCorrectly() { MetadataCounterGroup counters = new MetadataCounterGroup(COLUMN_FAMILY); counters.addToCount(1, dataType, fieldName, date); counters.addToCount(1, dataType, fieldName, date); counters.addToCount(-1, dataType, fieldName, date); assertOneEntryWithExpectedCount(counters, 1); }
@Test public void testAssignments() { MetadataCounterGroup counters = new MetadataCounterGroup(COLUMN_FAMILY); counters.addToCount(1, dataType, fieldName, date); MetadataCounterGroup.CountAndKeyComponents entry = getOnlyEntry(counters); Assert.assertEquals(dataType, entry.getDataType()); Assert.assertEquals(fieldName, entry.getRowId()); Assert.assertEquals(date, entry.getDate()); } |
### Question:
DnUtils { public static String getUserDN(String[] dns) { return getUserDN(dns, false); } static String[] splitProxiedDNs(String proxiedDNs, boolean allowDups); static String[] splitProxiedSubjectIssuerDNs(String proxiedDNs); static String buildProxiedDN(String... dns); static Collection<String> buildNormalizedDNList(String subjectDN, String issuerDN, String proxiedSubjectDNs, String proxiedIssuerDNs); static String buildNormalizedProxyDN(String subjectDN, String issuerDN, String proxiedSubjectDNs, String proxiedIssuerDNs); static String getCommonName(String dn); static String[] getOrganizationalUnits(String dn); static String getShortName(String dn); static boolean isServerDN(String dn); static String getUserDN(String[] dns); static String getUserDN(String[] dns, boolean issuerDNs); static String[] getComponents(String dn, String componentName); static String normalizeDN(String userName); static final String PROPS_RESOURCE; static final String SUBJECT_DN_PATTERN_PROPERTY; }### Answer:
@Test public void testGetUserDnFromArray() { String userDnForTest = "snd1"; String[] array = new String[] {userDnForTest, "idn"}; String userDN = DnUtils.getUserDN(array); assertEquals(userDnForTest, userDN); }
@Test(expected = IllegalArgumentException.class) public void testTest() { String[] dns = new String[] {"sdn"}; DnUtils.getUserDN(dns, true); } |
### Question:
AuthorizationsUtil { public static Set<Authorizations> getDowngradedAuthorizations(String requestedAuths, Principal principal) { if (principal instanceof DatawavePrincipal) { return getDowngradedAuthorizations(requestedAuths, (DatawavePrincipal) principal); } else { return Collections.singleton(new Authorizations()); } } static Authorizations union(Iterable<byte[]> authorizations1, Iterable<byte[]> authorizations2); static Set<Authorizations> mergeAuthorizations(String requestedAuths, Collection<? extends Collection<String>> userAuths); static Set<Authorizations> getDowngradedAuthorizations(String requestedAuths, Principal principal); static LinkedHashSet<Authorizations> getDowngradedAuthorizations(String requestedAuths, DatawavePrincipal principal); static String downgradeUserAuths(Principal principal, String requested); static List<String> splitAuths(String requestedAuths); static Set<Authorizations> buildAuthorizations(Collection<? extends Collection<String>> userAuths); static String buildAuthorizationString(Collection<? extends Collection<String>> userAuths); static String buildUserAuthorizationString(Principal principal); static Collection<Authorizations> minimize(Collection<Authorizations> authorizations); static Collection<? extends Collection<String>> prepareAuthsForMerge(Authorizations authorizations); }### Answer:
@Test public void testDowngradeAuthorizations() { HashSet<Authorizations> expected = Sets.newHashSet(new Authorizations("A", "C"), new Authorizations("A", "B", "E"), new Authorizations("A", "F", "G")); assertEquals(expected, AuthorizationsUtil.getDowngradedAuthorizations(methodAuths, principal)); }
@Test public void testUserAuthsFirstInMergedSet() { HashSet<Authorizations> mergedAuths = AuthorizationsUtil.getDowngradedAuthorizations(methodAuths, principal); assertEquals(3, mergedAuths.size()); assertEquals("Merged user authorizations were not first in the return set", new Authorizations("A", "C"), mergedAuths.iterator().next()); } |
### Question:
AuthorizationsUtil { public static Authorizations union(Iterable<byte[]> authorizations1, Iterable<byte[]> authorizations2) { LinkedList<byte[]> aggregatedAuthorizations = Lists.newLinkedList(); addTo(aggregatedAuthorizations, authorizations1); addTo(aggregatedAuthorizations, authorizations2); return new Authorizations(aggregatedAuthorizations); } static Authorizations union(Iterable<byte[]> authorizations1, Iterable<byte[]> authorizations2); static Set<Authorizations> mergeAuthorizations(String requestedAuths, Collection<? extends Collection<String>> userAuths); static Set<Authorizations> getDowngradedAuthorizations(String requestedAuths, Principal principal); static LinkedHashSet<Authorizations> getDowngradedAuthorizations(String requestedAuths, DatawavePrincipal principal); static String downgradeUserAuths(Principal principal, String requested); static List<String> splitAuths(String requestedAuths); static Set<Authorizations> buildAuthorizations(Collection<? extends Collection<String>> userAuths); static String buildAuthorizationString(Collection<? extends Collection<String>> userAuths); static String buildUserAuthorizationString(Principal principal); static Collection<Authorizations> minimize(Collection<Authorizations> authorizations); static Collection<? extends Collection<String>> prepareAuthsForMerge(Authorizations authorizations); }### Answer:
@Test public void testUnionAuthorizations() { assertEquals(new Authorizations("A", "C"), AuthorizationsUtil.union(new Authorizations("A", "C"), new Authorizations("A"))); }
@Test public void testUnionWithEmptyAuthorizations() { assertEquals(new Authorizations("A", "C"), AuthorizationsUtil.union(new Authorizations("A", "C"), new Authorizations())); }
@Test public void testUnionWithBothEmptyAuthorizations() { assertEquals(new Authorizations(), AuthorizationsUtil.union(new Authorizations(), new Authorizations())); } |
### Question:
AuthorizationsUtil { public static String buildAuthorizationString(Collection<? extends Collection<String>> userAuths) { if (null == userAuths) { return ""; } HashSet<byte[]> b = new HashSet<>(); for (Collection<String> userAuth : userAuths) { for (String string : userAuth) { b.add(string.getBytes()); } } return new Authorizations(b).toString(); } static Authorizations union(Iterable<byte[]> authorizations1, Iterable<byte[]> authorizations2); static Set<Authorizations> mergeAuthorizations(String requestedAuths, Collection<? extends Collection<String>> userAuths); static Set<Authorizations> getDowngradedAuthorizations(String requestedAuths, Principal principal); static LinkedHashSet<Authorizations> getDowngradedAuthorizations(String requestedAuths, DatawavePrincipal principal); static String downgradeUserAuths(Principal principal, String requested); static List<String> splitAuths(String requestedAuths); static Set<Authorizations> buildAuthorizations(Collection<? extends Collection<String>> userAuths); static String buildAuthorizationString(Collection<? extends Collection<String>> userAuths); static String buildUserAuthorizationString(Principal principal); static Collection<Authorizations> minimize(Collection<Authorizations> authorizations); static Collection<? extends Collection<String>> prepareAuthsForMerge(Authorizations authorizations); }### Answer:
@Test public void testBuilidAuthorizationString() { Collection<Collection<String>> auths = new HashSet<>(); List<String> authsList = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "A", "E", "I", "J"); HashSet<String> uniqAuths = new HashSet<>(authsList); auths.add(authsList.subList(0, 4)); auths.add(authsList.subList(4, 8)); auths.add(authsList.subList(8, 12)); uniqAuths.removeAll(Arrays.asList(AuthorizationsUtil.buildAuthorizationString(auths).split(","))); assertTrue(uniqAuths.isEmpty()); } |
### Question:
AuthorizationsUtil { public static String buildUserAuthorizationString(Principal principal) { String auths = ""; if (principal != null && (principal instanceof DatawavePrincipal)) { DatawavePrincipal datawavePrincipal = (DatawavePrincipal) principal; auths = new Authorizations(datawavePrincipal.getPrimaryUser().getAuths().toArray(new String[0])).toString(); } return auths; } static Authorizations union(Iterable<byte[]> authorizations1, Iterable<byte[]> authorizations2); static Set<Authorizations> mergeAuthorizations(String requestedAuths, Collection<? extends Collection<String>> userAuths); static Set<Authorizations> getDowngradedAuthorizations(String requestedAuths, Principal principal); static LinkedHashSet<Authorizations> getDowngradedAuthorizations(String requestedAuths, DatawavePrincipal principal); static String downgradeUserAuths(Principal principal, String requested); static List<String> splitAuths(String requestedAuths); static Set<Authorizations> buildAuthorizations(Collection<? extends Collection<String>> userAuths); static String buildAuthorizationString(Collection<? extends Collection<String>> userAuths); static String buildUserAuthorizationString(Principal principal); static Collection<Authorizations> minimize(Collection<Authorizations> authorizations); static Collection<? extends Collection<String>> prepareAuthsForMerge(Authorizations authorizations); }### Answer:
@Test public void testBuildUserAuthorizationsString() { String expected = new Authorizations("A", "C", "D").toString(); assertEquals(expected, AuthorizationsUtil.buildUserAuthorizationString(principal)); } |
### Question:
DateFormatter implements ParamConverter<Date> { @Override public Date fromString(String s) { Date d; synchronized (DateFormatter.dateFormat) { String str = s; if (str.equals("+24Hours")) { d = new Date(new Date().getTime() + 86400000); log.debug("Param passed in was '+24Hours', setting value to now + 86400000ms"); } else { if (StringUtils.isNotBlank(this.defaultTime) && !str.contains(" ")) { str = str + " " + this.defaultTime; } if (StringUtils.isNotBlank(this.defaultMillisec) && !str.contains(".")) { str = str + "." + this.defaultMillisec; } try { d = DateFormatter.dateFormat.parse(str); if (DateUtils.getFragmentInMilliseconds(d, Calendar.HOUR_OF_DAY) > 0) { DateUtils.setMilliseconds(d, 999); } } catch (ParseException pe) { throw new RuntimeException("Unable to parse date " + str + " with format " + formatPattern, pe); } } } return d; } DateFormatter(DateFormat format); @Override Date fromString(String s); @Override String toString(Date value); static String getFormatPattern(); }### Answer:
@Test(expected = RuntimeException.class) public void testDateFormatterFail1() { formatter.fromString("20120101120000"); }
@Test(expected = RuntimeException.class) public void testDateFormatterFail2() { formatter.fromString("20120101 250000"); } |
### Question:
ExampleDataloader implements TGDatasetInterface { @Override public String getExtention() { return "example"; } @Override String getExtention(); @Override String getFilterString(); @Override String getType(File file); @Override boolean Validator(File file); @Override DatasetTimp loadFile(File file); @Override FlimImageAbstract loadFlimFile(File file); }### Answer:
@Test public void testGetExtention() { System.out.println("getExtention"); ExampleDataloader instance = new ExampleDataloader(); String expResult = "example"; String result = instance.getExtention(); assertEquals(expResult, result); } |
### Question:
ExampleDataloader implements TGDatasetInterface { @Override public String getFilterString() { return ".example (Example datafile)"; } @Override String getExtention(); @Override String getFilterString(); @Override String getType(File file); @Override boolean Validator(File file); @Override DatasetTimp loadFile(File file); @Override FlimImageAbstract loadFlimFile(File file); }### Answer:
@Test public void testGetFilterString() { System.out.println("getFilterString"); ExampleDataloader instance = new ExampleDataloader(); String expResult = ".example (Example datafile)"; String result = instance.getFilterString(); assertEquals(expResult, result); } |
### Question:
ExampleDataloader implements TGDatasetInterface { @Override public String getType(File file) throws FileNotFoundException { String loadedString; Scanner sc = new Scanner(file); try { sc.nextLine(); sc.nextLine(); loadedString = sc.nextLine(); if (loadedString.contains("\t")) { loadedString = loadedString.trim().replaceAll("\t", " "); } if (loadedString.trim().equalsIgnoreCase("Time explicit") | loadedString.trim().equalsIgnoreCase("Wavelength explicit")) { return "spec"; } else { return "error"; } } catch (Exception e) { return "error"; } } @Override String getExtention(); @Override String getFilterString(); @Override String getType(File file); @Override boolean Validator(File file); @Override DatasetTimp loadFile(File file); @Override FlimImageAbstract loadFlimFile(File file); }### Answer:
@Test public void testGetType() throws Exception { System.out.println("getType"); ExampleDataloader instance = new ExampleDataloader(); String expResult = "spec"; String result = instance.getType(testFile); assertEquals(expResult, result); } |
### Question:
ExampleDataloader implements TGDatasetInterface { @Override public boolean Validator(File file) throws FileNotFoundException, IOException, IllegalAccessException, InstantiationException { String ext = getFileExtension(file); if (ext.equalsIgnoreCase(getExtention())) { String loadedString; Scanner sc = new Scanner(file); if (sc.hasNextLine()) { sc.nextLine(); sc.nextLine(); loadedString = sc.nextLine(); if (loadedString.contains("\t")) { loadedString = loadedString.trim().replaceAll("\t", " "); } if (loadedString.trim().equalsIgnoreCase("Time explicit") | loadedString.trim().equalsIgnoreCase("Wavelength explicit") | loadedString.trim().equalsIgnoreCase("FLIM image")) { loadedString = sc.nextLine(); if (loadedString.trim().contains("NumberOfRecordsPerDatapoint")) { return true; } else { return false; } } else { return false; } } else { return false; } } else { return false; } } @Override String getExtention(); @Override String getFilterString(); @Override String getType(File file); @Override boolean Validator(File file); @Override DatasetTimp loadFile(File file); @Override FlimImageAbstract loadFlimFile(File file); }### Answer:
@Test public void testValidator() throws Exception { System.out.println("Validator"); ExampleDataloader instance = new ExampleDataloader(); boolean expResult = true; boolean result = instance.Validator(testFile); assertEquals(expResult, result); } |
### Question:
ExampleDataloader implements TGDatasetInterface { @Override public FlimImageAbstract loadFlimFile(File file) throws FileNotFoundException { throw new UnsupportedOperationException("Not supported yet."); } @Override String getExtention(); @Override String getFilterString(); @Override String getType(File file); @Override boolean Validator(File file); @Override DatasetTimp loadFile(File file); @Override FlimImageAbstract loadFlimFile(File file); }### Answer:
@Test public void testLoadFlimFile() throws Exception { System.out.println("loadFlimFile: not tested anymore"); assertTrue(true); } |
### Question:
BlockingClassLoader extends URLClassLoader { @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (!m_shared.matches(name, false)) { if (m_respectGrandparents) { try { return Class.forName(name, resolve, getParent().getParent()); } catch (ClassNotFoundException e) { } } if (m_blocked.matches(name, false)) { throw new ClassNotFoundException(); } if (m_isolated.matches(name, false)) { synchronized (this) { Class<?> c = findLoadedClass(name); if (c == null) { c = findClass(name); } if (resolve) { resolveClass(c); } return c; } } } return super.loadClass(name, resolve); } BlockingClassLoader(URLClassLoader parent,
List<URL> additionalClassPath,
Set<String> blocked,
Set<String> isolated,
Set<String> shared,
boolean respectGrandparents); BlockingClassLoader(List<URL> additionalClassPath,
Set<String> blocked,
Set<String> isolated,
Set<String> shared,
boolean respectGrandparents); BlockingClassLoader(Set<String> blocked,
Set<String> isolated,
Set<String> shared,
boolean respectGrandparents); @Override URL getResource(String name); @Override Enumeration<URL> getResources(String name); }### Answer:
@Test public void testWithLoadableClass() throws Exception { final BlockingClassLoader cl = new BlockingClassLoader(Collections.<String>emptySet(), singleton("net.grinder.*"), Collections.<String>emptySet(), false); final String name = "net.grinder.util.AnIsolatedClass"; final Class<?> c = cl.loadClass(name, true); assertSame(c, Class.forName(name, false, cl)); } |
### Question:
FileExtensionMatcher implements FileFilter { @Override public boolean accept(File pathname) { return pathname.getName().toLowerCase(Locale.ENGLISH).endsWith(m_extension); } FileExtensionMatcher(String extension); @Override boolean accept(File pathname); }### Answer:
@Test public void testFilter() { final FileFilter f = new FileExtensionMatcher(".aBc"); assertTrue(f.accept(new File("foo.abc"))); assertTrue(f.accept(new File(".abc"))); assertTrue(f.accept(new File(".aBC"))); assertFalse(f.accept(new File("fooabc"))); assertFalse(f.accept(new File("foo.abcblah"))); assertFalse(f.accept(new File(""))); assertFalse(f.accept(new File(".abc", "x"))); } |
### Question:
JVM { public boolean isAtLeastVersion(int minimumMajor, int minimumMinor) throws VersionException { final String version = System.getProperty("java.version"); final StringTokenizer versionTokenizer = new StringTokenizer(version, "."); try { final int major = Integer.parseInt(versionTokenizer.nextToken()); final int minor = Integer.parseInt(versionTokenizer.nextToken()); return major >= minimumMajor && minor >= minimumMinor; } catch (NoSuchElementException e) { throw new VersionException("Could not parse JVM version " + version); } catch (NumberFormatException e) { throw new VersionException("Could not parse JVM version " + version); } } private JVM(); static JVM getInstance(); boolean haveRequisites(Logger logger); boolean isAtLeastVersion(int minimumMajor, int minimumMinor); String toString(); }### Answer:
@Test public void testIsAtLeastVersion() throws Exception { final JVM jvm = JVM.getInstance(); assertTrue(jvm.isAtLeastVersion(1, 1)); assertTrue(jvm.isAtLeastVersion(1, 2)); assertTrue(jvm.isAtLeastVersion(1, 3)); assertFalse(jvm.isAtLeastVersion(3, 0)); assertFalse(jvm.isAtLeastVersion(1, 9)); final String[] badVersions = { "not parseable", "123123", "", }; final String oldVersion = System.getProperty("java.version"); try { for (int i = 0; i < badVersions.length; ++i) { System.setProperty("java.version", badVersions[i]); try { jvm.isAtLeastVersion(1, 3); fail("Expected JVM.VersionException"); } catch (JVM.VersionException e) { } } } finally { System.setProperty("java.version", oldVersion); } } |
### Question:
JVM { public boolean haveRequisites(Logger logger) throws VersionException { final String name = "The Grinder " + GrinderBuild.getVersionString(); if (!isAtLeastVersion(1, 6)) { logger.error("Fatal Error - incompatible version of Java ({})%n" + "{} requires at least Java SE 6.", this, name); return false; } return true; } private JVM(); static JVM getInstance(); boolean haveRequisites(Logger logger); boolean isAtLeastVersion(int minimumMajor, int minimumMinor); String toString(); }### Answer:
@Test public void testHaveRequisites() throws Exception { final Logger logger = mock(Logger.class); final JVM jvm = JVM.getInstance(); assertTrue(jvm.haveRequisites(logger)); verifyNoMoreInteractions(logger); final String oldVersion = System.getProperty("java.version"); try { System.setProperty("java.version", "1.2"); assertFalse(jvm.haveRequisites(logger)); verify(logger).error(contains("incompatible version"), same(jvm), isA(String.class)); } finally { System.setProperty("java.version", oldVersion); } } |
### Question:
JVM { public String toString() { return System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version") + ": " + System.getProperty("java.vm.name") + " (" + System.getProperty("java.vm.version") + ", " + System.getProperty("java.vm.info") + ") on " + System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version"); } private JVM(); static JVM getInstance(); boolean haveRequisites(Logger logger); boolean isAtLeastVersion(int minimumMajor, int minimumMinor); String toString(); }### Answer:
@Test public void testToString() throws Exception { final String result = JVM.getInstance().toString(); assertTrue(result.indexOf(System.getProperty("java.vm.version")) > 0); assertTrue(result.indexOf(System.getProperty("os.version")) > 0); } |
### Question:
Directory implements Serializable { public File getFile() { return m_directory; } Directory(); Directory(final File directory); static FileFilter getMatchAllFilesFilter(); void create(); File getFile(); File getFile(final File child); File[] listContents(final FileFilter filter); File[] listContents(final FileFilter filter,
final boolean includeDirectories,
final boolean absolutePaths); void deleteContents(); void delete(); File rebaseFromCWD(final File file); File relativeFile(final File file, final boolean mustBeChild); List<File> rebasePath(final String path); boolean isParentOf(final File file); void copyTo(final Directory target, final boolean incremental); String[] getWarnings(); @Override int hashCode(); @Override boolean equals(final Object o); }### Answer:
@Test public void testDefaultConstructor() throws Exception { final Directory directory = new Directory(); final File cwd = new File(System.getProperty("user.dir")); assertEquals(cwd.getCanonicalPath(), directory.getFile().getCanonicalPath()); } |
### Question:
Directory implements Serializable { @Override public int hashCode() { return getFile().hashCode(); } Directory(); Directory(final File directory); static FileFilter getMatchAllFilesFilter(); void create(); File getFile(); File getFile(final File child); File[] listContents(final FileFilter filter); File[] listContents(final FileFilter filter,
final boolean includeDirectories,
final boolean absolutePaths); void deleteContents(); void delete(); File rebaseFromCWD(final File file); File relativeFile(final File file, final boolean mustBeChild); List<File> rebasePath(final String path); boolean isParentOf(final File file); void copyTo(final Directory target, final boolean incremental); String[] getWarnings(); @Override int hashCode(); @Override boolean equals(final Object o); }### Answer:
@Test public void testEquality() throws Exception { final Directory d1 = new Directory(getDirectory()); final Directory d2 = new Directory(getDirectory()); final File f = new File(getDirectory(), "comeonpilgrimyouknowhelovesyou"); assertTrue(f.mkdir()); final Directory d3 = new Directory(f); assertEquals(d1, d1); assertEquals(d1, d2); AssertUtilities.assertNotEquals(d2, d3); assertEquals(d1.hashCode(), d1.hashCode()); assertEquals(d1.hashCode(), d2.hashCode()); AssertUtilities.assertNotEquals(d1, null); AssertUtilities.assertNotEquals(d1, f); } |
### Question:
Directory implements Serializable { public void deleteContents() throws DirectoryException { final File[] deleteList = listContents(s_matchAllFilesFilter, true, true); for (int i = deleteList.length - 1; i >= 0; --i) { if (deleteList[i].equals(getFile())) { continue; } if (!deleteList[i].delete()) { throw new DirectoryException( "Could not delete '" + deleteList[i] + "'"); } } } Directory(); Directory(final File directory); static FileFilter getMatchAllFilesFilter(); void create(); File getFile(); File getFile(final File child); File[] listContents(final FileFilter filter); File[] listContents(final FileFilter filter,
final boolean includeDirectories,
final boolean absolutePaths); void deleteContents(); void delete(); File rebaseFromCWD(final File file); File relativeFile(final File file, final boolean mustBeChild); List<File> rebasePath(final String path); boolean isParentOf(final File file); void copyTo(final Directory target, final boolean incremental); String[] getWarnings(); @Override int hashCode(); @Override boolean equals(final Object o); }### Answer:
@Test public void testDeleteContents() throws Exception { final Directory directory = new Directory(getDirectory()); final String[] files = { "directory/foo/bah/blah", "directory/blah", "a/b/c/d/e", "a/b/f/g/h", "a/b/f/g/i", "x", "y/z", "another", }; for (final String file2 : files) { final File file = new File(getDirectory(), file2); file.getParentFile().mkdirs(); assertTrue(file.createNewFile()); } assertTrue(getDirectory().list().length > 0); directory.deleteContents(); assertEquals(0, getDirectory().list().length); } |
### Question:
Directory implements Serializable { public void create() throws DirectoryException { if (!getFile().exists()) { if (!getFile().mkdirs()) { throw new DirectoryException( "Could not create directory '" + getFile() + "'"); } } } Directory(); Directory(final File directory); static FileFilter getMatchAllFilesFilter(); void create(); File getFile(); File getFile(final File child); File[] listContents(final FileFilter filter); File[] listContents(final FileFilter filter,
final boolean includeDirectories,
final boolean absolutePaths); void deleteContents(); void delete(); File rebaseFromCWD(final File file); File relativeFile(final File file, final boolean mustBeChild); List<File> rebasePath(final String path); boolean isParentOf(final File file); void copyTo(final Directory target, final boolean incremental); String[] getWarnings(); @Override int hashCode(); @Override boolean equals(final Object o); }### Answer:
@Test public void testCreate() throws Exception { final String[] directories = { "toplevel", "down/a/few", }; for (final String directorie : directories) { final Directory directory = new Directory(new File(getDirectory(), directorie)); assertFalse(directory.getFile().exists()); directory.create(); assertTrue(directory.getFile().exists()); } final File file = new File(getDirectory(), "readonly"); assertTrue(file.createNewFile()); FileUtilities.setCanAccess(file, false); try { new Directory(new File(getDirectory(), "readonly/foo")).create(); fail("Expected DirectoryException"); } catch (final Directory.DirectoryException e) { } } |
### Question:
Directory implements Serializable { public void delete() throws DirectoryException { if (!getFile().delete()) { throw new DirectoryException("Could not delete '" + getFile() + "'"); } } Directory(); Directory(final File directory); static FileFilter getMatchAllFilesFilter(); void create(); File getFile(); File getFile(final File child); File[] listContents(final FileFilter filter); File[] listContents(final FileFilter filter,
final boolean includeDirectories,
final boolean absolutePaths); void deleteContents(); void delete(); File rebaseFromCWD(final File file); File relativeFile(final File file, final boolean mustBeChild); List<File> rebasePath(final String path); boolean isParentOf(final File file); void copyTo(final Directory target, final boolean incremental); String[] getWarnings(); @Override int hashCode(); @Override boolean equals(final Object o); }### Answer:
@Test public void testDelete() throws Exception { final Directory directory1 = new Directory(new File(getDirectory(), "a/directory")); directory1.create(); assertTrue(directory1.getFile().exists()); directory1.delete(); assertFalse(directory1.getFile().exists()); final Directory directory2 = new Directory(new File(getDirectory(), "another")); directory2.create(); final File file2 = new File(getDirectory(), "another/file"); assertTrue(file2.createNewFile()); try { directory2.delete(); fail("Expected DirectoryException"); } catch (final Directory.DirectoryException e) { } } |
### Question:
HTTPPlugin implements GrinderPlugin { public PluginThreadListener createThreadListener( PluginThreadContext threadContext) throws PluginException { return new HTTPPluginThreadState(threadContext, m_sslContextFactory, m_slowClientSleeper, m_pluginProcessContext.getTimeAuthority()); } void initialize(PluginProcessContext processContext); PluginThreadListener createThreadListener(
PluginThreadContext threadContext); }### Answer:
@Test public void testCreateThreadListener() throws Exception { final HTTPPlugin plugin = new HTTPPlugin(); plugin.initialize(m_pluginProcessContext); assertSame(m_pluginProcessContext, plugin.getPluginProcessContext()); final PluginThreadContext pluginThreadContext = mock(PluginThreadContext.class); final PluginThreadListener threadListener = plugin.createThreadListener(pluginThreadContext); assertNotNull(threadListener); } |
### Question:
Directory implements Serializable { public boolean isParentOf(final File file) { final File thisFile = getFile(); File candidate = file.getParentFile(); while (candidate != null) { if (thisFile.equals(candidate)) { return true; } candidate = candidate.getParentFile(); } return false; } Directory(); Directory(final File directory); static FileFilter getMatchAllFilesFilter(); void create(); File getFile(); File getFile(final File child); File[] listContents(final FileFilter filter); File[] listContents(final FileFilter filter,
final boolean includeDirectories,
final boolean absolutePaths); void deleteContents(); void delete(); File rebaseFromCWD(final File file); File relativeFile(final File file, final boolean mustBeChild); List<File> rebasePath(final String path); boolean isParentOf(final File file); void copyTo(final Directory target, final boolean incremental); String[] getWarnings(); @Override int hashCode(); @Override boolean equals(final Object o); }### Answer:
@Test public void testIsParentOf() throws Exception { final File f1 = new File("xfoo"); final File f2 = new File("xfoo/bah"); final File f3 = new File("xfoo/bah/blah"); final File f4 = new File("xfoo/bah/dah"); assertTrue(new Directory(f1).isParentOf(f2)); assertTrue(new Directory(f1).isParentOf(f3)); assertFalse(new Directory(f2).isParentOf(f2)); assertFalse(new Directory(f2).isParentOf(f1)); assertFalse(new Directory(f3).isParentOf(f1)); assertFalse(new Directory(f3).isParentOf(f4)); } |
### Question:
HTTPPluginControl { private HTTPPluginControl() { } private HTTPPluginControl(); static HTTPPluginConnection getConnectionDefaults(); static HTTPPluginConnection getThreadConnection(String url); static Object getThreadHTTPClientContext(); static HTTPUtilities getHTTPUtilities(); }### Answer:
@Test public void testHTTPPluginControl() throws Exception { final HTTPPluginThreadState threadState = new HTTPPluginThreadState(null, new InsecureSSLContextFactory(), null, new StandardTimeAuthority()); final ScriptContext scriptContext = mock(ScriptContext.class, RETURNS_MOCKS); final PluginProcessContext pluginProcessContext = mock(PluginProcessContext.class); when(pluginProcessContext.getPluginThreadListener()) .thenReturn(threadState); when(pluginProcessContext.getScriptContext()).thenReturn(scriptContext); new PluginRegistry() { { setInstance(this); } @Override public void register(final GrinderPlugin plugin) throws GrinderException { plugin.initialize(pluginProcessContext); } }; final PluginProcessContext existingMock = HTTPPlugin.getPlugin().getPluginProcessContext(); if (existingMock != null && existingMock != pluginProcessContext) { when(existingMock.getPluginThreadListener()).thenReturn(threadState); when(existingMock.getScriptContext()).thenReturn(scriptContext); } final HTTPPluginConnection connectionDefaults = HTTPPluginControl.getConnectionDefaults(); assertNotNull(connectionDefaults); assertSame(connectionDefaults, HTTPPluginControl.getConnectionDefaults()); final HTTPUtilities utilities = HTTPPluginControl.getHTTPUtilities(); assertNotNull(utilities); final Object threadContext = HTTPPluginControl.getThreadHTTPClientContext(); assertSame(threadState, threadContext); assertSame(threadState, HTTPPluginControl.getThreadHTTPClientContext()); final HTTPPluginConnection connection = HTTPPluginControl.getThreadConnection("http: assertSame(connection, HTTPPluginControl.getThreadConnection("http: assertNotSame(connection, HTTPPluginControl.getThreadConnection("http: } |
### Question:
EditorModel { public boolean isScriptFile(File f) { if (f != null && (!f.exists() || f.isFile())) { final int lastDot = f.getName().lastIndexOf('.'); if (lastDot >= 0) { final String suffix = f.getName().substring(lastDot + 1).toLowerCase(); return s_knownScriptTypes.contains(suffix); } } return false; } EditorModel(Resources resources,
TextSource.Factory textSourceFactory,
AgentCacheState agentCacheState,
FileChangeWatcher fileChangeWatcher); Buffer getSelectedBuffer(); void selectNewBuffer(); Buffer selectBufferForFile(File file); Buffer getBufferForFile(File file); Buffer[] getBuffers(); boolean isABufferDirty(); void selectBuffer(Buffer buffer); void closeBuffer(final Buffer buffer); File getSelectedPropertiesFile(); void setSelectedPropertiesFile(final File selectedProperties); void addListener(Listener listener); boolean isScriptFile(File f); boolean isPropertiesFile(File f); boolean isSelectedScript(File f); boolean isBoringFile(File f); void openWithExternalEditor(final File file); void setExternalEditor(File command, String arguments); }### Answer:
@Test public void testIsScriptFile() throws Exception { final EditorModel editorModel = new EditorModel(s_resources, new StringTextSource.Factory(), m_agentCacheState, m_fileChangeWatcher); final File[] script = { new File("my file.py"), new File(".blah.py"), new File("python.PY"), new File("~python.py"), new File("clojure.clj"), new File(".clj"), }; for (int i = 0; i < script.length; ++i) { assertTrue("Is script: " + script[i], editorModel.isScriptFile(script[i])); } final File[] notScript = { null, new File("script.python"), new File("script.py "), new File("foo.bah"), new File("x.text"), }; for (int i = 0; i < notScript.length; ++i) { assertTrue("Isn't script: " + notScript[i], !editorModel.isScriptFile(notScript[i])); } } |
### Question:
EditorModel { public boolean isPropertiesFile(File f) { return f != null && (!f.exists() || f.isFile()) && f.getName().toLowerCase().endsWith(".properties"); } EditorModel(Resources resources,
TextSource.Factory textSourceFactory,
AgentCacheState agentCacheState,
FileChangeWatcher fileChangeWatcher); Buffer getSelectedBuffer(); void selectNewBuffer(); Buffer selectBufferForFile(File file); Buffer getBufferForFile(File file); Buffer[] getBuffers(); boolean isABufferDirty(); void selectBuffer(Buffer buffer); void closeBuffer(final Buffer buffer); File getSelectedPropertiesFile(); void setSelectedPropertiesFile(final File selectedProperties); void addListener(Listener listener); boolean isScriptFile(File f); boolean isPropertiesFile(File f); boolean isSelectedScript(File f); boolean isBoringFile(File f); void openWithExternalEditor(final File file); void setExternalEditor(File command, String arguments); }### Answer:
@Test public void testIsPropertiesFile() throws Exception { final EditorModel editorModel = new EditorModel(s_resources, new StringTextSource.Factory(), m_agentCacheState, m_fileChangeWatcher); final File[] properties = { new File("my file.properties"), new File(".blah.properties"), new File("python.PROPERTIES"), new File("~python.properties"), }; for (int i = 0; i < properties.length; ++i) { assertTrue("Is properties: " + properties[i], editorModel.isPropertiesFile(properties[i])); } final File[] notProperties = { null, new File("script.props"), new File("script.properties "), new File("foo.bah"), new File("x.text"), }; for (int i = 0; i < notProperties.length; ++i) { assertTrue("Isn't properties: " + notProperties[i], !editorModel.isPropertiesFile(notProperties[i])); } } |
### Question:
EditorModel { public void openWithExternalEditor(final File file) throws ConsoleException { final ExternalEditor externalEditor; synchronized (this) { externalEditor = m_externalEditor; } if (externalEditor == null) { throw new DisplayMessageConsoleException(m_resources, "externalEditorNotSet.text"); } try { externalEditor.open(file); } catch (IOException e) { throw new DisplayMessageConsoleException(m_resources, "externalEditError.text", e); } } EditorModel(Resources resources,
TextSource.Factory textSourceFactory,
AgentCacheState agentCacheState,
FileChangeWatcher fileChangeWatcher); Buffer getSelectedBuffer(); void selectNewBuffer(); Buffer selectBufferForFile(File file); Buffer getBufferForFile(File file); Buffer[] getBuffers(); boolean isABufferDirty(); void selectBuffer(Buffer buffer); void closeBuffer(final Buffer buffer); File getSelectedPropertiesFile(); void setSelectedPropertiesFile(final File selectedProperties); void addListener(Listener listener); boolean isScriptFile(File f); boolean isPropertiesFile(File f); boolean isSelectedScript(File f); boolean isBoringFile(File f); void openWithExternalEditor(final File file); void setExternalEditor(File command, String arguments); }### Answer:
@Test public void testOpenWithExternalEditor() throws Exception { final EditorModel editorModel = new EditorModel(s_resources, new StringTextSource.Factory(), m_agentCacheState, m_fileChangeWatcher); try { editorModel.openWithExternalEditor(null); fail("Expected DisplayMessageConsoleException"); } catch (DisplayMessageConsoleException e) { assertNull(e.getCause()); } editorModel.setExternalEditor(new File("not a command"), "bah"); try { editorModel.openWithExternalEditor(new File("foo")); fail("Expected DisplayMessageConsoleException"); } catch (DisplayMessageConsoleException e) { assertTrue(e.getCause() instanceof IOException); } editorModel.setExternalEditor(null, "bah"); try { editorModel.openWithExternalEditor(new File("foo")); fail("Expected DisplayMessageConsoleException"); } catch (DisplayMessageConsoleException e) { assertNull(e.getCause()); } } |
### Question:
ConsoleCommunicationImplementation implements ConsoleCommunication { @PreDestroy public void shutdown() { m_shutdown.set(true); m_processing.set(false); reset(); } ConsoleCommunicationImplementation(Resources resources,
ConsoleProperties properties, ErrorHandler errorHandler,
TimeAuthority timeAuthority); ConsoleCommunicationImplementation(Resources resources,
ConsoleProperties properties,
ErrorHandler errorHandler,
TimeAuthority timeAuthority,
long idlePollDelay,
long inactiveClientTimeOut); MessageDispatchRegistry getMessageDispatchRegistry(); @PreDestroy void shutdown(); boolean processOneMessage(); int getNumberOfConnections(); void sendToAgents(Message message); void sendToAddressedAgents(Address address, Message message); }### Answer:
@Test public void testShutdown() throws Exception { m_processMessagesThread.start(); new StubConnector(InetAddress.getByName(null).getHostName(), m_properties.getConsolePort(), ConnectionType.AGENT) .connect(); waitForNumberOfConnections(1); m_consoleCommunication.shutdown(); waitForNumberOfConnections(0); } |
### Question:
ConsoleFoundation { public void shutdown() { m_timer.cancel(); m_container.dispose(); } ConsoleFoundation(Resources resources, Logger logger, boolean headless); @SuppressWarnings("unchecked") ConsoleFoundation(Resources resources,
Logger logger,
boolean headless,
Timer timer,
ConsoleProperties properties); void run(); void shutdown(); static ConsoleProperties PROPERTIES; }### Answer:
@Test public void testConstruction() throws Exception { final ConsoleFoundation consoleFoundation = new ConsoleFoundation(m_resources, m_logger, true); verify(m_logger).info(isA(String.class)); verifyNoMoreInteractions(m_logger); consoleFoundation.shutdown(); } |
### Question:
ConsoleBarrierGroups extends LocalBarrierGroups { public ConsoleBarrierGroups(ConsoleCommunication communication) { m_communication = communication; } ConsoleBarrierGroups(ConsoleCommunication communication); }### Answer:
@Test public void testConsoleBarrierGroups() throws Exception { final ConsoleBarrierGroups barrierGroups = new ConsoleBarrierGroups(m_consoleCommunication); final BarrierGroup bg = barrierGroups.createBarrierGroup("foo"); bg.addBarrier(); verifyNoMoreInteractions(m_consoleCommunication); bg.addWaiter(mock(BarrierIdentity.class)); verify(m_consoleCommunication).sendToAgents(m_messageCaptor.capture()); assertEquals("foo", ((OpenBarrierMessage)m_messageCaptor.getValue()).getName()); } |
### Question:
JavaDCRInstrumenter extends AbstractDCRInstrumenter { @Override public String getDescription() { return "byte code transforming instrumenter for Java"; } JavaDCRInstrumenter(DCRContext context); @Override String getDescription(); }### Answer:
@Test public void testGetDescription() throws Exception { assertTrue(m_instrumenter.getDescription().length() > 0); } |
### Question:
JavaDCRInstrumenter extends AbstractDCRInstrumenter { private void instrumentClass(Class<?> targetClass, Recorder recorder, InstrumentationFilter filter) throws NonInstrumentableTypeException { if (targetClass.isArray()) { throw new NonInstrumentableTypeException("Can't instrument arrays"); } for (Constructor<?> constructor : targetClass.getDeclaredConstructors()) { getContext().add(targetClass, constructor, recorder); } for (Method method : targetClass.getDeclaredMethods()) { if (Modifier.isStatic(method.getModifiers()) && filter.matches(method)) { getContext().add(targetClass, method, TargetSource.CLASS, recorder); } } } JavaDCRInstrumenter(DCRContext context); @Override String getDescription(); }### Answer:
@Test @Ignore ("solcyr: This tests fails but I lack knowledge to understand it") public void testInstrumentClass() throws Exception { assertEquals(6, MyClass.staticSix()); final MyClass c1 = new MyClass(); assertEquals(0, c1.getA()); final Object result = m_instrumenter.createInstrumentedProxy(null, m_recorder, MyClass.class); assertSame(MyClass.class, result); MyClass.staticSix(); verify(m_recorder).start(); verify(m_recorder).end(true); assertEquals(0, c1.getA()); final MyClass c2 = new MyClass(); verify(m_recorder, times(3)).start(); verify(m_recorder, times(3)).end(true); assertEquals(0, c1.getA()); assertEquals(0, c2.getA()); m_instrumenter.createInstrumentedProxy(null, m_recorder, MyExtendedClass.class); MyClass.staticSix(); verify(m_recorder, times(4)).start(); verify(m_recorder, times(4)).end(true); verifyNoMoreInteractions(m_recorder); } |
### Question:
JavaDCRInstrumenter extends AbstractDCRInstrumenter { private void instrumentInstance(Object target, Recorder recorder, InstrumentationFilter filter) throws NonInstrumentableTypeException { Class<?> c = target.getClass(); if (c.isArray()) { throw new NonInstrumentableTypeException("Can't instrument arrays"); } do { for (Method method : c.getDeclaredMethods()) { if (!Modifier.isStatic(method.getModifiers()) && filter.matches(method)) { getContext().add(target, method, TargetSource.FIRST_PARAMETER, recorder); } } c = c.getSuperclass(); } while (getContext().isInstrumentable(c)); } JavaDCRInstrumenter(DCRContext context); @Override String getDescription(); }### Answer:
@Test public void testInstrumentInstance() throws Exception { RecorderLocatorAccess.clearRecorders(); final MyClass c1 = new MyExtendedClass(); assertEquals(0, c1.getA()); final Object result = m_instrumenter.createInstrumentedProxy(null, m_recorder, c1); assertSame(c1, result); MyClass.staticSix(); assertEquals(0, c1.getA()); verify(m_recorder).start(); verify(m_recorder).end(true); final MyClass c2 = new MyClass(); assertEquals(0, c2.getA()); verifyNoMoreInteractions(m_recorder); } |
### Question:
JavaDCRInstrumenter extends AbstractDCRInstrumenter { @Override protected boolean instrument(Object target, Recorder recorder, InstrumentationFilter filter) throws NonInstrumentableTypeException { if (target instanceof Class<?>) { instrumentClass((Class<?>)target, recorder, filter); } else if (target != null) { instrumentInstance(target, recorder, filter); } return true; } JavaDCRInstrumenter(DCRContext context); @Override String getDescription(); }### Answer:
@Test public void testSelectivelyInstrumentInstance() throws Exception { RecorderLocatorAccess.clearRecorders(); final MyClass c1 = new MyExtendedClass(); assertEquals(0, c1.getA()); final InstrumentationFilter filter = new InstrumentationFilter() { public boolean matches(Object item) { return ((Method)item).getName().equals("getA"); } }; m_instrumenter.instrument(null, m_recorder, c1, filter); MyClass.staticSix(); assertEquals(0, c1.getA()); assertEquals(0, c1.getB()); verify(m_recorder).start(); verify(m_recorder).end(true); final MyClass c2 = new MyClass(); assertEquals(0, c2.getA()); verifyNoMoreInteractions(m_recorder); } |
### Question:
JavaScriptEngineService implements ScriptEngineService { @Override public List<? extends Instrumenter> createInstrumenters() throws EngineException { if (m_dcrContext != null) { return asList(new JavaDCRInstrumenter(m_dcrContext)); } return emptyList(); } JavaScriptEngineService(DCRContext dcrContext); JavaScriptEngineService(); @Override List<? extends Instrumenter> createInstrumenters(); @Override ScriptEngine createScriptEngine(ScriptLocation script); }### Answer:
@Test public void testCreateInstrumenter() throws Exception { final DCRContext context = DCRContextImplementation.create(null); final List<? extends Instrumenter> instrumenters = new JavaScriptEngineService(context).createInstrumenters(); assertEquals(1, instrumenters.size()); assertEquals("byte code transforming instrumenter for Java", instrumenters.get(0).getDescription()); }
@Test public void testCreateInstrumenterWithNoInstrumentation() throws Exception { final List<? extends Instrumenter> instrumenters = new JavaScriptEngineService().createInstrumenters(); assertEquals(0, instrumenters.size()); } |
### Question:
JavaScriptEngineService implements ScriptEngineService { @Override public ScriptEngine createScriptEngine(ScriptLocation script) throws EngineException { return null; } JavaScriptEngineService(DCRContext dcrContext); JavaScriptEngineService(); @Override List<? extends Instrumenter> createInstrumenters(); @Override ScriptEngine createScriptEngine(ScriptLocation script); }### Answer:
@Test public void testGetScriptEngine() throws Exception { final ScriptLocation script = new ScriptLocation(new File("foo.java")); assertNull(new JavaScriptEngineService(null).createScriptEngine(script)); } |
### Question:
JythonScriptEngineService implements ScriptEngineService { @Override public ScriptEngine createScriptEngine(ScriptLocation script) throws EngineException { if (m_pyFileMatcher.accept(script.getFile())) { return new JythonScriptEngine(script); } return null; } JythonScriptEngineService(GrinderProperties properties,
DCRContext dcrContext,
ScriptLocation scriptLocation); JythonScriptEngineService(); @Override List<Instrumenter> createInstrumenters(); @Override ScriptEngine createScriptEngine(ScriptLocation script); }### Answer:
@Test public void testInitialisationWithCollocatedGrinderAndJythonJars() throws Exception { System.clearProperty("python.cachedir"); final String originalClasspath = System.getProperty("java.class.path"); final File grinderJar = new File(getDirectory(), "grinder.jar"); grinderJar.createNewFile(); final File jythonJar = new File(getDirectory(), "jython.jar"); jythonJar.createNewFile(); System.setProperty("java.class.path", grinderJar.getAbsolutePath() + File.pathSeparator + jythonJar.getAbsolutePath()); try { m_jythonScriptEngineService.createScriptEngine(m_pyScript); assertNotNull(System.getProperty("python.cachedir")); System.clearProperty("python.cachedir"); } finally { System.setProperty("java.class.path", originalClasspath); } } |
### Question:
CompositeInstrumenter implements Instrumenter { @Override public String getDescription() { final StringBuilder result = new StringBuilder(); for (Instrumenter instrumenter : m_instrumenters) { final String description = instrumenter.getDescription(); if (description != null) { if (result.length() > 0) { result.append("; "); } result.append(description); } } return result.toString(); } CompositeInstrumenter(Instrumenter... instrumenters); CompositeInstrumenter(List<Instrumenter> instrumenters); @Override Object createInstrumentedProxy(Test test,
Recorder recorder,
Object target); @Override boolean instrument(Test test,
Recorder recorder,
Object target); @Override boolean instrument(Test test,
Recorder recorder,
Object target,
InstrumentationFilter filter); @Override String getDescription(); }### Answer:
@Test public void testGetDescription() throws Exception { when(m_instrumenter1.getDescription()).thenReturn("I1"); when(m_instrumenter2.getDescription()).thenReturn("I2"); assertEquals("I1; I2", new CompositeInstrumenter(m_instrumenter1, m_instrumenter2) .getDescription()); assertEquals("I1", new CompositeInstrumenter(m_instrumenter1).getDescription()); assertEquals("", new CompositeInstrumenter().getDescription()); when(m_instrumenter2.getDescription()).thenReturn(null); assertEquals("I1", new CompositeInstrumenter(m_instrumenter1, m_instrumenter2) .getDescription()); } |
### Question:
ClojureScriptEngineService implements ScriptEngineService { @Override public List<? extends Instrumenter> createInstrumenters() throws EngineException { return emptyList(); } @Override ScriptEngine createScriptEngine(ScriptLocation script); @Override List<? extends Instrumenter> createInstrumenters(); }### Answer:
@Test public void testCreateInstrumenters() throws Exception { final List<? extends Instrumenter> instrumenters = new ClojureScriptEngineService().createInstrumenters(); assertEquals(0, instrumenters.size()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.