A Technology Blog About Code Development, Architecture, Operating System, Hardware, Tips and Tutorials for Developers.

Monday, August 30, 2010

INCOMPLETE ROAD MAP TO Thread.run()

8:40:00 PM Posted by Satish , , 1 comment

When it comes to java thread, I always try to dig how the Thread.run() method get executed when, the Thread.start() method get called. Recently, I downloaded the JDK 5 source code and started looking into the implementation.

There is two way we can create user defined threads and in both the scenarios, we used to call the Thread constructor and that internally calls the Thread.init(). init() has the following signature. Basically this method initialize the Thread class members like group, daemon, priority, name etc.

private void init(ThreadGroup paramThreadGroup, Runnable paramRunnable, String paramString, long paramLong);

Now the actual game begins, when you call the start() on a thread object. start() method adds the thread to a thread group as per the initializing parameter. And here the start() calls a native method start0() after that. To find out further, I started looking at the Thread's native implementation.Starting with \JDK 1.5 Source\j2se\src\share\native\java\lang\Thread.c, I found the start0() method is mapped to (void *)&JVM_StartThread (refer line no 25). In \JDK 1.5 Source\j2se\src\share\javavm\export\jvm.h from line no 206 to 256 JNI configuration is there for Thread class native implementation.

Now it is time to jump to the implementation of (void *)&JVM_StartThread method. \JDK 1.5 Source\hotspot\src\share\vm\prims\jvm.cpp contains the implementation of above method. This method basically create a native Java thread and starts the same (refer from line no. 2257 to 2314).

To see the native thread start method, I went to \JDK 1.5 Source\hotspot\src\share\vm\runtime\thread.cpp. In the Thread::start(Thread* thread) method, the particular thread is initialized to RUNNABLE state followed by passing the thread reference to os.

In \JDK 1.5 Source\hotspot\src\share\vm\runtime\os.cpp, the os::start_thread(Thread* thread) method creates a OS thread.

As I have limited exposure in C/C++, I could not move further. But I discussed this in some of the Java forums and found that there will be different thread implementation for different OS and once the OS thread is created, the OS calls and manages the Thread.run() method according to it's own mechanism.

To move further in this, I was needing a C/C++ developer and could probably have looked in to the OS level. I started looking in to Ubuntu, but got confused. So finally left that there.  

Tuesday, August 10, 2010

JAVA EVENT DELEGATION MODEL

10:09:00 PM Posted by Satish , , , , 4 comments
Event broadcasting sytem in java  called as EVENT DELEGATION MODEL. This model is based on the Event Source and Event Listeners. Event Listener is an object that receives the message/ events. The Event Source is any object which creates the message/ event. The Event Delegation Model is based on the following things.
  • Event Source - This class which broadcasts the events.
  • Event Listeners - The classes which receive notifications of events. The Event Listeners are implemented to Adapter classes for the default action for a particular event. The API user is free to override the Adapter version of the method. The event listeners should extend the java.util.EventListener interface.
  • Event Object - The object which describes the event. The event object class should extend java.util.EventObject class.
  • Event Manager - This is the class which manages the relationship between the event and listeners. This class will register and de-register the listeners for a particular event.
The following picture explains how the event model works.


Now time to look at the programming implementation.

Event Class:

1
2
3
4
5
6
7
8
import java.util.EventObject;

//Declare the event. It must extend EventObject.
public class MyEvent extends EventObject {
    public MyEvent(Object source) {
        super(source);
    }
}

Event Listener:

1
2
3
4
5
6
7
8
9
package org.satish.event;

import java.util.EventListener;

//Declare the listener class. It must extend EventListener.
//A class must implement this interface to get MyEvents.
public interface MyEventListener extends EventListener {
    public void myEventOccurred(MyEvent evt);
}

Event Manager:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package org.satish.event;

import java.util.ArrayList;
import java.util.List;

//Add the event registration and notification code to a class. 
public class EventManager {
    // Create the listener list
    protected List listenerList = new ArrayList();

    // This methods allows classes to register for MyEvents
    public void addMyEventListener(MyEventListener listener) {
        listenerList.add(listener);
    }

