消息驱动的bean avec jboss 6

时间:2012-04-18 18:19:19

标签: ejb-3.0 jboss6.x message-driven-bean

您好我想在发生关键操作时通知我的客户端,所以我想使用消息驱动的bean 我写了这个mdb`

@MessageDriven(mappedName = "topic/MailConfirmationMdbTopic", 
activationConfig = {
 //@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
 //@ActivationConfigProperty(propertyName="subscriptionDurability", propertyValue="Durable"),
 //@ActivationConfigProperty(propertyName="subscriptionName", propertyValue="topicmdb"),
 //@ActivationConfigProperty(propertyName="clientId", propertyValue="mdbtopic-test"),

 @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
 @ActivationConfigProperty(propertyName = "destination", propertyValue = "topic/MailConfirmationMdbTopic")  
})

public class MailConfirmationMdbBean implements MessageListener {

    private static final Logger log = Logger.getLogger(MailConfirmationMdbBean.class);

     public MailConfirmationMdbBean(){
         log.info("Initialisation de l'envoi du mail depuis MailConfirmationMdbBean");  
     }

     public void onMessage(Message message) { 

        // Pour la classe de test MailConfirmationProducteur
      if (message instanceof TextMessage) {
           TextMessage mail = (TextMessage) message;
           // L'envoi d'un mail de confirmation au client est ici simul� par l'affichage d'un message au niveau des logs.
           try {
            String leMail = mail.getText();
            log.info(" Envoi du mail : " + leMail);
            log.info(" --------------------------------------------------- ");
            //sendMsg("eniejb3@gmail.com", "Confirmation de commande.", leMail);
            log.info(" --------------------------------------------------- ");
            log.info(" Mail envoy�.");
           }

           catch (JMSException e) {
            e.printStackTrace();
           } 
      } else if  (message instanceof ObjectMessage) {
          ObjectMessage lemessage = (ObjectMessage) message;

          try {
               Commande commande = (Commande)lemessage.getObject();
                Client client = commande.getUtilisateurFk();
                Adresse adresse = client.getAdresseFk();
                String contenuMail = "Bonjour " + client.getNom() + " " + client.getPrenom() + ". \n" 
                + "Votre num�ro de commande est : " + commande.getCommandeid()
                + " \n" + "Vous avez command� les articles suivants : " + " \n" ;

                String lesArticles = "";                        
                Set <Lignecommande> listeArticles = commande.getLignecommandeCollection();
                for (Lignecommande lc :  listeArticles){                    
                    Article article = lc.getArticleFk();
                    lesArticles += article.getNom() + " : " + article.getPrix()  + " euros. \n" ;               
                }

                contenuMail += lesArticles;

                String ladresse = 
                " \n" + "Votre adresse est : "+ " \n" 
                + adresse.getNumero()  + " rue " + adresse.getRue()  + " " + adresse.getCodepostal()  + " " + adresse.getVille();

                contenuMail += ladresse;

                contenuMail += "\n Votre commande est en cours de traitement."; 

                log.info(" Envoi du mail au client: " );
                log.info(" --------------------------------------------------- ");

                sendMsg(client.getEmail(), "Confirmation de votre commande.", contenuMail);
                log.info(" --------------------------------------------------- ");
                log.info(" Mail envoy� au client.");
               }
                catch (MessagingException e) {
                    e.printStackTrace();
                }
                catch (NamingException e) {
                    e.printStackTrace();                
               } catch (JMSException e) {
                    e.printStackTrace();
               } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
               }                  
      }
     }

        protected void sendMsg(String email, String subject, String body) throws MessagingException, NamingException, UnsupportedEncodingException {

            Properties props = new Properties();
            InitialContext ictx = new InitialContext(props);
            javax.mail.Session mailSession = (javax.mail.Session) ictx.lookup("java:/Mail");

            MimeMessage message = new MimeMessage(mailSession);

            message.setSubject(subject);
            message.setRecipients(javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse(email, false));
            message.setText(body);
            message.saveChanges();

            Transport transport = mailSession.getTransport("smtp");
            try {
                transport.connect();
                transport.sendMessage(message, message.getAllRecipients());
                log.info("Message envoy�");
            }
            finally {
                transport.close();
            }
        }

     @PreDestroy  
     public void remove() {
         log.info("Suppression de MailConfirmationMdbBean.");
     }
}`

为了测试,我有这个程序:

public class MailConfirmationConsommateur implements MessageListener {
 public static void main(String[] args) throws Exception {
     new MailConfirmationConsommateur();
 }

