org.springframework.jms.core.SessionCallback Java Examples

The following examples show how to use org.springframework.jms.core.SessionCallback. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JmsTransactionManagerTests.java    From java-technology-stack with MIT License 7 votes vote down vote up
@Test
public void testTransactionRollback() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute(new SessionCallback<Void>() {
		@Override
		public Void doInJms(Session sess) {
			assertTrue(sess == session);
			return null;
		}
	});
	tm.rollback(ts);

	verify(session).rollback();
	verify(session).close();
	verify(con).close();
}
 
Example #2
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testTransactionRollback() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	tm.rollback(ts);

	verify(session).rollback();
	verify(session).close();
	verify(con).close();
}
 
Example #3
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testTransactionCommit() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(con).close();
}
 
Example #4
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testSuspendedTransaction() throws JMSException {
	final ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);
	final Session session2 = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);
	given(con.createSession(false, Session.AUTO_ACKNOWLEDGE)).willReturn(session2);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	final JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			jt.execute((SessionCallback<Void>) sess -> {
				assertNotSame(sess, session);
				return null;
			});
		}
	});
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(session2).close();
	verify(con, times(2)).close();
}
 
Example #5
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testLazyTransactionalSession() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	tm.setLazyResourceRetrieval(true);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(con).close();
}
 
