method2testcases
stringlengths 118
6.63k
|
---|
### Question:
AbstractGrain extends AbstractIterableMap<String, Object> implements Grain { @Override public ConstSet<Entry<String, Object>> entrySet() { return new ConstEntriesView(); } @Override abstract Object get(Object key); @Deprecated @Override final Object put(String key, Object value); @Deprecated @Override final void putAll(Map<? extends String, ?> map); @Deprecated @Override final Object remove(Object key); @Deprecated @Override final void clear(); @Override ConstSet<String> keySet(); @Override ConstCollection<Object> values(); @Override ConstSet<Entry<String, Object>> entrySet(); }### Answer:
@Test public void test_entrySet_modify() { Grain grain = new MockGrain(sortedMapOf(null, "a", (Object)1), sortedMapOf(null, "b", (Object)2)); ConstSet<Entry<String, Object>> entrySet = grain.entrySet(); assertSame(entrySet, entrySet.with(newEntry("a", (Object)1))); assertSame(entrySet, entrySet.with(newEntry("b", (Object)2))); compare_sets( newSet(newEntry("a", 1), newEntry("b", 2), newEntry("a", 3)), entrySet.with(newEntry("a", (Object)3))); compare_sets( newSet(newEntry("a", 1), newEntry("b", 2), newEntry("a", 3), newEntry("c", 3)), entrySet.withAll(Arrays.asList(newEntry("a", (Object)3), newEntry("c", (Object)3)))); assertSame(entrySet, entrySet.withAll(Arrays.<Entry<String, Object>>asList())); assertSame(entrySet, entrySet.without(newEntry("a", 2))); compare_sets(newSet(newEntry("b", 2)), entrySet.without(newEntry("a", 1))); compare_sets(newSet(newEntry("a", 1)), entrySet.without(newEntry("b", 2))); compare_sets( newSet(newEntry("a", 1)), entrySet.withoutAll(Arrays.asList(newEntry("b", (Object)2), newEntry("c", (Object)3)))); compare_sets(newSet(), entrySet.withoutAll(entrySet)); assertSame(entrySet, entrySet.withoutAll(Arrays.asList())); } |
### Question:
ArrayTools { public static <T> int lastIndexOf(T element, T[] array) { if (element == null) { for (int i = array.length - 1; i >= 0; i--) { if (array[i] == null) { return i; } } } else { for (int i = array.length - 1; i >= 0; i--) { if (element.equals(array[i])) { return i; } } } return -1; } private ArrayTools(); static int indexOf(T element, T[] array); static int indexOf(T element, T[] array, int fromIndex, int toIndex); static int indexOf(T element, T[] array, Comparator<? super T> comparator); static int indexOf(T element, T[] array, int fromIndex, int toIndex, Comparator<? super T> comparator); static int lastIndexOf(T element, T[] array); static void checkRange(int fromIndex, int toIndex, int length); static T[] sort(T[] a); static T[] sort(T[] a, Comparator<? super T> c); static final Object[] EMPTY_OBJECT_ARRAY; static final Class<?>[] EMPTY_CLASS_ARRAY; static final Type[] EMPTY_TYPE_ARRAY; }### Answer:
@Test public void test_lastIndexOf() { Integer[] ary = new Integer[] {10, 11, 12, 13, null, 10, 11, 12, 13, null}; assertEquals(9, lastIndexOf(null, ary)); assertEquals(6, lastIndexOf(11, ary)); assertEquals(-1, lastIndexOf(42, ary)); assertEquals(-1, lastIndexOf(null, new Integer[] {1, 2, 3})); }
@Test(expected = NullPointerException.class) public void test_lastIndexOf_illegal_arg() { lastIndexOf(10, null); } |
### Question:
ArrayTools { public static void checkRange(int fromIndex, int toIndex, int length) { if (fromIndex < 0 || toIndex > length) { throw new IndexOutOfBoundsException( String.format("range [%d, %d) is outside bounds [%d, %d)", fromIndex, toIndex, 0, length)); } if (fromIndex > toIndex) { throw new IllegalArgumentException( String.format("fromIndex %d cannot be greater than toIndex %d", fromIndex, toIndex)); } } private ArrayTools(); static int indexOf(T element, T[] array); static int indexOf(T element, T[] array, int fromIndex, int toIndex); static int indexOf(T element, T[] array, Comparator<? super T> comparator); static int indexOf(T element, T[] array, int fromIndex, int toIndex, Comparator<? super T> comparator); static int lastIndexOf(T element, T[] array); static void checkRange(int fromIndex, int toIndex, int length); static T[] sort(T[] a); static T[] sort(T[] a, Comparator<? super T> c); static final Object[] EMPTY_OBJECT_ARRAY; static final Class<?>[] EMPTY_CLASS_ARRAY; static final Type[] EMPTY_TYPE_ARRAY; }### Answer:
@Test public void test_check_range() { checkRange(0, 0, 2); checkRange(0, 2, 2); checkRange(2, 2, 2); try { checkRange(-1, 2, 2); fail(); } catch (IndexOutOfBoundsException ignored) {} try { checkRange( 0, 3, 2); fail(); } catch (IndexOutOfBoundsException ignored) {} try { checkRange( 7, 6, 2); fail(); } catch (IndexOutOfBoundsException ignored) {} try { checkRange( 1, 0, 2); fail(); } catch (IllegalArgumentException ignored) {} } |
### Question:
ArrayTools { public static <T> T[] sort(T[] a) { Arrays.sort(a); return a; } private ArrayTools(); static int indexOf(T element, T[] array); static int indexOf(T element, T[] array, int fromIndex, int toIndex); static int indexOf(T element, T[] array, Comparator<? super T> comparator); static int indexOf(T element, T[] array, int fromIndex, int toIndex, Comparator<? super T> comparator); static int lastIndexOf(T element, T[] array); static void checkRange(int fromIndex, int toIndex, int length); static T[] sort(T[] a); static T[] sort(T[] a, Comparator<? super T> c); static final Object[] EMPTY_OBJECT_ARRAY; static final Class<?>[] EMPTY_CLASS_ARRAY; static final Type[] EMPTY_TYPE_ARRAY; }### Answer:
@Test public void test_sort() { Integer[] a = new Integer[] {3, 2, 1}; assertArrayEquals(new Integer[] {1, 2, 3}, sort(a)); assertSame(a, sort(a)); }
@Test(expected = NullPointerException.class) public void test_sort_nulls() { Integer[] a = new Integer[] {null, null}; sort(a); }
@Test public void test_sort_comparator() { Integer[] a = new Integer[] {2, 1, 3}; assertArrayEquals(new Integer[] {1, 2, 3}, sort(a, null)); assertSame(a, sort(a, null)); assertArrayEquals(new Integer[] {3, 2, 1}, sort(a, Collections.reverseOrder())); assertSame(a, sort(a, Collections.reverseOrder())); }
@Test(expected = NullPointerException.class) public void test_sort_comparator_nulls() { String[] a = new String[] {null, null}; sort(a, String.CASE_INSENSITIVE_ORDER); } |
### Question:
ThreadTools { public static ThreadFactory newDaemonThreadFactory(final ThreadFactory wrapped) { Objects.requireNonNull(wrapped); return new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = wrapped.newThread(r); if (!t.isDaemon()) { t.setDaemon(true); } return t; } }; } private ThreadTools(); static ThreadFactory newDaemonThreadFactory(final ThreadFactory wrapped); static ThreadFactory newNamingThreadFactory(final String format, final ThreadFactory wrapped); static ThreadFactory newContextThreadFactory(final ClassLoader classLoader, final ThreadFactory wrapped); }### Answer:
@Test public void test_daemon_thread_factory() { Runnable r = mock(Runnable.class); Thread thread = new Thread(r); thread.setDaemon(false); ThreadFactory factory = mock(ThreadFactory.class); when(factory.newThread(any(Runnable.class))).thenReturn(thread); assertSame(thread, newDaemonThreadFactory(factory).newThread(r)); assertTrue(thread.isDaemon()); verify(factory).newThread(r); } |
### Question:
ThreadTools { public static ThreadFactory newNamingThreadFactory(final String format, final ThreadFactory wrapped) { String.format(format, 0, "test name"); Objects.requireNonNull(wrapped); final AtomicInteger threadNumber = new AtomicInteger(0); return new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = wrapped.newThread(r); t.setName(String.format(format, threadNumber.getAndIncrement(), t.getName())); return t; } }; } private ThreadTools(); static ThreadFactory newDaemonThreadFactory(final ThreadFactory wrapped); static ThreadFactory newNamingThreadFactory(final String format, final ThreadFactory wrapped); static ThreadFactory newContextThreadFactory(final ClassLoader classLoader, final ThreadFactory wrapped); }### Answer:
@Test public void test_naming_thread_factory() { Runnable r = mock(Runnable.class); Thread thread = new Thread(r); thread.setName("Foo"); ThreadFactory factory = mock(ThreadFactory.class); when(factory.newThread(any(Runnable.class))).thenReturn(thread); assertSame(thread, newNamingThreadFactory("#%d %s", factory).newThread(r)); assertEquals("#0 Foo", thread.getName()); verify(factory).newThread(r); } |
### Question:
ThreadTools { public static ThreadFactory newContextThreadFactory(final ClassLoader classLoader, final ThreadFactory wrapped) { Objects.requireNonNull(wrapped); return new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = wrapped.newThread(r); t.setContextClassLoader(classLoader); return t; } }; } private ThreadTools(); static ThreadFactory newDaemonThreadFactory(final ThreadFactory wrapped); static ThreadFactory newNamingThreadFactory(final String format, final ThreadFactory wrapped); static ThreadFactory newContextThreadFactory(final ClassLoader classLoader, final ThreadFactory wrapped); }### Answer:
@Test public void test_context_thread_factory() { Runnable r = mock(Runnable.class); Thread thread = new Thread(r); ThreadFactory factory = mock(ThreadFactory.class); when(factory.newThread(any(Runnable.class))).thenReturn(thread); ClassLoader cl = new URLClassLoader(new URL[] {}); assertSame(thread, newContextThreadFactory(cl, factory).newThread(r)); assertSame(cl, thread.getContextClassLoader()); verify(factory).newThread(r); } |
### Question:
StringTools { public static String capitalize(String s) { return s == null || s.isEmpty() ? s : s.substring(0, 1).toUpperCase(Locale.ENGLISH) + s.substring(1); } private StringTools(); static String capitalize(String s); }### Answer:
@Test public void test_capitalize() { assertEquals("HellO", capitalize("hellO")); assertEquals("HellO", capitalize("HellO")); assertEquals("A", capitalize("a")); assertEquals("", capitalize("")); assertNull(capitalize(null)); } |
### Question:
ObjectTools { public static <T> T coalesce(T x, T y) { return x != null ? x : y; } private ObjectTools(); static T coalesce(T x, T y); static int compare(T left, T right, Comparator<? super T> comparator); }### Answer:
@Test public void test_coalesce() { Object x = new Object(); Object y = new Object(); assertSame(x, coalesce(x, y)); assertSame(x, coalesce(x, null)); assertNull(coalesce(null, null)); assertSame(y, coalesce(null, y)); } |
### Question:
ObjectTools { public static <T> int compare(T left, T right, Comparator<? super T> comparator) { if (comparator == null) { @SuppressWarnings("unchecked") Comparable<T> leftComparable = (Comparable<T>)left; return leftComparable.compareTo(right); } return comparator.compare(left, right); } private ObjectTools(); static T coalesce(T x, T y); static int compare(T left, T right, Comparator<? super T> comparator); }### Answer:
@Test public void test_compare() { assertEquals( 0, compare(1, 1, null)); assertEquals(-1, compare(0, 1, null)); assertEquals( 1, compare(1, 0, null)); assertEquals( 0, compare(1, 1, Collections.reverseOrder())); assertEquals( 1, compare(0, 1, Collections.reverseOrder())); assertEquals(-1, compare(1, 0, Collections.reverseOrder())); }
@Test public void test_compare_nulls() { @SuppressWarnings("unchecked") Comparator<Object> c = (Comparator<Object>)mock(Comparator.class); when(c.compare(any(), any())).thenReturn(5); assertEquals(5, compare(null, null, c)); }
@Test(expected = NullPointerException.class) public void test_natural_compare_nulls() { compare(null, 5, null); }
@Test(expected = ClassCastException.class) public void test_compare_not_comparable() { compare(int.class, int.class, null); } |
### Question:
LateTypeVariable implements TypeVariable<D> { @Override public Type[] getBounds() { if (bounds != null) { return bounds.clone(); } throw new IllegalStateException("bounds have not yet been assigned"); } LateTypeVariable(String name, D genericDeclaration, Type... bounds); static LateTypeVariable<D> copyOf(TypeVariable<D> tv); @Override String getName(); @Override D getGenericDeclaration(); @Override Type[] getBounds(); synchronized void assignBounds(Type... bounds); @Override boolean equals(Object that); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void test_recursive_type_variable() { compare(MY_ENUM.getE(), new LateTypeVariable<Class>("E", MyEnum.class, MY_ENUM.getE().getBounds()[0])); } |
### Question:
TypeToken { @Override public final int hashCode() { return type.hashCode(); } protected TypeToken(); final Type asType(); final T asNull(); @Override final boolean equals(Object that); @Override final int hashCode(); @Override final String toString(); }### Answer:
@Test public void test_equality() { TypeToken<Set<String>> setOfString1 = new TypeToken<Set<String>>(){}; TypeToken<Set<String>> setOfString2 = new TypeToken<Set<String>>(){}; TypeToken<Set<Long>> setOfLong = new TypeToken<Set<Long>>(){}; assertEquals(setOfString1, setOfString2); assertEquals(setOfString1.hashCode(), setOfString2.hashCode()); assertNotEquals(setOfString1, setOfLong); assertNotEquals(setOfString1.hashCode(), setOfLong.hashCode()); assertNotEquals(setOfString1, new Object()); } |
### Question:
TypeToken { public final T asNull() { return null; } protected TypeToken(); final Type asType(); final T asNull(); @Override final boolean equals(Object that); @Override final int hashCode(); @Override final String toString(); }### Answer:
@Test public void test_typed_null() { TypeToken<Long> token = new TypeToken<Long>(){}; assertEquals(42, invoke(token.asNull())); } |
### Question:
LateParameterizedType implements ParameterizedType { @Override public String toString() { return print(this); } LateParameterizedType(Type rawType, Type ownerType, Type... actualTypeArguments); static LateParameterizedType copyOf(ParameterizedType pt); @Override Class<?> getRawType(); @Override Type getOwnerType(); @Override Type[] getActualTypeArguments(); Type resolve(Type type); Type[] resolve(Type[] types); Type getSuperclass(); Type[] getInterfaces(); @Override boolean equals(Object that); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void test_nested_print() { assertEquals( "net.nullschool.reflect.Outer<java.lang.Short>.Inner1<java.lang.Integer>.Inner2<java.lang.Long>", new TypeToken<Outer<Short>.Inner1<Integer>.Inner2<Long>>(){}.asType().toString()); assertEquals( "net.nullschool.reflect.Outer.$Inner3<java.lang.Integer>", new TypeToken<Outer.$Inner3<Integer>>(){}.asType().toString()); assertEquals( "net.nullschool.reflect.Outer.$Inner3<java.lang.Integer>.$Inner4<java.lang.Long>", new TypeToken<Outer.$Inner3<Integer>.$Inner4<Long>>(){}.asType().toString()); } |
### Question:
LateParameterizedType implements ParameterizedType { public Type getSuperclass() { return resolve(rawType.getGenericSuperclass()); } LateParameterizedType(Type rawType, Type ownerType, Type... actualTypeArguments); static LateParameterizedType copyOf(ParameterizedType pt); @Override Class<?> getRawType(); @Override Type getOwnerType(); @Override Type[] getActualTypeArguments(); Type resolve(Type type); Type[] resolve(Type[] types); Type getSuperclass(); Type[] getInterfaces(); @Override boolean equals(Object that); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void test_superclass() { LateParameterizedType lpc = new LateParameterizedType(ArrayList.class, null, Long.class); compare( new JavaToken<AbstractList<Long>>(){}.asParameterizedType(), lpc = (LateParameterizedType)lpc.getSuperclass()); compare( new JavaToken<AbstractCollection<Long>>(){}.asParameterizedType(), lpc = (LateParameterizedType)lpc.getSuperclass()); assertSame(Object.class, lpc.getSuperclass()); LateParameterizedType listOfLong = new LateParameterizedType(List.class, null, Long.class); assertNull(listOfLong.getSuperclass()); } |
### Question:
LateParameterizedType implements ParameterizedType { public Type[] getInterfaces() { return resolve(rawType.getGenericInterfaces()); } LateParameterizedType(Type rawType, Type ownerType, Type... actualTypeArguments); static LateParameterizedType copyOf(ParameterizedType pt); @Override Class<?> getRawType(); @Override Type getOwnerType(); @Override Type[] getActualTypeArguments(); Type resolve(Type type); Type[] resolve(Type[] types); Type getSuperclass(); Type[] getInterfaces(); @Override boolean equals(Object that); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void test_interfaces() { LateParameterizedType lpc = new LateParameterizedType(ArrayList.class, null, Long.class); Type[] result = lpc.getInterfaces(); assertEquals(4, result.length); compare(new JavaToken<List<Long>>(){}.asParameterizedType(), lpc = (LateParameterizedType)result[0]); assertSame(RandomAccess.class, result[1]); assertSame(Cloneable.class, result[2]); assertSame(Serializable.class, result[3]); result = lpc.getInterfaces(); assertEquals(1, result.length); compare(new JavaToken<Collection<Long>>(){}.asParameterizedType(), lpc = (LateParameterizedType)result[0]); result = lpc.getInterfaces(); assertEquals(1, result.length); compare(new JavaToken<Iterable<Long>>(){}.asParameterizedType(), lpc = (LateParameterizedType)result[0]); result = lpc.getInterfaces(); assertEquals(0, result.length); } |
### Question:
TypeTools { public static Class<?> buildArrayType(Class<?> componentType) { return Array.newInstance(componentType, 0).getClass(); } private TypeTools(); static boolean isInnerClass(Class<?> clazz); static Class<?> buildArrayType(Class<?> componentType); static Class<?> erase(Type type); static String print(Type type); static String print(Type type, TypePrinter printer); static Type[] apply(TypeOperator<? extends Type> operator, Type[] types); static Class<?> publicInterfaceOf(Class<?> type); }### Answer:
@Test public void test_buildArrayType() { assertSame(int[].class, buildArrayType(int.class)); assertSame(int[][].class, buildArrayType(int[].class)); assertSame(Integer[].class, buildArrayType(Integer.class)); assertSame(Map[].class, buildArrayType(Map.class)); } |
### Question:
TypeTools { public static Class<?> erase(Type type) { return Eraser.INSTANCE.apply(type); } private TypeTools(); static boolean isInnerClass(Class<?> clazz); static Class<?> buildArrayType(Class<?> componentType); static Class<?> erase(Type type); static String print(Type type); static String print(Type type, TypePrinter printer); static Type[] apply(TypeOperator<? extends Type> operator, Type[] types); static Class<?> publicInterfaceOf(Class<?> type); }### Answer:
@Test public void test_erasure() { assertSame(int.class, erase(int.class)); assertSame(Object.class, erase(Object.class)); assertSame(Object[].class, erase(Object[].class)); assertSame(Set[].class, erase(new JavaToken<Set<?>[]>(){}.asGenericArrayType())); assertSame(Object.class, erase(new JavaToken<Set<?>>(){}.asWildcardType())); assertSame(Object.class, erase(new JavaToken<Set<? super Comparable>>(){}.asWildcardType())); assertSame(Comparable.class, erase(new JavaToken<Set<? extends Comparable>>(){}.asWildcardType())); assertSame(Map.class, erase(new LateWildcardType("? extends", Map.class, HashMap.class))); assertSame(Set.class, erase(new JavaToken<Set<Integer>>(){}.asParameterizedType())); assertSame(Set.class, erase(new JavaToken<Set<?>>(){}.asParameterizedType())); assertSame(Object.class, erase(new LateTypeVariable<Class>("E", Set.class))); assertSame(Map.class, erase(new LateTypeVariable<Class>("E", Set.class, Map.class))); assertSame(Map.class, erase(new LateTypeVariable<Class>("E", Set.class, Map.class, HashMap.class))); assertNull(erase(null)); try { erase(new Type(){}); fail(); } catch (IllegalArgumentException expected) {} } |
### Question:
TypeTools { public static String print(Type type) { return print(type, new FullNamePrinter()); } private TypeTools(); static boolean isInnerClass(Class<?> clazz); static Class<?> buildArrayType(Class<?> componentType); static Class<?> erase(Type type); static String print(Type type); static String print(Type type, TypePrinter printer); static Type[] apply(TypeOperator<? extends Type> operator, Type[] types); static Class<?> publicInterfaceOf(Class<?> type); }### Answer:
@Test public void test_print() { assertEquals("java.util.List", print(List.class)); assertEquals("java.util.List[]", print(List[].class)); assertEquals( "java.util.List<? extends java.lang.Integer>", print(new JavaToken<List<? extends Integer>>(){}.asType())); assertEquals( "java.util.List<? extends java.lang.Integer>[][]", print(new JavaToken<List<? extends Integer>[][]>(){}.asType())); assertEquals("java.util.Map.Entry", print(Map.Entry.class)); assertEquals("int", print(int.class)); assertEquals("int[]", print(int[].class)); }
@Test public void test_print_with_custom_printer() { assertEquals("~List", print(List.class, new PrependTildePrinter())); assertEquals("~List[]", print(List[].class, new PrependTildePrinter())); assertEquals( "~List<? extends ~Integer>", print(new JavaToken<List<? extends Integer>>(){}.asType(), new PrependTildePrinter())); assertEquals( "~List<? extends ~Integer>[][]", print(new JavaToken<List<? extends Integer>[][]>(){}.asType(), new PrependTildePrinter())); assertEquals("~Map.Entry", print(Map.Entry.class, new PrependTildePrinter())); assertEquals("~int", print(int.class, new PrependTildePrinter())); assertEquals("~int[]", print(int[].class, new PrependTildePrinter())); } |
### Question:
TypeTools { public static Type[] apply(TypeOperator<? extends Type> operator, Type[] types) { Type[] result = types.length > 0 ? new Type[types.length] : types; for (int i = 0; i < types.length; i++) { result[i] = operator.apply(types[i]); } return result; } private TypeTools(); static boolean isInnerClass(Class<?> clazz); static Class<?> buildArrayType(Class<?> componentType); static Class<?> erase(Type type); static String print(Type type); static String print(Type type, TypePrinter printer); static Type[] apply(TypeOperator<? extends Type> operator, Type[] types); static Class<?> publicInterfaceOf(Class<?> type); }### Answer:
@Test public void test_apply() { @SuppressWarnings("unchecked") TypeOperator<Type> operator = (TypeOperator<Type>)mock(TypeOperator.class); when(operator.apply((Type)String.class)).thenReturn(Character.class); when(operator.apply((Type)Integer.class)).thenReturn(Byte.class); Type[] result = apply(operator, new Type[] {String.class, Integer.class}); assertArrayEquals(new Type[] {Character.class, Byte.class}, result); } |
### Question:
TypeTools { static Type copyOf(Type type) { return LateTypeConverter.INSTANCE.apply(type); } private TypeTools(); static boolean isInnerClass(Class<?> clazz); static Class<?> buildArrayType(Class<?> componentType); static Class<?> erase(Type type); static String print(Type type); static String print(Type type, TypePrinter printer); static Type[] apply(TypeOperator<? extends Type> operator, Type[] types); static Class<?> publicInterfaceOf(Class<?> type); }### Answer:
@Test public void test_copyOf() { assertEquals(Class.class, copyOf(Object.class).getClass()); assertEquals(LateParameterizedType.class, copyOf(new JavaToken<Set<Byte>>(){}.asParameterizedType()).getClass()); assertEquals(LateGenericArrayType.class, copyOf(new JavaToken<Set<Byte>[]>(){}.asGenericArrayType()).getClass()); assertEquals(LateWildcardType.class, copyOf(new JavaToken<Set<?>>(){}.asWildcardType()).getClass()); } |
### Question:
LateWildcardType implements WildcardType { @Override public String toString() { return print(this); } private LateWildcardType(Type[] upperBounds, Type[] lowerBounds); LateWildcardType(String keyword, Type... bounds); static LateWildcardType copyOf(WildcardType wt); @Override Type[] getUpperBounds(); @Override Type[] getLowerBounds(); @Override boolean equals(Object that); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void test_extra_linguistic_wildcard_bounds() { assertEquals( "? extends java.io.Serializable & java.lang.Comparable", new LateWildcardType("? extends", Serializable.class, Comparable.class).toString()); assertEquals( "? extends java.lang.Class & java.lang.Class", new LateWildcardType("? extends", Class.class, Class.class).toString()); assertEquals( "? super java.io.Serializable & java.lang.Comparable", new LateWildcardType("? super", Serializable.class, Comparable.class).toString()); } |
### Question:
Eraser extends AbstractTypeOperator<Class<?>> { @Override public Class<?> apply(Class<?> clazz) { return clazz; } @Override Class<?> apply(Class<?> clazz); @Override Class<?> apply(ParameterizedType pt); @Override Class<?> apply(GenericArrayType gat); @Override Class<?> apply(WildcardType wt); @Override Class<?> apply(TypeVariable<?> tv); }### Answer:
@Test public void test_eraser() { Eraser eraser = Eraser.INSTANCE; assertSame(Object.class, eraser.apply(Object.class)); assertSame(Object[].class, eraser.apply(Object[].class)); assertSame(Set[].class, eraser.apply(new JavaToken<Set<?>[]>(){}.asGenericArrayType())); assertSame(Object.class, eraser.apply(new LateWildcardType("?"))); assertSame(Object.class, eraser.apply(new LateWildcardType("? super", Comparable.class))); assertSame(Comparable.class, eraser.apply(new LateWildcardType("? extends", Comparable.class))); assertSame(Map.class, eraser.apply(new LateWildcardType("? extends", Map.class, HashMap.class))); assertSame(Set.class, eraser.apply(new JavaToken<Set<Integer>>(){}.asParameterizedType())); assertSame(Object.class, eraser.apply(new LateTypeVariable<Class>("E", Set.class))); assertSame(Map.class, eraser.apply(new LateTypeVariable<Class>("E", Set.class, Map.class))); assertSame(Map.class, eraser.apply(new LateTypeVariable<Class>("E", Set.class, Map.class, HashMap.class))); assertSame(Object.class, eraser.apply((Type)Object.class)); assertSame(Object[].class, eraser.apply((Type)Object[].class)); assertSame(Set[].class, eraser.apply(new JavaToken<Set<?>[]>(){}.asType())); assertSame(Object.class, eraser.apply((Type)new LateWildcardType("?"))); assertSame(Object.class, eraser.apply((Type)new LateWildcardType("? super", Comparable.class))); assertSame(Comparable.class, eraser.apply((Type)new LateWildcardType("? extends", Comparable.class))); assertSame(Map.class, eraser.apply((Type)new LateWildcardType("? extends", Map.class, HashMap.class))); assertSame(Set.class, eraser.apply(new JavaToken<Set<Integer>>(){}.asType())); assertSame(Object.class, eraser.apply((Type)new LateTypeVariable<Class>("E", Set.class))); assertSame(Map.class, eraser.apply((Type)new LateTypeVariable<Class>("E", Set.class, Map.class))); assertSame(Map.class, eraser.apply((Type)new LateTypeVariable<Class>("E", Set.class, Map.class, HashMap.class))); assertNull(eraser.apply((Type)null)); }
@Test(expected = IllegalArgumentException.class) public void test_eraser_unknown() { Eraser.INSTANCE.apply(new Type(){}); } |
### Question:
AbstractTypeOperator implements TypeOperator<T> { @Override public T apply(Type type) { if (type instanceof Class) { return apply((Class<?>)type); } else if (type instanceof ParameterizedType) { return apply((ParameterizedType)type); } else if (type instanceof WildcardType) { return apply((WildcardType)type); } else if (type instanceof GenericArrayType) { return apply((GenericArrayType)type); } else if (type instanceof TypeVariable) { return apply((TypeVariable<?>)type); } else if (type == null) { return null; } throw new IllegalArgumentException("Unsupported Type implementation: " + type.getClass()); } @Override T apply(Type type); }### Answer:
@Test public void test_invoke() { TypeOperator<?> operator = mock(AbstractTypeOperator.class); given(operator.apply(any(Type.class))).willCallRealMethod(); operator.apply((Type)Object.class); operator.apply((Type)new LateParameterizedType(Set.class, null, Integer.class)); operator.apply((Type)new LateGenericArrayType(new LateTypeVariable<Class>("E", Set.class))); operator.apply((Type)new LateWildcardType("?")); operator.apply((Type)new LateTypeVariable<Class>("E", Set.class)); assertNull(operator.apply((Type)null)); verify(operator, times(1)).apply(any(Class.class)); verify(operator, times(1)).apply(any(ParameterizedType.class)); verify(operator, times(1)).apply(any(GenericArrayType.class)); verify(operator, times(1)).apply(any(WildcardType.class)); verify(operator, times(1)).apply(any(TypeVariable.class)); verify(operator, times(6)).apply(any(Type.class)); }
@Test(expected = IllegalArgumentException.class) public void test_invoke_unknown() { TypeOperator<?> operator = mock(AbstractTypeOperator.class); given(operator.apply(any(Type.class))).willCallRealMethod(); operator.apply(new Type(){}); } |
### Question:
BasicList1 extends BasicConstList<E> { @Override public ConstList<E> with(E e) { return listOf(e0, e); } @SuppressWarnings("unchecked") BasicList1(Object e0); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override E get(int index); @Override Object[] toArray(); @Override ConstList<E> with(E e); @Override ConstList<E> with(int index, E e); @Override ConstList<E> withAll(Collection<? extends E> c); @Override ConstList<E> withAll(int index, Collection<? extends E> c); @Override ConstList<E> replace(int index, E e); @Override ConstList<E> without(Object o); @Override ConstList<E> delete(int index); @Override ConstList<E> withoutAll(Collection<?> c); @Override ConstList<E> subList(int fromIndex, int toIndex); @Override boolean equals(Object that); @Override int hashCode(); }### Answer:
@Test public void test_with() { compare_lists(Arrays.asList(1, 1), new BasicList1<>(1).with(1)); compare_lists(Arrays.asList(1, null), new BasicList1<>(1).with(null)); }
@Test public void test_with_index() { compare_lists(Arrays.asList(2, 1), new BasicList1<>(1).with(0, 2)); compare_lists(Arrays.asList(1, 2), new BasicList1<>(1).with(1, 2)); }
@Test(expected = IndexOutOfBoundsException.class) public void test_with_index_out_of_bounds() { new BasicList1<>(1).with(2, 1); } |
### Question:
BasicList1 extends BasicConstList<E> { @Override public ConstList<E> withAll(Collection<? extends E> c) { return c.isEmpty() ? this : BasicCollections.<E>condenseToList(insert(c.toArray(), 0, e0)); } @SuppressWarnings("unchecked") BasicList1(Object e0); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override E get(int index); @Override Object[] toArray(); @Override ConstList<E> with(E e); @Override ConstList<E> with(int index, E e); @Override ConstList<E> withAll(Collection<? extends E> c); @Override ConstList<E> withAll(int index, Collection<? extends E> c); @Override ConstList<E> replace(int index, E e); @Override ConstList<E> without(Object o); @Override ConstList<E> delete(int index); @Override ConstList<E> withoutAll(Collection<?> c); @Override ConstList<E> subList(int fromIndex, int toIndex); @Override boolean equals(Object that); @Override int hashCode(); }### Answer:
@Test public void test_withAll() { ConstList<Integer> list = new BasicList1<>(1); compare_lists(Arrays.asList(1, 1, 2, 3), list.withAll(Arrays.asList(1, 2, 3))); assertSame(list, list.withAll(Collections.<Integer>emptyList())); }
@Test(expected = NullPointerException.class) public void test_withAll_throws() { new BasicList1<>(1).withAll(null); }
@Test public void test_withAll_index() { ConstList<Integer> list = new BasicList1<>(0); compare_lists(Arrays.asList(1, 2, 3, 0), list.withAll(0, Arrays.asList(1, 2, 3))); compare_lists(Arrays.asList(0, 1, 2, 3), list.withAll(1, Arrays.asList(1, 2, 3))); assertSame(list, list.withAll(0, Collections.<Integer>emptyList())); }
@Test(expected = IndexOutOfBoundsException.class) public void test_withAll_index_out_of_bounds() { new BasicList1<>(1).withAll(2, Collections.<Integer>emptyList()); }
@Test(expected = NullPointerException.class) public void test_withAll_index_throws() { new BasicList1<>(1).withAll(0, null); } |
### Question:
BasicList1 extends BasicConstList<E> { @Override public ConstList<E> replace(int index, E e) { if (index == 0) { return listOf(e); } throw new IndexOutOfBoundsException(); } @SuppressWarnings("unchecked") BasicList1(Object e0); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override E get(int index); @Override Object[] toArray(); @Override ConstList<E> with(E e); @Override ConstList<E> with(int index, E e); @Override ConstList<E> withAll(Collection<? extends E> c); @Override ConstList<E> withAll(int index, Collection<? extends E> c); @Override ConstList<E> replace(int index, E e); @Override ConstList<E> without(Object o); @Override ConstList<E> delete(int index); @Override ConstList<E> withoutAll(Collection<?> c); @Override ConstList<E> subList(int fromIndex, int toIndex); @Override boolean equals(Object that); @Override int hashCode(); }### Answer:
@Test public void test_replace() { compare_lists(Collections.singletonList(9), new BasicList1<>(1).replace(0, 9)); }
@Test(expected = IndexOutOfBoundsException.class) public void test_replace_out_of_bounds() { new BasicList1<>(1).replace(1, 1); } |
### Question:
BasicList1 extends BasicConstList<E> { @Override public ConstList<E> without(Object o) { return !contains(o) ? this : BasicCollections.<E>emptyList(); } @SuppressWarnings("unchecked") BasicList1(Object e0); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); @Override E get(int index); @Override Object[] toArray(); @Override ConstList<E> with(E e); @Override ConstList<E> with(int index, E e); @Override ConstList<E> withAll(Collection<? extends E> c); @Override ConstList<E> withAll(int index, Collection<? extends E> c); @Override ConstList<E> replace(int index, E e); @Override ConstList<E> without(Object o); @Override ConstList<E> delete(int index); @Override ConstList<E> withoutAll(Collection<?> c); @Override ConstList<E> subList(int fromIndex, int toIndex); @Override boolean equals(Object that); @Override int hashCode(); }### Answer:
@Test public void test_without() { ConstList<Integer> list = new BasicList1<>(1); assertSame(BasicList0.instance(), list.without(1)); assertSame(list, list.without(2)); assertSame(list, list.without(null)); } |
### Question:
EmailQueries { public ExecutionResult suspectBehaviour() { String query = "MATCH (bob:User {username:'Bob'})-[:SENT]->(email)-[:CC]->(alias),\n" + " (alias)-[:ALIAS_OF]->(bob)\n" + "RETURN email.id"; Map<String, Object> params = new HashMap<String, Object>(); return executionEngineWrapper.execute( query, params ); } EmailQueries( GraphDatabaseService db, ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult suspectBehaviour(); ExecutionResult suspectBehaviour2(); ExecutionResult suspectBehaviour3(); ExecutionResult lossyDb(); }### Answer:
@Test public void suspectBehaviour() throws Exception { GraphDatabaseService db = createDatabase(); EmailQueries queries = new EmailQueries( db, new PrintingExecutionEngineWrapper( db, "email", name ) ); ExecutionResult result = queries.suspectBehaviour(); Iterator<Map<String, Object>> iterator = result.iterator(); Map<String, Object> next = iterator.next(); assertEquals( "1", next.get( "email.id" )); assertFalse( iterator.hasNext() ); db.shutdown(); } |
### Question:
SocialNetworkQueries { public ExecutionResult friendOfAFriendWithMultipleInterest( String userName, int limit, String... interestLabels ) { String query = "MATCH (subject:User {name:{name}})\n" + "MATCH p=(subject)-[:WORKED_ON]->()-[:WORKED_ON*0..2]-()\n" + " <-[:WORKED_ON]-(person)-[:INTERESTED_IN]->(interest)\n" + "WHERE person<>subject AND interest.name IN {interests}\n" + "WITH person, interest, min(length(p)) as pathLength\n" + "ORDER BY interest.name\n"+ "RETURN person.name AS name,\n" + " count(interest) AS score,\n" + " collect(interest.name) AS interests,\n" + " ((pathLength - 1)/2) AS distance\n" + "ORDER BY score DESC\n" + "LIMIT {resultLimit}"; Map<String, Object> params = new HashMap<String, Object>(); params.put( "name", userName ); params.put( "interests", interestLabels ); params.put( "resultLimit", limit ); return executionEngineWrapper.execute( query, params ); } SocialNetworkQueries( GraphDatabaseService db, ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult sharedInterestsSameCompany( String userName ); ExecutionResult sharedInterestsAllCompanies( String userName, int limit ); ExecutionResult sharedInterestsAlsoInterestedInTopic( String userName, String topicLabel ); ExecutionResult friendOfAFriendWithInterest( String userName, String topicLabel, int limit ); Collection<Node> friendOfAFriendWithInterestTraversalFramework( String userName,
final String topicLabel,
int limit ); ExecutionResult friendOfAFriendWithMultipleInterest( String userName, int limit, String... interestLabels ); ExecutionResult friendWorkedWithFriendWithInterests( String userName, int limit, String... interestLabels ); ExecutionResult createWorkedWithRelationships( String userName ); ExecutionResult getAllUsers(); static final Label USER; static final Label TOPIC; }### Answer:
@Test public void friendOfAFriendWithMultipleInterest() throws Exception { ExecutionResult results = queries.friendOfAFriendWithMultipleInterest( "Arnold", 5, "Art", "Design" ); Iterator<Map<String, Object>> iterator = results.iterator(); Map<String, Object> result = iterator.next(); assertEquals( "Emily", result.get( "name" ) ); assertEquals( 2L, result.get( "score" ) ); assertEquals( 2L, result.get( "distance" ) ); assertEquals( asList( "Art", "Design" ), result.get( "interests" ) ); assertFalse( iterator.hasNext() ); }
@Test public void friendOfAFriendWithMultipleInterestShouldOrderByScore() throws Exception { ExecutionResult results = queries.friendOfAFriendWithMultipleInterest( "Sarah", 5, "Java", "Travel", "Medicine" ); Iterator<Map<String, Object>> iterator = results.iterator(); Map<String, Object> result = iterator.next(); assertEquals( "Arnold", result.get( "name" ) ); assertEquals( 2L, result.get( "score" ) ); assertEquals( 2L, result.get( "distance" ) ); assertEquals( asList( "Java", "Travel" ), result.get( "interests" ) ); result = iterator.next(); assertEquals( "Charlie", result.get( "name" ) ); assertEquals( 1L, result.get( "score" ) ); assertEquals( 1L, result.get( "distance" ) ); assertEquals( asList( "Medicine" ), result.get( "interests" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
SocialNetworkQueries { public ExecutionResult createWorkedWithRelationships( String userName ) { String query = "MATCH (subject:User {name:{name}})\n" + "MATCH (subject)-[:WORKED_ON]->()<-[:WORKED_ON]-(person)\n" + "WHERE NOT((subject)-[:WORKED_WITH]-(person))\n" + "WITH DISTINCT subject, person\n" + "CREATE UNIQUE (subject)-[:WORKED_WITH]-(person)\n" + "RETURN subject.name AS startName, person.name AS endName"; Map<String, Object> params = new HashMap<String, Object>(); params.put( "name", userName ); return executionEngineWrapper.execute( query, params ); } SocialNetworkQueries( GraphDatabaseService db, ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult sharedInterestsSameCompany( String userName ); ExecutionResult sharedInterestsAllCompanies( String userName, int limit ); ExecutionResult sharedInterestsAlsoInterestedInTopic( String userName, String topicLabel ); ExecutionResult friendOfAFriendWithInterest( String userName, String topicLabel, int limit ); Collection<Node> friendOfAFriendWithInterestTraversalFramework( String userName,
final String topicLabel,
int limit ); ExecutionResult friendOfAFriendWithMultipleInterest( String userName, int limit, String... interestLabels ); ExecutionResult friendWorkedWithFriendWithInterests( String userName, int limit, String... interestLabels ); ExecutionResult createWorkedWithRelationships( String userName ); ExecutionResult getAllUsers(); static final Label USER; static final Label TOPIC; }### Answer:
@Test public void shouldCreateNewWorkedWithRelationships() throws Exception { String cypher = "MATCH (sarah:User {name:'Sarah'}),\n" + " (ben:User {name:'Ben'})\n" + "CREATE sarah-[:WORKED_WITH]->ben"; createFromCypher( db, "Enriched Social Network", cypher ); ExecutionResult results = queries.createWorkedWithRelationships( "Sarah" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); Map<String, Object> result = iterator.next(); assertEquals( "Emily", result.get( "endName" ) ); result = iterator.next(); assertEquals( "Charlie", result.get( "endName" ) ); result = iterator.next(); assertEquals( "Kate", result.get( "endName" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
AccessControlWithRelationshipPropertiesQueries { public QueryUnionExecutionResult findAccessibleResources( String adminName ) { String inheritedQuery = "MATCH (admin:Administrator {name:{adminName}})\n" + "MATCH paths=(admin)-[:MEMBER_OF]->()-[permission:ALLOWED]->()<-[:CHILD_OF*0..3]-()" + "<-[:WORKS_FOR]-(employee)-[:HAS_ACCOUNT]->(account)\n" + "WHERE (permission.inherit=true) AND NOT (admin-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0..3]-()" + "<-[:WORKS_FOR]-employee-[:HAS_ACCOUNT]->account)\n" + "RETURN paths"; String notInheritedQuery = "MATCH (admin:Administrator {name:{adminName}})\n" + "MATCH paths=(admin)-[:MEMBER_OF]->()-[permission:ALLOWED]->()" + "<-[:WORKS_FOR]-employee-[:HAS_ACCOUNT]->account\n" + "WHERE (permission.inherit=false)\n" + "RETURN paths"; Map<String, Object> params = new HashMap<>(); params.put( "adminName", adminName ); return executionEngine.execute( params, inheritedQuery, notInheritedQuery ); } AccessControlWithRelationshipPropertiesQueries( ExecutionEngineWrapper executionEngine ); QueryUnionExecutionResult findAccessibleResources( String adminName ); QueryUnionExecutionResult findAccessibleCompanies( String adminName ); QueryUnionExecutionResult findAccessibleAccountsForCompany( String adminName,
String companyName ); QueryUnionExecutionResult findAdminForResource( String resourceName ); QueryUnionExecutionResult findAdminForCompany( String companyName ); QueryUnionExecutionResult hasAccessToResource( String adminName, String resourceName ); QueryUnionExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test public void allowedWithInheritTrueGivesAccessToSubcompaniesAndAccounts() throws Exception { QueryUnionExecutionResult results = queries.findAccessibleResources( "Ben" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Account-1", ((Path) iterator.next().get( "paths" )).endNode().getProperty( "name" ) ); assertEquals( "Account-2", ((Path) iterator.next().get( "paths" )).endNode().getProperty( "name" ) ); assertEquals( "Account-3", ((Path) iterator.next().get( "paths" )).endNode().getProperty( "name" ) ); assertEquals( "Account-6", ((Path) iterator.next().get( "paths" )).endNode().getProperty( "name" ) ); assertEquals( "Account-4", ((Path) iterator.next().get( "paths" )).endNode().getProperty( "name" ) ); assertEquals( "Account-5", ((Path) iterator.next().get( "paths" )).endNode().getProperty( "name" ) ); assertEquals( "Account-7", ((Path) iterator.next().get( "paths" )).endNode().getProperty( "name" ) ); assertFalse( iterator.hasNext() ); }
@Test public void deniedExcludesCompanyFromPermissionsTree() throws Exception { QueryUnionExecutionResult results = queries.findAccessibleResources( "Sarah" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Account-4", ((Path) iterator.next().get( "paths" )).endNode().getProperty( "name" ) ); assertEquals( "Account-5", ((Path) iterator.next().get( "paths" )).endNode().getProperty( "name" ) ); assertEquals( "Account-1", ((Path) iterator.next().get( "paths" )).endNode().getProperty( "name" ) ); assertEquals( "Account-2", ((Path) iterator.next().get( "paths" )).endNode().getProperty( "name" ) ); assertEquals( "Account-3", ((Path) iterator.next().get( "paths" )).endNode().getProperty( "name" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
AccessControlWithRelationshipPropertiesQueries { public QueryUnionExecutionResult findAccessibleCompanies( String adminName ) { String inheritedQuery = "MATCH (admin:Administrator {name:{adminName}})\n" + "MATCH admin-[:MEMBER_OF]->()-[permission:ALLOWED]->()<-[:CHILD_OF*0..3]-company\n" + "WHERE (permission.inherit=true) AND NOT (admin-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0." + ".3]-company)\n" + "RETURN company"; String notInheritedQuery = "MATCH (admin:Administrator {name:{adminName}})\n" + "MATCH admin-[:MEMBER_OF]->()-[permission:ALLOWED]->(company)\n" + "WHERE (permission.inherit=false)\n" + "RETURN company"; Map<String, Object> params = new HashMap<>(); params.put( "adminName", adminName ); return executionEngine.execute( params, inheritedQuery, notInheritedQuery ); } AccessControlWithRelationshipPropertiesQueries( ExecutionEngineWrapper executionEngine ); QueryUnionExecutionResult findAccessibleResources( String adminName ); QueryUnionExecutionResult findAccessibleCompanies( String adminName ); QueryUnionExecutionResult findAccessibleAccountsForCompany( String adminName,
String companyName ); QueryUnionExecutionResult findAdminForResource( String resourceName ); QueryUnionExecutionResult findAdminForCompany( String companyName ); QueryUnionExecutionResult hasAccessToResource( String adminName, String resourceName ); QueryUnionExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test public void shouldGetAccessibleCompaniesForAdmin() throws Exception { QueryUnionExecutionResult results = queries.findAccessibleCompanies( "Sarah" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Startup", ((Node) iterator.next().get( "company" )).getProperty( "name" ) ); assertEquals( "Acme", ((Node) iterator.next().get( "company" )).getProperty( "name" ) ); assertFalse( iterator.hasNext() ); }
@Test public void shouldGetAccessibleCompaniesForAdminWhereNoAllowedInheritFalse() throws Exception { QueryUnionExecutionResult results = queries.findAccessibleCompanies( "Ben" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Acme", ((Node) iterator.next().get( "company" )).getProperty( "name" ) ); assertEquals( "Spinoff", ((Node) iterator.next().get( "company" )).getProperty( "name" ) ); assertEquals( "Startup", ((Node) iterator.next().get( "company" )).getProperty( "name" ) ); assertEquals( "Skunkworkz", ((Node) iterator.next().get( "company" )).getProperty( "name" ) ); assertFalse( iterator.hasNext() ); }
@Test public void moreComplexShouldGetAccessibleCompaniesForAdmin() throws Exception { QueryUnionExecutionResult results = queries.findAccessibleCompanies( "Liz" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "BigCompany", ((Node) iterator.next().get( "company" )).getProperty( "name" ) ); assertEquals( "One-ManShop", ((Node) iterator.next().get( "company" )).getProperty( "name" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
AccessControlWithRelationshipPropertiesQueries { public QueryUnionExecutionResult findAccessibleAccountsForCompany( String adminName, String companyName ) { String inheritedQuery = "MATCH (admin:Administrator {name:{adminName}}),\n" + " (company:Company{name:{companyName}})\n" + "MATCH admin-[:MEMBER_OF]->group-[permission:ALLOWED]->company<-[:CHILD_OF*0." + ".3]-subcompany<-[:WORKS_FOR]-employee-[:HAS_ACCOUNT]->account\n" + "WHERE (permission.inherit=true) AND NOT (admin-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0." + ".3]-subcompany)\n" + "RETURN account"; String notInheritedQuery = "MATCH (admin:Administrator {name:{adminName}}),\n" + " (company:Company{name:{companyName}})\n" + "MATCH admin-[:MEMBER_OF]->group-[permission:ALLOWED]->company<-[:WORKS_FOR]-employee-[:HAS_ACCOUNT" + "]->account\n" + "WHERE (permission.inherit=false)\n" + "RETURN account"; Map<String, Object> params = new HashMap<>(); params.put( "adminName", adminName ); params.put( "companyName", companyName ); return executionEngine.execute( params, inheritedQuery, notInheritedQuery ); } AccessControlWithRelationshipPropertiesQueries( ExecutionEngineWrapper executionEngine ); QueryUnionExecutionResult findAccessibleResources( String adminName ); QueryUnionExecutionResult findAccessibleCompanies( String adminName ); QueryUnionExecutionResult findAccessibleAccountsForCompany( String adminName,
String companyName ); QueryUnionExecutionResult findAdminForResource( String resourceName ); QueryUnionExecutionResult findAdminForCompany( String companyName ); QueryUnionExecutionResult hasAccessToResource( String adminName, String resourceName ); QueryUnionExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test public void shouldFindAccessibleAccountsForAdminAndCompany() throws Exception { QueryUnionExecutionResult results = queries.findAccessibleAccountsForCompany( "Sarah", "Startup" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Account-4", ((Node) iterator.next().get( "account" )).getProperty( "name" ) ); assertEquals( "Account-5", ((Node) iterator.next().get( "account" )).getProperty( "name" ) ); assertFalse( iterator.hasNext() ); }
@Test public void moreComplexShouldFindAccessibleAccountsForAdminAndCompany() throws Exception { QueryUnionExecutionResult results = queries.findAccessibleAccountsForCompany( "Liz", "BigCompany" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Account-8", ((Node) iterator.next().get( "account" )).getProperty( "name" ) ); assertFalse( iterator.hasNext() ); }
@Test public void shouldFindAccessibleAccountsForAdminAndCompanyWhenNoAllowedWithInheritFalse() throws Exception { QueryUnionExecutionResult results = queries.findAccessibleAccountsForCompany( "Ben", "Startup" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Account-4", ((Node) iterator.next().get( "account" )).getProperty( "name" ) ); assertEquals( "Account-5", ((Node) iterator.next().get( "account" )).getProperty( "name" ) ); assertEquals( "Account-7", ((Node) iterator.next().get( "account" )).getProperty( "name" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
EmailQueries { public ExecutionResult suspectBehaviour2() { String query = "MATCH p=(email:Email {id:'6'})<-[:REPLY_TO*1..4]-()<-[:SENT]-(replier)\n" + "RETURN replier.username AS replier, length(p) - 1 AS depth ORDER BY depth"; Map<String, Object> params = new HashMap<String, Object>(); return executionEngineWrapper.execute( query, params ); } EmailQueries( GraphDatabaseService db, ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult suspectBehaviour(); ExecutionResult suspectBehaviour2(); ExecutionResult suspectBehaviour3(); ExecutionResult lossyDb(); }### Answer:
@Test public void suspectBehaviour2() throws Exception { GraphDatabaseService db = createDatabase2(); EmailQueries queries = new EmailQueries( db, new PrintingExecutionEngineWrapper( db, "email", name ) ); ExecutionResult result = queries.suspectBehaviour2(); Iterator<Map<String, Object>> iterator = result.iterator(); Map<String, Object> next = iterator.next(); assertEquals( 1L, next.get( "depth" ) ); assertEquals( "Davina", next.get( "replier" ) ); next = iterator.next(); assertEquals( 1L, next.get( "depth" ) ); assertEquals( "Bob", next.get( "replier" ) ); next = iterator.next(); assertEquals( 2L, next.get( "depth" ) ); assertEquals( "Charlie", next.get( "replier" ) ); next = iterator.next(); assertEquals( 3L, next.get( "depth" ) ); assertEquals( "Bob", next.get( "replier" ) ); assertFalse( iterator.hasNext() ); db.shutdown(); } |
### Question:
AccessControlWithRelationshipPropertiesQueries { public QueryUnionExecutionResult findAdminForResource( String resourceName ) { String inheritedQuery = "MATCH (resource:Resource {name:{resourceName}}) \n" + "MATCH p=resource-[:WORKS_FOR|HAS_ACCOUNT*1..2]-company-[:CHILD_OF*0..3]->()<-[permission:ALLOWED]-()" + "<-[:MEMBER_OF]-admin\n" + "WHERE (permission.inherit=true) AND NOT (admin-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0..3]-company)\n" + "RETURN DISTINCT admin, p"; String notInheritedQuery = "MATCH (resource:Resource{name:{resourceName}})\n" + "MATCH p=resource-[:WORKS_FOR|HAS_ACCOUNT*1..2]-company<-[permission:ALLOWED]-()" + "<-[:MEMBER_OF]-admin\n" + "WHERE (permission.inherit=false)\n" + "RETURN DISTINCT admin, p"; Map<String, Object> params = new HashMap<>(); params.put( "resourceName", resourceName ); return executionEngine.execute( params, inheritedQuery, notInheritedQuery ); } AccessControlWithRelationshipPropertiesQueries( ExecutionEngineWrapper executionEngine ); QueryUnionExecutionResult findAccessibleResources( String adminName ); QueryUnionExecutionResult findAccessibleCompanies( String adminName ); QueryUnionExecutionResult findAccessibleAccountsForCompany( String adminName,
String companyName ); QueryUnionExecutionResult findAdminForResource( String resourceName ); QueryUnionExecutionResult findAdminForCompany( String companyName ); QueryUnionExecutionResult hasAccessToResource( String adminName, String resourceName ); QueryUnionExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test public void shouldFindAdminForAccountResourceWhereAllowedInheritAndAllowedNotInherit() throws Exception { QueryUnionExecutionResult results = queries.findAdminForResource( "Account-10" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Phil", ((Node) iterator.next().get( "admin" )).getProperty( "name" ) ); assertEquals( "Liz", ((Node) iterator.next().get( "admin" )).getProperty( "name" ) ); assertFalse( iterator.hasNext() ); }
@Test public void shouldFindAdminForEmployeeResourceWhereAllowedInheritAndDenied() throws Exception { QueryUnionExecutionResult results = queries.findAdminForResource( "Kate" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Ben", ((Node) iterator.next().get( "admin" )).getProperty( "name" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
AccessControlWithRelationshipPropertiesQueries { public QueryUnionExecutionResult findAdminForCompany( String companyName ) { String inheritedQuery = "MATCH (company:Company{name:{companyName}})\n" + "MATCH p=company-[:CHILD_OF*0..3]->()<-[permission:ALLOWED]-()<-[:MEMBER_OF]-admin\n" + "WHERE (permission.inherit=true) AND NOT (admin-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0..3]-company)\n" + "RETURN DISTINCT admin, p"; String notInheritedQuery = "MATCH (company:Company{name:{companyName}})\n" + "MATCH p=company<-[permission:ALLOWED]-()<-[:MEMBER_OF]-admin\n" + "WHERE (permission.inherit=false)\n" + "RETURN DISTINCT admin, p"; Map<String, Object> params = new HashMap<>(); params.put( "companyName", companyName ); return executionEngine.execute( params, inheritedQuery, notInheritedQuery ); } AccessControlWithRelationshipPropertiesQueries( ExecutionEngineWrapper executionEngine ); QueryUnionExecutionResult findAccessibleResources( String adminName ); QueryUnionExecutionResult findAccessibleCompanies( String adminName ); QueryUnionExecutionResult findAccessibleAccountsForCompany( String adminName,
String companyName ); QueryUnionExecutionResult findAdminForResource( String resourceName ); QueryUnionExecutionResult findAdminForCompany( String companyName ); QueryUnionExecutionResult hasAccessToResource( String adminName, String resourceName ); QueryUnionExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test public void shouldFindAdminForCompanyWithAllowedInherit() throws Exception { QueryUnionExecutionResult results = queries.findAdminForCompany( "BigCompany" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Liz", ((Node) iterator.next().get( "admin" )).getProperty( "name" ) ); assertFalse( iterator.hasNext() ); }
@Test public void shouldFindAdminForCompanyWithDenied() throws Exception { QueryUnionExecutionResult results = queries.findAdminForCompany( "AcquiredLtd" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertFalse( iterator.hasNext() ); }
@Test public void shouldFindAdminForCompanyWithAllowedInheritAndAllowedDoNotInheritTooLowInTree() throws Exception { QueryUnionExecutionResult results = queries.findAdminForCompany( "Subsidiary" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Phil", ((Node) iterator.next().get( "admin" )).getProperty( "name" ) ); assertFalse( iterator.hasNext() ); }
@Test public void shouldFindAdminForCompanyWithAllowedInheritAndAllowedAllowedDoNotInherit() throws Exception { QueryUnionExecutionResult results = queries.findAdminForCompany( "One-ManShop" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Phil", ((Node) iterator.next().get( "admin" )).getProperty( "name" ) ); assertEquals( "Liz", ((Node) iterator.next().get( "admin" )).getProperty( "name" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
AccessControlWithRelationshipPropertiesQueries { public QueryUnionExecutionResult hasAccessToResource( String adminName, String resourceName ) { String inheritedQuery = "MATCH (admin:Administrator {name:{adminName}}),\n" + " (resource:Resource{name:{resourceName}})\n" + "MATCH p=(admin)-[:MEMBER_OF]->()-[permission:ALLOWED]->()<-[:CHILD_OF*0." + ".3]-(company)-[:WORKS_FOR|HAS_ACCOUNT*1..2]-(resource)\n" + "WHERE (permission.inherit=true) AND NOT (admin)-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0..3]-(company)\n" + "RETURN COUNT(p) AS accessCount"; String notInheritedQuery = "MATCH (admin:Administrator {name:{adminName}}),\n" + " (resource:Resource{name:{resourceName}})\n" + "MATCH p=admin-[:MEMBER_OF]->()-[permission:ALLOWED]->company-[:WORKS_FOR|HAS_ACCOUNT*1..2]-resource\n" + "WHERE (permission.inherit=false)\n" + "RETURN COUNT(p) AS accessCount"; Map<String, Object> params = new HashMap<>(); params.put( "adminName", adminName ); params.put( "resourceName", resourceName ); return executionEngine.execute( params, inheritedQuery, notInheritedQuery ); } AccessControlWithRelationshipPropertiesQueries( ExecutionEngineWrapper executionEngine ); QueryUnionExecutionResult findAccessibleResources( String adminName ); QueryUnionExecutionResult findAccessibleCompanies( String adminName ); QueryUnionExecutionResult findAccessibleAccountsForCompany( String adminName,
String companyName ); QueryUnionExecutionResult findAdminForResource( String resourceName ); QueryUnionExecutionResult findAdminForCompany( String companyName ); QueryUnionExecutionResult hasAccessToResource( String adminName, String resourceName ); QueryUnionExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test public void shouldDetermineWhetherAdminHasAccessToResource() throws Exception { Map<String, List<Long>> testData = new HashMap<String, List<Long>>(); testData.put( "Alistair", asList( 1L, 0L ) ); testData.put( "Account-8", asList( 1L, 0L ) ); testData.put( "Eve", asList( 0L, 0L ) ); testData.put( "Account-9", asList( 0L, 0L ) ); testData.put( "Mary", asList( 0L, 0L ) ); testData.put( "Account-12", asList( 0L, 0L ) ); testData.put( "Gary", asList( 0L, 0L ) ); testData.put( "Account-11", asList( 0L, 0L ) ); testData.put( "Bill", asList( 0L, 1L ) ); testData.put( "Account-10", asList( 0L, 1L ) ); for ( String resourceName : testData.keySet() ) { List<Long> expectedResults = testData.get( resourceName ); Iterator<Long> expectedResultsIterator = expectedResults.iterator(); QueryUnionExecutionResult results = queries.hasAccessToResource( "Liz", resourceName ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( resourceName + " inherited", expectedResultsIterator.next(), iterator.next().get( "accessCount" ) ); assertEquals( resourceName + " not inherited", expectedResultsIterator.next(), iterator.next().get( "accessCount" ) ); assertFalse( iterator.hasNext() ); assertFalse( expectedResultsIterator.hasNext() ); } } |
### Question:
AccessControlWithRelationshipPropertiesQueries { public QueryUnionExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ) { String inheritedQuery = "MATCH (admin:Administrator {name:{adminName}}),\n" + " (company)<-[:CHILD_OF*0..3]-(:Company)-[:WORKS_FOR|HAS_ACCOUNT*1..2]-(resource:Resource {name:{resourceName}})\n" + "MATCH p=(admin)-[:MEMBER_OF]->()-[permission:ALLOWED]->(company)\n" + "WHERE (permission.inherit=true) AND NOT ((admin)-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0..3]-(company))\n" + "RETURN COUNT(p) AS accessCount"; String notInheritedQuery = "MATCH (admin:Administrator {name:{adminName}}),\n" + " (company)<-[:CHILD_OF*0..3]-(:Company)-[:WORKS_FOR|HAS_ACCOUNT*1..2]-(resource:Resource {name:{resourceName}})\n" + "MATCH p=(admin)-[:MEMBER_OF]->()-[permission:ALLOWED]->(company)\n" + "WHERE (permission.inherit=false)\n" + "RETURN COUNT(p) AS accessCount"; Map<String, Object> params = new HashMap<>(); params.put( "adminName", adminName ); params.put( "resourceName", resourceName ); return executionEngine.execute( params, inheritedQuery, notInheritedQuery ); } AccessControlWithRelationshipPropertiesQueries( ExecutionEngineWrapper executionEngine ); QueryUnionExecutionResult findAccessibleResources( String adminName ); QueryUnionExecutionResult findAccessibleCompanies( String adminName ); QueryUnionExecutionResult findAccessibleAccountsForCompany( String adminName,
String companyName ); QueryUnionExecutionResult findAdminForResource( String resourceName ); QueryUnionExecutionResult findAdminForCompany( String companyName ); QueryUnionExecutionResult hasAccessToResource( String adminName, String resourceName ); QueryUnionExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test @Ignore("does not work conceptually") public void shouldDetermineWhetherAdminHasAccessToIndexedResource() throws Exception { Map<String, List<Long>> testData = new LinkedHashMap<>(); testData.put( "Alistair", asList( 1L, 0L ) ); testData.put( "Account-8", asList( 1L, 0L ) ); testData.put( "Eve", asList( 0L, 0L ) ); testData.put( "Account-9", asList( 0L, 0L ) ); testData.put( "Mary", asList( 0L, 0L ) ); testData.put( "Account-12", asList( 0L, 0L ) ); testData.put( "Gary", asList( 0L, 0L ) ); testData.put( "Account-11", asList( 0L, 0L ) ); testData.put( "Bill", asList( 0L, 1L ) ); testData.put( "Account-10", asList( 0L, 1L ) ); for ( String resourceName : testData.keySet() ) { List<Long> expectedResults = testData.get( resourceName ); Iterator<Long> expectedResultsIterator = expectedResults.iterator(); QueryUnionExecutionResult results = queries.hasAccessToIndexedResource( "Liz", resourceName ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( resourceName + " inherited", expectedResultsIterator.next(), iterator.next().get( "accessCount" ) ); assertEquals( resourceName + " not inherited", expectedResultsIterator.next(), iterator.next().get( "accessCount" ) ); assertFalse( iterator.hasNext() ); assertFalse( expectedResultsIterator.hasNext() ); } } |
### Question:
ShakespeareQueries { public ExecutionResult theatreCityBard() { String query = "MATCH (theater:Venue {name:'Theatre Royal'}), \n" + " (newcastle:City {name:'Newcastle'}), \n" + " (bard:Author {lastname:'Shakespeare'})\n" + "RETURN theater.name AS theater, newcastle.name AS city, bard.lastname AS bard"; Map<String, Object> params = new HashMap<String, Object>(); return executionEngineWrapper.execute( query, params ); } ShakespeareQueries( ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult theatreCityBard(); ExecutionResult allPlays(); ExecutionResult latePeriodPlays(); ExecutionResult orderedByPerformance(); ExecutionResult exampleOfWith(); }### Answer:
@Test public void theatreCityBard() throws Exception { try ( Transaction tx = db.beginTx() ) { assertTheatreCityBard( queries.theatreCityBard() ); assertTheatreCityBard( queries2.theatreCityBard() ); assertTheatreCityBard( queriesUsingAutoIndexes.theatreCityBard() ); tx.success(); } } |
### Question:
EmailQueries { public ExecutionResult suspectBehaviour3() { String query = "MATCH (email:Email {id:'11'})<-[f:FORWARD_OF*]-() \n" + "RETURN count(f)"; Map<String, Object> params = new HashMap<String, Object>(); return executionEngineWrapper.execute( query, params ); } EmailQueries( GraphDatabaseService db, ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult suspectBehaviour(); ExecutionResult suspectBehaviour2(); ExecutionResult suspectBehaviour3(); ExecutionResult lossyDb(); }### Answer:
@Test public void suspectBehaviour3() throws Exception { GraphDatabaseService db = createDatabase3(); EmailQueries queries = new EmailQueries( db, new PrintingExecutionEngineWrapper( db, "email", name ) ); ExecutionResult result = queries.suspectBehaviour3(); Iterator<Object> objectIterator = result.columnAs( "count(f)" ); assertEquals( 2L, objectIterator.next() ); assertFalse( objectIterator.hasNext() ); db.shutdown(); } |
### Question:
ShakespeareQueries { public ExecutionResult exampleOfWith() { String query = "MATCH (bard:Author {lastname:'Shakespeare'})\n" + "MATCH (bard)-[w:WROTE_PLAY]->(play)\n" + "WITH play \n" + "ORDER BY w.year DESC \n" + "RETURN collect(play.title) AS plays"; Map<String, Object> params = new HashMap<String, Object>(); return executionEngineWrapper.execute( query, params ); } ShakespeareQueries( ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult theatreCityBard(); ExecutionResult allPlays(); ExecutionResult latePeriodPlays(); ExecutionResult orderedByPerformance(); ExecutionResult exampleOfWith(); }### Answer:
@Test public void exampleOfWith() throws Exception { try ( Transaction tx = db.beginTx() ) { assertExampleOfWith( queries.exampleOfWith() ); assertExampleOfWith( queries2.exampleOfWith() ); assertExampleOfWith( queriesUsingAutoIndexes.exampleOfWith() ); tx.success(); } } |
### Question:
ShakespeareQueries { public ExecutionResult allPlays() { String query = "MATCH (theater:Venue {name:'Theatre Royal'}), \n" + " (newcastle:City {name:'Newcastle'}), \n" + " (bard:Author {lastname:'Shakespeare'})\n" + "MATCH (newcastle)<-[:STREET|CITY*1..2]-(theater)\n" + " <-[:VENUE]-()-[:PERFORMANCE_OF]->()-[:PRODUCTION_OF]->\n" + " (play)<-[:WROTE_PLAY]-(bard)\n" + "RETURN DISTINCT play.title AS play"; Map<String, Object> params = new HashMap<String, Object>(); return executionEngineWrapper.execute( query, params ); } ShakespeareQueries( ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult theatreCityBard(); ExecutionResult allPlays(); ExecutionResult latePeriodPlays(); ExecutionResult orderedByPerformance(); ExecutionResult exampleOfWith(); }### Answer:
@Test public void shouldReturnAllPlays() throws Exception { try ( Transaction tx = db.beginTx() ) { assertAllPlays( queries.allPlays() ); assertAllPlays( queries2.allPlays() ); assertAllPlays( queriesUsingAutoIndexes.allPlays() ); } } |
### Question:
ShakespeareQueries { public ExecutionResult latePeriodPlays() { String query = "MATCH (theater:Venue {name:'Theatre Royal'}), \n" + " (newcastle:City {name:'Newcastle'}), \n" + " (bard:Author {lastname:'Shakespeare'})\n" + "MATCH (newcastle)<-[:STREET|CITY*1..2]-(theater)<-[:VENUE]-()-[:PERFORMANCE_OF]->()\n" + " -[:PRODUCTION_OF]->(play)<-[w:WROTE_PLAY]-(bard)\n" + "WHERE w.year > 1608\n" + "RETURN DISTINCT play.title AS play"; Map<String, Object> params = new HashMap<String, Object>(); return executionEngineWrapper.execute( query, params ); } ShakespeareQueries( ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult theatreCityBard(); ExecutionResult allPlays(); ExecutionResult latePeriodPlays(); ExecutionResult orderedByPerformance(); ExecutionResult exampleOfWith(); }### Answer:
@Test public void shouldReturnLatePeriodPlays() throws Exception { try ( Transaction tx = db.beginTx() ) { assertLatePeriodPlays( queries.latePeriodPlays() ); assertLatePeriodPlays( queries2.latePeriodPlays() ); assertLatePeriodPlays( queriesUsingAutoIndexes.latePeriodPlays() ); tx.success(); } } |
### Question:
ShakespeareQueries { public ExecutionResult orderedByPerformance() { String query = "MATCH (theater:Venue {name:'Theatre Royal'}), \n" + " (newcastle:City {name:'Newcastle'}), \n" + " (bard:Author {lastname:'Shakespeare'})\n" + "MATCH (newcastle)<-[:STREET|CITY*1..2]-(theater)<-[:VENUE]-()-[p:PERFORMANCE_OF]->()\n" + " -[:PRODUCTION_OF]->(play)<-[:WROTE_PLAY]-(bard)\n" + "RETURN play.title AS play, count(p) AS performance_count \n" + "ORDER BY performance_count DESC"; Map<String, Object> params = new HashMap<String, Object>(); return executionEngineWrapper.execute( query, params ); } ShakespeareQueries( ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult theatreCityBard(); ExecutionResult allPlays(); ExecutionResult latePeriodPlays(); ExecutionResult orderedByPerformance(); ExecutionResult exampleOfWith(); }### Answer:
@Test public void orderedByPerformance() throws Exception { try ( Transaction tx = db.beginTx() ) { assertOrderedByPerformance( queries.orderedByPerformance() ); assertOrderedByPerformance( queries2.orderedByPerformance() ); assertOrderedByPerformance( queriesUsingAutoIndexes.orderedByPerformance() ); tx.success(); } } |
### Question:
LogisticsQueries { public Iterable<Node> findShortestPathWithSimpleParcelRouteCalculator( String start, String end, Interval interval ) { return simpleParcelRouteCalculator.calculateRoute( start, end, interval ); } LogisticsQueries( GraphDatabaseService db, ExecutionEngineWrapper executionEngineWrapper ); Iterable<Node> findShortestPathWithParcelRouteCalculator( String start, String end, Interval interval ); Iterable<Node> findShortestPathWithSimpleParcelRouteCalculator( String start, String end, Interval interval ); ExecutionResult findShortestPathWithCypherReduce( String start, String end, Interval interval ); }### Answer:
@Test public void parcelRoutingUsingSimpleParcelRouteCalculatorRespectsIntervals() throws Exception { DateTime startDtm = interval3.getStart().plusDays( 2 ); Interval queryInterval = new Interval( startDtm, startDtm.plusDays( 1 ) ); Iterable<Node> results = queries.findShortestPathWithSimpleParcelRouteCalculator( "DeliveryArea-1", "DeliverySegment-3", queryInterval ); Iterator<Node> iterator = results.iterator(); assertEquals( "DeliveryArea-1", iterator.next().getProperty( "name" ) ); assertEquals( "DeliveryBase-1", iterator.next().getProperty( "name" ) ); assertEquals( "ParcelCentre-1", iterator.next().getProperty( "name" ) ); assertEquals( "DeliveryBase-3", iterator.next().getProperty( "name" ) ); assertEquals( "DeliveryArea-3", iterator.next().getProperty( "name" ) ); assertEquals( "DeliverySegment-3", iterator.next().getProperty( "name" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
EmailQueries { public ExecutionResult lossyDb() { String query = "MATCH (bob:User {username:'Bob'})-[e:EMAILED]->(charlie:User {username:'Charlie'})\n" + "RETURN e"; Map<String, Object> params = new HashMap<String, Object>(); return executionEngineWrapper.execute( query, params ); } EmailQueries( GraphDatabaseService db, ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult suspectBehaviour(); ExecutionResult suspectBehaviour2(); ExecutionResult suspectBehaviour3(); ExecutionResult lossyDb(); }### Answer:
@Test public void lossyDb() throws Exception { GraphDatabaseService db = createDatabase4(); EmailQueries queries = new EmailQueries( db, new PrintingExecutionEngineWrapper( db, "email", name ) ); ExecutionResult result = queries.lossyDb(); assertEquals(1, count(result.iterator())); db.shutdown(); } |
### Question:
SocialNetworkQueries { public ExecutionResult sharedInterestsSameCompany( String userName ) { String query = "MATCH (subject:User {name:{name}})\n" + "MATCH (subject)-[:WORKS_FOR]->(company)<-[:WORKS_FOR]-(person),\n" + " (subject)-[:INTERESTED_IN]->(interest)<-[:INTERESTED_IN]-(person)\n" + "RETURN person.name AS name,\n" + " count(interest) AS score,\n" + " collect(interest.name) AS interests\n" + "ORDER BY score DESC"; Map<String, Object> params = new HashMap<String, Object>(); params.put( "name", userName ); return executionEngineWrapper.execute( query, params ); } SocialNetworkQueries( GraphDatabaseService db, ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult sharedInterestsSameCompany( String userName ); ExecutionResult sharedInterestsAllCompanies( String userName, int limit ); ExecutionResult sharedInterestsAlsoInterestedInTopic( String userName, String topicLabel ); ExecutionResult friendOfAFriendWithInterest( String userName, String topicLabel, int limit ); Collection<Node> friendOfAFriendWithInterestTraversalFramework( String userName,
final String topicLabel,
int limit ); ExecutionResult friendOfAFriendWithMultipleInterest( String userName, int limit, String... interestLabels ); ExecutionResult friendWorkedWithFriendWithInterests( String userName, int limit, String... interestLabels ); ExecutionResult createWorkedWithRelationships( String userName ); ExecutionResult getAllUsers(); static final Label USER; static final Label TOPIC; }### Answer:
@Test public void sharedInterestsSameCompany() throws Exception { ExecutionResult results = queries.sharedInterestsSameCompany( "Sarah" ); Iterator<Map<String, Object>> iterator = results.iterator(); Map<String, Object> result = iterator.next(); assertEquals( "Ben", result.get( "name" ) ); assertEquals( 2l, result.get( "score" ) ); assertEquals( asList( "Graphs", "REST" ), result.get( "interests" ) ); result = iterator.next(); assertEquals( "Charlie", result.get( "name" ) ); assertEquals( 1l, result.get( "score" ) ); assertEquals( asList( "Graphs" ), result.get( "interests" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
SimpleSocialNetworkExtension { @GET @Path("/{name1}/{name2}") public String getDistance ( @PathParam("name1") String name1, @PathParam("name2") String name2 ) { ExecutionResult result = queries.pathBetweenTwoFriends( name1, name2 ); return String.valueOf( result.columnAs( "depth" ).next() ); } SimpleSocialNetworkExtension( @Context GraphDatabaseService db ); @GET @Path("/{name1}/{name2}") String getDistance( @PathParam("name1") String name1, @PathParam("name2") String name2 ); }### Answer:
@Test public void extensionShouldReturnDistance() throws Exception { SimpleSocialNetworkExtension extension = new SimpleSocialNetworkExtension( db ); String distance = extension.getDistance( "Ben", "Mike" ); assertEquals( "4", distance ); } |
### Question:
AccessControlQueries { public ExecutionResult findAccessibleResources( String adminName ) { String query = "MATCH (admin:Administrator {name:{adminName}})\n" + "MATCH paths=(admin)-[:MEMBER_OF]->()-[:ALLOWED_INHERIT]->()\n" + " <-[:CHILD_OF*0..3]-(company)<-[:WORKS_FOR]-(employee)\n" + " -[:HAS_ACCOUNT]->(account)\n" + "WHERE NOT ((admin)-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0..3]-(company))\n" + "RETURN employee.name AS employee, account.name AS account\n" + "UNION\n" + "MATCH (admin:Administrator {name:{adminName}})\n" + "MATCH paths=(admin)-[:MEMBER_OF]->()-[:ALLOWED_DO_NOT_INHERIT]->()\n" + " <-[:WORKS_FOR]-(employee)-[:HAS_ACCOUNT]->(account)\n" + "RETURN employee.name AS employee, account.name AS account"; Map<String, Object> params = new HashMap<>(); params.put( "adminName", adminName ); return executionEngine.execute( query, params ); } AccessControlQueries( ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult findAccessibleResources( String adminName ); ExecutionResult findAccessibleCompanies( String adminName ); ExecutionResult findAccessibleAccountsForCompany( String adminName, String companyName ); ExecutionResult findAdminForResource( String resourceName ); ExecutionResult findAdminForCompany( String companyName ); ExecutionResult hasAccessToResource( String adminName, String resourceName ); ExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test public void allowedWithInheritTrueGivesAccessToSubcompaniesAndAccounts() throws Exception { ExecutionResult results = queries.findAccessibleResources( "Ben" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Account-1", iterator.next().get( "account" ) ); assertEquals( "Account-2", iterator.next().get( "account" ) ); assertEquals( "Account-3", iterator.next().get( "account" ) ); assertEquals( "Account-6", iterator.next().get( "account" ) ); assertEquals( "Account-4", iterator.next().get( "account" ) ); assertEquals( "Account-5", iterator.next().get( "account" ) ); assertEquals( "Account-7", iterator.next().get( "account" ) ); assertFalse( iterator.hasNext() ); }
@Test public void deniedExcludesCompanyFromPermissionsTree() throws Exception { ExecutionResult results = queries.findAccessibleResources( "Sarah" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Account-4", iterator.next().get( "account" ) ); assertEquals( "Account-5", iterator.next().get( "account" ) ); assertEquals( "Account-1", iterator.next().get( "account" ) ); assertEquals( "Account-2", iterator.next().get( "account" ) ); assertEquals( "Account-3", iterator.next().get( "account" ) ); assertFalse( iterator.hasNext() ); }
@Test public void deniedExcludesCompanyFromPermissionsTree2() throws Exception { ExecutionResult results = queries.findAccessibleResources( "Liz" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Account-8", iterator.next().get( "account" ) ); assertEquals( "Account-10", iterator.next().get( "account" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
AccessControlQueries { public ExecutionResult findAccessibleCompanies( String adminName ) { String query = "MATCH (admin:Administrator {name:{adminName}})\n" + "MATCH (admin)-[:MEMBER_OF]->()-[:ALLOWED_INHERIT]->()<-[:CHILD_OF*0..3]-(company)\n" + "WHERE NOT ((admin)-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0..3]-(company))\n" + "RETURN company.name AS company\n" + "UNION\n" + "MATCH (admin:Administrator {name:{adminName}})\n" + "MATCH (admin)-[:MEMBER_OF]->()-[:ALLOWED_DO_NOT_INHERIT]->(company)\n" + "RETURN company.name AS company"; Map<String, Object> params = new HashMap<>(); params.put( "adminName", adminName ); return executionEngine.execute( query, params ); } AccessControlQueries( ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult findAccessibleResources( String adminName ); ExecutionResult findAccessibleCompanies( String adminName ); ExecutionResult findAccessibleAccountsForCompany( String adminName, String companyName ); ExecutionResult findAdminForResource( String resourceName ); ExecutionResult findAdminForCompany( String companyName ); ExecutionResult hasAccessToResource( String adminName, String resourceName ); ExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test public void shouldGetAccessibleCompaniesForAdmin() throws Exception { ExecutionResult results = queries.findAccessibleCompanies( "Sarah" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Startup", iterator.next().get( "company" ) ); assertEquals( "Acme", iterator.next().get( "company" ) ); assertFalse( iterator.hasNext() ); }
@Test public void shouldGetAccessibleCompaniesForAdminWhereNoAllowedInheritFalse() throws Exception { ExecutionResult results = queries.findAccessibleCompanies( "Ben" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Acme", iterator.next().get( "company" ) ); assertEquals( "Spinoff", iterator.next().get( "company" ) ); assertEquals( "Startup", iterator.next().get( "company" ) ); assertEquals( "Skunkworkz", iterator.next().get( "company" ) ); assertFalse( iterator.hasNext() ); }
@Test public void moreComplexShouldGetAccessibleCompaniesForAdmin() throws Exception { ExecutionResult results = queries.findAccessibleCompanies( "Liz" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "BigCompany", iterator.next().get( "company" ) ); assertEquals( "One-ManShop", iterator.next().get( "company" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
SocialNetworkQueries { public ExecutionResult sharedInterestsAllCompanies( String userName, int limit ) { String query = "MATCH (subject:User {name:{name}})\n" + "MATCH (subject)-[:INTERESTED_IN]->(interest)<-[:INTERESTED_IN]-(person),\n" + " (person)-[:WORKS_FOR]->(company)\n" + "RETURN person.name AS name,\n" + " company.name AS company,\n" + " count(interest) AS score,\n" + " collect(interest.name) AS interests\n" + "ORDER BY score DESC"; Map<String, Object> params = new HashMap<String, Object>(); params.put( "name", userName ); params.put( "resultLimit", limit ); return executionEngineWrapper.execute( query, params ); } SocialNetworkQueries( GraphDatabaseService db, ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult sharedInterestsSameCompany( String userName ); ExecutionResult sharedInterestsAllCompanies( String userName, int limit ); ExecutionResult sharedInterestsAlsoInterestedInTopic( String userName, String topicLabel ); ExecutionResult friendOfAFriendWithInterest( String userName, String topicLabel, int limit ); Collection<Node> friendOfAFriendWithInterestTraversalFramework( String userName,
final String topicLabel,
int limit ); ExecutionResult friendOfAFriendWithMultipleInterest( String userName, int limit, String... interestLabels ); ExecutionResult friendWorkedWithFriendWithInterests( String userName, int limit, String... interestLabels ); ExecutionResult createWorkedWithRelationships( String userName ); ExecutionResult getAllUsers(); static final Label USER; static final Label TOPIC; }### Answer:
@Test public void sharedInterestsAllCompanies() throws Exception { ExecutionResult results = queries.sharedInterestsAllCompanies( "Sarah", 10 ); Iterator<Map<String, Object>> iterator = results.iterator(); Map<String, Object> result; result = iterator.next(); assertEquals( "Arnold", result.get( "name" ) ); assertEquals( "Startup, Ltd", result.get( "company" ) ); assertEquals( 3l, result.get( "score" ) ); assertEquals( asList( "Java", "Graphs", "REST" ), result.get( "interests" ) ); result = iterator.next(); assertEquals( "Ben", result.get( "name" ) ); assertEquals( "Acme, Inc", result.get( "company" ) ); assertEquals( 2l, result.get( "score" ) ); assertEquals( asList( "Graphs", "REST" ), result.get( "interests" ) ); result = iterator.next(); assertEquals( "Gordon", result.get( "name" ) ); assertEquals( "Startup, Ltd", result.get( "company" ) ); assertEquals( 1l, result.get( "score" ) ); assertEquals( asList( "Graphs" ), result.get( "interests" ) ); result = iterator.next(); assertEquals( "Charlie", result.get( "name" ) ); assertEquals( "Acme, Inc", result.get( "company" ) ); assertEquals( 1l, result.get( "score" ) ); assertEquals( asList( "Graphs" ), result.get( "interests" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
AccessControlQueries { public ExecutionResult findAccessibleAccountsForCompany( String adminName, String companyName ) { String query = "MATCH (admin:Administrator {name:{adminName}}),\n" + " (company:Company {name:{companyName}})\n" + "MATCH (admin)-[:MEMBER_OF]->(group)-[:ALLOWED_INHERIT]->(company)\n" + " <-[:CHILD_OF*0..3]-(subcompany)<-[:WORKS_FOR]-(employee)-[:HAS_ACCOUNT]->(account)\n" + "WHERE NOT ((admin)-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0..3]-(subcompany))\n" + "RETURN account.name AS account\n" + "UNION\n" + "MATCH (admin:Administrator {name:{adminName}}),\n" + " (company:Company {name:{companyName}})\n" + "MATCH (admin)-[:MEMBER_OF]->(group)-[:ALLOWED_DO_NOT_INHERIT]->(company)\n" + " <-[:WORKS_FOR]-(employee)-[:HAS_ACCOUNT]->(account)\n" + "RETURN account.name AS account"; Map<String, Object> params = new HashMap<>(); params.put( "adminName", adminName ); params.put( "companyName", companyName ); return executionEngine.execute( query, params ); } AccessControlQueries( ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult findAccessibleResources( String adminName ); ExecutionResult findAccessibleCompanies( String adminName ); ExecutionResult findAccessibleAccountsForCompany( String adminName, String companyName ); ExecutionResult findAdminForResource( String resourceName ); ExecutionResult findAdminForCompany( String companyName ); ExecutionResult hasAccessToResource( String adminName, String resourceName ); ExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test public void shouldFindAccessibleAccountsForAdminAndCompany() throws Exception { ExecutionResult results = queries.findAccessibleAccountsForCompany( "Sarah", "Startup" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Account-4", iterator.next().get( "account" ) ); assertEquals( "Account-5", iterator.next().get( "account" ) ); assertFalse( iterator.hasNext() ); }
@Test public void moreComplexShouldFindAccessibleAccountsForAdminAndCompany() throws Exception { ExecutionResult results = queries.findAccessibleAccountsForCompany( "Liz", "BigCompany" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Account-8", iterator.next().get( "account" ) ); assertFalse( iterator.hasNext() ); }
@Test public void shouldFindAccessibleAccountsForAdminAndCompanyWhenNoAllowedWithInheritFalse() throws Exception { ExecutionResult results = queries.findAccessibleAccountsForCompany( "Ben", "Startup" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Account-4", iterator.next().get( "account" ) ); assertEquals( "Account-5", iterator.next().get( "account" ) ); assertEquals( "Account-7", iterator.next().get( "account" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
AccessControlQueries { public ExecutionResult findAdminForResource( String resourceName ) { String query = "MATCH (resource:Resource {name:{resourceName}})\n" + "MATCH p=(resource)-[:WORKS_FOR|HAS_ACCOUNT*1..2]-(company)\n" + " -[:CHILD_OF*0..3]->()<-[:ALLOWED_INHERIT]-()<-[:MEMBER_OF]-(admin)\n" + "WHERE NOT ((admin)-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0..3]-(company))\n" + "RETURN admin.name AS admin\n" + "UNION\n" + "MATCH (resource:Resource {name:{resourceName}})\n" + "MATCH p=(resource)-[:WORKS_FOR|HAS_ACCOUNT*1..2]-(company)\n" + " <-[:ALLOWED_DO_NOT_INHERIT]-()<-[:MEMBER_OF]-(admin)\n" + "RETURN admin.name AS admin"; Map<String, Object> params = new HashMap<>(); params.put( "resourceName", resourceName ); return executionEngine.execute( query, params ); } AccessControlQueries( ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult findAccessibleResources( String adminName ); ExecutionResult findAccessibleCompanies( String adminName ); ExecutionResult findAccessibleAccountsForCompany( String adminName, String companyName ); ExecutionResult findAdminForResource( String resourceName ); ExecutionResult findAdminForCompany( String companyName ); ExecutionResult hasAccessToResource( String adminName, String resourceName ); ExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test public void shouldFindAdminForAccountResourceWhereAllowedInheritAndAllowedNotInherit() throws Exception { ExecutionResult results = queries.findAdminForResource( "Account-10" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Phil", iterator.next().get( "admin" ) ); assertEquals( "Liz", iterator.next().get( "admin" ) ); assertFalse( iterator.hasNext() ); }
@Test public void shouldFindAdminForEmployeeResourceWhereAllowedInheritAndDenied() throws Exception { ExecutionResult results = queries.findAdminForResource( "Kate" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Ben", iterator.next().get( "admin" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
AccessControlQueries { public ExecutionResult findAdminForCompany( String companyName ) { String query = "MATCH (company:Company {name:{companyName}})\n" + "MATCH (company)-[:CHILD_OF*0..3]->()<-[:ALLOWED_INHERIT]-()<-[:MEMBER_OF]-(admin)\n" + "WHERE NOT ((admin)-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0..3]-(company))\n" + "RETURN admin.name AS admin\n" + "UNION\n" + "MATCH (company:Company {name:{companyName}})\n" + "MATCH (company)<-[:ALLOWED_DO_NOT_INHERIT]-()<-[:MEMBER_OF]-(admin)\n" + "RETURN admin.name AS admin"; Map<String, Object> params = new HashMap<>(); params.put( "companyName", companyName ); return executionEngine.execute( query, params ); } AccessControlQueries( ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult findAccessibleResources( String adminName ); ExecutionResult findAccessibleCompanies( String adminName ); ExecutionResult findAccessibleAccountsForCompany( String adminName, String companyName ); ExecutionResult findAdminForResource( String resourceName ); ExecutionResult findAdminForCompany( String companyName ); ExecutionResult hasAccessToResource( String adminName, String resourceName ); ExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test public void shouldFindAdminForCompanyWithAllowedInherit() throws Exception { ExecutionResult results = queries.findAdminForCompany( "BigCompany" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Liz", iterator.next().get( "admin" ) ); assertFalse( iterator.hasNext() ); }
@Test public void shouldFindAdminForCompanyWithDenied() throws Exception { ExecutionResult results = queries.findAdminForCompany( "AcquiredLtd" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertFalse( iterator.hasNext() ); }
@Test public void shouldFindAdminForCompanyWithAllowedInheritAndAllowedDoNotInheritTooLowInTree() throws Exception { ExecutionResult results = queries.findAdminForCompany( "Subsidiary" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Phil", iterator.next().get( "admin" ) ); assertFalse( iterator.hasNext() ); }
@Test public void shouldFindAdminForCompanyWithAllowedInheritAndAllowedAllowedDoNotInherit() throws Exception { ExecutionResult results = queries.findAdminForCompany( "One-ManShop" ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( "Phil", iterator.next().get( "admin" ) ); assertEquals( "Liz", iterator.next().get( "admin" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
SocialNetworkQueries { public ExecutionResult sharedInterestsAlsoInterestedInTopic( String userName, String topicLabel ) { String query = "MATCH (person:User {name:{name}})\n" + "MATCH (person)-[:INTERESTED_IN]->()<-[:INTERESTED_IN]-(colleague)-[:INTERESTED_IN]->(topic)\n" + "WHERE topic.name={topic}\n" + "WITH colleague\n" + "MATCH (colleague)-[:INTERESTED_IN]->(allTopics)\n" + "RETURN colleague.name AS name, collect(distinct(allTopics.name)) AS topics"; Map<String, Object> params = new HashMap<String, Object>(); params.put( "name", userName ); params.put( "topicQuery", "name:" + topicLabel ); params.put( "topic", topicLabel ); return executionEngineWrapper.execute( query, params ); } SocialNetworkQueries( GraphDatabaseService db, ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult sharedInterestsSameCompany( String userName ); ExecutionResult sharedInterestsAllCompanies( String userName, int limit ); ExecutionResult sharedInterestsAlsoInterestedInTopic( String userName, String topicLabel ); ExecutionResult friendOfAFriendWithInterest( String userName, String topicLabel, int limit ); Collection<Node> friendOfAFriendWithInterestTraversalFramework( String userName,
final String topicLabel,
int limit ); ExecutionResult friendOfAFriendWithMultipleInterest( String userName, int limit, String... interestLabels ); ExecutionResult friendWorkedWithFriendWithInterests( String userName, int limit, String... interestLabels ); ExecutionResult createWorkedWithRelationships( String userName ); ExecutionResult getAllUsers(); static final Label USER; static final Label TOPIC; }### Answer:
@Test public void sharedInterestsAlsoInterestedInTopic() throws Exception { ExecutionResult results = queries.sharedInterestsAlsoInterestedInTopic( "Ben", "Travel" ); Iterator<Map<String, Object>> iterator = results.iterator(); Map<String, Object> result = iterator.next(); assertEquals( "Arnold", result.get( "name" ) ); assertEquals( asList( "Graphs", "Java", "REST", "Travel" ), result.get( "topics" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
AccessControlQueries { public ExecutionResult hasAccessToResource( String adminName, String resourceName ) { String query = "MATCH (admin:Administrator {name:{adminName}}),\n" + " (resource:Resource {name:{resourceName}})\n" + "MATCH p=(admin)-[:MEMBER_OF]->()-[:ALLOWED_INHERIT]->()<-[:CHILD_OF*0." + ".3]-(company)-[:WORKS_FOR|HAS_ACCOUNT*1..2]-(resource)\n" + "WHERE NOT ((admin)-[:MEMBER_OF]->()-[:DENIED]->()<-[:CHILD_OF*0..3]-(company))\n" + "RETURN count(p) AS accessCount\n" + "UNION\n" + "MATCH (admin:Administrator {name:{adminName}}),\n" + " (resource:Resource {name:{resourceName}})\n" + "MATCH p=(admin)-[:MEMBER_OF]->()-[:ALLOWED_DO_NOT_INHERIT]->(company)-[:WORKS_FOR|HAS_ACCOUNT*1..2]-(resource)\n" + "RETURN count(p) AS accessCount"; Map<String, Object> params = new HashMap<>(); params.put( "adminName", adminName ); params.put( "resourceName", resourceName ); return executionEngine.execute( query, params ); } AccessControlQueries( ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult findAccessibleResources( String adminName ); ExecutionResult findAccessibleCompanies( String adminName ); ExecutionResult findAccessibleAccountsForCompany( String adminName, String companyName ); ExecutionResult findAdminForResource( String resourceName ); ExecutionResult findAdminForCompany( String companyName ); ExecutionResult hasAccessToResource( String adminName, String resourceName ); ExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test public void shouldDetermineWhetherAdminHasAccessToResource() throws Exception { Map<String, List<Long>> testData = new LinkedHashMap<>(); testData.put( "Alistair", asList( 1L, 0L ) ); testData.put( "Account-8", asList( 1L, 0L ) ); testData.put( "Eve", asList( 0L ) ); testData.put( "Account-9", asList( 0L ) ); testData.put( "Mary", asList( 0L ) ); testData.put( "Account-12", asList( 0L ) ); testData.put( "Gary", asList( 0L ) ); testData.put( "Account-11", asList( 0L ) ); testData.put( "Bill", asList( 0L, 1L ) ); testData.put( "Account-10", asList( 0L, 1L ) ); for ( String resourceName : testData.keySet() ) { List<Long> expectedResults = testData.get( resourceName ); Iterator<Long> expectedResultsIterator = expectedResults.iterator(); ExecutionResult results = queries.hasAccessToResource( "Liz", resourceName ); Iterator<Map<String, Object>> iterator = results.iterator(); assertTrue( iterator.hasNext() ); assertEquals( expectedResultsIterator.next(), iterator.next().get( "accessCount" ) ); if ( expectedResultsIterator.hasNext() ) { assertEquals( expectedResultsIterator.next(), iterator.next().get( "accessCount" ) ); } assertFalse( iterator.hasNext() ); } } |
### Question:
AccessControlQueries { public ExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ) { String query = "MATCH (admin:Administrator {name:{adminName}}),\n" + " c1=(company)<-[:CHILD_OF*0..3]-(:Company)-[:WORKS_FOR|HAS_ACCOUNT*1..2]-(resource:Resource {name:{resourceName}})\n" + "MATCH p=(admin)-[:MEMBER_OF]->()-[:ALLOWED_INHERIT]->(company)\n" + "WHERE NOT ((admin)-[:MEMBER_OF]->()-[:DENIED]->(company))\n" + "RETURN count(p) AS accessCount\n" + "UNION\n" + "MATCH (admin:Administrator {name:{adminName}}),\n" + " c1=(company:Company)-[:WORKS_FOR|HAS_ACCOUNT*1..2]-(resource:Resource {name:{resourceName}})\n" + "MATCH p=(admin)-[:MEMBER_OF]->()-[:ALLOWED_DO_NOT_INHERIT]->(company)\n" + "RETURN count(p) AS accessCount\n"; Map<String, Object> params = new HashMap<>(); params.put( "adminName", adminName ); params.put( "resourceName", resourceName ); return executionEngine.execute( query, params ); } AccessControlQueries( ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult findAccessibleResources( String adminName ); ExecutionResult findAccessibleCompanies( String adminName ); ExecutionResult findAccessibleAccountsForCompany( String adminName, String companyName ); ExecutionResult findAdminForResource( String resourceName ); ExecutionResult findAdminForCompany( String companyName ); ExecutionResult hasAccessToResource( String adminName, String resourceName ); ExecutionResult hasAccessToIndexedResource( String adminName, String resourceName ); }### Answer:
@Test @Ignore("does conceptually not work") public void shouldDetermineWhetherAdminHasAccessToIndexedResource() throws Exception { Map<String, Boolean> testData = new LinkedHashMap<>(); testData.put( "Alistair", true ); testData.put( "Account-8", true ); testData.put( "Eve", false ); testData.put( "Account-9", false ); testData.put( "Mary", false ); testData.put( "Account-12", false ); testData.put( "Gary", false ); testData.put( "Account-11", false ); testData.put( "Bill", true ); testData.put( "Account-10", true ); for ( Map.Entry<String, Boolean> entry : testData.entrySet() ) { ExecutionResult results = queries.hasAccessToIndexedResource( "Liz", entry.getKey() ); assertEquals( entry.getKey(), entry.getValue(), isAuthorized( results ) ); } } |
### Question:
SimpleSocialNetworkQueries { public ExecutionResult pathBetweenTwoFriends( String firstUser, String secondUser ) { String query = "MATCH (first:User{name:{firstUser}}),\n" + " (second:User{name:{secondUser}})\n" + "MATCH p=shortestPath(first-[*..4]-second)\n" + "RETURN length(p) AS depth"; Map<String, Object> params = new HashMap<String, Object>(); params.put( "firstUser", firstUser ); params.put( "secondUser", secondUser ); return executionEngine.execute( query, params ); } SimpleSocialNetworkQueries( GraphDatabaseService db ); ExecutionResult pathBetweenTwoFriends( String firstUser, String secondUser ); ExecutionResult friendOfAFriendToDepth4(String name); }### Answer:
@Test public void shouldReturnShortestPathBetweenTwoFriends() throws Exception { ExecutionResult results = queries.pathBetweenTwoFriends( "Ben", "Mike" ); assertTrue( results.iterator().hasNext() ); assertEquals( 4, results.iterator().next().get( "depth" ) ); }
@Test public void shouldReturnNoResultsWhenThereIsNotAPathBetweenTwoFriends() throws Exception { ExecutionResult results = queries.pathBetweenTwoFriends( "Ben", "Arnold" ); assertFalse( results.iterator().hasNext() ); } |
### Question:
SimpleSocialNetworkQueries { public ExecutionResult friendOfAFriendToDepth4(String name) { String query = "MATCH (person:User {name:{name}})-[:FRIEND]-()-[:FRIEND]-()-[:FRIEND]-()-[:FRIEND]-(friend)\n" + "RETURN friend.name AS name"; Map<String, Object> params = new HashMap<String, Object>(); params.put( "name", name ); return executionEngine.execute( query, params ); } SimpleSocialNetworkQueries( GraphDatabaseService db ); ExecutionResult pathBetweenTwoFriends( String firstUser, String secondUser ); ExecutionResult friendOfAFriendToDepth4(String name); }### Answer:
@Test public void friendOfAFriendToDepth4() throws Exception { ExecutionResult results = queries.friendOfAFriendToDepth4( "Ben" ); assertTrue( results.iterator().hasNext() ); assertEquals( "Mike", results.iterator().next().get( "name" ) ); assertFalse( results.iterator().hasNext() ); } |
### Question:
SocialNetworkQueries { public ExecutionResult friendOfAFriendWithInterest( String userName, String topicLabel, int limit ) { String query = "MATCH (subject:User {name:{name}})\n" + "MATCH p=(subject)-[:WORKED_ON]->()-[:WORKED_ON*0..2]-()\n" + " <-[:WORKED_ON]-(person)-[:INTERESTED_IN]->(interest)\n" + "WHERE person<>subject AND interest.name={topic}\n" + "WITH DISTINCT person.name AS name,\n" + " min(length(p)) as pathLength\n" + "ORDER BY pathLength ASC\n" + "LIMIT {resultLimit}\n" + "RETURN name, pathLength"; Map<String, Object> params = new HashMap<String, Object>(); params.put( "name", userName ); params.put( "topicQuery", "name:" + topicLabel ); params.put( "topic", topicLabel ); params.put( "resultLimit", limit ); return executionEngineWrapper.execute( query, params ); } SocialNetworkQueries( GraphDatabaseService db, ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult sharedInterestsSameCompany( String userName ); ExecutionResult sharedInterestsAllCompanies( String userName, int limit ); ExecutionResult sharedInterestsAlsoInterestedInTopic( String userName, String topicLabel ); ExecutionResult friendOfAFriendWithInterest( String userName, String topicLabel, int limit ); Collection<Node> friendOfAFriendWithInterestTraversalFramework( String userName,
final String topicLabel,
int limit ); ExecutionResult friendOfAFriendWithMultipleInterest( String userName, int limit, String... interestLabels ); ExecutionResult friendWorkedWithFriendWithInterests( String userName, int limit, String... interestLabels ); ExecutionResult createWorkedWithRelationships( String userName ); ExecutionResult getAllUsers(); static final Label USER; static final Label TOPIC; }### Answer:
@Test public void friendOfAFriendWithInterest() throws Exception { ExecutionResult results = queries.friendOfAFriendWithInterest( "Sarah", "Java", 3 ); Iterator<Map<String, Object>> iterator = results.iterator(); Map<String, Object> result = iterator.next(); assertEquals( "Arnold", result.get( "name" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
SocialNetworkQueries { public Collection<Node> friendOfAFriendWithInterestTraversalFramework( String userName, final String topicLabel, int limit ) { Node user = IteratorUtil.single(db.findNodesByLabelAndProperty(USER, "name", userName)); final Node topic = IteratorUtil.single(db.findNodesByLabelAndProperty(TOPIC, "name", topicLabel)); final RelationshipType interested_in = withName( "INTERESTED_IN" ); final RelationshipType worked_on = withName( "WORKED_ON" ); TraversalDescription traversalDescription = db.traversalDescription() .breadthFirst() .uniqueness( Uniqueness.NODE_GLOBAL ) .relationships( worked_on ) .evaluator( new Evaluator() { @Override public Evaluation evaluate( Path path ) { if ( path.length() == 0 ) { return Evaluation.EXCLUDE_AND_CONTINUE; } Node currentNode = path.endNode(); if ( path.length() % 2 == 0 ) { for ( Relationship rel : currentNode.getRelationships( interested_in, Direction.OUTGOING ) ) { if ( rel.getEndNode().equals( topic ) ) { if ( path.length() % 4 == 0 ) { return Evaluation.INCLUDE_AND_PRUNE; } else { return Evaluation.INCLUDE_AND_CONTINUE; } } } } if ( path.length() % 4 == 0 ) { return Evaluation.EXCLUDE_AND_PRUNE; } else { return Evaluation.EXCLUDE_AND_CONTINUE; } } } ); Iterable<Node> nodes = traversalDescription.traverse( user ).nodes(); Iterator<Node> iterator = nodes.iterator(); int nodeCount = 0; List<Node> results = new ArrayList<Node>(); while ( iterator.hasNext() && nodeCount++ < limit ) { results.add( iterator.next() ); } return results; } SocialNetworkQueries( GraphDatabaseService db, ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult sharedInterestsSameCompany( String userName ); ExecutionResult sharedInterestsAllCompanies( String userName, int limit ); ExecutionResult sharedInterestsAlsoInterestedInTopic( String userName, String topicLabel ); ExecutionResult friendOfAFriendWithInterest( String userName, String topicLabel, int limit ); Collection<Node> friendOfAFriendWithInterestTraversalFramework( String userName,
final String topicLabel,
int limit ); ExecutionResult friendOfAFriendWithMultipleInterest( String userName, int limit, String... interestLabels ); ExecutionResult friendWorkedWithFriendWithInterests( String userName, int limit, String... interestLabels ); ExecutionResult createWorkedWithRelationships( String userName ); ExecutionResult getAllUsers(); static final Label USER; static final Label TOPIC; }### Answer:
@Test public void friendOfAFriendWithInterestTraversalFramework() throws Exception { try ( Transaction tx = db.beginTx() ) { Collection<Node> results = queries.friendOfAFriendWithInterestTraversalFramework( "Arnold", "Art", 5 ); Iterator<Node> iterator = results.iterator(); assertEquals( "Emily", iterator.next().getProperty( "name" ) ); assertFalse( iterator.hasNext() ); tx.success(); } } |
### Question:
SocialNetworkQueries { public ExecutionResult friendWorkedWithFriendWithInterests( String userName, int limit, String... interestLabels ) { String query = "MATCH (subject:User {name:{name}})\n" + "MATCH p=(subject)-[:WORKED_WITH*0..1]-()-[:WORKED_WITH]-(person)\n" + " -[:INTERESTED_IN]->(interest)\n" + "WHERE person<>subject AND interest.name IN {interests}\n" + "WITH person, interest, min(length(p)) as pathLength\n" + "RETURN person.name AS name,\n" + " count(interest) AS score,\n" + " collect(interest.name) AS interests,\n" + " (pathLength - 1) AS distance\n" + "ORDER BY score DESC\n" + "LIMIT {resultLimit}"; Map<String, Object> params = new HashMap<String, Object>(); params.put( "name", userName ); params.put( "userQuery", "name:" + userName ); params.put( "interests", interestLabels ); params.put( "resultLimit", limit ); StringBuilder builder = new StringBuilder(); builder.append( "[" ); for ( int i = 0; i < interestLabels.length; i++ ) { builder.append( "'" ); builder.append( interestLabels[i] ); builder.append( "'" ); if ( i < interestLabels.length - 1 ) { builder.append( "," ); } } builder.append( "]" ); params.put( "topicQuery", builder.toString() ); return executionEngineWrapper.execute( query, params ); } SocialNetworkQueries( GraphDatabaseService db, ExecutionEngineWrapper executionEngineWrapper ); ExecutionResult sharedInterestsSameCompany( String userName ); ExecutionResult sharedInterestsAllCompanies( String userName, int limit ); ExecutionResult sharedInterestsAlsoInterestedInTopic( String userName, String topicLabel ); ExecutionResult friendOfAFriendWithInterest( String userName, String topicLabel, int limit ); Collection<Node> friendOfAFriendWithInterestTraversalFramework( String userName,
final String topicLabel,
int limit ); ExecutionResult friendOfAFriendWithMultipleInterest( String userName, int limit, String... interestLabels ); ExecutionResult friendWorkedWithFriendWithInterests( String userName, int limit, String... interestLabels ); ExecutionResult createWorkedWithRelationships( String userName ); ExecutionResult getAllUsers(); static final Label USER; static final Label TOPIC; }### Answer:
@Test public void friendWorkedWithFriendWithInterests() throws Exception { createAllWorkedWithRelationships(); ExecutionResult results = queries.friendWorkedWithFriendWithInterests( "Arnold", 5, "Art", "Design" ); Iterator<Map<String, Object>> iterator = results.iterator(); Map<String, Object> result = iterator.next(); assertEquals( "Emily", result.get( "name" ) ); assertFalse( iterator.hasNext() ); } |
### Question:
MailController { @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ApiOperation(value = "删除某条站内信") public void deleteMail(@PathVariable("id") @ApiParam(value = "站内信的id", required = true) Long id) { mailService.deleteMail(id); } @RequestMapping(value = "/{targetId}", method = RequestMethod.GET) @ApiOperation(value = "按照发信人或收信人的id以及发信状态", notes = "target是指定按照收信人还是发信人查询,可选值是sender和receiver;如果是按照收信人查询,那么必须指定mail_status,可选值为ALL、NOT_VIEWED、VIEWED;如果是按照发信人查询,则不需要给出该参数", response = PageInfo.class) @ApiResponses(value = { @ApiResponse(code = 404, message = "按收信人查询时未给出mail_status"), @ApiResponse(code = 404, message = "未指定target") }) PageInfo<MailDO> findMails(@PathVariable("targetId") @ApiParam(value = "发信人或收信人的id", required = true) Long targetId,
@RequestParam("target") @ApiParam(value = "按照收信人还是发信人查询,可选值是sender和receiver", required = true) String target,
@RequestParam(value = "pageNum", required = false, defaultValue = "1") @ApiParam(value = "页码,从1开始,默认为1", required = false) Integer pageNum,
@RequestParam(value = "pageSize", required = false, defaultValue = "5") @ApiParam(value = "页的大小,默认为5") Integer pageSize,
@RequestParam(value = "mail_status", required = false) @ApiParam(value = "递信状态,如果是按照收信人查询,那么必须指定,可选值为ALL、NOT_VIEWED、VIEWED", required = false) String mailStatus) {; @RequestMapping(method = RequestMethod.POST) @PreAuthorize("hasRole('ADMIN') or (hasRole('USER') and #mailDTO.sendMode.toString() != 'BROADCAST' )") @ApiOperation(value = "发送站内信,可以单独发送、批量或广播", notes = "如果是单独发送或批量,那么必须指定receivers,并将sendMode置为BATCH;如果是广播,那么无需指定receivers,并将SendMode置为BROADCAST") @ApiResponses(value = { @ApiResponse(code = 400, message = "mail对象属性校验失败"), @ApiResponse(code = 403, message = "广播功能仅支持管理员"), }) void sendMails(@RequestBody @Valid @ApiParam(value = "站内信对象", required = true) MailDTO mailDTO, BindingResult result, @AuthenticationPrincipal JWTUser user) {; @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ApiOperation(value = "删除某条站内信") void deleteMail(@PathVariable("id") @ApiParam(value = "站内信的id", required = true) Long id) {; }### Answer:
@Test public void deleteMail() throws Exception { } |
### Question:
UrlFactory extends RegexNamedEntityFactory { @Override protected List<NamedPattern> getRegexes(SpanCollection spanCollection, String lang) { return Collections.singletonList(new NamedPattern(URL, URL_PATTERN)); } }### Answer:
@Test public void testRegexPattern() { Pattern p = new UrlFactory().getRegexes(null, null).get(0).getPattern(); String url1 = "http: String url2 = "Ein beispiel: https: String wrong_url1 = "khttp: String wrong_url2 = "Das ist keine URL khttp: Assert.assertTrue(p.matcher(url1).find()); Assert.assertTrue(p.matcher(url2).find()); Assert.assertFalse(p.matcher(wrong_url1).find()); Assert.assertFalse(p.matcher(wrong_url2).find()); } |
### Question:
Util { public static <T> T nonNull(T o) { return nonNull(o, "Require Non null object"); } private Util(); static T nonNull(T o); static T nonNull(T o, String msg); static String notBlank(String s); static String notBlank(String s, String msg); }### Answer:
@Test(expected = NullPointerException.class) public void nonNull() { Util.nonNull(null); }
@Test public void nonNullArg() { try { Util.nonNull(null, "test"); fail(); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("test"); } } |
### Question:
DenbunBox { @CheckResult public static Denbun get(@NonNull String id) { checkInitialized(); DenbunId denbunId = DenbunId.of(id); if (presetAdjuster.containsKey(denbunId)) { return get(denbunId, presetAdjuster.get(denbunId)); } else { return get(denbunId, Denbun.DEFAULT_FREQUENCY_ADJUSTER); } } private DenbunBox(); static void init(@NonNull DenbunConfig config); @RestrictTo(TESTS) static void reset(); @CheckResult static Denbun get(@NonNull String id); @CheckResult static Denbun get(@NonNull String id, @NonNull FrequencyAdjuster adjuster); static void remove(@NonNull String id); static boolean exist(@NonNull String id); static void preset(@NonNull String id, @NonNull FrequencyAdjuster adjuster); static void preset(@NonNull Map<String, FrequencyAdjuster> adjusters); }### Answer:
@Test(expected = IllegalStateException.class) public void notInitializedGet() { Denbun msg = DenbunBox.get("id"); } |
### Question:
DenbunBox { public static void preset(@NonNull String id, @NonNull FrequencyAdjuster adjuster) { notBlank(id, "Denbun ID can not be blank"); nonNull(adjuster); checkInitialized(); presetAdjuster.put(DenbunId.of(id), adjuster); } private DenbunBox(); static void init(@NonNull DenbunConfig config); @RestrictTo(TESTS) static void reset(); @CheckResult static Denbun get(@NonNull String id); @CheckResult static Denbun get(@NonNull String id, @NonNull FrequencyAdjuster adjuster); static void remove(@NonNull String id); static boolean exist(@NonNull String id); static void preset(@NonNull String id, @NonNull FrequencyAdjuster adjuster); static void preset(@NonNull Map<String, FrequencyAdjuster> adjusters); }### Answer:
@Test(expected = IllegalStateException.class) public void notInitializedPresetSingle() { DenbunBox.preset("id", new CountAdjuster(1)); }
@Test(expected = IllegalStateException.class) public void notInitializedPresetMulti() { Map<String, FrequencyAdjuster> map = new HashMap<>(); map.put("id", new CountAdjuster(1)); DenbunBox.preset(map); } |
### Question:
DenbunBox { public static void init(@NonNull DenbunConfig config) { nonNull(config, "DenbunConfig can not be null"); if (initialized()) { Log.w("DenbunBox", "DenbunBox is already initialized."); return; } DenbunBox.config = config; DenbunBox.presetAdjuster = new HashMap<>(); DenbunBox.dao = config.daoProvider().create(config.preference()); } private DenbunBox(); static void init(@NonNull DenbunConfig config); @RestrictTo(TESTS) static void reset(); @CheckResult static Denbun get(@NonNull String id); @CheckResult static Denbun get(@NonNull String id, @NonNull FrequencyAdjuster adjuster); static void remove(@NonNull String id); static boolean exist(@NonNull String id); static void preset(@NonNull String id, @NonNull FrequencyAdjuster adjuster); static void preset(@NonNull Map<String, FrequencyAdjuster> adjusters); }### Answer:
@Test public void initTwice() { DenbunBox.init(config); DenbunBox.init(config); }
@Test(expected = NullPointerException.class) public void initNull() { DenbunBox.init(null); } |
### Question:
DenbunBox { public static boolean exist(@NonNull String id) { checkInitialized(); return dao.exist(DenbunId.of(id)); } private DenbunBox(); static void init(@NonNull DenbunConfig config); @RestrictTo(TESTS) static void reset(); @CheckResult static Denbun get(@NonNull String id); @CheckResult static Denbun get(@NonNull String id, @NonNull FrequencyAdjuster adjuster); static void remove(@NonNull String id); static boolean exist(@NonNull String id); static void preset(@NonNull String id, @NonNull FrequencyAdjuster adjuster); static void preset(@NonNull Map<String, FrequencyAdjuster> adjusters); }### Answer:
@Test public void exist() { SharedPreferences pref = config.preference(); DenbunBox.init(config); assertThat(pref.getAll().isEmpty()).isTrue(); Denbun msg = DenbunBox.get("id"); msg.shown(); assertThat(pref.getAll().isEmpty()).isFalse(); assertThat(DenbunBox.exist("id")).isTrue(); } |
### Question:
Denbun { public Denbun shown() { updateState(new State( state.id, adjuster.increment(state), Time.now(), state.count + 1)); return this; } private Denbun(@NonNull DenbunId id, @NonNull FrequencyAdjuster adjuster, @NonNull Dao dao); @NonNull String id(); boolean isSuppress(); long recent(); int count(); Denbun suppress(boolean suppress); boolean isShowable(); Denbun shown(); Denbun shown(ShowingAction action); static FrequencyAdjuster DEFAULT_FREQUENCY_ADJUSTER; }### Answer:
@Test public void showingAction() { DenbunBox.init(config); Denbun.ShowingAction action = spy(new Denbun.ShowingAction() { @Override public void call() { } }); Denbun msg = DenbunBox.get("id"); msg.shown(action); verify(action, times(1)).call(); } |
### Question:
Util { public static String notBlank(String s) { return notBlank(s, "Require not blank"); } private Util(); static T nonNull(T o); static T nonNull(T o, String msg); static String notBlank(String s); static String notBlank(String s, String msg); }### Answer:
@Test(expected = IllegalArgumentException.class) public void notBlank() { Util.notBlank(null); }
@Test public void notBlankArg() { try { Util.notBlank(null, "test"); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("test"); } } |
### Question:
State { @Override public String toString() { return "State{" + "id=" + id + ", frequency=" + frequency.value + ", recent=" + recent + ", count=" + count + '}'; } State(@NonNull DenbunId id, @NonNull Frequency frequency, long recent, int count); @CheckResult State frequency(Frequency frequency); boolean isSuppress(); boolean isShowable(); @Override String toString(); @NonNull final DenbunId id; @NonNull final Frequency frequency; final long recent; final int count; }### Answer:
@Test public void toStringTest() { String s = new State(DenbunId.of("id"), Frequency.MIN, 0L, 0).toString(); } |
### Question:
Frequency { @CheckResult public static Frequency of(@IntRange(from = LOWER, to = UPPER) int value) { return new Frequency(value); } private Frequency(int value); @CheckResult static Frequency of(@IntRange(from = LOWER, to = UPPER) int value); @CheckResult Frequency plus(@Nullable Frequency frequency); @CheckResult Frequency plus(int value); @CheckResult Frequency minus(@Nullable Frequency frequency); @CheckResult Frequency minus(int value); boolean isLimited(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final Frequency MAX; static final Frequency MIN; final int value; }### Answer:
@SuppressWarnings("Range") @Test public void init() { assertThat(Frequency.of(MAX + 1).value).isEqualTo(MAX); assertThat(Frequency.of(MIN - 1).value).isEqualTo(MIN); assertThat(Frequency.of(50).value).isEqualTo(50); } |
### Question:
Frequency { @CheckResult public Frequency plus(@Nullable Frequency frequency) { if (frequency == null) return this; return plus(frequency.value); } private Frequency(int value); @CheckResult static Frequency of(@IntRange(from = LOWER, to = UPPER) int value); @CheckResult Frequency plus(@Nullable Frequency frequency); @CheckResult Frequency plus(int value); @CheckResult Frequency minus(@Nullable Frequency frequency); @CheckResult Frequency minus(int value); boolean isLimited(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final Frequency MAX; static final Frequency MIN; final int value; }### Answer:
@Test public void plus() { assertThat(Frequency.of(MIN).plus(5)).isEqualTo(Frequency.of(MIN + 5)); assertThat(Frequency.of(MAX).plus(1)).isEqualTo(Frequency.of(MAX)); assertThat(Frequency.of(MIN).plus(5).value).isEqualTo(MIN + 5); assertThat(Frequency.of(MAX).plus(1).value).isEqualTo(MAX); assertThat(Frequency.of(MIN).plus(Frequency.of(5))).isEqualTo(Frequency.of(MIN + 5)); assertThat(Frequency.of(MAX).plus(Frequency.of(1))).isEqualTo(Frequency.of(MAX)); Frequency freq = Frequency.of(1); assertThat(freq.plus(null)).isEqualTo(freq); } |
### Question:
Frequency { @CheckResult public Frequency minus(@Nullable Frequency frequency) { if (frequency == null) return this; return minus(frequency.value); } private Frequency(int value); @CheckResult static Frequency of(@IntRange(from = LOWER, to = UPPER) int value); @CheckResult Frequency plus(@Nullable Frequency frequency); @CheckResult Frequency plus(int value); @CheckResult Frequency minus(@Nullable Frequency frequency); @CheckResult Frequency minus(int value); boolean isLimited(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final Frequency MAX; static final Frequency MIN; final int value; }### Answer:
@Test public void minus() { assertThat(Frequency.of(MAX).minus(5)).isEqualTo(Frequency.of(MAX - 5)); assertThat(Frequency.of(MIN).minus(5)).isEqualTo(Frequency.of(MIN)); assertThat(Frequency.of(MAX).minus(5).value).isEqualTo(MAX - 5); assertThat(Frequency.of(MIN).minus(5).value).isEqualTo(MIN); assertThat(Frequency.of(MAX).minus(Frequency.of(5))).isEqualTo(Frequency.of(MAX - 5)); assertThat(Frequency.of(MIN).minus(Frequency.of(5))).isEqualTo(Frequency.of(MIN)); Frequency freq = Frequency.of(1); assertThat(freq.minus(null)).isEqualTo(freq); } |
### Question:
Frequency { @Override public String toString() { return "Frequency{value=" + value + '}'; } private Frequency(int value); @CheckResult static Frequency of(@IntRange(from = LOWER, to = UPPER) int value); @CheckResult Frequency plus(@Nullable Frequency frequency); @CheckResult Frequency plus(int value); @CheckResult Frequency minus(@Nullable Frequency frequency); @CheckResult Frequency minus(int value); boolean isLimited(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final Frequency MAX; static final Frequency MIN; final int value; }### Answer:
@Test public void toStringTest() { String s = Frequency.of(1).toString(); } |
### Question:
ZuulRateLimitFilter extends ZuulFilter { @Override public Object run() { RequestContext context = getCurrentRequestContext(); HttpServletRequest request = context.getRequest(); Long remainingLimit = null; for (RateLimitCheck<HttpServletRequest> rl : filterConfig.getRateLimitChecks()) { ConsumptionProbeHolder probeHolder = rl.rateLimit(request, false); if (probeHolder != null && probeHolder.getConsumptionProbe() != null) { ConsumptionProbe probe = probeHolder.getConsumptionProbe(); if (probe.isConsumed()) { remainingLimit = getRemainingLimit(remainingLimit, probe); } else { context.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value()); context.addZuulResponseHeader("X-Rate-Limit-Retry-After-Seconds", "" + TimeUnit.NANOSECONDS.toSeconds(probe.getNanosToWaitForRefill())); context.setResponseBody(filterConfig.getHttpResponseBody()); context.setSendZuulResponse(false); break; } if(filterConfig.getStrategy().equals(RateLimitConditionMatchingStrategy.FIRST)) { break; } } }; return null; } ZuulRateLimitFilter(FilterConfiguration<HttpServletRequest> filterConfig); @Override Object run(); @Override boolean shouldFilter(); @Override int filterOrder(); @Override String filterType(); }### Answer:
@Test public void should_execute_all_checks_when_using_RateLimitConditionMatchingStrategy_All() { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/url"); RequestContext context = new RequestContext(); context.setRequest(request); RequestContext.testSetCurrentContext(context); when(rateLimitCheck1.rateLimit(any(), Mockito.anyBoolean())).thenReturn(consumptionProbeHolder); when(rateLimitCheck2.rateLimit(any(), Mockito.anyBoolean())).thenReturn(consumptionProbeHolder); when(rateLimitCheck3.rateLimit(any(), Mockito.anyBoolean())).thenReturn(consumptionProbeHolder); configuration.setStrategy(RateLimitConditionMatchingStrategy.ALL); filter.run(); verify(rateLimitCheck1, times(1)).rateLimit(any(), Mockito.anyBoolean()); verify(rateLimitCheck2, times(1)).rateLimit(any(), Mockito.anyBoolean()); verify(rateLimitCheck3, times(1)).rateLimit(any(), Mockito.anyBoolean()); }
@Test public void should_execute_only_one_check_when_using_RateLimitConditionMatchingStrategy_FIRST() { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/url"); RequestContext context = new RequestContext(); context.setRequest(request); RequestContext.testSetCurrentContext(context); configuration.setStrategy(RateLimitConditionMatchingStrategy.FIRST); when(rateLimitCheck1.rateLimit(any(), Mockito.anyBoolean())).thenReturn(consumptionProbeHolder); filter.run(); verify(rateLimitCheck1, times(1)).rateLimit(any(), Mockito.anyBoolean()); verify(rateLimitCheck2, times(0)).rateLimit(any(), Mockito.anyBoolean()); verify(rateLimitCheck3, times(0)).rateLimit(any(), Mockito.anyBoolean()); } |
### Question:
UriBuilder { public APIConnection build() throws APIKeyNotAssignedException { buildFinalURLWithCommandString(); buildFinalURLWithTheAPIKey(); buildFinalURLWithParametersToken(); return new APIConnection(finalURL); } UriBuilder(String baseURL); APIConnection build(); String getFinalURL(); UriBuilder setCommand(String commandString); UriBuilder setAPIKey(String apiKey, String apiKeyValue); void addUrlParameter(String key, String value); UriBuilder setParamStart(String paramStart); UriBuilder setApiKeyIsRequired(boolean apiKeyIsRequired); UriBuilder setNoAPIKeyRequired(); }### Answer:
@Test(expected = APIKeyNotAssignedException.class) public void should_Return_Exception_When_No_API_Key_Is_Supplied() throws APIKeyNotAssignedException { uriBuilder.build(); } |
### Question:
Utils { public static String readPropertyFrom(String propertyFilename, String propertyName) throws PropertyNotDefinedException { Properties prop = new Properties(); try { prop.load(new FileReader(new File(propertyFilename))); String propertyValue = prop.getProperty(propertyName); if(propertyValue != null) { return propertyValue; } throw new PropertyNotDefinedException("There is no property " + propertyName + " defined on file " + propertyFilename); } catch (IOException exception) { try { logger.info("Current path: " + new File(".").getCanonicalPath()); } catch (IOException e) { logger.info("Could not determine the current path"); } logger.error(exception.getMessage()); throw new IllegalStateException("IO Exception occurred due to the following: " + exception.getMessage()); } } private Utils(); static String dropTrailingSeparator(String urlParameterTokens, String paramSeparator); static String urlEncode(String token); static boolean isAValidJSONText(String resultAsString); static String readPropertyFrom(String propertyFilename, String propertyName); static String dropStartAndEndDelimiters(String inputString); static final String OPENING_BOX_BRACKET; static final String CLOSING_BOX_BRACKET; }### Answer:
@Test public void should_Return_Property_Value() throws PropertyNotDefinedException { String propertyValue = readPropertyFrom("src/test/resources/test.properties", "propertyKey"); assertThat("The property value is not the expected one", propertyValue, is("propertyValue")); }
@Test(expected = IllegalStateException.class) public void should_Fail_If_File_Does_Not_Exist() throws PropertyNotDefinedException { readPropertyFrom("non-existing-path", "propertyKey"); }
@Test(expected = PropertyNotDefinedException.class) public void should_Fail_If_Property_Does_Not_Exist() throws PropertyNotDefinedException { readPropertyFrom("src/test/resources/test.properties", "nonExistingPropertyKey"); } |
### Question:
APIReader { public String executeGetUrl() throws IOException { Map<String, String> requestProperties = new HashMap<String, String>(); requestProperties.put("User-Agent", "RestAPIUnifier"); return executeGetUrl(requestProperties); } APIReader(UriBuilder uriBuilder); APIReader(String url); APIReader(URL url); APIReader setHeader(String header, String value); String executeGetUrl(); String executePostUrl(); String executePostUrl(String urlParameters); String executeGetUrl(Map<String, String> requestProperties); }### Answer:
@Test public void should_Send_A_Get_Request() throws Exception { when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("response")); apiReader.executeGetUrl(); verify(mockConnection).setRequestMethod(GET_REQUEST_METHOD); }
@Test public void should_Return_Response_To_Http_Get_Request() throws Exception { when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("response")); String response = apiReader.executeGetUrl(); assertThat(response, is("response")); }
@Test public void should_Return_Response_Without_Delimiters_To_Http_Get_Request() throws Exception { when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("[[response]]")); String response = apiReader.executeGetUrl(); assertThat(response, is("response")); }
@Test public void should_Send_A_Get_Request_With_Request_Properties() throws Exception { when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("response")); Map<String, String> properties = createProperties(); apiReader.executeGetUrl(properties); verify(mockConnection).setRequestProperty("propertyKey1", "propertyValue1"); verify(mockConnection).setRequestProperty("propertyKey2", "propertyValue2"); }
@Test public void should_Send_A_Get_Request_With_No_Request_Properties() throws Exception { when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("response")); Map<String, String> properties = new HashMap<>(); apiReader.executeGetUrl(properties); verify(mockConnection, never()).setRequestProperty(anyString(), anyString()); }
@Test public void should_Disconnect_When_Http_Get_Request_Response_Is_Back() throws IOException { when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("")); apiReader.executeGetUrl(); verify(mockConnection).disconnect(); }
@Test public void should_Disconnect_When_Http_Get_Request_Throws_An_Error() throws IOException { when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("")); try { apiReader.executeGetUrl(); } catch (IOException e) { } finally { verify(mockConnection).disconnect(); } }
@Test(expected = IOException.class) public void should_Throw_Exception_When_Connection_Error_On_Get_Request() throws Exception { when(mockConnection.getInputStream()).thenThrow(IOException.class); apiReader.executeGetUrl(new HashMap<String, String>()); }
@Test public void should_Only_Return_Response_For_Last_Get_Request() throws IOException { when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("response 1")); apiReader.executeGetUrl(); when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("response 2")); String response = apiReader.executeGetUrl(); assertThat(response, is("response 2")); } |
### Question:
Utils { public static boolean isAValidJSONText(String resultAsString) { try { new JSONObject(resultAsString); return true; } catch (JSONException ex) { return false; } } private Utils(); static String dropTrailingSeparator(String urlParameterTokens, String paramSeparator); static String urlEncode(String token); static boolean isAValidJSONText(String resultAsString); static String readPropertyFrom(String propertyFilename, String propertyName); static String dropStartAndEndDelimiters(String inputString); static final String OPENING_BOX_BRACKET; static final String CLOSING_BOX_BRACKET; }### Answer:
@Test public void should_Verify_Invalid_JSON_Text() { assertThat(isAValidJSONText("{abcde"), is(false)); }
@Test public void should_Verify_Valid_JSON_Text() { assertThat(isAValidJSONText("{color:'green', status: 'good'}"), is(true)); } |
### Question:
APIReader { public String executePostUrl() throws IOException { return executePostUrl(""); } APIReader(UriBuilder uriBuilder); APIReader(String url); APIReader(URL url); APIReader setHeader(String header, String value); String executeGetUrl(); String executePostUrl(); String executePostUrl(String urlParameters); String executeGetUrl(Map<String, String> requestProperties); }### Answer:
@Test public void should_Return_Response_To_Http_Post_Request() throws Exception { when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("response")); String response = apiReader.executePostUrl(); assertThat(response, is("response")); }
@Test public void should_Return_Response_Without_Delimiters_To_Http_Post_Request() throws Exception { when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("[[response]]")); String response = apiReader.executePostUrl(); assertThat(response, is("response")); }
@Test public void should_Fire_Http_Post_Request_With_Appropriate_Url_Parameters() throws Exception { String urlParameters = "urlParameters"; when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("response")); APIReader apiReader = createAPIReaderWithMockWriter(); apiReader.executePostUrl(urlParameters); verify(mockWriter).write(urlParameters); verify(mockWriter).flush(); verify(mockWriter).close(); }
@Test public void should_Fire_Http_Post_Request_With_No_Url_Parameters() throws Exception { String urlParameters = ""; when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("response")); APIReader apiReader = createAPIReaderWithMockWriter(); apiReader.executePostUrl(urlParameters); verifyZeroInteractions(mockWriter); }
@Test public void should_Disconnect_When_Http_Post_Request_Response_Is_Back() throws IOException { when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("")); apiReader.executePostUrl(); verify(mockConnection).disconnect(); }
@Test(expected = IOException.class) public void should_Throw_Exception_When_Connection_Error_On_Post_Request() throws Exception { when(mockConnection.getInputStream()).thenThrow(IOException.class); apiReader.executePostUrl(); }
@Test public void should_Disconnect_When_Http_Post_Request_Throws_An_Error() throws IOException { when(mockConnection.getInputStream()).thenThrow(IOException.class); try { apiReader.executePostUrl(); } catch (IOException exception) { } finally { verify(mockConnection).disconnect(); } }
@Test public void should_Only_Return_Response_For_Last_Post_Request() throws IOException { when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("response 1")); apiReader.executePostUrl(); when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream("response 2")); String response = apiReader.executePostUrl(); assertThat(response, is("response 2")); } |
### Question:
Utils { public static String urlEncode(String token) { if (token == null) { throw new IllegalArgumentException(THE_TOKEN_CANNOT_BE_NULL_MSG); } String encodedToken = token; try { encodedToken = URLEncoder.encode(token, UTF_8); } catch (UnsupportedEncodingException uee) { logger.warn(INVALID_TOKEN_WARNING); } return encodedToken; } private Utils(); static String dropTrailingSeparator(String urlParameterTokens, String paramSeparator); static String urlEncode(String token); static boolean isAValidJSONText(String resultAsString); static String readPropertyFrom(String propertyFilename, String propertyName); static String dropStartAndEndDelimiters(String inputString); static final String OPENING_BOX_BRACKET; static final String CLOSING_BOX_BRACKET; }### Answer:
@Test public void should_Return_A_Plus_When_Space_Is_Passed_To_Encode_Token() { assertThat(urlEncode(" "), is("+")); }
@Test(expected = IllegalArgumentException.class) public void should_Return_IllegalArgumentException_If_Null_Is_Passed_To_Encode_Token() { Utils.urlEncode(null); } |
### Question:
Utils { public static String dropTrailingSeparator(String urlParameterTokens, String paramSeparator) { return StringUtils.substringBeforeLast(urlParameterTokens, paramSeparator); } private Utils(); static String dropTrailingSeparator(String urlParameterTokens, String paramSeparator); static String urlEncode(String token); static boolean isAValidJSONText(String resultAsString); static String readPropertyFrom(String propertyFilename, String propertyName); static String dropStartAndEndDelimiters(String inputString); static final String OPENING_BOX_BRACKET; static final String CLOSING_BOX_BRACKET; }### Answer:
@Test public void should_Remove_Trailing_Separator_From_String_When_A_Single_Separator_Is_Passed_In() { assertThat(dropTrailingSeparator("http: } |
### Question:
Utils { public static String dropStartAndEndDelimiters(String inputString) { String result = inputString; if (result.startsWith(OPENING_BOX_BRACKET)) { if (result.length() == 1) { result = ""; } else { result = result.substring(1, result.length()); } } if (result.endsWith(CLOSING_BOX_BRACKET)) { result = result.substring(0, result.length() - 1); } return result; } private Utils(); static String dropTrailingSeparator(String urlParameterTokens, String paramSeparator); static String urlEncode(String token); static boolean isAValidJSONText(String resultAsString); static String readPropertyFrom(String propertyFilename, String propertyName); static String dropStartAndEndDelimiters(String inputString); static final String OPENING_BOX_BRACKET; static final String CLOSING_BOX_BRACKET; }### Answer:
@Test public void should_Drop_Begin_And_End_Delimiters_In_An_Empty_String() { String inputString = "[]"; String actualString = dropStartAndEndDelimiters(inputString); String expectedString = ""; assertThat("Begin & End delimiters haven't been dropped", actualString, is(expectedString)); }
@Test public void should_Drop_Double_Begin_And_End_Delimiters_In_An_Empty_String() { String inputString = "[[]]"; String actualString = dropStartAndEndDelimiters(inputString); actualString = dropStartAndEndDelimiters(actualString); String expectedString = ""; assertThat("Begin & End delimiters haven't been dropped", actualString, is(expectedString)); }
@Test public void should_Drop_Begin_And_End_Delimiters_In_A_Simple_String() { String inputString = "[{'some': 'value'}]"; String actualString = dropStartAndEndDelimiters(inputString); String expectedString = "{'some': 'value'}"; assertThat("Begin & End delimiters haven't been dropped", actualString, is(expectedString)); }
@Test public void should_Drop_Double_Begin_And_End_Delimiters_In_A_Simple_String() { String inputString = "[[{'some': 'value'}]]"; String actualString = dropStartAndEndDelimiters(inputString); actualString = dropStartAndEndDelimiters(actualString); String expectedString = "{'some': 'value'}"; assertThat("Begin & End delimiters haven't been dropped", actualString, is(expectedString)); } |
### Question:
TracingChannelInterceptor extends ChannelInterceptorAdapter implements
ExecutorChannelInterceptor { private Message<?> preSendServerSpan(Message<?> message) { Span span = tracer.buildSpan((String) message.getHeaders() .getOrDefault(SIMP_DESTINATION, UNKNOWN_DESTINATION)) .asChildOf(tracer .extract(Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(message.getHeaders()))) .withTag(Tags.SPAN_KIND.getKey(), spanKind) .withTag(Tags.COMPONENT.getKey(), WEBSOCKET) .start(); return MessageBuilder.fromMessage(message) .setHeader(OPENTRACING_SPAN, span) .build(); } TracingChannelInterceptor(Tracer tracer, String spanKind); @Override Message<?> preSend(Message<?> message, MessageChannel channel); @Override void afterMessageHandled(Message<?> message, MessageChannel channel,
MessageHandler handler, Exception arg3); @Override Message<?> beforeHandle(Message<?> message, MessageChannel channel,
MessageHandler handler); }### Answer:
@Test public void testPreSendServerSpan() { MessageBuilder<String> messageBuilder = MessageBuilder.withPayload("Hi") .setHeader(TracingChannelInterceptor.SIMP_MESSAGE_TYPE, SimpMessageType.MESSAGE) .setHeader(TracingChannelInterceptor.SIMP_DESTINATION, TEST_DESTINATION); MockSpan parentSpan = mockTracer.buildSpan("parent").start(); mockTracer.inject(parentSpan.context(), Format.Builtin.TEXT_MAP, new TextMapInjectAdapter(messageBuilder)); TracingChannelInterceptor interceptor = new TracingChannelInterceptor(mockTracer, Tags.SPAN_KIND_SERVER); Message<?> processed = interceptor.preSend(messageBuilder.build(), null); assertTrue(processed.getHeaders().containsKey(TracingChannelInterceptor.OPENTRACING_SPAN)); MockSpan childSpan = (MockSpan) processed.getHeaders() .get(TracingChannelInterceptor.OPENTRACING_SPAN); assertEquals(parentSpan.context().spanId(), childSpan.parentId()); assertEquals(parentSpan.context().traceId(), childSpan.context().traceId()); assertEquals(TEST_DESTINATION, childSpan.operationName()); assertEquals(Tags.SPAN_KIND_SERVER, childSpan.tags().get(Tags.SPAN_KIND.getKey())); assertEquals(TracingChannelInterceptor.WEBSOCKET, childSpan.tags().get(Tags.COMPONENT.getKey())); } |
### Question:
TracedThreadPoolTaskScheduler extends ThreadPoolTaskScheduler { @Override public int getActiveCount() { return delegate.getActiveCount(); } TracedThreadPoolTaskScheduler(Tracer tracer, ThreadPoolTaskScheduler delegate); @Override void setPoolSize(int poolSize); @Override void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy); @Override void setErrorHandler(ErrorHandler errorHandler); @Override ScheduledExecutorService getScheduledExecutor(); @Override ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(); @Override int getPoolSize(); @Override boolean isRemoveOnCancelPolicy(); @Override int getActiveCount(); @Override void execute(Runnable task); @Override void execute(Runnable task, long startTimeout); @Override Future<?> submit(Runnable task); @Override Future<T> submit(Callable<T> task); @Override ListenableFuture<?> submitListenable(Runnable task); @Override ListenableFuture<T> submitListenable(Callable<T> task); @Override @Nullable ScheduledFuture<?> schedule(Runnable task, Trigger trigger); @Override ScheduledFuture<?> schedule(Runnable task, Date startTime); @Override ScheduledFuture<?> schedule(Runnable task, Instant startTime); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime,
Duration delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay); @Override void setThreadFactory(ThreadFactory threadFactory); @Override void setThreadNamePrefix(String threadNamePrefix); @Override void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler); @Override void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown); @Override void setAwaitTerminationSeconds(int awaitTerminationSeconds); @Override void setBeanName(String name); @Override void afterPropertiesSet(); @Override void initialize(); @Override void destroy(); @Override void shutdown(); @Override Thread newThread(Runnable runnable); @Override String getThreadNamePrefix(); @Override void setThreadPriority(int threadPriority); @Override int getThreadPriority(); @Override void setDaemon(boolean daemon); @Override boolean isDaemon(); @Override void setThreadGroupName(String name); @Override void setThreadGroup(ThreadGroup threadGroup); @Override @Nullable ThreadGroup getThreadGroup(); @Override Thread createThread(Runnable runnable); @Override boolean prefersShortLivedTasks(); }### Answer:
@Test public void getActiveCount() { scheduler.getActiveCount(); verify(delegate).getActiveCount(); } |
### Question:
TracedThreadPoolTaskScheduler extends ThreadPoolTaskScheduler { @Override public void execute(Runnable task) { delegate.execute(new TracedRunnable(task, tracer)); } TracedThreadPoolTaskScheduler(Tracer tracer, ThreadPoolTaskScheduler delegate); @Override void setPoolSize(int poolSize); @Override void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy); @Override void setErrorHandler(ErrorHandler errorHandler); @Override ScheduledExecutorService getScheduledExecutor(); @Override ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(); @Override int getPoolSize(); @Override boolean isRemoveOnCancelPolicy(); @Override int getActiveCount(); @Override void execute(Runnable task); @Override void execute(Runnable task, long startTimeout); @Override Future<?> submit(Runnable task); @Override Future<T> submit(Callable<T> task); @Override ListenableFuture<?> submitListenable(Runnable task); @Override ListenableFuture<T> submitListenable(Callable<T> task); @Override @Nullable ScheduledFuture<?> schedule(Runnable task, Trigger trigger); @Override ScheduledFuture<?> schedule(Runnable task, Date startTime); @Override ScheduledFuture<?> schedule(Runnable task, Instant startTime); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime,
Duration delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay); @Override void setThreadFactory(ThreadFactory threadFactory); @Override void setThreadNamePrefix(String threadNamePrefix); @Override void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler); @Override void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown); @Override void setAwaitTerminationSeconds(int awaitTerminationSeconds); @Override void setBeanName(String name); @Override void afterPropertiesSet(); @Override void initialize(); @Override void destroy(); @Override void shutdown(); @Override Thread newThread(Runnable runnable); @Override String getThreadNamePrefix(); @Override void setThreadPriority(int threadPriority); @Override int getThreadPriority(); @Override void setDaemon(boolean daemon); @Override boolean isDaemon(); @Override void setThreadGroupName(String name); @Override void setThreadGroup(ThreadGroup threadGroup); @Override @Nullable ThreadGroup getThreadGroup(); @Override Thread createThread(Runnable runnable); @Override boolean prefersShortLivedTasks(); }### Answer:
@Test public void execute() { final ArgumentCaptor<TracedRunnable> argumentCaptor = ArgumentCaptor.forClass(TracedRunnable.class); scheduler.execute(mockRunnable); verify(delegate).execute(argumentCaptor.capture()); verifyTracedRunnable(argumentCaptor.getValue(), mockRunnable, mockTracer); }
@Test public void executeWithTimeout() { final ArgumentCaptor<TracedRunnable> argumentCaptor = ArgumentCaptor.forClass(TracedRunnable.class); scheduler.execute(mockRunnable, 1000L); verify(delegate).execute(argumentCaptor.capture(), eq(1000L)); verifyTracedRunnable(argumentCaptor.getValue(), mockRunnable, mockTracer); } |
### Question:
TracedThreadPoolTaskScheduler extends ThreadPoolTaskScheduler { @Override public Future<?> submit(Runnable task) { return delegate.submit(new TracedRunnable(task, tracer)); } TracedThreadPoolTaskScheduler(Tracer tracer, ThreadPoolTaskScheduler delegate); @Override void setPoolSize(int poolSize); @Override void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy); @Override void setErrorHandler(ErrorHandler errorHandler); @Override ScheduledExecutorService getScheduledExecutor(); @Override ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(); @Override int getPoolSize(); @Override boolean isRemoveOnCancelPolicy(); @Override int getActiveCount(); @Override void execute(Runnable task); @Override void execute(Runnable task, long startTimeout); @Override Future<?> submit(Runnable task); @Override Future<T> submit(Callable<T> task); @Override ListenableFuture<?> submitListenable(Runnable task); @Override ListenableFuture<T> submitListenable(Callable<T> task); @Override @Nullable ScheduledFuture<?> schedule(Runnable task, Trigger trigger); @Override ScheduledFuture<?> schedule(Runnable task, Date startTime); @Override ScheduledFuture<?> schedule(Runnable task, Instant startTime); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime,
Duration delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay); @Override void setThreadFactory(ThreadFactory threadFactory); @Override void setThreadNamePrefix(String threadNamePrefix); @Override void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler); @Override void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown); @Override void setAwaitTerminationSeconds(int awaitTerminationSeconds); @Override void setBeanName(String name); @Override void afterPropertiesSet(); @Override void initialize(); @Override void destroy(); @Override void shutdown(); @Override Thread newThread(Runnable runnable); @Override String getThreadNamePrefix(); @Override void setThreadPriority(int threadPriority); @Override int getThreadPriority(); @Override void setDaemon(boolean daemon); @Override boolean isDaemon(); @Override void setThreadGroupName(String name); @Override void setThreadGroup(ThreadGroup threadGroup); @Override @Nullable ThreadGroup getThreadGroup(); @Override Thread createThread(Runnable runnable); @Override boolean prefersShortLivedTasks(); }### Answer:
@Test public void submitRunnable() { final ArgumentCaptor<TracedRunnable> argumentCaptor = ArgumentCaptor.forClass(TracedRunnable.class); scheduler.submit(mockRunnable); verify(delegate).submit(argumentCaptor.capture()); verifyTracedRunnable(argumentCaptor.getValue(), mockRunnable, mockTracer); }
@Test public void submitCallable() { final ArgumentCaptor<TracedCallable> argumentCaptor = ArgumentCaptor.forClass(TracedCallable.class); scheduler.submit(mockCallable); verify(delegate).submit(argumentCaptor.capture()); verifyTracedCallable(argumentCaptor.getValue(), mockCallable, mockTracer); } |
### Question:
TracedThreadPoolTaskScheduler extends ThreadPoolTaskScheduler { @Override public ListenableFuture<?> submitListenable(Runnable task) { return delegate.submitListenable(new TracedRunnable(task, tracer)); } TracedThreadPoolTaskScheduler(Tracer tracer, ThreadPoolTaskScheduler delegate); @Override void setPoolSize(int poolSize); @Override void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy); @Override void setErrorHandler(ErrorHandler errorHandler); @Override ScheduledExecutorService getScheduledExecutor(); @Override ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(); @Override int getPoolSize(); @Override boolean isRemoveOnCancelPolicy(); @Override int getActiveCount(); @Override void execute(Runnable task); @Override void execute(Runnable task, long startTimeout); @Override Future<?> submit(Runnable task); @Override Future<T> submit(Callable<T> task); @Override ListenableFuture<?> submitListenable(Runnable task); @Override ListenableFuture<T> submitListenable(Callable<T> task); @Override @Nullable ScheduledFuture<?> schedule(Runnable task, Trigger trigger); @Override ScheduledFuture<?> schedule(Runnable task, Date startTime); @Override ScheduledFuture<?> schedule(Runnable task, Instant startTime); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime,
Duration delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay); @Override void setThreadFactory(ThreadFactory threadFactory); @Override void setThreadNamePrefix(String threadNamePrefix); @Override void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler); @Override void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown); @Override void setAwaitTerminationSeconds(int awaitTerminationSeconds); @Override void setBeanName(String name); @Override void afterPropertiesSet(); @Override void initialize(); @Override void destroy(); @Override void shutdown(); @Override Thread newThread(Runnable runnable); @Override String getThreadNamePrefix(); @Override void setThreadPriority(int threadPriority); @Override int getThreadPriority(); @Override void setDaemon(boolean daemon); @Override boolean isDaemon(); @Override void setThreadGroupName(String name); @Override void setThreadGroup(ThreadGroup threadGroup); @Override @Nullable ThreadGroup getThreadGroup(); @Override Thread createThread(Runnable runnable); @Override boolean prefersShortLivedTasks(); }### Answer:
@Test public void submitListenableRunnable() { final ArgumentCaptor<TracedRunnable> argumentCaptor = ArgumentCaptor.forClass(TracedRunnable.class); scheduler.submitListenable(mockRunnable); verify(delegate).submitListenable(argumentCaptor.capture()); verifyTracedRunnable(argumentCaptor.getValue(), mockRunnable, mockTracer); }
@Test public void submitListenableCallable() { final ArgumentCaptor<TracedCallable> argumentCaptor = ArgumentCaptor.forClass(TracedCallable.class); scheduler.submitListenable(mockCallable); verify(delegate).submitListenable(argumentCaptor.capture()); verifyTracedCallable(argumentCaptor.getValue(), mockCallable, mockTracer); } |
### Question:
TracedThreadPoolTaskScheduler extends ThreadPoolTaskScheduler { @Override @Nullable public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) { return delegate.schedule(new TracedRunnable(task, tracer), trigger); } TracedThreadPoolTaskScheduler(Tracer tracer, ThreadPoolTaskScheduler delegate); @Override void setPoolSize(int poolSize); @Override void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy); @Override void setErrorHandler(ErrorHandler errorHandler); @Override ScheduledExecutorService getScheduledExecutor(); @Override ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(); @Override int getPoolSize(); @Override boolean isRemoveOnCancelPolicy(); @Override int getActiveCount(); @Override void execute(Runnable task); @Override void execute(Runnable task, long startTimeout); @Override Future<?> submit(Runnable task); @Override Future<T> submit(Callable<T> task); @Override ListenableFuture<?> submitListenable(Runnable task); @Override ListenableFuture<T> submitListenable(Callable<T> task); @Override @Nullable ScheduledFuture<?> schedule(Runnable task, Trigger trigger); @Override ScheduledFuture<?> schedule(Runnable task, Date startTime); @Override ScheduledFuture<?> schedule(Runnable task, Instant startTime); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime,
Duration delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay); @Override void setThreadFactory(ThreadFactory threadFactory); @Override void setThreadNamePrefix(String threadNamePrefix); @Override void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler); @Override void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown); @Override void setAwaitTerminationSeconds(int awaitTerminationSeconds); @Override void setBeanName(String name); @Override void afterPropertiesSet(); @Override void initialize(); @Override void destroy(); @Override void shutdown(); @Override Thread newThread(Runnable runnable); @Override String getThreadNamePrefix(); @Override void setThreadPriority(int threadPriority); @Override int getThreadPriority(); @Override void setDaemon(boolean daemon); @Override boolean isDaemon(); @Override void setThreadGroupName(String name); @Override void setThreadGroup(ThreadGroup threadGroup); @Override @Nullable ThreadGroup getThreadGroup(); @Override Thread createThread(Runnable runnable); @Override boolean prefersShortLivedTasks(); }### Answer:
@Test public void scheduleWithTrigger() { final ArgumentCaptor<TracedRunnable> argumentCaptor = ArgumentCaptor.forClass(TracedRunnable.class); final Trigger trigger = mock(Trigger.class); scheduler.schedule(mockRunnable, trigger); verify(delegate).schedule(argumentCaptor.capture(), eq(trigger)); verifyTracedRunnable(argumentCaptor.getValue(), mockRunnable, mockTracer); }
@Test public void scheduleWithDate() { final ArgumentCaptor<TracedRunnable> argumentCaptor = ArgumentCaptor.forClass(TracedRunnable.class); final Date date = mock(Date.class); scheduler.schedule(mockRunnable, date); verify(delegate).schedule(argumentCaptor.capture(), eq(date)); verifyTracedRunnable(argumentCaptor.getValue(), mockRunnable, mockTracer); }
@Test public void scheduleWithInstant() { final ArgumentCaptor<TracedRunnable> argumentCaptor = ArgumentCaptor.forClass(TracedRunnable.class); final Instant instant = Instant.now(); scheduler.schedule(mockRunnable, instant); verify(delegate).schedule(argumentCaptor.capture(), eq(instant)); verifyTracedRunnable(argumentCaptor.getValue(), mockRunnable, mockTracer); } |
### Question:
TracingChannelInterceptor extends ChannelInterceptorAdapter implements
ExecutorChannelInterceptor { private Message<?> preSendClientSpan(Message<?> message) { Span span = tracer.buildSpan((String) message.getHeaders() .getOrDefault(SIMP_DESTINATION, UNKNOWN_DESTINATION)) .withTag(Tags.SPAN_KIND.getKey(), spanKind) .withTag(Tags.COMPONENT.getKey(), WEBSOCKET) .start(); MessageBuilder<?> messageBuilder = MessageBuilder.fromMessage(message) .setHeader(OPENTRACING_SPAN, span); tracer .inject(span.context(), Format.Builtin.TEXT_MAP, new TextMapInjectAdapter(messageBuilder)); return messageBuilder.build(); } TracingChannelInterceptor(Tracer tracer, String spanKind); @Override Message<?> preSend(Message<?> message, MessageChannel channel); @Override void afterMessageHandled(Message<?> message, MessageChannel channel,
MessageHandler handler, Exception arg3); @Override Message<?> beforeHandle(Message<?> message, MessageChannel channel,
MessageHandler handler); }### Answer:
@Test public void testPreSendClientSpan() { MessageBuilder<String> messageBuilder = MessageBuilder.withPayload("Hi") .setHeader(TracingChannelInterceptor.SIMP_MESSAGE_TYPE, SimpMessageType.MESSAGE) .setHeader(TracingChannelInterceptor.SIMP_DESTINATION, TEST_DESTINATION); MockSpan parentSpan = mockTracer.buildSpan("parent").start(); TracingChannelInterceptor interceptor = new TracingChannelInterceptor(mockTracer, Tags.SPAN_KIND_CLIENT); Scope parentScope = mockTracer.scopeManager().activate(parentSpan); Message<?> processed = interceptor.preSend(messageBuilder.build(), null); parentScope.close(); parentSpan.finish(); assertTrue(processed.getHeaders().containsKey(TracingChannelInterceptor.OPENTRACING_SPAN)); MockSpan childSpan = (MockSpan) processed.getHeaders() .get(TracingChannelInterceptor.OPENTRACING_SPAN); assertEquals(parentSpan.context().spanId(), childSpan.parentId()); assertEquals(parentSpan.context().traceId(), childSpan.context().traceId()); MockSpan.MockContext context = (MockSpan.MockContext) mockTracer .extract(Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(processed.getHeaders())); assertEquals(childSpan.context().traceId(), context.traceId()); assertEquals(childSpan.context().spanId(), context.spanId()); assertEquals(TEST_DESTINATION, childSpan.operationName()); assertEquals(Tags.SPAN_KIND_CLIENT, childSpan.tags().get(Tags.SPAN_KIND.getKey())); assertEquals(TracingChannelInterceptor.WEBSOCKET, childSpan.tags().get(Tags.COMPONENT.getKey())); } |
### Question:
TracedThreadPoolTaskScheduler extends ThreadPoolTaskScheduler { @Override public void setThreadFactory(ThreadFactory threadFactory) { delegate.setThreadFactory(threadFactory); } TracedThreadPoolTaskScheduler(Tracer tracer, ThreadPoolTaskScheduler delegate); @Override void setPoolSize(int poolSize); @Override void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy); @Override void setErrorHandler(ErrorHandler errorHandler); @Override ScheduledExecutorService getScheduledExecutor(); @Override ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(); @Override int getPoolSize(); @Override boolean isRemoveOnCancelPolicy(); @Override int getActiveCount(); @Override void execute(Runnable task); @Override void execute(Runnable task, long startTimeout); @Override Future<?> submit(Runnable task); @Override Future<T> submit(Callable<T> task); @Override ListenableFuture<?> submitListenable(Runnable task); @Override ListenableFuture<T> submitListenable(Callable<T> task); @Override @Nullable ScheduledFuture<?> schedule(Runnable task, Trigger trigger); @Override ScheduledFuture<?> schedule(Runnable task, Date startTime); @Override ScheduledFuture<?> schedule(Runnable task, Instant startTime); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime,
Duration delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay); @Override void setThreadFactory(ThreadFactory threadFactory); @Override void setThreadNamePrefix(String threadNamePrefix); @Override void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler); @Override void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown); @Override void setAwaitTerminationSeconds(int awaitTerminationSeconds); @Override void setBeanName(String name); @Override void afterPropertiesSet(); @Override void initialize(); @Override void destroy(); @Override void shutdown(); @Override Thread newThread(Runnable runnable); @Override String getThreadNamePrefix(); @Override void setThreadPriority(int threadPriority); @Override int getThreadPriority(); @Override void setDaemon(boolean daemon); @Override boolean isDaemon(); @Override void setThreadGroupName(String name); @Override void setThreadGroup(ThreadGroup threadGroup); @Override @Nullable ThreadGroup getThreadGroup(); @Override Thread createThread(Runnable runnable); @Override boolean prefersShortLivedTasks(); }### Answer:
@Test public void setThreadFactory() { final ThreadFactory threadFactory = mock(ThreadFactory.class); scheduler.setThreadFactory(threadFactory); verify(delegate).setThreadFactory(threadFactory); } |
### Question:
TracedThreadPoolTaskScheduler extends ThreadPoolTaskScheduler { @Override public void setThreadNamePrefix(String threadNamePrefix) { delegate.setThreadNamePrefix(threadNamePrefix); } TracedThreadPoolTaskScheduler(Tracer tracer, ThreadPoolTaskScheduler delegate); @Override void setPoolSize(int poolSize); @Override void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy); @Override void setErrorHandler(ErrorHandler errorHandler); @Override ScheduledExecutorService getScheduledExecutor(); @Override ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(); @Override int getPoolSize(); @Override boolean isRemoveOnCancelPolicy(); @Override int getActiveCount(); @Override void execute(Runnable task); @Override void execute(Runnable task, long startTimeout); @Override Future<?> submit(Runnable task); @Override Future<T> submit(Callable<T> task); @Override ListenableFuture<?> submitListenable(Runnable task); @Override ListenableFuture<T> submitListenable(Callable<T> task); @Override @Nullable ScheduledFuture<?> schedule(Runnable task, Trigger trigger); @Override ScheduledFuture<?> schedule(Runnable task, Date startTime); @Override ScheduledFuture<?> schedule(Runnable task, Instant startTime); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime,
Duration delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay); @Override void setThreadFactory(ThreadFactory threadFactory); @Override void setThreadNamePrefix(String threadNamePrefix); @Override void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler); @Override void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown); @Override void setAwaitTerminationSeconds(int awaitTerminationSeconds); @Override void setBeanName(String name); @Override void afterPropertiesSet(); @Override void initialize(); @Override void destroy(); @Override void shutdown(); @Override Thread newThread(Runnable runnable); @Override String getThreadNamePrefix(); @Override void setThreadPriority(int threadPriority); @Override int getThreadPriority(); @Override void setDaemon(boolean daemon); @Override boolean isDaemon(); @Override void setThreadGroupName(String name); @Override void setThreadGroup(ThreadGroup threadGroup); @Override @Nullable ThreadGroup getThreadGroup(); @Override Thread createThread(Runnable runnable); @Override boolean prefersShortLivedTasks(); }### Answer:
@Test public void setThreadNamePrefix() { final String threadNamePrefix = "c137"; scheduler.setThreadNamePrefix(threadNamePrefix); verify(delegate).setThreadNamePrefix(threadNamePrefix); } |
### Question:
TracingChannelInterceptor extends ChannelInterceptorAdapter implements
ExecutorChannelInterceptor { @Override public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception arg3) { if ((handler instanceof WebSocketAnnotationMethodMessageHandler || handler instanceof SubProtocolWebSocketHandler) && SimpMessageType.MESSAGE.equals(message.getHeaders().get(SIMP_MESSAGE_TYPE))) { message.getHeaders().get(OPENTRACING_SCOPE, Scope.class).close(); message.getHeaders().get(OPENTRACING_SPAN, Span.class).finish(); } } TracingChannelInterceptor(Tracer tracer, String spanKind); @Override Message<?> preSend(Message<?> message, MessageChannel channel); @Override void afterMessageHandled(Message<?> message, MessageChannel channel,
MessageHandler handler, Exception arg3); @Override Message<?> beforeHandle(Message<?> message, MessageChannel channel,
MessageHandler handler); }### Answer:
@Test public void testAfterMessageHandled() { Span span = mock(Span.class); Scope scope = mock(Scope.class); MessageHandler messageHandler = mock(WebSocketAnnotationMethodMessageHandler.class); MessageBuilder<String> messageBuilder = MessageBuilder.withPayload("Hi") .setHeader(TracingChannelInterceptor.SIMP_MESSAGE_TYPE, SimpMessageType.MESSAGE) .setHeader(TracingChannelInterceptor.SIMP_DESTINATION, TEST_DESTINATION) .setHeader(TracingChannelInterceptor.OPENTRACING_SCOPE, scope) .setHeader(TracingChannelInterceptor.OPENTRACING_SPAN, span); TracingChannelInterceptor interceptor = new TracingChannelInterceptor(mockTracer, Tags.SPAN_KIND_CLIENT); interceptor.afterMessageHandled(messageBuilder.build(), null, messageHandler, null); verify(span).finish(); verify(scope).close(); } |
### Question:
TracedThreadPoolTaskScheduler extends ThreadPoolTaskScheduler { @Override public void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler) { delegate.setRejectedExecutionHandler(rejectedExecutionHandler); } TracedThreadPoolTaskScheduler(Tracer tracer, ThreadPoolTaskScheduler delegate); @Override void setPoolSize(int poolSize); @Override void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy); @Override void setErrorHandler(ErrorHandler errorHandler); @Override ScheduledExecutorService getScheduledExecutor(); @Override ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(); @Override int getPoolSize(); @Override boolean isRemoveOnCancelPolicy(); @Override int getActiveCount(); @Override void execute(Runnable task); @Override void execute(Runnable task, long startTimeout); @Override Future<?> submit(Runnable task); @Override Future<T> submit(Callable<T> task); @Override ListenableFuture<?> submitListenable(Runnable task); @Override ListenableFuture<T> submitListenable(Callable<T> task); @Override @Nullable ScheduledFuture<?> schedule(Runnable task, Trigger trigger); @Override ScheduledFuture<?> schedule(Runnable task, Date startTime); @Override ScheduledFuture<?> schedule(Runnable task, Instant startTime); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime,
Duration delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay); @Override void setThreadFactory(ThreadFactory threadFactory); @Override void setThreadNamePrefix(String threadNamePrefix); @Override void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler); @Override void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown); @Override void setAwaitTerminationSeconds(int awaitTerminationSeconds); @Override void setBeanName(String name); @Override void afterPropertiesSet(); @Override void initialize(); @Override void destroy(); @Override void shutdown(); @Override Thread newThread(Runnable runnable); @Override String getThreadNamePrefix(); @Override void setThreadPriority(int threadPriority); @Override int getThreadPriority(); @Override void setDaemon(boolean daemon); @Override boolean isDaemon(); @Override void setThreadGroupName(String name); @Override void setThreadGroup(ThreadGroup threadGroup); @Override @Nullable ThreadGroup getThreadGroup(); @Override Thread createThread(Runnable runnable); @Override boolean prefersShortLivedTasks(); }### Answer:
@Test public void setRejectedExecutionHandler() { final RejectedExecutionHandler rejectedExecutionHandler = mock(RejectedExecutionHandler.class); scheduler.setRejectedExecutionHandler(rejectedExecutionHandler); verify(delegate).setRejectedExecutionHandler(rejectedExecutionHandler); } |
### Question:
TracedThreadPoolTaskScheduler extends ThreadPoolTaskScheduler { @Override public void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) { delegate.setWaitForTasksToCompleteOnShutdown(waitForJobsToCompleteOnShutdown); } TracedThreadPoolTaskScheduler(Tracer tracer, ThreadPoolTaskScheduler delegate); @Override void setPoolSize(int poolSize); @Override void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy); @Override void setErrorHandler(ErrorHandler errorHandler); @Override ScheduledExecutorService getScheduledExecutor(); @Override ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(); @Override int getPoolSize(); @Override boolean isRemoveOnCancelPolicy(); @Override int getActiveCount(); @Override void execute(Runnable task); @Override void execute(Runnable task, long startTimeout); @Override Future<?> submit(Runnable task); @Override Future<T> submit(Callable<T> task); @Override ListenableFuture<?> submitListenable(Runnable task); @Override ListenableFuture<T> submitListenable(Callable<T> task); @Override @Nullable ScheduledFuture<?> schedule(Runnable task, Trigger trigger); @Override ScheduledFuture<?> schedule(Runnable task, Date startTime); @Override ScheduledFuture<?> schedule(Runnable task, Instant startTime); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime,
Duration delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay); @Override void setThreadFactory(ThreadFactory threadFactory); @Override void setThreadNamePrefix(String threadNamePrefix); @Override void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler); @Override void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown); @Override void setAwaitTerminationSeconds(int awaitTerminationSeconds); @Override void setBeanName(String name); @Override void afterPropertiesSet(); @Override void initialize(); @Override void destroy(); @Override void shutdown(); @Override Thread newThread(Runnable runnable); @Override String getThreadNamePrefix(); @Override void setThreadPriority(int threadPriority); @Override int getThreadPriority(); @Override void setDaemon(boolean daemon); @Override boolean isDaemon(); @Override void setThreadGroupName(String name); @Override void setThreadGroup(ThreadGroup threadGroup); @Override @Nullable ThreadGroup getThreadGroup(); @Override Thread createThread(Runnable runnable); @Override boolean prefersShortLivedTasks(); }### Answer:
@Test public void setWaitForTasksToCompleteOnShutdown() { scheduler.setWaitForTasksToCompleteOnShutdown(true); verify(delegate).setWaitForTasksToCompleteOnShutdown(true); } |
### Question:
TracedThreadPoolTaskScheduler extends ThreadPoolTaskScheduler { @Override public void setAwaitTerminationSeconds(int awaitTerminationSeconds) { delegate.setAwaitTerminationSeconds(awaitTerminationSeconds); } TracedThreadPoolTaskScheduler(Tracer tracer, ThreadPoolTaskScheduler delegate); @Override void setPoolSize(int poolSize); @Override void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy); @Override void setErrorHandler(ErrorHandler errorHandler); @Override ScheduledExecutorService getScheduledExecutor(); @Override ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(); @Override int getPoolSize(); @Override boolean isRemoveOnCancelPolicy(); @Override int getActiveCount(); @Override void execute(Runnable task); @Override void execute(Runnable task, long startTimeout); @Override Future<?> submit(Runnable task); @Override Future<T> submit(Callable<T> task); @Override ListenableFuture<?> submitListenable(Runnable task); @Override ListenableFuture<T> submitListenable(Callable<T> task); @Override @Nullable ScheduledFuture<?> schedule(Runnable task, Trigger trigger); @Override ScheduledFuture<?> schedule(Runnable task, Date startTime); @Override ScheduledFuture<?> schedule(Runnable task, Instant startTime); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime,
Duration delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay); @Override void setThreadFactory(ThreadFactory threadFactory); @Override void setThreadNamePrefix(String threadNamePrefix); @Override void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler); @Override void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown); @Override void setAwaitTerminationSeconds(int awaitTerminationSeconds); @Override void setBeanName(String name); @Override void afterPropertiesSet(); @Override void initialize(); @Override void destroy(); @Override void shutdown(); @Override Thread newThread(Runnable runnable); @Override String getThreadNamePrefix(); @Override void setThreadPriority(int threadPriority); @Override int getThreadPriority(); @Override void setDaemon(boolean daemon); @Override boolean isDaemon(); @Override void setThreadGroupName(String name); @Override void setThreadGroup(ThreadGroup threadGroup); @Override @Nullable ThreadGroup getThreadGroup(); @Override Thread createThread(Runnable runnable); @Override boolean prefersShortLivedTasks(); }### Answer:
@Test public void setAwaitTerminationSeconds() { scheduler.setAwaitTerminationSeconds(5); verify(delegate).setAwaitTerminationSeconds(5); } |
### Question:
TracedThreadPoolTaskScheduler extends ThreadPoolTaskScheduler { @Override public void setBeanName(String name) { delegate.setBeanName(name); } TracedThreadPoolTaskScheduler(Tracer tracer, ThreadPoolTaskScheduler delegate); @Override void setPoolSize(int poolSize); @Override void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy); @Override void setErrorHandler(ErrorHandler errorHandler); @Override ScheduledExecutorService getScheduledExecutor(); @Override ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(); @Override int getPoolSize(); @Override boolean isRemoveOnCancelPolicy(); @Override int getActiveCount(); @Override void execute(Runnable task); @Override void execute(Runnable task, long startTimeout); @Override Future<?> submit(Runnable task); @Override Future<T> submit(Callable<T> task); @Override ListenableFuture<?> submitListenable(Runnable task); @Override ListenableFuture<T> submitListenable(Callable<T> task); @Override @Nullable ScheduledFuture<?> schedule(Runnable task, Trigger trigger); @Override ScheduledFuture<?> schedule(Runnable task, Date startTime); @Override ScheduledFuture<?> schedule(Runnable task, Instant startTime); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Instant startTime, Duration period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period); @Override ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration period); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Instant startTime,
Duration delay); @Override ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay); @Override void setThreadFactory(ThreadFactory threadFactory); @Override void setThreadNamePrefix(String threadNamePrefix); @Override void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler); @Override void setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown); @Override void setAwaitTerminationSeconds(int awaitTerminationSeconds); @Override void setBeanName(String name); @Override void afterPropertiesSet(); @Override void initialize(); @Override void destroy(); @Override void shutdown(); @Override Thread newThread(Runnable runnable); @Override String getThreadNamePrefix(); @Override void setThreadPriority(int threadPriority); @Override int getThreadPriority(); @Override void setDaemon(boolean daemon); @Override boolean isDaemon(); @Override void setThreadGroupName(String name); @Override void setThreadGroup(ThreadGroup threadGroup); @Override @Nullable ThreadGroup getThreadGroup(); @Override Thread createThread(Runnable runnable); @Override boolean prefersShortLivedTasks(); }### Answer:
@Test public void setBeanName() { final String name = "gazorp"; scheduler.setBeanName(name); verify(delegate).setBeanName(name); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.