List of usage examples for javax.jms MessageProducer send
void send(Message message) throws JMSException;
From source file:org.wso2.mb.integration.tests.amqp.functional.RedeliveryDelayTestCase.java
/** * This test publishes 1000 messages and the subscriber reject each 100th message and then wait for the redelivered * message.//w w w. ja va2 s . c o m * <p/> * The redelivered message is tested against the same message content with the original message and the timestamps * are also checked against the original message timestamp to make sure that the message was delayed. * Here message receive method is used instead of the message listener to receive messages. * * @throws AndesClientConfigurationException * @throws XPathExpressionException * @throws IOException * @throws JMSException * @throws AndesClientException * @throws NamingException */ @Test(groups = { "wso2.mb", "queue" }) public void oneByOneUnacknowledgeMessageReceiverForMultipleMessagesTestCase() throws AndesClientConfigurationException, XPathExpressionException, IOException, JMSException, AndesClientException, NamingException { long sendCount = 1000; final List<ImmutablePair<String, Calendar>> receivedMessages = new ArrayList<>(); // Creating a consumer client configuration AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(), ExchangeType.QUEUE, "oneByOneUnacknowledgeMessageReceiverForMultipleQueue"); consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.PER_MESSAGE_ACKNOWLEDGE); consumerConfig.setAsync(false); // Creating a publisher client configuration AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration( getAMQPPort(), ExchangeType.QUEUE, "oneByOneUnacknowledgeMessageReceiverForMultipleQueue"); publisherConfig.setNumberOfMessagesToSend(sendCount); // Creating clients AndesClient consumerClient = new AndesClient(consumerConfig, true); final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0); final MessageConsumer receiver = andesJMSConsumer.getReceiver(); Thread messageReceivingThread = new Thread() { public void run() { while (receiver != null) { try { TextMessage textMessage = (TextMessage) receiver.receive(); if (Integer.parseInt(textMessage.getText().split("#")[1]) % 100 != 0 || getMessageList(receivedMessages).contains(textMessage.getText())) { textMessage.acknowledge(); } receivedMessages.add(ImmutablePair.of(textMessage.getText(), Calendar.getInstance())); andesJMSConsumer.getReceivedMessageCount().incrementAndGet(); } catch (JMSException e) { throw new RuntimeException("Exception occurred when receiving messages.", e); } } } }; messageReceivingThread.start(); AndesClient publisherClient = new AndesClient(publisherConfig, true); AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0); MessageProducer sender = andesJMSPublisher.getSender(); for (int i = 0; i < sendCount; i++) { TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i)); sender.send(textMessage); } AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME * 2); log.info("Received Messages : " + getMessageList(receivedMessages)); for (int i = 0; i < sendCount; i++) { Assert.assertEquals(receivedMessages.get(i).getLeft(), "#" + Integer.toString(i), "Invalid messages received. #" + Integer.toString(i) + " expected."); } validateMessageContentAndDelay(receivedMessages, 0, 1000, "#0"); validateMessageContentAndDelay(receivedMessages, 99, 1001, "#100"); validateMessageContentAndDelay(receivedMessages, 199, 1002, "#200"); validateMessageContentAndDelay(receivedMessages, 299, 1003, "#300"); validateMessageContentAndDelay(receivedMessages, 399, 1004, "#400"); validateMessageContentAndDelay(receivedMessages, 499, 1005, "#500"); validateMessageContentAndDelay(receivedMessages, 599, 1006, "#600"); validateMessageContentAndDelay(receivedMessages, 699, 1007, "#700"); validateMessageContentAndDelay(receivedMessages, 799, 1008, "#800"); validateMessageContentAndDelay(receivedMessages, 899, 1009, "#900"); Assert.assertEquals(receivedMessages.size(), sendCount + 10, "Message receiving failed."); }
From source file:org.apache.axis2.transport.jms.MockEchoEndpoint.java
@Setup @SuppressWarnings("unused") private void setUp(JMSTestEnvironment env, JMSRequestResponseChannel channel) throws Exception { Destination destination = channel.getDestination(); Destination replyDestination = channel.getReplyDestination(); connection = env.getConnectionFactory().createConnection(); connection.setExceptionListener(this); connection.start();/*from w w w . j av a 2 s . c o m*/ replyConnection = env.getConnectionFactory().createConnection(); replyConnection.setExceptionListener(this); final Session replySession = replyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageProducer producer = replySession.createProducer(replyDestination); MessageConsumer consumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE) .createConsumer(destination); consumer.setMessageListener(new MessageListener() { public void onMessage(Message message) { try { log.info("Message received: ID = " + message.getJMSMessageID()); Message reply; if (message instanceof BytesMessage) { reply = replySession.createBytesMessage(); IOUtils.copy(new BytesMessageInputStream((BytesMessage) message), new BytesMessageOutputStream((BytesMessage) reply)); } else if (message instanceof TextMessage) { reply = replySession.createTextMessage(); ((TextMessage) reply).setText(((TextMessage) message).getText()); } else { // TODO throw new UnsupportedOperationException("Unsupported message type"); } reply.setJMSCorrelationID(message.getJMSMessageID()); reply.setStringProperty(BaseConstants.CONTENT_TYPE, message.getStringProperty(BaseConstants.CONTENT_TYPE)); producer.send(reply); log.info("Message sent: ID = " + reply.getJMSMessageID()); } catch (Throwable ex) { fireEndpointError(ex); } } }); }
From source file:org.jbpm.bpel.integration.server.SoapHandler.java
protected ObjectMessage sendRequest(SOAPMessage soapMessage, Session jmsSession, JbpmContext jbpmContext) throws SOAPException, JMSException { // create a jms message to deliver the incoming content ObjectMessage jmsRequest = jmsSession.createObjectMessage(); // put the partner link identified by handle in a jms property PartnerLinkEntry partnerLinkEntry = integrationControl.getPartnerLinkEntry(portTypeName, serviceName, portName);/*from ww w . j a v a 2 s. c o m*/ long partnerLinkId = partnerLinkEntry.getId(); jmsRequest.setLongProperty(IntegrationConstants.PARTNER_LINK_ID_PROP, partnerLinkId); Operation operation = determineOperation(soapMessage); if (operation == null) throw new SOAPException("could not determine operation to perform"); // put the operation name in a jms property String operationName = operation.getName(); jmsRequest.setStringProperty(IntegrationConstants.OPERATION_NAME_PROP, operationName); log.debug("received request: partnerLink=" + partnerLinkId + ", operation=" + operationName); // extract message content HashMap requestParts = new HashMap(); formatter.readMessage(operationName, soapMessage, requestParts, MessageDirection.INPUT); jmsRequest.setObject(requestParts); // fill message properties BpelProcessDefinition process = integrationControl.getDeploymentDescriptor() .findProcessDefinition(jbpmContext); MessageType requestType = process.getImportDefinition() .getMessageType(operation.getInput().getMessage().getQName()); fillCorrelationProperties(requestParts, jmsRequest, requestType.getPropertyAliases()); // set up producer MessageProducer producer = jmsSession.createProducer(partnerLinkEntry.getDestination()); try { // is the exchange pattern request/response? if (operation.getOutput() != null) { Destination replyTo = integrationControl.getIntegrationServiceFactory().getResponseDestination(); jmsRequest.setJMSReplyTo(replyTo); // have jms discard request message if response timeout expires Number responseTimeout = getResponseTimeout(jbpmContext); if (responseTimeout != null) producer.setTimeToLive(responseTimeout.longValue()); } else { // have jms discard message if one-way timeout expires Number oneWayTimeout = getOneWayTimeout(jbpmContext); if (oneWayTimeout != null) producer.setTimeToLive(oneWayTimeout.longValue()); } // send request message producer.send(jmsRequest); log.debug("sent request: " + RequestListener.messageToString(jmsRequest)); return jmsRequest; } finally { // release producer resources producer.close(); } }
From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java
private void addBloomScanListener() throws JMSException { addMessageListener("scanRequest", new MessageListener() { @Override//from w w w . jav a 2 s . com public void onMessage(Message msg) { BytesMessage o = (BytesMessage) msg; byte[] body; try { body = new byte[(int) o.getBodyLength()]; o.readBytes(body); BCSAPIMessage.FilterRequest request = BCSAPIMessage.FilterRequest.parseFrom(body); byte[] data = request.getFilter().toByteArray(); long hashFunctions = request.getHashFunctions(); long tweak = request.getTweak(); UpdateMode updateMode = UpdateMode.values()[request.getMode()]; final BloomFilter filter = new BloomFilter(data, hashFunctions, tweak, updateMode); final MessageProducer producer = session.createProducer(msg.getJMSReplyTo()); requestProcessor.execute(new Runnable() { @Override public void run() { try { store.scan(filter, new TransactionProcessor() { @Override public void process(Tx tx) { if (tx != null) { Transaction transaction = toBCSAPITransaction(tx); BytesMessage m; try { m = session.createBytesMessage(); m.writeBytes(transaction.toProtobuf().toByteArray()); producer.send(m); } catch (JMSException e) { } } else { try { BytesMessage m = session.createBytesMessage(); producer.send(m); // indicate EOF producer.close(); } catch (JMSException e) { } } } }); } catch (ValidationException e) { log.error("Error while scanning", e); } } }); } catch (JMSException e) { log.error("invalid filter request", e); } catch (InvalidProtocolBufferException e) { log.error("invalid filter request", e); } } }); }
From source file:org.apache.activemq.bugs.VMTransportClosureTest.java
/** * This test demonstrates how the "disposeOnDisonnect" feature of * VMTransportServer can incorrectly close all VM connections to the local * broker.//from w w w . j a v a 2 s. c o m */ public void testPrematureClosure() throws Exception { // Open a persistent connection to the local broker. The persistent // connection is maintained through the test and should prevent the // VMTransportServer from stopping itself when the local transport is // closed. ActiveMQConnection persistentConn = (ActiveMQConnection) createConnection(); persistentConn.start(); Session session = persistentConn.createSession(true, Session.SESSION_TRANSACTED); MessageProducer producer = session.createProducer(destination); for (int i = 0; i < NUM_ATTEMPTS; i++) { LOG.info("Attempt: " + i); // Open and close a local transport connection. As is done by by // most users of the transport, ensure that the transport is stopped // when closed by the peer (via ShutdownInfo). Closing the local // transport should not affect the persistent connection. final Transport localTransport = TransportFactory.connect(broker.getVmConnectorURI()); localTransport.setTransportListener(new TransportListener() { public void onCommand(Object command) { if (command instanceof ShutdownInfo) { try { localTransport.stop(); } catch (Exception ex) { throw new RuntimeException(ex); } } } public void onException(IOException error) { // ignore } public void transportInterupted() { // ignore } public void transportResumed() { // ignore } }); localTransport.start(); localTransport.stop(); // Ensure that the persistent connection is still usable. producer.send(session.createMessage()); session.rollback(); } persistentConn.close(); }
From source file:tools.ProducerTool.java
@Override public void run() { Connection connection = null; Session session = null;/*from ww w . j ava 2 s . c o m*/ 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:org.apache.qpid.test.utils.QpidBrokerTestCase.java
/** * Send messages to the given destination. * * If session is transacted then messages will be committed before returning * * @param session the session to use for sending * @param destination where to send them to * @param count no. of messages to send//from w w w. j av a2 s . c o m * * @param offset offset allows the INDEX value of the message to be adjusted. * @param batchSize the batchSize in which to commit, 0 means no batching, * but a single commit at the end * @return the sent message * * @throws Exception */ public List<Message> sendMessage(Session session, Destination destination, int count, int offset, int batchSize) throws Exception { List<Message> messages = new ArrayList<Message>(count); MessageProducer producer = session.createProducer(destination); int i = offset; for (; i < (count + offset); i++) { Message next = createNextMessage(session, i); producer.send(next); if (session.getTransacted() && batchSize > 0) { if (i % batchSize == 0) { session.commit(); } } messages.add(next); } // Ensure we commit the last messages // Commit the session if we are transacted and // we have no batchSize or // our count is not divible by batchSize. if (session.getTransacted() && ( batchSize == 0 || (i-1) % batchSize != 0)) { session.commit(); } return messages; }
From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java
private void addMatchScanListener() throws JMSException { addMessageListener("matchRequest", new MessageListener() { @Override//from w w w . j a va2 s . co m public void onMessage(Message msg) { BytesMessage o = (BytesMessage) msg; byte[] body; try { body = new byte[(int) o.getBodyLength()]; o.readBytes(body); BCSAPIMessage.ExactMatchRequest request = BCSAPIMessage.ExactMatchRequest.parseFrom(body); final List<byte[]> match = new ArrayList<byte[]>(); for (ByteString bs : request.getMatchList()) { match.add(bs.toByteArray()); } final UpdateMode mode = UpdateMode.values()[request.getMode()]; final MessageProducer producer = session.createProducer(msg.getJMSReplyTo()); final long after = request.hasAfter() ? request.getAfter() : 0; requestProcessor.execute(new Runnable() { @Override public void run() { try { store.filterTransactions(match, mode, after, new TransactionProcessor() { @Override public void process(Tx tx) { if (tx != null) { Transaction transaction = toBCSAPITransaction(tx); BytesMessage m; try { m = session.createBytesMessage(); m.writeBytes(transaction.toProtobuf().toByteArray()); producer.send(m); } catch (JMSException e) { } } else { try { BytesMessage m = session.createBytesMessage(); producer.send(m); // indicate EOF producer.close(); } catch (JMSException e) { } } } }); } catch (ValidationException e) { log.error("Error while scanning", e); } } }); } catch (JMSException e) { log.error("invalid filter request", e); } catch (InvalidProtocolBufferException e) { log.error("invalid filter request", e); } } }); }
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. * //www.ja v a 2s .co 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.identity.agent.outbound.server.UserStoreServerEndpoint.java
/** * Process response message and send to response queue. * @param message Message/* w w w.j ava2 s . c o m*/ */ private void processResponse(String message) { JMSConnectionFactory connectionFactory = new JMSConnectionFactory(); Connection connection = null; MessageProducer producer; try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Start processing response message: " + message); } MessageBrokerConfig conf = ServerConfigurationBuilder.build().getMessagebroker(); connectionFactory.createActiveMQConnectionFactory(conf.getUrl()); connection = connectionFactory.createConnection(); connectionFactory.start(connection); javax.jms.Session session = connectionFactory.createSession(connection); Destination responseQueue = connectionFactory.createQueueDestination(session, UserStoreConstants.QUEUE_NAME_RESPONSE); producer = connectionFactory.createMessageProducer(session, responseQueue, DeliveryMode.NON_PERSISTENT); producer.setTimeToLive(UserStoreConstants.QUEUE_SERVER_MESSAGE_LIFETIME); JSONObject resultObj = new JSONObject(message); String responseData = resultObj.get(UserStoreConstants.UM_JSON_ELEMENT_RESPONSE_DATA).toString(); String correlationId = (String) resultObj .get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID); UserOperation responseOperation = new UserOperation(); responseOperation.setCorrelationId(correlationId); responseOperation.setResponseData(responseData.toString()); ObjectMessage responseMessage = session.createObjectMessage(); responseMessage.setObject(responseOperation); responseMessage.setJMSCorrelationID(correlationId); producer.send(responseMessage); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Finished processing response message: " + message); } } catch (JMSException e) { LOGGER.error("Error occurred while sending message: " + message, e); } catch (JSONException e) { LOGGER.error("Error occurred while reading json payload of message: " + message, e); } catch (JMSConnectionException e) { LOGGER.error("Error occurred while creating JMS connection to send message: " + message, e); } finally { try { connectionFactory.closeConnection(connection); } catch (JMSConnectionException e) { LOGGER.error("Error occurred while closing JMS connection", e); } } }