Monday, 2 November 2015

IoT : Remotely Control the LED in Raspberry Pi 2 using Java (pi4j) and MQTT Protocol

In this post I am going to demonstrate that how remotely control LED and how it can be connected to Raspberry Pi using MQTT protocol and control GPIO pins using pi4j library. This work is done  using Java code.

Recently I bought Raspberry Pi 2, so I just wanted to do some learning stuff, basically how to blink (on/off)  LED remotely.

I have performed extensive survey about Raspberry Pi on internet I found lots of stuff about connect LED with Raspberry Pi via GPIO pins. This created a lots of interest. So I m searched Java library to control gpio pins and I got pi4j library.   Actually pi4j library easy to learn and provide bunch of examples. Details of its are mentioned below:

pi4j Library

Its provides a friendly object-oriented I/O API and implementation libraries for Java programmers to access the full I/O capabilities of the Raspberry Pi platform. This project abstracts the low-level native integration and interrupt monitoring to enable Java programmers to focus on implementing their application business logic. For more details, refer this website :

GPIO pins layout are differ from each iteration of Raspberry pi. I have used Raspberry Pi2

GPIO Pins Layout for Raspberry Pi 2
Raspberry Pi 2 GPIO Layout
Raspberry Pi 2 GPIO Layout
I have wired gpio pin no 15 and 16 to 2 LED's. Diagrammatic represent is shown below:

Some important key steps:
To control LED via Java I used pi4j lib code.

Sample Code for turn on LED and turn off via GPIO 15 pin, is mentioned below:


public class ControlGpioExample {
// create gpio controller
        final GpioController gpio = GpioFactory.getInstance();
        final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_15, "MyLED");
        pin.setShutdownOptions(true, PinState.LOW);



After this steps, we can  control LED  remotely by  performing network protocols, For this performance I got Dzone Refcard about MQTT protocols.

MQTT Protocol
MQTT (formerly MQ Telemetry Transport) is a publish-subscribe based "light weight" messaging protocol for use on top of the TCP/IP protocol. It is designed for connections with remote locations where a "small code footprint" is required or the network bandwidth is limited. The publish-subscribe messaging pattern requires a message broker. The broker is responsible for distributing messages to interested clients based on the topic of a message   --Wikipedia

Basically it is client server model. We need server, its called "message broker". First we need to install server. So here we use "Mosquitto server". Mosquitto is an open source (BSD licensed) message broker that implements the MQ Telemetry Transport protocol versions 3.1. Download and install from

So we need client to connect message broker(server). There are many mqtt clients available. Generally, one of the popular client is Eclipse Paho. Secondle we need to add Paho client to our java project for communicate to message broker (mosquitto server).

I have used Amazon Ec2 instances (free tier). I installed Mosquitto server and WildFly JavaEE7 server. Then deploy my war file into wildfly server. Here Mosquitto is message broker and wildfly provide webpage for control LED. (I used JSF and Primefaces Lib for quick prototype)

In Raspberry Pi, our code is to going  connect the Mosquitto message broker with the help of paho library in port 1883. It is default port for MQTT and  this subscribe the topic  and waiting for any message to receive. If any message is received, then it process the message based on we are turn on LED using pi4j library. Check the code here.

In Wildfly server, based on JSF page any button triggered which directly connect to Mosquitto server using same paho library and publish the message in same topic which raspberry pi subscribed.  That's it.  Check the server code here.

My web page 

All codes in my github repo here


Thursday, 15 October 2015

Docker : Tomcat Clustering with Load Balancer (Tomcat and Nginx)

In this post i will show Tomcat Clustering in Docker Container. In my previous post i discussed how to achieve tomcat clustering with Nginx Front end.

Its almost same scenario, but this time we will achieve via docker container.