 public MailConfirmationConsommateur() throws Exception {

    Properties props = new Properties(); //System.getProperties(); 
      //proprietes.load(new FileInputStream("jndi.properties")); 
     props.put(Context.INITIAL_CONTEXT_FACTORY,
                "org.jnp.interfaces.NamingContextFactory");
        props.put(Context.URL_PKG_PREFIXES,
                "org.jboss.naming:org.jnp.interfaces");
        props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
      InitialContext ctx = new InitialContext(props);       
      // 1:  recherche d'une connection factory
      ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");
      // 2:  création d'une connection JMS
      Connection conn = factory.createConnection();   
      // 3: création d'une session
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      // 4. Recherche d'une destination
      Topic topic = (Topic) ctx.lookup("topic/MailConfirmationMdbTopic");        
      // 5: création d'un consommateur de message
      MessageConsumer consommateur =session.createConsumer(topic);  
      consommateur.setMessageListener(this);

      System.out.println("Client JMS MailConfirmationConsommateur é l'écoute de messages.");
      conn.start();   // 
 }

 public void onMessage(Message msg) {
      if (msg instanceof TextMessage) {
       TextMessage tm = (TextMessage) msg;  
       // L'envoi d'un mail de confirmation au client est ici simulé 
       // par l'affichage d'un message au niveau des logs.
       try {
        String mail = tm.getText();
        System.out.println("Le client JMS MailConfirmationConsommateur a reçu le message : " + mail);
       } catch (JMSException e) {
        e.printStackTrace();
       }
      }
 }

 @PreDestroy 
 public void remove() {
     System.out.println("Suppression du client JMS MailConfirmationConsommateur.");
 }

}

 public class MailConfirmationProducteur {

     private static final Logger log = Logger.getLogger(MailConfirmationProducteur.class);

     public static void main(String[] args) throws Exception { 
         // Properties proprietes = new Properties();  
         // proprietes.load(new FileInputStream("jndi.properties")); 
          InitialContext ctx = new InitialContext();
          // 1: recherche d'une connection factory
          ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");  
          // 2: création d'une connection JMS
          Connection conn = factory.createConnection();

          // 3: création d'une session
          Session session = conn.createSession(false,Session.AUTO_ACKNOWLEDGE);

          // 4: Recherche d'une destination
          Topic topic = (Topic) ctx.lookup("topic/MailConfirmationMdbTopic");

          // 5: création d'un producteur de message
          MessageProducer producteur = session.createProducer(topic);

          // 6: publication d'un message
          TextMessage msg = session.createTextMessage();
          msg.setText("Mail de confirmation pour le client.");
          producteur.send(msg);

          producteur.close(); 
          log.info("Message envoyé.");
     }
    }

如果我不是好的方式,我现在不行  在控制台上我有这个错误

   Exception in thread "main" javax.naming.NameNotFoundException: topic not     bound
        at org.jnp.server.NamingServer.getBinding(NamingServer.java:771)
        at org.jnp.server.NamingServer.getBinding(NamingServer.java:779)
        at org.jnp.server.NamingServer.getObject(NamingServer.java:785)
        at org.jnp.server.NamingServer.lookup(NamingServer.java:396)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:616)
        at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322)
        at sun.rmi.transport.Transport$1.run(Transport.java:177)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
        at java.lang.Thread.run(Thread.java:636)
        at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:255)
        at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:233)
        at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:142)
        at org.jnp.server.NamingServer_Stub.lookup(Unknown Source)
        at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:728)
        at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:688)
        at javax.naming.InitialContext.lookup(InitialContext.java:392)
        at com.soutem.ejb.mdb.MailConfirmationConsommateur.<init>(MailConfirmationConsommateur.java:42)
        at com.soutem.ejb.mdb.MailConfirmationConsommateur.main(MailConfirmationConsommateur.java:22)

当我运行producteur

public class MailConfirmationProducteur {

 private static final Logger log = Logger.getLogger(MailConfirmationProducteur.class);

 public static void main(String[] args) throws Exception { 
     // Properties proprietes = new Properties();  
     // proprietes.load(new FileInputStream("jndi.properties")); 
      InitialContext ctx = new InitialContext();
      // 1: recherche d'une connection factory
      ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");  
      // 2: création d'une connection JMS
      Connection conn = factory.createConnection();

      // 3: création d'une session
      Session session = conn.createSession(false,Session.AUTO_ACKNOWLEDGE);

      // 4: Recherche d'une destination
      Topic topic = (Topic) ctx.lookup("topic/MailConfirmationMdbTopic");

      // 5: création d'un producteur de message
      MessageProducer producteur = session.createProducer(topic);

      // 6: publication d'un message
      TextMessage msg = session.createTextMessage();
      msg.setText("Mail de confirmation pour le client.");
      producteur.send(msg);

      producteur.close(); 
      log.info("Message envoyé.");
 }
}

1 个答案:

答案 0 :(得分:0)

it works now , i fill the solution : here 

