Skip to main content

Getting started with Ballerina in 10 minutes

Ballerina is the latest revelation in programming languages. It has been built with the mind of writing network services and functions. With this post I’m going to describe how to write network services and functions within a 10 minute tutorial.

Source: http://vkool.com/tips-and-tricks-on-ballet-for-beginners/

First things first, go to ballerinalang website and download the latest ballerina tools distribution which has the runtime and all the tools required for writing Ballerina programs. After downloading, you can extract the archive into a directory (let’s say BALLERINA_HOME) and set the PATHenvironment variable to the bin directory of BALLERINA_HOME which you have extracted the downloaded tools distribution. In linux, you can achieve this as mentioned below.
export PATH = $PATH:/BALLAERINA_HOME/bin
e.g. export PATH = $PATH:/Users/chanaka-mac/ballerinalang/Testing/ballerina-tools-0.8.3/bin
Now you have setup the ballerina in your system. Now it is time to run the first example of all, the Hello World example. Ballerina can be used to write 2 types of programs.
  • Network services
  • Main functions
Here, network services are long running services which keeps on running after it is started until the process is killed or stopped by external party. Main functions are programs which executes a given task and exit by itself.
Let’s run the more familiar main program style Hello World example. Only thing you have to do is run the ballerina command pointing to the hello world sample. You change your directory to the samples directory within ballerina tools distribution ($BALLERINA_HOME/samples). Now run the following command from your terminal.
$ ballerina run main helloWorld/helloWorld.bal
Hello, World!
Once you run the above command, you will see the output “Hello, World!” and you are all set (voila!).
Let’s go to the file and see how a ballerina hello world program looks like.
import ballerina.lang.system;
function main(string[] args) {
    system:println("Hello, World!");
}
This small program has several key concepts covered.
  • Signature of the main function is similar to other programming languages like C, Java
  • You need to import native utilities before using them (no auto-import)
  • How to run the program using ballerina run command

Source: http://vkool.com/tips-and-tricks-on-ballet-for-beginners/

Now the basics are covered. Let’s move on to the next step. Which is running a service which says “Hello, World!” and keeps on running.
All you have to do is execute the below command in your terminal.
$ ballerina run service helloWorldService/helloWorldService.bal
ballerina: deploying service(s) in 'helloWorldService/helloWorldService.bal'
ballerina: started server connector http-9090
Now things are getting little bit interesting. You can see 2 lines which describes what has happened with the above command. It has deployed a service which was described the the mentioned file and there is a port (9090) opened for http communication. Now this service is started and listening on port 9090. We need to send a request to get the response out of this service. If you browse to the README.txt within the helloWorldService sample directory, you can find the below curl command which can be used to invoke this service. Let’s run this command from another command window.
$ curl -v http://localhost:9090/hello
> GET /hello HTTP/1.1
> Host: localhost:9090
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/plain
< Content-Length: 13
<
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
Hello, World!
You can see that, we got a response message from the service saying “Hello, World!”. Let’s crack into the program which does this. Go the Ballerina file within helloWorldService/helloWorldService.bal.
import ballerina.lang.messages;
@http:BasePath ("/hello")
service helloWorld {
    
    @http:GET
    resource sayHello (message m) {
        message response = {};
        messages:setStringPayload(response, "Hello, World!");
        reply response;
    
    }
    
}
This program covers several important aspects of a Ballerina program.
  • annotations are used to define the service related entities. In this sample, “/hello” is the context of the service and “GET” is the HTTP method accepted by this service
  • message is the data carrier coming from the client. Users can do what ever they want with message and they can create new messages and many other things.
  • “reply” statement is used to send a reply back to the service client.
In the above example, we have created a new message called “response” and set the payload as “Hello, World!” and then replied back to the client. The way you executed this service was
In the above command, we specified the port (9090) which the service was started and the context (/hello) we defined in the code.

Source: http://vkool.com/tips-and-tricks-on-ballet-for-beginners/

We have few mins left, let’s go for another sample which is bit more advanced and completes the set.
Execute the following command in your terminal.
ballerina run service passthroughService/passthroughService.bsz
ballerina: deploying service(s) in 'passthroughService/passthroughService.bsz'
ballerina: started server connector http-9090
Here, we have run a file with a different extension (bsz) but the result was similar to the previous section. File has been deployed and the port is opened. Let’s quickly invoke this service with the following command as mentioned in the README.txt file.
curl -v http://localhost:9090/passthrough
> GET /passthrough HTTP/1.1
> Host: localhost:9090
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 49
<
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
{"exchange":"nyse","name":"IBM","value":"127.50"}
Now we got an interesting response. Let’s go inside the source and see what we have just executed. This sample is bit advanced and hence it covers several other important features we have not mentioned in previous sections.
  • Ballerina programs can be run as a self-contatining archive. In this sample, we have run service archive file (.bsz) which contains all the artifacts required to run this service.
  • Ballerina programs can have packages and the package structure follows the directory structure. In this sample, we have a package called “passthroughservice.samples” and the directory structure is similar passthroughservice/samples.