    // This methods allows classes to unregister for MyEvents
    public void removeMyEventListener(MyEventListener listener) {
        listenerList.remove(listener);
    }

    // This method is used to fire MyEvents
    void fireMyEvent(MyEvent evt) {
        System.out.println("Got the event." + listenerList.size());
        // Iterate the Listener list to fire the implemented method of each
        // listener.
        for (MyEventListener myEventListener : listenerList) {
            System.out
                    .println("Firing listener method for each of the listener.");
            myEventListener.myEventOccurred(evt);
        }
    }
}

Event Source:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package org.satish.event;

public class EventGenerator implements Runnable{
    
    Thread t;
    EventManager c;
    public EventGenerator(EventManager c) {
        // TODO Auto-generated constructor stub
        this.c = c;
        t =  new Thread(this, "Event Generator");
        t.start();
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("Event generator in the run method.");
        while(true){
            System.out.println("Generate a event.");
            c.fireMyEvent(new MyEvent(this));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO: handle exception
            }
        }
    }
}

Demo Starter:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package org.satish.event;

public class EventDemo {
    public static void main(String[] args) {

        EventManager c = new EventManager();

        // Event Generator is instantiated to generate the events.
        EventGenerator eventGenerator = new EventGenerator(c);
        System.out.println("Event generator started.");

        // Register for MyEvents from c
        // Here the object of MyEventListener is been created, implementing the
        // interface method. Developers are free to user the Adapter class
        // object or use their own implementation class object.
        c.addMyEventListener(new MyEventListener() {
            public void myEventOccurred(MyEvent evt) {
                // MyEvent was fired
                System.out.println("1st Event Fired");
            }
        });
        System.out.println("First event is registered.");

        // Register another event
        c.addMyEventListener(new MyEventListener() {
            public void myEventOccurred(MyEvent evt) {
                // MyEvent was fired
                System.out.println(" 2nd Event Fired");
            }
        });
        System.out.println("Second event is registered.");
    }
}


This is the basic implementation of event delegation model. In a multi threaded environment, where more than one listener are registered to each event and the generation of event is quite fast, then you need to change your design to deal with the requirement.

Source Code:

Complete source code you can fork from GitHub.

Saturday, July 17, 2010

TOMCAT SSL CONFIGURATION IN UBUNTU

11:12:00 PM Posted by Satish , , , , No comments

This post is made considering the the system is having jdk 6 and Tomcat 6 installed and "JAVA_HOME" environment variable is set.

Bellow are the steps to configure tomcat to listen https port (8443)

1. Create a certificate keystore by executing the following command. It will ask few questions. It will also ask one password to enter. You have to remember this password as you need to specify that to configuration file.  You can store the keystore any where.
    keytool -genkey -alias tomcat -keyalg RSA 
    \-keystore /usr/local/tomcat/conf/.keystore

2. Now configure "tomcat_home"\conf\server.xml, add the following code.
    <Connector
    port="8443" 
    protocol="org.apache.coyote.http11.Http11Protocol"   
    maxThreads="200"
    scheme="https" secure="true" SSLEnabled="true"
    keystoreFile="/usr/local/tomcat/conf/.keystore"  
    keystorePass="password"
    clientAuth="false" 
    sslProtocol="TLS"/>  

You are done with your configuration. Save the "server.xml" file. Restart your tomcat. Now type https://localhost:8443

This should show you the same tomcat homepage but in secured format.

Friday, July 9, 2010

JNI WITH UBUNTU

5:18:00 PM Posted by Satish , , , 1 comment

Most of the native methods are written in "C". The mechanism to integrate "C" code with a Java program is called the Java Native Interface(JNI).

Java Client to call native method :

package org.satish.chapter_13;

public class NativeDemo {
    int i;
    public static void main(String[] args) {
        NativeDemo ob = new NativeDemo();
       
        ob.i = 10;
        System.out.println("This is ob.i before this native method : " + ob.i);
        ob.test();
        System.out.println("This is ob.i after this native method : " + ob.i);
    }
   
