Monday, May 29, 2017

Ballerina for simple server side Web Socket programs

WebSockets is one of those protocols that was invented to solve the transmission barrier posted by HTTP’s stateless request-response model. One of the key differentiators of it is its ability piggy back on HTTP infrastructure using the HTTP upgrade mechanism[1], this ability when coupled with the inbuilt support provided by HTML5 for client-side WebSockets programming, allowed it to emerge as a strong contender to win the full-duplex protocol war.

As with other transport/application protocols supported by Ballerina, a consistent programming interface is provided to put together WebSocket based server side programs with ease. The example found below demonstrates this capability.

To try out the example, create the folder structure <BALLERINA_HOME>/socketproxy/sample and copy the content into the two appropriately named bal files. Make an archive[2] and make a websocket client call to “ws://localhost:9090/socketproxy/ws”, find a sample python client attached(it requires python-websocket package to work).

Look to the websocket samples found in the ballerina 0.87 distribution to learn more about websocket programming with ballerina.

Note: the example above was constructed to demonstrate a simple use case involving websockets, a real world implementation should be built after careful analysis of the requirements.

Wednesday, May 24, 2017

Ballerina in the Cloud

As discussed in other posts, Ballerina provides integration capabilities in a lean, mobile distribution. Its graphical and textual syntax parity makes it ideal for developers coming in from different backgrounds. Someone who wishes to avoid the textual syntax can do so without losing any programming mobility. Regardless of the syntax chosen, the end result of a designed ballerina program would be a file with a “.bal” extension or a combination of such files archived into files with either “.bsz” or “.bmz” extensions.

WSO2 Integration Cloud is a SaaS imagination of WSO2’s industry trusted enterprise integration solution, apart from handling WSO2 EI projects it is now capable of providing a cost effective means of serving your ballerina projects to the world. This post is meant to help you get started with serving your ballerina services from the cloud,

Creating Ballerina Services

Ballerina services that are meant for the integration cloud maybe created the same manner as any other ballerina service. However, they must be packed into archives prior to uploading. Look to the ballerina packaging documentation[1] if you’re not familiar with this task.