Example #6
Source File: JmsTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testTransactionCommit() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute(new SessionCallback<Void>() {
		@Override
		public Void doInJms(Session sess) {
			assertTrue(sess == session);
			return null;
		}
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(con).close();
}
 
Example #7
Source File: JmsTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionCommit() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute(new SessionCallback<Void>() {
		@Override
		public Void doInJms(Session sess) {
			assertTrue(sess == session);
			return null;
		}
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(con).close();
}
 
Example #8
Source File: JmsTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionRollback() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute(new SessionCallback<Void>() {
		@Override
		public Void doInJms(Session sess) {
			assertTrue(sess == session);
			return null;
		}
	});
	tm.rollback(ts);

	verify(session).rollback();
	verify(session).close();
	verify(con).close();
}
 
Example #9
Source File: BatchedJmsTemplate.java    From jadira with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Message receiveSelected(final String destinationName, final String messageSelector) throws JmsException {
    return execute(new SessionCallback<Message>() {
        public Message doInJms(Session session) throws JMSException {
            Destination destination = resolveDestinationName(session, destinationName);
            return doSingleReceive(session, destination, messageSelector);
        }
    }, true);
}
 
Example #10
Source File: BatchedJmsTemplate.java    From jadira with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Message receiveSelected(final Destination destination, final String messageSelector) throws JmsException {
    return execute(new SessionCallback<Message>() {
        public Message doInJms(Session session) throws JMSException {

            return doSingleReceive(session, destination, messageSelector);
        }
    }, true);
}
 
Example #11
Source File: BatchedJmsTemplate.java    From jadira with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Message receive(final String destinationName) throws JmsException {
    return execute(new SessionCallback<Message>() {
        public Message doInJms(Session session) throws JMSException {
            Destination destination = resolveDestinationName(session, destinationName);
            return doSingleReceive(session, destination, null);
        }
    }, true);
}
 
Example #12
Source File: BatchedJmsTemplate.java    From jadira with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Message receive(final Destination destination) throws JmsException {
    return execute(new SessionCallback<Message>() {
        public Message doInJms(Session session) throws JMSException {
            return doSingleReceive(session, destination, null);
        }
    }, true);
}
 
Example #13
Source File: BatchedJmsTemplate.java    From jadira with Apache License 2.0 5 votes vote down vote up
/**
 * Receive a batch of up to batchSize for given destination name and message selector. Other than batching this method is the same as {@link JmsTemplate#receiveSelected(String, String)}
 * @return A list of {@link Message}
 * @param destinationName The destination name
 * @param messageSelector The Selector
 * @param batchSize The batch size
 * @throws JmsException The {@link JmsException}
 */
public List<Message> receiveSelectedBatch(final String destinationName, final String messageSelector,
        final int batchSize) throws JmsException {
    return execute(new SessionCallback<List<Message>>() {
        public List<Message> doInJms(Session session) throws JMSException {
            Destination destination = resolveDestinationName(session, destinationName);
            return doBatchReceive(session, destination, messageSelector, batchSize);
        }
    }, true);
}
 
Example #14
Source File: BatchedJmsTemplate.java    From jadira with Apache License 2.0 5 votes vote down vote up
/**
 * Receive a batch of up to batchSize for given destination and message selector. Other than batching this method is the same as {@link JmsTemplate#receiveSelected(Destination, String)}
 * @return A list of {@link Message}
 * @param destination The Destination
 * @param messageSelector The Selector
 * @param batchSize The batch size
 * @throws JmsException The {@link JmsException}
 */
public List<Message> receiveSelectedBatch(final Destination destination, final String messageSelector,
        final int batchSize) throws JmsException {
    return execute(new SessionCallback<List<Message>>() {
        public List<Message> doInJms(Session session) throws JMSException {

            return doBatchReceive(session, destination, messageSelector, batchSize);
        }
    }, true);
}
 
Example #15
Source File: BatchedJmsTemplate.java    From jadira with Apache License 2.0 5 votes vote down vote up
/**
 * Receive a batch of up to default batch size for given destination. Other than batching this method is the same as {@link JmsTemplate#receive(String)}
 * @return A list of {@link Message}
 * @param destinationName The Destination
 * @param batchSize The batch size
 * @throws JmsException The {@link JmsException}
 */
public List<Message> receiveBatch(final String destinationName, final int batchSize) throws JmsException {
    return execute(new SessionCallback<List<Message>>() {
        public List<Message> doInJms(Session session) throws JMSException {
            Destination destination = resolveDestinationName(session, destinationName);
            return doBatchReceive(session, destination, null, batchSize);
        }
    }, true);
}
 
Example #16
Source File: BatchedJmsTemplate.java    From jadira with Apache License 2.0 5 votes vote down vote up
/**
 * Receive a batch of up to batchSize for given destination. Other than batching this method is the same as {@link JmsTemplate#receive(Destination)}
 * @return A list of {@link Message}
 * @param destination The Destination
 * @param batchSize The batch size
 * @throws JmsException The {@link JmsException}
 */
public List<Message> receiveBatch(final Destination destination, final int batchSize) throws JmsException {
    return execute(new SessionCallback<List<Message>>() {
        public List<Message> doInJms(Session session) throws JMSException {
            return doBatchReceive(session, destination, null, batchSize);
        }
    }, true);
}
 
Example #17
Source File: ProcessCommunicationManagerTest.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Tests request is sent and response is processed. Connects to in-memory
 * broker.
 */
@Test
public void testConfigurationRequest() throws Exception {
  //fake DAQ responding to request
  final JmsTemplate daqTemplate = new JmsTemplate(connectionFactory);
  new Thread(new Runnable() {

    @Override
    public void run() {
      try {
        daqTemplate.execute(new SessionCallback<Object>() {
          String reportString = MessageConverter.responseToJson(new ConfigurationChangeEventReport());
          @Override
          public Object doInJms(Session session) throws JMSException {
            Process process = processCache.get(50L);
            String jmsDaqQueue = "c2mon.process" + ".command." + process.getCurrentHost() + "." + process.getName() + "." + process.getProcessPIK();
            MessageConsumer consumer = session.createConsumer(new ActiveMQQueue(jmsDaqQueue));
            Message incomingMessage = consumer.receive(1000);
            MessageProducer messageProducer = session.createProducer(incomingMessage.getJMSReplyTo());
            TextMessage replyMessage = session.createTextMessage();
            replyMessage.setText(reportString);
            messageProducer.send(replyMessage);
            return null;
          }
        }, true); //start connection
      } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
      }
    }
  }).start();

  //test report is picked up correctly
  ConfigurationChangeEventReport report = processCommunicationManager.sendConfiguration(50L, Collections.EMPTY_LIST);
  assertNotNull(report);

}
 
