Friday, June 17, 2016

WSO2 ESB Spring mediator sample

This post demonstrates how to write a sample spring mediator for wso2 ESB.
  1. Create a java project with the following two classes.
    package spring;
    
    import org.apache.synapse.MessageContext;
    import org.apache.synapse.mediators.AbstractMediator;
    
    public class Person extends AbstractMediator {
    
        private String name;
        private String address;
        private String age;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    
        @Override
        public boolean mediate(MessageContext messageContext) {
            System.out.println("name " + name);
            System.out.println("address " + address);
            System.out.println("age " + age);
            return true;
        }
    }
    package spring;
    
    import org.apache.synapse.MessageContext;
    import org.apache.synapse.mediators.AbstractMediator;
    
    public class Customer extends AbstractMediator {
        private String type;
        private String action;
        private Person person;
    
        public void setType(String type){
            this.type = type;
        }
    
        public void setAction(String action){
            this.action = action;
        }
    
        public String getType() {
            return type;
        }
    
        public String getAction() {
            return action;
        }
    
        public Person getPerson() {
            return person;
        }
    
        public void setPerson(Person person) {
            this.person = person;
        }
    
        public boolean mediate(MessageContext arg0) {
            System.out.println("type " + type);
            System.out.println("action " + action);
            System.out.println("---------------Person Name---------------");
            System.out.println("person " + person.getName());
            System.out.println("person " + person.getAddress());
            System.out.println("person " + person.getAge());
    
            return true;
        }
    }
    
  2. Build the project and copy the jar file into <ESB_HOME>/repository/components/lib folder.
  3. Add spring configuration[springConfig.xml] below to registry path /_system/config/repository/springConfig.xml.
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
    <beans>
    
     <bean id="PersonBean1" class="spring.Person">
     <property name="name" value="Irham" />
     <property name="address" value="address 1" />
     <property name="age" value="27" />
     </bean>
    
     <bean id="PersonBean2" class="spring.Person">
     <property name="name" value="Iqbal" />
     <property name="address" value="address 2" />
     <property name="age" value="64" />
     </bean>
     <bean id="CustomerBean" class="spring.Customer">
     <property name="action" value="buy" />
     <property name="type" value="1" />
     <property name="person" ref="PersonBean1"/>
     </bean>
    </beans>
    
  4.  Add the folowing synapse configuration[proxyConfig.xml] to ESB.
    <?xml version="1.0" encoding="UTF-8"?>
    <proxy xmlns="http://ws.apache.org/ns/synapse"
     name="testSpring"
     transports="https,http"
     statistics="disable"
     trace="disable"
     startOnLoad="true">
     <target>
     <inSequence>
     <log level="full">
     <property name="START" value="________________________"/>
     </log>
     <spring:spring xmlns:spring="http://ws.apache.org/ns/synapse"
     bean="PersonBean1"
     key="conf:/repository/springConfig.xml"/>
     <spring:spring xmlns:spring="http://ws.apache.org/ns/synapse"
     bean="PersonBean2"
     key="conf:/repository/springConfig.xml"/>
     <spring:spring xmlns:spring="http://ws.apache.org/ns/synapse"
     bean="CustomerBean"
     key="conf:/repository/springConfig.xml"/>
     <log level="full">
     <property name="END" value="______________________"/>
     </log>
     </inSequence>
     </target>
     <description/>
    </proxy>
    
  5.  Invoke the created service that will print the created objects assigned values on ESB log.

Java Mail API

