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.

Reverse Ajax with Spring and DWR


Ajax is used heavily for web 2.0 applications to provide enhance user experience, which allows a web page to be updated without the need of full refresh. Normally this updated information is pulled from client side.
Javascript call is used to make an Ajax call to the server and received information is updated.
But there are scenarios when server decides to update information on client side e.g. Chat applications, server side processing status, user presence etc.


In these situations server side "PUSH" is required instead of Client side "PULL". There are three techniques used for this purpose:
  • Polling (the browser sends requests at regular interval)
  • Comet (long lived HTTP connection connection is kept open and server keeps replying)
  • Piggyback (server waits for client to make request and sends update with that request data)
Configuration:
1. Enable Reverse Ajax in DWR configuration
There are two ways of going this:

You can enable in DWR.xml
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>activeReverseAjaxEnabled</param-name>
<param-value>true</param-value>
</init-param>

or if you are using DWR name spaces then you can provide entry in [Servlet Name]-servelt.xml
<dwr:controller id="dwrController" debug="true">
<dwr:config-param name="activeReverseAjaxEnabled" value="true" />
</dwr:controller>

2. Enable Reverse Ajax in JSP
dwr.engine.setActiveReverseAjax(true);

3. Now we need to get Browser sessions from server side and push content there:

WebContext wctx = WebContextFactory.get();
String currentPage = wctx.getCurrentPage();

Get current page from webContext

Collection sessions = wctx.getScriptSessionsByPage(currentPage);
Get all other clients session

After getting these sessions you can push data from here using proxy interface
Util utilAll = new Util(sessions);
utilAll.addOptions("chatlog", messages, "text");

Above lines will add messages collection to all the browsers under "chatlog" element

Similarly you can execute scripts on browsers from server side.

ScriptBuffer script = new ScriptBuffer();
script.appendScript("receiveMessages(")
.appendData(messages)
.appendScript(");");

Above snippet will execute receiveMessages() javascript function on client side.

This way you can have full control on client side from server side. Chat application, Stock Ticker control applications, mail client can use this feature effectively.

Logging using Log4j

Logging is an important of any application. There are several APIs available majorly used are:
1. Apache Log4J
2. Java Logging (java.util.logging)

Logging is required to monitor the state of the running application, debug the application, ignorant developers heavily relies on System.out.println(), which is quite expensive in terms of resources and you dont have any way to manage these messages.

To control this we have different API's like mentioned above.

Using Log4J from Apache:
Log4j consists of 3 aspects: logger, appender and, layout relations between three can be expressed as "logger logs to an appender using a layout"

Each class in an application can have seperate logger or a common logger, now this logger should know where to send request for logging. This where are known as appenders which can be:
- FileAppender (flat file)
- JDBCAppender (database )
- Console Appender (Console)
- SMTPAppender (Email)
- JMSAppender (to remote JMS servers)
- SocketAppender (to remote server).
there are few more.

Now we need to decide what and how we want the out out of that log, this is decided by layout

Each class can have a logger as mentioned above similarly each logger should have log level. There are five different log levels (ordered):
- DEBUG
- INFO
- WARN
- ERROR
- FATAL

To configure a class with a logger, appender, layout and log level we need to use an external configuration file (log4j.properties is the default)

Sample configuratiion file is as:
--------------------------------
# Set root logger level to DEBUG and its only appender to CONSOLE.
log4j.rootLogger=INFO, CONSOLE

# A1 is set to be a ConsoleAppender.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

# Change the level of messages for various packages.
log4j.logger.com.tj.cand.controller=WARN
log4j.logger.com.tj.cand.domain=WARN
log4j.logger.com.tj.cand.dao=DEBUG
--------------------------------

Usage:

Logger log = Logger.getLogger(MyController.class);
log.info("This is a logging message);




Why Spring Framework

Last year I had to shift my web application to some latest framework.
I decided to go for Spring Framework, EJB3 was also an option.

The reason why Spring was:

1. Spring was a well established Open Source
2. Spring provides all the configurations into XML where as EJB3.0 relies in annotations, in my scenario I am using WebSphere 6.1 which runs on JDK1.4 which doesn't support annotations.

3. Spring is a loosely coupled Framework You can decide your own stack. Whereas EJB is whole integrated package.

4. One major reason was You are not forced to use any Spring imports or rely on Spring classes. Dependency Injection combined with external meta-data helps to achieve this independence. So you can easily migrate. While in case of EJB 3.0 this is different.

5. One disadvantage of using annotations based EJB 3.0 is you need to change java source to incorporate any configurations whereas in case of spring you need to change XML file.

XML binding using JiBX

JiBX is a XML binding framework which binds XML to your java class.
XML binding is a 2 phase process:
1. JiBX uses binding definition to define the rule how conversion wil happen and modifies byte code of the class.
2. In phase 2 JiBX runtime does marshalling and un-marshalling of java objects to populate XML to java and java 2 XML.

Algorithm
  • Add following jar files to your lib directory from JiBX distribution
    1. bcel.jar (Byte Code Engineering Library used to change bytecode for the class)
    2. jibx-bind.jar (1,2 are used in phase I)
    3. jibx-run.jar
    4. jibx-extras.jar
    5. xpp3.jar (3,4,5 are used in phase II)
  • Modify java class using binding compiler (java -jar ../lib/jibx-bind.jar binding.xml)
  • Write code for marshalling and unmarshalling of java object

Example:



public void XML2Java2XML() {
try {
IBindingFactory bfact = BindingDirectory.getFactory(Customer.class);
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();

Object obj = uctx.unmarshalDocument
(new FileInputStream("customer.xml"), null);
Customer customer = (Customer)obj;
System.out.print(customer.toString());

IMarshallingContext mctx = bfact.createMarshallingContext();
mctx.setIndent(4);
mctx.marshalDocument(obj, "UTF-8", null,
new FileOutputStream("customer2.xml"));

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JiBXException e) {
e.printStackTrace();
}
}

Password Strength Meter

Almost every web site provides password strength meter.
To make a strong password it should contain:
  • Sufficient length
  • Mixed case
  • Combination of numbers and Special characters

My password strength meter works on same line:

If password is of minimum length and same case it is a weak passwd

If password is min length mixed case and number normal passwd

if password is min length mixed case number and special char it is medium password

if password is above min length and combination of number and special char, it is strong passwd