June 2011 Posts

How to Get Offline Message’s Timestamp on Openfire

I had a simple project using Openfire and Smack library, i found an obstacle when i had to display offline message’s timestamp. I usually use local timestamp for simple messages, but when dealing with offline messages i had to use server’s timestamp, that’s the tricky part.

It is actually very simple to solve it, only several lines of codes. But i’ve spend ridiculously amount of time searching the net for it. That’s why i try to posted it in my blog in case of others might need it.

This is an ordinary packet received,

<message id="Vw7cj-13" to="gajah@edw/Smack" from="kelinci@edw/Smack">
  <body>ordinary message</body>
</message>

while this is what received offline packet looks like

<message id="Vw7cj-12" to="gajah@edw/Smack" from="kelinci@edw/Smack">
  <body>example of offline message</body>
  <thread>U249D0</thread>
  <x xmlns="jabber:x:delay" stamp="20110625T06:53:52" from="edw"/>
</message>

As you can see, offline messages send its timestamp on line 4. Now the problem is how to get it.
But before testing, dont forget to store your message offline policy. And btw, my server name is “edw”.

This is how i solve it,

DelayInformation inf = null;
try {
	inf = (DelayInformation)packet.getExtension("x","jabber:x:delay");
} catch (Exception e) {
	log.error(e);
}
// get offline message timestamp
if(inf!=null){
	Date date = inf.getStamp();

And please dont forget to include smackx.jar.

Im using Openfire 3.6.4 and Smack. I am very recommend these libraries for creating a simple yet powerful instant messaging application based on Java. Have fun :)

Google+

Simple Messaging Example using Hessian

According to Wikipedia, Hessian is a binary web service protocol that makes web services usable without requiring a large framework, and without learning a new set of protocols. Because it is a binary protocol, it is well-suited to sending binary data without any need to extend the protocol with attachments.

From what i’ve tested, perhaps it is somekind of light version of remote EJB3 because i dont have to include so many libraries like EJB3. Altough EJB3 and Hessian are not apple-to-apple comparable, because both arent using the same messaging protocol. EJB3 use RMI-IIOP while Hessian use WebService.

So let’s start with the code. First, for the server part (im using tomcat), create a web project on Netbeans 6.9 and creating a simple interface class,

package com.edw.service;

public interface HelloService {
    String sayHelloTo(String target);
}

after that, i create a simple servlet which implements HelloService interface,

package com.edw.servlet;

import com.caucho.hessian.server.HessianServlet;
import com.edw.service.HelloService;

public class HelloServlet extends HessianServlet implements HelloService {

    public String sayHelloTo(String target) {
        return "hello "+target+", have a nice day";
    }
    
}

dont forget to register your servlet to web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>com.edw.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/HelloServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

next, is creating the client application. I start with a simple java netbeans project, a main class and an interface, i copied the exact copy of HelloService and then put it on my client project,

package com.edw.service;

public interface HelloService {
    String sayHelloTo(String target);
}

and my main class

package com.edw.main;

import com.caucho.hessian.client.HessianProxyFactory;
import com.edw.service.HelloService;

public class Main {

    String url = "http://localhost:809/HessianServer/HelloServlet";
    HessianProxyFactory factory = new HessianProxyFactory();

    public Main() {
    }

