method2testcases
stringlengths 118
3.08k
|
---|
### Question:
TimeZoneStringBinding extends AbstractStringBinding<TimeZone> implements Binding<TimeZone, String> { @Override public TimeZone unmarshal(String str) { return TimeZone.getTimeZone(str); } @Override String marshal(TimeZone object); @Override TimeZone unmarshal(String str); Class<TimeZone> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(TimeZone.getTimeZone("PST"), BINDING.unmarshal("PST")); assertEquals(TimeZone.getTimeZone("GMT+08:00"), BINDING.unmarshal("GMT+08:00")); } |
### Question:
TimeZoneStringBinding extends AbstractStringBinding<TimeZone> implements Binding<TimeZone, String> { @Override public String marshal(TimeZone object) { return object.getID(); } @Override String marshal(TimeZone object); @Override TimeZone unmarshal(String str); Class<TimeZone> getBoundClass(); }### Answer:
@Test public void testMarshal() { assertEquals("PST", BINDING.marshal(TimeZone.getTimeZone("PST"))); assertEquals("GMT+08:00", BINDING.marshal(TimeZone.getTimeZone("GMT+08:00"))); } |
### Question:
CharacterStringBinding extends AbstractStringBinding<Character> implements Binding<Character, String> { @Override public Character unmarshal(String object) { if (object.length() == 1) { return Character.valueOf(object.charAt(0)); } else { throw new IllegalArgumentException("Only single character String can be unmarshalled to a Character"); } } @Override Character unmarshal(String object); Class<Character> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new Character('a'), BINDING.unmarshal("a")); assertEquals(new Character('\u00df'), BINDING.unmarshal("\u00df")); } |
### Question:
FloatStringBinding extends AbstractStringBinding<Float> implements Binding<Float, String> { @Override public Float unmarshal(String object) { return Float.valueOf(Float.parseFloat(object)); } @Override Float unmarshal(String object); Class<Float> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new Float(0), BINDING.unmarshal("0")); assertEquals(new Float(1), BINDING.unmarshal("1")); assertEquals(new Float(3.4028235E38F), BINDING.unmarshal("" + Float.MAX_VALUE)); assertEquals(new Float(1.4E-45), BINDING.unmarshal("" + Float.MIN_VALUE)); assertEquals(new Float("0.0"), BINDING.unmarshal("0.0")); assertEquals(new Float("1.123"), BINDING.unmarshal("1.123")); } |
### Question:
InetAddressStringBinding extends AbstractStringBinding<InetAddress> implements Binding<InetAddress, String> { @Override public InetAddress unmarshal(String object) { try { return InetAddress.getByName(object); } catch (UnknownHostException ex) { throw new IllegalArgumentException("Unknown host " + object + ":" + object); } } @Override InetAddress unmarshal(String object); @Override String marshal(InetAddress object); Class<InetAddress> getBoundClass(); }### Answer:
@Test public void testUnmarshal() throws UnknownHostException { assertEquals(InetAddress.getByName("www.google.com"), BINDING.unmarshal("www.google.com")); } |
### Question:
InetAddressStringBinding extends AbstractStringBinding<InetAddress> implements Binding<InetAddress, String> { @Override public String marshal(InetAddress object) { return object.getHostAddress(); } @Override InetAddress unmarshal(String object); @Override String marshal(InetAddress object); Class<InetAddress> getBoundClass(); }### Answer:
@Test public void testMarshal() throws UnknownHostException { assertEquals("173.194.36.104", BINDING.marshal(InetAddress.getByAddress("173.194.36.104", new byte[]{(byte)173,(byte)194,36,104}))); } |
### Question:
CurrencyStringBinding extends AbstractStringBinding<Currency> implements Binding<Currency, String> { @Override public Currency unmarshal(String object) { return Currency.getInstance(object); } @Override Currency unmarshal(String object); Class<Currency> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(Currency.getInstance("USD"), BINDING.unmarshal("USD")); assertEquals(Currency.getInstance("GBP"), BINDING.unmarshal("GBP")); assertEquals(Currency.getInstance("AUD"), BINDING.unmarshal("AUD")); } |
### Question:
LongStringBinding extends AbstractStringBinding<Long> implements Binding<Long, String> { @Override public Long unmarshal(String object) { return Long.valueOf(Long.parseLong(object)); } @Override Long unmarshal(String object); Class<Long> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new Long(0).toString(), BINDING.unmarshal("0").toString()); assertEquals(new Long(1).toString(), BINDING.unmarshal("1").toString()); assertEquals(new Long(9223372036854775807L).toString(), BINDING.unmarshal("" + Long.MAX_VALUE).toString()); assertEquals(new Long(-9223372036854775808L).toString(), BINDING.unmarshal("" + Long.MIN_VALUE).toString()); } |
### Question:
CharSequenceStringBinding extends AbstractStringBinding<CharSequence> implements Binding<CharSequence, String> { @Override public CharSequence unmarshal(String object) { return object; } @Override CharSequence unmarshal(String object); Class<CharSequence> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals("Hello World", BINDING.unmarshal("Hello World")); } |
### Question:
AtomicBooleanStringBinding extends AbstractStringBinding<AtomicBoolean> implements Binding<AtomicBoolean, String> { @Override public AtomicBoolean unmarshal(String object) { return new AtomicBoolean(Boolean.parseBoolean(object)); } @Override AtomicBoolean unmarshal(String object); Class<AtomicBoolean> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new AtomicBoolean(true).toString(), BINDING.unmarshal("true").toString()); assertEquals(new AtomicBoolean(false).toString(), BINDING.unmarshal("false").toString()); } |
### Question:
ClassLoaderUtils { public static ClassLoader getClassLoader() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassStringBinding.class.getClassLoader(); } return cl; } private ClassLoaderUtils(); static ClassLoader getClassLoader(); }### Answer:
@Test public void testGetClassLoader() { assertEquals("sun.misc.Launcher$AppClassLoader", ClassLoaderUtils.getClassLoader().getClass().getName()); } |
### Question:
AtomicLongStringBinding extends AbstractStringBinding<AtomicLong> implements Binding<AtomicLong, String> { @Override public AtomicLong unmarshal(String object) { return new AtomicLong(Long.parseLong(object)); } @Override AtomicLong unmarshal(String object); Class<AtomicLong> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new AtomicLong(0).toString(), BINDING.unmarshal("0").toString()); assertEquals(new AtomicLong(1).toString(), BINDING.unmarshal("1").toString()); assertEquals(new AtomicLong(9223372036854775807L).toString(), BINDING.unmarshal("" + Long.MAX_VALUE).toString()); assertEquals(new AtomicLong(-9223372036854775808L).toString(), BINDING.unmarshal("" + Long.MIN_VALUE).toString()); } |
### Question:
IterableEnumeration implements Iterable<E> { public IterableEnumeration(Enumeration<E> enumeration) { this.enumeration = enumeration; } IterableEnumeration(Enumeration<E> enumeration); Iterator<E> iterator(); static Iterable<E> wrapEnumeration(Enumeration<E> enumeration); }### Answer:
@Test public void testIterableEnumeration() { Iterable<String> testIterable = new IterableEnumeration<String>(ELEMENTS.elements()); Iterator<String> myIter = testIterable.iterator(); testValues(myIter); testIterable = IterableEnumeration.wrapEnumeration(ELEMENTS.elements()); myIter = testIterable.iterator(); testValues(myIter); } |
### Question:
StringUtils { public static String removeWhitespace(String string) { if (string == null || string.length() == 0) { return string; } else { int codePoints = string.codePointCount(0, string.length()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < codePoints; i++) { int offset = string.offsetByCodePoints(0, i); int nextCodePoint = string.codePointAt(offset); if (!Character.isWhitespace(nextCodePoint)) { sb.appendCodePoint(nextCodePoint); } } if (string.length() == sb.length()) { return string; } else { return sb.toString(); } } } private StringUtils(); static String removeWhitespace(String string); }### Answer:
@Test public void testRemoveWhitespace() { assertEquals("Helloworld", StringUtils.removeWhitespace("Hello world")); assertEquals("Hello\uD840\uDC08", StringUtils.removeWhitespace("Hello \uD840\uDC08")); assertEquals("Hello\uD840\uDC08", StringUtils.removeWhitespace(" Hello \uD840\uDC08 ")); assertEquals("Hello\uD840\uDC08", StringUtils.removeWhitespace(" Hello \n \uD840\uDC08 ")); } |
### Question:
BindingConverter implements ConditionalGenericConverter { public Object convert(Object object, TypeDescriptor sourceType, TypeDescriptor targetType) { final Object result; result = BINDING.convertTo(object.getClass(), targetType.getObjectType(), object, matchAnnotationToScope(targetType.getAnnotations())); return result; } Set<ConvertiblePair> getConvertibleTypes(); Object convert(Object object, TypeDescriptor sourceType, TypeDescriptor targetType); boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType); }### Answer:
@Test public void testBindingConverter() { assertEquals(new SubjectC("String"), svc.convert("String:String", SubjectC.class)); } |
### Question:
E164PhoneNumberWithExtension implements PhoneNumber, Serializable { public String getCountryDiallingCode() { return "+" + number.getCountryCode(); } E164PhoneNumberWithExtension(Phonenumber.PhoneNumber prototype); protected E164PhoneNumberWithExtension(String e164PhoneNumberWithExtension); protected E164PhoneNumberWithExtension(String e164PhoneNumber, String extension); protected E164PhoneNumberWithExtension(String phoneNumber, CountryCode defaultCountryCode); protected E164PhoneNumberWithExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofE164PhoneNumberString(String e164PhoneNumber); @FromString static E164PhoneNumberWithExtension ofE164PhoneNumberWithExtensionString(String e164PhoneNumber); static E164PhoneNumberWithExtension ofE164PhoneNumberStringAndExtension(String e164PhoneNumber, String extension); static E164PhoneNumberWithExtension ofPhoneNumberString(String phoneNumber, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofPhoneNumberStringAndExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); Phonenumber.PhoneNumber getUnderlyingPhoneNumber(); ISOCountryCode extractCountryCode(); String getCountryDiallingCode(); String getNationalNumber(); String getExtension(); String toE164NumberString(); @ToString String toE164NumberWithExtensionString(); String extractAreaCode(); String extractSubscriberNumber(); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testGetCountryDiallingCode() { E164PhoneNumberWithExtension number = E164PhoneNumberWithExtension.ofPhoneNumberStringAndExtension("1963350474", null, ISOCountryCode.GB); assertEquals("+44", number.getCountryDiallingCode()); } |
### Question:
E164PhoneNumberWithExtension implements PhoneNumber, Serializable { public String getNationalNumber() { return "" + number.getNationalNumber(); } E164PhoneNumberWithExtension(Phonenumber.PhoneNumber prototype); protected E164PhoneNumberWithExtension(String e164PhoneNumberWithExtension); protected E164PhoneNumberWithExtension(String e164PhoneNumber, String extension); protected E164PhoneNumberWithExtension(String phoneNumber, CountryCode defaultCountryCode); protected E164PhoneNumberWithExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofE164PhoneNumberString(String e164PhoneNumber); @FromString static E164PhoneNumberWithExtension ofE164PhoneNumberWithExtensionString(String e164PhoneNumber); static E164PhoneNumberWithExtension ofE164PhoneNumberStringAndExtension(String e164PhoneNumber, String extension); static E164PhoneNumberWithExtension ofPhoneNumberString(String phoneNumber, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofPhoneNumberStringAndExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); Phonenumber.PhoneNumber getUnderlyingPhoneNumber(); ISOCountryCode extractCountryCode(); String getCountryDiallingCode(); String getNationalNumber(); String getExtension(); String toE164NumberString(); @ToString String toE164NumberWithExtensionString(); String extractAreaCode(); String extractSubscriberNumber(); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testGetNationalNumber() { E164PhoneNumberWithExtension number = E164PhoneNumberWithExtension.ofPhoneNumberStringAndExtension("+441963350474", null, ISOCountryCode.DE); assertEquals("1963350474", number.getNationalNumber()); } |
### Question:
E164PhoneNumberWithExtension implements PhoneNumber, Serializable { public String getExtension() { return number.hasExtension() ? number.getExtension() : null; } E164PhoneNumberWithExtension(Phonenumber.PhoneNumber prototype); protected E164PhoneNumberWithExtension(String e164PhoneNumberWithExtension); protected E164PhoneNumberWithExtension(String e164PhoneNumber, String extension); protected E164PhoneNumberWithExtension(String phoneNumber, CountryCode defaultCountryCode); protected E164PhoneNumberWithExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofE164PhoneNumberString(String e164PhoneNumber); @FromString static E164PhoneNumberWithExtension ofE164PhoneNumberWithExtensionString(String e164PhoneNumber); static E164PhoneNumberWithExtension ofE164PhoneNumberStringAndExtension(String e164PhoneNumber, String extension); static E164PhoneNumberWithExtension ofPhoneNumberString(String phoneNumber, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofPhoneNumberStringAndExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); Phonenumber.PhoneNumber getUnderlyingPhoneNumber(); ISOCountryCode extractCountryCode(); String getCountryDiallingCode(); String getNationalNumber(); String getExtension(); String toE164NumberString(); @ToString String toE164NumberWithExtensionString(); String extractAreaCode(); String extractSubscriberNumber(); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testGetExtension() { E164PhoneNumberWithExtension number = E164PhoneNumberWithExtension.ofPhoneNumberStringAndExtension("+441963350474", null, ISOCountryCode.DE); assertNull(number.getExtension()); number = E164PhoneNumberWithExtension.ofPhoneNumberStringAndExtension("+441963350474", "14354", ISOCountryCode.DE); assertEquals("14354", number.getExtension()); } |
### Question:
E164PhoneNumberWithExtension implements PhoneNumber, Serializable { public String toE164NumberString() { StringBuilder result = new StringBuilder(); PHONE_NUMBER_UTIL.format(number, PhoneNumberFormat.E164, result); return result.toString(); } E164PhoneNumberWithExtension(Phonenumber.PhoneNumber prototype); protected E164PhoneNumberWithExtension(String e164PhoneNumberWithExtension); protected E164PhoneNumberWithExtension(String e164PhoneNumber, String extension); protected E164PhoneNumberWithExtension(String phoneNumber, CountryCode defaultCountryCode); protected E164PhoneNumberWithExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofE164PhoneNumberString(String e164PhoneNumber); @FromString static E164PhoneNumberWithExtension ofE164PhoneNumberWithExtensionString(String e164PhoneNumber); static E164PhoneNumberWithExtension ofE164PhoneNumberStringAndExtension(String e164PhoneNumber, String extension); static E164PhoneNumberWithExtension ofPhoneNumberString(String phoneNumber, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofPhoneNumberStringAndExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); Phonenumber.PhoneNumber getUnderlyingPhoneNumber(); ISOCountryCode extractCountryCode(); String getCountryDiallingCode(); String getNationalNumber(); String getExtension(); String toE164NumberString(); @ToString String toE164NumberWithExtensionString(); String extractAreaCode(); String extractSubscriberNumber(); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testToE164NumberString() { E164PhoneNumberWithExtension number = E164PhoneNumberWithExtension.ofPhoneNumberStringAndExtension("1963350474", null, ISOCountryCode.GB); assertEquals("+441963350474", number.toE164NumberString()); } |
### Question:
ClassStringBinding extends AbstractStringBinding<Class> implements Binding<Class, String> { @Override public Class unmarshal(String object) { return ClassUtils.getClass(object); } @Override Class unmarshal(String object); @Override String marshal(Class clazz); Class<Class> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { String className = "java.net.URL"; assertEquals(URL.class, BINDING.unmarshal(className)); assertEquals(new URL[]{}.getClass(), BINDING.unmarshal(className + "[]")); assertEquals(new URL[][]{}.getClass(), BINDING.unmarshal(className + "[][]")); assertEquals(Long.TYPE, BINDING.unmarshal("long")); assertEquals(Boolean.TYPE, BINDING.unmarshal("boolean")); assertEquals(Float.TYPE, BINDING.unmarshal("float")); assertEquals(Short.TYPE, BINDING.unmarshal("short")); assertEquals(Byte.TYPE, BINDING.unmarshal("byte")); assertEquals(Double.TYPE, BINDING.unmarshal("double")); assertEquals(Character.TYPE, BINDING.unmarshal("char")); assertEquals(new long[]{}.getClass(), BINDING.unmarshal("long[]")); assertEquals(new boolean[]{}.getClass(), BINDING.unmarshal("boolean[]")); assertEquals(new float[]{}.getClass(), BINDING.unmarshal("float[]")); assertEquals(new short[]{}.getClass(), BINDING.unmarshal("short[]")); assertEquals(new byte[]{}.getClass(), BINDING.unmarshal("byte[]")); assertEquals(new double[]{}.getClass(), BINDING.unmarshal("double[]")); assertEquals(new char[]{}.getClass(), BINDING.unmarshal("char[]")); assertEquals(new long[][]{}.getClass(), BINDING.unmarshal("long[][]")); } |
### Question:
JInterface extends JType { public List<JInterface> getSuperInterfaces() throws ClasspathAccessException { final List<JInterface> retVal = new ArrayList<JInterface>(); String[] interfaces = getClassFile().getInterfaces(); for (String next : interfaces) { retVal.add(JInterface.getJInterface(next, getResolver())); } return retVal; } protected JInterface(String name, ClasspathResolver resolver); protected JInterface(ClassFile classFile, ClasspathResolver resolver); static JInterface getJInterface(String name, ClasspathResolver resolver); static JInterface getJInterface(ClassFile classFile, ClasspathResolver resolver); List<JInterface> getSuperInterfaces(); List<Class<?>> getActualSuperInterfaces(); List<JMethod> getMethods(); Class<?> getActualInterface(); @Override Set<JAnnotation<?>> getAnnotations(); @Override JPackage getPackage(); @Override Class<?> getActualClass(); Set<JInterface> getSubInterfaces(); Set<JClass> getImplementingClasses(); @Override void acceptVisitor(IntrospectionVisitor visitor); @Override JPackage getEnclosingElement(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void getSuperInterfaces() throws ClasspathAccessException { ClasspathResolver helper = new ClasspathResolver(); JInterface intf = JInterface.getJInterface("java.awt.event.AWTEventListener", helper); List<JInterface> superIntf = intf.getSuperInterfaces(); assertEquals(1, superIntf.size()); assertEquals(java.util.EventListener.class, superIntf.get(0).getActualClass()); } |
### Question:
JInterface extends JType { public List<JMethod> getMethods() { final List<JMethod> retVal = new ArrayList<JMethod>(); @SuppressWarnings("unchecked") final List<MethodInfo> methods = (List<MethodInfo>) getClassFile().getMethods(); for (MethodInfo next : methods) { if (next.isMethod()) { retVal.add(JMethod.getJMethod(next, this, getResolver())); } } return retVal; } protected JInterface(String name, ClasspathResolver resolver); protected JInterface(ClassFile classFile, ClasspathResolver resolver); static JInterface getJInterface(String name, ClasspathResolver resolver); static JInterface getJInterface(ClassFile classFile, ClasspathResolver resolver); List<JInterface> getSuperInterfaces(); List<Class<?>> getActualSuperInterfaces(); List<JMethod> getMethods(); Class<?> getActualInterface(); @Override Set<JAnnotation<?>> getAnnotations(); @Override JPackage getPackage(); @Override Class<?> getActualClass(); Set<JInterface> getSubInterfaces(); Set<JClass> getImplementingClasses(); @Override void acceptVisitor(IntrospectionVisitor visitor); @Override JPackage getEnclosingElement(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void getMethods() { ClasspathResolver helper = new ClasspathResolver(); JInterface intf = JInterface.getJInterface("java.awt.event.AWTEventListener", helper); List<JInterface> superIntf = intf.getSuperInterfaces(); assertEquals(1, superIntf.size()); assertEquals(0, superIntf.get(0).getMethods().size()); assertEquals(1, intf.getMethods().size()); assertEquals("eventDispatched", intf.getMethods().get(0).getName()); assertEquals(1, intf.getMethods().get(0).getParameters().size()); assertEquals("0", intf.getMethods().get(0).getParameters().get(0).getName()); assertEquals(0, intf.getMethods().get(0).getParameters().get(0).getIndex()); assertEquals("java.awt.AWTEvent", intf.getMethods().get(0).getParameters().get(0).getType().getName()); } |
### Question:
JInterface extends JType { public Class<?> getActualInterface() throws ClasspathAccessException { return getResolver().loadClass(getClassFile().getName()); } protected JInterface(String name, ClasspathResolver resolver); protected JInterface(ClassFile classFile, ClasspathResolver resolver); static JInterface getJInterface(String name, ClasspathResolver resolver); static JInterface getJInterface(ClassFile classFile, ClasspathResolver resolver); List<JInterface> getSuperInterfaces(); List<Class<?>> getActualSuperInterfaces(); List<JMethod> getMethods(); Class<?> getActualInterface(); @Override Set<JAnnotation<?>> getAnnotations(); @Override JPackage getPackage(); @Override Class<?> getActualClass(); Set<JInterface> getSubInterfaces(); Set<JClass> getImplementingClasses(); @Override void acceptVisitor(IntrospectionVisitor visitor); @Override JPackage getEnclosingElement(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void getActualInterface() { ClasspathResolver helper = new ClasspathResolver(); JInterface intf = JInterface.getJInterface("java.awt.event.AWTEventListener", helper); assertEquals(java.awt.event.AWTEventListener.class, intf.getActualClass()); assertEquals(java.awt.event.AWTEventListener.class, intf.getActualInterface()); } |
### Question:
JInterface extends JType { @Override public JPackage getPackage() throws ClasspathAccessException { String fqClassName = getClassFile().getName(); String packageName; if (fqClassName.contains(".")) { packageName = fqClassName.substring(0, fqClassName.lastIndexOf('.')); } else { packageName = ""; } return JPackage.getJPackage(packageName, getResolver()); } protected JInterface(String name, ClasspathResolver resolver); protected JInterface(ClassFile classFile, ClasspathResolver resolver); static JInterface getJInterface(String name, ClasspathResolver resolver); static JInterface getJInterface(ClassFile classFile, ClasspathResolver resolver); List<JInterface> getSuperInterfaces(); List<Class<?>> getActualSuperInterfaces(); List<JMethod> getMethods(); Class<?> getActualInterface(); @Override Set<JAnnotation<?>> getAnnotations(); @Override JPackage getPackage(); @Override Class<?> getActualClass(); Set<JInterface> getSubInterfaces(); Set<JClass> getImplementingClasses(); @Override void acceptVisitor(IntrospectionVisitor visitor); @Override JPackage getEnclosingElement(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void getPackage() { ClasspathResolver helper = new ClasspathResolver(); JInterface intf = JInterface.getJInterface("java.awt.event.AWTEventListener", helper); assertEquals("java.awt.event", intf.getPackage().getName()); assertEquals(Package.getPackage("java.awt.event"), intf.getPackage().getActualPackage()); } |
### Question:
JInterface extends JType { @Override public Class<?> getActualClass() throws ClasspathAccessException { return getActualInterface(); } protected JInterface(String name, ClasspathResolver resolver); protected JInterface(ClassFile classFile, ClasspathResolver resolver); static JInterface getJInterface(String name, ClasspathResolver resolver); static JInterface getJInterface(ClassFile classFile, ClasspathResolver resolver); List<JInterface> getSuperInterfaces(); List<Class<?>> getActualSuperInterfaces(); List<JMethod> getMethods(); Class<?> getActualInterface(); @Override Set<JAnnotation<?>> getAnnotations(); @Override JPackage getPackage(); @Override Class<?> getActualClass(); Set<JInterface> getSubInterfaces(); Set<JClass> getImplementingClasses(); @Override void acceptVisitor(IntrospectionVisitor visitor); @Override JPackage getEnclosingElement(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void getActualClass() { ClasspathResolver helper = new ClasspathResolver(); JInterface intf = JInterface.getJInterface("java.awt.event.AWTEventListener", helper); assertEquals(java.awt.event.AWTEventListener.class, intf.getActualClass()); } |
### Question:
JInterface extends JType { @Override public void acceptVisitor(IntrospectionVisitor visitor) throws ClasspathAccessException { visitor.visit(this); for (JInterface next : getSuperInterfaces()) { next.acceptVisitor(visitor); } for (JMethod next : getMethods()) { next.acceptVisitor(visitor); } for (JAnnotation<?> next : getAnnotations()) { next.acceptVisitor(visitor); } } protected JInterface(String name, ClasspathResolver resolver); protected JInterface(ClassFile classFile, ClasspathResolver resolver); static JInterface getJInterface(String name, ClasspathResolver resolver); static JInterface getJInterface(ClassFile classFile, ClasspathResolver resolver); List<JInterface> getSuperInterfaces(); List<Class<?>> getActualSuperInterfaces(); List<JMethod> getMethods(); Class<?> getActualInterface(); @Override Set<JAnnotation<?>> getAnnotations(); @Override JPackage getPackage(); @Override Class<?> getActualClass(); Set<JInterface> getSubInterfaces(); Set<JClass> getImplementingClasses(); @Override void acceptVisitor(IntrospectionVisitor visitor); @Override JPackage getEnclosingElement(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void acceptVisitor() { ClasspathResolver helper = new ClasspathResolver(); JInterface intf = JInterface.getJInterface("java.awt.event.AWTEventListener", helper); CollectingVisitor visitor = new CollectingVisitor(); intf.acceptVisitor(visitor); assertEquals(4, visitor.getVisitedElements().size()); } |
### Question:
JInterface extends JType { @Override public JPackage getEnclosingElement() { return getPackage(); } protected JInterface(String name, ClasspathResolver resolver); protected JInterface(ClassFile classFile, ClasspathResolver resolver); static JInterface getJInterface(String name, ClasspathResolver resolver); static JInterface getJInterface(ClassFile classFile, ClasspathResolver resolver); List<JInterface> getSuperInterfaces(); List<Class<?>> getActualSuperInterfaces(); List<JMethod> getMethods(); Class<?> getActualInterface(); @Override Set<JAnnotation<?>> getAnnotations(); @Override JPackage getPackage(); @Override Class<?> getActualClass(); Set<JInterface> getSubInterfaces(); Set<JClass> getImplementingClasses(); @Override void acceptVisitor(IntrospectionVisitor visitor); @Override JPackage getEnclosingElement(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void getEnclosingElement() { ClasspathResolver helper = new ClasspathResolver(); JInterface intf = JInterface.getJInterface("java.awt.event.AWTEventListener", helper); assertEquals("java.awt.event", intf.getPackage().getName()); assertEquals("java.awt.event", intf.getEnclosingElement().getName()); } |
### Question:
ClassStringBinding extends AbstractStringBinding<Class> implements Binding<Class, String> { @Override public String marshal(Class clazz) { return ClassUtils.determineReadableClassName(clazz.getName()); } @Override Class unmarshal(String object); @Override String marshal(Class clazz); Class<Class> getBoundClass(); }### Answer:
@Test public void testMarshal() { assertEquals("org.jadira.bindings.core.jdk.ClassStringBindingTest", BINDING.marshal(ClassStringBindingTest.class)); assertEquals("org.jadira.bindings.core.jdk.ClassStringBindingTest[]", BINDING.marshal(new ClassStringBindingTest[]{}.getClass())); assertEquals("org.jadira.bindings.core.jdk.ClassStringBindingTest[][]", BINDING.marshal(new ClassStringBindingTest[][]{}.getClass())); assertEquals("long", BINDING.marshal(Long.TYPE)); assertEquals("boolean", BINDING.marshal(Boolean.TYPE)); assertEquals("float", BINDING.marshal(Float.TYPE)); assertEquals("short", BINDING.marshal(Short.TYPE)); assertEquals("byte", BINDING.marshal(Byte.TYPE)); assertEquals("double", BINDING.marshal(Double.TYPE)); assertEquals("char", BINDING.marshal(Character.TYPE)); assertEquals("long[]", BINDING.marshal(new long[]{}.getClass())); assertEquals("boolean[]", BINDING.marshal(new boolean[]{}.getClass())); assertEquals("float[]", BINDING.marshal(new float[]{}.getClass())); assertEquals("short[]", BINDING.marshal(new short[]{}.getClass())); assertEquals("byte[]", BINDING.marshal(new byte[]{}.getClass())); assertEquals("double[]", BINDING.marshal(new double[]{}.getClass())); assertEquals("char[]", BINDING.marshal(new char[]{}.getClass())); assertEquals("long[][]", BINDING.marshal(new long[][]{}.getClass())); } |
### Question:
ShortStringBinding extends AbstractStringBinding<Short> implements Binding<Short, String> { @Override public Short unmarshal(String object) { return Short.valueOf(Short.parseShort(object)); } @Override Short unmarshal(String object); Class<Short> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new Short((short)0).toString(), BINDING.unmarshal("0").toString()); assertEquals(new Short((short)1).toString(), BINDING.unmarshal("1").toString()); assertEquals(new Short((short)32767).toString(), BINDING.unmarshal("" + Short.MAX_VALUE).toString()); assertEquals(new Short((short)-32768).toString(), BINDING.unmarshal("" + Short.MIN_VALUE).toString()); } |
### Question:
AtomicIntegerStringBinding extends AbstractStringBinding<AtomicInteger> implements Binding<AtomicInteger, String> { @Override public AtomicInteger unmarshal(String object) { return new AtomicInteger(Integer.parseInt(object)); } @Override AtomicInteger unmarshal(String object); Class<AtomicInteger> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new AtomicInteger(0).toString(), BINDING.unmarshal("0").toString()); assertEquals(new AtomicInteger(1).toString(), BINDING.unmarshal("1").toString()); assertEquals(new AtomicInteger(2147483647).toString(), BINDING.unmarshal("" + Integer.MAX_VALUE).toString()); assertEquals(new AtomicInteger(-2147483648).toString(), BINDING.unmarshal("" + Integer.MIN_VALUE).toString()); } |
### Question:
CalendarStringBinding extends AbstractStringBinding<Calendar> implements Binding<Calendar, String> { @Override public Calendar unmarshal(String object) { if (object.length() < 31 || object.charAt(26) != ':' || object.charAt(29) != '[' || object.charAt(object.length() - 1) != ']') { throw new IllegalArgumentException("Unable to parse calendar: " + object); } TimeZone zone = TimeZone.getTimeZone(object.substring(30, object.length() - 1)); String parseableDateString = object.substring(0, 26) + object.substring(27, 29); GregorianCalendar cal = new GregorianCalendar(zone); cal.setTimeInMillis(0); DATE_FORMAT.get().setCalendar(cal); try { DATE_FORMAT.get().parseObject(parseableDateString); return DATE_FORMAT.get().getCalendar(); } catch (ParseException ex) { throw new BindingException(ex.getMessage(), ex); } } @Override Calendar unmarshal(String object); @Override String marshal(Calendar object); Class<Calendar> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { Calendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("Europe/London")); cal.setTimeInMillis(0); cal.set(2000, 10, 1, 23, 45); assertEquals(cal, BINDING.unmarshal("2000-11-01T23:45:00.000+00:00[Europe/London]")); } |
### Question:
CalendarStringBinding extends AbstractStringBinding<Calendar> implements Binding<Calendar, String> { @Override public String marshal(Calendar object) { if (object instanceof GregorianCalendar) { GregorianCalendar cal = (GregorianCalendar) object; DATE_FORMAT.get().setCalendar(cal); String str = DATE_FORMAT.get().format(cal.getTime()); String printableDateString = str.substring(0, 26) + ":" + str.substring(26) + "[" + cal.getTimeZone().getID() + "]"; return printableDateString; } else { throw new IllegalArgumentException("CalendarStringBinding can only support " + GregorianCalendar.class.getSimpleName()); } } @Override Calendar unmarshal(String object); @Override String marshal(Calendar object); Class<Calendar> getBoundClass(); }### Answer:
@Test public void testMarshal() { Calendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("Europe/London")); cal.setTimeInMillis(0); cal.set(2000, 10, 1, 23, 45); assertEquals("2000-11-01T23:45:00.000+00:00[Europe/London]", BINDING.marshal(cal)); } |
### Question:
TopicSubscriptionHelper { public static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions) { List<String> records = new ArrayList<String>(); if (!CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.isSubscribed()) { records.add(topicSubscription.getTopicFilter()); } } } return records.toArray(new String[records.size()]); } static TopicSubscription findByTopicFilter(final String topicFilter,
List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }### Answer:
@Test public void testGetSubscribedTopicSubscriptions() { Assert.assertArrayEquals(new String[0], TopicSubscriptionHelper.getSubscribedTopicFilters(topicSubscriptions)); topicSubscriptions.get(0).setSubscribed(true); Assert.assertArrayEquals(new String[]{ TOPIC_FILTER_1}, TopicSubscriptionHelper.getSubscribedTopicFilters(topicSubscriptions)); topicSubscriptions.get(1).setSubscribed(true); Assert.assertArrayEquals(new String[]{ TOPIC_FILTER_1, TOPIC_FILTER_2}, TopicSubscriptionHelper.getSubscribedTopicFilters(topicSubscriptions)); }
@Test public void testGetSubscribedEmptyTopicSubscriptions() { Assert.assertArrayEquals(new String[0], TopicSubscriptionHelper.getSubscribedTopicFilters(new ArrayList<TopicSubscription>())); } |
### Question:
TopicSubscriptionHelper { public static void markUnsubscribed(List<TopicSubscription> topicSubscriptions) { if (!CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { topicSubscription.setSubscribed(false); } } } static TopicSubscription findByTopicFilter(final String topicFilter,
List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }### Answer:
@Test public void testMarkUnsubscribedEmptyTopicSubscriptions() { TopicSubscriptionHelper.markUnsubscribed(new ArrayList<TopicSubscription>()); }
@Test public void testMarkUnsubscribed() { Assert.assertArrayEquals(new String[0], TopicSubscriptionHelper.getSubscribedTopicFilters(topicSubscriptions)); topicSubscriptions.get(0).setSubscribed(true); Assert.assertArrayEquals(new String[]{ TOPIC_FILTER_1}, TopicSubscriptionHelper.getSubscribedTopicFilters(topicSubscriptions)); topicSubscriptions.get(1).setSubscribed(true); Assert.assertArrayEquals(new String[]{ TOPIC_FILTER_1, TOPIC_FILTER_2}, TopicSubscriptionHelper.getSubscribedTopicFilters(topicSubscriptions)); TopicSubscriptionHelper.markUnsubscribed(topicSubscriptions); Assert.assertArrayEquals(new String[0], TopicSubscriptionHelper.getSubscribedTopicFilters(topicSubscriptions)); } |
### Question:
MqttHeaderHelper { public static String getTopicHeaderValue(Message<?> message) { String value = null; if (message != null && message.getHeaders().containsKey(TOPIC)) { value = message.getHeaders().get(TOPIC, String.class); } return value; } static String getTopicHeaderValue(Message<?> message); static MqttQualityOfService getMqttQualityOfServiceHeaderValue(Message<?> message,
int defaultLevelIdentifier); static boolean getRetainedHeaderValue(Message<?> message); static String getCorrelationIdHeaderValue(Message<?> message); static final String DUPLICATE; static final String ID; static final String QOS; static final String RETAINED; static final String TOPIC; static final String CORRELATION_ID; }### Answer:
@Test public void testTopicHeader() { Assert.assertNull(MqttHeaderHelper.getTopicHeaderValue(null)); MessageBuilder<String> builder = MessageBuilder.withPayload("See topic header"); Assert.assertNull(MqttHeaderHelper.getTopicHeaderValue(builder.build())); builder.setHeader(MqttHeaderHelper.TOPIC, TOPIC); Assert.assertEquals(TOPIC, MqttHeaderHelper.getTopicHeaderValue(builder.build())); } |
### Question:
MqttHeaderHelper { public static boolean getRetainedHeaderValue(Message<?> message) { boolean retained = false; try { if (message != null && message.getHeaders().containsKey(RETAINED)) { retained = message.getHeaders().get(RETAINED, Boolean.class); } } catch (IllegalArgumentException ex) { LOG.debug("Could not convert the RETAINED header value to a Boolean!", ex); } return retained; } static String getTopicHeaderValue(Message<?> message); static MqttQualityOfService getMqttQualityOfServiceHeaderValue(Message<?> message,
int defaultLevelIdentifier); static boolean getRetainedHeaderValue(Message<?> message); static String getCorrelationIdHeaderValue(Message<?> message); static final String DUPLICATE; static final String ID; static final String QOS; static final String RETAINED; static final String TOPIC; static final String CORRELATION_ID; }### Answer:
@Test public void testRetainedHeader() { Assert.assertFalse(MqttHeaderHelper.getRetainedHeaderValue(null)); MessageBuilder<String> builder = MessageBuilder.withPayload("See retained header"); Assert.assertFalse(MqttHeaderHelper.getRetainedHeaderValue(builder.build())); builder.setHeader(MqttHeaderHelper.RETAINED, "foo"); Assert.assertFalse(MqttHeaderHelper.getRetainedHeaderValue(builder.build())); builder.setHeader(MqttHeaderHelper.RETAINED, true); Assert.assertTrue(MqttHeaderHelper.getRetainedHeaderValue(builder.build())); } |
### Question:
MqttHeaderHelper { public static String getCorrelationIdHeaderValue(Message<?> message) { String correlationId = null; if (message != null && message.getHeaders().containsKey(CORRELATION_ID)) { correlationId = message.getHeaders().get(CORRELATION_ID, String.class); } return correlationId; } static String getTopicHeaderValue(Message<?> message); static MqttQualityOfService getMqttQualityOfServiceHeaderValue(Message<?> message,
int defaultLevelIdentifier); static boolean getRetainedHeaderValue(Message<?> message); static String getCorrelationIdHeaderValue(Message<?> message); static final String DUPLICATE; static final String ID; static final String QOS; static final String RETAINED; static final String TOPIC; static final String CORRELATION_ID; }### Answer:
@Test public void testCorrelationIdHeader() { Assert.assertNull(MqttHeaderHelper.getCorrelationIdHeaderValue(null)); MessageBuilder<String> builder = MessageBuilder.withPayload("See Correlation ID header"); Assert.assertNull(MqttHeaderHelper.getCorrelationIdHeaderValue(builder.build())); builder.setHeader(MqttHeaderHelper.CORRELATION_ID, "foo"); Assert.assertSame("foo", MqttHeaderHelper.getCorrelationIdHeaderValue(builder.build())); } |
### Question:
AbstractMqttClientService implements MqttClientService { public void setInboundMessageChannel(MessageChannel inboundMessageChannel) { if (MqttClientConnectionType.PUBLISHER == connectionType) { throw new IllegalStateException(String.format( "Client ID %s is setup as a PUBLISHER and cannot receive messages from the Broker!", getClientId())); } Assert.notNull(inboundMessageChannel, "'inboundMessageChannel' must be set!"); this.inboundMessageChannel = inboundMessageChannel; } protected AbstractMqttClientService(final MqttClientConnectionType connectionType); @Override MqttClientConnectionType getConnectionType(); abstract String getClientId(); @Override boolean isStarted(); MqttClientConfiguration getMqttClientConfiguration(); @Override void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher); void setInboundMessageChannel(MessageChannel inboundMessageChannel); void setReconnectDetails(ReconnectService reconnectService, TaskScheduler taskScheduler); @Override List<TopicSubscription> getTopicSubscriptions(); @Override void subscribe(String topicFilter); abstract void subscribe(String topicFilter, MqttQualityOfService qualityOfService); }### Answer:
@Test public void testPublisherSetInboundMessageChannel() { AbstractMqttClientService clientService = Mockito.mock(AbstractMqttClientService.class, Mockito.withSettings().useConstructor(MqttClientConnectionType.PUBLISHER) .defaultAnswer(Mockito.CALLS_REAL_METHODS)); Assert.assertNull(clientService.inboundMessageChannel); thrown.expect(IllegalStateException.class); thrown.expectMessage( "Client ID null is setup as a PUBLISHER and cannot receive messages from the Broker!"); clientService.setInboundMessageChannel(Mockito.mock(MessageChannel.class)); } |
### Question:
TopicSubscription { @Override public TopicSubscription clone() { TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService); record.setSubscribed(this.subscribed); return record; } TopicSubscription(final String topicFilter, final MqttQualityOfService qualityOfService); String getTopicFilter(); MqttQualityOfService getQualityOfService(); boolean isSubscribed(); void setSubscribed(boolean subscribed); @Override TopicSubscription clone(); }### Answer:
@Test public void testClone() { TopicSubscription topic = new TopicSubscription(TOPIC_FILTER, MqttQualityOfService.QOS_0); TopicSubscription clone = topic.clone(); Assert.assertEquals(topic.getTopicFilter(), clone.getTopicFilter()); Assert.assertEquals(topic.getQualityOfService(), clone.getQualityOfService()); Assert.assertThat(topic.isSubscribed(), Is.is(CoreMatchers.equalTo(clone.isSubscribed()))); topic.setSubscribed(true); Assert.assertThat(topic.isSubscribed(), Is.is(CoreMatchers.not(clone.isSubscribed()))); clone = topic.clone(); Assert.assertEquals(topic.getTopicFilter(), clone.getTopicFilter()); Assert.assertEquals(topic.getQualityOfService(), clone.getQualityOfService()); Assert.assertThat(topic.isSubscribed(), Is.is(CoreMatchers.equalTo(clone.isSubscribed()))); } |
### Question:
MqttClientConfiguration { public void setDefaultQualityOfService(MqttQualityOfService defaultQualityOfService) { Assert.notNull(defaultQualityOfService, "'defaultQualityOfService' must be set!"); this.defaultQualityOfService = defaultQualityOfService; } MqttClientConfiguration(); MqttQualityOfService getDefaultQualityOfService(); void setDefaultQualityOfService(MqttQualityOfService defaultQualityOfService); long getSubscribeWaitMilliseconds(); void setSubscribeWaitMilliseconds(long subscribeWaitMilliseconds); long getTopicUnsubscribeWaitTimeoutMilliseconds(); void setTopicUnsubscribeWaitTimeoutMilliseconds(
long topicUnsubscribeWaitTimeoutMilliseconds); long getDisconnectWaitMilliseconds(); void setDisconnectWaitMilliseconds(long disconnectWaitMilliseconds); MqttClientConnectionStatusPublisher getMqttClientConnectionStatusPublisher(); void setMqttClientConnectionStatusPublisher(
MqttClientConnectionStatusPublisher mqttClientConnectionStatusPublisher); }### Answer:
@Test public void testDefaultQualityOfServiceNull() { MqttClientConfiguration configuration = new MqttClientConfiguration(); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("'defaultQualityOfService' must be set!"); configuration.setDefaultQualityOfService(null); } |
### Question:
MqttMessagePublishFailureEvent extends MqttMessageStatusEvent { public MessagingException getException() { return exception; } MqttMessagePublishFailureEvent(final String clientId, final MessagingException exception,
final Object source); MessagingException getException(); }### Answer:
@Test public void test() { final Message<String> message = MessageBuilder.withPayload(PAYLOAD).build(); final MessagingException exception = new MessagingException(message, String.format( "Client ID '%s' could not publish this message because either the topic or payload isn't set, or the payload could not be converted.", CLIENT_ID)); final MqttMessagePublishFailureEvent event = new MqttMessagePublishFailureEvent(CLIENT_ID, exception, this); Assert.assertEquals(PAYLOAD, event.getException().getFailedMessage().getPayload()); } |
### Question:
MqttMessageDeliveredEvent extends MqttMessageStatusEvent { public int getMessageIdentifier() { return messageIdentifier; } MqttMessageDeliveredEvent(String clientId, int messageIdentifier, Object source); int getMessageIdentifier(); }### Answer:
@Test public void test() { MqttMessageDeliveredEvent event = new MqttMessageDeliveredEvent(CLIENT_ID, MESSAGE_ID, this); Assert.assertEquals(MESSAGE_ID, event.getMessageIdentifier()); } |
### Question:
MqttStatusEvent extends ApplicationEvent { public String getClientId() { return clientId; } MqttStatusEvent(String clientId, Object source); String getClientId(); }### Answer:
@Test public void test() { MqttStatusEvent event = new MqttStatusEvent(CLIENT_ID, this); Assert.assertEquals(CLIENT_ID, event.getClientId()); } |
### Question:
MqttClientConnectionLostEvent extends MqttConnectionStatusEvent { public boolean isAutoReconnect() { return autoReconnect; } MqttClientConnectionLostEvent(String clientId, boolean autoReconnect, Object source); boolean isAutoReconnect(); }### Answer:
@Test public void test() { MqttClientConnectionLostEvent event = new MqttClientConnectionLostEvent(CLIENT_ID, true, this); Assert.assertTrue(event.isAutoReconnect()); event = new MqttClientConnectionLostEvent(CLIENT_ID, false, this); Assert.assertFalse(event.isAutoReconnect()); } |
### Question:
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } static TopicSubscription findByTopicFilter(final String topicFilter,
List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }### Answer:
@Test public void testFindMatch() { Assert.assertNotNull( TopicSubscriptionHelper.findByTopicFilter(TOPIC_FILTER_1, topicSubscriptions)); }
@Test public void testFindNoMatchNoTopicFilter() { Assert.assertNull(TopicSubscriptionHelper.findByTopicFilter("test", topicSubscriptions)); }
@Test public void testFindNoMatchWrongCase() { Assert.assertNull(TopicSubscriptionHelper.findByTopicFilter(TOPIC_FILTER_1.toUpperCase(), topicSubscriptions)); }
@Test public void testFindNullTopicFilter() { Assert.assertNull(TopicSubscriptionHelper.findByTopicFilter(null, topicSubscriptions)); }
@Test public void testFindEmptyTopicSubscriptions() { Assert.assertNull(TopicSubscriptionHelper.findByTopicFilter(TOPIC_FILTER_1.toUpperCase(), new ArrayList<TopicSubscription>())); } |
### Question:
JuelTransform implements DomTransform { @Override public Object transform(Object dom, MappingContext context) { if (dom instanceof String) { final String str = (String) dom; if (str.contains("${")) { final boolean assigned = session.setLocalContext(context); try { final ValueExpression expr = factory.createValueExpression(elContext, str, Object.class); return expr.getValue(elContext); } finally { if (assigned) session.clearLocalContext(); } } else { return dom; } } else { return dom; } } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }### Answer:
@Test public void testNonString() { final Object in = new Object(); final Object out = new JuelTransform().transform(in, new MappingContext()); assertEquals(in, out); }
@Test public void testPlainString() { final Object in = "Hello"; final Object out = new JuelTransform().transform(in, new MappingContext()); assertEquals(in, out); } |
### Question:
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }### Answer:
@Test public void testMap() { assertEquals(singletonMap(Arrays.asList(8_000_000_000L)), singletonMap(FixDoubles.fix(Arrays.asList(8_000_000_000.0)))); }
@Test public void testDouble() { assertEquals(123.4, FixDoubles.fix(123.4)); }
@Test public void testInt() { assertEquals(123, FixDoubles.fix(123.0)); }
@Test public void testLong() { assertEquals(8_000_000_000L, FixDoubles.fix(8_000_000_000.0)); }
@Test public void testList() { assertEquals(Arrays.asList(8_000_000_000L), FixDoubles.fix(Arrays.asList(8_000_000_000.0))); } |
### Question:
LogConfig { public Logger getLogger() { return logger; } Logger getLogger(); }### Answer:
@Test public void test() throws IOException { final LogConfig config = new MappingContext() .withParser(new SnakeyamlParser()) .fromStream(LogConfigTest.class.getClassLoader().getResourceAsStream("sample-inline.yaml")) .map(LogConfig.class); assertNotNull(config.getLogger()); assertEquals("org.myproject.MyLogger", config.getLogger().getName()); } |
### Question:
JuelTransform implements DomTransform { public void configure(Configurator c) { Exceptions.wrap(() -> c.apply(this), RuntimeException::new); } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }### Answer:
@Test(expected=RuntimeException.class) public void testConfiguratorException() { new JuelTransform().configure(t -> { throw new Exception(); }); } |
### Question:
JuelTransform implements DomTransform { public static String getEnv(String key, String defaultValue) { final String existingValue = nullCoerce(System.getenv(key)); return ifAbsent(existingValue, give(defaultValue)); } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }### Answer:
@Test public void testGetEnvExisting() { final String value = JuelTransform.getEnv("HOME", null); assertNotNull(value); }
@Test public void testGetEnvNonExistent() { final String defaultValue = "someDefaultValue"; final String value = JuelTransform.getEnv("GIBB_BB_BBERISH", defaultValue); assertSame(defaultValue, value); } |
### Question:
JuelTransform implements DomTransform { static String nullCoerce(String str) { return str != null && ! str.isEmpty() ? str : null; } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }### Answer:
@Test public void testNullCoerce() { assertEquals("nonNullString", JuelTransform.nullCoerce("nonNullString")); assertNull(JuelTransform.nullCoerce(null)); assertNull(JuelTransform.nullCoerce("")); } |
### Question:
MessageProducerImpl implements MessageProducer { @Override public void send(String destination, Message message) { prepareMessageHeaders(destination, message); implementation.withContext(() -> send(message)); } MessageProducerImpl(MessageInterceptor[] messageInterceptors, ChannelMapping channelMapping, MessageProducerImplementation implementation); @Override void send(String destination, Message message); }### Answer:
@Test public void shouldSendMessage() { ChannelMapping channelMapping = mock(ChannelMapping.class); MessageProducerImplementation implementation = mock(MessageProducerImplementation.class); MessageProducerImpl mp = new MessageProducerImpl(new MessageInterceptor[0], channelMapping, implementation); String transformedDestination = "TransformedDestination"; String messageID = "1"; doAnswer((Answer<Void>) invocation -> { ((Runnable)invocation.getArgument(0)).run(); return null; }).when(implementation).withContext(any(Runnable.class)); when(channelMapping.transform("Destination")).thenReturn(transformedDestination); when(implementation.generateMessageId()).thenReturn(messageID); mp.send("Destination", MessageBuilder.withPayload("x").build()); ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class); verify(implementation).send(messageArgumentCaptor.capture()); Message sendMessage = messageArgumentCaptor.getValue(); assertEquals(messageID, sendMessage.getRequiredHeader(Message.ID)); assertEquals(transformedDestination, sendMessage.getRequiredHeader(Message.DESTINATION)); assertNotNull(sendMessage.getRequiredHeader(Message.DATE)); } |
### Question:
HttpDateHeaderFormatUtil { public static String nowAsHttpDateString() { return timeAsHttpDateString(ZonedDateTime.now(ZoneId.of("GMT"))); } static String nowAsHttpDateString(); static String timeAsHttpDateString(ZonedDateTime gmtTime); }### Answer:
@Test public void shouldFormatDateNow() { Assert.assertNotNull((HttpDateHeaderFormatUtil.nowAsHttpDateString())); } |
### Question:
HttpDateHeaderFormatUtil { public static String timeAsHttpDateString(ZonedDateTime gmtTime) { return gmtTime.format(DateTimeFormatter.RFC_1123_DATE_TIME); } static String nowAsHttpDateString(); static String timeAsHttpDateString(ZonedDateTime gmtTime); }### Answer:
@Test public void shouldFormatDate() { String expected = "Tue, 15 Nov 1994 08:12:31 GMT"; ZonedDateTime time = ZonedDateTime.parse(expected, DateTimeFormatter.RFC_1123_DATE_TIME); assertEquals(expected, HttpDateHeaderFormatUtil.timeAsHttpDateString(time)); } |
### Question:
ResourcePathPattern { public ResourcePath replacePlaceholders(PlaceholderValueProvider placeholderValueProvider) { return new ResourcePath(Arrays.stream(splits).map(s -> isPlaceholder(s) ? placeholderValueProvider.get(placeholderName(s)).orElseGet(() -> { throw new RuntimeException("Placeholder not found: " + placeholderName(s) + " in " + s + ", params=" + placeholderValueProvider.getParams()); }) : s).collect(toList()).toArray(new String[splits.length])); } ResourcePathPattern(String pathPattern); static ResourcePathPattern parse(String pathPattern); int length(); boolean isSatisfiedBy(ResourcePath mr); Map<String, String> getPathVariableValues(ResourcePath mr); ResourcePath replacePlaceholders(PlaceholderValueProvider placeholderValueProvider); ResourcePath replacePlaceholders(Object[] pathParams); }### Answer:
@Test public void shouldReplacePlaceholders() { ResourcePathPattern rpp = new ResourcePathPattern("/foo/{bar}"); ResourcePath rp = rpp.replacePlaceholders(new SingleValuePlaceholderValueProvider("baz")); assertEquals("/foo/baz", rp.toPath()); } |
### Question:
UserServiceImpl implements UserService { @Override public User getUserByApi(String token) { String s = HttpClientUtils.doGet(api_getUserByToken + token); QuarkResult quarkResult = JsonUtils.jsonToQuarkResult(s, User.class); User data= (User) quarkResult.getData(); return data; } @Override User getUserByApi(String token); }### Answer:
@Test public void getUserByApi() throws Exception { User user =userService.getUserByApi("bee1a09b-9867-4f1a-9886-c25d8b0e42b1"); System.out.println(user); } |
### Question:
PartlyCovered { String partlyCovered(String string, boolean trigger){ if(trigger){ string = string.toLowerCase(); } return string; } }### Answer:
@Test void test() { PartlyCovered partlyCovered = new PartlyCovered(); String string = partlyCovered.partlyCovered("THIS IS A STRING", false); assertThat(string).isEqualTo("THIS IS A STRING"); } |
### Question:
QuotesProperties { List<Quote> getQuotes() { return this.quotes; } QuotesProperties(List<Quote> quotes); }### Answer:
@Test void staticQuotesAreLoaded() { assertThat(quotesProperties.getQuotes()).hasSize(2); } |
### Question:
Controller { @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); } Controller(CacheClient cacheClient); @PostMapping(path = "/{number}", produces= MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(code = HttpStatus.CREATED) Car put(@RequestBody Car car, @PathVariable String number); @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) Car get(@PathVariable String number); }### Answer:
@Test void putGet() throws Exception { String number = "BO5489"; Car car = Car.builder() .number(number) .name("VW") .build(); String content = objectMapper.writeValueAsString(car); mockMvc.perform( post("/cars/" + number) .content(content) .contentType(MediaType.APPLICATION_JSON_VALUE) ).andExpect(status().isCreated()); String json = mockMvc.perform( get("/cars/" + number)) .andExpect(status().isOk() ).andReturn().getResponse().getContentAsString(); Car response = objectMapper.readValue(json, Car.class); assertThat(response).isEqualToComparingFieldByField(car); } |
### Question:
Controller { @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); } Controller(CacheClient cacheClient); @PostMapping(value = "/{number}",produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(code = HttpStatus.CREATED) Car put(@RequestBody Car car, @PathVariable String number); @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) Car get(@PathVariable String number); }### Answer:
@Test void putGet() throws Exception { String number = "BO5489"; Car car = Car.builder().color(number).name("VW").build(); String content = objectMapper.writeValueAsString(car); mockMvc .perform( post("/cars/" + number).content(content).contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isCreated()); String json = mockMvc .perform(get("/cars/" + number)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); Car response = objectMapper.readValue(json, Car.class); assertThat(response).isEqualToComparingFieldByField(car); } |
### Question:
StatefulBlockingClient { @Scheduled(fixedDelay = 3000) public void send() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); RegistrationDto registrationDto = template.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() { }); } StatefulBlockingClient(DirectExchange directExchange, RabbitTemplate template); @Scheduled(fixedDelay = 3000) void send(); static final String ROUTING_KEY; }### Answer:
@Test void sendMessageSynchronously() { ThrowableAssert.ThrowingCallable send = () -> statefulBlockingClient.send(); assertThatCode(send).doesNotThrowAnyException(); } |
### Question:
StatefulCallbackClient { @Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendAsynchronouslyWithCallback() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); RabbitConverterFuture<RegistrationDto> rabbitConverterFuture = asyncRabbitTemplate.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() {}); rabbitConverterFuture.addCallback(new ListenableFutureCallback<>() { @Override public void onFailure(Throwable ex) { LOGGER.error("Cannot get response for: {}", carDto.getId(), ex); } @Override public void onSuccess(RegistrationDto registrationDto) { LOGGER.info("Registration received {}", registrationDto); } }); } StatefulCallbackClient(AsyncRabbitTemplate asyncRabbitTemplate, DirectExchange directExchange); @Scheduled(fixedDelay = 3000, initialDelay = 1500) void sendAsynchronouslyWithCallback(); static final Logger LOGGER; static final String ROUTING_KEY; }### Answer:
@Test void sendAsynchronouslyWithCallback() { ThrowableAssert.ThrowingCallable send = () -> statefulCallbackClient.sendAsynchronouslyWithCallback(); assertThatCode(send).doesNotThrowAnyException(); } |
### Question:
StatefulFutureClient { @Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendWithFuture() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); ListenableFuture<RegistrationDto> listenableFuture = asyncRabbitTemplate.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() { }); try { RegistrationDto registrationDto = listenableFuture.get(); LOGGER.info("Message received: {}", registrationDto); } catch (InterruptedException | ExecutionException e) { LOGGER.error("Cannot get response.", e); } } StatefulFutureClient(AsyncRabbitTemplate asyncRabbitTemplate, DirectExchange directExchange); @Scheduled(fixedDelay = 3000, initialDelay = 1500) void sendWithFuture(); static final Logger LOGGER; static final String ROUTING_KEY; }### Answer:
@Test void sendAsynchronously() { ThrowableAssert.ThrowingCallable send = () -> statefulFutureClient.sendWithFuture(); assertThatCode(send) .doesNotThrowAnyException(); } |
### Question:
StatelessClient { @Scheduled(fixedDelay = 3000) public void sendAndForget() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); UUID correlationId = UUID.randomUUID(); registrationService.saveCar(carDto, correlationId); MessagePostProcessor messagePostProcessor = message -> { MessageProperties messageProperties = message.getMessageProperties(); messageProperties.setReplyTo(replyQueue.getName()); messageProperties.setCorrelationId(correlationId.toString()); return message; }; template.convertAndSend(directExchange.getName(), "old.car", carDto, messagePostProcessor); } StatelessClient(RabbitTemplate template, DirectExchange directExchange, Queue replyQueue, RegistrationService registrationService); @Scheduled(fixedDelay = 3000) void sendAndForget(); }### Answer:
@Test void sendAndForget() { ThrowableAssert.ThrowingCallable send = () -> statelessClient.sendAndForget(); assertThatCode(send).doesNotThrowAnyException(); } |
### Question:
CarResource { @PutMapping private CarDto updateCar(@RequestBody CarDto carDto) { Car car = carMapper.toCar(carDto); return carMapper.toCarDto(carService.update(car)); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }### Answer:
@Test @Sql("/insert_car.sql") void updateCar() throws Exception { CarDto carDto = CarDto.builder() .id(UUID.fromString("1b104b1a-8539-4e06-aea7-9d77f2193b80")) .name("vw") .color("white") .build(); mockMvc.perform( put("/cars") .content(objectMapper.writeValueAsString(carDto)) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isOk()); } |
### Question:
CarResource { @GetMapping(value = "/{uuid}") private CarDto get(@PathVariable UUID uuid){ return carMapper.toCarDto(carService.get(uuid)); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }### Answer:
@Test @Sql("/insert_car.sql") void getCar() throws Exception { UUID id = UUID.fromString("1b104b1a-8539-4e06-aea7-9d77f2193b80"); mockMvc.perform( get("/cars/" + id) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isOk()); } |
### Question:
CarResource { @DeleteMapping(value = "/{uuid}") @ResponseStatus(HttpStatus.NO_CONTENT) private void delete(@PathVariable UUID uuid){ carService.delete(uuid); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }### Answer:
@Test @Sql("/insert_car.sql") void deleteCar() throws Exception { UUID id = UUID.fromString("1b104b1a-8539-4e06-aea7-9d77f2193b80"); mockMvc.perform( delete("/cars/" + id) ) .andExpect(status().isNoContent()); } |
### Question:
PartlyCovered { String covered(String string) { string = string.toLowerCase(); return string; } }### Answer:
@Test void testSimple() { PartlyCovered fullyCovered = new PartlyCovered(); String string = fullyCovered.covered("THIS IS A STRING"); assertThat(string).isEqualTo("this is a string"); } |
### Question:
UserDetailsMapper { UserDetails toUserDetails(UserCredentials userCredentials) { return User.withUsername(userCredentials.getUsername()) .password(userCredentials.getPassword()) .roles(userCredentials.getRoles().toArray(String[]::new)) .build(); } }### Answer:
@Test void toUserDetails() { UserCredentials userCredentials = UserCredentials.builder() .enabled(true) .password("password") .username("user") .roles(Set.of("USER", "ADMIN")) .build(); UserDetails userDetails = userDetailsMapper.toUserDetails(userCredentials); assertThat(userDetails.getUsername()).isEqualTo("user"); assertThat(userDetails.getPassword()).isEqualTo("password"); assertThat(userDetails.isEnabled()).isTrue(); } |
### Question:
BCryptExample { public String encode(String plainPassword) { int strength = 10; BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(strength, new SecureRandom()); return bCryptPasswordEncoder.encode(plainPassword); } String encode(String plainPassword); }### Answer:
@Test void encode() { String plainPassword = "password"; String encoded = bcryptExample.encode(plainPassword); assertThat(encoded).startsWith("$2a$10"); } |
### Question:
Pbkdf2Example { public String encode(String plainPassword) { String pepper = "pepper"; int iterations = 200000; int hashWidth = 256; Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(pepper, iterations, hashWidth); return pbkdf2PasswordEncoder.encode(plainPassword); } String encode(String plainPassword); }### Answer:
@Test void encode() { String plainPassword = "plainPassword"; String actual = pbkdf2Example.encode(plainPassword); assertThat(actual).hasSize(80); } |
### Question:
Argon2Example { public String encode(String plainPassword) { int saltLength = 16; int hashLength = 32; int parallelism = 1; int memory = 4096; int iterations = 3; Argon2PasswordEncoder argon2PasswordEncoder = new Argon2PasswordEncoder(saltLength, hashLength, parallelism, memory, iterations); return argon2PasswordEncoder.encode(plainPassword); } String encode(String plainPassword); }### Answer:
@Test void encode() { String plainPassword = "password"; String actual = argon2Example.encode(plainPassword); assertThat(actual).startsWith("$argon2id$v=19$m=4096,t=3,p=1"); } |
### Question:
SCryptExample { public String encode(String plainPassword) { int cpuCost = (int) Math.pow(2, 14); int memoryCost = 8; int parallelization = 1; int keyLength = 32; int saltLength = 64; SCryptPasswordEncoder sCryptPasswordEncoder = new SCryptPasswordEncoder(cpuCost, memoryCost, parallelization, keyLength, saltLength); return sCryptPasswordEncoder.encode(plainPassword); } String encode(String plainPassword); }### Answer:
@Test void encode() { String plainPassword = "password"; String actual = sCryptExample.encode(plainPassword); assertThat(actual).hasSize(140); assertThat(actual).startsWith("$e0801"); } |
### Question:
BcCryptWorkFactorService { public int calculateStrength() { for (int strength = MIN_STRENGTH; strength <= MAX_STRENGTH; strength++) { long duration = calculateDuration(strength); if (duration >= GOAL_MILLISECONDS_PER_PASSWORD) { return strength; } } throw new RuntimeException( String.format( "Could not find suitable round number for bcrypt encoding. The encoding with %d rounds" + " takes less than %d ms.", MAX_STRENGTH, GOAL_MILLISECONDS_PER_PASSWORD)); } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }### Answer:
@Test void calculateStrength() { int strength = bcCryptWorkFactorService.calculateStrength(); assertThat(strength).isBetween(4, 31); } |
### Question:
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }### Answer:
@Test void findCloserToShouldReturnNumber1IfItCloserToGoalThanNumber2() { int number1 = 950; int number2 = 1051; boolean actual = bcCryptWorkFactorService.isPreviousDurationCloserToGoal(number1, number2); assertThat(actual).isTrue(); }
@Test void findCloserToShouldReturnNUmber2IfItCloserToGoalThanNumber1() { int number1 = 1002; int number2 = 999; boolean actual = bcCryptWorkFactorService.isPreviousDurationCloserToGoal(number1, number2); assertThat(actual).isFalse(); }
@Test void findCloserToShouldReturnGoalIfNumber2IsEqualGoal() { int number1 = 999; int number2 = 1000; boolean actual = bcCryptWorkFactorService.isPreviousDurationCloserToGoal(number1, number2); assertThat(actual).isFalse(); }
@Test void findCloserToShouldReturnGoalIfNumber1IsEqualGoal() { int number1 = 1000; int number2 = 1001; boolean actual = bcCryptWorkFactorService.isPreviousDurationCloserToGoal(number1, number2); assertThat(actual).isTrue(); } |
### Question:
FullyCovered { String lowercase(String string) { string = string.toLowerCase(); return string; } }### Answer:
@Test void test() { FullyCovered fullyCovered = new FullyCovered(); String string = fullyCovered.lowercase("THIS IS A STRING"); assertThat(string).isEqualTo("this is a string"); } |
### Question:
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }### Answer:
@Test void getStrengthShouldReturn4IfStrengthIs4() { int currentStrength = 4; int actual = bcCryptWorkFactorService.getStrength(0, 0, currentStrength); assertThat(actual).isEqualTo(4); }
@Test void getStrengthShouldReturnPreviousStrengthIfPreviousDurationCloserToGoal() { int actual = bcCryptWorkFactorService.getStrength(980, 1021, 5); assertThat(actual).isEqualTo(4); }
@Test void getStrengthShouldReturnCurrentStrengthIfCurrentDurationCloserToGoal() { int actual = bcCryptWorkFactorService.getStrength(960, 1021, 5); assertThat(actual).isEqualTo(5); } |
### Question:
Pbkdf2WorkFactorService { public int calculateIteration() { int iterationNumber = 150000; while (true) { Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(NO_ADDITIONAL_SECRET, iterationNumber, HASH_WIDTH); Stopwatch stopwatch = Stopwatch.createStarted(); pbkdf2PasswordEncoder.encode(TEST_PASSWORD); stopwatch.stop(); long duration = stopwatch.elapsed(TimeUnit.MILLISECONDS); if (duration > GOAL_MILLISECONDS_PER_PASSWORD) { return iterationNumber; } iterationNumber += ITERATION_STEP; } } int calculateIteration(); }### Answer:
@Test void calculateIteration() { int iterationNumber = pbkdf2WorkFactorService.calculateIteration(); assertThat(iterationNumber).isGreaterThanOrEqualTo(150000); } |
### Question:
MessageConsumer { public void consumeStringMessage(String messageString) throws IOException { logger.info("Consuming message '{}'", messageString); UserCreatedMessage message = objectMapper.readValue(messageString, UserCreatedMessage.class); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); Set<ConstraintViolation<UserCreatedMessage>> violations = validator.validate(message); if(!violations.isEmpty()){ throw new ConstraintViolationException(violations); } } MessageConsumer(ObjectMapper objectMapper); void consumeStringMessage(String messageString); }### Answer:
@Test @PactVerification("userCreatedMessagePact") public void verifyCreatePersonPact() throws IOException { messageConsumer.consumeStringMessage(new String(this.currentMessage)); } |
### Question:
ReactiveBatchProcessor { void start() { Scheduler scheduler = threadPoolScheduler(threads, threadPoolQueueSize); messageSource.getMessageBatches() .subscribeOn(Schedulers.from(Executors.newSingleThreadExecutor())) .doOnNext(batch -> logger.log(batch.toString())) .flatMap(batch -> Flowable.fromIterable(batch.getMessages())) .flatMapSingle(m -> Single.defer(() -> Single.just(m) .map(messageHandler::handleMessage)) .subscribeOn(scheduler)) .subscribeWith(new SimpleSubscriber<>(threads, 1)); } ReactiveBatchProcessor(
MessageSource messageSource,
MessageHandler messageHandler,
int threads,
int threadPoolQueueSize); }### Answer:
@Test void allMessagesAreProcessedOnMultipleThreads() { int batches = 10; int batchSize = 3; int threads = 2; int threadPoolQueueSize = 10; MessageSource messageSource = new TestMessageSource(batches, batchSize); TestMessageHandler messageHandler = new TestMessageHandler(); ReactiveBatchProcessor processor = new ReactiveBatchProcessor( messageSource, messageHandler, threads, threadPoolQueueSize); processor.start(); await() .atMost(10, TimeUnit.SECONDS) .pollInterval(1, TimeUnit.SECONDS) .untilAsserted(() -> assertEquals(batches * batchSize, messageHandler.getProcessedMessages())); assertEquals(threads, messageHandler.threadNames().size()); } |
### Question:
IpAddressValidator implements ConstraintValidator<IpAddress, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { Pattern pattern = Pattern.compile("^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$"); Matcher matcher = pattern.matcher(value); try { if (!matcher.matches()) { return false; } else { for (int i = 1; i <= 4; i++) { int octet = Integer.valueOf(matcher.group(i)); if (octet > 255) { return false; } } return true; } } catch (Exception e) { return false; } } @Override boolean isValid(String value, ConstraintValidatorContext context); }### Answer:
@Test void test(){ IpAddressValidator validator = new IpAddressValidator(); assertTrue(validator.isValid("111.111.111.111", null)); assertFalse(validator.isValid("111.foo.111.111", null)); assertFalse(validator.isValid("111.111.256.111", null)); } |
### Question:
ValidatingServiceWithGroups { @Validated(OnCreate.class) void validateForCreate(@Valid InputWithCustomValidator input){ } }### Answer:
@Test void whenInputIsInvalidForCreate_thenThrowsException() { InputWithCustomValidator input = validInput(); input.setId(42L); assertThrows(ConstraintViolationException.class, () -> { service.validateForCreate(input); }); } |
### Question:
ValidatingServiceWithGroups { @Validated(OnUpdate.class) void validateForUpdate(@Valid InputWithCustomValidator input){ } }### Answer:
@Test void whenInputIsInvalidForUpdate_thenThrowsException() { InputWithCustomValidator input = validInput(); input.setId(null); assertThrows(ConstraintViolationException.class, () -> { service.validateForUpdate(input); }); } |
### Question:
ValidatingService { void validateInput(@Valid Input input){ } }### Answer:
@Test void whenInputIsValid_thenThrowsNoException(){ Input input = new Input(); input.setNumberBetweenOneAndTen(5); input.setIpAddress("111.111.111.111"); service.validateInput(input); }
@Test void whenInputIsInvalid_thenThrowsException(){ Input input = new Input(); input.setNumberBetweenOneAndTen(0); input.setIpAddress("invalid"); assertThrows(ConstraintViolationException.class, () -> { service.validateInput(input); }); } |
### Question:
MigrationsPlugin implements Plugin { public void init(Application<? extends ApplicationConfiguration> application) { DatabaseConfiguration dbConfig = application.getConfiguration().getDatabaseConfiguration(); URI uri = getUri(dbConfig.getUrl()); if (Strings.isNullOrEmpty(uri.getPath())) { flyway.setDataSource(dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword()); } else { flyway.setDataSource(getUrl(uri, false), dbConfig.getUsername(), dbConfig.getPassword()); flyway.setSchemas(uri.getPath().substring(1)); } flyway.migrate(); } MigrationsPlugin(); MigrationsPlugin(Flyway flyway); void init(Application<? extends ApplicationConfiguration> application); void destroy(); }### Answer:
@Test public void shouldSetDataSourceOnInit() { plugin.init(application); verify(flyway).setDataSource("jdbc:mysql: verify(flyway).setSchemas("test"); }
@Test public void shouldMigrateOnInit() { plugin.init(application); verify(flyway).migrate(); } |
### Question:
EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); }### Answer:
@Test public void shouldSetEntityKeyOnMetaDataWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("getCode"); handler.handle(metaData, key, method); verify(metaData).setEntityKey("code"); }
@Test public void shouldSetEntityKeyOnMetaDataWhenOnField() throws Exception { Field field = DummyModel.class.getDeclaredField("code"); handler.handle(metaData, key, field); verify(metaData).setEntityKey("code"); }
@Test(expectedExceptions=IllegalArgumentException.class, expectedExceptionsMessageRegExp="Method - readCode is not a getter") public void shouldThrowExceptionWhenMethodIsNotGetter() throws Exception { Method method = DummyModel.class.getDeclaredMethod("readCode"); handler.handle(metaData, key, method); } |
### Question:
SecureMultipleAnnotationHandler extends SecureAnnotationHandler { public void handle(SecurableMetaData metaData, Annotation annotation) { for (Secure secure : ((SecureMultiple) annotation).value()) { super.handle(metaData, secure); } } void handle(SecurableMetaData metaData, Annotation annotation); }### Answer:
@Test public void shouldHandleSecureAnnotation() { SecurableMetaData metaData = mock(SecurableMetaData.class); SecureMultipleAnnotationHandler handler = new SecureMultipleAnnotationHandler(); SecureMultiple multiple = mock(SecureMultiple.class); Secure secure1 = mock(Secure.class); when(secure1.permissions()).thenReturn(new String[] {"permission1", "permission2"}); when(secure1.method()).thenReturn(Method.GET); Secure secure2 = mock(Secure.class); when(secure2.permissions()).thenReturn(new String[] {"permission3"}); when(secure2.method()).thenReturn(Method.POST); when(multiple.value()).thenReturn(new Secure[]{secure1, secure2}); handler.handle(metaData, multiple); verify(metaData).addPermissionMetaData(new PermissionMetaData(Method.GET.getMethod(), Sets.newHashSet("permission1", "permission2"))); verify(metaData).addPermissionMetaData(new PermissionMetaData(Method.POST.getMethod(), Sets.newHashSet("permission3"))); } |
### Question:
ManyToManyAnnotationHandler extends OneToManyAnnotationHandler { @Override public Class<?> getAnnotationType() { return ManyToMany.class; } @Override Class<?> getAnnotationType(); }### Answer:
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), ManyToMany.class); } |
### Question:
ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return Action.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); }### Answer:
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), Action.class); } |
### Question:
SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return Searchable.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); }### Answer:
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), Searchable.class); } |
### Question:
SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); }### Answer:
@Test public void shouldAddSearchFieldToMetadataWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("getCode"); handler.handle(metaData, annotation, method); ParameterMetaData data = new ParameterMetaData("code", "code", String.class); metaData.addSearchField(data); }
@Test public void shouldAddSearchFieldWithValueToMetadataWhenOnMethod() throws Exception { when(annotation.value()).thenReturn("customCode"); Method method = DummyModel.class.getDeclaredMethod("getCode"); handler.handle(metaData, annotation, method); ParameterMetaData data = new ParameterMetaData("customCode", "code", String.class); metaData.addSearchField(data); }
@Test public void shouldAddSearchFieldToMetadataWhenOnField() throws Exception { Field field = DummyModel.class.getDeclaredField("code"); handler.handle(metaData, annotation, field); ParameterMetaData data = new ParameterMetaData("code", "code", String.class); metaData.addSearchField(data); }
@Test public void shouldAddSearchFieldWithValueToMetadataWhenOnField() throws Exception { when(annotation.value()).thenReturn("customCode"); Field field = DummyModel.class.getDeclaredField("code"); handler.handle(metaData, annotation, field); ParameterMetaData data = new ParameterMetaData("customCode", "code", String.class); metaData.addSearchField(data); } |
### Question:
OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return OneToOne.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); }### Answer:
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), OneToOne.class); } |
### Question:
OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { AssociationMetaData associationMetaData = new AssociationMetaData(getGetterName(method, false), method.getReturnType(), isEntity(method.getReturnType())); metaData.addAssociation(associationMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); }### Answer:
@Test public void shouldAddToMetadataAssociationWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("getSpouse"); handler.handle(metaData, annotation, method); AssociationMetaData data = new AssociationMetaData("spouse", DummyModel.class, true); verify(metaData).addAssociation(data); }
@Test public void shouldAddToMetadataAssociationWhenOnField() throws Exception { Field field = DummyModel.class.getDeclaredField("spouse"); handler.handle(metaData, annotation, field); AssociationMetaData data = new AssociationMetaData("spouse", DummyModel.class, true); verify(metaData).addAssociation(data); } |
### Question:
SecureAnnotationHandler { public void handle(SecurableMetaData metaData, Annotation annotation) { metaData.addPermissionMetaData(constructPermissionMetaData(annotation)); } void handle(SecurableMetaData metaData, Annotation annotation); }### Answer:
@Test public void shouldHandleSecureAnnotation() { SecurableMetaData metaData = mock(SecurableMetaData.class); SecureAnnotationHandler handler = new SecureAnnotationHandler(); Secure secure = mock(Secure.class); when(secure.permissions()).thenReturn(new String[] {"permission1", "permission2"}); when(secure.method()).thenReturn(Method.GET); handler.handle(metaData, secure); verify(metaData).addPermissionMetaData(new PermissionMetaData(Method.GET.getMethod(), Sets.newHashSet("permission1", "permission2"))); } |
### Question:
ManyToOneAnnotationHandler extends OneToOneAnnotationHandler { @Override public Class<?> getAnnotationType() { return ManyToOne.class; } @Override Class<?> getAnnotationType(); }### Answer:
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), ManyToOne.class); } |
### Question:
EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public void construct() { LinkedList<EntityNode> queue = new LinkedList<EntityNode>(); queue.offer(this); while (! queue.isEmpty()) { EntityNode node = queue.poll(); for (CollectionMetaData collection : node.getValue().getCollections()) { if (! collection.isEntity()) { continue; } EntityNode child = new EntityNode(collection, namingStrategy); if (node.addChild(child) != null) { queue.offer(child); } } } } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); void construct(); String getResourceName(); String getName(); EntityMetaData getEntityMetaData(); CollectionMetaData getSource(); EntityNodePath getEntityNodePath(String path); @Override String toString(); }### Answer:
@Test public void shouldConstructEntityTree() { entityNode = new EntityNode(CompositeModel.class, namingStrategy); entityNode.construct(); assertEquals(entityNode.getChildren().size(), 2); } |
### Question:
EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public String getName() { return name; } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); void construct(); String getResourceName(); String getName(); EntityMetaData getEntityMetaData(); CollectionMetaData getSource(); EntityNodePath getEntityNodePath(String path); @Override String toString(); }### Answer:
@Test public void shouldPopulateEntityNodeName() { entityNode = new EntityNode(CompositeModel.class, namingStrategy); assertEquals(entityNode.getName(), "compositeModel"); } |
### Question:
EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public String getResourceName() { return resourceName; } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); void construct(); String getResourceName(); String getName(); EntityMetaData getEntityMetaData(); CollectionMetaData getSource(); EntityNodePath getEntityNodePath(String path); @Override String toString(); }### Answer:
@Test public void shouldPopulateEntityResourceName() { entityNode = new EntityNode(CompositeModel.class, namingStrategy); assertEquals(entityNode.getResourceName(), "composite_models"); } |
### Question:
EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public EntityMetaData getEntityMetaData() { return getValue(); } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); void construct(); String getResourceName(); String getName(); EntityMetaData getEntityMetaData(); CollectionMetaData getSource(); EntityNodePath getEntityNodePath(String path); @Override String toString(); }### Answer:
@Test public void shouldPopulateEntityMetaData() { entityNode = new EntityNode(Parent.class, namingStrategy); assertEquals(entityNode.getEntityMetaData(), EntityMetaDataProvider.instance().getEntityMetaData(Parent.class)); } |
### Question:
ResourceWrapper { public CtClass getGeneratedClass() { return generatedClass; } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }### Answer:
@Test public void shouldCreateGeneratedClass() { wrapper = new ResourceWrapper(resource, entityClass); assertNotNull(wrapper.getGeneratedClass()); } |
Subsets and Splits