How to handle failover in case of TIBCO - jms

I am struggling to setup fail over in tibco JMS provider. I know how to do this in case of ActiveMQ.
What I have tried is as follows
public class TibcoJMSQueueProducer {
private static final Logger LOGGER = LoggerFactory.getLogger(FDPMetaCacheProducer.class);
private static QueueConnectionFactory factory;
private QueueConnection connection;
private QueueSession session;
#Inject
private FDPTibcoConfigDAO fdpTibcoConfigDao;
private String providerURL;
private String userName;
private String password;
#PostConstruct
public void constructProducer(){
configure();
}
private void configure() {
try {
List<FDPTibcoConfigDTO> tibcoConfigList = fdpTibcoConfigDao.getAllTibcoConfig();
if(!tibcoConfigList.isEmpty()){
FDPTibcoConfigDTO fdpTibcoConfigDTO = tibcoConfigList.get(tibcoConfigList.size()-1);
String providerURL = getProviderUrl(fdpTibcoConfigDTO);
setProviderUrl(providerURL);
String userName = fdpTibcoConfigDTO.getUserName();
String password = fdpTibcoConfigDTO.getPassword();
this.userName = userName;
this.password=password;
factory = new com.tibco.tibjms.TibjmsQueueConnectionFactory(providerURL);
}
} catch (Exception e) {
System.err.println("Exitting with Error");
e.printStackTrace();
System.exit(0);
}
}
private void setProviderUrl(String providerURL) {
this.providerURL = providerURL;
}
private String getProviderUrl(final FDPTibcoConfigDTO FDPTibcoConfigDTO) {
return TibcoConstant.TCP_PROTOCOL + FDPTibcoConfigDTO.getIpAddress().getValue() + TibcoConstant.COLON_SEPERATOR + FDPTibcoConfigDTO.getPort();
}
private Object lookupQueue(String queueName) {
Properties props = new Properties();
Object tibcoQueue = null;
props.setProperty(Context.INITIAL_CONTEXT_FACTORY, TibcoConstant.TIB_JMS_INITIAL_CONTEXT_FACTORY);
props.setProperty(Context.PROVIDER_URL, this.providerURL);
props.setProperty(TibcoConstant.TIBCO_CONNECT_ATTEMPT, "20,10");
props.setProperty(TibcoConstant.TIBCO_RECOVER_START_UP_ERROR, "true");
props.setProperty(TibcoConstant.TIBCO_RECOVER_RECONNECT_ATTEMPT, "20,10");
InitialContext context;
try {
context = new InitialContext(props);
tibcoQueue = context.lookup(queueName);
} catch (NamingException e) {
System.out.println(e.getMessage());
}
return tibcoQueue;
}
public void pushIntoQueueAsync(String message,String queueName) throws JMSException {
connection = factory.createQueueConnection(userName, password);
connection.start();
session = connection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
Queue pushingQueue = (Queue)lookupQueue(queueName);
QueueSender queueSender = session.createSender(pushingQueue);
queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
TextMessage sendXMLRequest = session.createTextMessage(message);
queueSender.send(sendXMLRequest);
LOGGER.info("Pushing Queue {0} ,Pushing Message : {1}", pushingQueue.getQueueName(), sendXMLRequest.getText());
}
public String pushIntoQueueSync(String message,String queueName,String replyQueueName) throws JMSException {
connection = factory.createQueueConnection(userName, password);
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = (Destination)lookupQueue(queueName);
MessageProducer messageProducer = session.createProducer(destination);
session = connection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
UUID randomUUID =UUID.randomUUID();
TextMessage textMessage = session.createTextMessage(message);
String correlationId = randomUUID.toString();
//Create Reply To Queue
Destination replyDestination = (Destination)lookupQueue(queueName);
textMessage.setJMSReplyTo(replyDestination);
textMessage.setJMSCorrelationID(correlationId);
String messgeSelector = "JMSCorrelationID = '" + correlationId + "'";
MessageConsumer replyConsumer = session.createConsumer(replyDestination,messgeSelector);
messageProducer.send(textMessage, javax.jms.DeliveryMode.PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY, 1800000);
Message replayMessage = replyConsumer.receive();
TextMessage replyTextMessage = (TextMessage) replayMessage;
String replyText = replyTextMessage.getText();
LOGGER.info("Pushing Queue {0} ,Pushing Message : {1}", queueName, message);
return replyText;
}
public static QueueConnectionFactory getConnectionFactory(){
return factory;
}
}
In case of activeMQ we use
failover:(tcp://127.0.0.1:61616,tcp://127.0.0.1:61616)?randomize=false&backup=true url to handle failover as provider url in ActiveMQconnectionfactory constructor. I have seen somewhere to use multiple url in case of TIBCO like this
tcp://169.144.87.25:7222,tcp://127.0.0.1:7222
How I checked failover like this.
First at all I checked using single IP (tcp://169.144.87.25:7222) . Message is getting sent and received normally(I have not posted TibcoJMSReceiver code).
I tried with another IP(tcp://169.144.87.25:7222). It was working fine.
But when I tried with
final String
PROVIDER_URL="tcp://169.144.87.25:7222,tcp://127.0.0.1:7222";
I started my program. But before giving input I shutdown first server. As a failover the message should be sent to other server.
But It shows me session closed Exception.
So Am I handling failover in a correct way or is there other configuration I have to do.

Two TIBCO EMS daemons only work 'as one' if you enable fault-tolrance in both of them. Only then will they heartbeat with each other and share resources. You should have this in the remote daemon's tibemsd.conf:
listen = tcp://7222
...
ft_active = tcp://<ip to your box>:7222
and this on your local box:
listen = tcp://7222
...
ft_active = tcp://169.144.87.25:7222
And you don't need to create connection and session every time! One Connection and Session for many messages - 'Fault Tolerance' means it'll reconnect automatically for you. You could have an init() or connect() method you call once or just add it inside your configure method:
private void configure() {
try {
...
connection = factory.createQueueConnection(userName, password);
connection.start();
session = connection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
Then pushIntoQueue becomes as simple as this:
public void pushIntoQueueAsync(String message,String queueName) throws JMSException {
Queue pushingQueue = (Queue)lookupQueue(queueName);
QueueSender queueSender = session.createSender(pushingQueue);
queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
TextMessage sendXMLRequest = session.createTextMessage(message);
queueSender.send(sendXMLRequest);
LOGGER.info("Pushing Queue {0} ,Pushing Message : {1}", pushingQueue.getQueueName(), sendXMLRequest.getText());
}

Related

Send emails to multiple email addresses, It feeds email addresses from a csv file

I wanna create an application to send emails to several recipients. It feeds email addresses from a csv file and sends an email to each recipient, and I'm getting some trouble doing this.
Could you help me please?
Here is my CSVHelper.java
#Component
public class CSVHelper
{
public static String TYPE = "text/csv";
static String[] HEADERs = { "id", "email", "dateEcheance"};
//This method is used to filter the csv file and get only the emails
public List<ContactsFile> csvToEmails() throws NumberFormatException, ParseException
{
InputStream is = null;
try (BufferedReader fileReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
CSVParser csvParser = new CSVParser(fileReader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());)
{
List<ContactsFile> emailsList = new ArrayList<>();
Iterable<CSVRecord> csvRecords = csvParser.getRecords();
for (CSVRecord csvRecord : csvRecords)
{
ContactsFile contact = new ContactsFile(csvRecord.get("email"));
emailsList.add(contact);
}
System.out.println(emailsList);
return emailsList;
}
catch (IOException e) { throw new RuntimeException("fail to get emails: " + e.getMessage()); }
}
We call csvToEmails() method in the controller to send the emails
#Autowired
private CSVHelper csvHelper;
#PostMapping("/getdetails")
public #ResponseBody EmailNotification sendMail(#RequestBody EmailNotification details) throws Exception {
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
try {
helper.setTo((InternetAddress) csvHelper.csvToEmails());
helper.setText(details.getMessage(),true);
helper.setSubject("Test Mail");
} catch (javax.mail.MessagingException e) {
e.printStackTrace();
}
sender.send(message);
return details;
this is an example of the csv file:
id,email,dateEcheance
1,address#email.com,10/05/2021
2,address2#email.com,10/02/2021
I'm new to spring boot, and I'm in trouble completing this project.
Assuming that you've mail server configurations in place. First, you need to provide the JavaMailSender implementation. Spring does provide the implementation for the same. You've to create a bean and config the mail server configurations as follows.
#Configuration
public class MailConfig {
#Autowired
private Environment env;
#Bean
public JavaMailSender mailSender() {
try {
JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl();
mailSenderImpl.setHost(env.getRequiredProperty("mail.smtp.host"));
mailSenderImpl.setUsername(env.getRequiredProperty("mail.smtp.username"));
mailSenderImpl.setPassword(env.getRequiredProperty("mail.smtp.password"));
mailSenderImpl.setDefaultEncoding(env.getRequiredProperty("mail.smtp.encoding"));
mailSenderImpl.setPort(Integer.parseInt(env.getRequiredProperty("mail.smtp.port")));
mailSenderImpl.setProtocol(env.getRequiredProperty("mail.transport.protocol"));
Properties p = new Properties();
p.setProperty("mail.smtp.starttls.enable", "true");
p.setProperty("mail.smtp.auth", "true");
mailSenderImpl.setJavaMailProperties(p);
return mailSenderImpl;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Configuration settings in application.properties. Add settings according to the mail server.
# SMTP mail settings
mail.smtp.host=**********
mail.smtp.username=**********
mail.smtp.password=**********
mail.smtp.port=**********
mail.smtp.socketFactory.port=**********
mail.smtp.encoding=utf-8
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.timeout=10000
mail.smtp.starttls.enable=true
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
CSVHelper.java
#Component
public class CSVHelper {
// This method is used to filter the csv file and get only the emails
public List<String> csvToEmails() {
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("csvFile.csv");
try (BufferedReader fileReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
CSVParser csvParser = new CSVParser(fileReader,
CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());) {
List<String> emails = new ArrayList<>();
Iterable<CSVRecord> csvRecords = csvParser.getRecords();
for (CSVRecord csvRecord : csvRecords) {
String email = csvRecord.get("email");
emails.add(email);
}
return emails;
} catch (IOException e) {
throw new RuntimeException("fail to get emails: " + e.getMessage());
}
}
}
Send mail service
#Service
public class MailSenderService {
#Autowired
private CSVHelper csvHelper;
#Autowired
private JavaMailSender sender;
public void sendMail(EmailNotification details) {
try {
List<String> recipients = csvHelper.csvToEmails();
String[] to = recipients.stream().toArray(String[]::new);
JavaMailSenderImpl jms = (JavaMailSenderImpl) sender;
MimeMessage message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// add the sender email address below
helper.setFrom("sender#mail.com");
helper.setTo(to);
helper.setText(details.getMessage(), true);
helper.setSubject("Test Mail");
sender.send(message);
} catch (javax.mail.MessagingException | NumberFormatException e) {
// action for exception case
}
}
}

Spring integration TCP Server multiple connections of more than 5

I'm using the following version of Spring Boot and Spring integration now.
spring.boot.version 2.3.4.RELEASE
spring-integration 5.3.2.RELEASE
My requirement is to create a TCP client server communication and i'm using spring integration for the same. The spike works fine for a single communication between client and server and also works fine for exactly 5 concurrent client connections.
The moment i have increased the concurrent client connections from 5 to any arbitary numbers, it doesn't work but the TCP server accepts only 5 connections.
I have used the 'ThreadAffinityClientConnectionFactory' mentioned by #Gary Russell in one of the earlier comments ( for similar requirements ) but still doesn't work.
Below is the code i have at the moment.
#Slf4j
#Configuration
#EnableIntegration
#IntegrationComponentScan
public class SocketConfig {
#Value("${socket.host}")
private String clientSocketHost;
#Value("${socket.port}")
private Integer clientSocketPort;
#Bean
public TcpOutboundGateway tcpOutGate(AbstractClientConnectionFactory connectionFactory) {
TcpOutboundGateway gate = new TcpOutboundGateway();
//connectionFactory.setTaskExecutor(taskExecutor());
gate.setConnectionFactory(clientCF());
return gate;
}
#Bean
public TcpInboundGateway tcpInGate(AbstractServerConnectionFactory connectionFactory) {
TcpInboundGateway inGate = new TcpInboundGateway();
inGate.setConnectionFactory(connectionFactory);
inGate.setRequestChannel(fromTcp());
return inGate;
}
#Bean
public MessageChannel fromTcp() {
return new DirectChannel();
}
// Outgoing requests
#Bean
public ThreadAffinityClientConnectionFactory clientCF() {
TcpNetClientConnectionFactory tcpNetClientConnectionFactory = new TcpNetClientConnectionFactory(clientSocketHost, serverCF().getPort());
tcpNetClientConnectionFactory.setSingleUse(true);
ThreadAffinityClientConnectionFactory threadAffinityClientConnectionFactory = new ThreadAffinityClientConnectionFactory(
tcpNetClientConnectionFactory);
// Tested with the below too.
// threadAffinityClientConnectionFactory.setTaskExecutor(taskExecutor());
return threadAffinityClientConnectionFactory;
}
// Incoming requests
#Bean
public AbstractServerConnectionFactory serverCF() {
log.info("Server Connection Factory");
TcpNetServerConnectionFactory tcpNetServerConnectionFactory = new TcpNetServerConnectionFactory(clientSocketPort);
tcpNetServerConnectionFactory.setSerializer(new CustomSerializer());
tcpNetServerConnectionFactory.setDeserializer(new CustomDeserializer());
tcpNetServerConnectionFactory.setSingleUse(true);
return tcpNetServerConnectionFactory;
}
#Bean
public TaskExecutor taskExecutor () {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(50);
executor.setMaxPoolSize(100);
executor.setQueueCapacity(50);
executor.setAllowCoreThreadTimeOut(true);
executor.setKeepAliveSeconds(120);
return executor;
}
}
Did anyone had the same issue with having multiple concurrent Tcp client connections of more than 5 ?
Thanks
Client Code:
#Component
#Slf4j
#RequiredArgsConstructor
public class ScheduledTaskService {
// Timeout in milliseconds
private static final int SOCKET_TIME_OUT = 18000;
private static final int BUFFER_SIZE = 32000;
private static final int ETX = 0x03;
private static final String HEADER = "ABCDEF ";
private static final String data = "FIXED DARATA"
private final AtomicInteger atomicInteger = new AtomicInteger();
#Async
#Scheduled(fixedDelay = 100000)
public void sendDataMessage() throws IOException, InterruptedException {
int numberOfRequests = 10;
Callable<String> executeMultipleSuccessfulRequestTask = () -> socketSendNReceive();
final Collection<Callable<String>> callables = new ArrayList<>();
IntStream.rangeClosed(1, numberOfRequests).forEach(i-> {
callables.add(executeMultipleSuccessfulRequestTask);
});
ExecutorService executorService = Executors.newFixedThreadPool(numberOfRequests);
List<Future<String>> taskFutureList = executorService.invokeAll(callables);
List<String> strings = taskFutureList.stream().map(future -> {
try {
return future.get(20000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
return "";
}).collect(Collectors.toList());
strings.forEach(string -> log.info("Message received from the server: {} ", string));
}
public String socketSendNReceive() throws IOException{
int requestCounter = atomicInteger.incrementAndGet();
String host = "localhost";
int port = 8000;
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(host, port);
socket.connect(address, SOCKET_TIME_OUT);
socket.setSoTimeout(SOCKET_TIME_OUT);
//Send the message to the server
OutputStream os = socket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
bos.write(HEADER.getBytes());
bos.write(data.getBytes());
bos.write(ETX);
bos.flush();
// log.info("Message sent to the server : {} ", envio);
//Get the return message from the server
InputStream is = socket.getInputStream();
String response = receber(is);
log.info("Received response");
return response;
}
private String receber(InputStream in) throws IOException {
final StringBuffer stringBuffer = new StringBuffer();
int readLength;
byte[] buffer;
buffer = new byte[BUFFER_SIZE];
do {
if(Objects.nonNull(in)) {
log.info("Input Stream not null");
}
readLength = in.read(buffer);
log.info("readLength : {} ", readLength);
if(readLength > 0){
stringBuffer.append(new String(buffer),0,readLength);
log.info("String ******");
}
} while (buffer[readLength-1] != ETX);
buffer = null;
stringBuffer.deleteCharAt(resposta.length()-1);
return stringBuffer.toString();
}
}
Since you are opening the connections all at the same time, you need to increase the backlog property on the server connection factory.
It defaults to 5.
/**
* The number of sockets in the connection backlog. Default 5;
* increase if you expect high connection rates.
* #param backlog The backlog to set.
*/
public void setBacklog(int backlog) {

unable to make activemq consumer to deque

I am creating a JMS chat application using activemq and spring boot. I am trying to send message from producer to multiple subscribers. I am able to send message i.e message is en-queued. but in my receiver part message is unable to de-queue.` I am using the below code for communicating message from producer to multiple subscribers.
public class WelcomeController implements MessageListener {
public static Boolean TRANSACTIONAL = false;
public static String TOPIC_NAME = "firstTopic";
public static String BROKER_URL = "tcp://localhost:61616";
public static String BROKER_USERNAME = "admin";
public static String BROKER_PASSWORD = "admin";
public void createProducer() throws JMSException {
Connection connection = null;
Session session = null;
try {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
connectionFactory.setBrokerURL(BROKER_URL);
connectionFactory.setPassword(BROKER_USERNAME);
connectionFactory.setUserName(BROKER_PASSWORD);
connection = connectionFactory.createConnection();
connection.setClientID("CircliTopic");
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
for (int i = 1; i <= 3; i++) {
session = connection.createSession(TRANSACTIONAL,
Session.AUTO_ACKNOWLEDGE);
Topic destination = session.createTopic(TOPIC_NAME);
MessageProducer producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
message.setText( "My text message was send and received");//
System.out.println("Sending text '" + message + "'");
producer.send(message);
MessageConsumer consumer = session
.createDurableSubscriber(destination, "Listener" + i);
consumer.setMessageListener(new WelcomeController());
}
} finally {
connection.close();
}`
}
#Override
public void onMessage(Message message) {
try {
if (message instanceof TextMessage) {
TextMessage text = (TextMessage) message;
System.out.println(" - Consuming text msg: " + text.getText());
} else if (message instanceof ObjectMessage) {
ObjectMessage objmsg = (ObjectMessage) message;
Object obj = objmsg.getObject();
System.out.println(" - Consuming object msg: " + obj);
} else {
System.out.println(
" - Unrecognized Message type " + message.getClass());
}
} catch (JMSException e) {
e.printStackTrace();
}
}
I am able to get consuming text message in my console but my message is not de-queued to the subscribers and also in my activemq server message is not dequeued.
You are creating a Topic subscription only after the message has been sent and that won't work because these are Topics and a Topic with no subscriptions simply discards all messages sent to it. You need to establish a durable Topic subscription prior to any messages being sent, or switch to Queues if your design allows as a Queue will store a message sent to it until consumed.
It is hard to say more without knowing your requirements but it seems you need to spend a little bit more time understanding how Topics work.

Remove Thread.sleep() in case of Sending Message to ActiveMQ

I was fixing sonar lint error in my project. I have seen a block of Code where sonar lint is giving me error of rule squid:S2276 to replace Thread.sleep(100); with wait(). But wait() should be in conditional loop to escape spurious wakeup problem. But I am not getting such a condition how I should use.
Can i achieve the same thing without sleep()
public class ACTOOBEventSubSMSProducer {
private ACTOOBEventSubSMSProducer(){
super();
}
private static Logger logger = LoggerManager.getInstance().getCoreProcessingLogger();
public static final String CONNECTION_FACTORY = "java:jboss/activemq/ConnectionFactory";
static final String QUEUE_NAME = "java:jboss/exported/jms/queue/actOOBEventSubscriptionSMS";
static ConnectionFactory connectionFactory = null;
static Connection connection = null;
static Session session = null;
static Destination destination = null;
static MessageProducer messageProducer = null;
static {
connectionFactory = ServiceLocator.getJmsConnectionFactory(CONNECTION_FACTORY);
try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE);
destination = ServiceLocator.getJmsDestination(QUEUE_NAME);
messageProducer = session.createProducer(destination);
messageProducer.setDisableMessageID(true);
messageProducer.setDisableMessageTimestamp(true);
} catch (JMSException e) {
logger.error("Error in creating ConnectionFactory",e);
}
}
/**
* This method sends OOB Event SMS Message in Queue.
*
* #param message
*/
public static synchronized void sendMessage(Serializable payload) throws JmsProducerException {
try {
ObjectMessage message = session.createObjectMessage(payload);
messageProducer.send(message, javax.jms.DeliveryMode.NON_PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY,
1800000);
} catch (JMSException je) {
try {
Thread.sleep(100);
ObjectMessage message = session.createObjectMessage(payload);
messageProducer.send(message, javax.jms.DeliveryMode.PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY,
1800000);
} catch (JMSException jee) {
logger.error("Error in sendMessage()",jee);
throw new JmsProducerException(jee);
} catch (InterruptedException ie) {
logger.error("Error in sendMessage()",ie);
Thread.currentThread().interrupt();
throw new JmsProducerException(ie);
}
} catch (ServiceLocatorException sle) {
logger.error("Error in sendMessage()",sle);
throw new JmsProducerException(sle);
}
}
}
A carefully crafted for loop with the iterations count being the number of times you wanted to retry and some exception handling logic to break the loop if things work would do the trick in at a slightly clearer manner perhaps, otherwise using a ScheduledThreadPoolExecutor or or Timer would be an option.

How to get number of pending message in a jms queue

Is there any way to get count number of pending messages in jms queue. My aim is to close the connection if there is no message remaining in the queue to process. how can i achieve this.
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
Connection connection = connectionFactory.createConnection("admin", "admin");
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(subject);
MessageConsumer consumer = session.createConsumer(destination);
while (true) {
Message message = consumer.receive();
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
System.out.println("Incoming Message:: '" + textMessage.getText() + "'");
}
}
The only reliable way to get the true Queue count form the broker is to use the JMX MBean for the Queue and call the getQueueSize method.
The other programmatic alternative is to use the Statistics Broker Plugin which requires that you be able to change broker configuration to install it. Once installed you can send a special message to the control queue and get a response with details for the destination you want to monitor.
Using a QueueBrowser doesn't give you a true count because the browser has a max limit on how many messages it will page into memory to send you, so if your queue is deeper than the limit you won't get the actual size, just the value of the max page size limit.
I have done this by using createBrowser method below is my updated code.
public static void main(String[] args) throws JMSException {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
Connection connection = connectionFactory.createConnection("admin", "admin");
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(subject);
int queueSize = QueueConsumer.getQueueSize(session, (Queue) destination);
System.out.println("QUEUE SIZE: " + queueSize);
MessageConsumer consumer = session.createConsumer(destination);
for (int i = 0; i < queueSize; i++) {
Message message = consumer.receive();
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
System.out.println("Incomming Message: '" + textMessage.getText() + "'");
}
}
connection.close();
}
private int getQueueSize(Session session, Queue queue) {
int count = 0;
try {
QueueBrowser browser = session.createBrowser(queue);
Enumeration elems = browser.getEnumeration();
while (elems.hasMoreElements()) {
elems.nextElement();
count++;
}
} catch (JMSException ex) {
ex.printStackTrace();
}
return count;
}
I have done this with jmx it worked thanx #Tim Bish
here is my updated code
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://0.0.0.0:44444/jndi/rmi://0.0.0.0:1099/karaf-root");
HashMap<String, String[]> environment = new HashMap<String, String[]>();
String[] creds = { "admin", "admin" };
environment.put(JMXConnector.CREDENTIALS, creds);
JMXConnector jmxc = JMXConnectorFactory.connect(url, environment);
MBeanServerConnection connection = jmxc.getMBeanServerConnection();
ObjectName nameConsumers = new ObjectName("org.apache.activemq:type=Broker,brokerName=amq,destinationType=Queue,destinationName=myqueue");
DestinationViewMBean mbView = MBeanServerInvocationHandler.newProxyInstance(connection, nameConsumers, DestinationViewMBean.class, true);
long queueSize = mbView.getQueueSize();
System.out.println(queueSize);
Just break the loop and close the connection if your JMS Message is null..
while (true) {
Message message = consumer.receive(2000);
if (message == null){
break;
}
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
System.out.println("Incoming Message:: '" + textMessage.getText() + "'");
}
}
connection.close();

Resources