Docker is an open-source project that automates the deployment of applications inside software containers, by providing an additional layer of abstraction and automation of operating-system-level virtualization on Linux.[4] Docker uses resource isolation features of theLinux kernel such as cgroups and kernel namespaces to allow independent "containers" to run within a single Linux instance, avoiding the overhead of starting and maintaining virtual machine  --Wikipedia

we need 4 docker container (3 tomcat containers + 1 Nginx container).
i used official tomcat and nginx images. official tomcat container not enable the cluster aware feature. so we will take official image and deploy our code and change the server.xml file and run the image as container.

we need to do some steps like deploy the our code and change server.xml file in all 3 tomcat container. so i used here docker-compose tool.

Docker Compose
Compose is a tool for defining and running multi-container applications with Docker. With Compose, you define a multi-container application in a single file, then spin your application up in a single command which does everything that needs to be done to get it running.

In docker compose we need to define in single file called yaml file.


In that file define all 3 tomcat container entries and change the server.xml file and tomcat-users.xml and deploy our app to ROOT location in tomcat.

check my github repo

Once we defined the yaml file then use single command like docker-compose up for start all 4 container up and running.
we can also use docker-compose -d up for run in background.

Screencast :

Monday, 12 August 2013

HTML5 support in JSF 2.2 with Bean Validation 1.1 (JavaEE 7)

In this post i will show the HTML5 Support given by JSF 2.2, Which is part of Java EE 7 Spec. Also how to integrate the Bean Validation 1.1 feature with help of CDI (Contexts and Dependency Injection) 1.1 spec.

Before going the HTML5 support, my earlier posts on JSF, i used @ManagedBean annotation, because its part of Managed Bean Specification (Java EE 6). Another Reason i used Tomcat as a primary container, if i used Managed Bean Spec then its part of Mojjara implementation, so no need to add more CDI specific (Jboss Weld lib) lib to class-path.

But from Java EE 7 on-wards, JCP community expand the CDI capabilities and make CDI as important spec in Java EE 7 and Managed Bean spec is deprecated in favor of CDI . so they recommend to use CDI wherever its possible. so our future all post to target the CDI. next post i will show how add the CDI capability to tomcat container.

So as part of CDI we need to use @Named annotation. Its equal to @ManagedBean annotation, but its CDI Specific and all life cycle of the beans takes care by CDI container.
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

public class DemoBean implements Serializable{


            HTML5 is future of web standard, its provide lots of capability to browser like Full multimedia (audio and video playback), access the local resources like camera, microphone, Geolocation.
for more information check these resources

HTML5 Form elements are part of this features. This feature enable to the website without any 3rd party JavaScript framework to get fields/widgets like date picker, color picker, Check the sample page here

HTML5 Support in JSF2.2

           In JSF 2.0/2.1, its not supporting HTML5 form elements, the reason is HTML render-kit, which is part of JSF Implementation is not aware the HTML 5 elements or attributes. so even we put these attributes like placeholder, type=date, these Render-kit it just ignore while generating the HTML for client request. In that case there is 3rd party plugin called OmniFaces provides the Render-kit to support the HTML5 in JSF 2.0/2.1.

In JSF 2.2 onward's, HTML5 support internally as part of the Framework. The big issue is HTML5 attributes are we can't count or categorized. for example any input tag we add the data-* as attribute like data-theme, data-highlight, etc..  so we need to do some way to classify these attribute. That way is called "Pass through".

For eample i want to add one HTML5 input tag like this

<input type="text" placeholder="Enter your Name" />

here i want to convert this tag to JSF tags, because i want to bind this tag to my backing bean then 

<h:inputText  p:placeholder="Enter your Name" />

here h: is prefix for normal HTML components, but p: is prefix for pass through.

 Like we can add the HTML5 Date picker componet

Original HTML5 Code : <input type="date" />

JSF2.2 Code : <h:inputText  p:type="date" />

Check the Video below, for more information and step - by step

Add Validation