Example #18
Source File: JmsProxyTest.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Tests the sending of a request to the server and receiving a response
 * (decodes response and checks non null).
 *
 * Start a new thread to mimick the server response to a client request.
 * @throws JMSException
 * @throws InterruptedException
 */
@Test
public void testSendRequest() throws JMSException, InterruptedException {
  JsonRequest<SupervisionEvent> jsonRequest = new ClientRequestImpl<>(SupervisionEvent.class);
  final String queueName = properties.getJms().getRequestQueue() + "-" + System.currentTimeMillis();
  new Thread(new Runnable() {
    @Override
    public void run() {
      serverTemplate.execute(new SessionCallback<Object>() {

        @Override
        public Object doInJms(Session session) throws JMSException {
          MessageConsumer consumer = session.createConsumer(new ActiveMQQueue(queueName));
          Message message = consumer.receive(10000);
          Assert.assertNotNull(message);
          Assert.assertTrue(message instanceof TextMessage);
          //send some response (empty collection)
          Collection<SupervisionEvent> supervisionEvents = new ArrayList<>();
          supervisionEvents.add(new SupervisionEventImpl(SupervisionEntity.PROCESS, 1L, "P_TEST", SupervisionStatus.RUNNING, new Timestamp(System.currentTimeMillis()), "test response"));
          Message replyMessage = session.createTextMessage(GsonFactory.createGson().toJson(supervisionEvents));
          MessageProducer producer = session.createProducer(message.getJMSReplyTo());
          producer.send(replyMessage);
          return null;
        }

      }, true);
    }
  }).start();
  Collection<SupervisionEvent> response = jmsProxy.sendRequest(jsonRequest, queueName, 10000); //wait 10s for an answer
  Assert.assertNotNull(response);
}
 
Example #19
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testTransactionSuspension() throws JMSException {
	final ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);
	final Session session2 = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session, session2);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	final JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			jt.execute((SessionCallback<Void>) sess -> {
				assertNotSame(sess, session);
				return null;
			});
		}
	});
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session2).commit();
	verify(session).close();
	verify(session2).close();
	verify(con, times(2)).close();
}
 
Example #20
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testParticipatingTransactionWithRollbackOnly() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	final JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			jt.execute((SessionCallback<Void>) sess -> {
				assertSame(sess, session);
				return null;
			});
			status.setRollbackOnly();
		}
	});
	try {
		tm.commit(ts);
		fail("Should have thrown UnexpectedRollbackException");
	}
	catch (UnexpectedRollbackException ex) {
		// expected
	}

	verify(session).rollback();
	verify(session).close();
	verify(con).close();
}
 
Example #21
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testParticipatingTransactionWithCommit() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	final JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			jt.execute((SessionCallback<Void>) sess -> {
				assertSame(sess, session);
				return null;
			});
		}
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(con).close();
}
 
