method2testcases
stringlengths 118
6.63k
|
---|
### 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 Set<JAnnotation<?>> getAnnotations() throws ClasspathAccessException { AnnotationsAttribute visible = (AnnotationsAttribute) getClassFile().getAttribute(AnnotationsAttribute.visibleTag); AnnotationsAttribute invisible = (AnnotationsAttribute) getClassFile().getAttribute(AnnotationsAttribute.invisibleTag); Set<JAnnotation<?>> annotations = new HashSet<JAnnotation<?>>(); List<Annotation> annotationsList = new ArrayList<Annotation>(); if (visible != null) { annotationsList.addAll(Arrays.asList(visible.getAnnotations())); } if (invisible != null) { annotationsList.addAll(Arrays.asList(invisible.getAnnotations())); } for (Annotation nextAnnotation : annotationsList) { annotations.add(JAnnotation.getJAnnotation(nextAnnotation, this, getResolver())); } return annotations; } 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:
@SuppressWarnings("deprecation") @Test public void getAnnotations() { ClasspathResolver helper = new ClasspathResolver(); JInterface intf = JInterface.getJInterface("java.rmi.registry.RegistryHandler", helper); assertEquals(java.rmi.registry.RegistryHandler.class, intf.getActualClass()); assertEquals(java.rmi.registry.RegistryHandler.class, intf.getActualInterface()); assertEquals(1, intf.getAnnotations().size()); JAnnotation<?> ann = intf.getAnnotations().iterator().next(); assertTrue(ann.getActualAnnotation() instanceof Deprecated); } |
### 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:
PahoAsyncMqttClientService extends AbstractMqttClientService implements MqttClientService, MqttCallbackExtended, IMqttActionListener { @Override public String getClientId() { return mqttClient.getClientId(); } PahoAsyncMqttClientService(final String serverUri, final String clientId,
final MqttClientConnectionType connectionType,
final MqttClientPersistence clientPersistence); @Override /** * Publishes a {@link Message} to the MQTT Broker. * * @param message the {@link Message} to send * @throws IllegalArgumentException if the {@code message} is null * @throws MessagingException if the {@code message} could not be sent */ void handleMessage(final Message<?> message); @Override String getClientId(); @Override boolean start(); @Override boolean isConnected(); @Override String getConnectedServerUri(); @Override void subscribe(final String topicFilter, final MqttQualityOfService qualityOfService); @Override void unsubscribe(final String topicFilter); @Override void stop(); @Override void close(); @Override void connectionLost(final Throwable throwable); @Override void deliveryComplete(final IMqttDeliveryToken token); @Override void messageArrived(final String topic, final MqttMessage message); MqttConnectOptions getMqttConnectOptions(); @Override void connectComplete(final boolean reconnect, final String serverUri); @Override void onFailure(final IMqttToken token, final Throwable throwable); @Override void onSuccess(final IMqttToken token); }### Answer:
@Test public void testConstructionBlankServerUri() throws MqttException { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_SERVER_URI); new PahoAsyncMqttClientService(VALUE_BLANK, BrokerHelper.getClientId(), MqttClientConnectionType.PUBSUB, null); }
@Test public void testConstructionNullServerUri() throws MqttException { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_SERVER_URI); new PahoAsyncMqttClientService(null, BrokerHelper.getClientId(), MqttClientConnectionType.PUBSUB, null); }
@Test public void testConstructionNullConnectionType() throws MqttException { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("'connectionType' must be set!"); new PahoAsyncMqttClientService(BrokerHelper.getBrokerUri(), BrokerHelper.getClientId(), null, null); } |
### 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 MqttQualityOfService getMqttQualityOfServiceHeaderValue(Message<?> message, int defaultLevelIdentifier) { Integer levelIdentifier = defaultLevelIdentifier; try { if (message != null && message.getHeaders().containsKey(QOS)) { levelIdentifier = message.getHeaders().get(QOS, Integer.class); } } catch (IllegalArgumentException ex) { LOG.debug("Could not convert the QOS header value to an Integer!", ex); } return MqttQualityOfService.findByLevelIdentifier(levelIdentifier); } 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 testMqttQualityOfServiceHeader() { Assert.assertEquals(MqttQualityOfService.QOS_2, MqttHeaderHelper.getMqttQualityOfServiceHeaderValue(null, MqttQualityOfService.QOS_2.getLevelIdentifier())); MessageBuilder<String> builder = MessageBuilder.withPayload("See QoS header"); Assert.assertEquals(MqttQualityOfService.QOS_2, MqttHeaderHelper.getMqttQualityOfServiceHeaderValue(builder.build(), MqttQualityOfService.QOS_2.getLevelIdentifier())); builder.setHeader(MqttHeaderHelper.QOS, "blah!"); Assert.assertEquals(MqttQualityOfService.QOS_2, MqttHeaderHelper.getMqttQualityOfServiceHeaderValue(builder.build(), MqttQualityOfService.QOS_2.getLevelIdentifier())); builder.setHeader(MqttHeaderHelper.QOS, MqttQualityOfService.QOS_1.getLevelIdentifier()); Assert.assertEquals(MqttQualityOfService.QOS_1, MqttHeaderHelper.getMqttQualityOfServiceHeaderValue(builder.build(), MqttQualityOfService.QOS_2.getLevelIdentifier())); } |
### 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:
MqttClientEventPublisher { public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverUri, subscribedTopics, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect,
Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier,
String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception,
ApplicationEventPublisher applicationEventPublisher, Object source); }### Answer:
@Test public void testPublishConnectedEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishConnectedEvent(CLIENT_ID, SERVER_URI, SUBSCRIBED_TOPICS_EMPTY, null, this); }
@Test public void testPublishConnectedEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_CLIENT_ID); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectedEvent(null, SERVER_URI, SUBSCRIBED_TOPICS_EMPTY, applicationEventPublisher, this); }
@Test public void testPublishConnectedEventNullServerUri() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("'serverUri' must be set!"); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectedEvent(CLIENT_ID, null, SUBSCRIBED_TOPICS_EMPTY, applicationEventPublisher, this); }
@Test public void testPublishConnectedEventNullSubscribedTopics() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("'subscribedTopics' must be set!"); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectedEvent(CLIENT_ID, SERVER_URI, null, applicationEventPublisher, this); }
@Test public void testPublishConnectedEvent() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectedEvent(CLIENT_ID, SERVER_URI, SUBSCRIBED_TOPICS_EMPTY, applicationEventPublisher, this); Mockito.verify(applicationEventPublisher, Mockito.atLeast(1)) .publishEvent(Mockito.any(MqttClientConnectedEvent.class)); } |
### Question:
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect,
Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier,
String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception,
ApplicationEventPublisher applicationEventPublisher, Object source); }### Answer:
@Test public void testPublishConnectionFailureEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishConnectionFailureEvent(CLIENT_ID, true, new Exception(), null, this); }
@Test public void testPublishConnectionFailureEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_CLIENT_ID); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectionFailureEvent(null, true, new Exception(), applicationEventPublisher, this); }
@Test public void testPublishConnectionFailureEvent() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectionFailureEvent(CLIENT_ID, true, new Exception(), applicationEventPublisher, this); Mockito.verify(applicationEventPublisher, Mockito.atLeast(1)) .publishEvent(Mockito.any(MqttClientConnectionFailureEvent.class)); } |
### Question:
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect,
Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier,
String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception,
ApplicationEventPublisher applicationEventPublisher, Object source); }### Answer:
@Test public void testPublishConnectionLostEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishConnectionLostEvent(CLIENT_ID, true, null, this); }
@Test public void testPublishConnectionLostEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_CLIENT_ID); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectionLostEvent(null, true, applicationEventPublisher, this); }
@Test public void testPublishConnectionLostEvent() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectionLostEvent(CLIENT_ID, true, applicationEventPublisher, this); Mockito.verify(applicationEventPublisher, Mockito.atLeast(1)) .publishEvent(Mockito.any(MqttClientConnectionLostEvent.class)); } |
### Question:
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect,
Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier,
String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception,
ApplicationEventPublisher applicationEventPublisher, Object source); }### Answer:
@Test public void testPublishDisconnectedEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishDisconnectedEvent(CLIENT_ID, null, this); }
@Test public void testPublishDisconnectedEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_CLIENT_ID); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishDisconnectedEvent(null, applicationEventPublisher, this); }
@Test public void testPublishDisconnectedEvent() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishDisconnectedEvent(CLIENT_ID, applicationEventPublisher, this); Mockito.verify(applicationEventPublisher, Mockito.atLeast(1)) .publishEvent(Mockito.any(MqttClientDisconnectedEvent.class)); } |
### Question:
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect,
Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier,
String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception,
ApplicationEventPublisher applicationEventPublisher, Object source); }### Answer:
@Test public void testPublishMessageDeliveredEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishMessageDeliveredEvent(CLIENT_ID, MESSAGE_ID, null, this); }
@Test public void testPublishMessageDeliveredEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_CLIENT_ID); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishMessageDeliveredEvent(null, MESSAGE_ID, applicationEventPublisher, this); }
@Test public void testPublishMessageDeliveredEvent() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishMessageDeliveredEvent(CLIENT_ID, MESSAGE_ID, applicationEventPublisher, this); Mockito.verify(applicationEventPublisher, Mockito.atLeast(1)) .publishEvent(Mockito.any(MqttMessageDeliveredEvent.class)); } |
### Question:
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect,
Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier,
ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier,
String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception,
ApplicationEventPublisher applicationEventPublisher, Object source); }### Answer:
@Test public void testPublishMessagePublishedEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishMessagePublishedEvent(CLIENT_ID, MESSAGE_ID, CORRELATION_ID, null, this); }
@Test public void testPublishMessagePublishedEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_CLIENT_ID); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishMessagePublishedEvent(null, MESSAGE_ID, CORRELATION_ID, applicationEventPublisher, this); }
@Test public void testPublishMessagePublishedEventNullCorrelationId() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishMessagePublishedEvent(CLIENT_ID, MESSAGE_ID, null, applicationEventPublisher, this); }
@Test public void testPublishMessagePublishedEvent() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishMessagePublishedEvent(CLIENT_ID, MESSAGE_ID, CORRELATION_ID, applicationEventPublisher, this); Mockito.verify(applicationEventPublisher, Mockito.atLeast(1)) .publishEvent(Mockito.any(MqttMessagePublishedEvent.class)); } |
### 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:
CommandDispatcher { public void messageHandler(Message message) { logger.trace("Received message {} {}", commandDispatcherId, message); Optional<CommandHandler> possibleMethod = commandHandlers.findTargetMethod(message); if (!possibleMethod.isPresent()) { throw new RuntimeException("No method for " + message); } CommandHandler m = possibleMethod.get(); Object param = convertPayload(m, message.getPayload()); Map<String, String> correlationHeaders = correlationHeaders(message.getHeaders()); Map<String, String> pathVars = getPathVars(message, m); Optional<String> defaultReplyChannel = message.getHeader(CommandMessageHeaders.REPLY_TO); List<Message> replies; try { CommandMessage cm = new CommandMessage(message.getId(), param, correlationHeaders, message); replies = invoke(m, cm, pathVars); logger.trace("Generated replies {} {} {}", commandDispatcherId, message, replies); } catch (Exception e) { logger.error("Generated error {} {} {}", commandDispatcherId, message, e.getClass().getName()); logger.error("Generated error", e); handleException(message, param, m, e, pathVars, defaultReplyChannel); return; } if (replies != null) { sendReplies(correlationHeaders, replies, defaultReplyChannel); } else { logger.trace("Null replies - not publishling"); } } CommandDispatcher(String commandDispatcherId,
CommandHandlers commandHandlers,
MessageConsumer messageConsumer,
MessageProducer messageProducer); @PostConstruct void initialize(); void messageHandler(Message message); }### Answer:
@Test public void shouldDispatchCommand() { String commandDispatcherId = "fooId"; CommandDispatcherTestTarget target = spy(new CommandDispatcherTestTarget()); ChannelMapping channelMapping = mock(ChannelMapping.class); MessageConsumer messageConsumer = mock(MessageConsumer.class); MessageProducer messageProducer = mock(MessageProducer.class); CommandDispatcher dispatcher = new CommandDispatcher(commandDispatcherId, defineCommandHandlers(target), messageConsumer, messageProducer); String customerId = "customer0"; String resource = "/customers/" + customerId; Command command = new TestCommand(); String replyTo = "replyTo-xxx"; String channel = "myChannel"; Message message = CommandProducerImpl.makeMessage(channel, resource, command, replyTo, singletonMap(Message.ID, "999")); dispatcher.messageHandler(message); verify(target).reserveCredit(any(CommandMessage.class), any(PathVariables.class)); verify(messageProducer).send(any(), any()); verifyNoMoreInteractions(messageProducer, target); } |
### 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:
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }### Answer:
@Test public void isLogTraceEnabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.TRACE); assertTrue(logger.isEnabled(LogLevel.TRACE, "logger name")); }
@Test public void isLogDebugEnabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.DEBUG); assertTrue(logger.isEnabled(LogLevel.DEBUG, "logger name")); }
@Test public void isLogInfoEnabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.INFO); assertTrue(logger.isEnabled(LogLevel.INFO, "logger name")); }
@Test public void isLogErrorEnabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.ERROR); assertTrue(logger.isEnabled(LogLevel.ERROR, "logger name")); }
@Test public void isLogFatalEnabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.FATAL); assertTrue(logger.isEnabled(LogLevel.FATAL, "logger name")); }
@Test public void isLogTraceDisabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.OFF); assertFalse(logger.isEnabled(LogLevel.TRACE, "logger name")); } |
### Question:
HttpClient { public HttpRequestBuilder post() { return new RB(Method.POST); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); static HttpClientBuilder builder(); HttpRequestBuilder request(Method method); HttpRequestBuilder get(); HttpRequestBuilder head(); HttpRequestBuilder put(); HttpRequestBuilder post(); HttpRequestBuilder delete(); HttpRequestBuilder options(); @SuppressWarnings("deprecation") void shutdown(); void addActivityMonitor(ActivityMonitor monitor); void removeActivityMonitor(ActivityMonitor monitor); }### Answer:
@Test public void testPost() throws Throwable { final AM am = new AM(); final String ur = "http: client.addActivityMonitor(am); final DeferredAssertions assertions = new DeferredAssertions(); final Set<StateType> stateTypes = new HashSet<>(); final String[] xheader = new String[1]; ResponseFuture f = client.post() .setURL(ur) .addHeader(Headers.CONNECTION, Connection.close) .setBody("This is a test", MediaType.PLAIN_TEXT_UTF_8) .onEvent(new Receiver<State<?>>() { public void receive(State<?> state) { stateTypes.add(state.stateType()); if (null != state.stateType()) switch (state.stateType()) { case Finished: DefaultFullHttpResponse d = (DefaultFullHttpResponse) state.get(); assertions.add(() -> { assertTrue(am.started.contains(ur)); }); break; case Closed: assertions.add(() -> { assertTrue(am.ended.contains(ur)); }); break; case FullContentReceived: ByteBuf buf = (ByteBuf) state.get(); byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(0, bytes); final String content = new String(bytes, CharsetUtil.UTF_8); assertions.add(() -> { assertEquals("Hey you, This is a test", content); }); break; case HeadersReceived: xheader[0] = ((HttpResponse) state.get()).headers().get("X-foo"); break; default: break; } } }).execute(); f.await(5, TimeUnit.SECONDS).throwIfError(); server.throwLast(); assertions.exec(); assertTrue(stateTypes.contains(StateType.Connected)); assertTrue(stateTypes.contains(StateType.SendRequest)); assertTrue(stateTypes.contains(StateType.Connecting)); assertTrue(stateTypes.contains(StateType.ContentReceived)); assertTrue(stateTypes.contains(StateType.FullContentReceived)); assertTrue(stateTypes.contains(StateType.HeadersReceived)); assertFalse(stateTypes.contains(StateType.Cancelled)); assertFalse(stateTypes.contains(StateType.Error)); assertEquals("bar", xheader[0]); } |
### 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:
ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } @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 shouldAddActionMethodToMetadataWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("dummyAction"); handler.handle(metaData, annotation, method); ActionMetaData data = new ActionMetaData("dummyAction", "/dummy", method); verify(metaData).addActionMethod(data); }
@Test public void shouldAddActionMethodWithCustomValueToMetadataWhenOnMethod() throws Exception { when(annotation.value()).thenReturn("customAction"); Method method = DummyModel.class.getDeclaredMethod("dummyAction"); handler.handle(metaData, annotation, method); ActionMetaData data = new ActionMetaData("customAction", "/custom", method); verify(metaData).addActionMethod(data); }
@Test public void shouldAddActionMethodToMetadataWithParamsWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("dummyAction", String.class, Long.class); handler.handle(metaData, annotation, method); ActionMetaData data = new ActionMetaData("dummyAction", "/dummy", method); data.addParameter(new ParameterMetaData("param1", "param1", String.class)); data.addParameter(new ParameterMetaData("param2", "param2", Long.class)); verify(metaData).addActionMethod(data); }
@Test(expectedExceptions=IllegalArgumentException.class) public void shouldNotAddActionToMetadataWhenOnField() throws Exception { Field field = DummyModel.class.getDeclaredField("children"); handler.handle(metaData, annotation, field); }
@Test(expectedExceptions=MinnalInstrumentationException.class) public void shouldThrowExceptionWhenActionSpecifiedOnNonAggregateRoot() throws Exception { when(metaData.getEntityClass()).thenReturn((Class) NonAggregateRootModel.class); Method method = NonAggregateRootModel.class.getDeclaredMethod("dummyAction"); handler.handle(metaData, annotation, method); } |
### Question:
AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); Clients getClients(); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); void registerListener(AuthenticationListener listener); static final String PRINCIPAL; }### Answer:
@Test public void shouldGetClientFromSessionIfClientNameAttributeIsSet() { Session session = mock(Session.class); when(session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn("client1"); assertEquals(filter.getClient(session), basicClient); }
@Test public void shouldReturnNullClientFromSessionIfClientNameAttributeIsNotSet() { Session session = mock(Session.class); when(session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn(null); assertNull(filter.getClient(session)); }
@Test(expectedExceptions=TechnicalException.class) public void shouldThrowExceptionIfClientNameIsNotFoundInSession() { Session session = mock(Session.class); when(session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn("unknownClient"); filter.getClient(session); }
@Test public void shouldReturnNullFromRequestContextIfClientNameAttributeIsNotSet() { JaxrsWebContext context = mock(JaxrsWebContext.class); when(context.getRequestParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn(null); assertNull(filter.getClient(context)); }
@Test public void shouldThrowExceptionIfClientNameIsNotFoundInRequestContext() { JaxrsWebContext context = mock(JaxrsWebContext.class); when(context.getRequestParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn("unknownClient"); assertNull(filter.getClient(context)); }
@Test public void shouldGetClientFromRequestContextIfClientNameAttributeIsSet() { JaxrsWebContext context = mock(JaxrsWebContext.class); when(context.getRequestParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn("client1"); assertEquals(filter.getClient(context), basicClient); } |
### 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()); } |
### Question:
ResourceWrapper { protected ResourceClassCreator getResourceClassCreator() { return new ResourceClassCreator(resource, namingStrategy, entityClass, path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }### Answer:
@Test public void shouldCreateResourceClassCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourceClassCreator creator = wrapper.getResourceClassCreator(); assertEquals(creator.getEntityClass(), entityClass); assertEquals(creator.getPath(), resource.getPath()); assertEquals(creator.getResource(), resource); } |
### Question:
ResourceWrapper { protected CreateMethodCreator getCreateMethodCreator(ResourcePath path) { return new CreateMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }### Answer:
@Test public void shouldGetCreateMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, true, namingStrategy); CreateMethodCreator creator = wrapper.getCreateMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); } |
### Question:
ResourceWrapper { protected ReadMethodCreator getReadMethodCreator(ResourcePath path) { return new ReadMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }### Answer:
@Test public void shouldGetReadMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); ReadMethodCreator creator = wrapper.getReadMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); } |
### Question:
ResourceWrapper { protected ActionMethodCreator getActionMethodCreator(ResourcePath path, ActionMetaData action) { return new ActionMethodCreator(generatedClass, resource, path, this.path, action); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }### Answer:
@Test public void shouldGetActionMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); ActionMetaData action = mock(ActionMetaData.class); ActionMethodCreator creator = wrapper.getActionMethodCreator(resourcePath, action); assertMethodCreator(creator, resourcePath); assertEquals(creator.getAction(), action); } |
### Question:
ResourceWrapper { protected DeleteMethodCreator getDeleteMethodCreator(ResourcePath path) { return new DeleteMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }### Answer:
@Test public void shouldGetDeleteMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); DeleteMethodCreator creator = wrapper.getDeleteMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); } |
### Question:
ResourceWrapper { protected ListMethodCreator getListMethodCreator(ResourcePath path) { return new ListMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }### Answer:
@Test public void shouldGetListMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); ListMethodCreator creator = wrapper.getListMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); } |
### Question:
ResourceWrapper { protected UpdateMethodCreator getUpdateMethodCreator(ResourcePath path) { return new UpdateMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); }### Answer:
@Test public void shouldGetUpdateMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); UpdateMethodCreator creator = wrapper.getUpdateMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); } |