    public native void test();

   
    static{
        System.load("/home/satish/workspace/CompleteReference2010/bin/NativeDemo.so");
    }
}

Create headed file out of the Class :

Before to this compile the java to ".class" file. Now it is ready to create the ".h "file.

javah -jni org.satish.chapter_13.NativeDemo

Content of the header file :

/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class org_satish_chapter_13_NativeDemo */

#ifndef _Included_org_satish_chapter_13_NativeDemo
#define _Included_org_satish_chapter_13_NativeDemo
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     org_satish_chapter_13_NativeDemo
 * Method:    test
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_org_satish_chapter_113_NativeDemo_test
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

The C program : 

/*
    This file contains the C version of the test()
*/

#include
#include "org_satish_chapter_13_NativeDemo.h"
#include
JNIEXPORT void JNICALL Java_org_satish_chapter_113_NativeDemo_test(JNIEnv *env, jobject obj)
{
    jclass cls;
    jfieldID fid;
    jint i;
   
    printf("Starting the native method. \n");
    cls = (*env) ->GetObjectClass(env, obj);
    fid = (*env) ->GetFieldID(env, cls, "i", "I");

    if(fid == 0){
        printf("could not get field id. \n");
        return;
    }
    i = (*env)->GetIntField(env, obj, fid);
    printf("i = %d\n",i);
    (*env)->SetIntField(env,obj,fid,2*i);
    printf("Ending the native method.\n");
}

Create .SO file : 

Before to create the .so file, you need to install the gcc in your system.

sudo apt-get install gcc

Once gcc is installed, you can create the .so file using the following command.

sudo gcc -I /usr/lib/jvm/java-6-sun-1.6.0.20/include/linux/ -o NativeDemo.so -shared NativeDemo.c

Now your java class is ready to run and following is the output.

This is ob.i before this native method : 10
This is ob.i after this native method : 20
Starting the native method.
i = 10
Ending the native method.

Wednesday, June 23, 2010

GSM MODEM WITH MY GSM PHONE

10:02:00 PM Posted by Satish , , , , 6 comments

INTRODUCTION TO GSM MODEM:

A GSM modem is a wireless modem that works with a GSM wireless network. A wireless modem behaves like a dial-up modem. The main difference between them is that a dial-up modem sends and receives data through a fixed telephone line while a wireless modem sends and receives data through radio waves. Computers use AT commands to control modems. Both GSM modems and dial-up modems support a common set of standard AT commands.

MOBILE PHONE OR GSM MODEM:


In general, a GSM/GPRS modem is recommended for use with a computer to send and receive messages. This is because some mobile phones have certain limitations comparing to GSM/GPRS modems. Using my Nokia 3110C, I am not able to receive any messages to my computer. And also I noticed the phone always run out battery in no time. But there are some phones in the market which support all the AT commands. Here is the list of AT Commands supported by the Nokia phones.

SETUP THE MOBILE PHONE AS GSM MODEM:

1. Connect your mobile phone to a computer and set up the corresponding wireless modem driver.
2. Run MS HyperTerminal by selecting Start -> Programs -> Accessories -> Communications -> HyperTerminal.
3. In the Connection Description dialog box, enter a name and choose an icon you like for the connection. Then click the OK button.
-->

4. In the Connect To dialog box, choose the COM port that your mobile phone is connecting to in the Connect using combo box. For example, choose COM1 if your mobile phone is connecting to the COM1 port. Then click the OK button.
Note:
Sometimes there will have more than one COM port in the "Connect Using" combo box. To know which COM port is used by your mobile phone, follow the procedure below:
a. Go to Control Panel -> Phone and Modem Options".
b. Then click the Modems tab. In the list box, you can see which COM port the mobile phone or GSM/GPRS modem is connected to.
5. The "Properties" dialog box comes out. Enter the correct port settings for your mobile phone. Then click the OK button.
Note:
To find the correct port settings that should be used with your mobile phone, one way is to consult the manual of your mobile phone. Another way is to check the port settings used by the wireless modem driver that you installed earlier.
To check the port settings used by the wireless modem driver, follow these steps:
a. Go to Control Panel -> Phone and Modem Options -> Modems tab.
b. Select your mobile phone in the list box.
c. Click the "Properties" button.
d. The Properties dialog box appears. Click the Advanced tab and then click the Change Default Preferences button.
e. The Change Default Preferences dialog box appears. The Port speed field on the General tab corresponds to HyperTerminal's "Bits per second" field. You can also find the setting for flow control on the General tab. On the Advanced tab, you can find the settings for data bits, parity and stop bits.
6. Type AT in the main window. A response OK should be returned from the mobile phone or GSM/GPRS modem. Type AT+CPIN? in the main window. The AT command AT+CPIN? is used to query whether the mobile phone is waiting for a PIN (personal identification number, i.e. password). If the response is +CPIN: READY, it means the SIM card does not require a PIN and it is ready for use. If your SIM card requires a PIN, you need to set the PIN with the AT command AT+CPIN=[PIN].

