0 Replies Latest reply on Jul 30, 2009 10:08 PM by PavithraMK

    Using Jms Consumer with Flex using BlazeDS JMSAdapter

    PavithraMK

      Hello,

       

      I want my flex client application to consume from data from destination (Topic). At the back end a java application will be running, this will be listening to a folder changes. Whenever a new xml file gets added to that folder, java application has to parse the XML file and has  to send that message to the Topic (destination).Above Java program is acts as JMSPublisher.

       

      Flex client application has to get message from destination automatically whenever JMSPublisher sends message to the destination.

      JMSPublisher is sending the message to the destination, but Flex client not able to get the message.

       

       

      Below are the code for flex GUI and  JMS Publisher:

       

      1. Flex GUI:

       

      <?xml version="1.0" encoding="utf-8"?>

      <!--mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" borderStyle="inset" creationComplete="logon();"-->

      <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" borderStyle="inset" creationComplete="logon();">

      <!--mx:RemoteObject id="jmsProd" destination="JMSDataProducer">

      <mx:method name="fill" result="fillResult(event)"/>

      </mx:RemoteObject-->

      <mx:XML id="statusXML"

      source="assets/status.xml" />

       

      <mx:XMLListCollection id="RAXMLList"

      source="{statusXML.Message}" />

      <mx:XMLListCollection id="UserXMLList"

      source="{datagrid.selectedItem.ViewonlyUsers.User}" />

      <mx:Script>

      <![CDATA[

      import mx.rpc.events.ResultEvent;

      import mx.messaging.*;

      import mx.messaging.messages.*;

      import mx.messaging.events.*;

      import mx.controls.Alert;

      // Create a variable of type Consumer.

      private var consumer:Consumer;

      private var producer:Producer;

      private var msg:IMessage;

      private var message:String;

      // Create the Consumer.

      private function logon():void {

      //producer=new Producer();

      //producer.destination="flex-topic";

      //jmsProd.statusInfo();

       

       

      consumer = new Consumer();

      consumer.destination = "flex-topic";

      consumer.addEventListener (MessageEvent.MESSAGE, messageHandler);

      consumer.addEventListener (MessageFaultEvent.FAULT, faultHandler);

      consumer.subscribe();

       

      }

      // Write received message to TextArea control.

      private function messageHandler(event:MessageEvent):void {

      // Handle message event.

      //message = event.message.body.toString();

      //Alert.show(message);

      ta.text += event.message.body + "\n";

      }

      private function faultHandler(event:MessageFaultEvent):void{

      // Handle message fault event.

      }

       

      private function fillResult(event:ResultEvent):void

      {

      ta.text += event.message.body + "\n";

      }

       

      ]]>

      </mx:Script>

      <!--mx:Consumer id="Consumer" destination="flex-topic" message="messageHandler(event)" fault="faultHandler(event)"/-->

       

      <mx:Canvas id="avaTools" label="Available Tools">

       

      <mx:DataGrid id="datagrid" x="10" y="10" width="429" height="187" editable="false" backgroundColor="#EEEEFF" dataProvider="{RAXMLList}" rowCount="{RAXMLList.length+1}">

      <mx:columns>

      <mx:DataGridColumn headerText="Tool" dataField="ToolName"/>

      <mx:DataGridColumn headerText="ToolIP" dataField="ToolIP"/>

      <mx:DataGridColumn headerText="Operation" dataField="Operation"/>

      <mx:DataGridColumn headerText="Control" dataField="FullControl"/>

      <mx:DataGridColumn headerText="Users" dataField="ViewonlyUsers"/>

      </mx:columns>

      <!--mx:dataProvider>

      <mx:XMLList xmlns="">

      <node pcTool="Tool1" status="Online" control="Mark" user1="Peter" user2="John" user3="Tom" user4=""/>

      <node pcTool="Tool2" status="Online" control="Steve" user1="Allan" user2="Joe" user3="Johnny" user4="Peter"/>

      <node pcTool="Tool3" status="Online" control="" user1="" user2="" user3="" User4=""/>

      <node pcTool="Tool4" status="Online" control="Katie" user1="Nichole" user2="" user3="" User4=""/>

      <node pcTool="Tool5" status="Online" control="" user1="" user2="" user3="" User4=""/>

      <node pcTool="Tool6" status="Online" control="Mac" user1="" user2="" user3="" User4=""/>

      </mx:XMLList>

      </mx:dataProvider-->

      </mx:DataGrid>

      <!--mx:DataGrid id="parametersDataGrid"

      dataProvider="{UserXMLList}"

      width="100%"

      visible="{UserXMLList.length > 0}"

      rowCount="{UserXMLList.length + 1}">

      <mx:columns>

      <mx:DataGridColumn id="parameterNameCol"

      dataField="User"

      headerText="User" />

       

      </mx:columns>

      </mx:DataGrid-->

       

      <mx:TextArea id="ta" height="100%" width="100%"/>

       

       

      </mx:Canvas>

       

       

       

       

       

       

      </mx:Application>

       

      2. JMSPublisher

       

       

      package com.amat.ui.service;

      import org.apache.commons.vfs.*;
      import org.apache.commons.vfs.impl.DefaultFileMonitor;
      import org.apache.commons.vfs.provider.local.DefaultLocalFileProvider;
      import org.apache.commons.vfs.provider.LocalFileProvider;
      import java.io.File;

      //Pacakages for DOM parser
      import javax.xml.parsers.DocumentBuilder;
      import javax.xml.parsers.DocumentBuilderFactory;
      import org.w3c.dom.Document;
      import org.w3c.dom.Element;
      import org.w3c.dom.Node;
      import org.w3c.dom.NodeList;

      //Packages for Java Messaging Service
      import javax.jms.BytesMessage;
      import javax.jms.Connection;
      import javax.jms.DeliveryMode;
      import javax.jms.JMSException;
      import javax.jms.Message;
      import javax.jms.MessageListener;
      import javax.jms.MessageProducer;
      import javax.jms.Session;
      import javax.jms.TextMessage;
      import javax.jms.Topic;
      import javax.jms.TopicSession;
      import javax.jms.TopicConnection;
      import javax.jms.TopicPublisher;

      import org.apache.activemq.ActiveMQConnectionFactory;

      import java.util.ArrayList;
      import com.amat.ui.bean.AvailableUsersBean;
      import com.amat.ui.bean.ActiveUsersBean;


      public class JMSProducer{

      public void statusInfo(){
       
        try{
       
        FileSystemManager fsManager = VFS.getManager();
        FileObject jarFile = fsManager.resolveFile("file:c:/ExFolder/");
        DefaultFileMonitor fm = new DefaultFileMonitor(new FListener());
        //LocalFileProvider provider = new DefaultLocalFileProvider();  
        //FileObject file = provider.findLocalFile(new File("C:/ExFolder/"));
        fm.setRecursive(true);
        fm.addFile(jarFile);
        fm.start();
        fm.run();
        //FileListener FL = new FListener();
        //FileSystem FS = jarFile.getFileSystem();
        //FS.addListener(jarFile,FL);

        }catch(Exception e){System.out.println("Exception occured");
        }
      }
       
      public static void main(String arg[]){
       
        JMSProducer jmsProducer = new JMSProducer();
        jmsProducer.statusInfo();
      }
      }


       

      class FListener implements FileListener{

      private final Object mutex = new Object();
      private TopicConnection conn;
      private TopicSession sess;
      private TopicPublisher publisher;
      private Topic topic;
      private ActiveMQConnectionFactory factory;
      private String message = new String("Hello");

      private String url = "tcp://localhost:61616";

      public void fileChanged(FileChangeEvent fcEvt)
        throws Exception

      {
        System.out.println("fileChanged: "+fcEvt.getFile().getName());
        FileName fn = fcEvt.getFile().getName();
        String xmlname = fn.getPath();
        System.out.println(xmlname);
        publishXMLMessage(xmlname);
      }


      public void fileDeleted(FileChangeEvent fcEvt)

      throws Exception

      {
        System.out.println("FileDeleted"+fcEvt.getFile().getName());
      }


      public void fileCreated(FileChangeEvent fcEvt)

      throws Exception

      {
        System.out.println("FileCreated"+fcEvt.getFile().getName());
        FileName fn = fcEvt.getFile().getName();
        String xmlname = fn.getPath();
        System.out.println(xmlname);
        publishXMLMessage(xmlname);
      }

      public void publishXMLMessage(String xmlName)throws JMSException{
       
        try {
           ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
           conn = factory.createTopicConnection();
           sess = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
           topic = sess.createTopic("flex-topic");

           publisher =  sess.createPublisher(topic);
           publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
           String msg=null;

             File file = new File(xmlName);
             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
             DocumentBuilder db = dbf.newDocumentBuilder();
             Document doc = db.parse(file);
             doc.getDocumentElement().normalize();
           Element ele = doc.getDocumentElement();
           System.out.println("Attribute value"+ele.getAttribute("Type"));
             System.out.println("Root element " + doc.getDocumentElement().getNodeName());
             NodeList nodeLst = doc.getElementsByTagName("Message");
           System.out.println(((Node)nodeLst.item(0)).getAttributes());
             System.out.println("Information of all employees");
          
             AvailableUsersBean avaUsers;
             for (int s = 0; s < nodeLst.getLength(); s++) {

                Node fstNode = nodeLst.item(s);
            avaUsers = new AvailableUsersBean ();
            ArrayList<AvailableUsersBean> toolsInfo = new ArrayList<AvailableUsersBean>();  
                if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
       
                 Element fstElmnt = (Element) fstNode;
             
                   NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("ToolName");
                   Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                   NodeList fstNm = fstNmElmnt.getChildNodes();
              String ToolName = ((Node)fstNm.item(0)).getNodeValue();
                   avaUsers.setToolName(ToolName);

                   NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("ToolIP");
                   Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                   NodeList lstNm = lstNmElmnt.getChildNodes();
              String ToolIP = ((Node)lstNm.item(0)).getNodeValue();
                   avaUsers.setToolIP(ToolIP);

              //NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("ToolIP");
                   //Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                   //NodeList lstNm = lstNmElmnt.getChildNodes();

              NodeList operNmElmntLst = fstElmnt.getElementsByTagName("Operation");
                   Element operNmElmnt = (Element) operNmElmntLst.item(0);
                   NodeList operNm = operNmElmnt.getChildNodes();
              String operationName = ((Node)operNm.item(0)).getNodeValue();
              avaUsers.setOperation(operationName);

              NodeList conNmElmntLst = fstElmnt.getElementsByTagName("FullControl");
                   Element conNmElmnt = (Element) conNmElmntLst.item(0);
                   NodeList conNm = conNmElmnt.getChildNodes();
              String controlName = ((Node)conNm .item(0)).getNodeValue();
              avaUsers.setFullControl(controlName);

              toolsInfo.add(avaUsers);

             msg = ((Node) fstNm.item(0)).getNodeValue()+" "+((Node) lstNm.item(0)).getNodeValue()+" "+((Node) operNm.item(0)).getNodeValue()+" "+((Node) conNm.item(0)).getNodeValue();
             message = message.concat(msg);
            
                }
             }
           System.out.println("Sending message to the Subscriber "+message);
           TextMessage textMsg = sess.createTextMessage(message);
           //msg.writeBytes(msgBytes);
           publisher.publish(textMsg);
            }catch(JMSException jms){
             jms.printStackTrace();
            }
            catch (Exception e) {
           e.printStackTrace();
          }
          finally{
          conn.close();
          }
        
      }


      }