What is the Size of ” null ” Operator in Java?

[ This Blog Was Moved To : http://www.diknows.com ]

Today, in the Java Developers Group in LinkedIn; I found this question posted by Sneha Kesri. She asked “What is the size of ” null ” Operator in Java ?”.

Actually, I never thought of it that way, but I continued reading.

Ramesh Babu Kotehal replied with the following :

from the heap memory perspective it will be 0, as it wont allocate any memory from heap. But from stack memory perspective the object has reference which is set to null. and the reference variable size depends your system.
for 32 bit system it will be 4 byte and for 64 bit system it will be 8 byte.

but as such null is not referring to any data from heap, so heap memory will be same.

And that was the only reply by then, which was correct, but Sneha Kesri asked another question:

Thanks Ramesh, I am having one more doubt… when we say..

String str1 = null;
String str2 ="";

Since str1& str2 are not equal.Does Str2 allocates memory in heap?
Does it take any value i.e garbage value for str2;

And is there any way to check memory size in Java?

So, I replied her with the following :

When you write

String st1 = null;

You create a reference “str1” to an object that still does not exist in the heap, but when you type :

String st2 = "" ;

You create a reference “str2” to a string object that is already allocated in the heap which preserves the string object size.

if you do that expression

str1 == str2 ;

It should evaluate to false, because you are comparing reference values, which will not be equal.

if you do that expression

if(str1.equals(str2) ){ }

It should throw a NullPointerException because you are trying to access the method equals on a null object ( str1 )

but if you try that expression

if(str2.equals(str1) ) {}

It should return false, because the value of ( str2 ) is an empty string not null object.

I wish It was helpful.



How To Change Nagios Password

[ This Blog Was Moved To : http://www.diknows.com ]

Later this afternoon, a colleague asked my help to change the Nagios Password.

As I am not a Nagios user, I searched google for it and found this link about Nagios Installation.

So, lets cut to the chase, here are the steps I used:

root# touch /usr/local/nagios/sbin/.htaccess

root# vi /usr/local/nagios/share/.htaccess

And I wrote the follwing text in the .htaccess file

AuthName "Nagios Access"
AuthType Basic
AuthUserFile /usr/local/nagios/etc/htpasswd.users
require valid-user

Then, I did the following:

root# touch /usr/local/nagios/share/.htaccess

root# vi /usr/local/nagios/sbin/.htaccess

And I wrote the same text in that file too. Then, I did the following
(Which is the command for changing the password ):

root# htpasswd -c /usr/local/nagios/etc/htpasswd.users nagiosadmin

New password:
Re-type new password:
Adding password for user nagiosadmin

root#  ls -l /usr/local/nagios/etc/htpasswd.users
-rwxrwxr--  1 nagios nagios 26 Dec 21 15:54 /usr/local/nagios/etc/htpasswd.usersroot#

root# chmod o+r /usr/local/nagios/etc/htpasswd.users

root# service httpd restart

Stopping httpd:                                            [  OK  ]
Starting httpd:                                            [  OK  ]

And, This is it for now.

Read/Write System Properties From/Into XML Using Groovy

[ This Blog Was Moved To : http://www.diknows.com ]

Inspired by the following post ( http://www.ibm.com/developerworks/library/j-tiger02254.html ), I created the following code snippets to Read / Write System properties from/into XML files.

Writing system properties into XML file (output.xml):

def properties = System.properties
def fos = new FileOutputStream("output.xml")

Reading system properties from XML file (input.xml):

def prop = new Properties()
def fis = new FileInputStream("input.xml")

And, ofcourse this line can be used to list the properties in any properties object


Here is the resultant XML File:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
 <entry key="java.runtime.name">Java(TM) SE Runtime Environment</entry>
 <entry key="sun.boot.library.path">/opt/jdk1.6.0_17/jre/lib/amd64</entry>
 <entry key="java.vm.version">14.3-b01</entry>
 <entry key="java.vm.vendor">Sun Microsystems Inc.</entry>
 <entry key="java.vendor.url">http://java.sun.com/</entry>
 <entry key="path.separator">:</entry>
 <entry key="java.vm.name">Java HotSpot(TM) 64-Bit Server VM</entry>
 <entry key="file.encoding.pkg">sun.io</entry>
 <entry key="sun.java.launcher">SUN_STANDARD</entry>
 <entry key="user.country">US</entry>
 <entry key="sun.os.patch.level">unknown</entry>
 <entry key="program.name">groovyConsole</entry>
 <entry key="java.vm.specification.name">Java Virtual Machine Specification</entry>
 <entry key="user.dir">/home/dino/Documents</entry>
 <entry key="java.runtime.version">1.6.0_17-b04</entry>
 <entry key="java.awt.graphicsenv">sun.awt.X11GraphicsEnvironment</entry>
 <entry key="java.endorsed.dirs">/opt/jdk1.6.0_17/jre/lib/endorsed</entry>
 <entry key="os.arch">amd64</entry>
 <entry key="java.io.tmpdir">/tmp</entry>
 <entry key="line.separator">
 <entry key="java.vm.specification.vendor">Sun Microsystems Inc.</entry>
 <entry key="os.name">Linux</entry>
 <entry key="tools.jar">/opt/jdk1.6.0_17//lib/tools.jar</entry>
 <entry key="sun.jnu.encoding">UTF-8</entry>
 <entry key="script.name">/home/dino/installations/groovy/groovy-1.6.5/bin/groovyConsole</entry>
 <entry key="java.library.path">/opt/jdk1.6.0_17/jre/lib/amd64/server:/opt/jdk1.6.0_17/jre/lib/amd64:/opt/jdk1.6.0_17/jre/../lib/amd64:/usr/lib64/mpi/gcc/openmpi/lib64:/usr/java/packages/lib/amd64:/lib:/usr/lib</entry>
 <entry key="java.specification.name">Java Platform API Specification</entry>
 <entry key="java.class.version">50.0</entry>
 <entry key="sun.management.compiler">HotSpot 64-Bit Server Compiler</entry>
 <entry key="os.version"></entry>
 <entry key="user.home">/home/dino</entry>
 <entry key="user.timezone">Africa/Cairo</entry>
 <entry key="java.awt.printerjob">sun.print.PSPrinterJob</entry>
 <entry key="file.encoding">UTF-8</entry>
 <entry key="java.specification.version">1.6</entry>
 <entry key="java.class.path">/home/dino/installations/groovy/groovy-1.6.5/lib/groovy-1.6.5.jar</entry>
 <entry key="user.name">dino</entry>
 <entry key="java.vm.specification.version">1.0</entry>
 <entry key="java.home">/opt/jdk1.6.0_17/jre</entry>
 <entry key="sun.arch.data.model">64</entry>
 <entry key="user.language">en</entry>
 <entry key="java.specification.vendor">Sun Microsystems Inc.</entry>
 <entry key="java.vm.info">mixed mode</entry>
 <entry key="java.version">1.6.0_17</entry>
 <entry key="java.ext.dirs">/opt/jdk1.6.0_17/jre/lib/ext:/usr/java/packages/lib/ext</entry>
 <entry key="sun.boot.class.path">/opt/jdk1.6.0_17/jre/lib/resources.jar:/opt/jdk1.6.0_17/jre/lib/rt.jar:/opt/jdk1.6.0_17/jre/lib/sunrsasign.jar:/opt/jdk1.6.0_17/jre/lib/jsse.jar:/opt/jdk1.6.0_17/jre/lib/jce.jar:/opt/jdk1.6.0_17/jre/lib/charsets.jar:/opt/jdk1.6.0_17/jre/classes</entry>
 <entry key="java.vendor">Sun Microsystems Inc.</entry>
 <entry key="file.separator">/</entry>
 <entry key="java.vendor.url.bug">http://java.sun.com/cgi-bin/bugreport.cgi</entry>
 <entry key="sun.io.unicode.encoding">UnicodeLittle</entry>
 <entry key="sun.cpu.endian">little</entry>
 <entry key="groovy.sanitized.stacktraces">org.codehaus.groovy.runtime.
 <entry key="groovy.full.stacktrace">false</entry>
 <entry key="groovy.starter.conf">/home/dino/installations/groovy/groovy-1.6.5/conf/groovy-starter.conf</entry>
 <entry key="groovy.home">/home/dino/installations/groovy/groovy-1.6.5</entry>
 <entry key="sun.cpu.isalist"/>

And this is it for now.

Testing MySQL GET_LOCK() using PHP

[ This Blog Was Moved To : http://www.diknows.com ]

Early this morning, a friend of mine was stuck in GET_LOCK() MySQL function. She was using it in her application. The function was working very well from the MySQL Console , but it was not working from PHP ( Neither from her application, nor from PHPMyAdmin web interface).

She asked my help, so I searched Google, and had a look at the MySQL Documentation about this function.

This function as it appears in the MySQL Documentation, does the following :


Tries to obtain a lock with a name given by the string str, using a timeout of timeout seconds. Returns 1 if the lock was obtained successfully, 0 if the attempt timed out (for example, because another client has previously locked the name), or NULL if an error occurred (such as running out of memory or the thread was killed with mysqladmin kill). If you have a lock obtained with GET_LOCK(), it is released when you execute RELEASE_LOCK(), execute a new GET_LOCK(), or your connection terminates (either normally or abnormally). Locks obtained with GET_LOCK() do not interact with transactions. That is, committing a transaction does not release any such locks obtained during the transaction.

This function can be used to implement application locks or to simulate record locks. Names are locked on a server-wide basis. If a name has been locked by one client, GET_LOCK() blocks any request by another client for a lock with the same name. This allows clients that agree on a given lock name to use the name to perform cooperative advisory locking. But be aware that it also allows a client that is not among the set of cooperating clients to lock a name, either inadvertently or deliberately, and thus prevent any of the cooperating clients from locking that name. One way to reduce the likelihood of this is to use lock names that are database-specific or application-specific. For example, use lock names of the form db_name.str or app_name.str.

mysql> SELECT GET_LOCK('lock1',10);
        -> 1
mysql> SELECT IS_FREE_LOCK('lock2');
        -> 1
mysql> SELECT GET_LOCK('lock2',10);
        -> 1
mysql> SELECT RELEASE_LOCK('lock2');
        -> 1
mysql> SELECT RELEASE_LOCK('lock1');
        -> NULL

The second RELEASE_LOCK() call returns NULL because the lock 'lock1' was automatically released by the second GET_LOCK() call.

If multiple clients are waiting for a lock, the order in which they will acquire it is undefined and depends on factors such as the thread library in use. In particular, applications should not assume that clients will acquire the lock in the same order that they issued the lock requests.


If a client attempts to acquire a lock that is already held by another client, it blocks according to the timeout argument. If the blocked client terminates, its thread does not die until the lock request times out. This is a known bug (fixed in MySQL 5.6).

So, after reading the above wonderful documentation, I thought of several reasons “Why would she not be able to obtain a lock using that function from PHP ? ” and I guessed the following :

  1. She may have called GET_LOCK and never called RELEASE_LOCK and tried to call GET_LOCK again with the same lock name.
  2. She may be calling GET_LOCK from a script where the connection is closed by the end of that script and then tries to check IS_FREE_LOCK from another script.
  3. Something is error in her SETUP ( Which I have no clue how to solve ).

After arguing with her over these points, she proved to me that she is doing every thing the right way. So, I created the following PHP Script to check if there is really and issue in PHP calling GET_LOCK MySQL function.


$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die                      ('Error connecting to mysql');

$dbname = 'carpooling';


function LockProjet( $idProjetRevision)
  $sql = "SELECT GET_LOCK('LockedProject_$idProjetRevision', 28800) AS 'GetLock'"; //8 hours lock
  $res = mysql_query($sql);

function IsLockedProjet( $idProjetRevision)
  $sql = "SELECT IS_FREE_LOCK('LockedProject_$idProjetRevision');"; //8 hours lock
  $res = mysql_query($sql);

function ReleaseProjet($idProjetRevision)
  $sql = "SELECT RELEASE_LOCK('LockedProject_$idProjetRevision'); "; //8 hours lock
  $res = mysql_query($sql);

function showValue($res){
  # mysql_close();
 if (!$res) {
    die('Could not query:' . mysql_error());
  while ($i < $num) {
    echo "RESULT IS : $first \n";
    echo "----------------------\n";

When I tested this function on my Laptop, this was the result:

dino@linux-vxrd:~/Documents/php> php locks.php


Which means it should be working fine. So, I asked her to use my code instead, it didn’t work either.
So, the last thing I though of is the privileges of the user she is using to connect to the database, I asked her to open MySQL Administration tool and check user privileges.

So, She checked it, but no use. So, both of us get fed up and she said she gonna do it her own way. I suggested using any ORM Framework, but she got no knowledge about it.
So, This is it.

Wish her best of luck.

All Of you too.

Simple Apache Ant Tutorial

[ This Blog Was Moved To : http://www.diknows.com ]


Ant is free and open source build tool, written in Java, helps in automating the entire build process of a Java development project.

  • Ant uses XML build files.
  • By default, Ant looks for a build file named build.xml.
  • The build file contains information about how to build a particular project.
  • Each project contains multiple targets like creating directory, compiling source codes.
  • Target can depend on other targets.
  • Targets contain tasks.
  • Behind each task is a Java class that performs the described work.


To install Ant follow the steps given below.

  • Download the latest Ant package.
  • Extract it (my location is /home/dino/installations/apache-ant-1.7.1)
  • Set the following system variables
  • ANT_HOME =/home/dino/installations/apache-ant-1.7.1
  • PATH = %ANT_HOME%/bin


  • If you have root access, you can use your preferred Linux package manager (I use Yast) to install Ant

To make sure the installation is done correctly, open a console window and execute the command “ant – version”, you will see the installed ant version.

dino@linux-vxrd:~> ant -version
Apache Ant version 1.7.1 compiled on October 20 2009


In the next example you will see how to compile a java program and compress it into a .jar file using Ant build file. The following listing shows the build.xml file.

<?xml version="1.0" ?>
<project name="Hello World" default="compress">

	<target name="compile" depends="init">
		<echo>Starting the compilation process</echo>
		<javac srcdir="src" destdir="build/classes" source="1.5" target="1.5"/>
		<echo>Compilation Completed Successfully !</echo>

	<move todir="build/classes/">
		<fileset dir="src">
			<include name="**/*.class"/>
			<exclude name="**/*.java"/>

	<target name="init">
		<mkdir dir="build/classes" />
		<mkdir dir="dist" />

	<target name="compress"  depends="compile">
		<jar destfile="dist/HelloWorld.jar" basedir="build/classes" >
				<attribute name="Created-By" value="Diaa Kasem"/>
				<attribute name="Main-Class" value="HelloWorld"/>
		<echo>Building .jar file completed successfully!</echo>

	<target name="execute" depends="compile">
		<java classname="dino.HelloWorld" classpath="build/classes" />

	<target name="clean">
		<delete dir="build" />
		<delete dir="dist" />


  • The <project> element is the root element in Ant build files. The name attribute of the project element indicates the project name. Each project element can contain multiple <target> elements.
  • A target represents a single stage in the build process. A build process can have multiple targets. Here we have several targets compile, compress, init, execute and clean.
  • The default attribute of project element indicates the default target to be executed. Here the default target is compress.
  • When you see the compress target, it in turn depends on the compile target, that is indicated by the depends attribute. So the compile target will be executed first and because compile target depends on init target, init should be executed first.
  • The compile target has two task elements <javac> and <echo>. The javac task is used to compile the java files. The attribute srcdir=”.” indicates all the java files in the current directory. Echo task is used to display message on the console.
  • The compress target also performs two tasks, first the <jar> element as the name indicates, is used to build the jar file. The attributes destfile=”dist/HelloWorld.jar” , basedir=”build/classes” and includes=”**/*.class” indicates all the .class files in all the sub-directories should be compressed into HelloWorld.jar file. Later the echo task is used to display the success message on the console.

For a easier maintenanace all the source file should be kept in the src directory, the compressed jar file should be kept in the dist directory and all the intermediate class files should be kept in the build/classes directory.

By imposing structure cleaning the project becomes easy, we can just delete the directory and recreate it.

Using the <mkdir> task we create build/classes and dist directory.

<target name="init">
    <mkdir dir="build/classes" />
    <mkdir dir="dist" />

During the compilation process all the java files in the src directory will be compiled and the generated class files will be placed in the build/classes directory.

Since we placed all the class files under the build/classes directory, creating jar file becomes easier, you can simply specify the basedir attribute as “build/classes” instead of specifying basedir=”.” and includes=”*.class”. After creating the jar file we place it in the dist directory (destfile=”dist/HelloWorld.jar”).

<target name="compile" depends="init">
    <javac srcdir="src" destdir="build/classes" />
<target name="compress" depends="compile">
        <jar destfile="dist/HelloWorld.jar" basedir="build/classes" />

You can use the java task to execute a class file as shown below. The classname attribute refers to the java class to be executed and the classpath attribute refers to the directory in which the class is located.

<target name="execute" depends="compile">
    <java classname="dino.HelloWorld" classpath="build/classes" />

Since all the class files and jar files are isolated, we can easily clean the project by deleting the respective directories.

<target name="clean">
    <delete dir="build" />
    <delete dir="dist" />

When you run the “ant execute” command the execute target will be invoked. Execute target also depends on compile target which in turn depends on init target, but now the directories won’t be created again because it already exist. Since the java file is already compiled it won’t be compiled again. Ant checks the timestamp of the file and compiles only the updated files. The HelloWorld.class file will be execute and the “HelloWorld!” message will be displayed on the console.

dino@linux-vxrd:~/Documents/anttest/helloworld> ant execute
Buildfile: build.xml


[echo] Starting the compilation process
[echo] Compilation Completed Successfully !

[java] Hello ANT Wolrd !

Total time: 1 second

The java source file I used is :

package dino;

public class HelloWorld{
public static void main(String [] args){
System.out.println("Hello ANT Wolrd !");

And this is the directory structure:

Ant Project Directory Structure

Ant Project Directory Structure

I guess this is it for now.

Hope you like it and share your opinion below.


Posted in JAVA. Tags: , , , , . 1 Comment »

Creating Basic Financial JSF CRUD Application

[ This Blog Was Moved To : http://www.diknows.com ]

Today, I’m trying to revise my JSF, Hibernate Knowledge. I’m Creating a CRUD application.

Its a simple financial web application where there are admin/viewer privileges. The application will not be fully created in this tutorial.

The main idea is that the Admin can deposit/withdraw and the application should show his financial status to subscribed viewers.

In this basic tutorial I will introduce how to Generate JSF/Hibernate CRUD application using Netbeans 6.8 as a starting point for this small project.

I will use local MySQL as my database engine. And here is the ERD :

Financial Tutorial Image


And Here is the SQL :

USE financial;

/************ Update: Tables ***************/

/******************** Add Table: profile ************************/

/* Build Table Structure */
 profileName VARCHAR(50) NOT NULL,
 profile_state FLOAT NOT NULL DEFAULT 0,
 username VARCHAR(100) NULL

/* Table Items: profile */
 PRIMARY KEY (profileId);

/******************** Add Table: record ************************/

/* Build Table Structure */
 recordName VARCHAR(50) NOT NULL,
 description TEXT NULL

/* Table Items: record */
 PRIMARY KEY (recordId);

/******************** Add Table: security ************************/

/* Build Table Structure */
 username VARCHAR(100) NOT NULL,
 password VARCHAR(20) NOT NULL,
 security_role VARCHAR(20) NOT NULL DEFAULT 'user'

/* Table Items: security */
ALTER TABLE security ADD CONSTRAINT pksecurity
 PRIMARY KEY (username);

/* Set Comments */
EXEC sp_addextendedproperty 'MS_Description', 'user or admin', 'user', 'schemaA',
 'table', 'security', 'column', 'security_role';

/************ Add Foreign Keys to Database ***************/

/************ Foreign Key: fk_profile_security ***************/
ALTER TABLE profile ADD CONSTRAINT fk_profile_security
 FOREIGN KEY (username) REFERENCES security (username);

/************ Foreign Key: fk_record_profile ***************/
ALTER TABLE record ADD CONSTRAINT fk_record_profile
 FOREIGN KEY (profileId) REFERENCES profile (profileId);

After wards, I created JSF Project in NetBeans 6.8 Like this :

Then, I created Hibernate Mappings From DB like this :

By clicking The Finish Button : The hibernate.reveng.xml gets created.

Now, we need to create the Hibernate Mapping Files XML and POJOs

And the result become like this :

So, We now need to Generate the JSF CRUD application like this :

After clicking the Finish button , the project result is the following :

And the result is the following .. after running the application:

I would like to know your opinions and your suggestions, Next I will introduce EJB , Spring Acegi and may be web services.

Hope somebody liked this tutorial.

Keep Skype Alive Script

[ This Blog Was Moved To : http://www.diknows.com ]

I started to dislike skype.

  • Skype Application is closed source.
  • They (Skype Company) force users to use Untested Beta Version.
  • Upgrades are very slow for linux.

Lately, I had an issue the last few days with skype, It crashes while I’m talking and being away from the pc.

So, I tried to make a solution to keep skype alive.

Ok, I failed,  but I made a script to start skype again when it crashes.

while :; do echo "<em>USERNAME</em> <em>PASSWORD</em>" | skype --pipelogin; sleep 60; clear; done

Skype normally does not support multi-instances  for the same username, so as long as the original skype instance is up and running no new instances of skype will get instantiated. But, when it crashes, a new skype instance will start and login automatically.

Making the privacy configurations “Auto-accept” for all incomming calls, When skype crashes, normally the call’s other end gets “Call Dropped”.

So, He/She calls again, with the auto accept; I don’t need to get beside the PC to Accept the call.

For me this was helpful, I hope it is for you too.

I welcome any suggestions to replace skype with any communication application, that is reliable and OS independent, running on mobile devices and has clear voice too.