JmsQueueBrowser { @SuppressWarnings("unchecked") public int sizeOf(final String queueName) { final Destination destination = destinationProvider.getDestination(queueName); if (destination instanceof Queue) { try (final Connection connection = connectionFactory.createConnection(); final Session session = connection.createSession(false, AUTO_ACKNOWLEDGE); final QueueBrowser queueBrowser = session.createBrowser((Queue) destination)) { return list(queueBrowser.getEnumeration()).size(); } catch (final JMSException e) { throw new JmsQueueBrowserException(format("Failed to connect to queue: '%s', when requesting queue size.", queueName), e); } } throw new JmsQueueBrowserUnsupportedOperation(format("The named destination must be a Queue: '%s', unable to get the size of a Topic.", queueName)); }  @SuppressWarnings("unchecked") int sizeOf(final String queueName);  }
@Test public void shouldReturnSizeOfQueue() throws Exception { final String destinationName = "queue-name"; final Queue queue = mock(Queue.class); final Connection connection = mock(Connection.class); final Session session = mock(Session.class); final QueueBrowser queueBrowser = mock(QueueBrowser.class); final Message message = mock(Message.class); when(destinationProvider.getDestination(destinationName)).thenReturn(queue); when(connectionFactory.createConnection()).thenReturn(connection); when(connection.createSession(false, AUTO_ACKNOWLEDGE)).thenReturn(session); when(session.createBrowser(queue)).thenReturn(queueBrowser); when(queueBrowser.getEnumeration()).thenReturn(enumeration(asList(message, message, message, message, message))); final int queueSize = jmsQueueBrowser.sizeOf(destinationName); assertThat(queueSize, is(5)); }
@Test public void shouldThrowJmsQueueBrowserExceptionIfJMSExceptionThrown() throws Exception { final String destinationName = "queue-name"; final Queue queue = mock(Queue.class); final JMSException jmsException = new JMSException("Test Message"); when(destinationProvider.getDestination(destinationName)).thenReturn(queue); when(connectionFactory.createConnection()).thenThrow(jmsException); try { jmsQueueBrowser.sizeOf(destinationName); fail(); } catch (final JmsQueueBrowserException exception) { assertThat(exception.getMessage(), is("Failed to connect to queue: 'queue-name', when requesting queue size.")); } }
@Test public void shouldThrowJmsQueueBrowserUnsupportedOperationIfQueueNameIsNotAQueue() throws Exception { final String destinationName = "topic-name"; final Topic topic = mock(Topic.class); when(destinationProvider.getDestination(destinationName)).thenReturn(topic); try { jmsQueueBrowser.sizeOf(destinationName); fail(); } catch (final JmsQueueBrowserUnsupportedOperation exception) { assertThat(exception.getMessage(), is("The named destination must be a Queue: 'topic-name', unable to get the size of a Topic.")); } }