Tuesday, November 25, 2014

Creating a simple WebSocket Server to send ActiveMQ events from a queue

WebSocket 

WebSocket is a protocol providing full-duplex communications channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.- Wikipedia

ActiveMQ


Apache ActiveMQ is a popular open source messaging server. it supports many cross language clients and protocols. Mainly it supports JMS 1.1 and J2EE 1.4

This application dequeue events(or whatever things in the queue) and send them to a TCP clients using websocket.

This is the WebSocketHandler class. This contains the methods that use to initiate websocket connection with clients. In onConnect method, connection is established with the ActiveMQ and starts dequeuing events from the queue. Please make sure create a queue named "mydataque" in ActiveMQ before continuing.


/**

 * Created by IntelliJ IDEA.

 * User: Chann

 * Date: 11/23/14

 * Time: 11:06 PM

 * To change this template use File | Settings | File Templates.

 */

import java.io.IOException;

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.Future;

import java.util.concurrent.TimeUnit;



import org.apache.activemq.ActiveMQConnectionFactory;

import org.eclipse.jetty.websocket.api.Session;

import org.eclipse.jetty.websocket.api.StatusCode;

import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;

import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;

import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;

import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;

import org.eclipse.jetty.websocket.api.annotations.WebSocket;



import javax.jms.*;



@WebSocket

public class MyWebSocketHandler {





    private static String url = "tcp://localhost:61616";

    private static String subject = "mydataque";



    //private final CountDownLatch closeLatch;



    @SuppressWarnings("unused")

    private Session session;







    @OnWebSocketClose

    public void onClose(int statusCode, String reason) {

        System.out.println("Close: statusCode=" + statusCode + ", reason=" + reason);

    }



    @OnWebSocketError

    public void onError(Throwable t) {

        System.out.println("Error: " + t.getMessage());

    }



    @OnWebSocketConnect

    public void onConnect(Session session) {

        System.out.println("Connect: " + session.getRemoteAddress().getAddress());

        try {

            session.getRemote().sendString("Hello Webbrowser");

        } catch (IOException e) {

            e.printStackTrace();

        }

        /////////////////////////////////////////////////////////////////////

        System.out.printf("Got connect: %s%n", session);

        this.session = session;

        try {



            Future<Void> fut;



            int i = 0;



            // Getting JMS connection from the server

            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(

                    url);

            Connection connection = connectionFactory.createConnection();

            connection.start();



            // Creating session for sending messages

            javax.jms.Session session2 = connection.createSession(false,

                    javax.jms.Session.AUTO_ACKNOWLEDGE);



            // Getting the messages from the queue

            Destination destination = session2.createQueue(subject);



            // MessageConsumer is used for receiving (consuming) messages

            MessageConsumer consumer = session2.createConsumer(destination);



            try {



                // Receive the message.

                System.out.println("The Consumer : " + consumer.toString());

                while (true) {



                    Message message = consumer.receive();

                    System.out.println("Received message '"

                            + ((TextMessage) message).getText() + "'");

                    fut = session.getRemote().sendStringByFuture(((TextMessage) message).getText());

                    fut.get(2, TimeUnit.SECONDS);

                    Thread.sleep(50);

                    i++;

                }



            } catch (Exception e) {

                System.out.println("Error : " + e.getMessage());

            }



            finally {

                session.close(StatusCode.NORMAL,

                        "[Consumer]Closing the session with the Server!!");

                connection.close();

                session2.close();



            }





        } catch (Throwable t) {

            t.printStackTrace();

        }

        /////////////////////////////////

    }



    @OnWebSocketMessage

    public void onMessage(String message) {

        System.out.println("Message: " + message);

    }

}
This is the class that contains main methode that initiate webSocket.  After running this class you can access your webSocket using any browser which supports webSockets using url ws://localhost:8081
You can use simple Chrome extensions like this

/**

 * Created by IntelliJ IDEA.

 * User: Chann

 * Date: 11/23/14

 * Time: 11:01 PM

 * To change this template use File | Settings | File Templates.

 */

import org.eclipse.jetty.server.Server;

import org.eclipse.jetty.websocket.server.WebSocketHandler;

import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

import javax.servlet.ServletException;



public class WebSocketTest {



    public static void main(String[] args) throws Exception {

        Server server = new Server(8081);

        WebSocketHandler wsHandler = new WebSocketHandler() {

        //MessageSocket wsHandler = new MessageSocket()

            @Override

            public void configure(WebSocketServletFactory factory) {

                factory.register(MyWebSocketHandler.class);

            }

        };

        server.setHandler(wsHandler);

        server.start();

        server.join();

    }


}

Sunday, August 10, 2014

Adding String values to nvd3 line chart x axis values

If you're familier with nvd3 line charts you may experienced that adding a string values as x axis values may be little bit messy.
Here is the solution.
first you need to specify the xAxis tickformat function.


chart.xAxis
.axisLabel('Date')
.tickFormat(function(d) {
 var label = scope.totalLoanAmountData[0].values[d].label;
 return label;
});
here I'm using "label" attribute to display strings in the chart x axis.
And then add your data values with label attribute as follows.

scope.totalLoanAmountData=[{
                        "key": "name of line one",
                        "values":[
                {x:1,y:2, label:"label1"},
                {x:1,y:2, label:"label2"},
                {x:1,y:2, label:"label3"},
                {x:1,y:2, label:"label4"},
                {x:1,y:5, label:"label5"},
                {x:1,y:2, label:"label6"},
                {x:1,y:7, label:"label7"},
                {x:1,y:2, label:"label8"},
                {x:1,y:8, label:"label9"}]

                           },

                      {"key": "name of line two",
                        "values": [

                {x:1,y:8, label:"label1"},
                {x:1,y:2, label:"label2"},
                {x:1,y:2, label:"label3"},
                {x:1,y:6, label:"label4"},
                {x:1,y:5, label:"label5"},
                {x:1,y:2, label:"label6"},
                {x:1,y:8, label:"label7"},
                {x:1,y:2, label:"label8"},
                {x:1,y:2, label:"label9"}]

                      }];
You can use date, name, number or whatever string you want.

Sunday, June 15, 2014

Google Summer of Code 2014

Organization - Mifos Initiative 

Mifos is a diverse community of microfinance institutions, technology professionals, business people, volunteers, and contributors. The Mifos Initiative is a 501(c)3 non-profit incorporated in Washington state whose mission is to speed the elimination of poverty by enabling financial service providers to more effectively and efficiently deliver responsible financial services to the world’s 2.5 billion poor and unbanked

Project - Client Impact Portal 

For a Microfinance institution it is useful to have a way of presenting overall client details and other institution details in a high level manner. This information may be useful to external parties that involve with the institutions such as funders and investors. Idea of this project is to provide such a capability to Mifos using a Client Impact Portal. This project consists of both the backend support and frontend for the user who intend to retrieve high level detail of the institutions. Project wiki page

Summer of code Interns in Mifos

This year Mifos have seven interns from four different countries who will be working under the leadership of  mentors from six different countries. They'll be working on a wide spectrum of projects that range from the back-end platform to the front-end community app, on down to mobile apps used directly in the field. By the end of the summer, Mifos community will benefit from a native Android app dedicated to making field staff more efficient, a mobile app for enabling Pay as you Go Solar Energy transactions, a vastly improved user experience for  community app, enhancements to  data migration tool, a batching API that will unlock performance improvements across the entire platform, as well as a powerful ad-hoc reporting tool and evolutions to the client impact portal to a production-ready release.
A Light-hearted Look at  2014 GSOC Interns
2014 Google Summer of Code – Bigger and Better than Ever