We are accessing Gmail mail server in our application.We can get all or selected unread mails from inbox using IMAP as protocol. Then we can read or delete the emails.
  1. First have to create the Store using imap protocol
    private static Store getConnection() throws MessagingException {
     Properties properties;
     Session session;
     Store store;
     properties = new Properties();
     properties.setProperty("mail.host", "imap.gmail.com");
     properties.setProperty("mail.port", "995");
     properties.setProperty("mail.transport.protocol", "imaps");
     session = Session.getInstance(properties,new javax.mail.Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(receiver + "@" + domain,String.valueOf(receiverPasword));
     }
     });
     try {
     store = session.getStore("imaps");
     store.connect();
     return store;
     } catch (MessagingException e) {
     log.error("Error while connecting to email store ", e);
     throw new MessagingException("Error while connecting to email store ", e);
     }
    }
    
  2. Using the store you can read all the unread emails as below.
       Store store = null;
       Folder inbox = null;
       boolean emailReceived = false;
        try {
         store = getConnection();
         inbox = store.getFolder("INBOX");
         inbox.open(Folder.READ_WRITE);
     Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
       for (Message message : messages) {
         log.info("email subject : " + message.getSubject());
         }
        } catch (MessagingException ex) {
           log.error("Error when getting mail count", ex);
            throw new MessagingException("Error when getting mail count " + ex.getMessage(), ex);
        } finally {
          if (inbox != null) {
            inbox.close(true);
           }
         if (store != null) {
             store.close();
          }
        }
    
    
  3. Or you can select emails from the store by subject contain as below.
     Store store = null;
     Folder inbox = null;
     boolean emailReceived = false;
       try {
         store = getConnection();
         Folder mailFolder = store.getFolder(folder);
         mailFolder.open(Folder.READ_WRITE);
         SearchTerm st = new AndTerm(new SubjectTerm(subject), new BodyTerm(subject));
         Message[] messages = mailFolder.search(st);
         for (Message message : messages) {
           if (message.getSubject().contains(subject)) {
             log.info("Found the email subject : " + subject);
            }
          }
       } catch (MessagingException ex) {
           log.error("Error when getting mail count", ex);
           throw new MessagingException("Error when getting mail count " + ex.getMessage(), ex);
       } finally {
          if (inbox != null) {
            inbox.close(true);
           }
          if (store != null) {
             store.close();
           }
       }
    
    
  4. Delete emails as below
 Store store = null;
 Folder inbox = null;
   try {
     store = getConnection();
     inbox = store.getFolder("INBOX");
     inbox.open(Folder.READ_WRITE);
     Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
      for (Message message : messages) {
        message.setFlag(Flags.Flag.DELETED, true);
        log.info("Deleted email Subject : " + message.getSubject());
      }
     } catch (MessagingException e) {
        log.error("Error while connecting to email store ", e);
        throw new MessagingException("Error while connecting to email store ", e);
     } finally {
       if (inbox != null) {
         inbox.close(true);
       }
       if (store != null) {
         store.close();
       }
  }

How to receive email using WSO2 ESB

