Mongo Cheat Sheet

These days NoSQL concept is hot. I am doing some POC on mongodb.

I am using java driver to access mongodb, to use same DAO pattern and ORM like interface I am using mongo-morphia library.

Quick access to mongo commands, you can go through mongo cheat sheet

JSP 2.0 EL and Functions

In my last project I need to call some utility methods from my JSP to manipulate model data. I didn't wanted to use JSP scriplets within the JSP, so the solution was to use utility method via JSP2.0 EL feature.

Approach I folowed was:
1. Declare function in a tag library descriptor.




xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">

Image Utility functions
Image Utility Tag Library
1.0
ImageUtility

getImagePath
com.til.hk.utils.CommonUtils
java.lang.String getImagePath(java.lang.String, java.lang.String)


getRelativeImagePath
com.til.hk.utils.CommonUtils
java.lang.String getImagePath(java.lang.String)




2. Store TLD under WEB-INF directory (/WEB-INF/tld/)
3. Specify the function's prefix and the library's Uniform Resource Identifier (URI) in JSP file

<%@ taglib uri="/WEB-INF/tld/ImageManip.tld" prefix="image"%>

Using Alert conditionally

In my last project I faced a lot of Bugs filed by QC team related to test Alert pop-ups coming which were introduced by developers for debugging and they forgot to remove those.

To get rid of this I used a wrapper function over alert() function which checks the value of a test variable if that is true then only alert() function will get called, this way I was able to control test alert pop-ups across the web application with single test variable.


DEBUG = false;
function prompt(text) {
if(DEBUG) {
alert(text);
}
}

Message Property Like functionality in Javascript

In my last project I was using JavaScript heavily which was using messages extensively.

Repetition of same kind of messages from multiple places was becoming unmanageable to handle that I have written a JavaScript class which provides Text message with respect to the message code provided.

This function works in two ways:
1. With code only (Messages.getText("error.text"))
2. With code and args (Messages.getText("error.invalid",args))
Here args is replacement for place holders like:
error.invalid = "Invalid input [1] for [0]"
So Invalid error message can be reused for multiple places where [1] will replace by value and [0] wil be replaced for Field name

For function overloading I have used addMethod - By John Resig as reference


function addMethod(object, name, fn){
var old = object[ name ];
if ( old )
object[ name ] = function(){
if ( fn.length == arguments.length )
return fn.apply( this, arguments );
else if ( typeof old == 'function' )
return old.apply( this, arguments );
};
else
object[ name ] = fn;
}

function MessageProvider() {
this.msg = new Object();
this.msg['error.Login'] = 'Please login to submit link';
this.msg['error.invalid'] = 'Invalid input [1] for [0] [0] is invalid';

addMethod(this, "getText", function(code){
return this.msg[code];
});
addMethod(this, "getText", function(code,args){
var text = this.msg[code];
for (var i = 0; i < args.length; i++) {
var re = new RegExp('\\[' + i + '\\]', 'g');
var dest = args[i];
//text = oldtext.replace(re,'’);
text = text.replace(re,dest);
}
return text;

});

}

var Messages = new MessageProvider();


Now to use centralized messaging in javascript you need to add this code to .js File and include in your html
Add all your messages to msg Object

like :



Conflicts faced While Load Testing

I was working on load testing of a web application last month, results were very conflicting when I was accessing application from browser response was very good but while executing script from Jmeter throughput was very less.

I had applied all possible optimizations like :
1. Query Caching
2. Output compression (mod_deflate)
3. Minify JS and CSS

but result was same.
I enabled logs to see compression ratio and realized that Jmeter was not sending accept-encoding HTTP header so Apache was not sending compressed result and that was affecting throughput.
After adding accept-encoding header throughput was as desired.

Using RemoveAllRows function with DIV based pattern

For quite long time we were not able to use DIV based HTML in our DWR based applications.

DWR supports only tables to remove and add rows for any data. Now if your HTML contains DIV based pattern you can not clear and re-populate rows, you need to convert the design to TABLE.

I have modified removeAllRows function frovided by util.js and achieved same for DIV
 
dwr.util.removeAllRowsDiv = function(ele,options) {
return;
ele = document.getElementById(ele);
if (!options) options = {};
if (!options.filter) options.filter = function() { return true; };
if (ele == null) return;

var child = ele.firstChild;
var next;
while (child != null) {
next = child.nextSibling;
if (options.filter(child)) {
ele.removeChild(child);
}
child = next;
}
};


So Now by providing your parrent DIV id you can and pattern div Id you can acheive the same result.

Secrets of implementing a Gtalk Bot

I have read an article on implementing a Gtalk bot. I found it intresting so, I thought to write the concepts behind Google Talk and implementing your own Google Talk Bot.

Google Talk (GTalk) is a free Windows and web-based instant messaging application offered by Google Inc .

Instant messaging between the Google Talk servers and its clients uses an open protocol, XMPP, Protocol.

XMPP (Extensible Messaging and Presence Protocol) is an open technology for instant messaging. The core technology behind XMPP was invented by Jeremie Miller in 1998, refined in the Jabber open-source community in 1999 and 2000, and formalized by the IETF in 2002 and 2003, resulting in publication of the XMPP RFCs in 200.

Google talk uses XMPP for authentication, presence and messaging so any client that supports XMPP can connect to the Google Talk service . Google Talk seervice is hosted at talk.google.com on 5222 port.

To write a Google Talk bot you need to implement XMPP client API of your choice in your choice of platform. For example SMACK is java XMPP client API.

Steps required to write a Gtalk Bot:

1. Download SMACK client API from
2. Extract smack.jar, smackx.jar, smackx-debug.jar
3. Write Gtalk Service Code.

Sending and Receiving Message using SMACK:
  

public class MyGtalkClient implements MessageListener {

public void processMessage(Chat chat,Message message) {
/*Callback method from MessageListener interface .
It is called when a message is received */

System.out.println("Received message: " + message.getBody());
}

public static void main(String [] args) throws XMPPException,IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

/*Login to GTalk service*/
ConnectionConfiguration config = new ConnectionConfiguration (
"talk.google.com",
5222,
"gmail.com");
XMPPConnection connection = new XMPPConnection(config);

connection.connect(); /* Connect to the XMPP server */

connection.login("gtalkid","gtalk pass");
/*Enter your username & password to login to the gtalk service */
Chat chat = connection.getChatManager().createChat(
your_friend_id",new MyGtalkClient());

System.out.println(" ****Welcome to MyGtalkClient**** ");
System.out.println("****Enter your message, one per line ."+
"To stop chat enter stop****");

while( !(msg=br.readLine()).equals("stop")) {
chat.sendMessage(msg); //Send the message
}

connection.disconnect() ; //Disconnect
}
}


This is a very basic example here your buddy is hard coded and you are initiating the chat.
I will write implementing a calculator bot in next part which will provide concepts of listening for a packet, process that packet and send result back to that user.