For the moment it is advisable to limit your services to the HTTP transport and to a single archive(if it's a service spanning multiple ballerina files).

Uploading the Services to the Cloud  

Integration Cloud takes care of the administration and configuration tasks associated with serving ballerina integration projects, from containerization of the archives to scaling on demand.

Uploading a ballerina archive to the integration cloud is as easy as logging in, specifying an application name, version and uploading the archive from your local file system. Users may also select instance specifications and pass in environmental variables if required. It is advisable to select a container specification with moderate amount of ram(think 512).


The example below shows the ease at which ballerina integration projects maybe created and served from the cloud. Note that this example was written for Ballerina 0.87.


Integration Cloud Access: WSO2 integration cloud provides a 2 week trial program, you may avail this offer to try out the example.

Geoname Username: Geoname is a geolocation service made available free of charge for educational purposes. Create an account with Geonames and activate free web service usage through ManageAccounts.


  1. Create the folder structure <BALLERINA_HOME>/geochain/sample
  2. Copy the contents of the gist found below into <BALLERINA_HOME>/geochain/sample/GeoChainService.bal
  3. Navigate to <BALLERINA_HOME> and execute the package command on the service with ./bin/ballerina build service geochain/sample -o GeoChainService.bsz
  4. Login to the integration cloud with your credentials and start creating a new ballerina application (new application -> ballerina -> local file system)
  5. Put in “GeoChain” as the application name, “1.0.0” as the version and upload the newly created archive found at <BALLERINA_HOME>.
  6. Expand the advanced settings section and select a container specification which is more powerful than the one selected by default.
  7. Complete the upload by clicking “Create”.
  8. Give the integration cloud a moment to deploy the service and navigate to the application list to find the GeoChain service deployed. Click on it to get to its overview page and find the service host. It will look like,
    2. The service will be available at, <your service host>/geochain

Make a GET to the service with a JSON payload that contains the country code and your geoname username. Example payload and invocation,

curl -X GET -d @payload

[1] -

Tuesday, May 23, 2017

GeoChain: API Scraping with Ballerina

Ballerina makes it easy to scrape data from other endpoints. The example below uses some of the string manipulating capabilities discussed in String Manipulation with Ballerina to scrap a piece of data from one geonames API and using it calls another.

To try out the example, first create an account with Geonames and activate free web service usage through ManageAccounts. Then run the ballerina with the command line parameters shown below,

ballerina <Geonames Username> <Country Code> <Number of Wiki hits to retrieve> 
ballerina testaccount1101 LK 20

Similarly, ballerina can be used for service chaining scenarios. Look to the Service Chaining example shipped with the distribution for more information. Find out more about Ballerina here:

Note: this example was written for ballerina 0.87 and it may not work with other versions.

Monday, May 22, 2017

Using the ballerina file transport to access a local file

Ballerina provides support for multiple transports such as HTTP, JMS, Web Sockets, File, FTP and SFTP. A service file is bound to a single transport, however there are no restrictions on packaging services of different transports together, this allows programmers to craft interfaces and glue applications that span multiple varied transports.  Further, the mechanism in which content is accessed and manipulated is constant regardless of the protocol being used, meaning the manipulation logic written for one transport say HTTP can be used with another with little to no alterations. This uniformity provides for a smoother programming experience and is sure to increase your programming efficiency.

The example below uses the file transport to access a local file’s content, it then creates a simple xml payload using the content(if the given condition is met) before sending it out to a processing endpoint over HTTP.

Note: to use some of the transports mentioned above you will need to put in a few dependency jars into ballerina libs. Look to the respective transport’s documentation for further instructions.

Note: the example above s is meant to be a crude demonstration of the uniform, almost transport independent programming interface provided by ballerina.

Find out more about ballerina here:

Note: this example was written for ballerina 0.87 and may not work with other versions.

Thursday, May 18, 2017

Use ballerina to extend your bash scripts capabilities

Ballerina provides a comprehensive collection of connectors that can be used to work with popular services such as twitter, gmail and facebook. They are easy to use and comes bundled in a lean distribution(what is 15mb these days?) When coupled with its integration excellence it can solve many integration challenges in a way that was not possible before.

Ballerina can also become a useful tool for DevOps engineers who welcome the challenge of learning a new language. The example below shows how a ballerina script that uses the twitter API can be embedded into a shell script. Similarly you can avail any one of the ballerina connectors listed here[1].

Execute the script as follows,

 ./ <consumerKey> <consumerSecret> <accessToken> <accessTokenSecret>

Look to the ballerina 0.8X twitter connector sample readme for further instructions. Find out more about ballerina here:

[1] -

Note: this example was written for ballerina 0.86 and may not work with other versions. 

Handling server side issues of integration endpoints with Ballerina

Routing invocations to a backend service or chaining a bunch of services together is a common integration requirement. In such scenarios you will have to mitigate the risk of unpredictability integrating over disparate systems brings into the mix. One common way of address this risk is to utilize HTTP status codes. Ballerina makes dealing with status codes easy with the following methods found in the package,
  • getStatusCode
  • setStatusCode  
Refer to the API documentation for mode details on the methods:

The example below shows how getStatusCode method can be used to make invocation time decisions on an endpoint’s availability and act accordingly. Similarly, you can utilize received status codes of HTTP endpoints as an effective way of hardening your program when it’s appropriate.

To try out the example create the folder structure <BALLERINA_HOME>/statuscode/sample and then create ballerina files with the content of the two gists. Package the services into a bsz archive and run it. Invoke /proxy service with a header "CONTROLLER: faulty backend" to simulate an server side error.

curl -X GET -v http://localhost:9090/proxy -H "CONTROLLER: faulty backend"

find out more about ballerina here:

Note: this example was written for ballerina 0.86 and may not work with other versions.

Wednesday, May 17, 2017

String manipulation with Ballerina

Ballerina is one of the coolest things going on at work at the moment, a passion project initiated by WSO2's founder Sanjiva Weerawarana, it was birthed from the experiences amassed through over a decade of creating industry leading Middleware products and helping organizations succeed in their SOA based projects.

Whether you are integrating enterprise systems over different transports, messaging conventions, adding mediation logic to existing services or writing some code for your pet IoT project you will be dealing with a lot of string manipulations. Now, string manipulation is not something a programmer needs to learn repeatedly, but since Ballerina is a whole new beast of a programming language(in the making) it might be advisable to invest a bit of time to get familiar with the its string manipulation capabilities.

Ballerina provides a bunch of string utility methods somewhat similar to python, packed under ballerina.lang.strings. Look to the Strings API documentation[1] for a complete list of methods. Apart from these utility methods, Ballerina supports escaping(“\””) and concatenation(+) same as Java and provide inline formatting capabilities such as “\t” for tab and “\n” for newline.

The code segment found below shows how some of the methods discussed above can be used in a real world scenario where a header value passed into a ballerina service and depending on  the callers time a response is generated and sent out.

Try out the ballerina script above with these invocations,

[1] -

Note: this example was written for ballerina 0.86 and it may not work with other versions.