SCENARIO:
Imagine a scenario you need to receive emails to WSO2 ESB where you are using the mail transport.
HOW TO:
Following steps will guide you to get your scenario up and running.
  1. Download a distribution of the WSO2 ESB [1].
    ie. wso2esb-4.8.1.zip
  2. Extract the zip file. The folder created (wso2esb-4.8.1) will be referred as ESB_HOME.
  3. Uncomment the mail TransportSender and TransportReceiver from axis2.xml ie. ESB_HOME/conf/axis2.xml.
    <transportSender name="mailto" class="org.apache.axis2.transport.mail.MailTransportSender">
    <parameter name="mail.smtp.host">smtp.gmail.com</parameter>
    <parameter name="mail.smtp.port">587</parameter>
    <parameter name="mail.smtp.starttls.enable">true</parameter>
    <parameter name="mail.smtp.auth">true</parameter>
    <parameter name="mail.smtp.user">synapse.demo.0</parameter>
    <parameter name="mail.smtp.password">mailpassword</parameter>
    <parameter name="mail.smtp.from">synapse.demo.0@gmail.com</parameter>
    </transportSender>      
    <transportReceiver name="mailto" class="org.apache.axis2.transport.mail.MailTransportListener"></transportReceiver>
  4. Go to the ESB_HOME/bin and run the script which starts wso2server.
    eg. wso2server.bat for windows environments
    wso2server.sh for linux environments
  5. Then the server will be started. You can access the management console using the following URL [2].
  6. Log into the Mangement Console using following credentials.
    username: admin
    password: admin
  7. If your using imap create a proxy service using the following proxy configuration.
    <definitions xmlns="http://ws.apache.org/ns/synapse">
     <proxy xmlns="http://ws.apache.org/ns/synapse"
     name="MailTransportProtocolIMAP"
     transports="mailto"
     statistics="disable"
     trace="disable"
     startOnLoad="true">
      <target>
       <inSequence>
        <log level="custom">
         <property name="Date" expression="$trp:Date"/>
         <property name="Subject" expression="$trp:Subject"/>
         <property name="Content-Type" expression="$trp:Content-Type"/>
         <property name="From" expression="$trp:From"/>
        </log>
        <drop/>
       </inSequence>
       <outSequence>
         <send/>
       </outSequence>
      </target>
      <parameter name="mail.imap.socketFactory.class">javax.net.ssl.SSLSocketFactory</parameter>
      <parameter name="mail.imap.starttls.enable">false</parameter>
      <parameter name="transport.mail.ContentType">text/plain</parameter>
      <parameter name="mail.imap.host">imap.gmail.com</parameter>
      <parameter name="transport.mail.Address">test.automation.dummy@gmail.com</parameter>
      <parameter name="mail.imap.user">test.automation.dummy</parameter>
      <parameter name="mail.imap.socketFactory.port">993</parameter>
      <parameter name="transport.PollInterval">2</parameter>
      <parameter name="mail.imap.port">993</parameter>
      <parameter name="mail.imap.ssl.enable">false</parameter>
      <parameter name="mail.imap.fetchsize">2</parameter>
      <parameter name="mail.imap.socketFactory.fallback">false</parameter>
      <parameter name="transport.mail.Protocol">imap</parameter>
      <parameter name="mail.imap.password">automation.test</parameter>
      <description/>
     </proxy>
    </definitions>
  8. Or if you're using pop3 create a proxy service using the following proxy configuration.
  9. <definitions xmlns="http://ws.apache.org/ns/synapse">
     <proxy xmlns="http://ws.apache.org/ns/synapse"
     name="MailTranportAddress"
     transports="mailto"
     statistics="disable"
     trace="disable"
     startOnLoad="true">
      <target>
       <inSequence>
        <log level="custom">
         <property name="Date" expression="$trp:Date"/>
         <property name="Subject" expression="$trp:Subject"/>
         <property name="Content-Type" expression="$trp:Content-Type"/>
         <property name="From" expression="$trp:From"/>
        </log>
        <drop/>
       </inSequence>
       <outSequence>
       <send/>
       </outSequence>
      </target>
      <parameter name="mail.pop3.socketFactory.class">javax.net.ssl.SSLSocketFactory</parameter>
      <parameter name="transport.mail.ContentType">text/plain</parameter>
      <parameter name="mail.pop3.host">pop.gmail.com</parameter>
      <parameter name="transport.mail.Address">test.automation.dummy@gmail.com</parameter>
      <parameter name="mail.pop3.user">test.automation.dummy</parameter>
      <parameter name="mail.pop3.socketFactory.port">995</parameter>
      <parameter name="transport.PollInterval">1</parameter>
      <parameter name="mail.pop3.port">995</parameter>
      <parameter name="mail.pop3.fetchsize">1</parameter>
      <parameter name="mail.pop3.socketFactory.fallback">false</parameter>
      <parameter name="transport.mail.Protocol">pop3</parameter>
      <parameter name="mail.pop3.password">automation.test</parameter>
      <description/>
     </proxy>
    </definitions>
  10. Send email  to test.automation.dummy@gmail.com.
  11. Now you can see the email receiving to ESB by looking at the log.
References
[1] – http://wso2.org/downloads/esb

How to send email using WSO2 ESB