    private void doTest() {
        try {
            HelloService hello = (HelloService) factory.create(HelloService.class, url);
            System.out.println(hello.sayHelloTo("si pepe"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Main main = new Main();
        main.doTest();
    }
}

here is the screenshot of my project

This is what the messaging looks like

another good competitor for Spring Http Invoker.
Have fun ;-)

Google+

Creating an MD5 String using Java

MD5 is a simple cryptographic hashing algorithm widely used for various application. In this tutorial im trying to generate MD5 value from a string and then compare it to mysql’s MD5 query result.

This is my java code to generate MD5, im using java’s MessageDigest.

package com.edw.util;

import java.security.MessageDigest;
import org.junit.Test;

/**
 *
 * @author edw
 */
public class MD5Test {

    public MD5Test() {
    }

    public String hexStringFromBytes(byte[] b) {
        char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        String hex = "";
        int msb;
        int lsb = 0;
        int i;

        for (i = 0; i < b.length; i++) {
            msb = ((int) b[i] & 0x000000FF) / 16;
            lsb = ((int) b[i] & 0x000000FF) % 16;
            hex = hex + hexChars[msb] + hexChars[lsb];
        }
        return hex;
    }

    @Test
    public void testMD5() throws Exception {
        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
		
		// get md5 for word "PASSWORD"
        digest.update("PASSWORD".getBytes());
        byte[] passwordBytes = digest.digest();

		// result = 319f4d26e3c536b5dd871bb2c52e3178
        System.out.println(hexStringFromBytes(passwordBytes));		
    }
}

compared to mysql’s md5 function

you can see that MD5 strings generated by java and mysql are both the same.
(H)

Google+

Beginning Apache Velocity : Creating A Simple Web Application

Today im going to try create a simple web application using Apache Velocity. From what is written on its wiki, Apache Velocty is a simple yet powerful Java-based template engine that renders data from plain Java objects to text, xml, email, SQL, Post Script, HTML etc. The template syntax and rendering engine are both easy to understand and quick to learn and implement.
In this example i’m using Velocity 1.7 and Velocity Tools View 2.0, Netbeans 6.9 and Apache Tomcat 6. Im using a simple Servlet acting as Controller, Velocity file with extension .vm as View and a simple ArrayList to mimic ResultSets as the Model.

Lets start with a simple Velocity file

<html>
<head> <title>Hello Velocity</title> </head>
<body>
<h1>Hello World..!!</h1>
<br />
## this is a comment, set variable name with "Edw" value
#set( $name = "Edw" )

<h2> $name is using velocity</h2>

## if-else statement
#if($name.equals("NotEdw"))
    <br />
    not an Edw
#else
    <br />
    Only the Paranoid Survive
#end

<br />
<br />

<table>
<tr>
    <td>Name</td>
    <td>Address</td>
<tr>
## for each statement to iterate over a collection
#foreach($user in $users)
<tr>
    <td>$user.name</td>
    <td>$user.address</td>
<tr>
#end
</table>

## simple velocity method
Today is :  $date.medium
</body>
</html>

i named it index.vm and put it under the Web Pages folder.

Next is creating an xml file, toolbox.xml for registering classes that is needed by Velocity. In this example im only registering a simple DateTool class.

<toolbox>
    <tool>
        <key>date</key>
        <scope>application</scope>
        <class>org.apache.velocity.tools.generic.DateTool</class>
    </tool>
</toolbox>

Next is a simple javabean

package com.edw.bean;

public class User {

    private String name;
    private String address;

    public User() {
    }

    public User(String name, String address) {
        this.name = name;
        this.address = address;
    }

	// other setter - getter
}

And a simple Servlet, im using it simply just for Controller function, it forward my requests-responses to index.vm

package com.edw.servlet;

import com.edw.bean.User;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

public class VelocityServlet extends HttpServlet {

    private Logger logger = Logger.getLogger(getClass());

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {        
        try {
            // simulate a database query
            List<User> users = new ArrayList<User>();
            for (int i = 0; i < 5; i++) {
                User user = new User("name "+i, "Address "+i);
                users.add(user);
            }
            // set values
            request.setAttribute("users", users);

            // get UI
            RequestDispatcher requestDispatcher =  request.getRequestDispatcher("index.vm");
            requestDispatcher.forward(request, response);
        } catch(Exception ex){
            logger.error(ex);
        }
    } 
}

And the most important part is web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <!--    register servlet    -->
    <servlet>
        <servlet-name>ServletVelocity</servlet-name>
        <servlet-class>com.edw.servlet.VelocityServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletVelocity</servlet-name>
        <url-pattern>/velocity.service</url-pattern>
    </servlet-mapping>
    
    <!--    mapping all .vm files to velocity servlets  -->
    <servlet>
        <servlet-name>velocity</servlet-name>
        <servlet-class>org.apache.velocity.tools.view.servlet.VelocityViewServlet</servlet-class>
        <!--    load my toolbox -->
        <init-param>
             <param-name>org.apache.velocity.toolbox</param-name>
             <param-value>/WEB-INF/toolbox.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>velocity</servlet-name>
        <url-pattern>*.vm</url-pattern>
    </servlet-mapping>
    
    <!--    session timeout -->
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    
    <!--    welcome file    -->
    <welcome-file-list>
        <welcome-file>velocity.service</welcome-file>
    </welcome-file-list>
    

    
</web-app>

This is my Netbeans project structure

And this is what my browser displayed

In case of anybody asked about my log4j.properties, here is my configuration

# Global logging configuration
log4j.rootLogger=DEBUG,stdout

# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %c:%L - %m%n

Well it’s not too difficult isn’t it? (H)

Google+