Tuesday, January 12, 2016

How to extend prototyping capabilities of WSO2 API Manager

whats covered: creating API prototypes using mediation policies for APIM 1.10.0

WSO2 API Manager comes with API prototyping capability OOTB. However if you are in need of advance prototyping capabilities or feel restricted by the available implementation for the time being you could tap into the underlying mediation engine (WSO2 ESB) to meet your prototyping need.


1) Create a mediation policy with the prototype logic


The mediation policy should be such that it respond back to the client with configured response rather than passing the message back to the backend. We can achieve this requirement using Respond[1] and Payload Factory mediators[2].


 <sequence xmlns="http://ws.apache.org/ns/synapse" name="prototypesequence">
   <header name="To" action="remove"></header>
   <header name="CustomHeader" scope="transport" value="test123"></header>
   <property name="RESPONSE" value="true"></property>
   <property name="NO_ENTITY_BODY" action="remove" scope="axis2"></property>
   <payloadFactory media-type="json">
      <format>               {"id":"101","name": "dumiduh","desc": "hard coded json"}            </format>
   </payloadFactory>
   <class name="org.wso2.carbon.apimgt.usage.publisher.APIMgtResponseHandler"/>
   <respond></respond>
</sequence>


The example above is using a hard coded response body and headers, you could also populate the response with variables as required[3]. Find the example mediation policy here [4]

 

2) Attach mediation policy to API in flow


Start creating an API with required HTTP methods etc, select Manage API from implementation and from Message Mediation Policies section upload the prototype mediation policy. Publish the API.



3) Invoke

Invoke the API as you would any other managed API.


[1] - https://docs.wso2.com/display/ESB490/Respond+Mediator
[2] - https://docs.wso2.com/display/ESB490/PayloadFactory+Mediator
[3] - https://docs.wso2.com/display/ESB490/PayloadFactory+Mediator#PayloadFactoryMediator-Example3:Addingarguments
[4] -  https://drive.google.com/file/d/0B9oVIeyHJKBXb0xkTGUwSmlJc0E/view?usp=sharing

Saturday, January 2, 2016

Running a Jmeter script through Java

It may be useful to run a jmeter script through java and take actions depending on assertions in the script.

1) Creating the project


generate a java project using maven and add following dependencies,
  • ApacheJMeter_core
  • ApacheJMeter_http
  • jorphan
further dependencies[1] may need to be put if the jmeter script being run uses samplers other than http sampler or other comps such as pre-post processors.

 

2) Code


        ....
        ....   
        StandardJMeterEngine jmeter = new StandardJMeterEngine();
       
        //Initialize Properties, logging, locale, etc.
        JMeterUtils.loadJMeterProperties(JMETERPROPFILE);
        JMeterUtils.setJMeterHome(JMETERHOME);
        JMeterUtils.initLocale();
        SaveService.loadProperties();
               
        // Load existing .jmx Test Plan
        FileInputStream in = new FileInputStream(JMETERSCRIPT);
        HashTree testPlanTree = SaveService.loadTree(in);
        in.close();
       
        // Runing JMeter Test       
        Summariser summer = new Summariser();
        String testLog = JTLHOME+new Date().getTime()+".jtl";
        MyResultCollector resultCollector = new MyResultCollector(summer);
        resultCollector.setFilename(testLog);
        testPlanTree.add(testPlanTree.getArray()[0], resultCollector);      
        jmeter.configure(testPlanTree);
        jmeter.run();
        results = resultCollector.getResults();
        ....
        ....

ResultCollector class is extended so that actions can be taken based on the assertion result.

    ....
    ....   
    @Override
        public void sampleOccurred(SampleEvent e) {
        super.sampleOccurred(e);
        SampleResult r = e.getResult();
       
        ResultDTO result = new  ResultDTO();
        result.setSamplerName(r.getSampleLabel());
        result.setResponseCode(r.getResponseCode());
        result.setResult(r.isSuccessful());               
        results.add(result);
    }
    ....
    ....



Find the full example here,
https://github.com/handakumbura/jmeterrunner

