method2testcases
stringlengths 118
3.08k
|
---|
### Question:
MetaDataMergeKeyMapEntry { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } MetaDataMergeKeyMapEntry other = (MetaDataMergeKeyMapEntry)obj; return Objects.equals(mySourceKeyName, other.mySourceKeyName) && Objects.equals(myMergeKeyName, other.myMergeKeyName); } MetaDataMergeKeyMapEntry(); MetaDataMergeKeyMapEntry(MetaDataMergeKeyMapEntry other); MetaDataMergeKeyMapEntry(String mergeKeyName, String dataTypeKeyName); void decode(ObjectInputStream ois); int encode(ObjectOutputStream oos); @Override boolean equals(Object obj); String getMergeKeyName(); String getSourceKeyName(); @Override int hashCode(); void setMergeKeyName(String mergeKeyName); void setSourceKeyName(String sourceKeyName); @Override String toString(); }### Answer:
@Test public void testEqualsObjectDifferentClasses() { assertFalse(myTestObject.equals(RandomStringUtils.randomAlphabetic(25))); }
|
### Question:
MetaDataMergeKeyMapEntry { public void setMergeKeyName(String mergeKeyName) { myMergeKeyName = mergeKeyName; } MetaDataMergeKeyMapEntry(); MetaDataMergeKeyMapEntry(MetaDataMergeKeyMapEntry other); MetaDataMergeKeyMapEntry(String mergeKeyName, String dataTypeKeyName); void decode(ObjectInputStream ois); int encode(ObjectOutputStream oos); @Override boolean equals(Object obj); String getMergeKeyName(); String getSourceKeyName(); @Override int hashCode(); void setMergeKeyName(String mergeKeyName); void setSourceKeyName(String sourceKeyName); @Override String toString(); }### Answer:
@Test public void testSetMergeKeyName() { String testMergeKey = RandomStringUtils.randomAlphabetic(25); myTestObject.setMergeKeyName(testMergeKey); assertEquals(testMergeKey, myTestObject.getMergeKeyName()); }
|
### Question:
ElementData { public boolean found() { return myVisualizationState != null || myTimeSpan != null || myMetaDataProvider != null || myMapGeometrySupport != null; } ElementData(); ElementData(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); boolean found(); Long getID(); MapGeometrySupport getMapGeometrySupport(); MetaDataProvider getMetaDataProvider(); TimeSpan getTimeSpan(); VisualizationState getVisualizationState(); final void updateValues(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); }### Answer:
@Test public void testFound() { assertTrue(myTestObject.found()); myTestObject = new ElementData(myTestID, myTimeSpan, null, myMetaDataProvider, myMapGeometrySupport); assertTrue(myTestObject.found()); myTestObject = new ElementData(myTestID, null, myVisualizationState, myMetaDataProvider, myMapGeometrySupport); assertTrue(myTestObject.found()); myTestObject = new ElementData(myTestID, myTimeSpan, myVisualizationState, null, myMapGeometrySupport); assertTrue(myTestObject.found()); myTestObject = new ElementData(myTestID, myTimeSpan, myVisualizationState, myMetaDataProvider, null); assertTrue(myTestObject.found()); myTestObject = new ElementData(myTestID, null, null, null, null); assertFalse(myTestObject.found()); }
|
### Question:
PatternStringTokenizer implements StringTokenizer { @Override public List<String> tokenize(String line) { Matcher matcher = myPattern.matcher(line); if (matcher.matches()) { List<String> cells = new ArrayList<>(matcher.groupCount()); for (int index = 1; index <= matcher.groupCount(); ++index) { cells.add(matcher.group(index)); } return cells; } String[] cells = new String[matcher.groupCount()]; Arrays.fill(cells, StringUtilities.EMPTY); return Arrays.asList(cells); } PatternStringTokenizer(Pattern pattern); PatternStringTokenizer(String pattern); static PatternStringTokenizer createFromDivisions(int[] divisions); static PatternStringTokenizer createFromWidths(int[] widths); static String generatePatternFromColumnDivisions(final int[] divisions); static String generatePatternFromColumnWidths(final int[] widths); @Override List<String> tokenize(String line); }### Answer:
@Test public void testMatch() { PatternStringTokenizer tokenizer = new PatternStringTokenizer("(.{5})(\\S+)\\s*(.{7}).*"); List<String> actual = tokenizer.tokenize("a abb cccccccxxxx"); Assert.assertEquals(3, actual.size()); Assert.assertEquals("a a", actual.get(0)); Assert.assertEquals("bb", actual.get(1)); Assert.assertEquals("ccccccc", actual.get(2)); }
@Test public void testNoMatch() { PatternStringTokenizer tokenizer = new PatternStringTokenizer("(.{5})(\\S+)\\s*(.{7}).*"); List<String> actual = tokenizer.tokenize("a accccccc"); Assert.assertEquals(3, actual.size()); Assert.assertEquals("", actual.get(0)); Assert.assertEquals("", actual.get(1)); Assert.assertEquals("", actual.get(2)); }
|
### Question:
EnumUtilities { public static <T extends Enum<T>> T fromString(Class<T> type, String label) { return EnumSet.allOf(type).stream().filter(v -> v != null && Objects.equals(v.toString(), label)).findAny().orElse(null); } private EnumUtilities(); static T fromString(Class<T> type, String label); static T valueOf(Class<T> type, String name, T defaultValue); }### Answer:
@Test public void testFromStringClass() { Assert.assertEquals(TestEnum.ALPHA, EnumUtilities.fromString(TestEnum.class, "alpha")); Assert.assertEquals(TestEnum.BRAVO, EnumUtilities.fromString(TestEnum.class, "bravo")); Assert.assertEquals(TestEnum.CHARLIE, EnumUtilities.fromString(TestEnum.class, "charlie")); Assert.assertNull(EnumUtilities.fromString(TestEnum.class, "bad")); }
|
### Question:
GeographicUtilities { static List<LatLonAlt> removeDuplicates(List<? extends LatLonAlt> points) { List<LatLonAlt> list = New.list(points.size()); LatLonAlt lastPoint = null; for (LatLonAlt point : points) { if (!point.equals(lastPoint)) { list.add(point); lastPoint = point; } } return list; } private GeographicUtilities(); static Map<List<LatLonAlt>, Collection<List<LatLonAlt>>> decomposePositionsToPolygons(List<LatLonAlt> rings); static PolygonWinding getNaturalWinding(List<LatLonAlt> vertices); static List<ScreenPosition> toScreenPositions(List<? extends GeographicPosition> positions,
ScreenBoundingBox screenBounds); }### Answer:
@Test public void testRemoveDuplicates() { List<LatLonAlt> expected = New.list(LatLonAlt.createFromDegrees(1, 1), LatLonAlt.createFromDegrees(2, 2), LatLonAlt.createFromDegrees(1, 1), LatLonAlt.createFromDegrees(2, 2), LatLonAlt.createFromDegrees(1, 1)); List<LatLonAlt> input = New.list(LatLonAlt.createFromDegrees(1, 1), LatLonAlt.createFromDegrees(1, 1), LatLonAlt.createFromDegrees(2, 2), LatLonAlt.createFromDegrees(1, 1), LatLonAlt.createFromDegrees(1, 1), LatLonAlt.createFromDegrees(1, 1), LatLonAlt.createFromDegrees(2, 2), LatLonAlt.createFromDegrees(1, 1)); Assert.assertEquals(expected, GeographicUtilities.removeDuplicates(input)); }
|
### Question:
FileUtilities { public static File ensureSuffix(File file, String suffix) { if (suffix.equalsIgnoreCase(getSuffix(file))) { return file; } return new File(new StringBuilder(file.getPath()).append('.').append(suffix).toString()); } private FileUtilities(); static boolean archive(Path file); static boolean copyDirectory(File source, File destination, boolean copySubDirectories); static boolean copyfile(File srFile, File dtFile); static boolean createDirectories(File dir); static boolean createDirectoriesAndFile(File file); static boolean deleteDirRecursive(File fileOrDir); static File ensureSuffix(File file, String suffix); static List<String> explodeZip(InputStream inStream, File outputLocation, long seed); static String getBasename(File file); static String getDirectory(File baseDirectory, long seed); static long getDirSize(File file); static List<File> getFilesFromDirectory(File directory, final String extension); static String getSuffix(File file); static String getSuffix(String file); static ByteBuffer readFileToBuffer(File in); static List<String> readLines(File file); }### Answer:
@Test public void testEnsureSuffix() { File fullName = new File("C:\\path.dir\\last." + XYZ); Assert.assertEquals(fullName, FileUtilities.ensureSuffix(fullName, XYZ)); Assert.assertEquals(fullName, FileUtilities.ensureSuffix(new File("C:\\path.dir\\last"), XYZ)); }
|
### Question:
FileUtilities { public static String getBasename(File file) { final String name = file.getName(); final int ix = name.lastIndexOf('.'); return ix >= 0 ? name.substring(0, ix) : name; } private FileUtilities(); static boolean archive(Path file); static boolean copyDirectory(File source, File destination, boolean copySubDirectories); static boolean copyfile(File srFile, File dtFile); static boolean createDirectories(File dir); static boolean createDirectoriesAndFile(File file); static boolean deleteDirRecursive(File fileOrDir); static File ensureSuffix(File file, String suffix); static List<String> explodeZip(InputStream inStream, File outputLocation, long seed); static String getBasename(File file); static String getDirectory(File baseDirectory, long seed); static long getDirSize(File file); static List<File> getFilesFromDirectory(File directory, final String extension); static String getSuffix(File file); static String getSuffix(String file); static ByteBuffer readFileToBuffer(File in); static List<String> readLines(File file); }### Answer:
@Test public void testGetBasenameFile() { Assert.assertEquals(XYZ, FileUtilities.getBasename(new File(XYZ))); Assert.assertEquals("", FileUtilities.getBasename(new File("." + XYZ))); Assert.assertEquals("a", FileUtilities.getBasename(new File("a." + XYZ))); Assert.assertEquals("last", FileUtilities.getBasename(new File(File.separator + "path.dir" + File.separator + "last." + XYZ))); }
|
### Question:
FileUtilities { public static String getSuffix(File file) { return getSuffix(file.getName()); } private FileUtilities(); static boolean archive(Path file); static boolean copyDirectory(File source, File destination, boolean copySubDirectories); static boolean copyfile(File srFile, File dtFile); static boolean createDirectories(File dir); static boolean createDirectoriesAndFile(File file); static boolean deleteDirRecursive(File fileOrDir); static File ensureSuffix(File file, String suffix); static List<String> explodeZip(InputStream inStream, File outputLocation, long seed); static String getBasename(File file); static String getDirectory(File baseDirectory, long seed); static long getDirSize(File file); static List<File> getFilesFromDirectory(File directory, final String extension); static String getSuffix(File file); static String getSuffix(String file); static ByteBuffer readFileToBuffer(File in); static List<String> readLines(File file); }### Answer:
@Test public void testGetSuffixFile() { Assert.assertNull(FileUtilities.getSuffix(new File(XYZ))); Assert.assertNull(FileUtilities.getSuffix(new File("." + XYZ))); Assert.assertEquals(XYZ, FileUtilities.getSuffix(new File("a." + XYZ))); Assert.assertEquals(XYZ, FileUtilities.getSuffix(new File("C:\\path.dir\\last." + XYZ))); }
@Test public void testGetSuffixString() { Assert.assertNull(FileUtilities.getSuffix(XYZ)); Assert.assertNull(FileUtilities.getSuffix("." + XYZ)); Assert.assertEquals(XYZ, FileUtilities.getSuffix("a." + XYZ)); Assert.assertEquals(XYZ, FileUtilities.getSuffix("C:\\path.dir\\last." + XYZ)); }
|
### Question:
MetaDataMergeKeyMapEntry { public void setSourceKeyName(String sourceKeyName) { mySourceKeyName = sourceKeyName; } MetaDataMergeKeyMapEntry(); MetaDataMergeKeyMapEntry(MetaDataMergeKeyMapEntry other); MetaDataMergeKeyMapEntry(String mergeKeyName, String dataTypeKeyName); void decode(ObjectInputStream ois); int encode(ObjectOutputStream oos); @Override boolean equals(Object obj); String getMergeKeyName(); String getSourceKeyName(); @Override int hashCode(); void setMergeKeyName(String mergeKeyName); void setSourceKeyName(String sourceKeyName); @Override String toString(); }### Answer:
@Test public void testSetSourceKeyName() { String testSourceKey = RandomStringUtils.randomAlphabetic(25); myTestObject.setSourceKeyName(testSourceKey); assertEquals(testSourceKey, myTestObject.getSourceKeyName()); }
|
### Question:
NumberPredicate implements Predicate<String> { @Override public boolean test(String token) { boolean isValid; if (StringUtils.isBlank(token)) { isValid = false; } else { try { Double.valueOf(token); isValid = token.indexOf('d') == -1 && token.indexOf('f') == -1; } catch (NumberFormatException e) { isValid = false; } } return isValid; } @Override boolean test(String token); }### Answer:
@Test public void test() { NumberPredicate predicate = new NumberPredicate(); Assert.assertFalse(predicate.test(null)); Assert.assertFalse(predicate.test("")); Assert.assertFalse(predicate.test(" ")); Assert.assertFalse(predicate.test("a")); Assert.assertFalse(predicate.test("5d")); Assert.assertFalse(predicate.test("5f")); Assert.assertTrue(predicate.test("0")); Assert.assertTrue(predicate.test("01")); Assert.assertTrue(predicate.test("01.")); Assert.assertTrue(predicate.test("01.0")); Assert.assertTrue(predicate.test("-4e3")); }
|
### Question:
InPredicate implements Predicate<Object> { @Override public boolean test(Object input) { return myAllowed.contains(input); } InPredicate(Collection<? extends Object> allowed); @Override boolean equals(Object obj); @Override int hashCode(); @Override boolean test(Object input); }### Answer:
@Test public void test() { InPredicate predicate = new InPredicate(Arrays.asList("one", "two", "three")); Assert.assertFalse(predicate.test(null)); Assert.assertFalse(predicate.test("")); Assert.assertFalse(predicate.test("One")); Assert.assertTrue(predicate.test("one")); Assert.assertTrue(predicate.test("two")); Assert.assertTrue(predicate.test("three")); }
|
### Question:
AndPredicate implements Predicate<T> { @Override public boolean test(T input) { for (Predicate<? super T> p : myPredicates) { if (!p.test(input)) { return false; } } return true; } AndPredicate(Collection<? extends Predicate<? super T>> predicates); AndPredicate(Predicate<? super T> arg1, Predicate<? super T> arg2); @Override boolean test(T input); }### Answer:
@Test public void test() { Assert.assertTrue(new AndPredicate<Void>(Collections.<Predicate<Object>>emptyList()).test(null)); Assert.assertTrue(new AndPredicate<Void>(Arrays.asList(TRUE_PREDICATE)).test(null)); Assert.assertFalse(new AndPredicate<Void>(Arrays.asList(FALSE_PREDICATE)).test(null)); Assert.assertTrue(new AndPredicate<Void>(Arrays.asList(TRUE_PREDICATE, TRUE_PREDICATE)).test(null)); Assert.assertFalse(new AndPredicate<Void>(Arrays.asList(FALSE_PREDICATE, TRUE_PREDICATE)).test(null)); Assert.assertFalse(new AndPredicate<Void>(Arrays.asList(TRUE_PREDICATE, FALSE_PREDICATE)).test(null)); Assert.assertTrue(new AndPredicate<Void>(Arrays.asList(TRUE_PREDICATE, TRUE_PREDICATE, TRUE_PREDICATE)).test(null)); Assert.assertFalse(new AndPredicate<Void>(Arrays.asList(TRUE_PREDICATE, TRUE_PREDICATE, FALSE_PREDICATE)).test(null)); Assert.assertFalse(new AndPredicate<Void>(Arrays.asList(FALSE_PREDICATE, TRUE_PREDICATE, TRUE_PREDICATE)).test(null)); Assert.assertFalse(new AndPredicate<Void>(Arrays.asList(TRUE_PREDICATE, FALSE_PREDICATE, TRUE_PREDICATE)).test(null)); }
|
### Question:
BlankPredicate implements Predicate<String> { @Override public boolean test(String value) { return StringUtils.isBlank(value); } @Override boolean test(String value); }### Answer:
@Test public void test() { BlankPredicate predicate = new BlankPredicate(); Assert.assertTrue(predicate.test(null)); Assert.assertTrue(predicate.test("")); Assert.assertTrue(predicate.test(" ")); Assert.assertTrue(predicate.test(" \n\t")); Assert.assertFalse(predicate.test("bob")); Assert.assertFalse(predicate.test(" bob ")); }
|
### Question:
ValidURLPredicate implements Predicate<String> { @Override public boolean test(String input) { return input != null && isValidAbsoluteUrl(input); } @Override boolean test(String input); }### Answer:
@Test public void test() { ValidURLPredicate predicate = new ValidURLPredicate(); Assert.assertFalse(predicate.test(null)); Assert.assertFalse(predicate.test("")); Assert.assertFalse(predicate.test(" ")); Assert.assertFalse(predicate.test("a")); Assert.assertFalse(predicate.test("http: Assert.assertFalse(predicate.test("http: Assert.assertFalse(predicate.test("invalid.com")); Assert.assertTrue(predicate.test("http: Assert.assertTrue(predicate.test("http: Assert.assertTrue(predicate.test("http: }
|
### Question:
NonBlankPredicate implements Predicate<String> { @Override public boolean test(String value) { return !StringUtils.isBlank(value); } @Override boolean test(String value); }### Answer:
@Test public void test() { NonBlankPredicate predicate = new NonBlankPredicate(); Assert.assertFalse(predicate.test(null)); Assert.assertFalse(predicate.test("")); Assert.assertFalse(predicate.test(" ")); Assert.assertFalse(predicate.test(" \n\t")); Assert.assertTrue(predicate.test("bob")); Assert.assertTrue(predicate.test(" bob ")); }
|
### Question:
NonEmptyPredicate implements Predicate<String> { @Override public boolean test(String value) { return StringUtils.isNotEmpty(value); } @Override boolean test(String value); }### Answer:
@Test public void test() { NonEmptyPredicate predicate = new NonEmptyPredicate(); Assert.assertFalse(predicate.test(null)); Assert.assertFalse(predicate.test("")); Assert.assertTrue(predicate.test(" ")); Assert.assertTrue(predicate.test("bob")); Assert.assertTrue(predicate.test(" bob ")); }
|
### Question:
DoubleRangePredicate implements Predicate<Double> { @Override public boolean test(Double input) { if (input == null) { return false; } double val = input.doubleValue(); return myMin <= val && val <= myMax; } DoubleRangePredicate(double min, double max); @Override boolean test(Double input); }### Answer:
@Test public void test() { DoubleRangePredicate predicate = new DoubleRangePredicate(5., 7.); Assert.assertFalse(predicate.test(Double.valueOf(4))); Assert.assertTrue(predicate.test(Double.valueOf(5))); Assert.assertTrue(predicate.test(Double.valueOf(6))); Assert.assertTrue(predicate.test(Double.valueOf(7))); Assert.assertFalse(predicate.test(Double.valueOf(8))); }
|
### Question:
EqualsIgnoreCasePredicate implements Predicate<String> { @Override public boolean test(String input) { if (input == null) { return false; } for (String allowed : myStrings) { if (input.equalsIgnoreCase(allowed)) { return true; } } return false; } EqualsIgnoreCasePredicate(Collection<? extends String> strings); EqualsIgnoreCasePredicate(String string); @Override boolean equals(Object obj); @Override int hashCode(); @Override boolean test(String input); }### Answer:
@Test public void test() { EqualsIgnoreCasePredicate predicate = new EqualsIgnoreCasePredicate(Arrays.asList("ONE", "TWO", "THREE")); Assert.assertFalse(predicate.test(null)); Assert.assertFalse(predicate.test("")); Assert.assertTrue(predicate.test("One")); Assert.assertTrue(predicate.test("tWo")); Assert.assertTrue(predicate.test("thRee")); Assert.assertFalse(predicate.test("aOne")); Assert.assertFalse(predicate.test("atWo")); Assert.assertFalse(predicate.test("athRee")); Assert.assertFalse(predicate.test("Onea")); Assert.assertFalse(predicate.test("tWoa")); Assert.assertFalse(predicate.test("thReea")); }
|
### Question:
MetaDataMergeKeyMapEntry { @Override public String toString() { StringBuilder sb = new StringBuilder(100); sb.append(getClass().getSimpleName()).append(" MergeKeyName[").append(myMergeKeyName).append("] SourceKeyName[") .append(mySourceKeyName).append(']'); return sb.toString(); } MetaDataMergeKeyMapEntry(); MetaDataMergeKeyMapEntry(MetaDataMergeKeyMapEntry other); MetaDataMergeKeyMapEntry(String mergeKeyName, String dataTypeKeyName); void decode(ObjectInputStream ois); int encode(ObjectOutputStream oos); @Override boolean equals(Object obj); String getMergeKeyName(); String getSourceKeyName(); @Override int hashCode(); void setMergeKeyName(String mergeKeyName); void setSourceKeyName(String sourceKeyName); @Override String toString(); }### Answer:
@Test public void testToString() { String testMergeKey = RandomStringUtils.randomAlphabetic(25); String testSourceKey = RandomStringUtils.randomAlphabetic(25); myTestObject = new MetaDataMergeKeyMapEntry(testMergeKey, testSourceKey); assertEquals(MetaDataMergeKeyMapEntry.class.getSimpleName() + " MergeKeyName[" + testMergeKey + "] SourceKeyName[" + testSourceKey + "]", myTestObject.toString()); }
|
### Question:
IntegerRangePredicate implements Predicate<Integer> { @Override public boolean test(Integer input) { if (input == null) { return false; } int intVal = input.intValue(); return myMin <= intVal && intVal <= myMax; } IntegerRangePredicate(int min, int max); @Override boolean test(Integer input); }### Answer:
@Test public void test() { IntegerRangePredicate predicate = new IntegerRangePredicate(5, 7); Assert.assertFalse(predicate.test(Integer.valueOf(4))); Assert.assertTrue(predicate.test(Integer.valueOf(5))); Assert.assertTrue(predicate.test(Integer.valueOf(6))); Assert.assertTrue(predicate.test(Integer.valueOf(7))); Assert.assertFalse(predicate.test(Integer.valueOf(8))); }
|
### Question:
NotPredicate implements Predicate<T> { @Override public boolean test(T input) { return !myPredicate.test(input); } NotPredicate(Predicate<T> predicate); @Override boolean test(T input); }### Answer:
@Test public void test() { Predicate<Void> truePredicate = new Predicate<Void>() { @Override public boolean test(Void input) { return true; } }; Assert.assertFalse(new NotPredicate<>(truePredicate).test(null)); Predicate<Void> falsePredicate = new Predicate<Void>() { @Override public boolean test(Void input) { return false; } }; Assert.assertTrue(new NotPredicate<>(falsePredicate).test(null)); }
|
### Question:
EndsWithPredicate implements Predicate<String> { @Override public boolean test(String input) { if (input == null) { return false; } String subject = myIgnoreCase ? input.toLowerCase() : input; for (String allowed : mySuffixes) { if (subject.endsWith(allowed)) { return true; } } return false; } EndsWithPredicate(Collection<? extends String> suffixes); EndsWithPredicate(String... suffixes); EndsWithPredicate(Collection<? extends String> suffixes, boolean ignoreCase); @Override boolean equals(Object obj); @Override int hashCode(); @Override boolean test(String input); }### Answer:
@Test public void test() { EndsWithPredicate predicate = new EndsWithPredicate(Arrays.asList("one", "two", "three"), false); Assert.assertFalse(predicate.test(null)); Assert.assertFalse(predicate.test("")); Assert.assertFalse(predicate.test("One")); Assert.assertTrue(predicate.test("one")); Assert.assertTrue(predicate.test("two")); Assert.assertTrue(predicate.test("three")); Assert.assertTrue(predicate.test("aone")); Assert.assertTrue(predicate.test("atwo")); Assert.assertTrue(predicate.test("athree")); Assert.assertFalse(predicate.test("onea")); Assert.assertFalse(predicate.test("twoa")); Assert.assertFalse(predicate.test("threea")); }
@Test public void testIgnoreCase() { EndsWithPredicate predicate = new EndsWithPredicate(Arrays.asList("ONE", "TWO", "THREE"), true); Assert.assertFalse(predicate.test(null)); Assert.assertFalse(predicate.test("")); Assert.assertTrue(predicate.test("One")); Assert.assertTrue(predicate.test("tWo")); Assert.assertTrue(predicate.test("thRee")); Assert.assertTrue(predicate.test("aOne")); Assert.assertTrue(predicate.test("atWo")); Assert.assertTrue(predicate.test("athRee")); Assert.assertFalse(predicate.test("Onea")); Assert.assertFalse(predicate.test("tWoa")); Assert.assertFalse(predicate.test("thReea")); }
|
### Question:
HeterogeneousSet extends AbstractSet<E> { @SuppressWarnings("unchecked") public List<E> getObjectsAsList() { int size = 0; Collection<List<? extends E>> values = myClassToObjectMap.values(); for (List<? extends E> list : values) { size += list.size(); } Object[] arr = new Object[size]; int pos = 0; for (List<? extends E> list : values) { System.arraycopy(list.toArray(), 0, arr, pos, list.size()); pos += list.size(); } return (List<E>)Arrays.asList(arr); } @Override synchronized boolean add(E e); @Override synchronized boolean addAll(Collection<? extends E> c); synchronized boolean addAll(Collection<? extends E> c, Comparator<E> comparator); @Override synchronized void clear(); @Override boolean contains(Object o); @SuppressWarnings("unchecked") List<E> getObjectsAsList(); List<T> getObjectsOfClass(Class<T> cl); @Override Iterator<E> iterator(); @Override synchronized boolean remove(Object obj); @Override synchronized boolean removeAll(Collection<?> c); @Override int size(); }### Answer:
@Test public void testGetObjectsAsList() { TypeA a1 = new TypeA(); TypeA a2 = new TypeA(); TypeB b1 = new TypeB(); TypeB b2 = new TypeB(); HeterogeneousSet<Object> set = new HeterogeneousSet<>(); set.addAll(Arrays.asList(a1, a2, b1, b2, a1, a2)); List<Object> list = set.getObjectsAsList(); Assert.assertEquals(4, list.size()); Assert.assertTrue(list.containsAll(set)); }
|
### Question:
SpeedKey extends AbstractSpecialKey implements SpecialColumnDetector { @Override public boolean markSpecialColumn(MetaDataInfo metaData, String columnName) { boolean wasDetected = false; if (!metaData.hasTypeForSpecialKey(SpeedKey.DEFAULT)) { SpecialKey specialKey = detectColumn(columnName); if (specialKey != null) { metaData.setSpecialKey(columnName, specialKey, metaData); wasDetected = true; } } return wasDetected; } SpeedKey(); SpeedKey(SpeedUnit unit); @Override SpeedUnit getKeyUnit(); @Override boolean markSpecialColumn(MetaDataInfo metaData, String columnName); @Override SpecialKey detectColumn(String columnName); static boolean isSpeed(String columnName); static final SpeedKey DEFAULT; }### Answer:
@Test public void testMarkSpecialColumn() { DefaultMetaDataInfo metaData = new DefaultMetaDataInfo(); String column = "Speed (m/s)"; metaData.addKey(column, Double.class, this); SpeedKey.DEFAULT.markSpecialColumn(metaData, column); SpeedKey actual = (SpeedKey)metaData.getSpecialTypeForKey(column); SpeedKey expected = new SpeedKey(SpeedUnit.METERS_PER_SECOND); Assert.assertEquals(expected, actual); Assert.assertEquals(expected.getKeyUnit(), actual.getKeyUnit()); metaData = new DefaultMetaDataInfo(); column = "Speed (km/hr)"; metaData.addKey(column, Double.class, this); SpeedKey.DEFAULT.markSpecialColumn(metaData, column); actual = (SpeedKey)metaData.getSpecialTypeForKey(column); expected = new SpeedKey(SpeedUnit.KILOMETERS_PER_HOUR); Assert.assertEquals(expected, actual); Assert.assertEquals(expected.getKeyUnit(), actual.getKeyUnit()); }
|
### Question:
EllipseSemiMinorAxisKey extends AbstractSpecialKey implements SpecialColumnDetector { @Override public boolean markSpecialColumn(MetaDataInfo metaData, String columnName) { boolean wasDetected = false; if (!metaData.hasTypeForSpecialKey(EllipseSemiMinorAxisKey.DEFAULT)) { SpecialKey specialKey = detectColumn(columnName); if (specialKey != null) { metaData.setSpecialKey(columnName, specialKey, metaData); wasDetected = true; } } return wasDetected; } EllipseSemiMinorAxisKey(); EllipseSemiMinorAxisKey(Class<? extends Length> semiMinorUnit); @Override boolean markSpecialColumn(MetaDataInfo metaData, String columnName); @Override SpecialKey detectColumn(String columnName); @SuppressWarnings("unchecked") Class<? extends Length> getAltitudeUnit(); static Class<? extends Length> detectUnit(String columnName); static final EllipseSemiMinorAxisKey DEFAULT; }### Answer:
@Test public void testMarkSpecialColumn() { DefaultMetaDataInfo metaData = new DefaultMetaDataInfo(); String column = "Semi-Minor 95 (km)"; metaData.addKey(column, Double.class, this); EllipseSemiMinorAxisKey.DEFAULT.markSpecialColumn(metaData, column); EllipseSemiMinorAxisKey actual = (EllipseSemiMinorAxisKey)metaData.getSpecialTypeForKey(column); EllipseSemiMinorAxisKey expected = new EllipseSemiMinorAxisKey(Kilometers.class); Assert.assertEquals(expected, actual); Assert.assertEquals(expected.getKeyUnit(), actual.getKeyUnit()); }
|
### Question:
EllipseSemiMinorAxisKey extends AbstractSpecialKey implements SpecialColumnDetector { static boolean isSemiMinor(String columnName) { return COLUMN_PATTERN.matcher(columnName).matches(); } EllipseSemiMinorAxisKey(); EllipseSemiMinorAxisKey(Class<? extends Length> semiMinorUnit); @Override boolean markSpecialColumn(MetaDataInfo metaData, String columnName); @Override SpecialKey detectColumn(String columnName); @SuppressWarnings("unchecked") Class<? extends Length> getAltitudeUnit(); static Class<? extends Length> detectUnit(String columnName); static final EllipseSemiMinorAxisKey DEFAULT; }### Answer:
@Test public void testIsSemiMinor() { Assert.assertFalse(EllipseSemiMinorAxisKey.isSemiMinor("")); Assert.assertFalse(EllipseSemiMinorAxisKey.isSemiMinor("SEMI_MAJOR")); Assert.assertTrue(EllipseSemiMinorAxisKey.isSemiMinor("Semi-Minor 95 (km)")); Assert.assertTrue(EllipseSemiMinorAxisKey.isSemiMinor("SEMI_MINOR")); Assert.assertTrue(EllipseSemiMinorAxisKey.isSemiMinor("SMI")); Assert.assertTrue(EllipseSemiMinorAxisKey.isSemiMinor("SMI_NM")); Assert.assertTrue(EllipseSemiMinorAxisKey.isSemiMinor("SMIN")); }
|
### Question:
EllipseSemiMajorAxisKey extends AbstractSpecialKey implements SpecialColumnDetector { @Override public boolean markSpecialColumn(MetaDataInfo metaData, String columnName) { boolean wasDetected = false; if (!metaData.hasTypeForSpecialKey(EllipseSemiMajorAxisKey.DEFAULT)) { SpecialKey specialKey = detectColumn(columnName); if (specialKey != null) { metaData.setSpecialKey(columnName, specialKey, metaData); wasDetected = true; } } return wasDetected; } EllipseSemiMajorAxisKey(); EllipseSemiMajorAxisKey(Class<? extends Length> semiMajorUnit); @Override boolean markSpecialColumn(MetaDataInfo metaData, String columnName); @Override SpecialKey detectColumn(String columnName); @SuppressWarnings("unchecked") Class<? extends Length> getSemiMajorUnit(); static Class<? extends Length> detectUnit(String columnName); static final EllipseSemiMajorAxisKey DEFAULT; }### Answer:
@Test public void testMarkSpecialColumn() { DefaultMetaDataInfo metaData = new DefaultMetaDataInfo(); String column = "Semi-Major 95 (km)"; metaData.addKey(column, Double.class, this); EllipseSemiMajorAxisKey.DEFAULT.markSpecialColumn(metaData, column); EllipseSemiMajorAxisKey actual = (EllipseSemiMajorAxisKey)metaData.getSpecialTypeForKey(column); EllipseSemiMajorAxisKey expected = new EllipseSemiMajorAxisKey(Kilometers.class); Assert.assertEquals(expected, actual); Assert.assertEquals(expected.getKeyUnit(), actual.getKeyUnit()); }
|
### Question:
EllipseSemiMajorAxisKey extends AbstractSpecialKey implements SpecialColumnDetector { static boolean isSemiMajor(String columnName) { return COLUMN_PATTERN.matcher(columnName).matches(); } EllipseSemiMajorAxisKey(); EllipseSemiMajorAxisKey(Class<? extends Length> semiMajorUnit); @Override boolean markSpecialColumn(MetaDataInfo metaData, String columnName); @Override SpecialKey detectColumn(String columnName); @SuppressWarnings("unchecked") Class<? extends Length> getSemiMajorUnit(); static Class<? extends Length> detectUnit(String columnName); static final EllipseSemiMajorAxisKey DEFAULT; }### Answer:
@Test public void testIsSemiMajor() { Assert.assertFalse(EllipseSemiMajorAxisKey.isSemiMajor("")); Assert.assertFalse(EllipseSemiMajorAxisKey.isSemiMajor("SEMI_MINOR")); Assert.assertTrue(EllipseSemiMajorAxisKey.isSemiMajor("Semi-Major 95 (km)")); Assert.assertTrue(EllipseSemiMajorAxisKey.isSemiMajor("SEMI_MAJOR")); Assert.assertTrue(EllipseSemiMajorAxisKey.isSemiMajor("SMA")); Assert.assertTrue(EllipseSemiMajorAxisKey.isSemiMajor("SMJ_NM")); Assert.assertTrue(EllipseSemiMajorAxisKey.isSemiMajor("SMAJ")); }
|
### Question:
SpeedErrorKey extends AbstractSpecialKey implements SpecialColumnDetector { @Override public boolean markSpecialColumn(MetaDataInfo metaData, String columnName) { boolean wasDetected = false; if (!metaData.hasTypeForSpecialKey(SpeedErrorKey.DEFAULT)) { SpecialKey specialKey = detectColumn(columnName); if (specialKey != null) { metaData.setSpecialKey(columnName, specialKey, metaData); wasDetected = true; } } return wasDetected; } SpeedErrorKey(); SpeedErrorKey(SpeedUnit unit); @Override SpeedUnit getKeyUnit(); @Override boolean markSpecialColumn(MetaDataInfo metaData, String columnName); @Override SpecialKey detectColumn(String columnName); static final SpeedErrorKey DEFAULT; }### Answer:
@Test public void testMarkSpecialColumn() { DefaultMetaDataInfo metaData = new DefaultMetaDataInfo(); String column = "Speed Error (+/-mi/hr)"; metaData.addKey(column, Double.class, this); SpeedErrorKey.DEFAULT.markSpecialColumn(metaData, column); SpeedErrorKey actual = (SpeedErrorKey)metaData.getSpecialTypeForKey(column); SpeedErrorKey expected = new SpeedErrorKey(SpeedUnit.MILES_PER_HOUR); Assert.assertEquals(expected, actual); Assert.assertEquals(expected.getKeyUnit(), actual.getKeyUnit()); }
|
### Question:
ElementData { public Long getID() { return myID; } ElementData(); ElementData(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); boolean found(); Long getID(); MapGeometrySupport getMapGeometrySupport(); MetaDataProvider getMetaDataProvider(); TimeSpan getTimeSpan(); VisualizationState getVisualizationState(); final void updateValues(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); }### Answer:
@Test public void testGetID() { assertEquals(myTestID, myTestObject.getID()); }
|
### Question:
HeadingKey extends AbstractSpecialKey implements SpecialColumnDetector { @Override public boolean markSpecialColumn(MetaDataInfo metaData, String columnName) { boolean wasDetected = false; if (!metaData.hasTypeForSpecialKey(HeadingKey.DEFAULT)) { SpecialKey specialKey = detectColumn(columnName); if (specialKey != null) { metaData.setSpecialKey(columnName, specialKey, metaData); wasDetected = true; } } return wasDetected; } HeadingKey(); HeadingKey(HeadingUnit unit); @Override HeadingUnit getKeyUnit(); @Override boolean markSpecialColumn(MetaDataInfo metaData, String columnName); @Override SpecialKey detectColumn(String columnName); static boolean isHeading(String columnName); static final HeadingKey DEFAULT; }### Answer:
@Test public void testMarkSpecialColumn() { DefaultMetaDataInfo metaData = new DefaultMetaDataInfo(); String column = "Heading (degN)"; metaData.addKey(column, Double.class, this); HeadingKey.DEFAULT.markSpecialColumn(metaData, column); HeadingKey actual = (HeadingKey)metaData.getSpecialTypeForKey(column); HeadingKey expected = new HeadingKey(HeadingUnit.DEGREES_CLOCKWISE_FROM_NORTH); Assert.assertEquals(expected, actual); Assert.assertEquals(expected.getKeyUnit(), actual.getKeyUnit()); }
|
### Question:
TimeSpanUtility { public static String formatTimeSpan(SimpleDateFormat dateFormat, TimeSpan ts) { return ts == null ? BLANK : TimeSpanFormatter.buildString(ts, dateFormat, " to ", new StringBuilder(42)).toString(); } private TimeSpanUtility(); static String formatTimeSpan(SimpleDateFormat dateFormat, TimeSpan ts); static String formatTimeSpanSingleTimeOnly(SimpleDateFormat dateFormat, TimeSpan ts); static TimeSpan fromStartEnd(long startTime, long endTime); static long getWorkaroundEnd(TimeSpan ts); static long getWorkaroundStart(TimeSpan ts); static final long TIMELESS_END; static final long TIMELESS_START; }### Answer:
@Test public void testFormatTimeSpan() { SimpleDateFormat format = new SimpleDateFormat(DateTimeFormats.DATE_TIME_FORMAT); Assert.assertEquals("", TimeSpanUtility.formatTimeSpan(format, null)); Assert.assertEquals("TIMELESS", TimeSpanUtility.formatTimeSpan(format, TimeSpan.TIMELESS)); Assert.assertEquals("ZERO", TimeSpanUtility.formatTimeSpan(format, TimeSpan.ZERO)); Assert.assertEquals("1970-01-02 00:00:00", TimeSpanUtility.formatTimeSpan(format, TimeSpan.get(Constants.MILLIS_PER_DAY))); Assert.assertEquals("1970-01-02 00:00:00 to 1970-01-03 00:00:00", TimeSpanUtility.formatTimeSpan(format, TimeSpan.get(Constants.MILLIS_PER_DAY, Constants.MILLIS_PER_DAY * 2))); Assert.assertEquals("UNBOUNDED to 1970-01-02 00:00:00", TimeSpanUtility.formatTimeSpan(format, TimeSpan.newUnboundedStartTimeSpan(Constants.MILLIS_PER_DAY))); Assert.assertEquals("1970-01-02 00:00:00 to UNBOUNDED", TimeSpanUtility.formatTimeSpan(format, TimeSpan.newUnboundedEndTimeSpan(Constants.MILLIS_PER_DAY))); }
|
### Question:
QueryRegionStateController extends AbstractModuleStateController { @Override public boolean canActivateState(Node node) { try { return StateXML.newXPath().evaluate("/" + ModuleStateController.STATE_QNAME + "/:queryAreas", node, XPathConstants.NODE) != null; } catch (XPathExpressionException e) { LOGGER.error(e, e); return false; } } QueryRegionStateController(QueryRegionManager queryRegionManager, Toolbox toolbox); @Override synchronized void activateState(final String id, String description, Collection<? extends String> tags, Node node); @Override void activateState(String id, String description, Collection<? extends String> tags, StateType state); @Override boolean canActivateState(Node node); @Override boolean canActivateState(StateType state); @Override boolean canSaveState(); @Override synchronized void deactivateState(String id, Node node); @Override void deactivateState(String id, StateType state); @Override boolean isSaveStateByDefault(); @Override void saveState(Node node); @Override void saveState(StateType state); }### Answer:
@Test public void testCanActivateState() throws XPathExpressionException, ParserConfigurationException { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); QueryRegionStateController controller = new QueryRegionStateController(null, null); Assert.assertFalse(controller.canActivateState(doc)); doc.appendChild(StateXML.createElement(doc, ModuleStateController.STATE_NAME)) .appendChild(StateXML.createElement(doc, "queryAreas")); Assert.assertTrue(controller.canActivateState(doc)); }
|
### Question:
InfinityUtilities { public static String getUrl(DataTypeInfo dataType) { String url = getTagValue(URL, dataType); String index = getTagValue(INDEX, dataType); if (index != null) { url += "?" + index; } return url; } private InfinityUtilities(); static boolean isInfinityEnabled(DataTypeInfo dataType); static String getUrl(DataTypeInfo dataType); static String getTagValue(String tagKey, DataTypeInfo dataType); static String getDateFormat(String interval); static String infinify(String text, boolean isInfinity); static final String INFINITY; static final String URL; static final String INDEX; static final String POINT; static final String SHAPE; static final String START; static final String END; static final String TIME; static final long MISSING_VALUE; static final String MISSING_VALUE_SCI_NOTATION; static final double DEFAULT_BIN_WIDTH; static final int DEFAULT_BIN_WIDTH_FRAC_DIGITS; static final double DEFAULT_BIN_OFFSET; static final int DEFAULT_MIN_DOC_COUNT; static final int DEFAULT_SIZE; static final String DEFAULT_USER_NUM_FORMAT; static final int DEFAULT_INITIAL_BYTE_STREAM_SIZE; static final String BIN_MINUTE_INTERVAL; static final String BIN_HOUR_INTERVAL; static final String BIN_DAY_INTERVAL; static final String BIN_WEEK_INTERVAL; static final String BIN_MONTH_INTERVAL; static final String BIN_YEAR_INTERVAL; static final String BIN_UNIQUE_INTERVAL; static final String DEFAULT_DATE_BIN_INTERVAL; static final String DEFAULT_DATE_BIN_FORMAT; static final String DEFAULT_SCRIPT_LANGUAGE; }### Answer:
@Test public void testGetUrl() { DataTypeInfo dataType = new DefaultDataTypeInfo(null, null, "typeKey", null, null, true); dataType.addTag(".es-url=http: dataType.addTag(".es-index=layer=layer1&index=index1", null); Assert.assertEquals("http: }
|
### Question:
DataTypeChecker { public static boolean isFeatureType(DataTypeInfo dataType) { boolean isFeature = ((dataType == null) ? false : dataType.getBasicVisualizationInfo() != null && dataType.getBasicVisualizationInfo().usesDataElements() || dataType.getMapVisualizationInfo() != null && dataType.getMapVisualizationInfo().usesMapDataElements()); return isFeature; } private DataTypeChecker(); static boolean isFeatureType(DataTypeInfo dataType); }### Answer:
@Test public void testIsFeatureDataType() { EasyMockSupport support = new EasyMockSupport(); List<DataTypeInfo> dataTypes = createDataTypes(support); support.replayAll(); int index = 1; for (DataTypeInfo dataType : dataTypes) { if (index % 3 == 0) { assertTrue(DataTypeChecker.isFeatureType(dataType)); } else { assertFalse(DataTypeChecker.isFeatureType(dataType)); } index++; } support.verifyAll(); }
|
### Question:
ElementData { public MapGeometrySupport getMapGeometrySupport() { return myMapGeometrySupport; } ElementData(); ElementData(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); boolean found(); Long getID(); MapGeometrySupport getMapGeometrySupport(); MetaDataProvider getMetaDataProvider(); TimeSpan getTimeSpan(); VisualizationState getVisualizationState(); final void updateValues(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); }### Answer:
@Test public void testGetMapGeometrySupport() { assertEquals(myMapGeometrySupport, myTestObject.getMapGeometrySupport()); }
|
### Question:
DefaultDataGroupAndTypeFactory implements DataGroupAndTypeFactory { @Override public DefaultDataTypeInfo createType(Toolbox toolbox, String providerType, String id, String typeName, String layerName) { return new DefaultDataTypeInfo(toolbox, providerType, id, typeName, layerName, false); } @Override DefaultDataGroupInfo createGroup(Toolbox toolbox, String providerType, String folderName,
Consumer<DataGroupInfo> deleteListener); @Override DefaultDataTypeInfo createType(Toolbox toolbox, String providerType, String id, String typeName, String layerName); }### Answer:
@Test public void testCreateType() { EasyMockSupport support = new EasyMockSupport(); MantleToolbox mantle = createMantle(support); Toolbox toolbox = createToolbox(support, mantle); support.replayAll(); DefaultDataGroupAndTypeFactory factory = new DefaultDataGroupAndTypeFactory(); DataTypeInfo type = factory.createType(toolbox, ourProviderType, ourTypeKey, "my type name", "My layer name"); assertEquals(ourProviderType, type.getSourcePrefix()); assertEquals(ourTypeKey, type.getTypeKey()); assertEquals("My layer name", type.getDisplayName()); assertEquals("my type name", type.getTypeName()); assertFalse(type.providerFiltersMetaData()); support.verifyAll(); }
|
### Question:
ElementData { public MetaDataProvider getMetaDataProvider() { return myMetaDataProvider; } ElementData(); ElementData(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); boolean found(); Long getID(); MapGeometrySupport getMapGeometrySupport(); MetaDataProvider getMetaDataProvider(); TimeSpan getTimeSpan(); VisualizationState getVisualizationState(); final void updateValues(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); }### Answer:
@Test public void testGetMetaDataProvider() { assertEquals(myMetaDataProvider, myTestObject.getMetaDataProvider()); }
|
### Question:
ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public int size() { return myQueue.size(); } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer:
@Test public void testSizeZero() { assertEquals(0, myObservableBuffer.size()); }
|
### Question:
ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public boolean offer(final E element) { boolean changed = false; synchronized (myQueue) { beginChange(); while (remainingCapacity() < 1) { final E removedElement = myQueue.removeFirst(); if (removedElement != null) { nextRemove(0, removedElement); } } changed = myQueue.offer(element); if (changed) { nextAdd(myQueue.size() - 1, myQueue.size()); } endChange(); } return changed; } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer:
@Test public void testOfferUnderCapacity() { myObservableBuffer.offer("one"); myObservableBuffer.offer("two"); myObservableBuffer.offer("three"); myObservableBuffer.offer("four"); Object[] array = myObservableBuffer.toArray(); assertEquals(4, array.length); assertEquals("one", array[0]); assertEquals("two", array[1]); assertEquals("three", array[2]); assertEquals("four", array[3]); }
@Test public void testOfferOverCapacity() { myObservableBuffer.offer("one"); myObservableBuffer.offer("two"); myObservableBuffer.offer("three"); myObservableBuffer.offer("four"); myObservableBuffer.offer("five"); myObservableBuffer.offer("six"); myObservableBuffer.offer("seven"); Object[] array = myObservableBuffer.toArray(); assertEquals(5, array.length); assertEquals("three", array[0]); assertEquals("four", array[1]); assertEquals("five", array[2]); assertEquals("six", array[3]); assertEquals("seven", array[4]); }
|
### Question:
ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public boolean add(final E e) { if (remainingCapacity() == 0) { throw new IllegalStateException("Queue full"); } boolean changed = false; synchronized (myQueue) { beginChange(); try { if (myQueue.add(e)) { changed = true; nextAdd(myQueue.size() - 1, myQueue.size()); } } finally { endChange(); } } return changed; } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer:
@Test public void testAddOne() { myObservableBuffer.add("one"); Object[] array = myObservableBuffer.toArray(); assertEquals(1, array.length); assertEquals("one", array[0]); }
@Test public void testAddUnderCapacity() { myObservableBuffer.add("one"); myObservableBuffer.add("two"); myObservableBuffer.add("three"); myObservableBuffer.add("four"); Object[] array = myObservableBuffer.toArray(); assertEquals(4, array.length); assertEquals("one", array[0]); assertEquals("two", array[1]); assertEquals("three", array[2]); assertEquals("four", array[3]); }
@Test(expected = IllegalStateException.class) public void testAddOverCapacity() { myObservableBuffer.add("one"); myObservableBuffer.add("two"); myObservableBuffer.add("three"); myObservableBuffer.add("four"); myObservableBuffer.add("five"); myObservableBuffer.add("six"); myObservableBuffer.add("seven"); }
|
### Question:
ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public E poll() { E removedItem = null; synchronized (myQueue) { beginChange(); try { removedItem = myQueue.pollLast(); nextRemove(0, removedItem); } finally { endChange(); } } return removedItem; } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer:
@Test public void testPollEmpty() { assertNull(myObservableBuffer.poll()); }
|
### Question:
ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public E element() { if (myQueue.isEmpty()) { throw new NoSuchElementException(); } return myQueue.peekLast(); } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer:
@Test(expected = NoSuchElementException.class) public void testElementEmpty() { myObservableBuffer.element(); }
|
### Question:
ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public E peek() { return myQueue.peekLast(); } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer:
@Test public void testPeekEmpty() { assertNull(myObservableBuffer.peek()); }
|
### Question:
ObservableBuffer extends ObservableListBase<E> implements Queue<E> { @Override public E get(final int index) { if (index < 0 || index >= myQueue.size()) { throw new IndexOutOfBoundsException(0); } E item = null; synchronized (myQueue) { final Iterator<E> iterator = myQueue.iterator(); for (int i = 0; i < index; i++) { iterator.next(); } item = iterator.next(); } return item; } ObservableBuffer(final int capacity); @Override boolean offer(final E element); @Override boolean add(final E e); @Override E remove(); @Override E poll(); @Override E element(); @Override E peek(); @Override E get(final int index); @Override int size(); @Override void clear(); }### Answer:
@Test(expected = IndexOutOfBoundsException.class) public void testGetIntNegative() { myObservableBuffer.get(-1); }
@Test(expected = IndexOutOfBoundsException.class) public void testGetIntZeroEmpty() { myObservableBuffer.get(0); }
|
### Question:
LazyMap extends WrappedMap<K, V> { @Override public V put(K key, V value) { synchronized (getMap()) { return super.put(key, value); } } LazyMap(Map<K, V> map, Class<? extends K> keyType); LazyMap(Map<K, V> map, Class<? extends K> keyType, Factory<? super K, ? extends V> factory); static LazyMap<K, Collection<E>> create(Map<K, Collection<E>> map, Class<K> keyType,
CollectionProvider<E> provider); static LazyMap<K, List<E>> create(Map<K, List<E>> map, Class<K> keyType, ListProvider<E> provider); static LazyMap<K, Set<E>> create(Map<K, Set<E>> map, Class<K> keyType, SetProvider<E> provider); static LazyMap<K, V> create(Map<K, V> map, Class<? extends K> keyType); static LazyMap<K, V> create(Map<K, V> map, Class<? extends K> keyType, Factory<? super K, ? extends V> factory); static Factory<Object, Collection<V>> providerToFactory(final CollectionProvider<V> provider); static Factory<Object, List<V>> providerToFactory(final ListProvider<V> provider); static Factory<Object, Set<V>> providerToFactory(final SetProvider<V> provider); @Override V get(Object key); V get(Object key, Factory<? super K, ? extends V> factory); V getIfExists(Object key); @Override V put(K key, V value); @Override void putAll(Map<? extends K, ? extends V> m); }### Answer:
@Test public void testPut() { Assert.assertEquals("1", myLazyMap.put(Integer.valueOf(1), ONE)); Assert.assertEquals(ONE, myWrappedMap.get(Integer.valueOf(1))); Assert.assertEquals(NULL_VALUE1, myLazyMap.put(null, NULL_VALUE2)); Assert.assertEquals(NULL_VALUE2, myWrappedMap.get(null)); }
|
### Question:
StreamUtilities { public static <T> boolean anyMatch(Iterable<? extends T> input, Predicate<? super T> filter) { for (T in : input) { if (filter.test(in)) { return true; } } return false; } private StreamUtilities(); static boolean anyMatch(Iterable<? extends T> input, Predicate<? super T> filter); static List<T> filter(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static T[] filter(T[] input, Predicate<? super T> predicate); static T filterOne(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static Stream<T> filterDowncast(Stream<?> input, Class<T> type); static Collection<R> map(Collection<? extends T> input, Function<? super T, ? extends R> mapper,
CollectionProvider<R> collectionProvider); @SuppressWarnings("unchecked") static List<R> map(Iterable<? extends T> input, Function<? super T, ? extends R> mapper); }### Answer:
@Test public void testAnyMatch() { boolean result; result = StreamUtilities.anyMatch(Collections.emptyList(), null); Assert.assertFalse(result); result = StreamUtilities.anyMatch(INPUT, new Predicate<String>() { @Override public boolean test(String s) { return s.charAt(0) == 'A'; } }); Assert.assertTrue(result); result = StreamUtilities.anyMatch(INPUT, new Predicate<String>() { @Override public boolean test(String s) { return s.charAt(0) == 'C'; } }); Assert.assertFalse(result); }
|
### Question:
StreamUtilities { public static <T> T filterOne(Collection<? extends T> input, Predicate<? super T> predicate) { return predicate != null ? input.stream().filter(predicate).findFirst().orElse(null) : null; } private StreamUtilities(); static boolean anyMatch(Iterable<? extends T> input, Predicate<? super T> filter); static List<T> filter(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static T[] filter(T[] input, Predicate<? super T> predicate); static T filterOne(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static Stream<T> filterDowncast(Stream<?> input, Class<T> type); static Collection<R> map(Collection<? extends T> input, Function<? super T, ? extends R> mapper,
CollectionProvider<R> collectionProvider); @SuppressWarnings("unchecked") static List<R> map(Iterable<? extends T> input, Function<? super T, ? extends R> mapper); }### Answer:
@Test public void testFilterOne() { String expected; String actual; expected = null; actual = StreamUtilities.filterOne(Collections.<String>emptyList(), null); Assert.assertEquals(expected, actual); expected = "Apple"; actual = StreamUtilities.filterOne(INPUT, new Predicate<String>() { @Override public boolean test(String s) { return s.charAt(0) == 'A'; } }); Assert.assertEquals(expected, actual); actual = StreamUtilities.filterOne(INPUT, new Predicate<Object>() { @Override public boolean test(Object o) { return o.toString().charAt(0) == 'A'; } }); Assert.assertEquals(expected, actual); }
|
### Question:
StreamUtilities { @SuppressWarnings("unchecked") public static <T> Stream<T> filterDowncast(Stream<?> input, Class<T> type) { return input.filter(obj -> type.isInstance(obj)).map(obj -> (T)obj); } private StreamUtilities(); static boolean anyMatch(Iterable<? extends T> input, Predicate<? super T> filter); static List<T> filter(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static T[] filter(T[] input, Predicate<? super T> predicate); static T filterOne(Collection<? extends T> input, Predicate<? super T> predicate); @SuppressWarnings("unchecked") static Stream<T> filterDowncast(Stream<?> input, Class<T> type); static Collection<R> map(Collection<? extends T> input, Function<? super T, ? extends R> mapper,
CollectionProvider<R> collectionProvider); @SuppressWarnings("unchecked") static List<R> map(Iterable<? extends T> input, Function<? super T, ? extends R> mapper); }### Answer:
@Test public void testFilterDowcast() { List<Number> input = Arrays.asList(Integer.valueOf(1), Long.valueOf(2)); Assert.assertEquals(Arrays.asList(Integer.valueOf(1)), StreamUtilities.filterDowncast(input.stream(), Integer.class).collect(Collectors.toList())); }
|
### Question:
TinySet extends AbstractProxySet<E> { @Override public void clear() { mySet = Collections.emptySet(); } static Set<T> add(Set<T> input, T e); static Set<T> addAll(Set<T> input, Collection<? extends T> c); static Set<T> remove(Set<T> set, Object o); static Set<T> removeAll(Set<T> set, Collection<T> c); static Set<T> retainAll(Set<T> mySet, Collection<?> c); @Override boolean add(E e); @Override boolean addAll(Collection<? extends E> c); @Override void clear(); @Override boolean remove(Object o); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); }### Answer:
@Test public void testClear() { TinySet<Object> set = new TinySet<>(); set.clear(); checkSize0(set); Assert.assertTrue(set.add(TEST_OBJ1)); checkSize1(set); set.clear(); checkSize0(set); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2, TEST_OBJ3))); checkSizeN(set, 3); set.clear(); checkSize0(set); }
|
### Question:
TinySet extends AbstractProxySet<E> { public static <T> Set<T> remove(Set<T> set, Object o) { if (set.isEmpty()) { return set; } else if (set.size() == 1) { if (set.contains(o)) { return Collections.emptySet(); } return set; } else { if (set.remove(o)) { return resetStorage(set); } return set; } } static Set<T> add(Set<T> input, T e); static Set<T> addAll(Set<T> input, Collection<? extends T> c); static Set<T> remove(Set<T> set, Object o); static Set<T> removeAll(Set<T> set, Collection<T> c); static Set<T> retainAll(Set<T> mySet, Collection<?> c); @Override boolean add(E e); @Override boolean addAll(Collection<? extends E> c); @Override void clear(); @Override boolean remove(Object o); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); }### Answer:
@Test public void testRemove() { TinySet<Object> set = new TinySet<>(); Assert.assertFalse(set.remove(TEST_OBJ2)); checkSize0(set); Assert.assertTrue(set.add(TEST_OBJ1)); checkSize1(set); Assert.assertFalse(set.remove(TEST_OBJ2)); checkSize1(set); Assert.assertTrue(set.remove(TEST_OBJ1)); checkSize0(set); Assert.assertFalse(set.remove(TEST_OBJ1)); checkSize0(set); Assert.assertTrue(set.addAll(Arrays.asList(TEST_OBJ1, TEST_OBJ2, TEST_OBJ3))); checkSizeN(set, 3); Assert.assertTrue(set.remove(TEST_OBJ1)); checkSizeN(set, 2); Assert.assertFalse(set.remove(TEST_OBJ1)); checkSizeN(set, 2); Assert.assertTrue(set.remove(TEST_OBJ3)); checkSize1(set); Assert.assertTrue(set.remove(TEST_OBJ2)); checkSize0(set); }
|
### Question:
NoEffectPredicate implements Predicate<T> { @Override public boolean test(T input) { return Objects.equals(myFunction.apply(input), input); } NoEffectPredicate(Function<? super T, ? extends T> function); @Override boolean test(T input); }### Answer:
@Test public void test() { Assert.assertTrue( new NoEffectPredicate<Boolean>(new ConstantFunction<Boolean, Boolean>(Boolean.TRUE)).test(Boolean.TRUE)); Assert.assertFalse( new NoEffectPredicate<Boolean>(new ConstantFunction<Boolean, Boolean>(Boolean.TRUE)).test(Boolean.FALSE)); Assert.assertFalse(new NoEffectPredicate<Boolean>(new ConstantFunction<Boolean, Boolean>(Boolean.TRUE)).test(null)); Assert.assertFalse(new NoEffectPredicate<Boolean>(new ConstantFunction<Boolean, Boolean>(null)).test(Boolean.TRUE)); }
|
### Question:
ScaledImageController implements Observer { public void close() { myModel.deleteObserver(this); } ScaledImageController(ScaledImageModel model); void close(); @Override void update(Observable o, Object arg); }### Answer:
@Test public void testClose() { ScaledImageModel model = new ScaledImageModel(); ScaledImageController controller = new ScaledImageController(model); assertEquals(1, model.countObservers()); controller.close(); assertEquals(0, model.countObservers()); }
|
### Question:
BoundingBoxModel extends Observable { public void setBoundingBox(Collection<LineSegment2d> boundingBox) { myBoundingBox.clear(); myBoundingBox.addAll(boundingBox); setChanged(); notifyObservers(BOUNDING_BOX_PROP); } Collection<LineSegment2d> getBoundingBox(); void setBoundingBox(Collection<LineSegment2d> boundingBox); static final String BOUNDING_BOX_PROP; }### Answer:
@Test public void testSetBoundingBox() { BoundingBoxModel model = new BoundingBoxModel(); List<LineSegment2d> boundingBox = New.list(new LineSegment2d(new Vector2d(0, 0), new Vector2d(10, 10))); EasyMockSupport support = new EasyMockSupport(); Observer observer = createObserver(support, model); support.replayAll(); model.addObserver(observer); model.setBoundingBox(boundingBox); assertEquals(boundingBox.get(0), model.getBoundingBox().iterator().next()); support.verifyAll(); }
|
### Question:
ColorUtilities { public static boolean isEqual(Color c1, Color c2) { return Utilities.sameInstance(c1, c2) || c1 != null && c1.equals(c2); } private ColorUtilities(); static Color blendColors(Color color1, Color color2); static Color brighten(Color input, double factor); static Color convertFromColorString(String color); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex); static Color convertFromHexString(String color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex); static String convertToHexString(Color color, int redIndex, int greenIndex, int blueIndex, int alphaIndex); static String convertToRGBAColorString(Color aColor); static Color darken(Color input, double factor); static Color lighten(Color color); static int getBrightness(Color color); static Color getContrastingColor(Color color); static Color getAlternateColor(Color color, int shift); static boolean isEqual(Color c1, Color c2); static boolean isEqualIgnoreAlpha(Color c1, Color c2); static Color opacitizeColor(Color startingColor, float alpha); static Color opacitizeColor(Color startingColor, int alpha); static final int COLOR_COMPONENT_MAX_VALUE; }### Answer:
@Test public void testIsEqual() { Assert.assertTrue(ColorUtilities.isEqual(Color.RED, Color.RED)); Assert.assertTrue(ColorUtilities.isEqual(Color.RED, new Color(255, 0, 0, 255))); Assert.assertFalse(ColorUtilities.isEqual(Color.RED, new Color(255, 0, 0, 254))); Assert.assertTrue(ColorUtilities.isEqual(null, null)); Assert.assertFalse(ColorUtilities.isEqual(Color.RED, null)); Assert.assertFalse(ColorUtilities.isEqual(null, Color.RED)); }
|
### Question:
RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { public boolean containsValue(long value) { return value >= myStartValue && value <= myEndValue; } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer:
@Test public void testContainsValue() { RangeLongBlock aBlock = new RangeLongBlock(3, 7); Assert.assertTrue(aBlock.containsValue(3)); Assert.assertTrue(aBlock.containsValue(4)); Assert.assertTrue(aBlock.containsValue(5)); Assert.assertTrue(aBlock.containsValue(6)); Assert.assertTrue(aBlock.containsValue(7)); Assert.assertFalse(aBlock.containsValue(2)); Assert.assertFalse(aBlock.containsValue(8)); }
|
### Question:
RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { @Override public Iterator<Long> iterator() { return new BlockLongIterator(this); } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer:
@Test public void testIterator() { RangeLongBlock aBlock = new RangeLongBlock(1, 5); Iterator<Long> itr = aBlock.iterator(); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(1, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(2, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(3, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(4, itr.next().longValue()); Assert.assertTrue(itr.hasNext()); Assert.assertEquals(5, itr.next().longValue()); Assert.assertTrue(!itr.hasNext()); TestHelper.testNoSuchElement(itr); TestHelper.testUnsupportedRemove(itr); }
|
### Question:
BoundingBoxOverlay implements Overlay { @Override public void close() { myController.close(); } BoundingBoxOverlay(MapModel mapModel); @Override void close(); @Override void draw(Graphics graphics); }### Answer:
@Test public void testClose() { MapModel mapModel = new MapModel(); BoundingBoxOverlay overlay = new BoundingBoxOverlay(mapModel); assertEquals(1, mapModel.countObservers()); overlay.close(); assertEquals(0, mapModel.countObservers()); }
|
### Question:
RangeLongBlock implements Comparable<RangeLongBlock>, Iterable<Long> { public int size() { return (int)(myEndValue - myStartValue) + 1; } RangeLongBlock(long value); RangeLongBlock(long startValue, long endValue); RangeLongBlock(RangeLongBlock other); static List<RangeLongBlock> createRangeLongBlocks(Collection<? extends Long> values); static List<RangeLongBlock> createRangeLongBlocks(long[] values); static List<RangeLongBlock> createRangeLongBlocks(Long[] values); static List<RangeLongBlock> createSubBlocksByRemovingValue(RangeLongBlock block, long valueToRemove); static boolean isContiguous(long[] values); static RangeLongBlock merge(RangeLongBlock one, RangeLongBlock two); boolean borders(long value); boolean borders(RangeLongBlock block); @Override int compareTo(RangeLongBlock o); boolean containsValue(long value); @Override boolean equals(Object obj); boolean formsContiguousRange(RangeLongBlock other); long getEnd(); RangeRelationType getRelation(RangeLongBlock block); long getStart(); @Override int hashCode(); RangeLongBlock intersection(RangeLongBlock other); boolean isAfter(RangeLongBlock other); boolean isBefore(RangeLongBlock other); @Override Iterator<Long> iterator(); boolean overlaps(RangeLongBlock other); int size(); @Override String toString(); }### Answer:
@Test public void testSizeFunction() { RangeLongBlock aBlock = new RangeLongBlock(1, 10); Assert.assertTrue(aBlock.size() == 10); }
|
### Question:
BoundingBoxController implements Observer { public void close() { myModel.deleteObserver(this); myMapModel.deleteObserver(this); } BoundingBoxController(MapModel mapModel, BoundingBoxModel model); void close(); @Override void update(Observable o, Object arg); }### Answer:
@Test public void testClose() { MapModel mapModel = new MapModel(); mapModel.setHeightWidth(400, 400); BoundingBoxModel model = new BoundingBoxModel(); BoundingBoxController controller = new BoundingBoxController(mapModel, model); assertEquals(1, mapModel.countObservers()); assertEquals(1, model.countObservers()); controller.close(); assertEquals(0, mapModel.countObservers()); assertEquals(0, model.countObservers()); }
|
### Question:
MapModel extends Observable { public void setHeightWidth(int height, int width) { if (myHeight != height || myWidth != width) { myHeight = height; myWidth = width; setChanged(); notifyObservers(SIZE_PROP); } } int getHeight(); Quadrilateral<GeographicPosition> getRegion(); ScreenBoundingBox getViewport(); int getWidth(); void setHeightWidth(int height, int width); void setRegion(Quadrilateral<GeographicPosition> region); void setViewport(ScreenBoundingBox viewport); static final String REGION_PROP; static final String SIZE_PROP; }### Answer:
@Test public void testSetHeightWidth() { EasyMockSupport support = new EasyMockSupport(); MapModel model = new MapModel(); Observer observer = createObserver(support, model, MapModel.SIZE_PROP, 3); model.addObserver(observer); support.replayAll(); model.setHeightWidth(100, 200); assertEquals(100, model.getHeight()); assertEquals(200, model.getWidth()); model.setHeightWidth(100, 200); model.setHeightWidth(200, 200); assertEquals(200, model.getHeight()); assertEquals(200, model.getWidth()); model.setHeightWidth(200, 100); assertEquals(200, model.getHeight()); assertEquals(100, model.getWidth()); support.verifyAll(); }
|
### Question:
ElementData { public TimeSpan getTimeSpan() { return myTimeSpan; } ElementData(); ElementData(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); boolean found(); Long getID(); MapGeometrySupport getMapGeometrySupport(); MetaDataProvider getMetaDataProvider(); TimeSpan getTimeSpan(); VisualizationState getVisualizationState(); final void updateValues(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); }### Answer:
@Test public void testGetTimeSpan() { assertEquals(myTimeSpan, myTestObject.getTimeSpan()); }
|
### Question:
MapModel extends Observable { public void setRegion(Quadrilateral<GeographicPosition> region) { myRegion = region; setChanged(); notifyObservers(REGION_PROP); } int getHeight(); Quadrilateral<GeographicPosition> getRegion(); ScreenBoundingBox getViewport(); int getWidth(); void setHeightWidth(int height, int width); void setRegion(Quadrilateral<GeographicPosition> region); void setViewport(ScreenBoundingBox viewport); static final String REGION_PROP; static final String SIZE_PROP; }### Answer:
@Test public void testSetRegion() { EasyMockSupport support = new EasyMockSupport(); GeographicBoundingBox region = new GeographicBoundingBox(LatLonAlt.createFromDegrees(-45d, -90d), LatLonAlt.createFromDegrees(0, 0)); MapModel model = new MapModel(); Observer observer = createObserver(support, model, MapModel.REGION_PROP, 1); model.addObserver(observer); support.replayAll(); model.setRegion(region); assertEquals(region, model.getRegion()); support.verifyAll(); }
|
### Question:
Aggregator { public void addItem(T item) { if (myBatchSize > 1) { myItems.add(item); if (myItems.size() >= myBatchSize) { processAll(); } } else { myProcessor.accept(Collections.singletonList(item)); } } Aggregator(int batchSize, Consumer<List<T>> processor); static void process(Collection<? extends T> items, int batchSize, Consumer<List<T>> processor); void addItem(T item); void addItems(Collection<? extends T> items); void processAll(); }### Answer:
@Test public void testAggregation() { StringJoiner joiner = new StringJoiner("-"); Aggregator<String> aggregator = new Aggregator<>(3, items -> items.forEach(joiner::add)); aggregator.addItem("hey"); Assert.assertEquals("", joiner.toString()); aggregator.addItem("there"); Assert.assertEquals("", joiner.toString()); aggregator.addItem("dude"); Assert.assertEquals("hey-there-dude", joiner.toString()); }
@Test public void testNoAggregation() { StringJoiner joiner = new StringJoiner("-"); Aggregator<String> aggregator = new Aggregator<>(1, items -> items.forEach(joiner::add)); aggregator.addItem("hey"); Assert.assertEquals("hey", joiner.toString()); aggregator.addItem("there"); Assert.assertEquals("hey-there", joiner.toString()); }
|
### Question:
URLEncodingUtilities { public static URL encodeURL(URL url) { URL encodedURL = null; if (url != null) { UrlBuilder builder = new UrlBuilder(url); builder.setQueryParameters(encodeQueryParameters(builder.getQueryParameters())); try { encodedURL = builder.toURL(); } catch (MalformedURLException e) { encodedURL = url; } } return encodedURL; } private URLEncodingUtilities(); static URL encodeURL(URL url); }### Answer:
@Test public void testEncodeURL() throws MalformedURLException { URL input = new URL("http: URL expected = new URL("http: URL actual = URLEncodingUtilities.encodeURL(input); Assert.assertEquals(expected.toString(), actual.toString()); }
@Test public void testEncodeURLNoQuery() throws MalformedURLException { URL input = new URL("http: URL actual = URLEncodingUtilities.encodeURL(input); Assert.assertEquals(input.toString(), actual.toString()); }
@Test public void testEncodeURLNull() { Assert.assertNull(URLEncodingUtilities.encodeURL(null)); }
|
### Question:
UrlBuilder { public void addPath(String path) { myPath = StringUtilities.concat(myPath, ensureStartsWith(path, '/')); } UrlBuilder(); UrlBuilder(String url); UrlBuilder(URL url); void addPath(String path); void addQuery(String query); String getHost(); String getPath(); int getPort(); String getProtocol(); String getQuery(); Map<String, String> getQueryParameters(); String getRef(); void setHost(String host); void setPath(String path); void setPort(int port); void setProtocol(String protocol); void setQuery(String query); void setQueryParameters(Map<String, String> queryParameters); void setRef(String ref); void setUrl(URL url); @Override String toString(); URL toURL(); }### Answer:
@Test public void testAddPath() { URL input = createUrl("http: URL expected = createUrl("http: UrlBuilder builder = new UrlBuilder(input); builder.addPath("more"); try { Assert.assertEquals(expected.toString(), builder.toURL().toString()); } catch (MalformedURLException e) { Assert.fail(e.getMessage()); } }
|
### Question:
BackgroundModel extends Observable { public void add(Collection<TileGeometry> geometry) { myGeometries.addAll(geometry); setChanged(); notifyObservers(GEOMETRIES_PROP); } void add(Collection<TileGeometry> geometry); Collection<TileGeometry> getGeometries(); List<Double> getGeometryScaleFactors(); void remove(Collection<TileGeometry> geometry); static final String GEOMETRIES_PROP; }### Answer:
@Test public void testAdd() { EasyMockSupport support = new EasyMockSupport(); BackgroundModel model = new BackgroundModel(); Observer observer = createObserver(support, model); support.replayAll(); model.addObserver(observer); TileGeometry[] geometries = createGeometries(); model.add(New.list(geometries)); assertEquals(2, model.getGeometries().size()); assertTrue(model.getGeometries().contains(geometries[0])); assertTrue(model.getGeometries().contains(geometries[1])); support.verifyAll(); }
|
### Question:
UrlBuilder { public void addQuery(String query) { if (!StringUtils.isBlank(query)) { getQueryParameters().putAll(getQueryParameters(query)); myQuery = null; } } UrlBuilder(); UrlBuilder(String url); UrlBuilder(URL url); void addPath(String path); void addQuery(String query); String getHost(); String getPath(); int getPort(); String getProtocol(); String getQuery(); Map<String, String> getQueryParameters(); String getRef(); void setHost(String host); void setPath(String path); void setPort(int port); void setProtocol(String protocol); void setQuery(String query); void setQueryParameters(Map<String, String> queryParameters); void setRef(String ref); void setUrl(URL url); @Override String toString(); URL toURL(); }### Answer:
@Test public void testAddQuery() { URL input = createUrl("http: URL expected = createUrl("http: UrlBuilder builder = new UrlBuilder(input); builder.addQuery("e=f"); try { Assert.assertEquals(expected.toString(), builder.toURL().toString()); } catch (MalformedURLException e) { Assert.fail(e.getMessage()); } }
|
### Question:
UrlBuilder { public void setPath(String path) { myPath = ensureStartsWith(path, '/'); } UrlBuilder(); UrlBuilder(String url); UrlBuilder(URL url); void addPath(String path); void addQuery(String query); String getHost(); String getPath(); int getPort(); String getProtocol(); String getQuery(); Map<String, String> getQueryParameters(); String getRef(); void setHost(String host); void setPath(String path); void setPort(int port); void setProtocol(String protocol); void setQuery(String query); void setQueryParameters(Map<String, String> queryParameters); void setRef(String ref); void setUrl(URL url); @Override String toString(); URL toURL(); }### Answer:
@Test public void testSetPath() { URL input = createUrl("http: URL expected = createUrl("http: UrlBuilder builder = new UrlBuilder(input); builder.setPath("something/getKml.pl"); try { Assert.assertEquals(expected.toString(), builder.toURL().toString()); } catch (MalformedURLException e) { Assert.fail(e.getMessage()); } builder.setPath("/something/getKml.pl"); try { Assert.assertEquals(expected.toString(), builder.toURL().toString()); } catch (MalformedURLException e) { Assert.fail(e.getMessage()); } }
|
### Question:
UrlBuilder { public URL toURL() throws MalformedURLException { return new URL(toString()); } UrlBuilder(); UrlBuilder(String url); UrlBuilder(URL url); void addPath(String path); void addQuery(String query); String getHost(); String getPath(); int getPort(); String getProtocol(); String getQuery(); Map<String, String> getQueryParameters(); String getRef(); void setHost(String host); void setPath(String path); void setPort(int port); void setProtocol(String protocol); void setQuery(String query); void setQueryParameters(Map<String, String> queryParameters); void setRef(String ref); void setUrl(URL url); @Override String toString(); URL toURL(); }### Answer:
@Test public void testToURL() { URL input = createUrl("http: UrlBuilder builder = new UrlBuilder(input); Assert.assertEquals("http", builder.getProtocol()); Assert.assertEquals("www.blah.com", builder.getHost()); Assert.assertEquals(8080, builder.getPort()); Assert.assertEquals("/something/getKml.pl", builder.getPath()); Assert.assertEquals("a=b&c=d", builder.getQuery()); Assert.assertEquals("ref", builder.getRef()); Assert.assertEquals("b", builder.getQueryParameters().get("a")); try { Assert.assertEquals(input.toString(), builder.toURL().toString()); } catch (MalformedURLException e) { Assert.fail(e.getMessage()); } }
|
### Question:
UrlUtilities { public static boolean isFile(URL url) { boolean isFile = false; String protocol = url.getProtocol(); if ("file".equalsIgnoreCase(protocol) || "jar".equalsIgnoreCase(protocol)) { isFile = true; } return isFile; } private UrlUtilities(); static String getBaseURL(URL u); static String getBaseURL(String u); static ThreeTuple<String, String, Integer> getProtocolHostPort(String url, int defaultPort); static boolean isFragmentPresent(URL url); static String getFragment(URL url); static boolean isFile(URL url); static URL toURL(String urlString); static URL toURLNew(String urlOrPathString); static String concatUrlFragments(String... fragments); }### Answer:
@Test public void testIsFile() throws MalformedURLException { URL fileUrl = new URL("file:/C:/test.txt"); URL javaFileUrl = new URL("jar:file:/C:/Program%20Files/OpenSphere/OpenSphere-KML-plugin.jar!" + "/images/maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png"); URL httpUrl = new URL("http: assertTrue(UrlUtilities.isFile(fileUrl)); assertTrue(UrlUtilities.isFile(javaFileUrl)); assertFalse(UrlUtilities.isFile(httpUrl)); }
|
### Question:
UrlUtilities { public static URL toURLNew(String urlOrPathString) { URL url = null; if (StringUtils.isNotEmpty(urlOrPathString)) { String urlString = hasValidProtocol(urlOrPathString) ? fixFileProtocol(urlOrPathString) : addFileProtocol(urlOrPathString); url = toURL(urlString); } return url; } private UrlUtilities(); static String getBaseURL(URL u); static String getBaseURL(String u); static ThreeTuple<String, String, Integer> getProtocolHostPort(String url, int defaultPort); static boolean isFragmentPresent(URL url); static String getFragment(URL url); static boolean isFile(URL url); static URL toURL(String urlString); static URL toURLNew(String urlOrPathString); static String concatUrlFragments(String... fragments); }### Answer:
@SuppressFBWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME") @Test public void testToURLNew() throws MalformedURLException { assertEquals(null, UrlUtilities.toURLNew(null)); assertEquals(null, UrlUtilities.toURLNew("")); assertEquals(new URL("http: assertEquals(new URL("file: assertEquals(new URL("file: assertEquals(new URL("file: assertEquals(new URL("file: assertEquals(new URL("file: assertEquals(new URL("file: }
|
### Question:
InlineExecutorService extends AbstractExecutorService { @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); while (nanos > 0) { myLock.lock(); try { if (isTerminated()) { return true; } nanos = myCondition.awaitNanos(nanos); } finally { myLock.unlock(); } } return isTerminated(); } InlineExecutorService(); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override final void execute(Runnable command); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override void shutdown(); @Override List<Runnable> shutdownNow(); }### Answer:
@Test public void testAwaitTermination() throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(2); final CountDownLatch latch = new CountDownLatch(2); final AtomicBoolean flag1 = new AtomicBoolean(); final AtomicBoolean flag2 = new AtomicBoolean(); final ExecutorService service = new InlineExecutorService(); pool.execute(new TestRunnable(service, latch, flag1, 100L)); pool.execute(new TestRunnable(service, latch, flag2, 100L)); latch.await(); Assert.assertFalse(service.isShutdown()); service.shutdown(); Assert.assertTrue(service.isShutdown()); Assert.assertFalse(service.isTerminated()); Assert.assertFalse(service.awaitTermination(1, TimeUnit.MILLISECONDS)); Assert.assertFalse(flag1.get()); Assert.assertFalse(flag2.get()); Assert.assertTrue(service.awaitTermination(1000, TimeUnit.MILLISECONDS)); Assert.assertTrue(service.isShutdown()); Assert.assertTrue(service.isTerminated()); Assert.assertTrue(flag1.get()); Assert.assertTrue(flag2.get()); }
|
### Question:
BackgroundModel extends Observable { public void remove(Collection<TileGeometry> geometry) { for (TileGeometry aGeometry : geometry) { myGeometries.remove(aGeometry); } setChanged(); notifyObservers(GEOMETRIES_PROP); } void add(Collection<TileGeometry> geometry); Collection<TileGeometry> getGeometries(); List<Double> getGeometryScaleFactors(); void remove(Collection<TileGeometry> geometry); static final String GEOMETRIES_PROP; }### Answer:
@Test public void testRemove() { EasyMockSupport support = new EasyMockSupport(); BackgroundModel model = new BackgroundModel(); Observer observer = createObserver(support, model); TileGeometry[] geometries = createGeometries(); model.add(New.list(geometries)); support.replayAll(); model.addObserver(observer); model.remove(New.list(geometries[0])); assertEquals(1, model.getGeometries().size()); assertEquals(geometries[1], model.getGeometries().iterator().next()); support.verifyAll(); }
|
### Question:
InlineExecutorService extends AbstractExecutorService { @Override public void shutdown() { myShutdown = true; } InlineExecutorService(); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override final void execute(Runnable command); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override void shutdown(); @Override List<Runnable> shutdownNow(); }### Answer:
@Test public void testShutdown() { Runnable command = new Runnable() { @Override public void run() { } }; ExecutorService service = new InlineExecutorService(); service.execute(command); Assert.assertFalse(service.isShutdown()); service.shutdown(); Assert.assertTrue(service.isShutdown()); try { service.execute(command); Assert.fail("Command should not have been executed."); } catch (RejectedExecutionException e) { Assert.assertTrue(true); } }
|
### Question:
InlineExecutorService extends AbstractExecutorService { @Override public List<Runnable> shutdownNow() { shutdown(); myLock.lock(); try { for (Thread thread : myThreads) { thread.interrupt(); } } finally { myLock.unlock(); } return Collections.emptyList(); } InlineExecutorService(); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override final void execute(Runnable command); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override void shutdown(); @Override List<Runnable> shutdownNow(); }### Answer:
@Test public void testShutdownNow() throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(2); final CountDownLatch latch = new CountDownLatch(2); final AtomicBoolean flag1 = new AtomicBoolean(); final AtomicBoolean flag2 = new AtomicBoolean(); final ExecutorService service = new InlineExecutorService(); pool.execute(new TestRunnable(service, latch, flag1, 5000L)); pool.execute(new TestRunnable(service, latch, flag2, 5000L)); latch.await(); Assert.assertFalse(service.isShutdown()); service.shutdownNow(); Assert.assertTrue(service.isShutdown()); Assert.assertTrue(service.awaitTermination(1000L, TimeUnit.MILLISECONDS)); Assert.assertTrue(flag1.get()); Assert.assertTrue(flag2.get()); }
|
### Question:
SequentialExecutor implements Executor { @Override public void execute(Runnable command) { boolean needExecute; synchronized (myWorkQueue) { myWorkQueue.add(command); if (myPending) { needExecute = false; } else { needExecute = true; myPending = true; } } if (needExecute) { myExecutor.execute(myTask); } } SequentialExecutor(Executor executor); @Override void execute(Runnable command); }### Answer:
@Test public void test() throws InterruptedException { if (StringUtils.isEmpty(System.getenv("SLOW_MACHINE"))) { final ExecutorService actualExecutor = Executors.newFixedThreadPool(5); SequentialExecutor executor = new SequentialExecutor(actualExecutor); int count = 100; TestRunnable[] arr = new TestRunnable[count]; for (int index = 0; index < count;) { arr[index++] = new TestRunnable(); } for (int index = 0; index < count;) { executor.execute(arr[index++]); } executor.execute(new Runnable() { @Override public void run() { actualExecutor.shutdown(); } }); actualExecutor.awaitTermination(1L, TimeUnit.SECONDS); for (int index = 1; index < count; ++index) { Assert.assertTrue("Runnable at index " + (index - 1) + " did not run", arr[index - 1].getRunStop() > 0L); Assert.assertTrue("Start time at index " + index + " [" + arr[index].getRunStart() + "] should have been >= stop time of index " + (index - 1) + " [" + arr[index - 1].getRunStop() + "]", arr[index].getRunStart() >= arr[index - 1].getRunStop()); } } }
|
### Question:
InlineExecutor implements Executor { @Override public final void execute(Runnable command) { command.run(); } @Override final void execute(Runnable command); }### Answer:
@Test public void testExecute() { final Thread[] result = new Thread[1]; new InlineExecutor().execute(new Runnable() { @Override public void run() { result[0] = Thread.currentThread(); } }); Assert.assertEquals(Thread.currentThread(), result[0]); }
|
### Question:
SharedObjectPool { public T get(T input) { myReadLock.lock(); try { WeakReference<T> ref = myPool.get(input); T poolObject = ref == null ? null : ref.get(); if (poolObject != null) { return poolObject; } } finally { myReadLock.unlock(); } myWriteLock.lock(); try { WeakReference<T> ref = myPool.get(input); T poolObject = ref == null ? null : ref.get(); if (poolObject == null) { myPool.put(input, new WeakReference<>(input)); poolObject = input; } return poolObject; } finally { myWriteLock.unlock(); } } T get(T input); void remove(T obj); void runProcedure(PoolObjectProcedure<T> procedure); int size(); @Override String toString(); }### Answer:
@Test @SuppressWarnings({ "PMD.IntegerInstantiation", "deprecation" }) public void testGet() { SharedObjectPool<Integer> pool = new SharedObjectPool<>(); Integer first = new Integer(1); Integer second = new Integer(1); Integer two = new Integer(2); Assert.assertNotSame(first, second); Assert.assertSame(first, pool.get(first)); Assert.assertSame(first, pool.get(second)); Assert.assertNotSame(second, pool.get(second)); Assert.assertSame(two, pool.get(two)); first = new Integer(1); System.gc(); Assert.assertSame(first, pool.get(first)); }
|
### Question:
SharedObjectPool { public void remove(T obj) { myWriteLock.lock(); try { myPool.remove(obj); } finally { myWriteLock.unlock(); } } T get(T input); void remove(T obj); void runProcedure(PoolObjectProcedure<T> procedure); int size(); @Override String toString(); }### Answer:
@Test @SuppressWarnings({ "PMD.IntegerInstantiation", "deprecation" }) public void testRemove() { SharedObjectPool<Integer> pool = new SharedObjectPool<>(); Integer first = new Integer(1); Integer second = new Integer(1); Assert.assertNotSame(first, second); Assert.assertSame(first, pool.get(first)); Assert.assertSame(first, pool.get(second)); pool.remove(second); Assert.assertNotSame(first, pool.get(second)); Assert.assertSame(second, pool.get(second)); }
|
### Question:
AppendFunction implements Function<String, String> { @Override public String apply(String input) { return new StringBuilder().append(input).append(myString).toString(); } AppendFunction(String string); @Override String apply(String input); }### Answer:
@Test public void testApply() { Assert.assertEquals("Knock knock Who's there?", new AppendFunction("Who's there?").apply("Knock knock ")); }
|
### Question:
ToLowerCaseFunction implements Function<String, String> { @Override public String apply(String input) { return input == null ? null : input.toLowerCase(); } @Override String apply(String input); }### Answer:
@Test public void test() { Assert.assertEquals("one", new ToLowerCaseFunction().apply("one")); Assert.assertEquals("one", new ToLowerCaseFunction().apply("One")); Assert.assertEquals("one", new ToLowerCaseFunction().apply("ONE")); Assert.assertEquals("", new ToLowerCaseFunction().apply("")); Assert.assertNull(new ToLowerCaseFunction().apply(null)); }
|
### Question:
AWTUtilities { public static String encode(Font font) { String style; if (font.isBold()) { style = font.isItalic() ? "bolditalic" : "bold"; } else { style = font.isItalic() ? "italic" : "plain"; } return String.join("-", font.getName(), style, String.valueOf(font.getSize())); } private AWTUtilities(); static int getMaxX(Rectangle rect); static int getMaxY(Rectangle rect); static int getTextXLocation(String text, int anchorX, int pad, int position, Graphics g); static double getTextWidth(String text, Graphics g); static String encode(Font font); static int getFontSize(String encodedFont); }### Answer:
@Test public void testEncode() { Font font = new Font("Arial", Font.BOLD + Font.ITALIC, 14); Assert.assertEquals(font, Font.decode(AWTUtilities.encode(font))); }
|
### Question:
TerrainUtil { public double getElevationInMeters(MapContext<DynamicViewer> mapContext, GeographicPosition position) { double elevation = 0.; Projection proj = mapContext.getRawProjection(); if (proj.getElevationManager() != null) { elevation = proj.getElevationManager().getElevationM(position, true); elevation = Math.max(0., elevation); } return elevation; } private TerrainUtil(); static TerrainUtil getInstance(); double getElevationInMeters(MapContext<DynamicViewer> mapContext, GeographicPosition position); }### Answer:
@Test public void testGetElevationInMeters() { EasyMockSupport support = new EasyMockSupport(); GeographicPosition pos = new GeographicPosition(LatLonAlt.createFromDegrees(10, 9)); MapContext<DynamicViewer> mapContext = createMapContext(support, new MockedElevationManager(pos)); support.replayAll(); double elevation = TerrainUtil.getInstance().getElevationInMeters(mapContext, pos); assertEquals(1001.1, elevation, 0d); support.verifyAll(); }
|
### Question:
BackgroundController implements Observer { public void close() { myMapModel.deleteObserver(this); } BackgroundController(MapModel mapModel, BackgroundModel model); void close(); @Override void update(Observable o, Object arg); }### Answer:
@Test public void testClose() { MapModel mapModel = new MapModel(); mapModel.setHeightWidth(150, 300); mapModel.setViewport(new ScreenBoundingBox(new ScreenPosition(0d, 0d), new ScreenPosition(300, 150))); BackgroundModel model = new BackgroundModel(); BackgroundController controller = new BackgroundController(mapModel, model); assertEquals(1, mapModel.countObservers()); controller.close(); assertEquals(0, mapModel.countObservers()); }
|
### Question:
TimelineUtilities { public static TimeSpan getToday() { return TimeSpan.get(get0000().getTimeInMillis(), Days.ONE); } private TimelineUtilities(); static void addDuration(Calendar calendar, Duration duration); static Calendar get0000(); static Calendar get0000(Date aDate); static List<TimeSpan> getIntervalsForSpan(Date startDate, TimeSpan span, int spanType); static Calendar getNext0000(Date aDate); static TimeSpan getPartialWeek(); static TimeSpan getPrecedingMonths(Date reference, int months, boolean includeThisMonth); static TimeSpan getPrecedingMonths(int months, boolean includeThisMonth); static TimeSpan getPrecedingWeeks(Date reference, int numWeeks, boolean includeThisWeek); static TimeSpan getPrecedingWeeks(int numWeeks, boolean includeThisWeek); static Map<Duration, List<DateDurationKey>> getTableOfLegalDates(TimeSpan span, Duration duration); static TimeSpan getThisDay(Date time); static TimeSpan getThisMonth(Date time); static TimeSpan getThisWeek(Date time); static TimeSpan getToday(); static TimeSpan getYesterday(); static boolean isAt0000(Date aDate); static boolean isDayWeekMonth(TimeSpan span); static boolean isDay(TimeSpan span); static boolean isWeek(TimeSpan span); static boolean isMonth(TimeSpan span); static boolean isRounded(Date time, Duration duration); static Calendar roundDown(Date date, Duration interval); static Calendar roundUp(Date date, Duration interval); static TimeSpan scale(TimeSpan span, double factor); }### Answer:
@Test public void testGetToday() { TimeSpan today = TimelineUtilities.getToday(); Assert.assertTrue(Days.ONE.compareTo(today.getDuration()) == 0); Assert.assertTrue(TimelineUtilities.isAt0000(today.getStartDate())); Assert.assertTrue(today.getStart() < System.currentTimeMillis()); Assert.assertTrue(TimelineUtilities.isAt0000(today.getEndDate())); Assert.assertTrue(today.getEnd() > System.currentTimeMillis()); }
|
### Question:
BackgroundOverlay implements Observer, Overlay { @Override public void close() { myController.close(); myModel.deleteObserver(this); } BackgroundOverlay(MapModel mapModel); @Override void close(); @Override void draw(Graphics graphics); @Override void update(Observable o, Object arg); }### Answer:
@Test public void testClose() { MapModel mapModel = new MapModel(); mapModel.setHeightWidth(150, 300); mapModel.setViewport(new ScreenBoundingBox(new ScreenPosition(0d, 0d), new ScreenPosition(300, 150))); BackgroundOverlay overlay = new BackgroundOverlay(mapModel); assertEquals(1, mapModel.countObservers()); overlay.close(); assertEquals(0, mapModel.countObservers()); }
|
### Question:
ZipInputAdapter { public abstract String getName(); ZipInputAdapter(int method); void closeInputStream(); abstract InputStream getInputStream(); abstract String getLocation(); int getMethod(); abstract String getName(); long getSize(); }### Answer:
@Test public void testNonPrivateMethods() { Method[] declaredMethods = ZipInputAdapter.class.getDeclaredMethods(); for (Method method : declaredMethods) { if (!method.getName().startsWith("$") && !method.getName().startsWith("lambda$")) { assertFalse(method.getName() + " is private. No private methods are permitted.", Modifier.isPrivate(method.getModifiers())); } } }
|
### Question:
ZipInputAdapter { public void closeInputStream() throws IOException { } ZipInputAdapter(int method); void closeInputStream(); abstract InputStream getInputStream(); abstract String getLocation(); int getMethod(); abstract String getName(); long getSize(); }### Answer:
@Test public void testCloseInputStream() throws IOException { myTestObject.closeInputStream(); }
|
### Question:
ZipInputAdapter { public int getMethod() { return myMethod; } ZipInputAdapter(int method); void closeInputStream(); abstract InputStream getInputStream(); abstract String getLocation(); int getMethod(); abstract String getName(); long getSize(); }### Answer:
@Test public void testGetMethod() { assertEquals(myMethod, myTestObject.getMethod()); }
|
### Question:
ZipInputAdapter { public long getSize() { return 0; } ZipInputAdapter(int method); void closeInputStream(); abstract InputStream getInputStream(); abstract String getLocation(); int getMethod(); abstract String getName(); long getSize(); }### Answer:
@Test public void testGetSize() { assertEquals(0, myTestObject.getSize()); }
|
### Question:
ZipByteArrayInputAdapter extends ZipInputAdapter { @Override public void closeInputStream() throws IOException { if (myBAIS != null) { myBAIS.close(); myBAIS = null; } } ZipByteArrayInputAdapter(String name, String location, byte[] byteArray, int method); @Override void closeInputStream(); @Override InputStream getInputStream(); @Override String getLocation(); @Override String getName(); }### Answer:
@Test public void testCloseInputStream() throws IOException { try (InputStream in = myTestObject.getInputStream()) { myTestObject.closeInputStream(); } myTestObject.closeInputStream(); }
|
### Question:
ZipByteArrayInputAdapter extends ZipInputAdapter { @Override public InputStream getInputStream() throws IOException { if (myBAIS == null) { myBAIS = new ByteArrayInputStream(myByteArray); } return myBAIS; } ZipByteArrayInputAdapter(String name, String location, byte[] byteArray, int method); @Override void closeInputStream(); @Override InputStream getInputStream(); @Override String getLocation(); @Override String getName(); }### Answer:
@Test public void testGetInputStream() throws IOException { byte[] bytes = new byte[myByteArray.length]; int bytesRead = 0; try (InputStream in = myTestObject.getInputStream(); InputStream in2 = myTestObject.getInputStream()) { bytesRead = in.read(bytes); assertTrue(Utilities.sameInstance(in, in2)); } assertEquals(bytesRead, myByteArray.length); String expectedContent = new String(myByteArray); String actualContent = new String(bytes); assertEquals(expectedContent, actualContent); }
|
### Question:
ZipByteArrayInputAdapter extends ZipInputAdapter { @Override public String getLocation() { return myLocation; } ZipByteArrayInputAdapter(String name, String location, byte[] byteArray, int method); @Override void closeInputStream(); @Override InputStream getInputStream(); @Override String getLocation(); @Override String getName(); }### Answer:
@Test public void testGetLocation() { assertEquals(myLocation, myTestObject.getLocation()); }
|
### Question:
ZipByteArrayInputAdapter extends ZipInputAdapter { @Override public String getName() { return myName; } ZipByteArrayInputAdapter(String name, String location, byte[] byteArray, int method); @Override void closeInputStream(); @Override InputStream getInputStream(); @Override String getLocation(); @Override String getName(); }### Answer:
@Test public void testGetName() { assertEquals(myName, myTestObject.getName()); }
|
### Question:
ZipByteArrayInputAdapter extends ZipInputAdapter { public ZipByteArrayInputAdapter(String name, String location, byte[] byteArray, int method) { super(method); myName = name; myLocation = location; myByteArray = Arrays.copyOf(byteArray, byteArray.length); } ZipByteArrayInputAdapter(String name, String location, byte[] byteArray, int method); @Override void closeInputStream(); @Override InputStream getInputStream(); @Override String getLocation(); @Override String getName(); }### Answer:
@Test public void testZipByteArrayInputAdapter() { assertNotNull(myTestObject); assertEquals(myName, myTestObject.getName()); assertEquals(myMethod, myTestObject.getMethod()); assertEquals(myLocation, myTestObject.getLocation()); }
|
### Question:
ChainFunction implements Function<T, T> { @Override public T apply(T input) { T result = input; for (Function<? super T, ? extends T> f : myFunctions) { result = f.apply(result); } return result; } ChainFunction(Collection<? extends Function<? super T, ? extends T>> functions); ChainFunction(Function<? super T, ? extends T> arg1, Function<? super T, ? extends T> arg2); @Override T apply(T input); }### Answer:
@Test public void test() { Function<? super Integer, ? extends Integer> plusFive = new Function<Integer, Integer>() { @Override public Integer apply(Integer t) { return Integer.valueOf(t.intValue() + 5); } }; Function<? super Integer, ? extends Integer> timesThree = new Function<Integer, Integer>() { @Override public Integer apply(Integer t) { return Integer.valueOf(t.intValue() * 3); } }; Assert.assertEquals(Integer.valueOf(36), new ChainFunction<Integer>(plusFive, timesThree).apply(Integer.valueOf(7))); Assert.assertEquals(Integer.valueOf(26), new ChainFunction<Integer>(timesThree, plusFive).apply(Integer.valueOf(7))); Assert.assertEquals(Integer.valueOf(31), new ChainFunction<Integer>( Arrays.<Function<? super Integer, ? extends Integer>>asList(timesThree, plusFive, plusFive)) .apply(Integer.valueOf(7))); }
|
### Question:
ElementData { public VisualizationState getVisualizationState() { return myVisualizationState; } ElementData(); ElementData(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); boolean found(); Long getID(); MapGeometrySupport getMapGeometrySupport(); MetaDataProvider getMetaDataProvider(); TimeSpan getTimeSpan(); VisualizationState getVisualizationState(); final void updateValues(Long id, TimeSpan ts, VisualizationState vs, MetaDataProvider mdp, MapGeometrySupport mgs); }### Answer:
@Test public void testGetVisualizationState() { assertEquals(myVisualizationState, myTestObject.getVisualizationState()); }
|
### Question:
DriverChecker { static List<String> getActions(String glVendor, String driverVersion, Map<String, String> configMap) { List<String> actions = null; for (Map.Entry<String, String> entry : configMap.entrySet()) { String[] tokens = entry.getKey().split(":"); String vendor = tokens[0]; String versionFragment = tokens[1]; if (glVendor.startsWith(vendor) && driverVersion.startsWith(versionFragment) && !versionFragment.isEmpty()) { actions = New.list(entry.getValue().split(",")); } } return actions; } DriverChecker(Component component, Preferences prefs, PreferencesRegistry preferencesRegistry,
String displayListPrefsKey); void checkGraphicsDriver(GL gl); }### Answer:
@Test public void testGetActionsNvidia() { Assert.assertNull(DriverChecker.getActions("NVIDIA Corporation", "369.49", UNSUPPORTED_DRIVERS)); }
@Test public void testGetActionsAtiGood() { Assert.assertNull(DriverChecker.getActions("ATI Technologies Inc.", "15.201.2201.0", UNSUPPORTED_DRIVERS)); }
@Test public void testGetActionsAtiBad() { Assert.assertEquals(New.list("disableTooltips"), DriverChecker.getActions("ATI Technologies Inc.", "14.501.1003.0", UNSUPPORTED_DRIVERS)); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.