Example #22
Source File: JMSConsumer.java    From nifi with Apache License 2.0 4 votes vote down vote up
public void consume(final String destinationName, String errorQueueName, final boolean durable, final boolean shared, final String subscriberName, final String charset,
                    final ConsumerCallback consumerCallback) {
    this.jmsTemplate.execute(new SessionCallback<Void>() {
        @Override
        public Void doInJms(final Session session) throws JMSException {

            final MessageConsumer msgConsumer = createMessageConsumer(session, destinationName, durable, shared, subscriberName);
            try {
                final Message message = msgConsumer.receive(JMSConsumer.this.jmsTemplate.getReceiveTimeout());
                JMSResponse response = null;

                if (message != null) {
                    String messageType;
                    byte[] messageBody;

                    try {
                        if (message instanceof TextMessage) {
                            messageType = TextMessage.class.getSimpleName();
                            messageBody = MessageBodyToBytesConverter.toBytes((TextMessage) message, Charset.forName(charset));
                        } else if (message instanceof BytesMessage) {
                            messageType = BytesMessage.class.getSimpleName();
                            messageBody = MessageBodyToBytesConverter.toBytes((BytesMessage) message);
                        } else if (message instanceof ObjectMessage) {
                            messageType = ObjectMessage.class.getSimpleName();
                            messageBody = MessageBodyToBytesConverter.toBytes((ObjectMessage) message);
                        } else if (message instanceof StreamMessage) {
                            messageType = StreamMessage.class.getSimpleName();
                            messageBody = MessageBodyToBytesConverter.toBytes((StreamMessage) message);
                        } else if (message instanceof MapMessage) {
                            messageType = MapMessage.class.getSimpleName();
                            messageBody = MessageBodyToBytesConverter.toBytes((MapMessage) message);
                        } else {
                            acknowledge(message, session);

                            if (errorQueueName != null) {
                                processLog.error("Received unsupported JMS Message type [{}]; rerouting message to error queue [{}].", new Object[] {message, errorQueueName});
                                jmsTemplate.send(errorQueueName, __ -> message);
                            } else {
                                processLog.error("Received unsupported JMS Message type [{}]; will skip this message.", new Object[] {message});
                            }

                            return null;
                        }
                    } catch (final MessageConversionException mce) {
                        processLog.error("Received a JMS Message [{}] but failed to obtain the content of the message; will acknowledge this message without creating a FlowFile for it.",
                            new Object[] {message}, mce);
                        acknowledge(message, session);

                        if (errorQueueName != null) {
                            jmsTemplate.send(errorQueueName, __ -> message);
                        }

                        return null;
                    }

                    final Map<String, String> messageHeaders = extractMessageHeaders(message);
                    final Map<String, String> messageProperties = extractMessageProperties(message);
                    response = new JMSResponse(messageType, messageBody, messageHeaders, messageProperties);
                }

                // invoke the processor callback (regardless if it's null,
                // so the processor can yield) as part of this inJMS call
                // and ACK message *only* after its successful invocation
                // and if CLIENT_ACKNOWLEDGE is set.
                consumerCallback.accept(response);
                acknowledge(message, session);
            } catch (Exception e) {
                // We need to call recover to ensure that in the event of
                // abrupt end or exception the current session will stop message
                // delivery and restart with the oldest unacknowledged message
                try {
                    session.recover();
                } catch (Exception e1) {
                    // likely the session is closed...need to catch this so that the root cause of failure is propagated
                    processLog.debug("Failed to recover JMS session while handling initial error. The recover error is: ", e1);
                }
                throw e;
            } finally {
                JmsUtils.closeMessageConsumer(msgConsumer);
            }

            return null;
        }
    }, true);
}
 
Example #23
Source File: JmsProxyTest.java    From c2mon with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Tests error reports are correctly processed. Fakes a sequence of progress reports back from the
 * server followed by an error report.
 *
 * @throws JMSException
 */
@Test
public void testErrorReportProcessing() throws JMSException {
  ClientRequestReportListener reportListener = EasyMock.createMock(ClientRequestReportListener.class);
  reportListener.onProgressReportReceived(EasyMock.isA(ClientRequestProgressReport.class));
  EasyMock.expectLastCall().times(3);
  reportListener.onErrorReportReceived(EasyMock.isA(ClientRequestErrorReport.class));

  EasyMock.replay(reportListener);

  ClientRequestImpl<ConfigurationReport> jsonRequest = new ClientRequestImpl<>(ConfigurationReport.class);
  final String queueName = properties.getJms().getRequestQueue() + "-" + System.currentTimeMillis();
  new Thread(new Runnable() {
    @Override
    public void run() {
      serverTemplate.execute(new SessionCallback<Object>() {

        @Override
        public Object doInJms(Session session) throws JMSException {
          MessageConsumer consumer = session.createConsumer(new ActiveMQQueue(queueName));
          Message message = consumer.receive(10000);
          Assert.assertNotNull(message);
          Assert.assertTrue(message instanceof TextMessage);

          //send progress reports
          MessageProducer producer = session.createProducer(message.getJMSReplyTo());
          Collection<ConfigurationReport> configReport = new ArrayList<>();
          configReport.add(new ConfigurationReport(10, 5, 20, 2, "fake progress"));
          Message replyMessage = session.createTextMessage(GsonFactory.createGson().toJson(configReport));
          producer.send(replyMessage);

          configReport.clear();
          configReport.add(new ConfigurationReport(1, 1, 2, 1, "fake progress"));
          replyMessage = session.createTextMessage(GsonFactory.createGson().toJson(configReport));
          producer.send(replyMessage);

          configReport.clear();
          configReport.add(new ConfigurationReport(10, 6, 22, 10, "fake progress"));
          replyMessage = session.createTextMessage(GsonFactory.createGson().toJson(configReport));
          producer.send(replyMessage);

          //send result
          configReport.clear();
          configReport.add(new ConfigurationReport(false, "error occurred"));
          replyMessage = session.createTextMessage(GsonFactory.createGson().toJson(configReport));
          producer.send(replyMessage);
          return null;
        }

      }, true);
    }
  }).start();
  boolean exceptionCaught = false;
  Collection<ConfigurationReport> response = null;
  try {
    response = jmsProxy.sendRequest(jsonRequest, queueName, 10000, reportListener); //wait 10s for an answer
  } catch (RuntimeException e) {
    exceptionCaught = true;
    assertTrue(e.getMessage().endsWith("error occurred"));
  }
  assertTrue(exceptionCaught);
  assertNull(response);

  EasyMock.verify(reportListener);

}
 