SCENARIO:
Imagine a scenario you need to send email through WSO2 ESB where you are using the mail transport.
HOW TO:
Following steps will guide you to get your scenario up and running.
  1. Download a distribution of the WSO2 ESB [1].
    ie. wso2esb-4.8.1.zip
  2. Extract the zip file. The folder created (wso2esb-4.8.1) will be referred as ESB_HOME.
  3. Uncomment the mail TransportSender and TransportReceiver from axis2.xml.  ie. ESB_HOME/conf/axis2.xml.
    [code language="css"]<transportSender name="mailto" class="org.apache.axis2.transport.mail.MailTransportSender">
    <parameter name="mail.smtp.host">smtp.gmail.com</parameter>
    <parameter name="mail.smtp.port">587</parameter>
    <parameter name="mail.smtp.starttls.enable">true</parameter>
    <parameter name="mail.smtp.auth">true</parameter>
    <parameter name="mail.smtp.user">synapse.demo.0</parameter>
    <parameter name="mail.smtp.password">mailpassword</parameter>
    <parameter name="mail.smtp.from">synapse.demo.0@gmail.com</parameter>
    </transportSender>[/code]
    [code language="css"]<transportReceiver name="mailto" class="org.apache.axis2.transport.mail.MailTransportListener">
    </transportReceiver>[/code]
  4. Add the following line to axis2.xml's MessageFormatters.
    [code language="css"]<messageFormatter contentType="text/plain" class="org.apache.axis2.format.PlainTextFormatter"/>[/code]
  5. Go to the ESB_HOME/bin and run the script which starts wso2server.
    eg. wso2server.bat for windows environments
    wso2server.sh for linux environments
  6. Then the server will be started. You can access the management console using the following URL [2].
  7. Log into the Mangement Console using following credentials.
    username: admin
    password: admin
  8. Create a proxy service using the following proxy configuration.
    [code language="css"]<!-- Using the mail transport -->
    <definitions xmlns="http://ws.apache.org/ns/synapse">
    <proxy xmlns="http://ws.apache.org/ns/synapse"
     name="MailToTransportSender"
     transports="https,http"
     statistics="disable"
     trace="disable"
     startOnLoad="true">
      <target>
        <inSequence>
          <property name="Subject" value="Email Subject"
           scope="transport"/>
          <property name="OUT_ONLY" value="true" scope="default" type="STRING"/>
          <property name="ContentType" value="text/plain" scope="axis2"/>
          <property name="messageType" value="text/plain" scope="axis2"/>
        <payloadFactory media-type="xml">
         <format>
          <ns:text xmlns:ns="http://ws.apache.org/commons/ns/payload">$1</ns:text>
         </format>
         <args>
           <arg value="Hello WSO2.....!"/>
         </args>
        </payloadFactory>
        <send>
          <endpoint>
             <address uri="mailto:test.automation.dummy@gmail.com"/>
          </endpoint>
        </send>
        <header name="To" action="remove"/>
          <property name="NO_ENTITY_BODY" scope="axis2" action="remove"/>
          <property name="RESPONSE" value="true" scope="default" type="STRING"/>
        <send/>
       </inSequence>
       <outSequence>
         <send/>
       </outSequence>
       </target>
       <description/>
      </proxy>
    </definitions>[/code]
  9. Create soup request to url[2] using soapui.
  10. Send a request to ESB using soapui.
    [code language="css"]<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
        <soapenv:Header/>
        <soapenv:Body>
        </soapenv:Body>
     </soapenv:Envelope>[/code]
References
[1] - http://wso2.org/downloads/esb
[2] - http://localhost:8280/services/MailToTransportSender?wsdl

Sunday, September 13, 2015

Using MCollecetive to broadcast paradigm for puppet request distribution.

ActiveMQ installation
  1. http://servicebus.blogspot.com/2011/02/installing-apache-active-mq-on-ubuntu.html
Mcollective server installing on puppet agents.
  1. If puppet agent not install, install puppet agent                                                                          sudo apt-get install puppet
  2. Add the puppetlab repositories.
    wget https://apt.puppetlabs.com/puppetlabs-release-trusty.deb
    sudo dpkg -i puppetlabs-release-trusty.deb
    wget https://apt.puppetlabs.com/puppetlabs-release-pc1-trusty.deb
    sudo dpkg -i puppetlabs-release-pc1-trusty.deb
    sudo apt-get update
  3. Install mcollective and ruby-stomp                                                                                               sudo apt-get install ruby-stomp mcollective
  4. Ensure that inbound TCP sessions to port 61613 can be created, you can allow all by using the following
    sudo iptables -A INPUT -m conntrack –ctstate ESTABLISHED,RELATED -j ACCEPT
  5. Install the following to run puppet commands                                                                 sudo apt-get install mcollective-puppet-agent            sudo apt-get install mcollective-shell-agent              sudo apt-get install  mcollective-service-agent
  6. Configure /etc/mcollective/server.cfg
  7. service mcollective restart
  8. Check the logs in file  tail -f /var/log/mcollective.log
Mcollective client installing on puppet master.
  1. If puppet master not install, install puppet master                                                                      sudo apt-get install puppetmaster.
  2. Add the puppetlab repositories.                                                                                                  wget https://apt.puppetlabs.com/puppetlabs-release-trusty.deb
    sudo dpkg -i puppetlabs-release-trusty.deb
    wget https://apt.puppetlabs.com/puppetlabs-release-pc1-trusty.deb
    sudo dpkg -i puppetlabs-release-pc1-trusty.deb
    sudo apt-get update
  3. Install MCollective client                                                                                                           sudo apt-get install mcollective-client.
  4. Configure /etc/mcollective/client.cfg.
  5. Install mcollective-puppet-client to run puppet commands                                                          sudo apt-get install mcollective-puppet-client.
  6. Run command mco puppet runonce
  7. Check the logs in file  /var/log/puppet/masterhttp.log