Sunday, July 26, 2015

Getting Started with Simple WSO2 ESB Connectors


A WSO2 connector allows you to interact with a third-party product's functionality and data from your ESB message flow, enabling you to connect to and interact with the APIs of services such as Twitter, Salesforce, and JIRA. This means that if you have enabled the Twitter and Google Spreadsheet connectors in your ESB instance,
your message flow could receive requests containing a user's Twitter name and password, log into the user's Twitter account, get a list of the user's followers, and write that information to a Google spreadsheet. You can use one or more connectors in order to manage generic use cases related to a business scenario that you may need to address.

The following topics provide more information on connectors and the use of connectors in managing various business scenarios:


Synapse Template : This is the component which calling to actual end point with the given request data. This will be placed in resources directory.

Proxy : This will handle the request coming inside to the ESB and response coming from the actual end point. This is not a part of connector, but need to invoke the connector.

Request : The request which follows the API published from the connector. This request can be REST or SOAP.

Connector for which API ?
There are large number of services which is provide in the world wide web to do a specific functions. In order to use these for developers, there will be one or several web service APIs  like REST, SOAP or a client libraries in one or several languages are provided by the service provider. Out of these, REST will be the simplest one that others since it has less work. Here we are using Atom feed Which are not using any Authentication and extra works.

Run the following maven command to generate sample maven connector project   code.



mvn archetype:generate -DarchetypeGroupId=org.wso2.carbon.extension.archetype -DarchetypeArtifactId=org.wso2.carbon.extension.esb.connector-archetype -DarchetypeVersion=2.0.0  -DgroupId=org.wso2.carbon.esb.connector -DartifactId=org.wso2.carbon.esb.connector.helloworld -Dversion=1.0.0 -DarchetypeRepository=http://maven.wso2.org/nexus/content/repositories/wso2-public/

You may need give a name for the connector while processing the above process. (Let's proceed with entering HelloWorldConnector as connector name.) If the project creation success, you are ready to develop a connector with the following directory structure.




Writing Synapse Template :
You can have a look on the sample Synapse template generated at helloWorld directory. Following synapse template is providing the service at helloworld. This should be placed under "helloworld" directory as helloworldconnector-template.xml.

connector.xml
this will include the all available methods we can set list the available methods through list the dependency here. here we are calling to list the methods  from the dependency with the name helloworld. we can add more then one dependency here.
<?xml version="1.0" encoding="UTF-8"?>
<connector>
    <component name="HelloWorldConnector" package="org.wso2.carbon.connector" >
        <dependency component="helloWorld"/>
        <description>wso2 sample connector library</description>
    </component>
</connector>


component.xml
this is the dependency with the name helloworld. This may contain more then one component and this have only one method call helloworldconnector-operation and its synapse configuration written in helloworldconnector-template.xml.
<?xml version="1.0" encoding="UTF-8"?>
<component name="helloWorld" type="synapse/template" >
    <subComponents>
        <component name="helloworldconnector-operation">
            <file>HelloWorldConnector-template.xml</file>
            <description>sample wso2 connector library</description>
        </component>
    </subComponents>
</component>


helloworldconnector-template.xml
this will have the synapse configuration for the methods. here we need only the host address for the feeds so we get the value with the name HostAddress and sent it to org.wso2.carbon.connector.HelloWorldConnector class
<template xmlns="http://ws.apache.org/ns/synapse" name="helloworldconnector-operation">
    <parameter name="HostAddress"/>
    <sequence>
        <log level="full">
            <property name="HostAddress" expression="$func:HostAddress" />
        </log>
        <class name="org.wso2.carbon.connector.HelloWorldConnector" />
    </sequence>
</template>



HelloWorldConnector.java
finally we received the Parameters. messageContext will have the values  we can extract the values from that and can sent back also.
/*
*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*  WSO2 Inc. licenses this file to you under the Apache License,
*  Version 2.0 (the "License"); you may not use this file except
*  in compliance with the License.
*  You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.connector;

import org.apache.abdera.Abdera;
import org.apache.abdera.model.Document;
import org.apache.abdera.protocol.client.AbderaClient;
import org.apache.synapse.MessageContext;
import org.wso2.carbon.connector.core.*;
import org.apache.abdera.model.Entry;

public class HelloWorldConnector extends AbstractConnector {

    Abdera abdera;
    AbderaClient abderaClient;

    Document<Entry> doc;
    String HostAddress;

    public void connect(MessageContext messageContext) throws ConnectException {

        try {
            /**
             * Add your connector code here
             */
            HostAddress = getParameter(messageContext, "HostAddress").toString();
            abdera = new Abdera();
            abderaClient = new AbderaClient(abdera);

                // Get the Entry from Server
                doc = abderaClient.get(HostAddress).getDocument();

        log.info(doc.getRoot());
        } catch (Exception e) {
            throw new ConnectException(e);
        }
    }
}


Now you can build the connector code and test the implemented service foe volume search method. To build the connector, run maven clean install command from the org.wso2.carbon.connector directory.

This will generate HelloWorldConnector.zip file in the target directory. You can upload this zip file through the ESB interface under connector category. Make sure you enabled the connector after uploading.

Writing Proxy :
Now you can invoke the implemented service for search volumes, by writing a proxy through ESB server interface. (Home>Manage>Services>Add>Proxy Service>Custom Proxy>switch to source view)

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="Helloworld"
       transports="http,https"
       statistics="disable"
       trace="disable"
       startOnLoad="true">
   <target>
      <inSequence>
         <HelloWorldConnector.helloworldconnector-operation>
            <HostAddress>http://wso2experience.blogspot.com/feeds/posts/default</HostAddress>
         </HelloWorldConnector.helloworldconnector-operation>
         <log level="full"/>
         <respond/>
      </inSequence>
   </target>
   <description/>
</proxy>
                                


now try
https://10.100.7.64:9443/services/Helloworld?tryit


Finally you will get the output in the bellow format for Atom feeds.

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
        <title>Example Feed</title>
        <subtitle>Insert witty or insightful remark here</subtitle>
        <link href="http://example.org/"/>
        <updated>2003-12-13T18:30:02Z</updated>
        <author>
                <name>WSO@ Inc</name>
                <email>WSO@@wso2.com</email>
        </author>
        <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
        <entry>
                <title>Atom-Powered Robots Run Amok</title>
                <link href="http://example.org/2003/12/13/atom03"/>
                <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
                <updated>2003-12-13T18:30:02Z</updated>
                <summary>Some text.</summary>
        </entry>
  
</feed>

References