       Now we got HTML5 Form elements in our projects, we need to validate what user entered, for this purpose either we used client side validation or server side validation.

Client side validation is faster and good. but if somebody disable the JavaScript and submit the form then big problem. so we need server side validation also important. In server side we manually validate these fields.

Java EE 7 gives updated Bean Validation 1.1 spec for this purpose. These Bean validations are declarative way we can specify and validate by the system. so its very cool feature.

For example i asked user name to client, now client entered some value, now i need to validate its should not be null and its satisfy my other requirements like at-least 5 char for name like this

so usually what we do we put if condition like this

if(name !=null && "".equals(name.trim())  && name.length>5)
          // some logic

these kind of statements needed for all fields. But if we using Bean Validation then its simple.

open the backing bean and mark the fields with constraint annotation

public class DemoBean {
     private String name;

     private Date dob;

     private String email;

     // Getter and Setters

When the the form is submit, then CDI called the bean validation features in transparent manner. If any validation is failed then its add those messages into faces context. so we can see those messages in that page.

Bean Validation applicable not only bean fields, Its have capability to validate the method arguments and its return type. This is grate features of bean validation.

    public String method1( @NotNull String name, @Size(min=5) String lastName)

          return somevalue;

Now when we call this method through CDI, these validation are applied.

Twitter BootStrap Theme

        I make one small example of HTML5 support and Bean validation, i used some free template based on Twitter bootstrap.  these are the refernce

In last link we can learn the twitter bootstrap in depth.

Check the video for small demo code combine HTML5 Support + Bean Validation + Twitter Bootstrap Theme. (Watch it in HD mode)

Demo Code is available in my Github or u can download zip from here

Screen Cast :

Tuesday, 4 June 2013

File Upload is Easy in JSF2.2

To bring the File Upload feature in Java based web application is one of the difficult and complex job, we need to dependent on 3rd party libraries like Apache Commons FileUpload Libraries. These libraries codes are complex and most of them boilerplate code.

If we are using Java Server Faces (JSF), we have the page with some fields and file upload menu the its add more complexity, fields are binded to backing bean but these file uploads components are need to tie up with some 3rd party file upload libraries.

In Primefaces provide easy way to do the file upload in JSF web application, even though primefaces internally used the same Apache Commons FileUpload Libraries, but provide simple JSF tags. We need configure  some listeners.

In Servlet 3.0 they introduced the Part Interfaces and @MultiPartConfig annotations for easy way to do the file upload without any 3rd party libs, Servlet 3.0 is part of Java EE 6 specification. so any servlet 3.0 implementation servers  like Tomcat 7, Jboss 6, GlassFish 3 they can get benefit of servlet 3.0. but this feature is not available in JSF 2.1. so again still it's complex to use file upload in JSF, because we need to mix servlet and JSF backing bean.

Recently JSF 2.2 is released as part of Java EE 7 specification. Now this specs are final and its going to release Q2 of 2013.

Check my post about An introduction to JSF 2.2

in this post i going to show the File Upload feature with a demo

At last JSF 2.2 is added the File Upload component, so we just use <h:inputFile> tag to make the file upload web application so easily, and this component use the Part interface, which its introduced its part of Servlet 3.0. so this JSF2.2 libraries is working perfectly with Tomcat 7 (because tomcat 7 is implemented the Servlet 3.0 spec).

To bring the File Upload feature we need to follow 3 step process

  1. Add <h:inputFile> tag in JSF page
  2. Add enctype="multipart/form-data" attribute in enclosing <h:form> tag
  3. Create the field in Backing bean with Part data type.

Setup the Environment

JSF 2.2 lib are part of Java EE 7, but we can include as a libraries into existing Java EE 6 platform without upgrading the server.
we can get the JSF 2.2 libraries (Mojarra implementation) from here

Step 1:  Add <h:inputFile> tag in JSF page

In JSF page add the <h:inputFile> tag where we need file upload component