Tuesday, October 6, 2015

Java Regex


Putting this up for my own reference more than any other reason. Java Regex are useful in manipulation strings. A regex consist of pattern blocks and optional quantifiers.


Pattern Blocks


some patterns are built in to java,

\d - digit
\w – word character
\s – whitespace

if a range of characters need to be used as a pattern it should be put as follows,

[a-z] – a to z simple
[a-zA-Z] - a to z capital and simple
[1-9] – 1 to 9

Quantifiers


these add meaning to the patterns. They should be added immediately after the pattern.

* - match pattern 0 or more times
+ - match pattern 1 or more times
{n} - match pattern exactly n times
{n,m} – match pattern between n to m times


Regex Examples


[a-zA-Z]* - a to z capital and simple 0 or more times
[a-zA-Z]+ - a to z capital and simple 1 or more times
\d{2,5} – digits 2 to 5 times
[.]*[a-zA-Z]{1,5} - . 0 or more times in the beginning followed by a to z capital and simple 1 to 5 time, the whole pattern once. 

Thursday, September 10, 2015

How to Write a Simple Authentication Handler for an API in WSO2 ESB

whats covered: creating a simple authentication handler for an API in WSO2 ESB 4.8.1


1) Create the Project


Generate the pom file with the required dependencies using WSO2 Developer Studio.


2) Put in the Authentication Logic


In this example the authentication is done based on a per-configured header value in the API request. Find the complete code here[1].

Put the authentication logic inside the handleRequest() method.

....
....

boolean auticationSuccessfull;
        if(!headers.containsKey(TOKEN_HEADER_NAME))
        {
            throw new SynapseException("Access token was not found in the header");
        }
        else
        {
            String token = headers.get(TOKEN_HEADER_NAME).toString();
            if(authenticate(token))
            {
                auticationSuccessfull=true;
            }
            else
            {
                auticationSuccessfull=false;
            }
        }

return auticationSuccessfull;

....
....

private boolean authenticate(String tk)
    {
        //authentication logic
        boolean sentinal=false;
        if(tk.equals("testtoken"))
        {
            sentinal=true;
        }
        if(!sentinal)
        {   
            log.debug("authentication failed for token: "+tk);   
        }
        return sentinal;
    }

....
....


3) Build and Copy the Jar


Drop the jar inside <ESB_HOME>/repository/components/lib


4) Include Handler in the API Configuration


Open up the API configuration with an editor(find it in <ESB_HOME>/repository/deployment/server/synapse-configs/default/api/), Include the handler after the API resource closing tag(at the end of the config) as shown below,

....
....

   </resource>
   <handlers>
      <handler class="com.dumiduh.SimpleAuthenticationHandler"/>
   </handlers>
</api>


[1] - https://drive.google.com/file/d/0B9oVIeyHJKBXY1hZZjBvT1FGQlU/view?usp=sharing

Tuesday, September 8, 2015

Another Way to Transfer Files Over the Network in Linux


Transfer files with nc when SimpleHTTPServer python module is not available.

nc -l <port_to_listen_on> < <file to transfer>

nc <ip_of_server> <port> > <output_file_name>


example,

nc -l 9000 < logs.zip
nc 192.168.1.3 > logs.zip

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


Friday, August 28, 2015

How to Run WSO2 BAM 2.5.0 on Cygwin


whats covered: configuring and running BAM 2.5.0 on Win 7 over Cygwin.

1) Install Java


install java using the installer and once thats complete setup JAVA_HOME user variable and add the java bin folder to path system variable.


2) Install Cygwin


download from https://cygwin.com/install.html and install using the wizard.


3) Setup JAVA_HOME in Cygwin.


Open <cygwin_home>/home/<user_name>/.profile and export JAVA_HOME following way,

/cygdrive/c/<java_home_user_variable_in_windows>

ex,

export JAVA_HOME=/cygdrive/c/Java/jdk1.7.0_45


4) Run the Start Script


open cygwin terminal, navigate to BAM 2.5.0 folder and start the server with wso2server.sh script. 




What's in my Bag? EDC of a Tester