Now the mobile phone is configured to work as a GSM modem.
JAVA CONFIGURATION FOR COM PORT:

As the modem is connected to the COM port of the computer, you have to use Java Communications API.
Sun provides an API extension for communicating with parallel and serial ports, specifically for Solaris and Windows environments. The API can be found here. There are also third party APIs and an open source implementation, which works on several platforms including Linux. You can download the Java Communications API from here.

INSTALLING THE JAVA COMMUNICATIONS API IN WINDOWS ENVIRONMENT:

Among the items that you download from Sun are three very important files:
1. comm.jar
2. win32com.dll
3. javax.comm.properties

For the JVM to recognize the serial ports, proper placement of these files is important. And have found the following installation methods to be effective:

1. comm.jar should be placed in:

    %JAVA_HOME%/lib
    %JAVA_HOME%/jre/lib/ext

2. win32com.dll should be placed in:

    %JAVA_HOME%/bin
    %JAVA_HOME%/jre/bin
    %windir%System32

3. javax.comm.properties should be placed in:

    %JAVA_HOME%/lib
    %JAVA_HOME%/jre/lib

Now Java is correctly configured to interact with the COM ports. Now it is the time to write a program to send and receive message.

SENDING AND RECEIVEING SMS:

For sending and receiving SMS I am using the following procedure.

1. Connecting to the COM port where the modem is connected.
2. Registering the listener for serial port event.
3. Using the following set of AT commands to send the SMS.

            AT (To check the modem)
            OK (Response - modem connected)

            AT+CMGF=1 (To set the text messaging mode)
            OK (Response - text messaging mode set successfully)

            AT+CSCA="+979797979796464" (To set the message center)
            OK (Response - message center is set properly)

            AT+CMGS="+91021482048023" (To set the recipient no and open the message writing prompt)
            >my test message + [Ctrl+z] ("Ctrl+z" is to come out of the message writing prompt)
            OK             
            CMGS: +919886599334 (Message sent)
    
4. As we have registered to the serial port events, when ever any data will come to the serial port the implemented method will print the data to the console. It is applicable for receive message also.

If you are using the GSM/GPRS modem, then lot of other features of phone like call receiving, making a call, call forwarding, answering machine etc can be developed for any enterprise application. 

SHARED ITEMS:

1. Source Code or you can fork at GitHub.

Tuesday, June 1, 2010

OBJECT ORIENTED PROGRAMING WITH JAVASCRIPT

9:25:00 AM Posted by Satish , , 2 comments

JavaScript is a object based language and Java is a object oriented language. There are lot of object oriented features comes with java like static and non-static members, private and public members, inheritance etc. So why can't we have all these in JavaScript??? After googling and discussing with some of the JavaScript developers, finally we could able to demonstrate the object oriented features using JavaScript. We made use of JavaScript function and prototype to achieve this.

Work Flow:

1. One base class is created.
2. Another child class created extending the base class to demonstrate the inheritance.
3. One subclass created extending the second class to demonstrate the multilevel inheritance.

I am sharing the source code to better understand, what we did.

Note:

1. All the classes will be having static, non-static, private and public members.
2. In the test client we are demonstrating some of these features.
3. To test the other features, additional caller codes has to be added.

