下面列出了javax.jms.QueueConnection#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testWithQueueConnection() throws JMSException {
Connection con = mock(QueueConnection.class);
SingleConnectionFactory scf = new SingleConnectionFactory(con);
QueueConnection con1 = scf.createQueueConnection();
con1.start();
con1.stop();
con1.close();
QueueConnection con2 = scf.createQueueConnection();
con2.start();
con2.stop();
con2.close();
scf.destroy(); // should trigger actual close
verify(con, times(2)).start();
verify(con, times(2)).stop();
verify(con).close();
verifyNoMoreInteractions(con);
}
@Test
public void testWithQueueConnection() throws JMSException {
Connection con = mock(QueueConnection.class);
SingleConnectionFactory scf = new SingleConnectionFactory(con);
QueueConnection con1 = scf.createQueueConnection();
con1.start();
con1.stop();
con1.close();
QueueConnection con2 = scf.createQueueConnection();
con2.start();
con2.stop();
con2.close();
scf.destroy(); // should trigger actual close
verify(con, times(2)).start();
verify(con, times(2)).stop();
verify(con).close();
verifyNoMoreInteractions(con);
}
@Test
public void testConnectionCredentialsFail() throws Exception {
resourceAdapter = newResourceAdapter();
MyBootstrapContext ctx = new MyBootstrapContext();
resourceAdapter.start(ctx);
ActiveMQRAManagedConnectionFactory mcf = new ActiveMQRAManagedConnectionFactory();
mcf.setResourceAdapter(resourceAdapter);
ActiveMQRAConnectionFactory qraConnectionFactory = new ActiveMQRAConnectionFactoryImpl(mcf, qraConnectionManager);
QueueConnection queueConnection = qraConnectionFactory.createQueueConnection();
QueueSession session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
ManagedConnection mc = ((ActiveMQRASession) session).getManagedConnection();
queueConnection.close();
mc.destroy();
try {
queueConnection = qraConnectionFactory.createQueueConnection("testuser", "testwrongpassword");
queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE).close();
fail("should throw esxception");
} catch (JMSException e) {
//pass
}
}
@Test
public void createReceiver() throws Exception
{
Queue queue = createQueue(getTestName());
QueueConnection queueConnection = getQueueConnection();
try
{
queueConnection.start();
Utils.sendMessages(queueConnection, queue, 3);
QueueSession session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
QueueReceiver receiver = session.createReceiver(queue, String.format("%s=2", INDEX));
assertEquals("Queue names should match from QueueReceiver", queue.getQueueName(), receiver.getQueue().getQueueName());
Message received = receiver.receive(getReceiveTimeout());
assertNotNull("Message is not received", received);
assertEquals("Unexpected message is received", 2, received.getIntProperty(INDEX));
}
finally
{
queueConnection.close();
}
}
@Test
public void testQueueSessionCannotCreateTopics() throws Exception
{
QueueConnection queueConnection = getQueueConnection();
try
{
QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
try
{
queueSession.createTopic("abc");
fail("expected exception did not occur");
}
catch (javax.jms.IllegalStateException s)
{
// PASS
}
}
finally
{
queueConnection.close();
}
}
@Test
public void testQueueSessionCannotCreateDurableSubscriber() throws Exception
{
Topic topic = createTopic(getTestName());
QueueConnection queueConnection = getQueueConnection();
try
{
QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
try
{
queueSession.createDurableSubscriber(topic, "abc");
fail("expected exception did not occur");
}
catch (javax.jms.IllegalStateException s)
{
// PASS
}
}
finally
{
queueConnection.close();
}
}
@Test
public void testQueueSessionCannotUnsubscribe() throws Exception
{
QueueConnection queueConnection = getQueueConnection();
try
{
QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
try
{
queueSession.unsubscribe("abc");
fail("expected exception did not occur");
}
catch (javax.jms.IllegalStateException s)
{
// PASS
}
}
finally
{
queueConnection.close();
}
}
private void sendBytesMessage(String destName, byte[] buffer) throws Exception {
InitialContext ic = getInitialContext();
QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) ic.lookup("ConnectionFactory");
QueueConnection connection = queueConnectionFactory.createQueueConnection();
QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
BytesMessage bm = session.createBytesMessage();
bm.writeBytes(buffer);
QueueSender sender = session.createSender((Queue) ic.lookup(destName));
sender.send(bm);
sender.close();
session.close();
connection.close();
}
@Test
public void testCachingConnectionFactoryWithQueueConnectionFactoryAndJms102Usage() throws JMSException {
QueueConnectionFactory cf = mock(QueueConnectionFactory.class);
QueueConnection con = mock(QueueConnection.class);
QueueSession txSession = mock(QueueSession.class);
QueueSession nonTxSession = mock(QueueSession.class);
given(cf.createQueueConnection()).willReturn(con);
given(con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession);
given(txSession.getTransacted()).willReturn(true);
given(con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession);
CachingConnectionFactory scf = new CachingConnectionFactory(cf);
scf.setReconnectOnException(false);
Connection con1 = scf.createQueueConnection();
Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
session1.rollback();
session1.close();
session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
session1.close();
con1.start();
QueueConnection con2 = scf.createQueueConnection();
Session session2 = con2.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
session2.close();
session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
session2.getTransacted();
session2.close(); // should lead to rollback
con2.start();
con1.close();
con2.close();
scf.destroy(); // should trigger actual close
verify(txSession).rollback();
verify(txSession).close();
verify(nonTxSession).close();
verify(con).start();
verify(con).stop();
verify(con).close();
}
@Test
public void testCreateTopicOnAQueueSession() throws Exception {
QueueConnection c = (QueueConnection) getConnectionFactory().createConnection();
QueueSession s = c.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
try {
s.createTopic("TestTopic");
ProxyAssertSupport.fail("should throw IllegalStateException");
} catch (javax.jms.IllegalStateException e) {
// OK
}
c.close();
}
@Test(timeout = 60000)
public void testQueueCreateConnection() throws Exception {
QueueConnection connection = cf.createQueueConnection();
assertNotNull(connection);
assertEquals(1, cf.getNumConnections());
connection.close();
assertEquals(1, cf.getNumConnections());
}
@Test(timeout = 60000)
public void testQueueCreateConnectionWithCredentials() throws Exception {
QueueConnection connection = cf.createQueueConnection("user", "pass");
assertNotNull(connection);
assertEquals(1, cf.getNumConnections());
connection.close();
assertEquals(1, cf.getNumConnections());
}
/**
* Test that ConnectionFactory can be cast to QueueConnectionFactory and QueueConnection can be
* created.
*/
@Test
public void testQueueConnectionFactory() throws Exception {
deployConnectionFactory(0, JMSFactoryType.QUEUE_CF, "CF_QUEUE_XA_FALSE", "/CF_QUEUE_XA_FALSE");
QueueConnectionFactory qcf = (QueueConnectionFactory) ic.lookup("/CF_QUEUE_XA_FALSE");
QueueConnection qc = qcf.createQueueConnection();
qc.close();
undeployConnectionFactory("CF_QUEUE_XA_FALSE");
}
@Test
public void testCreateQueueConnection() throws Exception {
ActiveMQJAASSecurityManager securityManager = (ActiveMQJAASSecurityManager) server.getSecurityManager();
securityManager.getConfiguration().addUser("IDo", "Exist");
try {
QueueConnection queueC = ((QueueConnectionFactory) cf).createQueueConnection("IDont", "Exist");
fail("supposed to throw exception");
queueC.close();
} catch (JMSSecurityException e) {
// expected
}
JMSContext ctx = cf.createContext("IDo", "Exist");
ctx.close();
}
/**
* Test creation of QueueSession
*/
@Test
public void testQueueConnection1() throws Exception {
QueueConnection qc = queueCf.createQueueConnection();
qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
qc.close();
}
@Test
public void testCachingConnectionFactoryWithQueueConnectionFactoryAndJms102Usage() throws JMSException {
QueueConnectionFactory cf = mock(QueueConnectionFactory.class);
QueueConnection con = mock(QueueConnection.class);
QueueSession txSession = mock(QueueSession.class);
QueueSession nonTxSession = mock(QueueSession.class);
given(cf.createQueueConnection()).willReturn(con);
given(con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession);
given(txSession.getTransacted()).willReturn(true);
given(con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession);
CachingConnectionFactory scf = new CachingConnectionFactory(cf);
scf.setReconnectOnException(false);
Connection con1 = scf.createQueueConnection();
Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
session1.rollback();
session1.close();
session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
session1.close();
con1.start();
QueueConnection con2 = scf.createQueueConnection();
Session session2 = con2.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
session2.close();
session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
session2.getTransacted();
session2.close(); // should lead to rollback
con2.start();
con1.close();
con2.close();
scf.destroy(); // should trigger actual close
verify(txSession).rollback();
verify(txSession).close();
verify(nonTxSession).close();
verify(con).start();
verify(con).stop();
verify(con).close();
}
@Test(timeout = 60000)
public void testSessionArgsIgnoredWithTm() throws Exception {
JmsPoolXAConnectionFactory pcf = createXAPooledConnectionFactory();
// simple TM that with no tx
pcf.setTransactionManager(new TransactionManager() {
@Override
public void begin() throws NotSupportedException, SystemException {
throw new SystemException("NoTx");
}
@Override
public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException {
throw new IllegalStateException("NoTx");
}
@Override
public int getStatus() throws SystemException {
return Status.STATUS_NO_TRANSACTION;
}
@Override
public Transaction getTransaction() throws SystemException {
throw new SystemException("NoTx");
}
@Override
public void resume(Transaction tobj) throws IllegalStateException, InvalidTransactionException, SystemException {
throw new IllegalStateException("NoTx");
}
@Override
public void rollback() throws IllegalStateException, SecurityException, SystemException {
throw new IllegalStateException("NoTx");
}
@Override
public void setRollbackOnly() throws IllegalStateException, SystemException {
throw new IllegalStateException("NoTx");
}
@Override
public void setTransactionTimeout(int seconds) throws SystemException {
}
@Override
public Transaction suspend() throws SystemException {
throw new SystemException("NoTx");
}
});
QueueConnection connection = pcf.createQueueConnection();
// like ee tck
assertNotNull("can create session(false, 0)", connection.createQueueSession(false, 0));
connection.close();
pcf.stop();
}
@Parameters({"admin-username", "admin-password", "broker-hostname", "broker-port"})
@Test
public void testNonExistingConsumer(String username, String password,
String hostname, String port) throws Exception {
String queueName = "testNonExistingConsumer";
// Create a durable queue using a JMS client
InitialContext initialContextForQueue = ClientHelper
.getInitialContextBuilder(username, password, hostname, port)
.withQueue(queueName)
.build();
QueueConnectionFactory connectionFactory
= (QueueConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
QueueConnection connection = connectionFactory.createQueueConnection();
connection.start();
QueueSession queueSession = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
Queue queue = queueSession.createQueue(queueName);
QueueReceiver receiver1 = queueSession.createReceiver(queue);
HttpGet getAllConsumers = new HttpGet(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH
+ "/" + queueName + "/consumers");
ClientHelper.setAuthHeader(getAllConsumers, username, password);
CloseableHttpResponse response = client.execute(getAllConsumers);
Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK,
"Incorrect status code");
String consumerArray = EntityUtils.toString(response.getEntity());
ConsumerMetadata[] consumers = objectMapper.readValue(consumerArray, ConsumerMetadata[].class);
Assert.assertEquals(consumers.length, 1, "There should be a single consumer");
int id = consumers[0].getId();
receiver1.close();
HttpGet getConsumer = new HttpGet(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH
+ "/" + queueName + "/consumers/" + String.valueOf(id));
ClientHelper.setAuthHeader(getConsumer, username, password);
response = client.execute(getConsumer);
Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_NOT_FOUND);
String errorMessage = EntityUtils.toString(response.getEntity());
Error error = objectMapper.readValue(errorMessage, Error.class);
Assert.assertFalse(error.getMessage().isEmpty(), "Error message should be non empty.");
queueSession.close();
connection.close();
}
public void run() {
QueueConnection connection = null;
StandardLogger logger = LoggerUtil.getStandardLogger();
try {
String txt = message.getText();
if (logger.isDebugEnabled()) {
logger.debug("JMS Listener receives request: " + txt);
}
String resp;
ListenerHelper helper = new ListenerHelper();
Map<String, String> metaInfo = new HashMap<>();
metaInfo.put(Listener.METAINFO_PROTOCOL, Listener.METAINFO_PROTOCOL_JMS);
metaInfo.put(Listener.METAINFO_REQUEST_PATH, getQueueName());
metaInfo.put(Listener.METAINFO_SERVICE_CLASS, this.getClass().getName());
metaInfo.put(Listener.METAINFO_REQUEST_ID, message.getJMSMessageID());
metaInfo.put(Listener.METAINFO_CORRELATION_ID, message.getJMSCorrelationID());
if (message.getJMSReplyTo() != null)
metaInfo.put("ReplyTo", message.getJMSReplyTo().toString());
resp = helper.processRequest(txt, metaInfo);
Queue respQueue = (Queue) message.getJMSReplyTo();
String correlId = message.getJMSCorrelationID();
if (resp != null && respQueue != null) {
// String msgId = jmsMessage.getJMSMessageID();
QueueConnectionFactory qcf
= JMSServices.getInstance().getQueueConnectionFactory(null);
connection = qcf.createQueueConnection();
Message respMsg;
try (QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE)) {
try (QueueSender sender = session.createSender(respQueue)) {
respMsg = session.createTextMessage(resp);
respMsg.setJMSCorrelationID(correlId);
sender.send(respMsg);
}
}
if (logger.isDebugEnabled()) {
logger.debug("JMS Listener sends response (corr id='" +
correlId + "'): " + resp);
}
}
}
catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
}
finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
logger.error(e.getMessage(), e);
}
}
}
}
public void stopClientSync(){
if (null != connection && null != session && null != receiver) {
try {
log.info("Closing Consumer");
if (ExchangeType.TOPIC == consumerConfig.getExchangeType()) {
if (null != receiver) {
TopicSubscriber topicSubscriber = (TopicSubscriber) receiver;
topicSubscriber.close();
}
if (null != session) {
TopicSession topicSession = (TopicSession) session;
topicSession.close();
}
if (null != connection) {
TopicConnection topicConnection = (TopicConnection) connection;
topicConnection.close();
}
} else if (ExchangeType.QUEUE == consumerConfig.getExchangeType()) {
if (null != receiver) {
QueueReceiver queueReceiver = (QueueReceiver) receiver;
queueReceiver.close();
}
if (null != session) {
QueueSession queueSession = (QueueSession) session;
queueSession.close();
}
if (null != connection) {
QueueConnection queueConnection = (QueueConnection) connection;
queueConnection.stop();
queueConnection.close();
}
}
receiver = null;
session = null;
connection = null;
log.info("Consumer Closed");
} catch (JMSException e) {
log.error("Error in stopping client.", e);
throw new RuntimeException("Error in stopping client.", e);
}
}
}