Here are the contents of this sample.
passthroughService.bal
package passthroughservice.samples;
import ballerina.net.http;
@http:BasePath ("/passthrough")
service passthrough {
@http:GET
    resource passthrough (message m) {
        http:ClientConnector nyseEP = create http:ClientConnector("http://localhost:9090");
        message response = http:ClientConnector.get(nyseEP, "/nyseStock", m);
        reply response;
}
}
nyseStockService.bal
package passthroughservice.samples;
import ballerina.lang.messages;
@http:BasePath ("/nyseStock")
service nyseStockQuote {
@http:GET
    resource stocks (message m) {
        json payload = `{"exchange":"nyse", "name":"IBM", "value":"127.50"}`;
        message response = {};
        messages:setJsonPayload(response, payload);
        reply response;
}
}
In this sample, we have written a simple integration by conncting to another service which is also written in Ballerina and running on the same runtime. “passthroughService.bal” contains the main Ballerina service logic in which,
  • Create a client connector to the backend service
  • Send a GET request to a given path with the incoming message
  • Reply back the response from the backend service
In this sample, we have written the back end service also from ballerina. In that service “nyseStockService.bal”,
  • Create a json message with the content
  • Set that message as the payload of a new message
  • Reply back to the client (which is the passthroughService)
It’s Done! Now you can run the remainder of the sample or write your own programs using Ballerina.
Happy Dancing !

Comments

Post a Comment

Popular posts from this blog

Understanding Threads created in WSO2 ESB

WSO2 ESB is an asynchronous high performing messaging engine which uses Java NIO technology for its internal implementations. You can find more information about the implementation details about the WSO2 ESB’s high performing http transport known as Pass-Through Transport (PTT) from the links given below. [1] http://soatutorials.blogspot.com/2015/05/understanding-wso2-esb-pass-through.html [2] http://wso2.com/library/articles/2013/12/demystifying-wso2-esb-pass-through-transport-part-i/ From this tutorial, I am going to discuss about various threads created when you start the ESB and start processing requests with that. This would help you to troubleshoot critical ESB server issues with the usage of a thread dump. You can monitor the threads created by using a monitoring tool like Jconsole or java mission control (java 1.7.40 upwards). Given below is a list of important threads and their stack traces from an active ESB server.  PassThroughHTTPSSender ( 1 Thread )

How to configure timeouts in WSO2 ESB to get rid of client timeout errors

WSO2 ESB has defined some configuration parameters which controls the timeout of a particular request which is going out of ESB. In a particular  scneario, your client sends a request to ESB, and then ESB sends a request to another endpoint to serve the request. CLIENT->WSO2 ESB->BACKEND The reason for clients getting timeout is that ESB timeout is larger than client's timeout. This can be solved by either increasing the timeout at client side or by decreasing the timeout in ESB side. In any of the case, you can control the timeout in ESB using the below properties. 1) Global timeout defined in synapse.properties (ESB_HOME\repository\conf\) file. This will decide the maximum time that a callback is waiting in the ESB for a response for a particular request. If ESB does not get any response from Back End, it will drop the message and clears out the call back. This is a global level parameter which affects all the endpoints configured in ESB. synapse.global_timeout_inte

How puppet works in your IT infrstructure

What is Puppet? Puppet is IT automation software that helps system administrators manage infrastructure throughout its lifecycle, from provisioning and configuration to orchestration and reporting. Using Puppet, you can easily automate repetitive tasks, quickly deploy critical applications, and proactively manage change, scaling from 10s of servers to 1000s, on-premise or in the cloud. How the puppet works? It works like this..Puppet agent is a daemon that runs on all the client servers(the servers where you require some configuration, or the servers which are going to be managed using puppet.) All the clients which are to be managed will have puppet agent installed on them, and are called nodes in puppet. Puppet Master: This machine contains all the configuration for different hosts. Puppet master will run as a daemon on this master server. Puppet Agent: This is the daemon that will run on all the servers, which are to be managed using p