Friday, April 12, 2013

Creating CSV Files from a Proxy Service

If you want to write a CSV file from a proxy service in WSO2 ESB, then following sample would help you to understand how it works.

  1. Uncomment the following lines in wso2esb-4.x.x/repository/conf/axis2/axis2.xml.
    <transportreceiver class="org.apache.synapse.transport.vfs.VFSTransportListener" name="vfs"/>
    <transportsender class="org.apache.synapse.transport.vfs.VFSTransportSender" name="vfs"/>
  2. Add below content into the resource called /_system/governance/xml2csv.xslt
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="iso-8859-1"/>
    
    <xsl:strip-space elements="*" />
    
    <xsl:template match="/*/child::*">
     <xsl:for-each select="child::*">
      <xsl:if test="position() != last()"><xsl:value-of select="normalize-space(.)"/>,</xsl:if>
      <xsl:if test="position()  = last()"><xsl:value-of select="normalize-space(.)"/><xsl:text>
    </xsl:text></xsl:if>
     </xsl:for-each>
    </xsl:template>
    
    </xsl:stylesheet>
    
  3. Create a proxy service named CSVProxy with the following content.
    <proxy xmlns="http://ws.apache.org/ns/synapse" name="CSVProxy" transports="https,http" 
        statistics="disable" trace="disable" startOnLoad="true">
       <target>
          <inSequence>
             <property name="FORCE_SC_ACCEPTED" value="true" scope="axis2"/>
             <payloadFactory>
                <format>
                   <data>
                      <row>
                         <firstName>Ruchira</firstName>
                         <lastName>Wageesha</lastName>
                      </row>
                      <row>
                         <month>May</month>
                         <date>31</date>
                         <year>1984</year>
                      </row>
                      <row>
                         <street>Flower Road</street>
                         <province>Western</province>
                         <city>Colombo</city>
                         <country>Sri Lanka</country>
                         <postalCode>0007</postalCode>
                      </row>
                   </data>
                </format>
             </payloadFactory>
             <xslt key="gov:/xml2csv.xslt"/>
             <property name="transport.vfs.ReplyFileName" expression="fn:concat(fn:substring-after(get-property('MessageID'), 'urn:uuid:'), '.csv')" scope="transport"/>
             <property name="OUT_ONLY" value="true"/>
             <send>
                <endpoint>
                   <address uri="vfs:file:///home/ruchira/csv"/>
                </endpoint>
             </send>
             <drop/>
          </inSequence>
       </target>
    </proxy>                               
    
    Note : vfs:file:///home/ruchira/csv is the path where generated csv files are stored. Hence replace it with a valid path in your machine.
  4. Invoke the CSVProxy service by issuing an HTTP GET to http://localhost:8280/services/CSVProxy
  5. CSV files will be created in the above specified path.

Thursday, April 11, 2013

Sending JSON Responses from a Proxy Service in WSO2 ESB

If you have come up with the requirement of sending JSON responses from a proxy service, then following proxy configuration can be used straightaway to try that out.

i.e. Create a proxy service named JSONProxy with the following content. Then, you can try that out by issuing HTTP GET to http://localhost:8280/services/JSONProxy

Proxy Configuration
<proxy xmlns="http://ws.apache.org/ns/synapse" name="JSONProxy" transports="https,http" 
       statistics="disable" trace="disable" startOnLoad="true"> 
   <target> 
      <inSequence> 
         <header name="To" action="remove"/> 
         <property name="RESPONSE" value="true"/> 
         <property name="NO_ENTITY_BODY" scope="axis2" action="remove"/> 
         <payloadFactory> 
            <format> 
               <person> 
                  <fullName> 
                     <firstName>Ruchira</firstName> 
                     <lastName>Wageesha</lastName> 
                  </fullName> 
                  <birthDate> 
                     <month>May</month> 
                     <date>31</date> 
                     <year>1984</year> 
                  </birthDate> 
                  <address> 
                     <street>Flower Road</street> 
                     <province>Western</province> 
                     <city>Colombo</city> 
                     <country>Sri Lanka</country> 
                     <postalCode>0007</postalCode> 
                  </address> 
               </person> 
            </format> 
         </payloadFactory> 
         <property name="messageType" value="application/json" scope="axis2"/> 
         <send/> 
      </inSequence> 
   </target> 
   <description></description> 