4. What ever we worked out is not the actual object oriented features in JavaScript. But certainly works like that.
5. There can be many other ways to do the same.

Shared Items:


Friday, May 21, 2010

LOG TAILER (DWR)

6:54:00 PM Posted by Satish , , , No comments

I was working in Ubuntu platform and most of the time used the "tail -f xxx.log" command to tail the application logs. It also helps the administrator to keep an eye on the happenings at application side. I created a small application to tail the logs to the web UI. So the administrator can see the logs to web UI, even if he does not have the server login credentials.

Environment set up:
1. Install JDK 1.6 in your system or any platform you want.

2. Install Tomcat 6 followed by JDK installation.

3. Deploy the war file to " webapps" of Tomcat installation directory and start the server.(I configured the log path to "/usr/local/tomcat/logs/")

4. Now you can view the demonstration by entering "http://localhost:8080/DWR" to the browser location bar.

Eclipse setup:

1. To work with the source code, please use eclipse 3.3 or higher version.

2. Download the source code.

3. Create a dynamic web project with name "DWR".

4. Copy the whole content of downloaded "DWR" folder to the workspace "DWR" folder and refresh the workspace.

5. Configure Tomcat to eclipse and add the project to that.
About the application:

The application will be keep listening to the log files and when ever a new line get added to that, the message will be get pushed to the client.

The whole process goes some thing like this.

1. When you start the server, the event engine will get started and will keep creating the event objects when ever there is any update to the log file.

2. Now you can view the demonstration by entering "http://localhost:8080/DWR/" to the browser location bar.

3. When ever there is any update to the log file, the message will be get to the UI.

Shared Items:

1. Source Codes or you can fork at GitHub.

2. War File

3. Java Doc

Thursday, May 20, 2010

REVERSE AJAX (DWR)

7:31:00 PM Posted by Satish , , , No comments

It had been a long time, I last worked in DWR. Around one year back at my previous company, I was working in DWR. I used reverse AJAX technique to some part of the application, which was quite impressive. So I started playing around this again to do some new things.

This part of the post is just a basic demonstration of reverse AJAX. The basic idea is to push different messages to different clients.  Let's take a example; there is a page with javascript links to load different shelf's of a ware house in to a div element. Client "A" is viewing shelf "SH-01" and client "B" is viewing shelf "SH-2". In this case client "A" and client "B" should have been pushed with different updates.

Environment set up:

1. Install JDK 1.6 in your system or any platform you want.

2. Install Tomcat 6 followed by JDK installation.

3. Deploy the war file to " webapps" of Tomcat installation directory and start the server.

4. Now you can view the demonstration by entering "http://localhost:8080/DWR" to the browser location bar.

Eclipse setup:

1. To work with the source code, please use eclipse 3.3 or higher version.

2. Download the source code.

3. Create a dynamic web project with name "DWR".

4. Copy the whole content of downloaded "DWR" folder to the workspace "DWR" folder and refresh the workspace.

5. Configure Tomcat to eclipse and add the project to that.

About the application:

The application has got the following components.

1. Event Engine

2. Event Listener

3. Script Session Manager

Event Engine is nothing to do with reverse AJAX. I just created to demonstrate the message pushing technique. Event Engine will get stated when the server starts for the first time. This engine will keep on create the messages and notify all the listeners.

Event Listeners will be listening to all the events generated by the Event Engine and use the Script Session Manager to push the message to respective client.

Script Session Manager is responsible for registration and de-registration the client script sessions. And it is also responsible for message processing and pushing to respective client.

The whole process goes something like this.

1. When you start the server, the event engine will get started with that.(Created a servlet with init block and configured in web.xml to create a event object at startup)

2. Now you can view the demonstration by entering "http://localhost:8080/DWR" to the browser location bar.

3. Select Any parameter from the dropdown.(The application will create a script session at server side.)

4. Now when ever any message for that parameter will get generated, the message will be pushed to the client.

5. You can change the parameter in UI and get the respective updates accordingly.

6. If you close the window without removing the session, the session will get expire after 500ms.

Shared Items:

1. Source Codes or you can pull it from GitHub.

2. War File

3. Java Doc