  <h:inputFile value="#{demoBean.file1}" />

here i bind the value property to file1 field, which data type is Part, check the third step

Step 2:  Add enctype="multipart/form-data" attribute in enclosing <h:form> tag

When u want file upload feature then we need to inform the browser that form may contain multiple normal text input field  and some file upload component, so prepare the POST request in special form, like parts by part with special delimiter boundary.
 <h:form enctype="multipart/form-data">

so index.xhtml file looks like

        Facelet Title
        Hello from Facelets



Step 2:  Create Backing Bean

now create the backing bean for this page. we need to create the fields for input File component with Part type. Part interface is introduced in servlet 3.0 for represent the file chunks sent by browser, JSF 2.2 use this Part interface, Using the Part interface we can get the header information of each file chunk sent by browser, these header contain the file name and other meta information about the file.

Part interface also contain write() method to write the file contents into specified server location, or u can get the InputStream then we can process it.

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.servlet.http.Part;

 * @author ramki
public class DemoBean {

    private Part file1;
    private Part file2;

    // getters and setters for file1 and file2

    public String upload() throws IOException {
         InputStream inputStream = file1.getInputStream();        
        FileOutputStream outputStream = new FileOutputStream(getFilename(file1));
        byte[] buffer = new byte[4096];        
        int bytesRead = 0;
        while(true) {                        
            bytesRead =;
            if(bytesRead > 0) {
                outputStream.write(buffer, 0, bytesRead);
            }else {
        return "success";

    private static String getFilename(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
        return null;

here we need get the file name from the Header of the chunk, so there is boilerplate code can do, here i don't like this method :-(

there is no direct method to retrieve the file name. so use this code we can get the name of the file is uploaded by client, then using write method we can store into server.

Get my sample project from my Github or download from here

For more information (step by step) see the screencast


An Introduction to JSF 2.2

Recently Java EE 7 specification goes into final. Next week (June 12) oracle going to release the Java EE 7 specification and Glass Fish 4 as reference implementation to general availability.

Java EE 7 adds more features like JSF 2.2, Servlet 3.1, Json Processing, websocket support, etc..
click here about the spec.

In this post i'm going walk through in JSF 2.2

JSF 2.2 is added more features, and JSF as  a main presentation layer of Java EE platform. compare to JSP, jsp is not getting more feature, they just add maintenance release.

Features of JSF 2.2

  • File Upload Component
  • Faces Flow
  • HTML5 Support
  • Cross Site Request Forgery Protection (CSRF)
  • Multi-Templating

File Upload Component

This is most awaited feature in JSF, now we can build the file upload feature in web application without any 3rd party libraries.

i am going to cover this topic in another post.

Faces Flows

Faces flows provides to create the JSF web application in modular way, each module is self contained pages , own backing beans and entry and exit points. Its make the module more reusable.

Faces flows are inspired from Spring Web Flows and Oracle Task Flows

Arun Gupta described his post about Faces Flows

HTML5 Support

HTML5 is future of the web, old JSF libraries are doesn't support HTML5 tags and attributes like placeholder attribute in input field tag, etc.
  <h:inputText   value="#{backingBean.field}"   p:placeholder="Enter text"  />

Cross Site Request Forgery Protection (CSRF)

CSRF is one kind of security attack, Its make the request on existing session.

For example i opened the Tomcat Manager web application and i logged in, now i try to open another web site in different tab, now that website try to execute the code like

then browser make the request to that server (localhost:8080), browser already have session, so that server stop the application.

so we need to add CSRF protection token for every request, if token is not found or invalid then that request is not proceed further, server ignores the request

tomcat 7 uses own CSRF token

here tomcat 7 adds the CSRF token

now JSF 2.2 we can declaratively add the CSRF token to protecting the resources from CSRF attacks

Multi - Templating

Multi Templating is another feature to add more templates (Layout, skins), to web applications.
so we can change the template in run time like wordpress we can change the themes,
just put the theme jar file in classpath, Java platform discovered and apply the templates.

If u have any comments welcomed

Related Posts Plugin for WordPress, Blogger...