Example #24
Source File: JmsProxyTest.java    From c2mon with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Tests client requests with intermediate progress reports are processed and notify listener
 * correctly. Fakes server response with some progress reports followed by the result.
 * @throws JMSException
 */
@Test
public void testProgressReportProcessing() throws JMSException {
  ClientRequestReportListener reportListener = EasyMock.createMock(ClientRequestReportListener.class);
  reportListener.onProgressReportReceived(EasyMock.isA(ClientRequestProgressReport.class));
  EasyMock.expectLastCall().times(3);

  EasyMock.replay(reportListener);

  ClientRequestImpl<ConfigurationReport> jsonRequest = new ClientRequestImpl<>(ConfigurationReport.class);
  final String queueName = properties.getJms().getRequestQueue() + "-" + System.currentTimeMillis();
  new Thread(new Runnable() {
    @Override
    public void run() {
      serverTemplate.execute(new SessionCallback<Object>() {

        @Override
        public Object doInJms(Session session) throws JMSException {
          MessageConsumer consumer = session.createConsumer(new ActiveMQQueue(queueName));
          Message message = consumer.receive(10000);
          Assert.assertNotNull(message);
          Assert.assertTrue(message instanceof TextMessage);

          //send progress reports
          MessageProducer producer = session.createProducer(message.getJMSReplyTo());
          Collection<ConfigurationReport> configReport = new ArrayList<>();
          configReport.add(new ConfigurationReport(10, 5, 20, 2, "fake progress"));
          Message replyMessage = session.createTextMessage(GsonFactory.createGson().toJson(configReport));
          producer.send(replyMessage);

          configReport.clear();
          configReport.add(new ConfigurationReport(1, 1, 2, 1, "fake progress"));
          replyMessage = session.createTextMessage(GsonFactory.createGson().toJson(configReport));
          producer.send(replyMessage);

          configReport.clear();
          configReport.add(new ConfigurationReport(10, 6, 22, 10, "fake progress"));
          replyMessage = session.createTextMessage(GsonFactory.createGson().toJson(configReport));
          producer.send(replyMessage);

          //send result
          configReport.clear();
          configReport.add(new ConfigurationReport(10L, "name", "user"));
          replyMessage = session.createTextMessage(GsonFactory.createGson().toJson(configReport));
          producer.send(replyMessage);
          return null;
        }

      }, true);
    }
  }).start();
  Collection<ConfigurationReport> response = jmsProxy.sendRequest(jsonRequest, queueName, 10000, reportListener); //wait 10s for an answer
  Assert.assertNotNull(response);
  Assert.assertTrue(response.iterator().next().isResult());

  EasyMock.verify(reportListener);

}
 
Example #25
Source File: JMSConsumer.java    From solace-integration-guides with Apache License 2.0 4 votes vote down vote up
/**
 *
 */
