List of usage examples for javax.jms Connection createSession
Session createSession(boolean transacted, int acknowledgeMode) throws JMSException;
From source file:org.dawnsci.commandserver.core.consumer.RemoteSubmission.java
/** * Submits the bean onto the server. From there events about this * bean are tacked by monitoring the status queue. * // ww w . ja va2 s . c o m * @param uri * @param bean */ public synchronized TextMessage submit(StatusBean bean, boolean prepareBean) throws Exception { if (getQueueName() == null || "".equals(getQueueName())) throw new Exception("Please specify a queue name!"); Connection send = null; Session session = null; MessageProducer producer = null; try { QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); send = connectionFactory.createConnection(); session = send.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(queueName); producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.PERSISTENT); ObjectMapper mapper = new ObjectMapper(); if (getTimestamp() < 1) setTimestamp(System.currentTimeMillis()); if (getPriority() < 1) setPriority(1); if (getLifeTime() < 1) setLifeTime(7 * 24 * 60 * 60 * 1000); // 7 days in ms if (prepareBean) { if (bean.getUserName() == null) bean.setUserName(System.getProperty("user.name")); bean.setUniqueId(uniqueId); bean.setSubmissionTime(getTimestamp()); } String jsonString = mapper.writeValueAsString(bean); TextMessage message = session.createTextMessage(jsonString); message.setJMSMessageID(uniqueId); message.setJMSExpiration(getLifeTime()); message.setJMSTimestamp(getTimestamp()); message.setJMSPriority(getPriority()); producer.send(message); return message; } finally { if (send != null) send.close(); if (session != null) session.close(); if (producer != null) producer.close(); } }
From source file:org.wso2.carbon.esb.scenario.test.common.jms.ActiveMQJMSClient.java
/** * Function to produce message to ActiveMQ Queue * * @param queueName name of the target queue * @param messageStr message to place// ww w . j a va 2s .c om * @throws JMSException */ public void produceMessageToQueue(String queueName, String messageStr) throws JMSException { Connection connection = null; Session session = null; try { // Create a ConnectionFactory ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); // Create a Connection connection = connectionFactory.createConnection(); connection.start(); connection.setExceptionListener(this); // Create a Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Create the destination (Topic or Queue) Destination destination = session.createQueue(queueName); // Create a MessageProducer from the Session to the Topic or Queue MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // Create a messages TextMessage message = session.createTextMessage(messageStr); // Tell the producer to send the message producer.send(message); } finally { // Clean up if (session != null) { session.close(); } if (connection != null) { connection.close(); } } }
From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java
public void dotestJAASSecurityManagerAuthorizationPositive(String jaasConfigScope, String artemisRoleName) throws Exception { createArtemisServer(jaasConfigScope); Set<Role> roles = new HashSet<>(); roles.add(new Role(artemisRoleName, true, true, true, true, true, true, true, true, true, true)); server.getConfiguration().putSecurityRoles(QUEUE_NAME, roles); server.start();/*from w ww . j a va 2 s . c o m*/ JmsConnectionFactory jmsConnectionFactory = new JmsConnectionFactory( "amqp://localhost:5672?amqp.saslMechanisms=GSSAPI"); Connection connection = jmsConnectionFactory.createConnection("client", null); try { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = session.createQueue(QUEUE_NAME); // PRODUCE final String text = RandomUtil.randomString(); try { MessageProducer producer = session.createProducer(queue); producer.send(session.createTextMessage(text)); } catch (Exception e) { e.printStackTrace(); Assert.fail("should not throw exception here"); } // CONSUME try { MessageConsumer consumer = session.createConsumer(queue); TextMessage m = (TextMessage) consumer.receive(1000); Assert.assertNotNull(m); Assert.assertEquals(text, m.getText()); } catch (Exception e) { Assert.fail("should not throw exception here"); } } finally { connection.close(); } }
From source file:org.aludratest.service.jms.impl.JmsActionImpl.java
@Override public void unsubscribeTopic(@TechnicalArgument String subscriptionName) throws JMSException { if (StringUtils.isEmpty(clientId)) { throw new IllegalArgumentException("Client-Id must be provided to unsubscribe"); }// w ww .ja v a 2 s . c o m LOGGER.debug("Unsubscribing from subscription " + subscriptionName); Connection c = getDynamicConnection(subscriptionName); c.stop(); TopicSubscriber subscriber = this.durableConsumers.get(subscriptionName); if (subscriber != null) { subscriber.close(); c.createSession(false, Session.AUTO_ACKNOWLEDGE).unsubscribe(subscriptionName); this.durableConsumers.remove(subscriptionName); } c.close(); this.dynamicConnections.remove(c); }
From source file:org.apache.qpid.client.ssl.SSLTest.java
private void missingClientCertWhileNeedingOrWantingTestImpl(boolean needClientCerts, boolean wantClientCerts, boolean shouldSucceed) throws Exception { if (shouldPerformTest()) { clearSslStoreSystemProperties(); //Start the broker configureJavaBrokerIfNecessary(true, true, needClientCerts, wantClientCerts); super.setUp(); String url = "amqp://guest:guest@test/?brokerlist='tcp://localhost:%s" + "?ssl='true'&trust_store='%s'&trust_store_password='%s''"; url = String.format(url, QpidBrokerTestCase.DEFAULT_SSL_PORT, TRUSTSTORE, TRUSTSTORE_PASSWORD); try {/*from www. ja v a 2s. c om*/ Connection con = getConnection(new AMQConnectionURL(url)); if (!shouldSucceed) { fail("Connection succeeded, expected exception was not thrown"); } else { //Use the connection to verify it works con.createSession(true, Session.SESSION_TRANSACTED); } } catch (JMSException e) { if (shouldSucceed) { _logger.error("Caught unexpected exception", e); fail("Connection failed, unexpected exception thrown"); } else { //expected verifyExceptionCausesContains(e, "Caused by: javax.net.ssl.SSLException:"); } } } }
From source file:ConsumerTool.java
public void run() { try {//w ww . j av a 2s .co m running = true; ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url); Connection connection = connectionFactory.createConnection(); if (durable && clientId != null && clientId.length() > 0 && !"null".equals(clientId)) { connection.setClientID(clientId); } connection.setExceptionListener(this); connection.start(); session = connection.createSession(transacted, ackMode); if (topic) { destination = session.createTopic(subject); } else { destination = session.createQueue(subject); } replyProducer = session.createProducer(null); replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); MessageConsumer consumer = null; if (durable && topic) { consumer = session.createDurableSubscriber((Topic) destination, consumerName); } else { consumer = session.createConsumer(destination); } if (maxiumMessages > 0) { consumeMessagesAndClose(connection, session, consumer); } else { if (receiveTimeOut == 0) { consumer.setMessageListener(this); } else { consumeMessagesAndClose(connection, session, consumer, receiveTimeOut); } } } catch (Exception e) { System.out.println("[" + this.getName() + "] Caught: " + e); e.printStackTrace(); } }
From source file:org.wso2.carbon.esb.scenario.test.common.jms.ActiveMQJMSClient.java
/** * Function to retrieve message from specified message queue * * @param queueName Name of the queue/*w w w .j ava 2s .com*/ * @param timeout Timeout value (in milliseconds) * @return Retrieved message from the queue * @throws JMSException if error occurred */ public Message consumeMessageFromQueue(String queueName, long timeout) throws JMSException { Connection connection = null; Session session = null; MessageConsumer consumer = null; try { // Create a ConnectionFactory ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); // Create a Connection connection = connectionFactory.createConnection(); connection.start(); connection.setExceptionListener(this); // Create a Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Create the destination (Topic or Queue) Destination destination = session.createQueue(queueName); // Create a MessageConsumer from the Session to the Topic or Queue consumer = session.createConsumer(destination); // Wait for a message return consumer.receive(timeout); } finally { if (consumer != null) { consumer.close(); } if (session != null) { session.close(); } if (connection != null) { connection.close(); } } }
From source file:tools.ProducerTool.java
@Override public void run() { Connection connection = null; Session session = null;/*from w w w. j a v a2 s .com*/ try { connection = connectionFactory.createConnection(); if (clientId != null) { connection.setClientID(clientId); } session = connection.createSession(transacted, acknowledgeMode); Destination destination = null; if (jndiLookupDestinations) { destination = (Destination) context.lookup(destinationName); } else { if (useQueueDestinations) { if (useTemporaryDestinations) { destination = session.createTemporaryQueue(); } else { destination = session.createQueue(destinationName); } } else { if (useTemporaryDestinations) { destination = session.createTemporaryTopic(); } else { destination = session.createTopic(destinationName); } } } MessageProducer producer = session.createProducer(destination); if (durable) { producer.setDeliveryMode(DeliveryMode.PERSISTENT); } else { producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); } int numMessagesToSend = useFinalControlMessage ? numMessages - 1 : numMessages; for (int i = 0; i < numMessagesToSend; i++) { String messageText = "Message " + i + " at " + new Date(); if (bytesLength > -1) { byte[] messageTextBytes = messageText.getBytes(StandardCharsets.UTF_8); BytesMessage bytesMessage = session.createBytesMessage(); bytesMessage.writeBytes(messageTextBytes); if (messageTextBytes.length < bytesLength) { byte[] paddingBytes = new byte[bytesLength - messageTextBytes.length]; bytesMessage.writeBytes(paddingBytes); } if (messageGroupId != null) { bytesMessage.setStringProperty("JMSXGroupID", messageGroupId); } LOGGER.info("Sending bytes message"); producer.send(bytesMessage); } else { TextMessage textMessage = session.createTextMessage(messageText); if (messageGroupId != null) { textMessage.setStringProperty("JMSXGroupID", messageGroupId); } LOGGER.info("Sending text message: " + messageText); producer.send(textMessage); } if (perMessageSleepMS > 0) { Thread.sleep(perMessageSleepMS); } if (transacted) { if ((i + 1) % batchSize == 0) { session.commit(); } } } if (useFinalControlMessage) { Message message = session.createMessage(); if (messageGroupId != null) { message.setStringProperty("JMSXGroupID", messageGroupId); } LOGGER.info("Sending message"); producer.send(message); if (transacted) { session.commit(); } } producer.close(); } catch (Exception ex) { LOGGER.error("ProducerTool hit exception: " + ex.getMessage(), ex); } finally { if (session != null) { try { session.close(); } catch (JMSException e) { LOGGER.error("JMSException closing session", e); } } if (connection != null) { try { connection.close(); } catch (JMSException e) { LOGGER.error("JMSException closing session", e); } } } }
From source file:com.zotoh.maedr.device.JmsIO.java
private void inizFac(Context ctx, Object obj) throws Exception { ConnectionFactory f = (ConnectionFactory) obj; final JmsIO me = this; Connection conn; Object c = ctx.lookup(_dest); if (!isEmpty(_jmsUser)) { conn = f.createConnection(_jmsUser, _jmsPwd); } else {/*from w ww .j ava2s . c o m*/ conn = f.createConnection(); } _conn = conn; if (c instanceof Destination) { //TODO ? ack always ? Session s = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer u = s.createConsumer((Destination) c); u.setMessageListener(new MessageListener() { public void onMessage(Message msg) { me.onMessage(msg); } }); } else { throw new Exception("JmsIO: Object not of Destination type"); } }
From source file:org.frameworkset.mq.ReceiveDispatcher.java
public ReceiveDispatcher(Connection connection) throws JMSException { if (connection instanceof JMSConnection) this.connection = (JMSConnection) connection; else/*ww w . j a v a2s . c o m*/ this.connection = new JMSConnection(connection, null); session = connection.createSession(this.transacted, acknowledgeMode); }