Saturday, August 29, 2015

How to Invoke a Shell Script using WSO2 ESB


whats covered: creating a custom mediator to invoke shell scripts for ESB 4.8.1.


1) Create a Mediator Project


Generate a mediator project using WSO2 Developer Studio. Developer Studio Dashboard > Mediator Project.


2) Put in the logic to execute shell scripts


exec() method of the of the current runtime object can be used for this purpose. put the logic inside the mediate method(this method should return true to continue the mediation flow). Find the complete code here[1]


    ...
    ...   
    public String execute()
    {
        StringBuilder output = new StringBuilder();
        Process p;
        try
        {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line = "";
            while ((line = reader.readLine())!= null) {
                output.append(line + "\n");
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }

        return output.toString();
    }
    ...
    ...


3) Build and Copy the jar

build the project. Copy the created jar file to <ESB_HOME>/repository/components/lib .


4) Create a proxy service

create a proxy service with the class mediator in the mediation path.

...
...
<inSequence>
<class name="org.wso2.demo.ShellScriptMediator">
      <property name="scriptname"
                value="/home/dumiduh/backup_script.sh"/>
      <property name="scriptparam"
                value="/home/dumiduh/BACKUPS"/>
</class>
<drop/>
</inSequence>
...
...


[1] - https://github.com/handakumbura/ShellScriptMediatorDemo/tree/master

Find more info on the class mediator here,
https://docs.wso2.com/display/ESB481/Class+Mediator


No comments:

Post a Comment

What's in my Bag? EDC of a Tester