Programming

basic programming

Useful DB2 Commands

Among dozens of usefull db2 commands, these are several most usefull db2command, well at least commands that i use the most.

db2move
A Database Movement Tool Command. This tool facilitates the movement of large numbers of tables between DB2 databases located on workstations. The tool queries the system catalog tables for a particular database and compiles a list of all user tables. It then exports these tables in PC/IXF format. The PC/IXF files can be imported or loaded to another local DB2 database on the same system, or can be transferred to another workstation platform and imported or loaded to a DB2 database on that platform.

db2batch
A Benchmark Tool Command. Reads SQL statements from either a flat file or standard input, dynamically prepares and describes the statements, and returns an answer set.

restore
The RESTORE DATABASE command rebuilds a damaged or corrupted database that has been backed up using the DB2 backup utility. The restored database is in the same state that it was in when the backup copy was made. This utility can also overwrite a database with a different image or restore the backup copy to a new database.

Sample Command

db2move sample export

This will export all tables in the SAMPLE database; default values are used for all options.

db2move sample export -tc userid1,us*rid2 -tn tbname1,*tbname2

This will export all tables created by “userid1” or user IDs LIKE “us%rid2”, and with the name “tbname1” or table names LIKE “%tbname2”.

db2move sample export -tn *cust*

This will export all tables with the name “%cust%”.

db2move sample import -io replace -u userid -p password

This will import all tables in the SAMPLE database in REPLACE mode; the specified user ID and password will be used. Parameters for io can be one of INSERT, INSERT_UPDATE, REPLACE, CREATE, and REPLACE_CREATE.

restore db rcms2 from /data/tempdb taken at 20100324184458  into RCMS3 without rolling forward

Restore the DB to another name and with a specific timestamp.

db2batch -d CSS -f insertproduct.sql

This will execute insertproduct.sql

references :

http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/core/r0002079.htm
http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/core/r0002043.htm
http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/core/r0001976.htm

Have Fun (@)

A Simple Hibernate Caching Example using OSCache and EHCache

In this example im trying to create a simple application using Hibernate’s caching feature. What is cache anyway? A cache is designed to reduce traffic between your application and the database by conserving data already loaded from the database and put it whether in memory or in file. Database access is necessary only when retrieving data that is not currently available in the cache. So basically not all queries are taken from database, but from cache instead.

Hibernate use EHCache for default caching, but now im trying to demonstrate both OSCache and EHCache caching library. But you can only use one of it at one time. Both of them only differ in caching configuration, but the rest are still the same.

First is a simple sql file, a java bean and its hibernate xml configuration

CREATE
    TABLE matakuliah
    (
        kodematakuliah VARCHAR(10) NOT NULL,        
        namamatakuliah VARCHAR(20),
        PRIMARY KEY (kodematakuliah)
    )
    ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT
INTO
    matakuliah
    (
        kodematakuliah,        
        namamatakuliah
    )
    VALUES
    (
        '123',        
        'ccc'
    );
package com.edw.bean;

public class Matakuliah  implements java.io.Serializable {

     public class Matakuliah  implements java.io.Serializable {

     private String kodematakuliah;
     private String namamatakuliah;

    public Matakuliah() {
    }

    public Matakuliah(String kodematakuliah) {
        this.kodematakuliah = kodematakuliah;
    }
    public Matakuliah(String kodematakuliah, String namamatakuliah) {
       this.kodematakuliah = kodematakuliah;      
       this.namamatakuliah = namamatakuliah;
    }
   
    // other setters and getters   
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class catalog="kampus" name="com.edw.bean.Matakuliah" table="matakuliah">

    <!-- caching configuration -->
    <cache usage="read-write" />
    
    <id name="kodematakuliah" type="string">
      <column length="10" name="kodematakuliah"/>
      <generator class="assigned"/>
    </id>
      
    <property name="namamatakuliah" type="string">
      <column length="20" name="namamatakuliah"/>
    </property>       
  </class>
</hibernate-mapping>

please take a look at line 7, im using read-write because my data sometimes get updated. If you are planning to have static data that never changes, use read-only.

Next is registering EhCacheProvider on hibernate.cfg.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3307/kampus</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.autocommit">true</property>
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.use_query_cache">true</property>
    <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    <mapping resource="com/edw/bean/Matakuliah.hbm.xml"/>    
  </session-factory>
</hibernate-configuration>

create a java file to load your hibernate configuration file

package com.edw.util;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class HiberUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

and dont forget your ehcache.xml configuration

<?xml version="1.0" encoding="UTF-8"?>
<!--
    caching configuration
-->
<ehcache>
    <defaultCache
        maxElementsInMemory="10"
        eternal="false"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"/>
</ehcache>

and this is my java file to test hibernate’s caching ability

package com.edw.main.caching;

import com.edw.bean.Matakuliah;
import com.edw.util.HiberUtil;
import java.util.Date;
import org.hibernate.Session;

public class CachingMain {

    public CachingMain() {
    }   

    /**
     *  do some repeated queries for table Matakuliah
     *  query results are taken from cache memory instead of database     
     */
    private void withCache() {

        Session session = null;
        try {            
            for (int i = 0; i < 3; i++) {

                // open session
                session = HiberUtil.getSessionFactory().openSession();                

                // time needed
                long now = new Date().getTime();

                // select
                Matakuliah matakuliah = (Matakuliah)session.load(Matakuliah.class, "123");

                // print
                System.out.println("matakuliah "+matakuliah.getNamamatakuliah());
                System.out.println("Time : " + (new Date().getTime() - now) + " ms");

                // sleep for 3seconds
                Thread.sleep(3000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

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

you can see in your console, if you use log4j, this is what happen when Hibernate is querying from cache instead of database

DEBUG org.hibernate.impl.SessionImpl:220 - opened session at timestamp: 5364197853302784
DEBUG org.hibernate.jdbc.ConnectionManager:404 - aggressively releasing JDBC connection
DEBUG org.hibernate.impl.SessionImpl:832 - initializing proxy: [com.edw.bean.Matakuliah#123]
DEBUG org.hibernate.cache.EhCache:68 - key: com.edw.bean.Matakuliah#123
DEBUG org.hibernate.engine.StatefulPersistenceContext:790 - initializing non-lazy collections
matakuliah ccc
Time : 1 ms

Moving from EhCache to OsCache is very simple, all you have to do is replacing 1 line in your xml file, and adding an oscache.properties file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3307/kampus</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.autocommit">false</property>
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.use_query_cache">true</property>
    <property name="hibernate.cache.provider_class">org.hibernate.cache.OSCacheProvider</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    <mapping resource="com/edw/bean/Matakuliah.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

and this is my oscache.properties

cache.capacity=1000
cache.path=c:\\cache\\
cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.HashDiskPersistenceListener

this is what happen on my Netbeans console when im using OsCache

DEBUG org.hibernate.impl.SessionImpl:220 - opened session at timestamp: 5364208706285568
DEBUG org.hibernate.jdbc.ConnectionManager:404 - aggressively releasing JDBC connection
DEBUG org.hibernate.impl.SessionImpl:832 - initializing proxy: [com.edw.bean.Matakuliah#123]
DEBUG com.opensymphony.oscache.base.algorithm.AbstractConcurrentReadCache:694 - get called (key=com.edw.bean.Matakuliah#123.com.edw.bean.Matakuliah)
DEBUG org.hibernate.engine.StatefulPersistenceContext:790 - initializing non-lazy collections
matakuliah ccc
Time : 1 ms

This is my project structure,

Hope it can help others. Have fun. (*)

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 🙂

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 😉

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)