-
15. Re: namenotfound exception in JMS Client
cypnsv Dec 8, 2006 6:37 PM (in response to cypnsv)You are great! Thanks a lot
its fine now
But i have a doubt,
Actual queueconnection factory name declared in my web.xml is AlarmMgrConnectionFactory and as per the server.log file its jndianame is java:AlarmMgrConnectionFactory
Is it not necessary to give this connection factory name instead of "Connectionfactory" -
16. Re: namenotfound exception in JMS Client
cypnsv Dec 8, 2006 6:54 PM (in response to cypnsv)i have a queue connection factory and topic connection factory ,
i need to use both of them in my jmsclient
but i try to use these connection factories i get the exception as
AlarmMgrConnectionFactory not bound and also EventConnectionFactory not bound
But as per the server.log files these connection factories are bound
below is my code of jmsclient program, please check the program and let me know what i need to do to make this program runimport com.tlc.utils.Utility; import com.tlc.event.TLEvent; import java.math.BigInteger; import java.io.*; import javax.jms.*; import java.util.*; import javax.naming.*; import java.rmi.RemoteException; import javax.rmi.PortableRemoteObject; import javax.ejb.CreateException; import java.sql.Timestamp; import org.apache.log4j.*; /** * The class schedules and manages time-based events. * External modules can interface with the AlarmManager only via JMS Messages. * See package level comments on how to send messages to the AlarmManager, * what kind of messages are sent by the AlarmManager. */ public class AlarmManager extends TimerTask implements MessageListener { private static Category logger = Category.getInstance(AlarmManager.class.getName()); private static java.util.Date now = new java.util.Date(); private static final long CONNECTION_INITIAL_WAIT = 10000; // 10 seconds private static final long CONNECTION_TEST_PERIOD = 180000; // 3 minutes private static final long EVENT_RETRY_PERIOD = 300000; // 5 minutes private static final int MSG_PRIORITY = 5; private static final long MSG_TIMETOLIVE = 3600000; // One hour public String TLPROP_CLUSTER_MEMBERS = "cluster_members"; private static String initJNDIInitialContextFactory = null; private static String initJMSInitialContextFactory = null; private static String initJMSAlarmConnFactoryName = "AlarmMgrConnectionFactory"; private static String initJMSEventConnFactoryName = "EventConnectionFactory"; private static String initJMSAlarmQueue = "queue/AlarmMgrRecvQueue"; private static String initJMSEventTopic = "topic/Event"; private static String initJMSProviders = "localhost:3099"; private static String initAlarmHomeName = null; public static final String MSG_ADD_ALARM = "ADD_ALARM"; public static final String MSG_DEL_ALARM = "DEL_ALARM"; public static final String MSGTYPE = "MSGTYPE"; public static final String ALARM_ID = "ALARM_ID"; public static final String TIMESTAMP = "TIMESTAMP"; public static final String TIMEINTERVAL = "TIMEINTERVAL"; public static final String CID = "CID"; public static final String USERID = "USERID"; public Vector clusterMembers = new Vector(); private Properties tlGlobalProperties = null; /* * The connectionTimer is used to periodically check the status of the * the JMS connections to all servers in the cluster and to attempt to * reestablish them, if necessary. */ private Timer connectionTimer = null; /* * The alarmTimer is used to schedule all alarms. */ private Timer alarmTimer = null; private boolean isActive = false; private Map alarmtasks = null; private Vector servers = new Vector(); /* * Instances of the Server class are used to represent each server in the cluster */ private static class Server implements ExceptionListener { public boolean valid; public AlarmManager am; public String provider; public javax.jms.Queue alarmQ; public javax.jms.Topic eventT; public String alarmQName; public String eventTName; public QueueConnection qconnection; public TopicConnection tconnection; public TopicSession tsession; public TopicPublisher eventPublisher; public QueueReceiver alarmReceiver; public Alarm alarmEJB; public Server(AlarmManager am, String provider) { this.valid = false; this.am = am; this.provider = provider; this.alarmQName = alarmQName; this.eventTName = eventTName; this.alarmQ = null; this.eventT = null; this.qconnection = null; this.tconnection = null; this.tsession = null; this.eventPublisher = null; this.alarmReceiver = null; this.alarmEJB = null; } public void init() throws NamingException, JMSException, RemoteException, CreateException { // Set up JMS stuff Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, initJMSInitialContextFactory); System.out.println("initJMSInitialContextFactory" + initJMSInitialContextFactory); env.put(Context.PROVIDER_URL, provider); System.out.println("provider" + provider); InitialContext ctx = new InitialContext(env); qconnection = ((QueueConnectionFactory)ctx.lookup(initJMSAlarmConnFactoryName)).createQueueConnection(); System.out.println("initJMSAlarmConnFactoryName " + initJMSAlarmConnFactoryName); qconnection.setExceptionListener(this); QueueSession qsession = qconnection.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE); alarmQ = (javax.jms.Queue)ctx.lookup(initJMSAlarmQueue); alarmReceiver = qsession.createReceiver(alarmQ); alarmReceiver.setMessageListener(am); tconnection = ((TopicConnectionFactory)ctx.lookup(initJMSEventConnFactoryName)).createTopicConnection(); tconnection.setExceptionListener(this); tsession = tconnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); eventT = (Topic)ctx.lookup(initJMSEventTopic); eventPublisher = tsession.createPublisher(eventT); ctx.close(); // Get Alarm EJB env.put(Context.INITIAL_CONTEXT_FACTORY, initJNDIInitialContextFactory); ctx = new InitialContext(env); Object obj = ctx.lookup(initAlarmHomeName); AlarmHome home = (AlarmHome)PortableRemoteObject.narrow(obj, AlarmHome.class); alarmEJB = home.create(); ctx.close(); valid = true; } public void onException(JMSException ex) { logger.error("onException() called", ex); valid = false; try { qconnection.close(); tconnection.close(); alarmEJB.remove(); } catch (Exception e) { // ignore } finally { am.onServerException(this); } } public void start() { if (valid) { try { qconnection.start(); tconnection.start(); } catch (JMSException e) { // ignore } } } public void stop() { if (valid) { try { qconnection.close(); tconnection.close(); } catch (JMSException e) { // ignore } } } } public static void main(String args[]) { // If a Log4j config file specified as an argument, use it. // Otherwise, if there is a "logger.props" in the current directory, use it. // If none of the above, configure the logger statically. if (args.length > 0) PropertyConfigurator.configure(args[0]); else { File configFile = new File("logger.props"); if (configFile.exists()) PropertyConfigurator.configure("logger.props"); else { try { RollingFileAppender rfap = new RollingFileAppender(new PatternLayout("%5p %d{DATE} [%t] (%F:%L) - %m%n"), "am.log", true); rfap.setMaxBackupIndex(5); rfap.setMaxFileSize("1MB"); BasicConfigurator.configure(rfap); } catch (IOException e) { BasicConfigurator.configure(); } logger.setLevel(Level.DEBUG); } } AlarmManager as = new AlarmManager(); } public Properties getTLProps() throws Exception { if (tlGlobalProperties == null) { // TightLink global properties String tlPropFile ="C:\\jboss\\bin\\Tightlink_prod\\config\\TLGlobal.properties"; Properties tlProps = new Properties(); try { tlProps.load(new FileInputStream(tlPropFile)); tlGlobalProperties = tlProps; String prop = tlProps.getProperty(TLPROP_CLUSTER_MEMBERS); if (prop != null) { StringTokenizer stk = new StringTokenizer(prop, ";"); while (stk.hasMoreTokens()) { clusterMembers.addElement(stk.nextToken().trim()); } } } catch (FileNotFoundException fe) { throw new Exception(fe.getMessage()); } catch (IOException ioe) { throw new Exception(ioe.getMessage()); } } return tlGlobalProperties; } public AlarmManager() { try { // Get initialization parameters (from TLGlobal.properties): Properties globalProps = getTLProps(); initJNDIInitialContextFactory = globalProps.getProperty("jndi_context_factory"); initJMSInitialContextFactory = globalProps.getProperty("jms_context_factory"); initJMSAlarmConnFactoryName = globalProps.getProperty("jms_alarm_connection_factory"); initJMSEventConnFactoryName = globalProps.getProperty("jms_event_connection_factory"); initJMSAlarmQueue = globalProps.getProperty("jms_alarm_queue"); initJMSEventTopic = globalProps.getProperty("jms_event_topic"); initJMSProviders = globalProps.getProperty("cluster_members"); initAlarmHomeName = globalProps.getProperty("alarm_home"); } catch (Exception ex) { logger.error("Error getting initialization properties.", ex); System.exit(1); return; } if (initJMSProviders != null) { StringTokenizer stk = new StringTokenizer(initJMSProviders, ",;"); while (stk.hasMoreTokens()) { String provider = stk.nextToken().trim(); Server s = new Server(this, provider); servers.add(s); //logger.debug("Added server: " + provider); } } else { logger.error("Error: no JMS providers (cluster members) specified."); System.exit(1); return; } connectionTimer = new Timer(); connectionTimer.schedule(this, CONNECTION_INITIAL_WAIT, CONNECTION_TEST_PERIOD); } /** * This method (part of TimerTask interface) is called by the connectionTimer * periodically to test conncetions to the servers in the cluster. */ public void run() { testConnections(); } /** * Checks JMS connections to servers in the cluster and reestablishes them * if needed. */ private void testConnections() { logger.debug("Entering testConnections()"); int upServers = 0; Enumeration enum1 = servers.elements(); if (enum1 != null) { while (enum1.hasMoreElements()) { Server s = (Server)enum1.nextElement(); if (!s.valid) { try { s.init(); upServers++; } catch (Exception ex) { logger.error("Error initializing " + s.provider, ex); s.stop(); continue; } } else upServers++; } } if (upServers == 0) { logger.error("Couldn't connect to any servers."); setActive(false); } else if (!isActive) { setActive(true); } logger.debug("Exiting testConnections()"); } /** * This method forces this instance of AlarmManager to become active or inactive. */ private void setActive(boolean active) { if (active) { loadAlarms(); // start processing JMS messages Enumeration enum1 = servers.elements(); if (enum1 != null) { while (enum1.hasMoreElements()) { Server s = (Server)enum1.nextElement(); s.start(); } } isActive = true; } else { // stop processing JMS messages Enumeration enum1 = servers.elements(); if (enum1 != null) { while (enum1.hasMoreElements()) { Server s = (Server)enum1.nextElement(); s.stop(); } } // stop alarm timer if (alarmTimer != null) { alarmTimer.cancel(); alarmTimer = null; } isActive = false; } } /** * Invoked by JMS Provider when a JMS message is received for this * Alarm Manager. */ public void onMessage(Message msg) { logger.debug("Entering onMessage()"); try { String msgType = msg.getStringProperty(MSGTYPE); logger.debug("Message type: " + msgType); if (msgType == null) { logger.debug("Message Type is not set..."); return; } else if (msgType.equals(MSG_ADD_ALARM)) { logger.debug("Add Alarm received..."); createAlarm(msg); } else if (msgType.equals(MSG_DEL_ALARM)) { logger.debug("Delete Alarm received..."); deleteAlarm(msg); } else { logger.debug("Invalid message type: " + msgType); return; } // Acknowledge the JMS message msg.acknowledge(); } catch (Exception e) { logger.error("Exception in onMessage()", e); } finally { logger.debug("Exiting onMessage()"); } } /** * This method is called by a Server after it has caught a JMS exception * and stopped itself. */ public void onServerException(Server as) { isActive = false; Enumeration enum1 = servers.elements(); if (enum1 != null) { while (enum1.hasMoreElements()) { Server s = (Server)enum1.nextElement(); if (s.valid) { isActive = true; break; } } } } /** * Deletes the Alarm specified in the JMS message from the Alarms Table */ private void deleteAlarm(Message msg) { logger.debug("Entering deleteAlarm(Message)"); try { String alarmID = msg.getStringProperty(ALARM_ID); AlarmTask at = (AlarmTask)alarmtasks.get(alarmID); if (at == null) return; else deleteAlarm(at); } catch (JMSException e) { logger.error("Exception in deleteAlarm()", e); } finally { logger.debug("Exiting deleteAlarm(Message)"); } } /** * Deletes the Alarm corresponding to an AlarmTask */ private void deleteAlarm(AlarmTask at) { logger.debug("Entering deleteAlarm(AlarmTask)"); try { logger.debug("Deleting Alarm..."); at.setDeleted(true); alarmtasks.remove(at.getId()); Alarm alarm = getAlarmEJB(); alarm.deleteAlarm(at.getId()); } catch (Exception e) { logger.error("Exception in deleteAlarm()", e); } finally { logger.debug("Exiting deleteAlarm(AlarmTask)"); } } /** * This method creates a time-based alarm. It adds * the Alarm to the Alarms table, and schedules it with the Timer. */ private void createAlarm(Message msg) { logger.debug("Entering createAlarm()"); try { ObjectMessage omsg = (ObjectMessage) msg; HashMap hm = (HashMap)omsg.getObject(); Timestamp ts = null; //This will be either Integer or Long Object tStamp; if ((hm.get(TIMESTAMP) == null) && (hm.get(TIMEINTERVAL) == null)) { logger.debug("NO Timestamp or TimeInterval specified for ALARM message"); return; } if (hm.get(TIMEINTERVAL) != null) { //The following code is to get the long value from tStamp. //tStamp - Long object when we use "times"(multiply) in rule engine. //tStamp - Integer when we directly get it from TLObject. //tStamp - value in milliSeconds tStamp = (Object)hm.get(TIMEINTERVAL); logger.debug("Processing TIMEINTERVAL tStamp is : " + tStamp.toString()); ts = new Timestamp(now().getTime() + ((new Long(tStamp.toString())).longValue())); } else { //For absolute time tStamp is java.util.Date tStamp = (Object) hm.get(TIMESTAMP); logger.debug("Processing TIMESTAMP tStamp is : " + tStamp.toString()); ts = new Timestamp(((java.util.Date)tStamp).getTime()); } String id = newID(); Alarm alarm = getAlarmEJB(); alarm.createAlarm(id, ts, hm); // Schedule a Timer Task as well... AlarmTask at = new AlarmTask(this, id, ts, hm); alarmTimer.schedule(at, ts); alarmtasks.put(id, at); logger.debug("Created AlarmTask"); } catch (Exception e) { logger.error("Exception in createAlarm()", e); } finally { logger.debug("Exiting createAlarm()"); } } /** * Loads alarms from the Alarms table and schedules them with * the Alarm Timer. */ public void loadAlarms() { logger.debug("Entering loadAlarms()"); if (alarmTimer != null) alarmTimer.cancel(); alarmTimer = new Timer(); try { Alarm alarm = getAlarmEJB(); Iterator it = alarm.getAlarms().iterator(); Vector tasks = new Vector(); while (it.hasNext()) { Object[] row = (Object[])it.next(); AlarmTask at = new AlarmTask(this, (String)row[0], (Timestamp)row[1], (HashMap)row[2]); tasks.add(at); logger.debug("Added alarm task for id: " + at.getId()); } if (alarmtasks != null) alarmtasks.clear(); else { // The alarmtasks HashMap is synchronized alarmtasks = Collections.synchronizedMap(new HashMap()); } for (int i=0; i < tasks.size(); i++) { AlarmTask at = (AlarmTask)tasks.get(i); alarmTimer.schedule(at, at.getTimestamp()); alarmtasks.put(at.getId(), at); } logger.debug("Loaded alarms..."); } catch (Exception e) { logger.error("Exception in loadAlarms()", e); } finally { logger.debug("Exiting loadAlarms()"); } } public void alarmExpired(AlarmTask at) { logger.debug("Entering alarmExpired()"); try { HashMap hm = at.getHashMap(); Object obj = (Object)hm.get(AlarmManager.CID); String cid = (obj != null ? obj.toString() : ""); obj = (Object)hm.get(AlarmManager.USERID); String userId = (obj != null ? obj.toString() : ""); hm.put(AlarmManager.ALARM_ID, at.getId()); TLEvent event = new TLEvent(TLEvent.ALARM_EXPIRED, new Long(now().getTime()), userId, null , cid , hm); if (sendEvent(event)) { deleteAlarm(at); } else { // Couldn't send the ALARM_EXPIRED event // Try it again in EVENT_RETRY_PERIOD alarmTimer.schedule(at, EVENT_RETRY_PERIOD); } } catch (Exception e) { logger.error("Exception in alarmExpired()", e); } finally { logger.debug("Exiting alarmExpired()"); } } private boolean sendEvent(TLEvent ev) { logger.debug("Entering sendEvent()"); boolean success = false; Enumeration enum1 = servers.elements(); if (enum1 != null) { while (enum1.hasMoreElements() && !success) { Server s = (Server)enum1.nextElement(); if (s.valid) { try { ObjectMessage omsg = s.tsession.createObjectMessage(ev); s.eventPublisher.publish(omsg, DeliveryMode.PERSISTENT, MSG_PRIORITY, MSG_TIMETOLIVE); success = true; } catch (JMSException ex) { // Mark this connection bad so it can be reinitialized next time logger.error("Error sending event to " + s.provider, ex); s.stop(); s.valid = false; // Go on and try to find another server to send to } } } } logger.debug("Exiting sendEvent() - ret=" + success); return success; } private Alarm getAlarmEJB() throws Exception { Alarm alarm = null; Enumeration enum1 = servers.elements(); if (enum1 != null) { while ((alarm == null) && enum1.hasMoreElements()) { Server s = (Server)enum1.nextElement(); if (s.valid) alarm = s.alarmEJB; } } if (alarm == null) throw new Exception("Unable to get an Alarm EJB."); return alarm; } /** * Returns a unique string for use as an ALARM ID. */ private String newID() { long timetick = System.currentTimeMillis(); Random rd = new Random(timetick); BigInteger bi = new BigInteger(64, rd); bi.shiftLeft(64); BigInteger bi1 = BigInteger.valueOf(timetick); bi = bi.add(bi1); return bi.toString(36); } private synchronized java.util.Date now() { now.setTime(System.currentTimeMillis()); return now; } }
-
17. Re: namenotfound exception in JMS Client
cypnsv Dec 8, 2006 7:08 PM (in response to cypnsv)please clarify my doubt
Please..Please..Please.. -
18. Re: namenotfound exception in JMS Client
weston.price Dec 8, 2006 7:10 PM (in response to cypnsv)I am not sure what you are asking.
Lookup "ConnectionFactory"
Your resources are not available to you as a thin client. Do not put them in yoru code. -
19. Re: namenotfound exception in JMS Client
cypnsv Dec 8, 2006 7:17 PM (in response to cypnsv)ok i will explain you more
There is a EJB which uses these connection factory and queue to send message and my will listen to this queue
my question is that ,is it not necessary to same connection factory name or is it fine using "Connectionfactory" in my JMSCLIENT
Since i thought that connection factory also plays a part in sending and reveiving message i have asked this doubt -
20. Re: namenotfound exception in JMS Client
cypnsv Dec 8, 2006 7:19 PM (in response to cypnsv)Hi weston
Thanks for the great help!
I may come back with some more doubts
i need to check and make my program to recive the messages successfully