the  methode on my session bean for producing mail :

    public void producteurMail(Commande commande) {
        // Properties proprietes = new Properties();
        // proprietes.load(new FileInputStream("jndi.properties")
        InitialContext ctx = null;
        try {
            ctx = new InitialContext();
        } catch (NamingException e) {
            e.printStackTrace();
        }
        // 1: recherche d'une connection factory
        ConnectionFactory factory = null;
        try {
            factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");
        } catch (NamingException e) {
            e.printStackTrace();
        }
        // 2: création d'une connection JMS
        Connection conn = null;
        try {
            conn = factory.createConnection();
        } catch (JMSException e) {
            e.printStackTrace();
        }
        // 3: création d'une session
        Session session = null;
        try {
            session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        } catch (JMSException e) {
            e.printStackTrace();
        }
        // 4: Recherche d'une destination
        Topic topic = null;
        try {
            topic = (Topic) ctx.lookup("topic/MailConfirmationMdbTopic");

        } catch (NamingException e) {
            e.printStackTrace();
        }
        // 5: cr�ation d'un producteur de message
        MessageProducer producteur = null;
        try {
            producteur = session.createProducer(topic);
        // 6: publication d'un message
        TextMessage msg = null;

            msg = session.createTextMessage();
            msg.setText("Votre Commande est en cour de traitment .");
            //producteur.
            producteur.send(msg);
            producteur.close();
            conn.close();
            session.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
        log.info("Message envoyé.");
    }

my message driven bean : 


     package com.soutem.ejb.mdb;

    import java.io.UnsupportedEncodingException;
    import java.util.Properties;
    import java.util.Set;
    import javax.activation.DataHandler;
    import javax.activation.DataSource;
    import javax.activation.FileDataSource;
    import javax.annotation.PreDestroy;
    import javax.annotation.Resource;
    import javax.ejb.ActivationConfigProperty;
    import javax.ejb.MessageDriven;
    import javax.ejb.MessageDrivenContext;
    import javax.jms.JMSException;
    import javax.jms.Message;
    import javax.jms.MessageListener;
    import javax.jms.ObjectMessage;
    import javax.jms.TextMessage;
    import javax.mail.BodyPart;
    import javax.mail.MessagingException;
    import javax.mail.Transport;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import org.jboss.logging.Logger;

    @MessageDriven(mappedName = "topic/MailConfirmationMdbTopic", 
    activationConfig = {
     @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
     @ActivationConfigProperty(propertyName="subscriptionDurability", propertyValue="Durable"),
     @ActivationConfigProperty(propertyName="subscriptionName", propertyValue="topicmdb"),
    @ActivationConfigProperty(propertyName="clientId", propertyValue="mdbtopic-test"),
    //        
     @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
     @ActivationConfigProperty(propertyName = "destination", propertyValue = "topic/MailConfirmationMdbTopic")  
    })

    public class MailConfirmationMdbBean implements MessageListener {

        private static final Logger log = Logger.getLogger(MailConfirmationMdbBean.class);
    //  @Resource MessageDrivenContext mdc;
         public MailConfirmationMdbBean(){
             log.info("Initialisation de l'envoi du mail depuis MailConfirmationMdbBean");  
         }

         public void onMessage(Message message) { //Message de javax.jms.Message

            // Pour la classe de test MailConfirmationProducteur
          if (message instanceof TextMessage) {
               TextMessage mail = (TextMessage) message;
               // L'envoi d'un mail de confirmation au client est ici simulé par l'affichage d'un message au niveau des logs.
               try {
                String leMail = mail.getText();
                log.info(" Envoi du mail : " + leMail);
                log.info(" --------------------------------------------------- ");
                sendMsg("ahmed.drira@gmail.com", "Confirmation de commande.",leMail /*leMail*/);
                log.info(" --------------------------------------------------- ");
                log.info(" Mail envoyé.");
               }
               catch (JMSException e) {
                e.printStackTrace();
               } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NamingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
          } else if  (message instanceof ObjectMessage) {
              ObjectMessage lemessage = (ObjectMessage) message;                  
          }
         }

            protected void sendMsg(String email, String subject, String body) throws MessagingException, NamingException, UnsupportedEncodingException {

                Properties props = new Properties();
                InitialContext ictx = new InitialContext(props);
                javax.mail.Session mailSession = (javax.mail.Session) ictx.lookup("java:/Mail");

                MimeMessage message = new MimeMessage(mailSession);

                message.setSubject(subject);
                message.setRecipients(javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse(email, false));
                message.setText(body);
                message.saveChanges();
                Transport transport = mailSession.getTransport("smtp");
                try {
                    transport.connect();
                    transport.sendMessage(message, message.getAllRecipients());
                    log.info("Message envoyé");
                }
                finally {
                    transport.close();
                }
            }   
         @PreDestroy  
         public void remove() {
             log.info("Suppression de MailConfirmationMdbBean.");
         }
    }  

for the producer and consumer programe , you can test with this :




     package com.soutem.ejb.mdb;


    import java.io.FileInputStream;
    import java.util.Properties;

    import javax.annotation.PreDestroy;
    import javax.jms.Connection;
    import javax.jms.ConnectionFactory;
    import javax.jms.JMSException;
    import javax.jms.Message;
    import javax.jms.MessageConsumer;
    import javax.jms.MessageListener;
    import javax.jms.Session;
    import javax.jms.TextMessage;
    import javax.jms.Topic;
    import javax.naming.Context;
    import javax.naming.InitialContext;

    public class MailConfirmationConsommateur implements MessageListener {

         public static void main(String[] args) throws Exception {
             new MailConfirmationConsommateur();
         }
     public MailConfirmationConsommateur() throws Exception {

          Properties proprietes = new Properties();  
          proprietes.load(new FileInputStream("jndi.properties")); 
          InitialContext ctx = new InitialContext(proprietes);

          // 1:  recherche d'une connection factory
          ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");

          // 2:  cr�ation d'une connection JMS
          Connection conn = factory.createConnection();

          // 3: cr�ation d'une session
          Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

          // 4. Recherche d'une destination
          Topic topic = (Topic) ctx.lookup("topic/MailConfirmationMdbTopic");     

          // 5: cr�ation d'un consommateur de message
          MessageConsumer consommateur = session.createConsumer(topic);  
          consommateur.setMessageListener(this);

          System.out.println("Client JMS MailConfirmationConsommateur à l'écoute de messages.");
          conn.start();   // 
     }

         public void onMessage(Message msg) {
              if (msg instanceof TextMessage) {
               TextMessage tm = (TextMessage) msg;  

               // L'envoi d'un mail de confirmation au client est ici simul� 
               // par l'affichage d'un message au niveau des logs.
               try {
                String mail = tm.getText();
                System.out.println("Le client JMS MailConfirmationConsommateur a reçu le message : " + mail);
               } catch (JMSException e) {
                e.printStackTrace();
               }
              }
         }

         @PreDestroy 
         public void remove() {
             System.out.println("Suppression du client JMS     MailConfirmationConsommateur.");
         }
    }
    package com.soutem.ejb.mdb;


    import java.io.FileInputStream;
    import java.util.Properties;

    import javax.annotation.Resource;
    import javax.jms.*;
    import javax.naming.InitialContext;

    import org.jboss.logging.Logger;





    public class MailConfirmationProducteur {

         private static final Logger log = Logger.getLogger(MailConfirmationProducteur.class);

         public static void main(String[] args) throws Exception {

              Properties proprietes = new Properties();  
              proprietes.load(new FileInputStream("jndi.properties")); 
              InitialContext ctx = new InitialContext(proprietes);

              // 1: recherche d'une connection factory
              ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");

              // 2: cr�ation d'une connection JMS
              Connection conn = factory.createConnection();

              // 3: cr�ation d'une session
              Session session = conn.createSession(false,Session.AUTO_ACKNOWLEDGE);

              // 4: Recherche d'une destination
              Topic topic = (Topic) ctx.lookup("topic/MailConfirmationMdbTopic");
          // 5: cr�ation d'un producteur de message
          MessageProducer producteur = session.createProducer(topic);

          // 6: publication d'un message
          TextMessage msg = session.createTextMessage();
          msg.setText("Mail de confirmation pour le client.");
          producteur.send(msg);

          producteur.close(); 
          log.info("Message envoy�.");
     }
    }

you need also some configuration on the server to set up the topic so you need to add this lines on the /server/default/deploy/hornetq/hornetq-jms.xml

    <topic name="/topic/MailConfirmationMdbTopic">
        <entry name="/topic/MailConfirmationMdbTopic"/>
    </topic>
you need also to configure the java mail by adding your smtp privider , mail and pass  here is the config 

    <mbean code="org.jboss.mail.MailService"
         name="jboss:service=Mail">
    <attribute name="JNDIName">java:/Mail</attribute>
    <attribute name="User">.......@gmail.com</attribute>
    <attribute name="Password">.........</attribute>
    <attribute name="Configuration">
      <!-- A test configuration -->
     <configuration>
    <property name="mail.smtp.host" value="smtp.gmail.com">
    <property name="mail.smtp.port" value="465">
    <property name="mail.smtp.auth" value="true">
    <property name="mail.smtp.ssl.enable" value="true">
   </property></property></property></property></configuration>
    </attribute>
    <depends>jboss:service=Naming</depends>
  </mbean>

So hope it can be helpful any question i can give a hand