</proxy>
JSON Response
{
    "person": {
        "fullName": {
            "firstName": "Ruchira",
            "lastName": "Wageesha"
        },
        "birthDate": {
            "month": "May",
            "date": "31",
            "year": "1984"
        },
        "address": {
            "street": "Flower Road",
            "province": "Western",
            "city": "Colombo",
            "country": "Sri Lanka",
            "postalCode": "0007"
        }
    }
}

Wednesday, April 3, 2013

Error Handling in Jaggery

Proper error handling is a key points in any application. If you are using WSO2 Jaggery, then you might have also come up with the same requirement.

Jaggery is JavaScript, hence try, catch and finally blocks can be used within your code as you usual. Also,  passed JavaScript Error object can be used to get a brief information about the error. But, as we are dealing with a server side environment, we might need to know additional details about the errors, such as stacktrace, line numbers etc.

Using the additional properties/methods which can be found in the passed Error object, error details can be accessed as below.
var log = new Log();

try {
    parse(null); //code where exception is thrown
} catch (e) {
    log.error(e.lineNumber); // Error occured line number
    log.error(e.fileName); // Error occured script name
    log.error(e.stack); // Executed JavaScript file stack
    log.error(e.message); // JavaScript error message

    log.error(e.rhinoException); // Rhino exception object
    log.error(e.javaException); // Java excepton object

    log.error(e); // Logs the stack trace

    print(e); // prints the stack trace
} finally {
    log.info('finally :)');
}


Thursday, March 14, 2013

Logging in Jaggery

In Jaggery, you can log with different levels i.e. debug, info, warn, error, fatal which can be enabled/disabled using the logLevel parameter in the jaggery.conf.
{
    "welcomeFiles" : ["index.html"],
    "logLevel" : "debug"
} 

Logging can be done with the desired log level using log.debug(), log.info(), log.warn(), log.error() and log.fatal() methods. Also, whether the debug logs are enabled can be checked using log.isDebugEnabled().
var log = new Log();

if(log.isDebugEnabled()) {
    log.debug('This is a debug log');
}

log.info('This is an info log');
log.warn('This is a warning log');
log.error('This is an error log');
log.fatal('This is a fatal log');

Get Environment Variables and System Properties in Jaggery

Environment variables and system properties can be read using the process module as below.
var process = require('process');

print(process.getEnvs()); // json object
print(process.getEnv('PATH')); // string
print(process.getProperties()); // json object
print(process.getProperty('jaggery.home')); // string

How to Generate a UUID in Jaggery

A UUID can be generated in WSO2 Jaggery server using the uuid module as below.
var uuid = require('uuid');
var id = new uuid.UUID();

print(id.toString()); // 0af9cb30-f660-4d5c-8d39-28cf87c7e574

How to Execute Tasks in WSO2 Jaggery

If you have come across the requirement of executing timer tasks within a Jaggery code, then you can use the following code to do that. These are the same set of functions that you have in the browser.

You can also use clearTimeout and clearInterval functions to stop the task execution.

One time tasks
setTimeout(function() {
     var log = new Log();
     log.info('setTimeout() is executed after 2s');
}, 2000);  
Recurring tasks
setInterval(function() {
     var log = new Log();
     log.info('setInterval() is being executed within 4s intervals');
}, 4000);

Wednesday, January 30, 2013

Check your A/L Exam Results a Bit Earlier

If you have sat for the A/L exam in Sri Lanka, you can check your unofficial results a bit earlier(when it shows you the "AWAIT RESULTS" banner) by accessing the following url from your browser(Please replaces 0000000 with your index number).

http://www.doenets.lk/exam/exam_AL.jsp?submit=Submit&action=result&exyear=2012&indexno=0000000