public void consume(final String destinationName, final ConsumerCallback consumerCallback) {
    this.jmsTemplate.execute(new SessionCallback<Void>() {
        @Override
        public Void doInJms(Session session) throws JMSException {
            /*
             * We need to call recover to ensure that in in the event of
             * abrupt end or exception the current session will stop message
             * delivery and restarts with the oldest unacknowledged message
             */
            session.recover();
            Destination destination = JMSConsumer.this.jmsTemplate.getDestinationResolver().resolveDestinationName(
                    session, destinationName, JMSConsumer.this.jmsTemplate.isPubSubDomain());
            MessageConsumer msgConsumer = session.createConsumer(destination, null,
                    JMSConsumer.this.jmsTemplate.isPubSubDomain());
            Message message = msgConsumer.receive(JMSConsumer.this.jmsTemplate.getReceiveTimeout());
            JMSResponse response = null;
            try {
                if (message != null) {
                    byte[] messageBody = null;
                    if (message instanceof TextMessage) {
                        messageBody = MessageBodyToBytesConverter.toBytes((TextMessage) message);
                    } else if (message instanceof BytesMessage) {
                        messageBody = MessageBodyToBytesConverter.toBytes((BytesMessage) message);
                    } else {
                        throw new IllegalStateException("Message type other then TextMessage and BytesMessage are "
                                + "not supported at the moment");
                    }
                    Map<String, Object> messageHeaders = extractMessageHeaders(message);
                    Map<String, String> messageProperties = extractMessageProperties(message);
                    response = new JMSResponse(messageBody, messageHeaders, messageProperties);
                    if (logger.isDebugEnabled())
                        logger.debug("message received : " + message.toString());                        
                }
                // invoke the processor callback (regardless if it's null,
                // so the processor can yield) as part of this inJMS call
                // and ACK message *only* after its successful invocation
                // and if CLIENT_ACKNOWLEDGE is set.
                consumerCallback.accept(response);
                if (message != null && session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE) {
                    message.acknowledge();
                }
            } finally {
                JmsUtils.closeMessageConsumer(msgConsumer);
            }
            return null;
        }
    }, true);
}
 
Example #26
Source File: JMSConsumer.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 *
 */
public void consume(final String destinationName, final ConsumerCallback consumerCallback) {
    this.jmsTemplate.execute(new SessionCallback<Void>() {
        @Override
        public Void doInJms(Session session) throws JMSException {
            /*
             * We need to call recover to ensure that in in the event of
             * abrupt end or exception the current session will stop message
             * delivery and restarts with the oldest unacknowledged message
             */
            session.recover();
            Destination destination = JMSConsumer.this.jmsTemplate.getDestinationResolver().resolveDestinationName(
                    session, destinationName, JMSConsumer.this.jmsTemplate.isPubSubDomain());
            MessageConsumer msgConsumer = session.createConsumer(destination, null,
                    JMSConsumer.this.jmsTemplate.isPubSubDomain());
            Message message = msgConsumer.receive(JMSConsumer.this.jmsTemplate.getReceiveTimeout());
            JMSResponse response = null;
            try {
                if (message != null) {
                    byte[] messageBody = null;
                    if (message instanceof TextMessage) {
                        messageBody = MessageBodyToBytesConverter.toBytes((TextMessage) message);
                    } else if (message instanceof BytesMessage) {
                        messageBody = MessageBodyToBytesConverter.toBytes((BytesMessage) message);
                    } else {
                        throw new IllegalStateException("Message type other then TextMessage and BytesMessage are "
                                + "not supported at the moment");
                    }
                    Map<String, Object> messageHeaders = extractMessageHeaders(message);
                    Map<String, String> messageProperties = extractMessageProperties(message);
                    response = new JMSResponse(messageBody, messageHeaders, messageProperties);
                }
                // invoke the processor callback (regardless if it's null,
                // so the processor can yield) as part of this inJMS call
                // and ACK message *only* after its successful invocation
                // and if CLIENT_ACKNOWLEDGE is set.
                consumerCallback.accept(response);
                if (message != null && session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE) {
                    message.acknowledge();
                }
            } finally {
                JmsUtils.closeMessageConsumer(msgConsumer);
            }
            return null;
        }
    }, true);
}