method2testcases
stringlengths 118
6.63k
|
---|
### Question:
JmsPoolSession implements Session, TopicSession, QueueSession, XASession, AutoCloseable { @Override public XAResource getXAResource() { final PooledSessionHolder session; try { session = safeGetSessionHolder(); } catch (JMSException e) { throw JMSExceptionSupport.createRuntimeException(e); } if (session.getSession() instanceof XASession) { return ((XASession) session.getSession()).getXAResource(); } return null; } JmsPoolSession(PooledSessionKey key, PooledSessionHolder sessionHolder, KeyedObjectPool<PooledSessionKey, PooledSessionHolder> sessionPool, boolean transactional); @Override void close(); @Override TemporaryQueue createTemporaryQueue(); @Override TemporaryTopic createTemporaryTopic(); @Override Queue createQueue(String s); @Override Topic createTopic(String s); @Override BytesMessage createBytesMessage(); @Override MapMessage createMapMessage(); @Override Message createMessage(); @Override ObjectMessage createObjectMessage(); @Override ObjectMessage createObjectMessage(Serializable serializable); @Override StreamMessage createStreamMessage(); @Override TextMessage createTextMessage(); @Override TextMessage createTextMessage(String s); @Override void unsubscribe(String s); @Override int getAcknowledgeMode(); @Override boolean getTransacted(); @Override void recover(); @Override void commit(); @Override void rollback(); @Override XAResource getXAResource(); @Override Session getSession(); @Override MessageListener getMessageListener(); @Override void setMessageListener(MessageListener messageListener); @Override void run(); @Override QueueBrowser createBrowser(Queue queue); @Override QueueBrowser createBrowser(Queue queue, String selector); @Override MessageConsumer createConsumer(Destination destination); @Override MessageConsumer createConsumer(Destination destination, String selector); @Override MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal); @Override TopicSubscriber createDurableSubscriber(Topic topic, String selector); @Override TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal); @Override TopicSubscriber createSubscriber(Topic topic); @Override TopicSubscriber createSubscriber(Topic topic, String selector, boolean local); @Override QueueReceiver createReceiver(Queue queue); @Override QueueReceiver createReceiver(Queue queue, String selector); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector); @Override MessageConsumer createDurableConsumer(Topic topic, String name); @Override MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector); @Override MessageProducer createProducer(Destination destination); @Override QueueSender createSender(Queue queue); @Override TopicPublisher createPublisher(Topic topic); void addSessionEventListener(JmsPoolSessionEventListener listener); Session getInternalSession(); void setIsXa(boolean isXa); boolean isIgnoreClose(); void setIgnoreClose(boolean ignoreClose); @Override String toString(); }### Answer:
@Test(timeout = 60000) public void testGetXAResource() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); JmsPoolSession session = (JmsPoolSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); assertNull("Non-XA session should not return an XA Resource", session.getXAResource()); session.close(); try { session.getXAResource(); fail("Session should be closed."); } catch (IllegalStateRuntimeException isre) {} }
@Test(timeout = 60000) public void testGetXAResourceOnNonXAPooledSession() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); JmsPoolSession session = (JmsPoolSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); assertNull(session.getXAResource()); } |
### Question:
JmsPoolJMSProducer implements JMSProducer { @Override public JMSProducer clearProperties() { messageProperties.clear(); return this; } JmsPoolJMSProducer(JmsPoolSession session, JmsPoolMessageProducer producer); @Override String toString(); @Override JMSProducer send(Destination destination, Message message); @Override JMSProducer send(Destination destination, byte[] body); @Override JMSProducer send(Destination destination, Map<String, Object> body); @Override JMSProducer send(Destination destination, Serializable body); @Override JMSProducer send(Destination destination, String body); @Override JMSProducer clearProperties(); @Override Set<String> getPropertyNames(); @Override boolean propertyExists(String name); @Override boolean getBooleanProperty(String name); @Override byte getByteProperty(String name); @Override double getDoubleProperty(String name); @Override float getFloatProperty(String name); @Override int getIntProperty(String name); @Override long getLongProperty(String name); @Override Object getObjectProperty(String name); @Override short getShortProperty(String name); @Override String getStringProperty(String name); @Override JMSProducer setProperty(String name, boolean value); @Override JMSProducer setProperty(String name, byte value); @Override JMSProducer setProperty(String name, double value); @Override JMSProducer setProperty(String name, float value); @Override JMSProducer setProperty(String name, int value); @Override JMSProducer setProperty(String name, long value); @Override JMSProducer setProperty(String name, Object value); @Override JMSProducer setProperty(String name, short value); @Override JMSProducer setProperty(String name, String value); @Override String getJMSCorrelationID(); @Override JMSProducer setJMSCorrelationID(String correlationId); @Override byte[] getJMSCorrelationIDAsBytes(); @Override JMSProducer setJMSCorrelationIDAsBytes(byte[] correlationIdBytes); @Override Destination getJMSReplyTo(); @Override JMSProducer setJMSReplyTo(Destination replyTo); @Override String getJMSType(); @Override JMSProducer setJMSType(String type); @Override CompletionListener getAsync(); @Override JMSProducer setAsync(CompletionListener completionListener); @Override long getDeliveryDelay(); @Override JMSProducer setDeliveryDelay(long deliveryDelay); @Override int getDeliveryMode(); @Override JMSProducer setDeliveryMode(int deliveryMode); @Override boolean getDisableMessageID(); @Override JMSProducer setDisableMessageID(boolean disableMessageId); @Override boolean getDisableMessageTimestamp(); @Override JMSProducer setDisableMessageTimestamp(boolean disableTimestamp); @Override int getPriority(); @Override JMSProducer setPriority(int priority); @Override long getTimeToLive(); @Override JMSProducer setTimeToLive(long timeToLive); MessageProducer getMessageProducer(); }### Answer:
@Test public void testClearProperties() { JMSProducer producer = context.createProducer(); producer.setProperty("Property_1", "1"); producer.setProperty("Property_2", "2"); producer.setProperty("Property_3", "3"); assertEquals(3, producer.getPropertyNames().size()); producer.clearProperties(); assertEquals(0, producer.getPropertyNames().size()); } |
### Question:
JmsPoolSession implements Session, TopicSession, QueueSession, XASession, AutoCloseable { @Override public Queue createQueue(String s) throws JMSException { return getInternalSession().createQueue(s); } JmsPoolSession(PooledSessionKey key, PooledSessionHolder sessionHolder, KeyedObjectPool<PooledSessionKey, PooledSessionHolder> sessionPool, boolean transactional); @Override void close(); @Override TemporaryQueue createTemporaryQueue(); @Override TemporaryTopic createTemporaryTopic(); @Override Queue createQueue(String s); @Override Topic createTopic(String s); @Override BytesMessage createBytesMessage(); @Override MapMessage createMapMessage(); @Override Message createMessage(); @Override ObjectMessage createObjectMessage(); @Override ObjectMessage createObjectMessage(Serializable serializable); @Override StreamMessage createStreamMessage(); @Override TextMessage createTextMessage(); @Override TextMessage createTextMessage(String s); @Override void unsubscribe(String s); @Override int getAcknowledgeMode(); @Override boolean getTransacted(); @Override void recover(); @Override void commit(); @Override void rollback(); @Override XAResource getXAResource(); @Override Session getSession(); @Override MessageListener getMessageListener(); @Override void setMessageListener(MessageListener messageListener); @Override void run(); @Override QueueBrowser createBrowser(Queue queue); @Override QueueBrowser createBrowser(Queue queue, String selector); @Override MessageConsumer createConsumer(Destination destination); @Override MessageConsumer createConsumer(Destination destination, String selector); @Override MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal); @Override TopicSubscriber createDurableSubscriber(Topic topic, String selector); @Override TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal); @Override TopicSubscriber createSubscriber(Topic topic); @Override TopicSubscriber createSubscriber(Topic topic, String selector, boolean local); @Override QueueReceiver createReceiver(Queue queue); @Override QueueReceiver createReceiver(Queue queue, String selector); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector); @Override MessageConsumer createDurableConsumer(Topic topic, String name); @Override MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector); @Override MessageProducer createProducer(Destination destination); @Override QueueSender createSender(Queue queue); @Override TopicPublisher createPublisher(Topic topic); void addSessionEventListener(JmsPoolSessionEventListener listener); Session getInternalSession(); void setIsXa(boolean isXa); boolean isIgnoreClose(); void setIgnoreClose(boolean ignoreClose); @Override String toString(); }### Answer:
@Test(timeout = 60000) public void testCreateQueue() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(getTestName()); assertNotNull(queue); assertEquals(getTestName(), queue.getQueueName()); assertTrue(queue instanceof MockJMSQueue); } |
### Question:
JmsPoolSession implements Session, TopicSession, QueueSession, XASession, AutoCloseable { @Override public Topic createTopic(String s) throws JMSException { return getInternalSession().createTopic(s); } JmsPoolSession(PooledSessionKey key, PooledSessionHolder sessionHolder, KeyedObjectPool<PooledSessionKey, PooledSessionHolder> sessionPool, boolean transactional); @Override void close(); @Override TemporaryQueue createTemporaryQueue(); @Override TemporaryTopic createTemporaryTopic(); @Override Queue createQueue(String s); @Override Topic createTopic(String s); @Override BytesMessage createBytesMessage(); @Override MapMessage createMapMessage(); @Override Message createMessage(); @Override ObjectMessage createObjectMessage(); @Override ObjectMessage createObjectMessage(Serializable serializable); @Override StreamMessage createStreamMessage(); @Override TextMessage createTextMessage(); @Override TextMessage createTextMessage(String s); @Override void unsubscribe(String s); @Override int getAcknowledgeMode(); @Override boolean getTransacted(); @Override void recover(); @Override void commit(); @Override void rollback(); @Override XAResource getXAResource(); @Override Session getSession(); @Override MessageListener getMessageListener(); @Override void setMessageListener(MessageListener messageListener); @Override void run(); @Override QueueBrowser createBrowser(Queue queue); @Override QueueBrowser createBrowser(Queue queue, String selector); @Override MessageConsumer createConsumer(Destination destination); @Override MessageConsumer createConsumer(Destination destination, String selector); @Override MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal); @Override TopicSubscriber createDurableSubscriber(Topic topic, String selector); @Override TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal); @Override TopicSubscriber createSubscriber(Topic topic); @Override TopicSubscriber createSubscriber(Topic topic, String selector, boolean local); @Override QueueReceiver createReceiver(Queue queue); @Override QueueReceiver createReceiver(Queue queue, String selector); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector); @Override MessageConsumer createDurableConsumer(Topic topic, String name); @Override MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector); @Override MessageProducer createProducer(Destination destination); @Override QueueSender createSender(Queue queue); @Override TopicPublisher createPublisher(Topic topic); void addSessionEventListener(JmsPoolSessionEventListener listener); Session getInternalSession(); void setIsXa(boolean isXa); boolean isIgnoreClose(); void setIgnoreClose(boolean ignoreClose); @Override String toString(); }### Answer:
@Test(timeout = 60000) public void testCreateTopic() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(getTestName()); assertNotNull(topic); assertEquals(getTestName(), topic.getTopicName()); assertTrue(topic instanceof MockJMSTopic); } |
### Question:
JmsPoolSession implements Session, TopicSession, QueueSession, XASession, AutoCloseable { @Override public TemporaryQueue createTemporaryQueue() throws JMSException { TemporaryQueue result; result = getInternalSession().createTemporaryQueue(); for (JmsPoolSessionEventListener listener : this.sessionEventListeners) { listener.onTemporaryQueueCreate(result); } return result; } JmsPoolSession(PooledSessionKey key, PooledSessionHolder sessionHolder, KeyedObjectPool<PooledSessionKey, PooledSessionHolder> sessionPool, boolean transactional); @Override void close(); @Override TemporaryQueue createTemporaryQueue(); @Override TemporaryTopic createTemporaryTopic(); @Override Queue createQueue(String s); @Override Topic createTopic(String s); @Override BytesMessage createBytesMessage(); @Override MapMessage createMapMessage(); @Override Message createMessage(); @Override ObjectMessage createObjectMessage(); @Override ObjectMessage createObjectMessage(Serializable serializable); @Override StreamMessage createStreamMessage(); @Override TextMessage createTextMessage(); @Override TextMessage createTextMessage(String s); @Override void unsubscribe(String s); @Override int getAcknowledgeMode(); @Override boolean getTransacted(); @Override void recover(); @Override void commit(); @Override void rollback(); @Override XAResource getXAResource(); @Override Session getSession(); @Override MessageListener getMessageListener(); @Override void setMessageListener(MessageListener messageListener); @Override void run(); @Override QueueBrowser createBrowser(Queue queue); @Override QueueBrowser createBrowser(Queue queue, String selector); @Override MessageConsumer createConsumer(Destination destination); @Override MessageConsumer createConsumer(Destination destination, String selector); @Override MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal); @Override TopicSubscriber createDurableSubscriber(Topic topic, String selector); @Override TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal); @Override TopicSubscriber createSubscriber(Topic topic); @Override TopicSubscriber createSubscriber(Topic topic, String selector, boolean local); @Override QueueReceiver createReceiver(Queue queue); @Override QueueReceiver createReceiver(Queue queue, String selector); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector); @Override MessageConsumer createDurableConsumer(Topic topic, String name); @Override MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector); @Override MessageProducer createProducer(Destination destination); @Override QueueSender createSender(Queue queue); @Override TopicPublisher createPublisher(Topic topic); void addSessionEventListener(JmsPoolSessionEventListener listener); Session getInternalSession(); void setIsXa(boolean isXa); boolean isIgnoreClose(); void setIgnoreClose(boolean ignoreClose); @Override String toString(); }### Answer:
@Test(timeout = 60000) public void testCreateTemporaryQueue() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = session.createTemporaryQueue(); assertNotNull(queue); assertTrue(queue instanceof MockJMSTemporaryQueue); } |
### Question:
JmsPoolSession implements Session, TopicSession, QueueSession, XASession, AutoCloseable { @Override public TemporaryTopic createTemporaryTopic() throws JMSException { TemporaryTopic result; result = getInternalSession().createTemporaryTopic(); for (JmsPoolSessionEventListener listener : this.sessionEventListeners) { listener.onTemporaryTopicCreate(result); } return result; } JmsPoolSession(PooledSessionKey key, PooledSessionHolder sessionHolder, KeyedObjectPool<PooledSessionKey, PooledSessionHolder> sessionPool, boolean transactional); @Override void close(); @Override TemporaryQueue createTemporaryQueue(); @Override TemporaryTopic createTemporaryTopic(); @Override Queue createQueue(String s); @Override Topic createTopic(String s); @Override BytesMessage createBytesMessage(); @Override MapMessage createMapMessage(); @Override Message createMessage(); @Override ObjectMessage createObjectMessage(); @Override ObjectMessage createObjectMessage(Serializable serializable); @Override StreamMessage createStreamMessage(); @Override TextMessage createTextMessage(); @Override TextMessage createTextMessage(String s); @Override void unsubscribe(String s); @Override int getAcknowledgeMode(); @Override boolean getTransacted(); @Override void recover(); @Override void commit(); @Override void rollback(); @Override XAResource getXAResource(); @Override Session getSession(); @Override MessageListener getMessageListener(); @Override void setMessageListener(MessageListener messageListener); @Override void run(); @Override QueueBrowser createBrowser(Queue queue); @Override QueueBrowser createBrowser(Queue queue, String selector); @Override MessageConsumer createConsumer(Destination destination); @Override MessageConsumer createConsumer(Destination destination, String selector); @Override MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal); @Override TopicSubscriber createDurableSubscriber(Topic topic, String selector); @Override TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal); @Override TopicSubscriber createSubscriber(Topic topic); @Override TopicSubscriber createSubscriber(Topic topic, String selector, boolean local); @Override QueueReceiver createReceiver(Queue queue); @Override QueueReceiver createReceiver(Queue queue, String selector); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector); @Override MessageConsumer createDurableConsumer(Topic topic, String name); @Override MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector); @Override MessageProducer createProducer(Destination destination); @Override QueueSender createSender(Queue queue); @Override TopicPublisher createPublisher(Topic topic); void addSessionEventListener(JmsPoolSessionEventListener listener); Session getInternalSession(); void setIsXa(boolean isXa); boolean isIgnoreClose(); void setIgnoreClose(boolean ignoreClose); @Override String toString(); }### Answer:
@Test(timeout = 60000) public void testCreateTemporaryTopic() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryTopic topic = session.createTemporaryTopic(); assertNotNull(topic); assertTrue(topic instanceof MockJMSTemporaryTopic); } |
### Question:
JmsPoolSession implements Session, TopicSession, QueueSession, XASession, AutoCloseable { public void addSessionEventListener(JmsPoolSessionEventListener listener) throws JMSException { checkClosed(); if (!sessionEventListeners.contains(listener)) { this.sessionEventListeners.add(listener); } } JmsPoolSession(PooledSessionKey key, PooledSessionHolder sessionHolder, KeyedObjectPool<PooledSessionKey, PooledSessionHolder> sessionPool, boolean transactional); @Override void close(); @Override TemporaryQueue createTemporaryQueue(); @Override TemporaryTopic createTemporaryTopic(); @Override Queue createQueue(String s); @Override Topic createTopic(String s); @Override BytesMessage createBytesMessage(); @Override MapMessage createMapMessage(); @Override Message createMessage(); @Override ObjectMessage createObjectMessage(); @Override ObjectMessage createObjectMessage(Serializable serializable); @Override StreamMessage createStreamMessage(); @Override TextMessage createTextMessage(); @Override TextMessage createTextMessage(String s); @Override void unsubscribe(String s); @Override int getAcknowledgeMode(); @Override boolean getTransacted(); @Override void recover(); @Override void commit(); @Override void rollback(); @Override XAResource getXAResource(); @Override Session getSession(); @Override MessageListener getMessageListener(); @Override void setMessageListener(MessageListener messageListener); @Override void run(); @Override QueueBrowser createBrowser(Queue queue); @Override QueueBrowser createBrowser(Queue queue, String selector); @Override MessageConsumer createConsumer(Destination destination); @Override MessageConsumer createConsumer(Destination destination, String selector); @Override MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal); @Override TopicSubscriber createDurableSubscriber(Topic topic, String selector); @Override TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal); @Override TopicSubscriber createSubscriber(Topic topic); @Override TopicSubscriber createSubscriber(Topic topic, String selector, boolean local); @Override QueueReceiver createReceiver(Queue queue); @Override QueueReceiver createReceiver(Queue queue, String selector); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector); @Override MessageConsumer createDurableConsumer(Topic topic, String name); @Override MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector); @Override MessageProducer createProducer(Destination destination); @Override QueueSender createSender(Queue queue); @Override TopicPublisher createPublisher(Topic topic); void addSessionEventListener(JmsPoolSessionEventListener listener); Session getInternalSession(); void setIsXa(boolean isXa); boolean isIgnoreClose(); void setIgnoreClose(boolean ignoreClose); @Override String toString(); }### Answer:
@Test(timeout = 60000) public void testAddSessionEventListener() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); JmsPoolSession session = (JmsPoolSession) connection.createSession(); final CountDownLatch tempTopicCreated = new CountDownLatch(2); final CountDownLatch tempQueueCreated = new CountDownLatch(2); final CountDownLatch sessionClosed = new CountDownLatch(2); JmsPoolSessionEventListener listener = new JmsPoolSessionEventListener() { @Override public void onTemporaryTopicCreate(TemporaryTopic tempTopic) { tempTopicCreated.countDown(); } @Override public void onTemporaryQueueCreate(TemporaryQueue tempQueue) { tempQueueCreated.countDown(); } @Override public void onSessionClosed(JmsPoolSession session) { sessionClosed.countDown(); } }; session.addSessionEventListener(listener); session.addSessionEventListener(listener); assertNotNull(session.createTemporaryQueue()); assertNotNull(session.createTemporaryTopic()); session.close(); assertEquals(1, tempQueueCreated.getCount()); assertEquals(1, tempTopicCreated.getCount()); assertEquals(1, sessionClosed.getCount()); try { session.addSessionEventListener(listener); fail("Should throw on closed session."); } catch (IllegalStateException ise) {} } |
### Question:
JmsPoolSession implements Session, TopicSession, QueueSession, XASession, AutoCloseable { @Override public TopicSubscriber createDurableSubscriber(Topic topic, String selector) throws JMSException { return addTopicSubscriber(getInternalSession().createDurableSubscriber(topic, selector)); } JmsPoolSession(PooledSessionKey key, PooledSessionHolder sessionHolder, KeyedObjectPool<PooledSessionKey, PooledSessionHolder> sessionPool, boolean transactional); @Override void close(); @Override TemporaryQueue createTemporaryQueue(); @Override TemporaryTopic createTemporaryTopic(); @Override Queue createQueue(String s); @Override Topic createTopic(String s); @Override BytesMessage createBytesMessage(); @Override MapMessage createMapMessage(); @Override Message createMessage(); @Override ObjectMessage createObjectMessage(); @Override ObjectMessage createObjectMessage(Serializable serializable); @Override StreamMessage createStreamMessage(); @Override TextMessage createTextMessage(); @Override TextMessage createTextMessage(String s); @Override void unsubscribe(String s); @Override int getAcknowledgeMode(); @Override boolean getTransacted(); @Override void recover(); @Override void commit(); @Override void rollback(); @Override XAResource getXAResource(); @Override Session getSession(); @Override MessageListener getMessageListener(); @Override void setMessageListener(MessageListener messageListener); @Override void run(); @Override QueueBrowser createBrowser(Queue queue); @Override QueueBrowser createBrowser(Queue queue, String selector); @Override MessageConsumer createConsumer(Destination destination); @Override MessageConsumer createConsumer(Destination destination, String selector); @Override MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal); @Override TopicSubscriber createDurableSubscriber(Topic topic, String selector); @Override TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal); @Override TopicSubscriber createSubscriber(Topic topic); @Override TopicSubscriber createSubscriber(Topic topic, String selector, boolean local); @Override QueueReceiver createReceiver(Queue queue); @Override QueueReceiver createReceiver(Queue queue, String selector); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector); @Override MessageConsumer createDurableConsumer(Topic topic, String name); @Override MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector); @Override MessageProducer createProducer(Destination destination); @Override QueueSender createSender(Queue queue); @Override TopicPublisher createPublisher(Topic topic); void addSessionEventListener(JmsPoolSessionEventListener listener); Session getInternalSession(); void setIsXa(boolean isXa); boolean isIgnoreClose(); void setIgnoreClose(boolean ignoreClose); @Override String toString(); }### Answer:
@Test(timeout = 60000) public void testCreateDurableSubscriber() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); JmsPoolSession session = (JmsPoolSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(getTestName()); assertNotNull(session.createDurableSubscriber(topic, "name")); session.close(); try { session.createDurableSubscriber(topic, "name-2"); fail("Should not be able to createDurableSubscriber when closed"); } catch (JMSException ex) {} } |
### Question:
JmsPoolJMSProducer implements JMSProducer { @Override public boolean propertyExists(String name) { return messageProperties.containsKey(name); } JmsPoolJMSProducer(JmsPoolSession session, JmsPoolMessageProducer producer); @Override String toString(); @Override JMSProducer send(Destination destination, Message message); @Override JMSProducer send(Destination destination, byte[] body); @Override JMSProducer send(Destination destination, Map<String, Object> body); @Override JMSProducer send(Destination destination, Serializable body); @Override JMSProducer send(Destination destination, String body); @Override JMSProducer clearProperties(); @Override Set<String> getPropertyNames(); @Override boolean propertyExists(String name); @Override boolean getBooleanProperty(String name); @Override byte getByteProperty(String name); @Override double getDoubleProperty(String name); @Override float getFloatProperty(String name); @Override int getIntProperty(String name); @Override long getLongProperty(String name); @Override Object getObjectProperty(String name); @Override short getShortProperty(String name); @Override String getStringProperty(String name); @Override JMSProducer setProperty(String name, boolean value); @Override JMSProducer setProperty(String name, byte value); @Override JMSProducer setProperty(String name, double value); @Override JMSProducer setProperty(String name, float value); @Override JMSProducer setProperty(String name, int value); @Override JMSProducer setProperty(String name, long value); @Override JMSProducer setProperty(String name, Object value); @Override JMSProducer setProperty(String name, short value); @Override JMSProducer setProperty(String name, String value); @Override String getJMSCorrelationID(); @Override JMSProducer setJMSCorrelationID(String correlationId); @Override byte[] getJMSCorrelationIDAsBytes(); @Override JMSProducer setJMSCorrelationIDAsBytes(byte[] correlationIdBytes); @Override Destination getJMSReplyTo(); @Override JMSProducer setJMSReplyTo(Destination replyTo); @Override String getJMSType(); @Override JMSProducer setJMSType(String type); @Override CompletionListener getAsync(); @Override JMSProducer setAsync(CompletionListener completionListener); @Override long getDeliveryDelay(); @Override JMSProducer setDeliveryDelay(long deliveryDelay); @Override int getDeliveryMode(); @Override JMSProducer setDeliveryMode(int deliveryMode); @Override boolean getDisableMessageID(); @Override JMSProducer setDisableMessageID(boolean disableMessageId); @Override boolean getDisableMessageTimestamp(); @Override JMSProducer setDisableMessageTimestamp(boolean disableTimestamp); @Override int getPriority(); @Override JMSProducer setPriority(int priority); @Override long getTimeToLive(); @Override JMSProducer setTimeToLive(long timeToLive); MessageProducer getMessageProducer(); }### Answer:
@Test public void testPropertyExists() { JMSProducer producer = context.createProducer(); producer.setProperty("Property_1", "1"); producer.setProperty("Property_2", "2"); producer.setProperty("Property_3", "3"); assertEquals(3, producer.getPropertyNames().size()); assertTrue(producer.propertyExists("Property_1")); assertTrue(producer.propertyExists("Property_2")); assertTrue(producer.propertyExists("Property_3")); assertFalse(producer.propertyExists("Property_4")); } |
### Question:
JmsPoolSession implements Session, TopicSession, QueueSession, XASession, AutoCloseable { @Override public TopicSubscriber createSubscriber(Topic topic) throws JMSException { return addTopicSubscriber(((TopicSession) getInternalSession()).createSubscriber(topic)); } JmsPoolSession(PooledSessionKey key, PooledSessionHolder sessionHolder, KeyedObjectPool<PooledSessionKey, PooledSessionHolder> sessionPool, boolean transactional); @Override void close(); @Override TemporaryQueue createTemporaryQueue(); @Override TemporaryTopic createTemporaryTopic(); @Override Queue createQueue(String s); @Override Topic createTopic(String s); @Override BytesMessage createBytesMessage(); @Override MapMessage createMapMessage(); @Override Message createMessage(); @Override ObjectMessage createObjectMessage(); @Override ObjectMessage createObjectMessage(Serializable serializable); @Override StreamMessage createStreamMessage(); @Override TextMessage createTextMessage(); @Override TextMessage createTextMessage(String s); @Override void unsubscribe(String s); @Override int getAcknowledgeMode(); @Override boolean getTransacted(); @Override void recover(); @Override void commit(); @Override void rollback(); @Override XAResource getXAResource(); @Override Session getSession(); @Override MessageListener getMessageListener(); @Override void setMessageListener(MessageListener messageListener); @Override void run(); @Override QueueBrowser createBrowser(Queue queue); @Override QueueBrowser createBrowser(Queue queue, String selector); @Override MessageConsumer createConsumer(Destination destination); @Override MessageConsumer createConsumer(Destination destination, String selector); @Override MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal); @Override TopicSubscriber createDurableSubscriber(Topic topic, String selector); @Override TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal); @Override TopicSubscriber createSubscriber(Topic topic); @Override TopicSubscriber createSubscriber(Topic topic, String selector, boolean local); @Override QueueReceiver createReceiver(Queue queue); @Override QueueReceiver createReceiver(Queue queue, String selector); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector); @Override MessageConsumer createDurableConsumer(Topic topic, String name); @Override MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector); @Override MessageProducer createProducer(Destination destination); @Override QueueSender createSender(Queue queue); @Override TopicPublisher createPublisher(Topic topic); void addSessionEventListener(JmsPoolSessionEventListener listener); Session getInternalSession(); void setIsXa(boolean isXa); boolean isIgnoreClose(); void setIgnoreClose(boolean ignoreClose); @Override String toString(); }### Answer:
@Test(timeout = 60000) public void testCreateSubscriber() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); JmsPoolSession session = (JmsPoolSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(getTestName()); assertNotNull(session.createSubscriber(topic)); session.close(); try { session.createSubscriber(topic); fail("Should not be able to createSubscriber when closed"); } catch (JMSException ex) {} } |
### Question:
JmsPoolSession implements Session, TopicSession, QueueSession, XASession, AutoCloseable { @Override public QueueReceiver createReceiver(Queue queue) throws JMSException { return addQueueReceiver(((QueueSession) getInternalSession()).createReceiver(queue)); } JmsPoolSession(PooledSessionKey key, PooledSessionHolder sessionHolder, KeyedObjectPool<PooledSessionKey, PooledSessionHolder> sessionPool, boolean transactional); @Override void close(); @Override TemporaryQueue createTemporaryQueue(); @Override TemporaryTopic createTemporaryTopic(); @Override Queue createQueue(String s); @Override Topic createTopic(String s); @Override BytesMessage createBytesMessage(); @Override MapMessage createMapMessage(); @Override Message createMessage(); @Override ObjectMessage createObjectMessage(); @Override ObjectMessage createObjectMessage(Serializable serializable); @Override StreamMessage createStreamMessage(); @Override TextMessage createTextMessage(); @Override TextMessage createTextMessage(String s); @Override void unsubscribe(String s); @Override int getAcknowledgeMode(); @Override boolean getTransacted(); @Override void recover(); @Override void commit(); @Override void rollback(); @Override XAResource getXAResource(); @Override Session getSession(); @Override MessageListener getMessageListener(); @Override void setMessageListener(MessageListener messageListener); @Override void run(); @Override QueueBrowser createBrowser(Queue queue); @Override QueueBrowser createBrowser(Queue queue, String selector); @Override MessageConsumer createConsumer(Destination destination); @Override MessageConsumer createConsumer(Destination destination, String selector); @Override MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal); @Override TopicSubscriber createDurableSubscriber(Topic topic, String selector); @Override TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal); @Override TopicSubscriber createSubscriber(Topic topic); @Override TopicSubscriber createSubscriber(Topic topic, String selector, boolean local); @Override QueueReceiver createReceiver(Queue queue); @Override QueueReceiver createReceiver(Queue queue, String selector); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector); @Override MessageConsumer createDurableConsumer(Topic topic, String name); @Override MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector); @Override MessageProducer createProducer(Destination destination); @Override QueueSender createSender(Queue queue); @Override TopicPublisher createPublisher(Topic topic); void addSessionEventListener(JmsPoolSessionEventListener listener); Session getInternalSession(); void setIsXa(boolean isXa); boolean isIgnoreClose(); void setIgnoreClose(boolean ignoreClose); @Override String toString(); }### Answer:
@Test(timeout = 60000) public void testCreateReceiver() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); JmsPoolSession session = (JmsPoolSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(getTestName()); assertNotNull(session.createReceiver(queue)); session.close(); try { session.createReceiver(queue); fail("Should not be able to createReceiver when closed"); } catch (JMSException ex) {} } |
### Question:
JmsPoolSession implements Session, TopicSession, QueueSession, XASession, AutoCloseable { @Override public void setMessageListener(MessageListener messageListener) throws JMSException { getInternalSession().setMessageListener(messageListener); } JmsPoolSession(PooledSessionKey key, PooledSessionHolder sessionHolder, KeyedObjectPool<PooledSessionKey, PooledSessionHolder> sessionPool, boolean transactional); @Override void close(); @Override TemporaryQueue createTemporaryQueue(); @Override TemporaryTopic createTemporaryTopic(); @Override Queue createQueue(String s); @Override Topic createTopic(String s); @Override BytesMessage createBytesMessage(); @Override MapMessage createMapMessage(); @Override Message createMessage(); @Override ObjectMessage createObjectMessage(); @Override ObjectMessage createObjectMessage(Serializable serializable); @Override StreamMessage createStreamMessage(); @Override TextMessage createTextMessage(); @Override TextMessage createTextMessage(String s); @Override void unsubscribe(String s); @Override int getAcknowledgeMode(); @Override boolean getTransacted(); @Override void recover(); @Override void commit(); @Override void rollback(); @Override XAResource getXAResource(); @Override Session getSession(); @Override MessageListener getMessageListener(); @Override void setMessageListener(MessageListener messageListener); @Override void run(); @Override QueueBrowser createBrowser(Queue queue); @Override QueueBrowser createBrowser(Queue queue, String selector); @Override MessageConsumer createConsumer(Destination destination); @Override MessageConsumer createConsumer(Destination destination, String selector); @Override MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal); @Override TopicSubscriber createDurableSubscriber(Topic topic, String selector); @Override TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal); @Override TopicSubscriber createSubscriber(Topic topic); @Override TopicSubscriber createSubscriber(Topic topic, String selector, boolean local); @Override QueueReceiver createReceiver(Queue queue); @Override QueueReceiver createReceiver(Queue queue, String selector); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName); @Override MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector); @Override MessageConsumer createDurableConsumer(Topic topic, String name); @Override MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name); @Override MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector); @Override MessageProducer createProducer(Destination destination); @Override QueueSender createSender(Queue queue); @Override TopicPublisher createPublisher(Topic topic); void addSessionEventListener(JmsPoolSessionEventListener listener); Session getInternalSession(); void setIsXa(boolean isXa); boolean isIgnoreClose(); void setIgnoreClose(boolean ignoreClose); @Override String toString(); }### Answer:
@Test(timeout = 60000) public void testSetMessageListener() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); JmsPoolSession session = (JmsPoolSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageListener listener = new MessageListener() { @Override public void onMessage(Message message) { } }; session.setMessageListener(listener); assertSame(listener, session.getMessageListener()); MockJMSSession mockSession = (MockJMSSession) session.getInternalSession(); assertSame(listener, mockSession.getMessageListener()); session.close(); try { session.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { } }); fail("Should not be able to setMessageListener when closed"); } catch (JMSException ex) {} try { session.getMessageListener(); fail("Should not be able to setMessageListener when closed"); } catch (JMSException ex) {} } |
### Question:
JmsPoolJMSProducer implements JMSProducer { @Override public String getStringProperty(String name) { try { return convertPropertyTo(name, messageProperties.get(name), String.class); } catch (JMSException jmse) { throw JMSExceptionSupport.createRuntimeException(jmse); } } JmsPoolJMSProducer(JmsPoolSession session, JmsPoolMessageProducer producer); @Override String toString(); @Override JMSProducer send(Destination destination, Message message); @Override JMSProducer send(Destination destination, byte[] body); @Override JMSProducer send(Destination destination, Map<String, Object> body); @Override JMSProducer send(Destination destination, Serializable body); @Override JMSProducer send(Destination destination, String body); @Override JMSProducer clearProperties(); @Override Set<String> getPropertyNames(); @Override boolean propertyExists(String name); @Override boolean getBooleanProperty(String name); @Override byte getByteProperty(String name); @Override double getDoubleProperty(String name); @Override float getFloatProperty(String name); @Override int getIntProperty(String name); @Override long getLongProperty(String name); @Override Object getObjectProperty(String name); @Override short getShortProperty(String name); @Override String getStringProperty(String name); @Override JMSProducer setProperty(String name, boolean value); @Override JMSProducer setProperty(String name, byte value); @Override JMSProducer setProperty(String name, double value); @Override JMSProducer setProperty(String name, float value); @Override JMSProducer setProperty(String name, int value); @Override JMSProducer setProperty(String name, long value); @Override JMSProducer setProperty(String name, Object value); @Override JMSProducer setProperty(String name, short value); @Override JMSProducer setProperty(String name, String value); @Override String getJMSCorrelationID(); @Override JMSProducer setJMSCorrelationID(String correlationId); @Override byte[] getJMSCorrelationIDAsBytes(); @Override JMSProducer setJMSCorrelationIDAsBytes(byte[] correlationIdBytes); @Override Destination getJMSReplyTo(); @Override JMSProducer setJMSReplyTo(Destination replyTo); @Override String getJMSType(); @Override JMSProducer setJMSType(String type); @Override CompletionListener getAsync(); @Override JMSProducer setAsync(CompletionListener completionListener); @Override long getDeliveryDelay(); @Override JMSProducer setDeliveryDelay(long deliveryDelay); @Override int getDeliveryMode(); @Override JMSProducer setDeliveryMode(int deliveryMode); @Override boolean getDisableMessageID(); @Override JMSProducer setDisableMessageID(boolean disableMessageId); @Override boolean getDisableMessageTimestamp(); @Override JMSProducer setDisableMessageTimestamp(boolean disableTimestamp); @Override int getPriority(); @Override JMSProducer setPriority(int priority); @Override long getTimeToLive(); @Override JMSProducer setTimeToLive(long timeToLive); MessageProducer getMessageProducer(); }### Answer:
@Test public void testGetStringProperty() { JMSProducer producer = context.createProducer(); producer.setProperty(STRING_PROPERTY_NAME, STRING_PROPERTY_VALUE); assertEquals(STRING_PROPERTY_VALUE, producer.getStringProperty(STRING_PROPERTY_NAME)); } |
### Question:
JmsPoolJMSProducer implements JMSProducer { @Override public byte getByteProperty(String name) { try { return convertPropertyTo(name, messageProperties.get(name), Byte.class); } catch (JMSException jmse) { throw JMSExceptionSupport.createRuntimeException(jmse); } } JmsPoolJMSProducer(JmsPoolSession session, JmsPoolMessageProducer producer); @Override String toString(); @Override JMSProducer send(Destination destination, Message message); @Override JMSProducer send(Destination destination, byte[] body); @Override JMSProducer send(Destination destination, Map<String, Object> body); @Override JMSProducer send(Destination destination, Serializable body); @Override JMSProducer send(Destination destination, String body); @Override JMSProducer clearProperties(); @Override Set<String> getPropertyNames(); @Override boolean propertyExists(String name); @Override boolean getBooleanProperty(String name); @Override byte getByteProperty(String name); @Override double getDoubleProperty(String name); @Override float getFloatProperty(String name); @Override int getIntProperty(String name); @Override long getLongProperty(String name); @Override Object getObjectProperty(String name); @Override short getShortProperty(String name); @Override String getStringProperty(String name); @Override JMSProducer setProperty(String name, boolean value); @Override JMSProducer setProperty(String name, byte value); @Override JMSProducer setProperty(String name, double value); @Override JMSProducer setProperty(String name, float value); @Override JMSProducer setProperty(String name, int value); @Override JMSProducer setProperty(String name, long value); @Override JMSProducer setProperty(String name, Object value); @Override JMSProducer setProperty(String name, short value); @Override JMSProducer setProperty(String name, String value); @Override String getJMSCorrelationID(); @Override JMSProducer setJMSCorrelationID(String correlationId); @Override byte[] getJMSCorrelationIDAsBytes(); @Override JMSProducer setJMSCorrelationIDAsBytes(byte[] correlationIdBytes); @Override Destination getJMSReplyTo(); @Override JMSProducer setJMSReplyTo(Destination replyTo); @Override String getJMSType(); @Override JMSProducer setJMSType(String type); @Override CompletionListener getAsync(); @Override JMSProducer setAsync(CompletionListener completionListener); @Override long getDeliveryDelay(); @Override JMSProducer setDeliveryDelay(long deliveryDelay); @Override int getDeliveryMode(); @Override JMSProducer setDeliveryMode(int deliveryMode); @Override boolean getDisableMessageID(); @Override JMSProducer setDisableMessageID(boolean disableMessageId); @Override boolean getDisableMessageTimestamp(); @Override JMSProducer setDisableMessageTimestamp(boolean disableTimestamp); @Override int getPriority(); @Override JMSProducer setPriority(int priority); @Override long getTimeToLive(); @Override JMSProducer setTimeToLive(long timeToLive); MessageProducer getMessageProducer(); }### Answer:
@Test public void testGetByteProperty() { JMSProducer producer = context.createProducer(); producer.setProperty(BYTE_PROPERTY_NAME, BYTE_PROPERTY_VALUE); assertEquals(BYTE_PROPERTY_VALUE, producer.getByteProperty(BYTE_PROPERTY_NAME)); } |
### Question:
JmsPoolJMSProducer implements JMSProducer { @Override public boolean getBooleanProperty(String name) { try { return convertPropertyTo(name, messageProperties.get(name), Boolean.class); } catch (JMSException jmse) { throw JMSExceptionSupport.createRuntimeException(jmse); } } JmsPoolJMSProducer(JmsPoolSession session, JmsPoolMessageProducer producer); @Override String toString(); @Override JMSProducer send(Destination destination, Message message); @Override JMSProducer send(Destination destination, byte[] body); @Override JMSProducer send(Destination destination, Map<String, Object> body); @Override JMSProducer send(Destination destination, Serializable body); @Override JMSProducer send(Destination destination, String body); @Override JMSProducer clearProperties(); @Override Set<String> getPropertyNames(); @Override boolean propertyExists(String name); @Override boolean getBooleanProperty(String name); @Override byte getByteProperty(String name); @Override double getDoubleProperty(String name); @Override float getFloatProperty(String name); @Override int getIntProperty(String name); @Override long getLongProperty(String name); @Override Object getObjectProperty(String name); @Override short getShortProperty(String name); @Override String getStringProperty(String name); @Override JMSProducer setProperty(String name, boolean value); @Override JMSProducer setProperty(String name, byte value); @Override JMSProducer setProperty(String name, double value); @Override JMSProducer setProperty(String name, float value); @Override JMSProducer setProperty(String name, int value); @Override JMSProducer setProperty(String name, long value); @Override JMSProducer setProperty(String name, Object value); @Override JMSProducer setProperty(String name, short value); @Override JMSProducer setProperty(String name, String value); @Override String getJMSCorrelationID(); @Override JMSProducer setJMSCorrelationID(String correlationId); @Override byte[] getJMSCorrelationIDAsBytes(); @Override JMSProducer setJMSCorrelationIDAsBytes(byte[] correlationIdBytes); @Override Destination getJMSReplyTo(); @Override JMSProducer setJMSReplyTo(Destination replyTo); @Override String getJMSType(); @Override JMSProducer setJMSType(String type); @Override CompletionListener getAsync(); @Override JMSProducer setAsync(CompletionListener completionListener); @Override long getDeliveryDelay(); @Override JMSProducer setDeliveryDelay(long deliveryDelay); @Override int getDeliveryMode(); @Override JMSProducer setDeliveryMode(int deliveryMode); @Override boolean getDisableMessageID(); @Override JMSProducer setDisableMessageID(boolean disableMessageId); @Override boolean getDisableMessageTimestamp(); @Override JMSProducer setDisableMessageTimestamp(boolean disableTimestamp); @Override int getPriority(); @Override JMSProducer setPriority(int priority); @Override long getTimeToLive(); @Override JMSProducer setTimeToLive(long timeToLive); MessageProducer getMessageProducer(); }### Answer:
@Test public void testGetBooleanProperty() { JMSProducer producer = context.createProducer(); producer.setProperty(BOOLEAN_PROPERTY_NAME, BOOLEAN_PROPERTY_VALUE); assertEquals(BOOLEAN_PROPERTY_VALUE, producer.getBooleanProperty(BOOLEAN_PROPERTY_NAME)); } |
### Question:
JmsPoolJMSProducer implements JMSProducer { @Override public short getShortProperty(String name) { try { return convertPropertyTo(name, messageProperties.get(name), Short.class); } catch (JMSException jmse) { throw JMSExceptionSupport.createRuntimeException(jmse); } } JmsPoolJMSProducer(JmsPoolSession session, JmsPoolMessageProducer producer); @Override String toString(); @Override JMSProducer send(Destination destination, Message message); @Override JMSProducer send(Destination destination, byte[] body); @Override JMSProducer send(Destination destination, Map<String, Object> body); @Override JMSProducer send(Destination destination, Serializable body); @Override JMSProducer send(Destination destination, String body); @Override JMSProducer clearProperties(); @Override Set<String> getPropertyNames(); @Override boolean propertyExists(String name); @Override boolean getBooleanProperty(String name); @Override byte getByteProperty(String name); @Override double getDoubleProperty(String name); @Override float getFloatProperty(String name); @Override int getIntProperty(String name); @Override long getLongProperty(String name); @Override Object getObjectProperty(String name); @Override short getShortProperty(String name); @Override String getStringProperty(String name); @Override JMSProducer setProperty(String name, boolean value); @Override JMSProducer setProperty(String name, byte value); @Override JMSProducer setProperty(String name, double value); @Override JMSProducer setProperty(String name, float value); @Override JMSProducer setProperty(String name, int value); @Override JMSProducer setProperty(String name, long value); @Override JMSProducer setProperty(String name, Object value); @Override JMSProducer setProperty(String name, short value); @Override JMSProducer setProperty(String name, String value); @Override String getJMSCorrelationID(); @Override JMSProducer setJMSCorrelationID(String correlationId); @Override byte[] getJMSCorrelationIDAsBytes(); @Override JMSProducer setJMSCorrelationIDAsBytes(byte[] correlationIdBytes); @Override Destination getJMSReplyTo(); @Override JMSProducer setJMSReplyTo(Destination replyTo); @Override String getJMSType(); @Override JMSProducer setJMSType(String type); @Override CompletionListener getAsync(); @Override JMSProducer setAsync(CompletionListener completionListener); @Override long getDeliveryDelay(); @Override JMSProducer setDeliveryDelay(long deliveryDelay); @Override int getDeliveryMode(); @Override JMSProducer setDeliveryMode(int deliveryMode); @Override boolean getDisableMessageID(); @Override JMSProducer setDisableMessageID(boolean disableMessageId); @Override boolean getDisableMessageTimestamp(); @Override JMSProducer setDisableMessageTimestamp(boolean disableTimestamp); @Override int getPriority(); @Override JMSProducer setPriority(int priority); @Override long getTimeToLive(); @Override JMSProducer setTimeToLive(long timeToLive); MessageProducer getMessageProducer(); }### Answer:
@Test public void testGetShortProperty() { JMSProducer producer = context.createProducer(); producer.setProperty(SHORT_PROPERTY_NAME, SHORT_PROPERTY_VALUE); assertEquals(SHORT_PROPERTY_VALUE, producer.getShortProperty(SHORT_PROPERTY_NAME)); } |
### Question:
JMSExceptionSupport { public static JMSException create(String message, Throwable cause) { if (cause instanceof JMSException) { return (JMSException) cause; } if (cause.getCause() instanceof JMSException) { return (JMSException) cause.getCause(); } if (message == null || message.isEmpty()) { message = cause.getMessage(); if (message == null || message.isEmpty()) { message = cause.toString(); } } JMSException exception = new JMSException(message); if (cause instanceof Exception) { exception.setLinkedException((Exception) cause); } exception.initCause(cause); return exception; } static JMSException create(String message, Throwable cause); static JMSException create(Throwable cause); static MessageEOFException createMessageEOFException(Throwable cause); static MessageFormatException createMessageFormatException(Throwable cause); static JMSRuntimeException createRuntimeException(Exception exception); }### Answer:
@Test public void testCreateAssignsLinkedException() { JMSException result = JMSExceptionSupport.create(ERROR_MESSAGE, new IOException(CAUSE_MESSAGE)); assertNotNull(result.getLinkedException()); }
@Test public void testCreateUsesCauseIfJMSExceptionPresent() { IOException ioe = new IOException("Ignore me", new JMSSecurityException("error")); JMSException result = JMSExceptionSupport.create(ERROR_MESSAGE, ioe); assertNotNull(result); assertTrue(result instanceof JMSSecurityException); }
@Test public void testCreateDoesNotFillLinkedExceptionWhenGivenNonExceptionThrowable() { JMSException result = JMSExceptionSupport.create(ERROR_MESSAGE, new AssertionError(CAUSE_MESSAGE)); assertNull(result.getLinkedException()); }
@Test public void testCreateFillsMessageFromMessageParam() { JMSException result = JMSExceptionSupport.create(ERROR_MESSAGE, new IOException(CAUSE_MESSAGE)); assertEquals(ERROR_MESSAGE, result.getMessage()); }
@Test public void testCreateFillsMessageFromMCauseessageParamMessage() { JMSException result = JMSExceptionSupport.create(new IOException(CAUSE_MESSAGE)); assertEquals(CAUSE_MESSAGE, result.getMessage()); }
@Test public void testCreateFillsMessageFromMCauseessageParamToString() { JMSException result = JMSExceptionSupport.create(NO_MESSAGE_CAUSE); assertEquals(NO_MESSAGE_CAUSE.toString(), result.getMessage()); }
@Test public void testCreateFillsMessageFromMCauseessageParamToStringWhenMessageIsEmpty() { JMSException result = JMSExceptionSupport.create(EMPTY_MESSAGE_CAUSE); assertEquals(EMPTY_MESSAGE_CAUSE.toString(), result.getMessage()); }
@Test public void testCreateFillsMessageFromCauseMessageParamWhenErrorMessageIsNull() { JMSException result = JMSExceptionSupport.create(null, new IOException(CAUSE_MESSAGE)); assertEquals(CAUSE_MESSAGE, result.getMessage()); }
@Test public void testCreateFillsMessageFromCauseMessageParamWhenErrorMessageIsEmpty() { JMSException result = JMSExceptionSupport.create("", new IOException(CAUSE_MESSAGE)); assertEquals(CAUSE_MESSAGE, result.getMessage()); } |
### Question:
JmsPoolJMSProducer implements JMSProducer { @Override public long getLongProperty(String name) { try { return convertPropertyTo(name, messageProperties.get(name), Long.class); } catch (JMSException jmse) { throw JMSExceptionSupport.createRuntimeException(jmse); } } JmsPoolJMSProducer(JmsPoolSession session, JmsPoolMessageProducer producer); @Override String toString(); @Override JMSProducer send(Destination destination, Message message); @Override JMSProducer send(Destination destination, byte[] body); @Override JMSProducer send(Destination destination, Map<String, Object> body); @Override JMSProducer send(Destination destination, Serializable body); @Override JMSProducer send(Destination destination, String body); @Override JMSProducer clearProperties(); @Override Set<String> getPropertyNames(); @Override boolean propertyExists(String name); @Override boolean getBooleanProperty(String name); @Override byte getByteProperty(String name); @Override double getDoubleProperty(String name); @Override float getFloatProperty(String name); @Override int getIntProperty(String name); @Override long getLongProperty(String name); @Override Object getObjectProperty(String name); @Override short getShortProperty(String name); @Override String getStringProperty(String name); @Override JMSProducer setProperty(String name, boolean value); @Override JMSProducer setProperty(String name, byte value); @Override JMSProducer setProperty(String name, double value); @Override JMSProducer setProperty(String name, float value); @Override JMSProducer setProperty(String name, int value); @Override JMSProducer setProperty(String name, long value); @Override JMSProducer setProperty(String name, Object value); @Override JMSProducer setProperty(String name, short value); @Override JMSProducer setProperty(String name, String value); @Override String getJMSCorrelationID(); @Override JMSProducer setJMSCorrelationID(String correlationId); @Override byte[] getJMSCorrelationIDAsBytes(); @Override JMSProducer setJMSCorrelationIDAsBytes(byte[] correlationIdBytes); @Override Destination getJMSReplyTo(); @Override JMSProducer setJMSReplyTo(Destination replyTo); @Override String getJMSType(); @Override JMSProducer setJMSType(String type); @Override CompletionListener getAsync(); @Override JMSProducer setAsync(CompletionListener completionListener); @Override long getDeliveryDelay(); @Override JMSProducer setDeliveryDelay(long deliveryDelay); @Override int getDeliveryMode(); @Override JMSProducer setDeliveryMode(int deliveryMode); @Override boolean getDisableMessageID(); @Override JMSProducer setDisableMessageID(boolean disableMessageId); @Override boolean getDisableMessageTimestamp(); @Override JMSProducer setDisableMessageTimestamp(boolean disableTimestamp); @Override int getPriority(); @Override JMSProducer setPriority(int priority); @Override long getTimeToLive(); @Override JMSProducer setTimeToLive(long timeToLive); MessageProducer getMessageProducer(); }### Answer:
@Test public void testGetLongProperty() { JMSProducer producer = context.createProducer(); producer.setProperty(LONG_PROPERTY_NAME, LONG_PROPERTY_VALUE); assertEquals(LONG_PROPERTY_VALUE, producer.getLongProperty(LONG_PROPERTY_NAME)); } |
### Question:
DigestUtils { public static byte[] digest(MessageDigest digest, byte[] data) { return digest.digest(data); } static byte[] digest(MessageDigest digest, byte[] data); static MessageDigest updateDigest(MessageDigest messageDigest, byte[] valueToDigest); static byte[] digest(MessageDigest digest, InputStream data); static String getHexString(byte[] data); static byte[] fromHexString(String hexString); static String digest(MessageDigestAlgorithms algorithms, String data); }### Answer:
@Test public void testMd5() { String source = "123456"; PerformanceMonitor.start("DigestUtilsTest"); for (int i = 0; i < 5; i++) { for (int j = 0; j < 10000; j++) { Assert.assertEquals("e10adc3949ba59abbe56e057f20f883e", DigestUtils.digest(MessageDigestAlgorithms.MD5, source)); } PerformanceMonitor.mark("md5 Test"); } for (int i = 0; i < 5; i++) { for (int j = 0; j < 10000; j++) { Assert.assertEquals("7c4a8d09ca3762af61e59520943dc26494f8941b", DigestUtils.digest(MessageDigestAlgorithms.SHA_1, source)); } PerformanceMonitor.mark("sha1 Test"); } PerformanceMonitor.stop(); PerformanceMonitor.summarize(new AdvancedStopWatchSummary(true)); PerformanceMonitor.remove(); } |
### Question:
NumberUtils { public static boolean isPositiveNumber(Number number) { if (number == null) return false; return org.apache.commons.lang3.math.NumberUtils.isDigits(number.toString()) && number.byteValue() > 0; } static int toInt(String str); static long toLong(String str); static float toFloat(String str); static float toFloat(String str, float defaultValue); static double toDouble(String str); static double toDouble(String str, double defaultValue); static Integer createInteger(String str); static Long createLong(String str); static BigInteger createBigInteger(String str); static BigDecimal createBigDecimal(String str); static Float createFloat(String str); static Double createDouble(String str); static boolean isNumber(String str); static boolean isDigits(String str); static boolean isPositiveNumber(Number number); static long min(long[] array); static int min(int[] array); static short min(short[] array); static byte min(byte[] array); static double min(double[] array); static float min(float[] array); static long max(long[] array); static int max(int[] array); static short max(short[] array); static byte max(byte[] array); static double max(double[] array); static float max(float[] array); }### Answer:
@Test public void testIsPositiveNumber() { Assert.assertFalse(NumberUtils.isPositiveNumber(-1L)); Assert.assertFalse(NumberUtils.isPositiveNumber(-10000000000000000L)); Assert.assertFalse(NumberUtils.isPositiveNumber(0)); Assert.assertFalse(NumberUtils.isPositiveNumber(1.6)); Assert.assertTrue(NumberUtils.isPositiveNumber(1)); } |
### Question:
BeanUtils { public static void copyProperties(Object source, Object target) throws BeansException { org.springframework.beans.BeanUtils.copyProperties(source, target); } static void copyProperties(Object source, Object target); static void copyProperties(Object source, String[] copyProperties, Object target); static void copyProperties(Map<String, Object> source, String[] copyProperties, Object target); static void copyProperties(Object source, String[] copyProperties, Map<String, Object> target); static void copyProperties(Object source, Object target, String... ignoreProperties); static void copyProperties(Map<String, Object> source, Object target, String... ignoreProperties); static void copyProperties(Object source, Map<String, Object> target, String... ignoreProperties); static Method findDeclaredMethod(Class<?> clazz, String methodName, Class<?>... paramTypes); static Method findMethod(Class<?> clazz, String methodName, Class<?>... paramTypes); static Method findStaticMethod(Class<?> clazz, String methodName, Class<?>... paramTypes); static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz); static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String propertyName); static PropertyDescriptor findPropertyForMethod(Method method); static Class<?> findPropertyType(String propertyName, Class<?>[] beanClasses); static MethodParameter getWriteMethodParameter(PropertyDescriptor pd); static PropertyEditor findEditorByConvention(Class<?> targetType); static T instantiate(Class<T> clazz); static T instantiateClass(Class<T> clazz); static T instantiateClass(Class<?> clazz, Class<T> assignableTo); static T instantiateClass(Constructor<T> ctor, Object... args); }### Answer:
@Test public void testBeanToBean() { Person person = new Person("Daniel Li", 24); PerformanceMonitor.start("BeanUtilsTest"); for (int i = 0; i < 5; i++) { for (int j = 0; j < 50000; j++) { PersonDto personDto = new PersonDto(); BeanUtils.copyProperties(person, personDto); } PerformanceMonitor.mark("BeanUtils" + i); } BeanCopier copier = BeanCopier.create(Person.class, PersonDto.class, false); for (int i = 0; i < 5; i++) { for (int j = 0; j < 50000; j++) { PersonDto personDto = new PersonDto(); copier.copy(person, personDto, null); } PerformanceMonitor.mark("BeanCopier" + i); } BeanCopy beanCopy = BeanCopy.create(Person.class, PersonDto.class); for (int i = 0; i < 5; i++) { for (int j = 0; j < 50000; j++) { PersonDto personDto = new PersonDto(); beanCopy.copy(person, personDto); } PerformanceMonitor.mark("BeanCopy" + i); } PerformanceMonitor.stop(); PerformanceMonitor.summarize(new AdvancedStopWatchSummary(true)); PerformanceMonitor.remove(); }
@Test public void testBeanToMapping() { Person person = new Person("Daniel Li", 24); PerformanceMonitor.start("BeanUtilsTest"); for (int i = 0; i < 5; i++) { for (int j = 0; j < 50000; j++) { Map<String, Object> map = new HashMap<>(); BeanUtils.copyProperties(person, map); } PerformanceMonitor.mark("BeanUtils" + i); } BeanMap beanMap = BeanMap.create(Person.class); for (int i = 0; i < 5; i++) { for (int j = 0; j < 50000; j++) { beanMap.newInstance(person); } PerformanceMonitor.mark("cglibBeanMap" + i); } com.alibaba.tamper.BeanMap tamperBeanMap = com.alibaba.tamper.BeanMap.create(Person.class); for (int i = 0; i < 5; i++) { for (int j = 0; j < 50000; j++) { tamperBeanMap.describe(person); } PerformanceMonitor.mark("tamperBeanMap" + i); } PerformanceMonitor.stop(); PerformanceMonitor.summarize(new AdvancedStopWatchSummary(true)); PerformanceMonitor.remove(); } |
### Question:
HashCodeBuilderUtils { public static int reflectionHashCode(Object object) { return reflectionHashCode(17, 37, object); } static int reflectionHashCode(Object object); static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, T object); }### Answer:
@Test public void test1() { DateTime date = new DateTime(); Employee employee1 = new Employee("Daniel Li", 20, date); Employee employee2 = new Employee("Daniel Li", 20, date); Manager manager1 = new Manager("Daniel Li", 20, date, 0); Manager manager2 = new Manager("Daniel Li", 20, date, 0) { }; PerformanceMonitor.start("HashCodeBuilderUtilsTest"); LOGGER.info(String.valueOf(HashCodeBuilder.reflectionHashCode(employee1))); PerformanceMonitor.mark("HashCodeBuilder.reflectionHashCode(employee1)"); LOGGER.info(String.valueOf(HashCodeBuilderUtils.reflectionHashCode(employee1))); PerformanceMonitor.mark("HashCodeBuilderUtils.reflectionHashCode(employee1)"); LOGGER.info(String.valueOf(HashCodeBuilderUtils.reflectionHashCode(employee2))); PerformanceMonitor.mark("HashCodeBuilderUtils.reflectionHashCode(employee2)"); LOGGER.info(String.valueOf(HashCodeBuilder.reflectionHashCode(employee2))); PerformanceMonitor.mark("HashCodeBuilder.reflectionHashCode(employee2)"); LOGGER.info(String.valueOf(HashCodeBuilder.reflectionHashCode(manager1))); PerformanceMonitor.mark("HashCodeBuilder.reflectionHashCode(manager1)"); LOGGER.info(String.valueOf(HashCodeBuilderUtils.reflectionHashCode(manager1))); PerformanceMonitor.mark("HashCodeBuilderUtils.reflectionHashCode(manager1)"); LOGGER.info(String.valueOf(HashCodeBuilder.reflectionHashCode(manager2))); PerformanceMonitor.mark("HashCodeBuilder.reflectionHashCode(manager2)"); LOGGER.info(String.valueOf(HashCodeBuilderUtils.reflectionHashCode(manager2))); PerformanceMonitor.mark("HashCodeBuilderUtils.reflectionHashCode(manager2)"); PerformanceMonitor.stop(); PerformanceMonitor.summarize(new AdvancedStopWatchSummary(false)); PerformanceMonitor.remove(); } |
### Question:
ToStringBuilderUtils { public static String reflectionToString(Object object) { ToStringBuilder builder = new ToStringBuilder(object); Class<?> clazz = object.getClass(); reflectionAppend(object, clazz, builder); while (clazz.getSuperclass() != null) { clazz = clazz.getSuperclass(); reflectionAppend(object, clazz, builder); } return builder.toString(); } static String reflectionToString(Object object); }### Answer:
@Test public void test1() { DateTime date = new DateTime(); Employee employee1 = new Employee("Daniel Li", 20, date); Employee employee2 = new Employee("Daniel Li", 20, date); Manager manager1 = new Manager("Daniel Li", 20, date, 0); Manager manager2 = new Manager("Daniel Li", 20, date, 0) { }; PerformanceMonitor.start("ToStringBuilderUtilsTest"); LOGGER.info(String.valueOf(ToStringBuilder.reflectionToString(employee1))); PerformanceMonitor.mark("ToStringBuilder.reflectionToString(employee1)"); LOGGER.info(String.valueOf(ToStringBuilderUtils.reflectionToString(employee1))); PerformanceMonitor.mark("ToStringBuilderUtils.reflectionToString(employee1)"); LOGGER.info(String.valueOf(ToStringBuilder.reflectionToString(employee2))); PerformanceMonitor.mark("ToStringBuilder.reflectionToString(employee2)"); LOGGER.info(String.valueOf(ToStringBuilderUtils.reflectionToString(employee2))); PerformanceMonitor.mark("ToStringBuilderUtils.reflectionToString(employee2)"); LOGGER.info(String.valueOf(ToStringBuilder.reflectionToString(manager1))); PerformanceMonitor.mark("ToStringBuilder.reflectionToString(manager1)"); LOGGER.info(String.valueOf(ToStringBuilderUtils.reflectionToString(manager1))); PerformanceMonitor.mark("ToStringBuilderUtils.reflectionToString(manager1)"); LOGGER.info(String.valueOf(ToStringBuilder.reflectionToString(manager2))); PerformanceMonitor.mark("ToStringBuilder.reflectionToString(manager2)"); LOGGER.info(String.valueOf(ToStringBuilderUtils.reflectionToString(manager2))); PerformanceMonitor.mark("ToStringBuilderUtils.reflectionToString(manager2)"); PerformanceMonitor.stop(); PerformanceMonitor.summarize(new AdvancedStopWatchSummary(false)); PerformanceMonitor.remove(); } |
### Question:
Message { public T getContent() { return content; } Message(MessageType type, T content); MessageType getType(); T getContent(); }### Answer:
@Test public void test() { ApplicationContext applicationContext = BeanFactoryContext.currentApplicationContext(); LOGGER.info(ApplicationContextUtils.getMessage(applicationContext, Locale.CHINA, "helloWorld")); LOGGER.info(ApplicationContextUtils.getMessage(applicationContext, Locale.US, "helloWorld")); if (ApplicationContextUtils.getMessage(applicationContext, Locale.CHINA, "helloWorld1") == null) { LOGGER.info("helloWorld1 is not existsed"); } LOGGER.info(MessageUtils.success("helloWorld").getContent()); } |
### Question:
ReportExportRestApi { @NotNull public ExportExecutionDescriptor runExportExecution(@NotNull String executionId, @NotNull ExecutionRequestOptions executionOptions) throws IOException, HttpException { Utils.checkNotNull(executionId, "Execution id should not be null"); Utils.checkNotNull(executionOptions, "Execution options should not be null"); HttpUrl url = new PathResolver.Builder() .addPath("rest_v2") .addPath("reportExecutions") .addPath(executionId) .addPath("exports") .build() .resolve(mNetworkClient.getBaseUrl()); RequestBody jsonRequestBody = mNetworkClient.createJsonRequestBody(executionOptions); Request request = new Request.Builder() .addHeader("Accept", "application/json; charset=UTF-8") .post(jsonRequestBody) .url(url) .build(); com.squareup.okhttp.Response response = mNetworkClient.makeCall(request); return mNetworkClient.deserializeJson(response, ExportExecutionDescriptor.class); } ReportExportRestApi(NetworkClient networkClient); @NotNull ExportExecutionDescriptor runExportExecution(@NotNull String executionId,
@NotNull ExecutionRequestOptions executionOptions); @NotNull ExecutionStatus checkExportExecutionStatus(@NotNull String executionId,
@NotNull String exportId); @NotNull ExportOutputResource requestExportOutput(@NotNull String executionId,
@NotNull String exportId); @NotNull OutputResource requestExportAttachment(@NotNull String executionId,
@NotNull String exportId,
@NotNull String attachmentId); }### Answer:
@Test public void executionIdShouldNotBeNullForRunRequestExecution() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Execution id should not be null"); restApiUnderTest.runExportExecution(null, ExecutionRequestOptions.create()); }
@Test public void shouldRunExportExecution() throws Exception { MockResponse mockResponse = MockResponseFactory.create200(); mWebMockRule.enqueue(mockResponse); restApiUnderTest.runExportExecution(EXECUTION_ID, ExecutionRequestOptions.create()); RecordedRequest request = mWebMockRule.get().takeRequest(); assertThat(request, containsHeader("Accept", "application/json; charset=UTF-8")); assertThat(request, hasPath("/rest_v2/reportExecutions/f3a9805a-4089-4b53-b9e9-b54752f91586/exports")); assertThat(request, wasMethod("POST")); }
@Test public void runExportExecutionShouldThrowRestErrorOn500() throws Exception { mExpectedException.expect(HttpException.class); mWebMockRule.enqueue(MockResponseFactory.create500()); restApiUnderTest.runExportExecution("any_id", ExecutionRequestOptions.create()); }
@Test public void bodyShouldNotBeNullForRunRequestExecution() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Execution options should not be null"); restApiUnderTest.runExportExecution("any_id", null); } |
### Question:
RepositoryRestApi { @NotNull public ResourceLookup requestResource(@NotNull String resourceUri, @NotNull String type) throws IOException, HttpException { Utils.checkNotNull(resourceUri, "Report uri should not be null"); Utils.checkNotNull(type, "Report type should not be null"); HttpUrl url = new PathResolver.Builder() .addPath("rest_v2") .addPath("resources") .addPaths(resourceUri) .build() .resolve(mNetworkClient.getBaseUrl()); Request request = new Request.Builder() .addHeader("Accept", String.format("application/repository.%s+json", type)) .get() .url(url) .build(); com.squareup.okhttp.Response rawResponse = mNetworkClient.makeCall(request); if ("file".equals(type)) { return mNetworkClient.deserializeJson(rawResponse, FileLookup.class); } if ("folder".equals(type)) { return mNetworkClient.deserializeJson(rawResponse, FolderLookup.class); } if ("reportUnit".equals(type)) { return mNetworkClient.deserializeJson(rawResponse, ReportLookup.class); } return mNetworkClient.deserializeJson(rawResponse, ResourceLookup.class); } RepositoryRestApi(NetworkClient networkClient); @NotNull ResourceSearchResult searchResources(@NotNull Map<String, Object> searchParams); @NotNull ResourceLookup requestResource(@NotNull String resourceUri, @NotNull String type); @NotNull DashboardComponentCollection requestDashboardComponents(@NotNull String dashboardUri); @NotNull OutputResource requestResourceOutput(@NotNull String resourceUri); }### Answer:
@Test public void requestForResourceByTypeShouldNotAcceptNullType() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Report type should not be null"); restApiUnderTest.requestResource("/", null); }
@Test public void requestForResourceByTypeShouldNotAcceptNullUri() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Report uri should not be null"); restApiUnderTest.requestResource(null, "file"); }
@Test @Parameters({ "reportUnit|com.jaspersoft.android.sdk.network.entity.resource.ReportLookup", "folder|com.jaspersoft.android.sdk.network.entity.resource.FolderLookup", "file|com.jaspersoft.android.sdk.network.entity.resource.FileLookup" }) public void shouldRequestReportResources(String type, String className) throws Exception { mWebMockRule.enqueue(MockResponseFactory.create200().setBody("{}")); ResourceLookup expected = restApiUnderTest.requestResource("/my/uri", type); assertThat(expected, instanceOf(Class.forName(className))); RecordedRequest request = mWebMockRule.get().takeRequest(); assertThat(request, containsHeader("Accept", String.format("application/repository.%s+json", type))); assertThat(request, hasPath("/rest_v2/resources/my/uri")); assertThat(request, wasMethod("GET")); } |
### Question:
RepositoryRestApi { @NotNull public OutputResource requestResourceOutput(@NotNull String resourceUri) throws IOException, HttpException { Utils.checkNotNull(resourceUri, "Resource uri should not be null"); HttpUrl url = new PathResolver.Builder() .addPath("rest_v2") .addPath("resources") .addPaths(resourceUri) .build() .resolve(mNetworkClient.getBaseUrl()); Request request = new Request.Builder() .get() .url(url) .build(); com.squareup.okhttp.Response rawResponse = mNetworkClient.makeCall(request); return new RetrofitOutputResource(rawResponse.body()); } RepositoryRestApi(NetworkClient networkClient); @NotNull ResourceSearchResult searchResources(@NotNull Map<String, Object> searchParams); @NotNull ResourceLookup requestResource(@NotNull String resourceUri, @NotNull String type); @NotNull DashboardComponentCollection requestDashboardComponents(@NotNull String dashboardUri); @NotNull OutputResource requestResourceOutput(@NotNull String resourceUri); }### Answer:
@Test public void requestForFileContentShouldNotAcceptNullUri() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Resource uri should not be null"); restApiUnderTest.requestResourceOutput(null); }
@Test public void shouldRequestFileContent() throws Exception { mWebMockRule.enqueue(MockResponseFactory.create200()); restApiUnderTest.requestResourceOutput("/my/uri"); RecordedRequest request = mWebMockRule.get().takeRequest(); assertThat(request, hasPath("/rest_v2/resources/my/uri")); assertThat(request, wasMethod("GET")); } |
### Question:
RepositoryRestApi { @NotNull public DashboardComponentCollection requestDashboardComponents(@NotNull String dashboardUri) throws IOException, HttpException { Utils.checkNotNull(dashboardUri, "Dashboard uri should not be null"); HttpUrl url = new PathResolver.Builder() .addPath("rest_v2") .addPath("resources") .addPaths(dashboardUri + "_files") .addPath("components") .build() .resolve(mNetworkClient.getBaseUrl()) .newBuilder() .addQueryParameter("expanded", "false") .build(); Request request = new Request.Builder() .addHeader("Accept", "application/dashboardComponentsSchema+json") .get() .url(url) .build(); com.squareup.okhttp.Response rawResponse = mNetworkClient.makeCall(request); return mNetworkClient.deserializeJson(rawResponse, DashboardComponentCollection.class); } RepositoryRestApi(NetworkClient networkClient); @NotNull ResourceSearchResult searchResources(@NotNull Map<String, Object> searchParams); @NotNull ResourceLookup requestResource(@NotNull String resourceUri, @NotNull String type); @NotNull DashboardComponentCollection requestDashboardComponents(@NotNull String dashboardUri); @NotNull OutputResource requestResourceOutput(@NotNull String resourceUri); }### Answer:
@Test public void requestForRequestDashboardComponentsdNotAcceptNullUri() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Dashboard uri should not be null"); restApiUnderTest.requestDashboardComponents(null); }
@Test public void shouldRequestDashboardComponents() throws Exception { mWebMockRule.enqueue(MockResponseFactory.create200()); restApiUnderTest.requestDashboardComponents("/my/uri"); RecordedRequest request = mWebMockRule.get().takeRequest(); assertThat(request, containsHeader("Accept", "application/dashboardComponentsSchema+json")); assertThat(request, hasPath("/rest_v2/resources/my/uri_files/components?expanded=false")); assertThat(request, wasMethod("GET")); } |
### Question:
ReportExportRestApi { @NotNull public OutputResource requestExportAttachment(@NotNull String executionId, @NotNull String exportId, @NotNull String attachmentId) throws IOException, HttpException { Utils.checkNotNull(executionId, "Execution id should not be null"); Utils.checkNotNull(exportId, "Export id should not be null"); Utils.checkNotNull(attachmentId, "Attachment id should not be null"); HttpUrl url = new PathResolver.Builder() .addPath("rest_v2") .addPath("reportExecutions") .addPath(executionId) .addPath("exports") .addPath(exportId) .addPath("attachments") .addPath(attachmentId) .build() .resolve(mNetworkClient.getBaseUrl()); Request request = new Request.Builder() .addHeader("Accept", "application/json; charset=UTF-8") .get() .url(url) .build(); com.squareup.okhttp.Response response = mNetworkClient.makeCall(request); return new RetrofitOutputResource(response.body()); } ReportExportRestApi(NetworkClient networkClient); @NotNull ExportExecutionDescriptor runExportExecution(@NotNull String executionId,
@NotNull ExecutionRequestOptions executionOptions); @NotNull ExecutionStatus checkExportExecutionStatus(@NotNull String executionId,
@NotNull String exportId); @NotNull ExportOutputResource requestExportOutput(@NotNull String executionId,
@NotNull String exportId); @NotNull OutputResource requestExportAttachment(@NotNull String executionId,
@NotNull String exportId,
@NotNull String attachmentId); }### Answer:
@Test public void requestForAttachmentShouldBeWrappedInsideInput() throws Exception { MockResponse mockResponse = MockResponseFactory.create200() .setBody(mResource.asString()); mWebMockRule.enqueue(mockResponse); OutputResource resource = restApiUnderTest.requestExportAttachment("any_id", "any_id", "any_id"); InputStream stream = resource.getStream(); assertThat(stream, is(notNullValue())); stream.close(); }
@Test public void shouldRequestExportAttachment() throws Exception { MockResponse mockResponse = MockResponseFactory.create200() .setBody(mResource.asString()); mWebMockRule.enqueue(mockResponse); restApiUnderTest.requestExportAttachment(EXECUTION_ID, "html;pages=1", "attachment_id"); RecordedRequest request = mWebMockRule.get().takeRequest(); assertThat(request, containsHeader("Accept", "application/json; charset=UTF-8")); assertThat(request, hasPath("/rest_v2/reportExecutions/f3a9805a-4089-4b53-b9e9-b54752f91586/exports/html;pages=1/attachments/attachment_id")); assertThat(request, wasMethod("GET")); }
@Test public void requestExportAttachmentShouldThrowRestErrorOn500() throws Exception { mExpectedException.expect(HttpException.class); mWebMockRule.enqueue(MockResponseFactory.create500()); restApiUnderTest.requestExportAttachment("any_id", "any_id", "any_id"); }
@Test public void executionIdParameterShouldNotBeNullForAttachmentRequest() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Execution id should not be null"); restApiUnderTest.requestExportAttachment(null, "any_id", "any_id"); }
@Test public void exportIdParameterShouldNotBeNullForAttachmentRequest() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Export id should not be null"); restApiUnderTest.requestExportAttachment("any_id", null, "any_id"); }
@Test public void attachmentIdParameterShouldNotBeNullForAttachmentRequest() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Attachment id should not be null"); restApiUnderTest.requestExportAttachment("any_id", "any_id", null); } |
### Question:
SpringAuthServiceFactory { public SpringAuthService create() { AuthRestApi restApi = new AuthRestApi(mClient); JSEncryptionAlgorithm encryptionAlgorithm = JSEncryptionAlgorithm.create(); return new SpringAuthService(restApi, encryptionAlgorithm); } SpringAuthServiceFactory(NetworkClient client); SpringAuthService create(); }### Answer:
@Test public void testCreate() throws Exception { SpringAuthService service = authServiceFactory.create(); assertThat(service, is(notNullValue())); } |
### Question:
Utils { public static String normalizeBaseUrl(String url) { if (url == null || url.length() == 0) { return url; } if (url.endsWith("/")) { return url; } return url + "/"; } private Utils(); static T checkNotNull(T object, String message); static void checkArgument(boolean condition, String message); static int headerToInt(com.squareup.okhttp.Headers headers, String key); static String normalizeBaseUrl(String url); static String joinString(CharSequence delimiter, Iterable tokens); }### Answer:
@Test public void normalizeBaseUrlShouldAddTrailingSlashIfMissing() { String url = "http: assertThat(Utils.normalizeBaseUrl(url), is(url + "/")); }
@Test public void normalizeBaseUrlShouldNotNormalizeEmptyString() { String url = ""; assertThat(Utils.normalizeBaseUrl(url), is("")); }
@Test public void normalizeBaseUrlShouldNotNormalizeNullString() { String url = null; assertThat(Utils.normalizeBaseUrl(url), is(nullValue())); } |
### Question:
JobData { @Override public final boolean equals(Object o) { if (this == o) return true; if (!(o instanceof JobData)) return false; JobData jobData = (JobData) o; if (mId != jobData.mId) return false; if (mVersion != jobData.mVersion) return false; if (!mCreationDate.equals(jobData.mCreationDate)) return false; if (!mDescription.equals(jobData.mDescription)) return false; if (!mLabel.equals(jobData.mLabel)) return false; if (!mOutputFormats.equals(jobData.mOutputFormats)) return false; if (!mUsername.equals(jobData.mUsername)) return false; return true; } JobData(int id,
int version,
@NotNull String username,
@NotNull String label,
@NotNull String description,
@NotNull Date creationDate,
@NotNull List<JobOutputFormat> outputFormats); @NotNull int getId(); int getVersion(); @NotNull String getUsername(); @NotNull String getLabel(); @NotNull String getDescription(); @NotNull Date getCreationDate(); @NotNull List<JobOutputFormat> getOutputFormats(); @Override final boolean equals(Object o); @Override final int hashCode(); @Override String toString(); }### Answer:
@Test public void testEquals() throws Exception { EqualsVerifier.forClass(JobData.class).verify(); } |
### Question:
TimePattern { public void setRange(int start, int end) { if (start < mLowerBound) { throw new IllegalArgumentException("start cannot be less than lower bound."); } if (end > mHigherBound) { throw new IllegalArgumentException("end cannot be more than upper bound."); } if (start > end) { throw new IllegalArgumentException("start must be lesser than end."); } mPattern.setLength(0); mPattern.append(String.valueOf(start)) .append("-") .append(String.valueOf(end)); } TimePattern(int lowerBound, int higherBound); void setRange(int start, int end); @Override String toString(); void setValue(int value); void setIncrement(int interval, int from); void setRawValue(String rawValue); String parse(String rawValue); }### Answer:
@Test public void should_throw_if_lower_bound_higher_than_upper_one() throws Exception { expected.expect(IllegalArgumentException.class); expected.expectMessage("start must be lesser than end."); mTimePattern.setRange(10, 0); }
@Test public void should_throw_if_start_less_than_lower_bound() throws Exception { expected.expect(IllegalArgumentException.class); expected.expectMessage("start cannot be less than lower bound."); mTimePattern.setRange(-10, 0); }
@Test public void should_throw_if_upper_bound_negative() throws Exception { expected.expect(IllegalArgumentException.class); expected.expectMessage("end cannot be more than upper bound."); mTimePattern.setRange(0, 200); } |
### Question:
TimePattern { public void setValue(int value) { validateWithinBounds(value, String.format("Value should be within bounds [ %d, %d ]", mLowerBound, mHigherBound)); mPattern.setLength(0); mPattern.append(String.valueOf(value)); } TimePattern(int lowerBound, int higherBound); void setRange(int start, int end); @Override String toString(); void setValue(int value); void setIncrement(int interval, int from); void setRawValue(String rawValue); String parse(String rawValue); }### Answer:
@Test public void should_not_accept_value_that_less_than_lower_bound() throws Exception { expected.expect(IllegalArgumentException.class); expected.expectMessage("Value should be within bounds [ 0, 59 ]"); mTimePattern.setValue(-10); }
@Test public void should_not_accept_value_that_more_than_upper_bound() throws Exception { expected.expect(IllegalArgumentException.class); expected.expectMessage("Value should be within bounds [ 0, 59 ]"); mTimePattern.setValue(100); } |
### Question:
TimePattern { public void setIncrement(int interval, int from) { validateWithinBounds(interval, String.format("Interval should be within bounds [ %d, %d ]", mLowerBound, mHigherBound)); validateWithinBounds(from, String.format("From should be within bounds [ %d, %d ]", mLowerBound, mHigherBound)); mPattern.setLength(0); mPattern.append(String.valueOf(interval)) .append("/") .append(String.valueOf(from)); } TimePattern(int lowerBound, int higherBound); void setRange(int start, int end); @Override String toString(); void setValue(int value); void setIncrement(int interval, int from); void setRawValue(String rawValue); String parse(String rawValue); }### Answer:
@Test public void should_not_accept_interval_that_less_than_lower_bound() throws Exception { expected.expect(IllegalArgumentException.class); expected.expectMessage("Interval should be within bounds [ 0, 59 ]"); mTimePattern.setIncrement(-10, 5); }
@Test public void should_not_accept_interval_that_more_than_upper_bound() throws Exception { expected.expect(IllegalArgumentException.class); expected.expectMessage("Interval should be within bounds [ 0, 59 ]"); mTimePattern.setIncrement(100, -5); }
@Test public void should_not_accept_from_that_less_than_lower_bound() throws Exception { expected.expect(IllegalArgumentException.class); expected.expectMessage("From should be within bounds [ 0, 59 ]"); mTimePattern.setIncrement(0, -5); }
@Test public void should_not_accept_from_that_more_than_upper_bound() throws Exception { expected.expect(IllegalArgumentException.class); expected.expectMessage("From should be within bounds [ 0, 59 ]"); mTimePattern.setIncrement(0, 100); } |
### Question:
RepositoryDestination { @Nullable public Boolean getUseDefaultReportOutputFolderURI() { return useDefaultReportOutputFolderURI; } RepositoryDestination(Builder builder); @Nullable Boolean getSequentialFileNames(); @Nullable Boolean getOverwriteFiles(); @Nullable Boolean getSaveToRepository(); @Nullable Boolean getUseDefaultReportOutputFolderURI(); @Nullable String getTimestampPattern(); @Nullable String getOutputDescription(); @Nullable String getOutputLocalFolder(); @NotNull String getFolderUri(); @Nullable String getDefaultReportOutputFolderURI(); @Nullable JobOutputFtpInfo getOutputFtpInfo(); Builder newBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void should_use_default_folder_uri_if_one_not_supplied() throws Exception { RepositoryDestination destination = new RepositoryDestination.Builder().build(); assertThat(destination.getUseDefaultReportOutputFolderURI(), is(true)); } |
### Question:
ReportMetadata { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ReportMetadata that = (ReportMetadata) o; if (totalPages != that.totalPages) return false; if (uri != null ? !uri.equals(that.uri) : that.uri != null) return false; return true; } ReportMetadata(String uri, int totalPages); String getUri(); int getTotalPages(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testEquals() throws Exception { EqualsVerifier.forClass(ReportMetadata.class).verify(); } |
### Question:
ReportOption { @Override public final boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ReportOption)) return false; ReportOption that = (ReportOption) o; if (!id.equals(that.id)) return false; if (!label.equals(that.label)) return false; if (!uri.equals(that.uri)) return false; return true; } private ReportOption(@NotNull String id, @NotNull String uri, @NotNull String label); @NotNull String getId(); @NotNull String getUri(); @NotNull String getLabel(); @Override final boolean equals(Object o); @Override final int hashCode(); @Override String toString(); }### Answer:
@Test public void testEquals() throws Exception { EqualsVerifier.forClass(ReportOption.class).verify(); } |
### Question:
PageRange { @NotNull public static PageRange parse(@NotNull String pages) { Preconditions.checkNotNull(pages, "Pages should not be null"); int lowerBound = parseLowerBound(pages); int upperBound = parseUpperBound(pages); return new PageRange(lowerBound, upperBound); } private PageRange(int lowerBound, int upperBound); int getLowerBound(); int getUpperBound(); boolean isRange(); @NotNull static PageRange parse(@NotNull String pages); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void throwsNumberFormatExceptionIfLowerBoundNotANumber() { mExpectedException.expect(NumberFormatException.class); PageRange.parse("q"); }
@Test public void throwsNumberFormatExceptionIfUpperBoundNotANumber() { mExpectedException.expect(NumberFormatException.class); PageRange.parse("1-q"); }
@Test public void should_not_allow_null() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Pages should not be null"); PageRange.parse(null); } |
### Question:
PageRange { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PageRange pageRange = (PageRange) o; if (mLowerBound != pageRange.mLowerBound) return false; if (mUpperBound != pageRange.mUpperBound) return false; return true; } private PageRange(int lowerBound, int upperBound); int getLowerBound(); int getUpperBound(); boolean isRange(); @NotNull static PageRange parse(@NotNull String pages); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testEquals() throws Exception { EqualsVerifier.forClass(PageRange.class).verify(); } |
### Question:
VersionParser { public static double toDouble(String version) { if (version != null) { try { return Double.parseDouble(version); } catch (NumberFormatException ex) { if (version.contains(".")) { return parseAsVersionName(version); } else { return parseAsNumber(version); } } } return INVALID_VERSION; } private VersionParser(); static double toDouble(String version); }### Answer:
@Test @Parameters({ "5.0.0, 5", "5.1.0, 5.1", "5.2.0, 5.2", "5.5.0, 5.5", "5.6.0, 5.6", "5.6.1, 5.61", "6.0, 6", "6.0.1, 6.01", "6.1, 6.1", "6.1.1, 6.11", }) public void shouldParseSemanticVersioning(String versionCode, String expected) { double expectedCode = Double.valueOf(expected); double resultCode = VersionParser.toDouble(versionCode); assertThat(resultCode, Is.is(expectedCode)); }
@Test @Parameters({ "5.61, 5.61", "6.01, 6.01" }) public void shouldParseValidDouble(String versionCode, String expected) { double expectedCode = Double.valueOf(expected); double resultCode = VersionParser.toDouble(versionCode); assertThat(resultCode, Is.is(expectedCode)); }
@Test @Parameters({ "5.6.1.2, 5.612", "5.6.1.2.0, 5.612", "5.5.6.1.2, 5.5612", "5.5.6.1.2.0, 5.5612", "5.5.6.1.2.3, 5.56123", "5.5.6.1.2.3.0, 5.56123", }) public void shouldParseLongSemanticVersioning(String versionCode, String expected) { double expectedCode = Double.valueOf(expected); double resultCode = VersionParser.toDouble(versionCode); assertThat(resultCode, Is.is(expectedCode)); }
@Test @Parameters({ "0, 0", "0.0, 0", "1-asdasdsad, 1", "1-asdasdsad2, 1", "12-asdasdsad2, 12", }) public void shouldParseIfHasNumber(String version, String result) { double resultCode = VersionParser.toDouble(version); assertThat(resultCode, Is.is(Double.valueOf(result))); }
@Test @Parameters({ "invalid", ".-", "" }) public void shouldReturnZeroForIncorrectVersion(String invalidVersion) { assertThat(String.format("Version '%s' should be treated as zero", invalidVersion), VersionParser.toDouble(invalidVersion), is(-1d)); } |
### Question:
ReportExportRestApi { @NotNull public ExecutionStatus checkExportExecutionStatus(@NotNull String executionId, @NotNull String exportId) throws IOException, HttpException { Utils.checkNotNull(executionId, "Execution id should not be null"); Utils.checkNotNull(exportId, "Export id should not be null"); HttpUrl url = new PathResolver.Builder() .addPath("rest_v2") .addPath("reportExecutions") .addPath(executionId) .addPath("exports") .addPath(exportId) .addPath("status") .build() .resolve(mNetworkClient.getBaseUrl()); Request request = new Request.Builder() .addHeader("Accept", "application/json; charset=UTF-8") .get() .url(url) .build(); com.squareup.okhttp.Response response = mNetworkClient.makeCall(request); return mNetworkClient.deserializeJson(response, ExecutionStatus.class); } ReportExportRestApi(NetworkClient networkClient); @NotNull ExportExecutionDescriptor runExportExecution(@NotNull String executionId,
@NotNull ExecutionRequestOptions executionOptions); @NotNull ExecutionStatus checkExportExecutionStatus(@NotNull String executionId,
@NotNull String exportId); @NotNull ExportOutputResource requestExportOutput(@NotNull String executionId,
@NotNull String exportId); @NotNull OutputResource requestExportAttachment(@NotNull String executionId,
@NotNull String exportId,
@NotNull String attachmentId); }### Answer:
@Test public void shouldCheckExportExecutionStatus() throws Exception { MockResponse mockResponse = MockResponseFactory.create200(); mWebMockRule.enqueue(mockResponse); restApiUnderTest.checkExportExecutionStatus(EXECUTION_ID, "html;pages=1"); RecordedRequest request = mWebMockRule.get().takeRequest(); assertThat(request, containsHeader("Accept", "application/json; charset=UTF-8")); assertThat(request, hasPath("/rest_v2/reportExecutions/f3a9805a-4089-4b53-b9e9-b54752f91586/exports/html;pages=1/status")); assertThat(request, wasMethod("GET")); }
@Test public void checkExportExecutionStatusShouldThrowRestErrorOn500() throws Exception { mExpectedException.expect(HttpException.class); mWebMockRule.enqueue(MockResponseFactory.create500()); restApiUnderTest.checkExportExecutionStatus("any_id", "any_id"); }
@Test public void executionIdShouldNotBeNullForCheckRequestExecutionStatus() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Execution id should not be null"); restApiUnderTest.checkExportExecutionStatus(null, "any_id"); }
@Test public void exportIdShouldNotBeNullForCheckRequestExecutionStatus() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Export id should not be null"); restApiUnderTest.checkExportExecutionStatus("any_id", null); } |
### Question:
RepositoryUseCase { public DashboardComponentCollection requestDashboardComponents(String dashboardUri) throws ServiceException { try { return mRestApi.requestDashboardComponents(dashboardUri); } catch (HttpException e) { throw mExceptionMapper.transform(e); } catch (IOException e) { throw mExceptionMapper.transform(e); } } RepositoryUseCase(ServiceExceptionMapper exceptionMapper, RepositoryRestApi restApi); DashboardComponentCollection requestDashboardComponents(String dashboardUri); }### Answer:
@Test public void list_dashboard_components() throws Exception { useCase.requestDashboardComponents(DASHBOARD_URI); verify(mRepositoryRestApi).requestDashboardComponents(DASHBOARD_URI); }
@Test public void list_dashboard_components_adapts_io_exception() throws Exception { when(mRepositoryRestApi.requestDashboardComponents(anyString())).thenThrow(mIOException); try { useCase.requestDashboardComponents(DASHBOARD_URI); fail("Should adapt IO exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mIOException); } }
@Test public void list_dashboard_components_adapts_http_exception() throws Exception { when(mRepositoryRestApi.requestDashboardComponents(anyString())).thenThrow(mHttpException); try { useCase.requestDashboardComponents(DASHBOARD_URI); fail("Should adapt HTTP exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mHttpException); } } |
### Question:
ReportOptionMapper { public Set<ReportOption> transform(Set<ReportOptionEntity> entities) { Set<ReportOption> options = new HashSet<>(entities.size()); for (ReportOptionEntity entity : entities) { if (entity != null) { ReportOption option = transform(entity); options.add(option); } } return options; } Set<ReportOption> transform(Set<ReportOptionEntity> entities); ReportOption transform(ReportOptionEntity entity); }### Answer:
@Test public void should_map_entities_to_data_objects() throws Exception { Set<ReportOption> expected = mReportOptionMapper.transform(Collections.singleton(mEntity)); assertThat(expected, is(not(empty()))); }
@Test public void should_map_entity_to_data_object() throws Exception { ReportOption expected = mReportOptionMapper.transform(mEntity); assertThat(expected.getId(), is("id")); assertThat(expected.getUri(), is("/my/uri")); assertThat(expected.getLabel(), is("label")); } |
### Question:
ReportOptionsUseCase { public Set<ReportOption> requestReportOptionsList(String reportUnitUri) throws ServiceException { try { Set<ReportOptionEntity> entities = mReportOptionRestApi.requestReportOptionsList(reportUnitUri); return mReportOptionMapper.transform(entities); } catch (HttpException e) { throw mExceptionMapper.transform(e); } catch (IOException e) { throw mExceptionMapper.transform(e); } } ReportOptionsUseCase(ServiceExceptionMapper exceptionMapper, ReportOptionRestApi reportOptionRestApi, ReportOptionMapper reportOptionMapper); Set<ReportOption> requestReportOptionsList(String reportUnitUri); ReportOption createReportOption(String reportUri,
String optionLabel,
List<ReportParameter> parameters,
boolean overwrite); void updateReportOption(String reportUri, String optionId, List<ReportParameter> parameters); void deleteReportOption(String reportUri, String optionId); }### Answer:
@Test public void should_list_report_options() throws Exception { reportOptionsUseCase.requestReportOptionsList(REPORT_URI); verify(mReportOptionMapper).transform(anySetOf(ReportOptionEntity.class)); verify(mReportOptionRestApi).requestReportOptionsList(REPORT_URI); }
@Test public void list_report_options_adapts_io_exception() throws Exception { when(mReportOptionRestApi.requestReportOptionsList(anyString())).thenThrow(mIOException); try { reportOptionsUseCase.requestReportOptionsList(REPORT_URI); fail("Should adapt IO exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mIOException); } }
@Test public void list_report_options_adapts_http_exception() throws Exception { when(mReportOptionRestApi.requestReportOptionsList(anyString())).thenThrow(mHttpException); try { reportOptionsUseCase.requestReportOptionsList(REPORT_URI); fail("Should adapt HTTP exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mHttpException); } } |
### Question:
ReportOptionsUseCase { public ReportOption createReportOption(String reportUri, String optionLabel, List<ReportParameter> parameters, boolean overwrite) throws ServiceException { try { ReportOptionEntity entity = mReportOptionRestApi.createReportOption(reportUri, optionLabel, parameters, overwrite); return mReportOptionMapper.transform(entity); } catch (HttpException e) { throw mExceptionMapper.transform(e); } catch (IOException e) { throw mExceptionMapper.transform(e); } } ReportOptionsUseCase(ServiceExceptionMapper exceptionMapper, ReportOptionRestApi reportOptionRestApi, ReportOptionMapper reportOptionMapper); Set<ReportOption> requestReportOptionsList(String reportUnitUri); ReportOption createReportOption(String reportUri,
String optionLabel,
List<ReportParameter> parameters,
boolean overwrite); void updateReportOption(String reportUri, String optionId, List<ReportParameter> parameters); void deleteReportOption(String reportUri, String optionId); }### Answer:
@Test public void should_create_report_option() throws Exception { reportOptionsUseCase.createReportOption(REPORT_URI, OPTION_LABEL, REPORT_PARAMETERS, true); verify(mReportOptionMapper).transform(any(ReportOptionEntity.class)); verify(mReportOptionRestApi).createReportOption(REPORT_URI, OPTION_LABEL, REPORT_PARAMETERS, true); }
@Test public void create_report_option_adapts_io_exception() throws Exception { when(mReportOptionRestApi.createReportOption(anyString(), anyString(), anyListOf(ReportParameter.class), anyBoolean())).thenThrow(mIOException); try { reportOptionsUseCase.createReportOption(REPORT_URI, OPTION_LABEL, REPORT_PARAMETERS, true); fail("Should adapt IO exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mIOException); } }
@Test public void create_report_option_adapts_http_exception() throws Exception { when(mReportOptionRestApi.createReportOption(anyString(), anyString(), anyListOf(ReportParameter.class), anyBoolean())).thenThrow(mHttpException); try { reportOptionsUseCase.createReportOption(REPORT_URI, OPTION_LABEL, REPORT_PARAMETERS, true); fail("Should adapt HTTP exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mHttpException); } } |
### Question:
ReportOptionsUseCase { public void updateReportOption(String reportUri, String optionId, List<ReportParameter> parameters) throws ServiceException { try { mReportOptionRestApi.updateReportOption(reportUri, optionId, parameters); } catch (HttpException e) { throw mExceptionMapper.transform(e); } catch (IOException e) { throw mExceptionMapper.transform(e); } } ReportOptionsUseCase(ServiceExceptionMapper exceptionMapper, ReportOptionRestApi reportOptionRestApi, ReportOptionMapper reportOptionMapper); Set<ReportOption> requestReportOptionsList(String reportUnitUri); ReportOption createReportOption(String reportUri,
String optionLabel,
List<ReportParameter> parameters,
boolean overwrite); void updateReportOption(String reportUri, String optionId, List<ReportParameter> parameters); void deleteReportOption(String reportUri, String optionId); }### Answer:
@Test public void should_update_report_option() throws Exception { reportOptionsUseCase.updateReportOption(REPORT_URI, OPTION_ID, REPORT_PARAMETERS); verify(mReportOptionRestApi).updateReportOption(REPORT_URI, OPTION_ID, REPORT_PARAMETERS); }
@Test public void update_report_option_adapts_io_exception() throws Exception { doThrow(mIOException).when(mReportOptionRestApi).updateReportOption(anyString(), anyString(), anyListOf(ReportParameter.class)); try { reportOptionsUseCase.updateReportOption(REPORT_URI, OPTION_LABEL, REPORT_PARAMETERS); fail("Should adapt IO exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mIOException); } }
@Test public void update_report_option_adapts_http_exception() throws Exception { doThrow(mHttpException).when(mReportOptionRestApi).updateReportOption(anyString(), anyString(), anyListOf(ReportParameter.class)); try { reportOptionsUseCase.updateReportOption(REPORT_URI, OPTION_LABEL, REPORT_PARAMETERS); fail("Should adapt HTTP exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mHttpException); } } |
### Question:
ReportOptionsUseCase { public void deleteReportOption(String reportUri, String optionId) throws ServiceException { try { mReportOptionRestApi.deleteReportOption(reportUri, optionId); } catch (HttpException e) { throw mExceptionMapper.transform(e); } catch (IOException e) { throw mExceptionMapper.transform(e); } } ReportOptionsUseCase(ServiceExceptionMapper exceptionMapper, ReportOptionRestApi reportOptionRestApi, ReportOptionMapper reportOptionMapper); Set<ReportOption> requestReportOptionsList(String reportUnitUri); ReportOption createReportOption(String reportUri,
String optionLabel,
List<ReportParameter> parameters,
boolean overwrite); void updateReportOption(String reportUri, String optionId, List<ReportParameter> parameters); void deleteReportOption(String reportUri, String optionId); }### Answer:
@Test public void should_delete_report_option() throws Exception { reportOptionsUseCase.deleteReportOption(REPORT_URI, OPTION_LABEL); verify(mReportOptionRestApi).deleteReportOption(REPORT_URI, OPTION_ID); }
@Test public void delete_report_option_adapts_io_exception() throws Exception { doThrow(mIOException).when(mReportOptionRestApi).deleteReportOption(anyString(), anyString()); try { reportOptionsUseCase.deleteReportOption(REPORT_URI, OPTION_LABEL); fail("Should adapt IO exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mIOException); } }
@Test public void delete_report_option_adapts_http_exception() throws Exception { doThrow(mHttpException).when(mReportOptionRestApi).deleteReportOption(anyString(), anyString()); try { reportOptionsUseCase.deleteReportOption(REPORT_URI, OPTION_LABEL); fail("Should adapt HTTP exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mHttpException); } } |
### Question:
ReportControlsUseCase { public List<InputControl> requestControls(String reportUri, Set<String> ids, boolean excludeState) throws ServiceException { try { return mRestApi.requestInputControls(reportUri, ids, excludeState); } catch (HttpException e) { throw mExceptionMapper.transform(e); } catch (IOException e) { throw mExceptionMapper.transform(e); } } ReportControlsUseCase(ServiceExceptionMapper exceptionMapper, InputControlRestApi restApi); List<InputControl> requestControls(String reportUri, Set<String> ids, boolean excludeState); List<InputControlState> requestControlsValues(String reportUri,
List<ReportParameter> parameters,
boolean fresh); List<InputControlState> requestResourceValues(String resourceUri, boolean freshData); }### Answer:
@Test public void should_request_controls() throws Exception { mReportControlsUseCase.requestControls(REPORT_URI, null, false); verify(mRestApi).requestInputControls(REPORT_URI, null, false); }
@Test public void request_controls_adapt_io_exception() throws Exception { when(mRestApi.requestInputControls(anyString(), anySetOf(String.class), anyBoolean())).thenThrow(mIOException); try { mReportControlsUseCase.requestControls(REPORT_URI, null, false); fail("Should adapt IO exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mIOException); } }
@Test public void request_controls_adapt_http_exception() throws Exception { when(mRestApi.requestInputControls(anyString(), anySetOf(String.class), anyBoolean())).thenThrow(mHttpException); try { mReportControlsUseCase.requestControls(REPORT_URI, null, false); fail("Should adapt HTTP exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mHttpException); } } |
### Question:
ReportControlsUseCase { public List<InputControlState> requestResourceValues(String resourceUri, boolean freshData) throws ServiceException { try { return mRestApi.requestInputControlsInitialStates(resourceUri, freshData); } catch (HttpException e) { throw mExceptionMapper.transform(e); } catch (IOException e) { throw mExceptionMapper.transform(e); } } ReportControlsUseCase(ServiceExceptionMapper exceptionMapper, InputControlRestApi restApi); List<InputControl> requestControls(String reportUri, Set<String> ids, boolean excludeState); List<InputControlState> requestControlsValues(String reportUri,
List<ReportParameter> parameters,
boolean fresh); List<InputControlState> requestResourceValues(String resourceUri, boolean freshData); }### Answer:
@Test public void should_request_resource_values() throws Exception { mReportControlsUseCase.requestResourceValues(REPORT_URI, false); verify(mRestApi).requestInputControlsInitialStates(REPORT_URI, false); } |
### Question:
ReportControlsUseCase { public List<InputControlState> requestControlsValues(String reportUri, List<ReportParameter> parameters, boolean fresh) throws ServiceException { try { return mRestApi.requestInputControlsStates(reportUri, parameters, fresh); } catch (HttpException e) { throw mExceptionMapper.transform(e); } catch (IOException e) { throw mExceptionMapper.transform(e); } } ReportControlsUseCase(ServiceExceptionMapper exceptionMapper, InputControlRestApi restApi); List<InputControl> requestControls(String reportUri, Set<String> ids, boolean excludeState); List<InputControlState> requestControlsValues(String reportUri,
List<ReportParameter> parameters,
boolean fresh); List<InputControlState> requestResourceValues(String resourceUri, boolean freshData); }### Answer:
@Test public void request_controls_values_adapt_io_exception() throws Exception { when(mRestApi.requestInputControlsStates(anyString(), anyListOf(ReportParameter.class), anyBoolean())).thenThrow(mIOException); try { mReportControlsUseCase.requestControlsValues(REPORT_URI, PARAMS, false); fail("Should adapt IO exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mIOException); } }
@Test public void request_controls_values_adapt_http_exception() throws Exception { when(mRestApi.requestInputControlsStates(anyString(), anyListOf(ReportParameter.class), anyBoolean())).thenThrow(mHttpException); try { mReportControlsUseCase.requestControlsValues(REPORT_URI, PARAMS, false); fail("Should adapt HTTP exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mHttpException); } }
@Test public void should_request_controls_values() throws Exception { mReportControlsUseCase.requestControlsValues(REPORT_URI, PARAMS, false); verify(mRestApi).requestInputControlsStates(REPORT_URI, PARAMS, false); } |
### Question:
ServerInfoTransformer { public ServerInfo transform(ServerInfoData response) { ServerInfo serverInfo = new ServerInfo(); serverInfo.setBuild(response.getBuild()); SimpleDateFormat dateDateFormat = new SimpleDateFormat(response.getDateFormatPattern()); serverInfo.setDateFormatPattern(dateDateFormat); SimpleDateFormat dateTimeFormat = new SimpleDateFormat(response.getDatetimeFormatPattern()); serverInfo.setDatetimeFormatPattern(dateTimeFormat); ServerVersion version = ServerVersion.valueOf(response.getVersion()); serverInfo.setVersion(version); serverInfo.setEdition(response.getEdition()); serverInfo.setEditionName(response.getEditionName()); Set<String> features = parseFeatureSet(response.getFeatures()); serverInfo.setFeatures(features); serverInfo.setLicenseType(response.getLicenseType()); return serverInfo; } private ServerInfoTransformer(); static ServerInfoTransformer get(); ServerInfo transform(ServerInfoData response); }### Answer:
@Test public void shouldTransform() { ServerInfo info = transformerUnderTest.transform(mServerInfoData); assertThat(info.getBuild(), is("20150527_1447")); assertThat(info.getDateFormatPattern(), is(new SimpleDateFormat("yyyy-MM-dd"))); assertThat(info.getDatetimeFormatPattern(), is(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"))); assertThat(info.getVersion(), is(ServerVersion.v6_1)); assertThat(info.isEditionPro(), is(true)); assertThat(info.getEditionName(), is("Enterprise for AWS")); assertThat(info.getFeatures(), contains("Fusion")); assertThat(info.getLicenseType(), is("Type")); } |
### Question:
FileResourceMapper extends AbstractResourceMapper<FileResource, FileLookup> { @Override public FileResource transform(FileLookup lookup) { FileResource.Builder builder = new FileResource.Builder(); AbstractResourceBuilder abstractResourceBuilder = builder.addResource(); buildLookup(abstractResourceBuilder, lookup); FileResource.Type type = FileResource.Type.valueOf(lookup.getType()); builder.withFileType(type); return builder.build(); } FileResourceMapper(@NotNull SimpleDateFormat format, @Nullable ResourceType backupType); FileResourceMapper(@NotNull SimpleDateFormat format); @Override FileResource transform(FileLookup lookup); }### Answer:
@Test public void should_map_file_lookup() throws Exception { mockFileLookup(); FileResource resource = mapper.transform(mFileLookup); assertThat(resource.getType(), is(FileResource.Type.pdf)); } |
### Question:
RepositorySearchCriteria { @NotNull public static Builder builder() { return new Builder(); } private RepositorySearchCriteria(Builder builder); @NotNull static Builder builder(); @NotNull static RepositorySearchCriteria empty(); int getLimit(); int getOffset(); @Nullable String getQuery(); @Nullable Boolean getRecursive(); @Nullable SortType getSortBy(); int getResourceMask(); @Nullable String getFolderUri(); AccessType getAccessType(); static final int DEFAULT_OFFSET; static final int DEFAULT_LIMIT; static int ALL; static int REPORT; static int DASHBOARD; static int LEGACY_DASHBOARD; static int FOLDER; static int REPORT_OPTION; static int FILE; }### Answer:
@Test public void shouldNotAcceptNegativeOffset() { mExpectedException.expect(IllegalArgumentException.class); mExpectedException.expectMessage("Offset should be positive"); RepositorySearchCriteria.builder().withOffset(-1).build(); }
@Test public void shouldNotAcceptNegativeLimit() { mExpectedException.expect(IllegalArgumentException.class); mExpectedException.expectMessage("Limit should be positive"); RepositorySearchCriteria.builder().withLimit(-1).build(); } |
### Question:
ReportResourceMapper extends AbstractResourceMapper<ReportResource, ReportLookup> { @Override public ReportResource transform(ReportLookup lookup) { ReportResource.Builder builder = new ReportResource.Builder(); AbstractResourceBuilder abstractResourceBuilder = builder.addResource(); buildLookup(abstractResourceBuilder, lookup); builder.withAlwaysPrompt(lookup.alwaysPromptControls()); return builder.build(); } ReportResourceMapper(@NotNull SimpleDateFormat format, @Nullable ResourceType backupType); ReportResourceMapper(@NotNull SimpleDateFormat format); @Override ReportResource transform(ReportLookup lookup); }### Answer:
@Test public void should_map_file_lookup() throws Exception { mockFileLookup(); ReportResource resource = mapper.transform(mReportLookup); assertThat(resource.alwaysPromptControls(), is(true)); } |
### Question:
ResourceMapper extends AbstractResourceMapper<Resource, ResourceLookup> { @Override public Resource transform(ResourceLookup lookup) { AbstractResourceBuilder<?> builder = new AbstractResourceBuilder<>(null); buildLookup(builder, lookup); return builder.getResourceBuilder().build(); } ResourceMapper(@NotNull SimpleDateFormat format); ResourceMapper(@NotNull SimpleDateFormat format, @Nullable ResourceType backupType); @Override Resource transform(ResourceLookup lookup); }### Answer:
@Test public void should_map_lookup_to_resource() throws Exception { long creationTime = TestConstants.DATE_TIME_FORMAT.parse("2013-10-03 16:32:05").getTime(); long updateTime = TestConstants.DATE_TIME_FORMAT.parse("2013-11-03 16:32:05").getTime(); Resource resource = mMapper.transform(mResourceLookup); assertThat(resource.getCreationDate().getTime(), is(creationTime)); assertThat(resource.getUpdateDate().getTime(), is(updateTime)); assertThat(resource.getDescription(), is("description")); assertThat(resource.getLabel(), is("label")); assertThat(resource.getUri(), is("/my/uri")); assertThat(resource.getResourceType(), is(ResourceType.reportUnit)); assertThat(resource.getVersion(), is(100)); assertThat(resource.getPermissionMask(), is(PermissionMask.NO_ACCESS)); } |
### Question:
ReportExportRestApi { @NotNull public ExportOutputResource requestExportOutput(@NotNull String executionId, @NotNull String exportId) throws IOException, HttpException { Utils.checkNotNull(executionId, "Execution id should not be null"); Utils.checkNotNull(exportId, "Export id should not be null"); HttpUrl url = new PathResolver.Builder() .addPath("rest_v2") .addPath("reportExecutions") .addPath(executionId) .addPath("exports") .addPath(exportId) .addPath("outputResource") .build() .resolve(mNetworkClient.getBaseUrl()) .newBuilder() .addQueryParameter("suppressContentDisposition", "true") .build(); Request request = new Request.Builder() .addHeader("Accept", "application/json; charset=UTF-8") .get() .url(url) .build(); com.squareup.okhttp.Response response = mNetworkClient.makeCall(request); com.squareup.okhttp.Headers headers = response.headers(); RetrofitOutputResource exportInput = new RetrofitOutputResource(response.body()); String pages = headers.get("report-pages"); boolean isFinal = Boolean.parseBoolean(headers.get("output-final")); return ExportOutputResource.create(exportInput, pages, isFinal); } ReportExportRestApi(NetworkClient networkClient); @NotNull ExportExecutionDescriptor runExportExecution(@NotNull String executionId,
@NotNull ExecutionRequestOptions executionOptions); @NotNull ExecutionStatus checkExportExecutionStatus(@NotNull String executionId,
@NotNull String exportId); @NotNull ExportOutputResource requestExportOutput(@NotNull String executionId,
@NotNull String exportId); @NotNull OutputResource requestExportAttachment(@NotNull String executionId,
@NotNull String exportId,
@NotNull String attachmentId); }### Answer:
@Test public void requestExportOutputShouldThrowRestErrorOn500() throws Exception { mExpectedException.expect(HttpException.class); mWebMockRule.enqueue(MockResponseFactory.create500()); restApiUnderTest.requestExportOutput("any_id", "any_id"); }
@Test public void requestForOutputShouldParsePagesFromHeader() throws Exception { MockResponse mockResponse = MockResponseFactory.create200() .setBody("") .addHeader("report-pages", "1-10"); mWebMockRule.enqueue(mockResponse); ExportOutputResource resource = restApiUnderTest.requestExportOutput(EXECUTION_ID, EXPORT_ID); assertThat(resource.getPages(), is("1-10")); }
@Test public void requestForOutputShouldParseIsFinalHeader() throws Exception { MockResponse mockResponse = MockResponseFactory.create200() .setBody("") .addHeader("output-final", "true"); mWebMockRule.enqueue(mockResponse); ExportOutputResource resource = restApiUnderTest.requestExportOutput(EXECUTION_ID, EXPORT_ID); assertThat(resource.isFinal(), is(true)); }
@Test public void shouldRequestExportOutput() throws Exception { MockResponse mockResponse = MockResponseFactory.create200(); mWebMockRule.enqueue(mockResponse); restApiUnderTest.requestExportOutput(EXECUTION_ID, "html;pages=1"); RecordedRequest request = mWebMockRule.get().takeRequest(); assertThat(request, containsHeader("Accept", "application/json; charset=UTF-8")); assertThat(request, hasPath("/rest_v2/reportExecutions/f3a9805a-4089-4b53-b9e9-b54752f91586/exports/html;pages=1/outputResource?suppressContentDisposition=true")); assertThat(request, wasMethod("GET")); } |
### Question:
RepositorySearchTaskV5_6Plus extends RepositorySearchTask { @NotNull @Override public List<Resource> nextLookup() throws ServiceException { if (mEndReached || mInitialCriteria.getLimit() == 0){ return EMPTY_RESPONSE; } if (mInternalOffset == UNDEFINED) { defineInternalOffset(); } return Collections.unmodifiableList(performLookup()); } RepositorySearchTaskV5_6Plus(InternalCriteria criteria, SearchUseCase searchUseCase); @NotNull @Override List<Resource> nextLookup(); @Override boolean hasNext(); static final List<Resource> EMPTY_RESPONSE; }### Answer:
@Test public void shouldMakeImmediateCallOnApiForUserOffsetZero() throws Exception { InternalCriteria searchCriteria = new InternalCriteria.Builder().offset(0).create(); RepositorySearchTask strategy = new RepositorySearchTaskV5_6Plus(searchCriteria, mSearchUseCase); strategy.nextLookup(); InternalCriteria internalCriteria = new InternalCriteria.Builder() .offset(0) .forceFullPage(true) .create(); verify(mSearchUseCase).performSearch(internalCriteria); }
@Test public void makesAdditionalCallOnApiIfUserOffsetNotZero() throws Exception { InternalCriteria searchCriteria = new InternalCriteria.Builder().offset(5).create(); RepositorySearchTask strategy = new RepositorySearchTaskV5_6Plus(searchCriteria, mSearchUseCase); strategy.nextLookup(); InternalCriteria internalCriteria = new InternalCriteria.Builder() .limit(5) .forceFullPage(true) .create(); verify(mSearchUseCase).performSearch(internalCriteria); }
@Test public void secondSearchLookupShouldUseNextOffset() throws Exception { InternalCriteria searchCriteria = new InternalCriteria.Builder().offset(0).create(); RepositorySearchTask strategy = new RepositorySearchTaskV5_6Plus(searchCriteria, mSearchUseCase); when(mResponse.getNextOffset()).thenReturn(133); strategy.nextLookup(); when(mResponse.getNextOffset()).thenReturn(233); strategy.nextLookup(); InternalCriteria internalCriteria = new InternalCriteria.Builder() .offset(133) .limit(100) .forceFullPage(true) .create(); verify(mResponse, times(2)).getNextOffset(); verify(mSearchUseCase).performSearch(internalCriteria); }
@Test public void shouldReturnEmptyCollectionForZeroLimit() throws Exception { InternalCriteria userCriteria = new InternalCriteria.Builder().limit(0).offset(5).create(); RepositorySearchTask strategy = new RepositorySearchTaskV5_6Plus(userCriteria, mSearchUseCase); Collection<Resource> result = strategy.nextLookup(); assertThat(result, Matchers.is(Matchers.empty())); verifyZeroInteractions(mSearchUseCase); } |
### Question:
RepositorySearchTaskV5_5 extends RepositorySearchTask { @NotNull @Override public List<Resource> nextLookup() throws ServiceException { int limit = mInitialCriteria.getLimit(); int offset = mInitialCriteria.getOffset(); if (mEndReached || limit == 0) { return EMPTY_RESPONSE; } calculateDisposition(offset); return Collections.unmodifiableList(internalSearch(limit)); } RepositorySearchTaskV5_5(InternalCriteria criteria, SearchUseCase searchUseCase); @NotNull @Override List<Resource> nextLookup(); @Override boolean hasNext(); }### Answer:
@Test public void shouldReturnEmptyCollectionForZeroLimit() throws Exception { InternalCriteria userCriteria = new InternalCriteria.Builder().limit(0).offset(5).create(); RepositorySearchTask strategy = new RepositorySearchTaskV5_5(userCriteria, mSearchUseCase); List<Resource> result = strategy.nextLookup(); assertThat(result, is(empty())); verifyZeroInteractions(mSearchUseCase); } |
### Question:
SearchUseCase { @NotNull public SearchResult performSearch(@NotNull final InternalCriteria internalCriteria) throws ServiceException { final SimpleDateFormat dateTimeFormat = mInfoCacheManager.getInfo().getDatetimeFormatPattern(); Call<SearchResult> call = new Call<SearchResult>() { @Override public SearchResult perform() throws IOException, HttpException { Map<String, Object> criteria = CriteriaMapper.map(internalCriteria); ResourceSearchResult response = mRestApi.searchResources(criteria); List<Resource> resources = mDataMapper.toResources(response.getResources(), dateTimeFormat); return new SearchResult(resources, response.getNextOffset()); } }; return mCallExecutor.execute(call); } SearchUseCase(ResourcesMapper dataMapper,
RepositoryRestApi restApi,
InfoCacheManager infoCacheManager,
CallExecutor callExecutor); @NotNull SearchResult performSearch(@NotNull final InternalCriteria internalCriteria); }### Answer:
@Test public void shouldProvideAndAdaptSearchResult() throws Exception { when(mResult.getNextOffset()).thenReturn(100); when(mRepositoryRestApi.searchResources(anyMapOf(String.class, Object.class))).thenReturn(mResult); List<Resource> resources = new ArrayList<Resource>(); when(mDataMapper.toResources(anyCollectionOf(ResourceLookup.class), Matchers.any(SimpleDateFormat.class))).thenReturn(resources); SearchResult result = objectUnderTest.performSearch(mCriteria); assertThat(result, is(not(nullValue()))); assertThat(result.getNextOffset(), is(100)); assertThat(result.getResources(), is(resources)); verify(mRepositoryRestApi).searchResources(anyMapOf(String.class, Object.class)); } |
### Question:
RepositorySearchTaskProxy extends RepositorySearchTask { @NotNull @Override public List<Resource> nextLookup() throws ServiceException { if (mDelegate == null) { mDelegate = mSearchTaskFactory.create(); } return mDelegate.nextLookup(); } RepositorySearchTaskProxy(SearchTaskFactory searchTaskFactory); @NotNull @Override List<Resource> nextLookup(); @Override boolean hasNext(); }### Answer:
@Test public void testNextLookup() throws Exception { searchTask.nextLookup(); verify(mSearchTaskFactory).create(); searchTask.nextLookup(); verifyNoMoreInteractions(mSearchTaskFactory); } |
### Question:
RepositorySearchTaskProxy extends RepositorySearchTask { @Override public boolean hasNext() { return mDelegate != null && mDelegate.hasNext(); } RepositorySearchTaskProxy(SearchTaskFactory searchTaskFactory); @NotNull @Override List<Resource> nextLookup(); @Override boolean hasNext(); }### Answer:
@Test public void testHasNext() throws Exception { when(mDelegate.hasNext()).thenReturn(true); assertThat("Has next returns false by default", searchTask.hasNext(), is(false)); searchTask.nextLookup(); assertThat("Has next returns true from delegate", searchTask.hasNext(), is(true)); } |
### Question:
ExportOptionsMapper { public ExecutionRequestOptions transform(ReportExportOptions options) { ExecutionRequestOptions resultOptions = ExecutionRequestOptions.create(); ReportFormat format = options.getFormat(); resultOptions.withOutputFormat(format.toString().toLowerCase()); PageRange pageRange = options.getPageRange(); if (pageRange != null) { resultOptions.withPages(pageRange.toString()); } String prefix = options.getAttachmentPrefix(); if (prefix != null) { resultOptions.withAttachmentsPrefix(prefix); } ReportMarkup markup = options.getMarkupType(); if (markup != null) { resultOptions.withMarkupType(markup.toString().toLowerCase()); } resultOptions.withIgnorePagination(options.getIgnorePagination()); resultOptions.withAnchor(options.getAnchor()); resultOptions.withAllowInlineScripts(options.getAllowInlineScripts()); resultOptions.withBaseUrl(mBaseUrl); return resultOptions; } protected ExportOptionsMapper(String baseUrl); static ExportOptionsMapper create(ServerVersion serverVersion, String baseUrl); ExecutionRequestOptions transform(ReportExportOptions options); }### Answer:
@Test public void should_map_format() { ReportExportOptions criteria = ReportExportOptions.builder() .withFormat(ReportFormat.PDF) .build(); ExecutionRequestOptions options = mapper.transform(criteria); assertThat("Failed to map 'format' option", options.getOutputFormat(), is("pdf")); }
@Test public void should_map_pages() { PageRange range = PageRange.parse("1-10"); ReportExportOptions criteria = ReportExportOptions.builder() .withFormat(ReportFormat.PDF) .withPageRange(range) .build(); ExecutionRequestOptions options = mapper.transform(criteria); assertThat("Failed to map 'pages' option", options.getPages(), is("1-10")); }
@Test public void should_include_ignore_pagination_flag() throws Exception { ReportExportOptions criteria = ReportExportOptions.builder() .withFormat(ReportFormat.PDF) .withIgnorePagination(true) .build(); ExecutionRequestOptions options = mapper.transform(criteria); assertThat("Failed to map 'ignorePagination' option", options.getIgnorePagination(), is(true)); }
@Test public void should_map_anchor() { ReportExportOptions criteria = ReportExportOptions.builder() .withFormat(ReportFormat.PDF) .withAnchor("anchor") .build(); ExecutionRequestOptions options = mapper.transform(criteria); assertThat("Failed to map 'anchor' option", options.getAnchor(), is("anchor")); }
@Test public void should_map_attachmentPrefix() { ReportExportOptions criteria = ReportExportOptions.builder() .withFormat(ReportFormat.PDF) .withAttachmentPrefix("./") .build(); ExecutionRequestOptions options = mapper.transform(criteria); assertThat("Failed to map 'attachmentPrefix' option", options.getAttachmentsPrefix(), is("./")); }
@Test public void should_map_allowInlineScripts() { ReportExportOptions criteria = ReportExportOptions.builder() .withFormat(ReportFormat.PDF) .withAllowInlineScripts(true) .build(); ExecutionRequestOptions options = mapper.transform(criteria); assertThat("Failed to map 'allowInlineScripts' option", options.getAllowInlineScripts(), is(true)); }
@Test public void should_map_baseUrl() { ReportExportOptions criteria = ReportExportOptions.builder() .withFormat(ReportFormat.PDF) .build(); ExecutionRequestOptions options = mapper.transform(criteria); assertThat("Failed to map 'baseUrl' option", options.getBaseUrl(), is(BASE_URL)); } |
### Question:
JobTriggerMapper extends JobMapper { @Override public void mapEntityOnForm(JobForm.Builder form, JobFormEntity entity) { JobSimpleTriggerEntity simpleTrigger = entity.getSimpleTrigger(); if (simpleTrigger == null) { mCalendarTriggerMapper.mapEntityOnForm(form, entity); } else { Integer recurrenceInterval = simpleTrigger.getRecurrenceInterval(); String recurrenceIntervalUnit = simpleTrigger.getRecurrenceIntervalUnit(); boolean triggerIsSimpleType = (recurrenceInterval != null && recurrenceIntervalUnit != null); if (triggerIsSimpleType) { mSimpleTriggerMapper.mapEntityOnForm(form, entity); } else { mNoneTriggerMapper.mapEntityOnForm(form, entity); } } } JobTriggerMapper(
JobCalendarTriggerMapper calendarTriggerMapper,
JobSimpleTriggerMapper simpleTriggerMapper,
JobNoneTriggerMapper noneTriggerMapper
); @Override void mapFormOnEntity(JobForm form, JobFormEntity entity); @Override void mapEntityOnForm(JobForm.Builder form, JobFormEntity entity); }### Answer:
@Test public void should_map_simple_entity_trigger_to_form() throws Exception { givenEntityFormWithSimpleTrigger(); whenMapsEntityToForm(); verify(mSimpleTriggerMapper).mapEntityOnForm(formBuilder, providedFormEntity); }
@Test public void should_map_calendar_entity_trigger_to_form() throws Exception { givenEntityFormWithCalendarTrigger(); whenMapsEntityToForm(); verify(mCalendarTriggerMapper).mapEntityOnForm(formBuilder, providedFormEntity); }
@Test public void should_map_none_entity_trigger_to_form() throws Exception { givenEntityFormWithNoneTrigger(); whenMapsEntityToForm(); verify(mNoneTriggerMapper).mapEntityOnForm(formBuilder, providedFormEntity); } |
### Question:
JobTriggerMapper extends JobMapper { @Override public void mapFormOnEntity(JobForm form, JobFormEntity entity) { Trigger trigger = form.getTrigger(); if (trigger == null) { mNoneTriggerMapper.mapFormOnEntity(form, entity); } else { Recurrence recurrence = trigger.getRecurrence(); if (recurrence instanceof CalendarRecurrence) { mCalendarTriggerMapper.mapFormOnEntity(form, entity); } else { mSimpleTriggerMapper.mapFormOnEntity(form, entity); } } } JobTriggerMapper(
JobCalendarTriggerMapper calendarTriggerMapper,
JobSimpleTriggerMapper simpleTriggerMapper,
JobNoneTriggerMapper noneTriggerMapper
); @Override void mapFormOnEntity(JobForm form, JobFormEntity entity); @Override void mapEntityOnForm(JobForm.Builder form, JobFormEntity entity); }### Answer:
@Test public void should_map_simple_trigger_to_entity() throws Exception { givenFormWithSimpleTrigger(); whenMapsFormToEntity(); verify(mSimpleTriggerMapper).mapFormOnEntity(providedForm, mappedFormEntity); }
@Test public void should_map_calendar_trigger_to_entity() throws Exception { givenFormWithCalendarTrigger(); whenMapsFormToEntity(); verify(mCalendarTriggerMapper).mapFormOnEntity(providedForm, mappedFormEntity); }
@Test public void should_map_none_trigger_to_entity() throws Exception { givenFormWithNoneTrigger(); whenMapsFormToEntity(); verify(mNoneTriggerMapper).mapFormOnEntity(providedForm, mappedFormEntity); } |
### Question:
PathResolver { public HttpUrl resolve(HttpUrl base) { HttpUrl.Builder builder = base.newBuilder(); for (String path : mPaths) { builder.addPathSegment(path); } return builder.build(); } PathResolver(List<String> paths); HttpUrl resolve(HttpUrl base); }### Answer:
@Test public void shouldAggregateSinglePath() throws Exception { HttpUrl base = HttpUrl.parse("http: PathResolver resolver = new PathResolver.Builder() .addPath("path") .build(); HttpUrl expected = resolver.resolve(base); assertThat(expected, is(HttpUrl.parse("http: }
@Test public void shouldAggregateMultiplePaths() throws Exception { HttpUrl base = HttpUrl.parse("http: PathResolver resolver = new PathResolver.Builder() .addPaths("/path/a/b") .build(); HttpUrl expected = resolver.resolve(base); assertThat(expected, is(HttpUrl.parse("http: }
@Test public void shouldAggregateSinglePathAsItIs() throws Exception { HttpUrl base = HttpUrl.parse("http: PathResolver resolver = new PathResolver.Builder() .addPaths("path") .build(); HttpUrl expected = resolver.resolve(base); assertThat(expected, is(HttpUrl.parse("http: }
@Test public void shouldNotAggregatePathIfEmptinessSupplied() throws Exception { HttpUrl base = HttpUrl.parse("http: PathResolver resolver = new PathResolver.Builder() .addPath("") .build(); HttpUrl expected = resolver.resolve(base); assertThat(expected, is(HttpUrl.parse("http: PathResolver resolver2 = new PathResolver.Builder() .addPaths("") .build(); HttpUrl expected2 = resolver2.resolve(base); assertThat(expected2, is(HttpUrl.parse("http: } |
### Question:
JobSourceMapper extends JobMapper { @Override public void mapFormOnEntity(JobForm form, JobFormEntity entity) { JobSource source = form.getSource(); List<ReportParameter> params = source.getParameters(); Map<String, Set<String>> values = mapSourceParamValues(params); entity.setSourceUri(source.getUri()); entity.setSourceParameters(values); } @Override void mapFormOnEntity(JobForm form, JobFormEntity entity); @Override void mapEntityOnForm(JobForm.Builder form, JobFormEntity entity); }### Answer:
@Test public void should_map_form_to_entity() throws Exception { List<ReportParameter> parameters = Collections.singletonList( new ReportParameter("key", Collections.singleton("value"))); JobSource source = new JobSource.Builder() .withUri("/my/uri") .withParameters(parameters) .build(); JobFormEntity mappedEntity = formFactory.givenNewJobFormEntity(); JobForm preparedForm = formFactory.givenJobFormBuilderWithValues() .withJobSource(source) .build(); mapperUnderTest.mapFormOnEntity(preparedForm, mappedEntity); assertThat(mappedEntity.getSourceUri(), is("/my/uri")); Map<String, Set<String>> params = mappedEntity.getSourceParameters(); Collection<String> values = new ArrayList<>(); for (Map.Entry<String, Set<String>> entry : params.entrySet()) { values.addAll(entry.getValue()); } assertThat(params.keySet(), hasItem("key")); assertThat(values, hasItem("value")); } |
### Question:
JobSourceMapper extends JobMapper { @Override public void mapEntityOnForm(JobForm.Builder form, JobFormEntity entity) { JobSource.Builder builder = new JobSource.Builder(); builder.withUri(entity.getSourceUri()); Map<String, Set<String>> parameters = entity.getSourceParameters(); if (parameters != null) { List<ReportParameter> params = mapParams(parameters); builder.withParameters(params); } JobSource source = builder.build(); form.withJobSource(source); } @Override void mapFormOnEntity(JobForm form, JobFormEntity entity); @Override void mapEntityOnForm(JobForm.Builder form, JobFormEntity entity); }### Answer:
@Test public void should_map_entity_to_form() throws Exception { JobFormEntity preparedEntity = formFactory.givenJobFormEntityWithValues(); JobForm.Builder form = formFactory.givenJobFormBuilderWithValues(); mapperUnderTest.mapEntityOnForm(form, preparedEntity); JobSource source = form.build().getSource(); assertThat(source.getUri(), is("/my/uri")); assertThat(source.getParameters(), hasItem(new ReportParameter("key", Collections.singleton("value")))); } |
### Question:
ReportScheduleUseCase { public List<JobUnit> searchJob(JobSearchCriteria criteria) throws ServiceException { try { Map<String, Object> searchParams = mSearchCriteriaMapper.transform(criteria); List<JobUnitEntity> jobUnitEntities = mScheduleRestApi.searchJob(searchParams); return mJobUnitMapper.transform(jobUnitEntities); } catch (IOException e) { throw mExceptionMapper.transform(e); } catch (HttpException e) { throw mExceptionMapper.transform(e); } } ReportScheduleUseCase(ServiceExceptionMapper exceptionMapper,
ReportScheduleRestApi scheduleRestApi,
InfoCacheManager cacheManager,
JobSearchCriteriaMapper searchCriteriaMapper,
JobDataMapper jobDataMapper,
JobFormMapper jobFormMapper,
JobUnitMapper jobUnitMapper
); List<JobUnit> searchJob(JobSearchCriteria criteria); JobData createJob(JobForm form); JobData updateJob(int id, JobForm form); Set<Integer> deleteJobs(Set<Integer> jobIds); JobForm readJob(int jobId); }### Answer:
@Test public void should_perform_search() throws Exception { when(mScheduleRestApi.searchJob(anyMapOf(String.class, Object.class))).thenReturn(Collections.<JobUnitEntity>emptyList()); useCase.searchJob(CRITERIA); verify(mSearchCriteriaMapper).transform(CRITERIA); verify(mScheduleRestApi).searchJob(SEARCH_PARAMS); verify(mJobUnitMapper).transform(Collections.<JobUnitEntity>emptyList()); }
@Test public void search_adapts_io_exception() throws Exception { when(mScheduleRestApi.searchJob(anyMapOf(String.class, Object.class))).thenThrow(mIOException); try { useCase.searchJob(CRITERIA); fail("Should adapt IO exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mIOException); } }
@Test public void search_adapts_http_exception() throws Exception { when(mScheduleRestApi.searchJob(anyMapOf(String.class, Object.class))).thenThrow(mHttpException); try { useCase.searchJob(CRITERIA); fail("Should adapt HTTP exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mHttpException); } } |
### Question:
ReportScheduleUseCase { public JobData createJob(JobForm form) throws ServiceException { return alterJob(form, null); } ReportScheduleUseCase(ServiceExceptionMapper exceptionMapper,
ReportScheduleRestApi scheduleRestApi,
InfoCacheManager cacheManager,
JobSearchCriteriaMapper searchCriteriaMapper,
JobDataMapper jobDataMapper,
JobFormMapper jobFormMapper,
JobUnitMapper jobUnitMapper
); List<JobUnit> searchJob(JobSearchCriteria criteria); JobData createJob(JobForm form); JobData updateJob(int id, JobForm form); Set<Integer> deleteJobs(Set<Integer> jobIds); JobForm readJob(int jobId); }### Answer:
@Test public void should_perform_create_job() throws Exception { when(mScheduleRestApi.createJob(any(JobFormEntity.class))).thenReturn(mJobDescriptor); useCase.createJob(mJobForm); verify(mJobDataMapper).transform(mJobDescriptor, SIMPLE_DATE_FORMAT); verify(mScheduleRestApi).createJob(mJobFormEntity); }
@Test public void create_job_adapts_io_exception() throws Exception { when(mScheduleRestApi.createJob(any(JobFormEntity.class))).thenThrow(mIOException); try { useCase.createJob(mJobForm); fail("Should adapt IO exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mIOException); } }
@Test public void create_job_adapts_http_exception() throws Exception { when(mScheduleRestApi.createJob(any(JobFormEntity.class))).thenThrow(mHttpException); try { useCase.createJob(mJobForm); fail("Should adapt HTTP exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mHttpException); } } |
### Question:
ReportScheduleUseCase { public JobData updateJob(int id, JobForm form) throws ServiceException { return alterJob(form, id); } ReportScheduleUseCase(ServiceExceptionMapper exceptionMapper,
ReportScheduleRestApi scheduleRestApi,
InfoCacheManager cacheManager,
JobSearchCriteriaMapper searchCriteriaMapper,
JobDataMapper jobDataMapper,
JobFormMapper jobFormMapper,
JobUnitMapper jobUnitMapper
); List<JobUnit> searchJob(JobSearchCriteria criteria); JobData createJob(JobForm form); JobData updateJob(int id, JobForm form); Set<Integer> deleteJobs(Set<Integer> jobIds); JobForm readJob(int jobId); }### Answer:
@Test public void should_perform_update_job() throws Exception { when(mScheduleRestApi.updateJob(anyInt(), any(JobFormEntity.class))).thenReturn(mJobDescriptor); useCase.updateJob(JOB_ID, mJobForm); verify(mJobDataMapper).transform(mJobDescriptor, SIMPLE_DATE_FORMAT); verify(mScheduleRestApi).updateJob(JOB_ID, mJobFormEntity); } |
### Question:
ReportScheduleUseCase { public Set<Integer> deleteJobs(Set<Integer> jobIds) throws ServiceException { try { return mScheduleRestApi.deleteJobs(jobIds); } catch (IOException e) { throw mExceptionMapper.transform(e); } catch (HttpException e) { throw mExceptionMapper.transform(e); } } ReportScheduleUseCase(ServiceExceptionMapper exceptionMapper,
ReportScheduleRestApi scheduleRestApi,
InfoCacheManager cacheManager,
JobSearchCriteriaMapper searchCriteriaMapper,
JobDataMapper jobDataMapper,
JobFormMapper jobFormMapper,
JobUnitMapper jobUnitMapper
); List<JobUnit> searchJob(JobSearchCriteria criteria); JobData createJob(JobForm form); JobData updateJob(int id, JobForm form); Set<Integer> deleteJobs(Set<Integer> jobIds); JobForm readJob(int jobId); }### Answer:
@Test public void should_perform_delete_jobs() throws Exception { useCase.deleteJobs(JOB_IDS); verify(mScheduleRestApi).deleteJobs(JOB_IDS); }
@Test public void delete_jobs_adapts_io_exception() throws Exception { when(mScheduleRestApi.deleteJobs(anySetOf(Integer.class))).thenThrow(mIOException); try { useCase.deleteJobs(JOB_IDS); fail("Should adapt IO exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mIOException); } }
@Test public void delete_jobs_adapts_http_exception() throws Exception { when(mScheduleRestApi.deleteJobs(anySetOf(Integer.class))).thenThrow(mHttpException); try { useCase.deleteJobs(JOB_IDS); fail("Should adapt HTTP exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mHttpException); } } |
### Question:
ReportScheduleUseCase { public JobForm readJob(int jobId) throws ServiceException { try { JobFormEntity entity = mScheduleRestApi.requestJob(jobId); return mJobFormMapper.toDataForm(entity); } catch (IOException e) { throw mExceptionMapper.transform(e); } catch (HttpException e) { throw mExceptionMapper.transform(e); } } ReportScheduleUseCase(ServiceExceptionMapper exceptionMapper,
ReportScheduleRestApi scheduleRestApi,
InfoCacheManager cacheManager,
JobSearchCriteriaMapper searchCriteriaMapper,
JobDataMapper jobDataMapper,
JobFormMapper jobFormMapper,
JobUnitMapper jobUnitMapper
); List<JobUnit> searchJob(JobSearchCriteria criteria); JobData createJob(JobForm form); JobData updateJob(int id, JobForm form); Set<Integer> deleteJobs(Set<Integer> jobIds); JobForm readJob(int jobId); }### Answer:
@Test public void should_perform_read_job() throws Exception { when(mScheduleRestApi.requestJob(anyInt())).thenReturn(mJobFormEntity); JobForm expected = useCase.readJob(JOB_ID); assertThat(mJobForm, is(expected)); verify(mJobFormMapper).toDataForm(mJobFormEntity); verify(mScheduleRestApi).requestJob(JOB_ID); }
@Test public void read_job_adapts_io_exception() throws Exception { when(mScheduleRestApi.requestJob(anyInt())).thenThrow(mIOException); try { useCase.readJob(JOB_ID); fail("Should adapt IO exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mIOException); } }
@Test public void read_job_adapts_http_exception() throws Exception { when(mScheduleRestApi.requestJob(anyInt())).thenThrow(mHttpException); try { useCase.readJob(JOB_ID); fail("Should adapt HTTP exception"); } catch (ServiceException ex) { verify(mExceptionMapper).transform(mHttpException); } } |
### Question:
JobUnitMapper { public List<JobUnit> transform(List<JobUnitEntity> entities) { List<JobUnit> list = new ArrayList<>(entities.size()); for (JobUnitEntity entity : entities) { if (entity != null) { JobUnit unit = transform(entity); list.add(unit); } } return list; } JobUnitMapper(JobUnitDateParser jobUnitDateParser); List<JobUnit> transform(List<JobUnitEntity> entities); JobUnit transform(JobUnitEntity entity); }### Answer:
@Test public void should_map_collection_of_units() throws Exception { List<JobUnitEntity> entities = Collections.singletonList(mJobUnitEntity); List<JobUnit> expected = mJobUnitMapper.transform(entities); assertThat(expected.size(), is(1)); }
@Test public void should_map_entity_to_service_counterpart() throws Exception { JobUnit expected = mJobUnitMapper.transform(mJobUnitEntity); assertThat(expected.getId(), is(1)); assertThat(expected.getVersion(), is(100)); assertThat(expected.getLabel(), is("label")); assertThat(expected.getDescription(), is("description")); assertThat(expected.getReportUri(), is("/my/uri")); assertThat(expected.getReportLabel(), is("report label")); assertThat(expected.getOwner().toString(), is("jasperadmin|organization_1")); assertThat(expected.getState().toString(), is("NORMAL")); } |
### Question:
JobNoneTriggerMapper extends BaseTriggerMapper { @Override public void mapFormOnEntity(JobForm form, JobFormEntity entity) { JobSimpleTriggerEntity triggerEntity = new JobSimpleTriggerEntity(); mapCommonTriggerFieldsOnEntity(form, triggerEntity); triggerEntity.setOccurrenceCount(1); triggerEntity.setRecurrenceInterval(1); triggerEntity.setRecurrenceIntervalUnit("DAY"); entity.setSimpleTrigger(triggerEntity); } @Override void mapFormOnEntity(JobForm form, JobFormEntity entity); @Override void mapEntityOnForm(JobForm.Builder form, JobFormEntity entity); }### Answer:
@Test public void should_map_on_entity() throws Exception { JobFormEntity formEntity = formFactory.givenNewJobFormEntity(); JobForm form = formFactory.givenJobFormBuilderWithValues() .withStartDate(null) .build(); mapperUnderTest.mapFormOnEntity(form, formEntity); JobSimpleTriggerEntity simpleTrigger = formEntity.getSimpleTrigger(); assertThat(simpleTrigger.getOccurrenceCount(), is(1)); assertThat(simpleTrigger.getRecurrenceInterval(), is(1)); assertThat(simpleTrigger.getRecurrenceIntervalUnit(), is("DAY")); assertThat(simpleTrigger.getTimezone(), is(formFactory.provideTimeZone().getID())); assertThat(simpleTrigger.getStartType(), is(1)); }
@Test public void should_map_start_date_on_entity() throws Exception { JobFormEntity formEntity = formFactory.givenNewJobFormEntity(); JobForm form = formFactory.givenJobFormWithValues(); mapperUnderTest.mapFormOnEntity(form, formEntity); JobSimpleTriggerEntity simpleTrigger = formEntity.getSimpleTrigger(); assertThat(simpleTrigger.getStartType(), is(2)); assertThat(simpleTrigger.getStartDate(), is(formFactory.provideStartDateSrc())); } |
### Question:
JobNoneTriggerMapper extends BaseTriggerMapper { @Override public void mapEntityOnForm(JobForm.Builder form, JobFormEntity entity) { mapCommonEntityTriggerFieldsOnEntity(form, entity); } @Override void mapFormOnEntity(JobForm form, JobFormEntity entity); @Override void mapEntityOnForm(JobForm.Builder form, JobFormEntity entity); }### Answer:
@Test public void should_map_none_trigger_type_as_simple_one() throws Exception { JobForm.Builder formBuilder = formFactory.givenJobFormBuilderWithValues(); JobFormEntity jobFormEntity = formFactory.givenJobFormEntityWithValues(); JobSimpleTriggerEntity simpleTrigger = new JobSimpleTriggerEntity(); simpleTrigger.setOccurrenceCount(1); simpleTrigger.setStartDate(formFactory.provideStartDateSrc()); simpleTrigger.setTimezone(formFactory.provideTimeZone().getID()); jobFormEntity.setSimpleTrigger(simpleTrigger); mapperUnderTest.mapEntityOnForm(formBuilder, jobFormEntity); JobForm expected = formBuilder.build(); assertThat(expected.getStartDate(), is(formFactory.provideStartDate())); assertThat(expected.getTimeZone(), is(formFactory.provideTimeZone())); assertThat(expected.getTrigger(), is(nullValue())); } |
### Question:
JobDataMapper { public JobData transform(JobDescriptor jobDescriptor, SimpleDateFormat dateTimeFormat) { JobData.Builder builder = new JobData.Builder(); builder.withId(jobDescriptor.getId()); builder.withLabel(jobDescriptor.getLabel()); builder.withDescription(jobDescriptor.getDescription()); builder.withVersion(jobDescriptor.getVersion()); builder.withLabel(jobDescriptor.getLabel()); builder.withUsername(jobDescriptor.getUsername()); Date creationDate; try { creationDate = dateTimeFormat.parse(jobDescriptor.getCreationDate()); } catch (ParseException e) { creationDate = null; } builder.withCreationDate(creationDate); Collection<String> outputFormat = jobDescriptor.getOutputFormats().getOutputFormat(); List<JobOutputFormat> formats = new ArrayList<>(outputFormat.size()); for (String format : outputFormat) { formats.add(JobOutputFormat.valueOf(format)); } builder.withOutputFormats(formats); return builder.build(); } JobData transform(JobDescriptor jobDescriptor, SimpleDateFormat dateTimeFormat); }### Answer:
@Test public void testTransform() throws Exception { long creationTime = DATE_FORMAT.parse("2013-10-03 16:32:05").getTime(); JobData jobData = jobDataMapper.transform(mJobDescriptor, DATE_FORMAT); assertThat("Should map id", jobData.getId(), is(20)); assertThat("Should map version", jobData.getVersion(), is(2)); assertThat("Should map username", jobData.getUsername(), is("user")); assertThat("Should map label", jobData.getLabel(), is("label")); assertThat("Should map description", jobData.getDescription(), is("description")); assertThat("Should map creation date", jobData.getCreationDate().getTime(), is(creationTime)); assertThat("Should map description", jobData.getOutputFormats(), hasItem(JobOutputFormat.HTML)); } |
### Question:
JobSimpleTriggerMapper extends BaseTriggerMapper { @Override public void mapFormOnEntity(JobForm form, JobFormEntity entity) { Trigger trigger = form.getTrigger(); EndDate endDate = trigger.getEndDate(); JobSimpleTriggerEntity simpleTrigger = new JobSimpleTriggerEntity(); mapCommonTriggerFieldsOnEntity(form, simpleTrigger); IntervalRecurrence recurrence = (IntervalRecurrence) trigger.getRecurrence(); simpleTrigger.setRecurrenceInterval(recurrence.getInterval()); simpleTrigger.setRecurrenceIntervalUnit(recurrence.getUnit().name()); simpleTrigger.setCalendarName(trigger.getCalendarName()); if (endDate == null) { simpleTrigger.setOccurrenceCount(-1); } else if (endDate instanceof RepeatedEndDate) { RepeatedEndDate date = (RepeatedEndDate) endDate; simpleTrigger.setOccurrenceCount(date.getOccurrenceCount()); } else if (endDate instanceof UntilEndDate) { mapEndDate((UntilEndDate) endDate, simpleTrigger); simpleTrigger.setOccurrenceCount(-1); } entity.setSimpleTrigger(simpleTrigger); } @Override void mapFormOnEntity(JobForm form, JobFormEntity entity); @Override void mapEntityOnForm(JobForm.Builder form, JobFormEntity entity); }### Answer:
@Test public void should_map_simple_trigger_with_infinite_value_on_entity() throws Exception { IntervalRecurrence recurrence = new IntervalRecurrence.Builder() .withInterval(10) .withUnit(RecurrenceIntervalUnit.DAY) .build(); Trigger trigger = new Trigger.Builder() .withCalendarName("Gregorian") .withRecurrence(recurrence) .build(); JobForm form = formFactory.givenJobFormBuilderWithValues() .withTrigger(trigger) .build(); mapperUnderTest.mapFormOnEntity(form, formEntity); JobSimpleTriggerEntity simpleTrigger = formEntity.getSimpleTrigger(); assertThat(simpleTrigger.getCalendarName(), is("Gregorian")); assertThat(simpleTrigger.getOccurrenceCount(), is(-1)); assertThat(simpleTrigger.getRecurrenceIntervalUnit(), is("DAY")); assertThat(simpleTrigger.getRecurrenceInterval(), is(10)); }
@Test public void should_map_simple_trigger_with_repeated_value_on_entity() throws Exception { IntervalRecurrence recurrence = new IntervalRecurrence.Builder() .withInterval(10) .withUnit(RecurrenceIntervalUnit.DAY) .build(); Trigger trigger = new Trigger.Builder() .withRecurrence(recurrence) .withEndDate(new RepeatedEndDate(100)) .build(); JobForm form = formFactory.givenJobFormBuilderWithValues() .withTrigger(trigger) .build(); mapperUnderTest.mapFormOnEntity(form, formEntity); JobSimpleTriggerEntity simpleTrigger = formEntity.getSimpleTrigger(); assertThat(simpleTrigger.getOccurrenceCount(), is(100)); assertThat(simpleTrigger.getRecurrenceIntervalUnit(), is("DAY")); assertThat(simpleTrigger.getRecurrenceInterval(), is(10)); }
@Test public void should_map_simple_trigger_with_until_date_value_on_entity() throws Exception { IntervalRecurrence recurrence = new IntervalRecurrence.Builder() .withInterval(10) .withUnit(RecurrenceIntervalUnit.DAY) .build(); Trigger trigger = new Trigger.Builder() .withRecurrence(recurrence) .withEndDate(new UntilEndDate(formFactory.provideEndDate())) .build(); JobForm form = formFactory.givenJobFormBuilderWithValues() .withTrigger(trigger) .build(); mapperUnderTest.mapFormOnEntity(form, formEntity); JobSimpleTriggerEntity simpleTrigger = formEntity.getSimpleTrigger(); assertThat(simpleTrigger.getEndDate(), is(formFactory.provideEndDateSrc())); assertThat(simpleTrigger.getOccurrenceCount(), is(-1)); assertThat(simpleTrigger.getRecurrenceIntervalUnit(), is("DAY")); assertThat(simpleTrigger.getRecurrenceInterval(), is(10)); } |
### Question:
JobSimpleTriggerMapper extends BaseTriggerMapper { @Override public void mapEntityOnForm(JobForm.Builder form, JobFormEntity entity) { mapCommonEntityTriggerFieldsOnEntity(form, entity); JobSimpleTriggerEntity simpleTrigger = entity.getSimpleTrigger(); int occurrenceCount = simpleTrigger.getOccurrenceCount(); Integer recurrenceInterval = simpleTrigger.getRecurrenceInterval(); String recurrenceIntervalUnit = simpleTrigger.getRecurrenceIntervalUnit(); Date endDate = null; String endDateString = simpleTrigger.getEndDate(); if (endDateString != null) { endDate = parseDate(endDateString); } IntervalRecurrence recurrence = new IntervalRecurrence.Builder() .withInterval(recurrenceInterval) .withUnit(RecurrenceIntervalUnit.valueOf(recurrenceIntervalUnit)) .build(); Trigger.SimpleTriggerBuilder triggerBuilder = new Trigger.Builder() .withCalendarName(simpleTrigger.getCalendarName()) .withRecurrence(recurrence); if (occurrenceCount < 0 && endDate != null) { triggerBuilder.withEndDate(new UntilEndDate(endDate)); } else { triggerBuilder.withEndDate(new RepeatedEndDate(occurrenceCount)); } Trigger trigger = triggerBuilder.build(); form.withTrigger(trigger); } @Override void mapFormOnEntity(JobForm form, JobFormEntity entity); @Override void mapEntityOnForm(JobForm.Builder form, JobFormEntity entity); }### Answer:
@Test public void should_map_simple_trigger_with_occurrence_count() throws Exception { JobSimpleTriggerEntity simpleTrigger = new JobSimpleTriggerEntity(); simpleTrigger.setOccurrenceCount(1); simpleTrigger.setRecurrenceIntervalUnit("DAY"); simpleTrigger.setCalendarName("Gregorian"); simpleTrigger.setRecurrenceInterval(100); formEntity.setSimpleTrigger(simpleTrigger); JobForm.Builder formBuilder = formFactory.givenJobFormBuilderWithValues(); mapperUnderTest.mapEntityOnForm(formBuilder, formEntity); JobForm expected = formBuilder.build(); Trigger trigger = expected.getTrigger(); IntervalRecurrence recurrence = (IntervalRecurrence) trigger.getRecurrence(); RepeatedEndDate endDate = (RepeatedEndDate) trigger.getEndDate(); assertThat(recurrence.getInterval(), is(100)); assertThat(recurrence.getUnit(), is(RecurrenceIntervalUnit.DAY)); assertThat(endDate.getOccurrenceCount(), is(1)); }
@Test public void should_map_simple_trigger_with_end_date() throws Exception { JobSimpleTriggerEntity simpleTrigger = new JobSimpleTriggerEntity(); simpleTrigger.setOccurrenceCount(-1); simpleTrigger.setRecurrenceInterval(1); simpleTrigger.setRecurrenceIntervalUnit("DAY"); simpleTrigger.setEndDate(formFactory.provideEndDateSrc()); formEntity.setSimpleTrigger(simpleTrigger); JobForm.Builder formBuilder = formFactory.givenJobFormBuilderWithValues(); mapperUnderTest.mapEntityOnForm(formBuilder, formEntity); JobForm expected = formBuilder.build(); Trigger trigger = expected.getTrigger(); IntervalRecurrence recurrence = (IntervalRecurrence) trigger.getRecurrence(); UntilEndDate endDate = (UntilEndDate) trigger.getEndDate(); assertThat(recurrence.getInterval(), is(1)); assertThat(recurrence.getUnit(), is(RecurrenceIntervalUnit.DAY)); assertThat(endDate.getSpecifiedDate(), is(formFactory.provideEndDate())); } |
### Question:
JobUnitDateParser { @Nullable abstract Date parseDate(String rawDate); }### Answer:
@Test public void should_parse_without_milliseconds() throws Exception { parser.parseDate(PREVIOUS_FIRE_TIME); }
@Test public void should_parse_with_milliseconds() throws Exception { parser.parseDate(NEXT_FIRE_TIME); } |
### Question:
AttachmentsFactory { public List<ReportAttachment> create(ExportDescriptor export, String execId) { String exportId = export.getId(); Set<AttachmentDescriptor> rawAttachments = export.getAttachments(); List<ReportAttachment> attachments = new ArrayList<>(rawAttachments.size()); for (AttachmentDescriptor attachment : rawAttachments) { String fileName = attachment.getFileName(); ReportAttachment reportAttachment = new ReportAttachment( mExportExecutionApi, execId, exportId, fileName ); attachments.add(reportAttachment); } return attachments; } AttachmentsFactory(ExportExecutionApi exportExecutionApi); List<ReportAttachment> create(ExportDescriptor export, String execId); }### Answer:
@Test public void testCreate() throws Exception { when(mExportDescriptor.getId()).thenReturn(EXPORT_ID); when(mAttachmentDescriptor.getFileName()).thenReturn(ATTACHMENT_ID); when(mExportDescriptor.getAttachments()).thenReturn(Collections.singleton(mAttachmentDescriptor)); List<ReportAttachment> result = attachmentsFactory.create(mExportDescriptor, EXEC_ID); assertThat(result.size(), is(1)); verify(mExportDescriptor).getId(); verify(mExportDescriptor).getAttachments(); verify(mAttachmentDescriptor).getFileName(); } |
### Question:
ExportExecutionApi { public ExportExecutionDescriptor start(String execId, ReportExportOptions reportExportOptions) throws ServiceException { ExecutionRequestOptions options = mExportOptionsMapper.transform(reportExportOptions); try { return mReportExportRestApi.runExportExecution(execId, options); } catch (HttpException e) { throw mExceptionMapper.transform(e); } catch (IOException e) { throw mExceptionMapper.transform(e); } } ExportExecutionApi(ServiceExceptionMapper exceptionMapper,
ReportExportRestApi reportExportRestApi,
ExportOptionsMapper exportOptionsMapper,
ReportExportMapper reportExportMapper,
AttachmentExportMapper attachmentExportMapper); ExportExecutionDescriptor start(String execId, ReportExportOptions reportExportOptions); ExecutionStatus awaitReadyStatus(String execId, String exportId, String reportUri, long delay); ReportExportOutput downloadExport(String execId, String exportId); ResourceOutput downloadAttachment(String execId, String exportId, String attachmentId); }### Answer:
@Test public void testStart() throws Exception { when(mExportOptionsMapper.transform(any(ReportExportOptions.class))).thenReturn(mExecutionRequestOptions); ReportExportOptions criteria = FakeOptions.export(); exportExecutionApi.start(EXEC_ID, criteria); verify(mReportExportRestApi).runExportExecution(EXEC_ID, mExecutionRequestOptions); } |
### Question:
ExportExecutionApi { public ReportExportOutput downloadExport(String execId, String exportId) throws ServiceException { try { ExportOutputResource result = mReportExportRestApi.requestExportOutput(execId, exportId); return mReportExportMapper.transform(result); } catch (HttpException e) { throw mExceptionMapper.transform(e); } catch (IOException e) { throw mExceptionMapper.transform(e); } } ExportExecutionApi(ServiceExceptionMapper exceptionMapper,
ReportExportRestApi reportExportRestApi,
ExportOptionsMapper exportOptionsMapper,
ReportExportMapper reportExportMapper,
AttachmentExportMapper attachmentExportMapper); ExportExecutionDescriptor start(String execId, ReportExportOptions reportExportOptions); ExecutionStatus awaitReadyStatus(String execId, String exportId, String reportUri, long delay); ReportExportOutput downloadExport(String execId, String exportId); ResourceOutput downloadAttachment(String execId, String exportId, String attachmentId); }### Answer:
@Test public void testDownloadExport() throws Exception { when(mReportExportRestApi.requestExportOutput(anyString(), anyString())).thenReturn(export); exportExecutionApi.downloadExport(EXEC_ID, EXPORT_ID); verify(mReportExportRestApi).requestExportOutput(EXEC_ID, EXPORT_ID); verify(mReportExportMapper).transform(export); } |
### Question:
ExportExecutionApi { public ResourceOutput downloadAttachment(String execId, String exportId, String attachmentId) throws ServiceException { try { OutputResource result = mReportExportRestApi.requestExportAttachment(execId, exportId, attachmentId); return mAttachmentExportMapper.transform(result); } catch (HttpException e) { throw mExceptionMapper.transform(e); } catch (IOException e) { throw mExceptionMapper.transform(e); } } ExportExecutionApi(ServiceExceptionMapper exceptionMapper,
ReportExportRestApi reportExportRestApi,
ExportOptionsMapper exportOptionsMapper,
ReportExportMapper reportExportMapper,
AttachmentExportMapper attachmentExportMapper); ExportExecutionDescriptor start(String execId, ReportExportOptions reportExportOptions); ExecutionStatus awaitReadyStatus(String execId, String exportId, String reportUri, long delay); ReportExportOutput downloadExport(String execId, String exportId); ResourceOutput downloadAttachment(String execId, String exportId, String attachmentId); }### Answer:
@Test public void testDownloadAttachment() throws Exception { when(mReportExportRestApi.requestExportAttachment(anyString(), anyString(), anyString())).thenReturn(attachment); exportExecutionApi.downloadAttachment(EXEC_ID, EXPORT_ID, ATTACHMENT_ID); verify(mReportExportRestApi).requestExportAttachment(EXEC_ID, EXPORT_ID, ATTACHMENT_ID); verify(mAttachmentExportMapper).transform(attachment); } |
### Question:
ExportFactory { @NotNull public ReportExport create(ReportExecutionDescriptor descriptor, String execId, ExportIdWrapper exportIdWrapper) throws ServiceException { ExportDescriptor export = findExportDescriptor(descriptor, exportIdWrapper.getServerId()); if (export == null) { throw new ServiceException("Server returned malformed export details", null, StatusCodes.EXPORT_EXECUTION_FAILED); } List<ReportAttachment> attachments = mAttachmentsFactory.create(export, execId); return new ReportExport(mExportExecutionApi, attachments, execId, exportIdWrapper.getExactId()); } ExportFactory(ExportExecutionApi exportExecutionApi, AttachmentsFactory attachmentsFactory); @NotNull ReportExport create(ReportExecutionDescriptor descriptor, String execId, ExportIdWrapper exportIdWrapper); }### Answer:
@Test public void should_create_export_if_details_fulfilled() throws Exception { ReportExport result = exportFactory.create(mReportExecutionDescriptor, EXEC_ID, mExportIdWrapper); assertThat(result, is(notNullValue())); assertThat(result, is(instanceOf(ReportExport.class))); verify(mAttachmentsFactory).create(mExportDescriptor, EXEC_ID); }
@Test public void should_throw_if_details_missing() throws Exception { when(mExportDescriptor.getId()).thenReturn("123122"); try { exportFactory.create(mReportExecutionDescriptor, EXEC_ID, mExportIdWrapper); fail("Should throw ServiceException"); } catch (ServiceException ex) { assertThat(ex.getMessage(), is("Server returned malformed export details")); assertThat(ex.code(), is(StatusCodes.EXPORT_EXECUTION_FAILED)); } } |
### Question:
AbstractReportExecution extends ReportExecution { @NotNull @Override public final ReportMetadata waitForReportCompletion() throws ServiceException { mReportExecutionApi.awaitStatus(mExecId, mReportUri, mDelay, Status.ready()); ReportExecutionDescriptor reportDescriptor = mReportExecutionApi.getDetails(mExecId); return new ReportMetadata(mReportUri, reportDescriptor.getTotalPages()); } protected AbstractReportExecution(ReportExecutionApi reportExecutionApi,
String execId,
String reportUri,
long delay); @NotNull @Override final ReportMetadata waitForReportCompletion(); @NotNull @Override final ReportExport export(@NotNull ReportExportOptions options); @NotNull final ReportExecution updateExecution(@Nullable List<ReportParameter> newParameters); @NotNull @Override String getExecutionId(); }### Answer:
@Test public void testWaitForReportCompletion() throws Exception { ReportMetadata metadata = abstractReportExecution.waitForReportCompletion(); assertThat("Failed to create report metadata with exact total pages", metadata.getUri(), is(REPORT_URI)); assertThat("Failed to create report metadata with exact report uri", metadata.getTotalPages(), is(TOTAL_PAGES)); verify(mReportExecutionApi).awaitStatus(EXEC_ID, REPORT_URI, 0, Status.ready()); verify(mReportExecutionApi).getDetails(EXEC_ID); } |
### Question:
AbstractReportExecution extends ReportExecution { @NotNull @Override public final ReportExport export(@NotNull ReportExportOptions options) throws ServiceException { Preconditions.checkNotNull(options, "Export options should not be null"); return doExport(options); } protected AbstractReportExecution(ReportExecutionApi reportExecutionApi,
String execId,
String reportUri,
long delay); @NotNull @Override final ReportMetadata waitForReportCompletion(); @NotNull @Override final ReportExport export(@NotNull ReportExportOptions options); @NotNull final ReportExecution updateExecution(@Nullable List<ReportParameter> newParameters); @NotNull @Override String getExecutionId(); }### Answer:
@Test public void should_not_run_export_with_null_options() throws Exception { expected.expect(NullPointerException.class); expected.expectMessage("Export options should not be null"); abstractReportExecution.export(null); } |
### Question:
ExportOptionsMapper5_5 extends ExportOptionsMapper { @Override public ExecutionRequestOptions transform(ReportExportOptions criteria) { ExecutionRequestOptions options = super.transform(criteria); options.withIgnorePagination(null); options.withBaseUrl(null); options.withMarkupType(null); return options; } ExportOptionsMapper5_5(String baseUrl); @Override ExecutionRequestOptions transform(ReportExportOptions criteria); }### Answer:
@Test public void should_exclude_ignore_pagination_flag() throws Exception { ReportExportOptions criteria = ReportExportOptions.builder() .withFormat(ReportFormat.PDF) .withIgnorePagination(true) .build(); ExecutionRequestOptions options = mapper.transform(criteria); assertThat("Failed to remove 'ignorePagination' option", options.getIgnorePagination(), is(nullValue())); }
@Test public void should_exclude_base_url() throws Exception { ReportExportOptions criteria = ReportExportOptions.builder() .withFormat(ReportFormat.PDF) .withIgnorePagination(true) .build(); ExecutionRequestOptions options = mapper.transform(criteria); assertThat("Failed to remove 'baseUrl' option", options.getBaseUrl(), is(nullValue())); } |
### Question:
ProxyReportService extends ReportService { @NotNull @Override public ReportExecution run(@Nullable String reportUri, @Nullable ReportExecutionOptions execOptions) throws ServiceException { Preconditions.checkNotNull(reportUri, "Report uri should not be null"); if (execOptions == null) { execOptions = ReportExecutionOptions.builder().build(); } return getDelegate().run(reportUri, execOptions); } ProxyReportService(ReportServiceFactory serviceFactory); @NotNull @Override ReportExecution run(@Nullable String reportUri,
@Nullable ReportExecutionOptions execOptions); }### Answer:
@Test public void should_not_run_with_null_uri() throws Exception { expected.expect(NullPointerException.class); expected.expectMessage("Report uri should not be null"); proxyReportService.run(null, null); }
@Test public void should_delegate_run_call() throws Exception { proxyReportService.run(REPORT_URI, null); verify(mReportServiceFactory).newService(); verify(mReportService).run(eq(REPORT_URI), any(ReportExecutionOptions.class)); } |
### Question:
ReportService { @NotNull public static ReportService newService(@NotNull AuthorizedClient client) { Preconditions.checkNotNull(client, "Client should not be null"); InfoCacheManager cacheManager = InfoCacheManager.create(client); ServiceExceptionMapper reportMapper = ReportExceptionMapper.getInstance(); ReportServiceFactory reportServiceFactory = new ReportServiceFactory(cacheManager, client.reportExecutionApi(), client.reportExportApi(), reportMapper, client.getBaseUrl(), TimeUnit.SECONDS.toMillis(1) ); return new ProxyReportService(reportServiceFactory); } @NotNull abstract ReportExecution run(@NotNull String reportUri,
@Nullable ReportExecutionOptions execOptions); @NotNull static ReportService newService(@NotNull AuthorizedClient client); }### Answer:
@Test public void should_create_proxy_instance() throws Exception { ReportService service = ReportService.newService(mClient); assertThat("Should be instance of proxy service", service, is(instanceOf(ProxyReportService.class))); assertThat(service, is(notNullValue())); }
@Test public void should_reject_null_client() throws Exception { expected.expectMessage("Client should not be null"); expected.expect(NullPointerException.class); ReportService.newService(null); } |
### Question:
ReportExportMapper { public ReportExportOutput transform(final ExportOutputResource outputResource) { return new ReportExportOutput() { @Override public boolean isFinal() { return outputResource.isFinal(); } @Override public PageRange getPages() { return PageRange.parse(outputResource.getPages()); } @Override public InputStream getStream() throws IOException { return outputResource.getOutputResource().getStream(); } }; } ReportExportOutput transform(final ExportOutputResource outputResource); }### Answer:
@Test public void testTransform() throws Exception { when(mExportOutputResource.getPages()).thenReturn(TOTAL_PAGES); when(mExportOutputResource.isFinal()).thenReturn(Boolean.FALSE); when(mOutput.getStream()).thenReturn(mStream); when(mExportOutputResource.getOutputResource()).thenReturn(mOutput); ReportExportOutput export = mapper.transform(mExportOutputResource); assertThat(export.getPages(), is(PAGE_RANGE)); assertThat(export.isFinal(), is(Boolean.FALSE)); assertThat(export.getStream(), is(mStream)); } |
### Question:
InputControlRestApi { @NotNull public List<InputControlState> requestInputControlsStates(@NotNull String reportUri, @NotNull List<ReportParameter> parameters, boolean freshData) throws HttpException, IOException { Utils.checkNotNull(reportUri, "Report URI should not be null"); Utils.checkNotNull(parameters, "Parameters should not be null"); Map<String, Set<String>> params = ReportParamsMapper.INSTANCE.toMap(parameters); String ids = Utils.joinString(";", params.keySet()); HttpUrl url = new PathResolver.Builder() .addPath("rest_v2") .addPath("reports") .addPaths(reportUri) .addPath("inputControls") .addPath(ids) .addPath("values") .build() .resolve(mNetworkClient.getBaseUrl()) .newBuilder() .addQueryParameter("freshData", String.valueOf(freshData)) .build(); RequestBody jsonRequestBody = mNetworkClient.createJsonRequestBody(params); Request request = new Request.Builder() .addHeader("Accept", "application/json; charset=UTF-8") .post(jsonRequestBody) .url(url) .build(); Response response = mNetworkClient.makeCall(request); if (response.code() == 204) { return Collections.emptyList(); } InputControlStateCollection inputControlStateCollection = mNetworkClient.deserializeJson(response, InputControlStateCollection.class); return Collections.unmodifiableList(inputControlStateCollection.get()); } InputControlRestApi(NetworkClient networkClient); @NotNull List<InputControl> requestInputControls(@NotNull String reportUri,
@Nullable Set<String> controlIds,
boolean excludeState); @NotNull List<InputControlState> requestInputControlsInitialStates(@NotNull String reportUri,
boolean freshData); @NotNull List<InputControlState> requestInputControlsStates(@NotNull String reportUri,
@NotNull List<ReportParameter> parameters,
boolean freshData); }### Answer:
@Test public void requestInputControlsStatesShouldNotAllowNullReportUri() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Report URI should not be null"); restApiUnderTest.requestInputControlsStates(null, Collections.<ReportParameter>emptyList(), true); }
@Test public void requestInputControlsStatesShouldNotAllowNullControlParams() throws Exception { mExpectedException.expect(NullPointerException.class); mExpectedException.expectMessage("Parameters should not be null"); restApiUnderTest.requestInputControlsStates("any_id", null, true); }
@Test public void requestInputControlsStatesShouldThrowRestErrorFor500() throws Exception { mExpectedException.expect(HttpException.class); mWebMockRule.enqueue(MockResponseFactory.create500()); restApiUnderTest.requestInputControlsStates("any_id", Collections.<ReportParameter>emptyList(), true); }
@Test public void apiShouldProvideFreshStatesForInputControls() throws Exception { List<ReportParameter> parameters = Collections.singletonList( new ReportParameter("sales_fact_ALL__store_sales_2013_1", Collections.singleton("19"))); MockResponse mockResponse = MockResponseFactory.create200() .setBody(icsStates.asString()); mWebMockRule.enqueue(mockResponse); Collection<InputControlState> states = restApiUnderTest.requestInputControlsStates("/my/uri", parameters, true); assertThat(states, Matchers.is(not(Matchers.empty()))); RecordedRequest request = mWebMockRule.get().takeRequest(); assertThat(request, containsHeader("Accept", "application/json; charset=UTF-8")); assertThat(request, hasPath("/rest_v2/reports/my/uri/inputControls/sales_fact_ALL__store_sales_2013_1/values?freshData=true")); assertThat(request, wasMethod("POST")); }
@Test public void list_input_control_states_returns_empty_collection_on_204() throws Exception { mWebMockRule.enqueue(MockResponseFactory.create204()); List<InputControlState> expected = restApiUnderTest.requestInputControlsStates("/my/uri", Collections.<ReportParameter>emptyList(), false); assertThat(expected, Matchers.is(Matchers.empty())); } |
### Question:
ExportIdWrapper { public abstract String getExactId(); abstract String getServerId(); abstract String getExactId(); final void wrap(ExportExecutionDescriptor exportDetails, ReportExportOptions options); }### Answer:
@Test public void should_generate_specific_exact_id_for_5_5() throws Exception { giveExportDetailsWithId(); givenExportForFirstHtmlPage(); givenConfigured5_5Wrapper(); String exactId = mWrapper5_5.getExactId(); assertThat(exactId, is("HTML;pages=1")); }
@Test public void should_generate_specific_exact_id_for_5_6Plus() throws Exception { giveExportDetailsWithId(); givenExportForFirstHtmlPage(); givenConfigured5_6PlusWrapper(); String exactId = mWrapper5_6Plus.getExactId(); assertThat(exactId, is(EXPORT_ID)); } |
### Question:
ExportIdWrapper { public abstract String getServerId(); abstract String getServerId(); abstract String getExactId(); final void wrap(ExportExecutionDescriptor exportDetails, ReportExportOptions options); }### Answer:
@Test public void should_return_export_descriptor_id_for_5_5() throws Exception { giveExportDetailsWithId(); givenConfigured5_5Wrapper(); String serverId = mWrapper5_5.getServerId(); assertThat(serverId, is(EXPORT_ID)); }
@Test public void should_return_export_descriptor_id_for_5_6Plus() throws Exception { giveExportDetailsWithId(); givenConfigured5_6PlusWrapper(); String serverId = mWrapper5_6Plus.getServerId(); assertThat(serverId, is(EXPORT_ID)); } |
### Question:
RetryReportExecution extends ReportExecution { @NotNull @Override public ReportExport export(@NotNull ReportExportOptions options) throws ServiceException { try { return mDelegate.export(options); } catch (ServiceException ex) { boolean isCancelled = (ex.code() == StatusCodes.EXPORT_EXECUTION_CANCELLED || ex.code() == StatusCodes.REPORT_EXECUTION_CANCELLED); if (isCancelled) { return mDelegate.export(options); } throw ex; } } RetryReportExecution(ReportExecution delegate); @NotNull @Override ReportExport export(@NotNull ReportExportOptions options); @NotNull @Override ReportMetadata waitForReportCompletion(); @NotNull @Override ReportExecution updateExecution(@Nullable List<ReportParameter> newParameters); @NotNull @Override String getExecutionId(); }### Answer:
@Test public void should_retry_export_if_cancelled_on_first_run() throws Exception { when(mDelegate.export(any(ReportExportOptions.class))).then(crashOnFirstRun()); reportExecution.export(EXPORT_CRITERIA); verify(mDelegate, times(2)).export(EXPORT_CRITERIA); }
@Test(expected = ServiceException.class) public void should_throw_if_cancelled_on_second_run() throws Exception { when(mDelegate.export(any(ReportExportOptions.class))).thenThrow(CANCELLED_EXCEPTION); reportExecution.export(EXPORT_CRITERIA); } |
### Question:
RetryReportExecution extends ReportExecution { @NotNull @Override public ReportMetadata waitForReportCompletion() throws ServiceException { return mDelegate.waitForReportCompletion(); } RetryReportExecution(ReportExecution delegate); @NotNull @Override ReportExport export(@NotNull ReportExportOptions options); @NotNull @Override ReportMetadata waitForReportCompletion(); @NotNull @Override ReportExecution updateExecution(@Nullable List<ReportParameter> newParameters); @NotNull @Override String getExecutionId(); }### Answer:
@Test public void should_delegate_waitForReportCompletion() throws Exception { reportExecution.waitForReportCompletion(); verify(mDelegate).waitForReportCompletion(); } |
### Question:
RetryReportExecution extends ReportExecution { @NotNull @Override public ReportExecution updateExecution(@Nullable List<ReportParameter> newParameters) throws ServiceException { return mDelegate.updateExecution(newParameters); } RetryReportExecution(ReportExecution delegate); @NotNull @Override ReportExport export(@NotNull ReportExportOptions options); @NotNull @Override ReportMetadata waitForReportCompletion(); @NotNull @Override ReportExecution updateExecution(@Nullable List<ReportParameter> newParameters); @NotNull @Override String getExecutionId(); }### Answer:
@Test public void should_delegate_updateExecution() throws Exception { reportExecution.updateExecution(REPORT_PARAMS); verify(mDelegate).updateExecution(REPORT_PARAMS); } |
### Question:
AbstractReportService extends ReportService { @NotNull @Override public final ReportExecution run(@NotNull String reportUri, @NotNull ReportExecutionOptions execOptions) throws ServiceException { ReportExecutionDescriptor descriptor = mReportExecutionApi.start(reportUri, execOptions); String executionId = descriptor.getExecutionId(); mReportExecutionApi.awaitStatus(executionId, reportUri, mDelay, Status.execution(), Status.ready()); return buildExecution(reportUri, executionId, execOptions); } protected AbstractReportService(ExportExecutionApi exportExecutionApi,
ReportExecutionApi reportExecutionApi,
ExportFactory exportFactory,
long delay); @NotNull @Override final ReportExecution run(@NotNull String reportUri, @NotNull ReportExecutionOptions execOptions); }### Answer:
@Test public void testRun() throws Exception { ReportExecutionOptions criteria = ReportExecutionOptions.builder().build(); reportService.run(REPORT_URI, criteria); verify(mReportExecutionApi).start(REPORT_URI, criteria); verify(mReportExecutionApi).awaitStatus(EXEC_ID, REPORT_URI, 0, execution(), ready()); verify(reportService).buildExecution(REPORT_URI, EXEC_ID, criteria); } |
### Question:
AttachmentExportMapper { public ResourceOutput transform(final OutputResource resource) { return new ResourceOutput() { @Override public InputStream getStream() throws IOException { return resource.getStream(); } }; } ResourceOutput transform(final OutputResource resource); }### Answer:
@Test public void testTransform() throws Exception { when(mOutputResource.getStream()).thenReturn(mStream); ResourceOutput result = mapper.transform(mOutputResource); assertThat(result.getStream(), is(mStream)); } |
### Question:
InputControlRestApi { @NotNull public List<InputControlState> requestInputControlsInitialStates(@NotNull String reportUri, boolean freshData) throws IOException, HttpException { Utils.checkNotNull(reportUri, "Report URI should not be null"); HttpUrl url = new PathResolver.Builder() .addPath("rest_v2") .addPath("reports") .addPaths(reportUri) .addPath("inputControls") .addPath("values") .build() .resolve(mNetworkClient.getBaseUrl()) .newBuilder() .addQueryParameter("freshData", String.valueOf(freshData)) .build(); Request request = new Request.Builder() .addHeader("Accept", "application/json; charset=UTF-8") .get() .url(url) .build(); Response response = mNetworkClient.makeCall(request); if (response.code() == 204) { return Collections.emptyList(); } InputControlStateCollection inputControlStateCollection = mNetworkClient.deserializeJson(response, InputControlStateCollection.class); return Collections.unmodifiableList(inputControlStateCollection.get()); } InputControlRestApi(NetworkClient networkClient); @NotNull List<InputControl> requestInputControls(@NotNull String reportUri,
@Nullable Set<String> controlIds,
boolean excludeState); @NotNull List<InputControlState> requestInputControlsInitialStates(@NotNull String reportUri,
boolean freshData); @NotNull List<InputControlState> requestInputControlsStates(@NotNull String reportUri,
@NotNull List<ReportParameter> parameters,
boolean freshData); }### Answer:
@Test public void requestInputControlsInitialStatesShouldThrowRestErrorFor500() throws Exception { mExpectedException.expect(HttpException.class); mWebMockRule.enqueue(MockResponseFactory.create500()); restApiUnderTest.requestInputControlsInitialStates("any_id", true); }
@Test public void apiShouldProvideListOfInputControlsInitialStatesWithFreshData() throws Exception { MockResponse mockResponse = MockResponseFactory.create200() .setBody(icsStates.asString()); mWebMockRule.enqueue(mockResponse); Collection<InputControlState> states = restApiUnderTest.requestInputControlsInitialStates("/my/uri", true); assertThat(states, is(not(empty()))); RecordedRequest request = mWebMockRule.get().takeRequest(); assertThat(request, containsHeader("Accept", "application/json; charset=UTF-8")); assertThat(request, hasPath("/rest_v2/reports/my/uri/inputControls/values?freshData=true")); assertThat(request, wasMethod("GET")); }
@Test public void list_input_control_initial_states_returns_empty_collection_on_204() throws Exception { mWebMockRule.enqueue(MockResponseFactory.create204()); List<InputControlState> expected = restApiUnderTest.requestInputControlsInitialStates("/my/uri", false); assertThat(expected, Matchers.is(Matchers.empty())); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.