Thursday, December 16, 2010

How to split a log file in tomcat

Source : http://jameslhf.blogspot.com/2010/03/how-to-split-log-file-in-tomcat.html

Tomcat log file splitter procedure:

1. Replace tomcat-juli inside bin\

2. Copy commons-logging-1.1.1, log4j.jar, and tomcat-juli-adapters to lib directory

3. Change log4j.p file in lib

4. Delete logging.properties in conf directory

Reading web-page made easy using JSP

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<html>
    <body>
        <c:import url="http://www.yahoo.com" var="newstuff"/>
        <c:out value="${newstuff}"/>
    </body>
</html>

It gives the content of the page into a variable called newstuff…

Friday, December 3, 2010

HttpWatch

HTTPWatch is a tool which can be used to check the HTTP traffic triggered when we access a web page. It can be used for debugging. Mostly all web applications make extensive use of the HTTP protocol (or HTTPS). HTTPWatch integrates with Internet Explorer and Firefox browsers. It also supports non-interactive examination of HTTP data wherein we can even examine log files that our customers and suppliers have recorded. It gives information regarding the URL, methods used (GET/POST), parameters passed etc.

Wednesday, November 24, 2010

How to add all jars from a folder quickly

    jars=""
    for j in `ls $libs/*.jar`
    do
        jars=$jars:$j
    done


Use the above jars varible in the classpath.

Tuesday, November 23, 2010

How to set temporary directory for MySQL?

Source : http://maisonbisson.com/blog/post/11657/mysql-error-28-temp-tables-and-running-out-of-disk-space/

Error 28 is about disk space, usually the disk space for temp tables. The first thing to do is figure out what filesystem(s) the tables are on. SHOW VARIABLES LIKE “%dir%” will return a number of results, but the ones that matter are tmpdir and datadir.
SHOW VARIABLES LIKE “%dir%”;

basedir /
character_sets_dir /usr/share/mysql/charsets/
datadir /var/lib/mysql/
innodb_data_home_dir
innodb_log_arch_dir
innodb_log_group_home_dir ./
innodb_max_dirty_pages_pct 90
slave_load_tmpdir /tmp/
tmpdir /tmp/


As it turns out, df shows plenty of space available on all the filesystems:

# df -H

Filesystem Size Used Avail Use% Mounted on
/dev/sda3 195G 11G 175G 6% /
/dev/sda1 98M 16M 78M 17% /boot
none 1.1G 0 1.1G 0% /dev/shm
/usr/tmpDSK 508M 12M 471M 3% /tmp
/tmp 508M 12M 471M 3% /var/tmp

How to set temporary directory?

# export TMPDIR = /var/tmp/Yogesh

# /etc/init.d/mysqld restart

mysql restart is a must, because temporary directory does not gets picked up dynamically, but it is picked up during startup of mysql.

Saturday, November 20, 2010

Can singleton be broken?

Singleton pattern
The most common code for creating a singleton pattern is as follows:

Code 1:
public class SingletonSample {
   private static SingletonSample instance;
   private SingletonSample(){}
   public static SingletonSample getInstance() {
         if (instance == null)                     // 1
         {instance = new SingletonSample();}       // 2
         return instance;                          // 3
   }
}
In the above design, the constructor is declared as private and the getInstance() method ensures that only a single object is created. This program will work well for single threaded program. But however, for multithreaded programs this pattern will fail inconsistently. Let’s have a look at how and where this pattern will fail.

a) Thread 1 enters the getInstance() method and determines that instance variable is null at line // 1.
b) Thread 1 enters if block but is pre-empted by thread 2 before executing line // 2.
c) Thread 2 calls getInstance() method and determines instance variable is null at line //1.
d) Thread 2 enters the IF block and creates a new object which is assigned to instance.
e) Thread 2 then returns the Object reference at line // 3.
f) Thread 2 is pre-empted by thread 1.
g) Thread 1 starts off where it left and creates another object at line // 2 and returns the reference at // 3.

Thus two Objects of the class are created when it was required to generate only one. A “synchronized” keyword is used to make multithreaded application thread safe and hence so, if we want to use the singleton pattern in multithreaded application we must synchronized the getInstance() method as follows :

Code 2:
synchronized public static SingletonSample getInstance() {
         if (instance == null)                     // 1
         {instance = new SingletonSample();}       // 2
         return instance;                          // 3
   }
The above code works fine for multithreaded access to getInstance() method but on deeper analysis we find that the ‘synchronization’ is actually required only for the first invocation as only on the first invocation will the line // 2 be actually executed, which also happens to be the line which needs to be synchronized. All other invocation apart from the first will get a not-null value and return the reference. However, it also adds up to performance issue as the complete getInstance() method is synchronized and that any other invocation will have to wait for the lock to be released to execute the getInstance().

Hence, in order improve the performance we can wrap up the line // 2 in a synchronized block instead of the complete method as follows

Code 3:
public static SingletonSample getInstance() {
         if (instance == null)                                                        // 1
         synchronized(SingletonSample.class){instance = new SingletonSample();}       // 2
         return instance;                                                             // 3
   }
However, in the above code too, we face the same problem as we had in code 1.Two threads can enter the IF block after finding instance is null. Now, Thread 1 enters the ‘synchronized’ block and creates the Object. Thread 2 also enters the synchronized block after Thread 1 releases the lock and also creates one more object. Now, in this case the Thread 2 does not check for the instance==null and directly creates a second Object.
Double-checked locking
A way to fix the problem in Code 3 is to put one more check, a second check on instance variable as follows:

Code 4:
public static SingletonSample getInstance() {
         if (instance == null)                                                        
         synchronized(SingletonSample.class){                      // 1               
             if(instance==null)                                    // 2
                instance = new SingletonSample();                  // 3
         }       
         return instance;                                          
   }
Thus by implementing the second check on instance variable makes it impossible for creation of more than one SingletonSample objects.
Since, this design uses two checks it’s called as “Double-checked locking”. Consider the following scenario.

a) Thread 1 enters the getInstance() method and the synchronized block at line as instance is null.
b) Thread 1 is pre-empted by thread 2.
c) Thread 2 enters the getInstance() and tries to acquire lock at // 1 as instance is still null but fails because Thread 1 already has a lock on the Object.
d) Thread 2 is pre-empted by Thread 1.
e) Thread 1 then executes line //2 and line // 3 to create an Object as instance is still null at line // 2.
f) Thread 1 is pre-empted by thread 2 and acquires a lock at line // 1.
g) Thread 2 does a null check at line // 2 and after finding that it is not null exits the block without creating a new Object.

Now, finally we can conclude that we are able to generate a single instance at last. But can we really do that? Let us have a look at the code 4 line 3 again. The problem with this line is that instance can become non-null even before the constructor executes completely. Let’s look at the following flow.

a) Thread 1 enters the getInstance() and the synchronized block at line // 1 as instance is null.
b) Thread 1 executes the code at line // 3. Now after the fully creating the Object but BEFORE the initializing the object.
c) Thread 1 is pre-empted by thread 2.
d) Thread 2 checks to see if instance is null. Because it is not, thread 2 returns a reference to a fully constructed but partially initialized Object.
e) Thread 2 is pre-empted by thread 1.
f) Thread 1 completes the constructor and initializes the object and returning the reference.

Solution
This problem is because of the Java memory problem and hence the solution to the above problem is to use synchronized getInstance() as in Code // 2 or static as follows :

public static Singleton getInstance()
  {
    return instance;
  } 

Friday, November 12, 2010

Reading files made easy in Java

Courtesy : http://code.hammerpig.com/how-to-read-really-large-files-in-java.html

import java.util.*;
import java.io.*;
 
public class BigFile implements Iterable<String>
{
    private BufferedReader _reader;
 
    public BigFile(String filePath) throws Exception
    {
        _reader = new BufferedReader(new FileReader(filePath));
    }
 
    public void Close()
    {
        try
        {
            _reader.close();
        }
        catch (Exception ex) {}
    }
 
    public Iterator<String> iterator()
    {
        return new FileIterator();
    }
 
    private class FileIterator implements Iterator<String>
    {
        private String _currentLine;
 
        public boolean hasNext()
        {
            try
            {
                _currentLine = _reader.readLine();
            }
            catch (Exception ex)
            {
                _currentLine = null;
                ex.printStackTrace();
            }
 
            return _currentLine != null;
        }
 
        public String next()
        {
            return _currentLine;
        }
 
        public void remove()
        {
        }
    }
}

Here is how you might use it:

BigFile file = new BigFile("C:\\Temp\\BigFile.txt");
 
for (String line : file)
    System.out.println(line);

Thursday, November 11, 2010

How to read a file in Java

Usually such kind of function is not recommended when reading huge files. Because it is not possible for java to allocate so much contigous memory.

As far a possible, avoid using this function.

public static String getFile(String filepath) 
{
        StringBuilder output = new StringBuilder("");
        try 
        {       
            File file = new File(filepath);
            FileReader fileReader = new FileReader(file);
            BufferedReader bfr = new BufferedReader(fileReader);
            String line ;
            while((line = bfr.readLine()) != null)
            {
                output.append(line + "\n");
            } 
            bfr.close();
            fileReader.close();
        }
        catch (FileNotFoundException e) 
        {
              e.printStackTrace();
        } 
        catch (IOException e) 
        {
              e.printStackTrace();
        }   
        finally
        {
            
        }
        return output.toString();
}

Wednesday, November 10, 2010

Code that creates the code to create text

Many times it was required that I need to write a code that writes a particular text.
When such a requirement was being faced repetitively, i decided to write a small snippet of code for it.

@Action
    public void createCode() {
       
        String txt = txtarea.getText();
        String[] s2=txt.split("\\n");
        StringBuilder sb = new StringBuilder("");
        sb.append("public static String createCode()\n");
        sb.append("{\n");
        sb.append("\tStringBuilder sb=new StringBuilder(\"\");\n");
        for(String s:s2)
        {
            sb.append("\tsb.append(\"");
            sb.append(s);
            sb.append("\\n\");\n");
        }
        sb.append("\treturn sb.toString();");
        sb.append("\n}");
        code.setText(sb.toString());
    }

I have a complete application for it as well. But I do not have web-space where I can host it.
And attachments are not allowed in blog. :(

Thursday, October 28, 2010

How to put limitation of time on a method call

Lets say, you are reading a website, and you want that, if you get a response within 3 seconds then its ok..
otherwise, you want to give a message to user that internet is tooo slow...how will you do it...

I always wondered it...today found a solution...Not tooo complex, its just that, i was not able to develop this logic using my own knowledge of java. :)

This is just an example:
Declare a private Thread mainThread;

final int factorialOf = 1 + (int) (30000 * Math.random());
System.out.println("computing " + factorialOf + '!');

Thread testThread = new Thread() {

    public void run() {
        System.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf));
        //Now run method has completed its execution
        // so it should interrupt the main Thread
        mainThread.interrupt();
    }
};
mainThread=Thread.currentThread();
testThread.start();
try
{
    Thread.sleep(1000);
}
catch(InterruptedException e)
{
    // If we reach here, that means sleep was interrrupted before 1000 ms.
}
testThread.interrupt();

if (testThread.isInterrupted()) {
    throw new TimeoutException("the test took too long to complete");
}

PS: Though this should work, but some time is being taken by the statements which create new thread.


Some other/better methods are also given here : http://javakafunda.blogspot.in/2012/05/how-to-put-time-restriction-on-method.html

Sunday, October 24, 2010

Add zooming effect to images on your website

You must have wondered, how to add zooming effect to an image.
Its pretty simple to do....

A simple attribute of <img> has the capbility of doing it

<img src="http://www.celebrity-pictures.ca/Celebrities/Katrina-Kaif/Katrina-Kaif-i105058.jpg" 

onmousedown="this.height=450;this.width=600" 

onmouseup="this.height=150;this.width=200" width=200 height=150>

Output :





Here are few of the event handlers :

Attribute Description
onabort Script to be run when loading of an image is interrupted
onclick Script to be run on a mouse click
ondblclick Script to be run on a mouse double-click
onmousedown Script to be run when mouse button is pressed
onmousemove Script to be run when mouse pointer moves
onmouseout Script to be run when mouse pointer moves out of an element
onmouseover Script to be run when mouse pointer moves over an
element
onmouseup Script to be run when mouse button is released
onkeydown Script to be run when a key is pressed
onkeypress Script to be run when a key is pressed and released
onkeyup Script to be run when a key is released

If you want a effect that gradually grows the image, you can refer to the link : http://javascript.internet.com/image-effects/growing-image.html

Wednesday, October 13, 2010

Rules about classpath

Source : http://mindprod.com/jgloss/classpath.html

Rules About Classpaths

  1. Simply copying or moving your jar files to the ext directory pointed to by the system property java.ext.dirs =C:\Program Files\java\jre6\lib\ext automatically puts them on the classpath without having to mention them explicitly. This is a great way to prune back an overblown classpath. It is safest to put your jars in all the ext directories:
    where to look for ext directories :
    You never know for sure where your javac.exe or java.exe is going to look. Grrr. You can change the location of the
    java.exe -Djava.ext.dirs=C:\mylibs mypackage.MyClass
    See the ext dirs entry for details.

Classpath Gotchas

Source :  http://mindprod.com/jgloss/classpath.html


  • If you use the -jar option, java.exe ignores the classpath. It will only look in that jar!! Try using the manifest Class-Path instead to get Java to look in auxiliary jars.
  • The elements of the classpath are platform specific OS directory names (with \ or / separators) or jar file names. The package/classnames on the command line are not; they are fully-qualified dotted names. Don’t try to concoct a chimera class name such as C:/com.mindprod.mypackage.MyClass
  • If you want a jar on the classpath, you must put the jar file name on the classpath, not just the name of the directory where the jar lives. This means you need whacking long classpaths, with every jar in a common directory each added to the classpath individually. Perhaps one day Sun will implement a JARPATH. In would not be hard to build a wrapper around javac.exe and Java.exe that faked in a JARPATH. In the meantime you

    rem how to fake jarpath
    rem separate jarnames with File.pathSeparatorChar, i.e. ; in Windows : in Unix
    java.exe -Djava.ext.dirs=usualextdir;anotherdir ...
    To add to the usual extdir. In Java version 1.6 you can use a wildcard to include all jars in a directory.
    rem use of wildcard in classpath to add all jars in C:\jardir and E:\morejars
    java.exe -classpath C:\jardir\*;E:\morejars\*
  • Beware of inserting extra semicolons (in general, FilepathSeparatorChar chars) in your CLASSPATH. Everything to the right will be ignored!, leading you to pull out your remaining hair in frustration wondering why java.exe can’t find the classes. You must have exactly one semicolon between elements, no lead/trail/extras.
  • Beware. Putting D: on the classpath is not the same thing as putting D:\. The first put the current directory of D: on the classpath. The second puts the root directory. They are often the same, but not always

Friday, October 8, 2010

Clustering J2EE Applications

All mission critical applications need to be have high Availability and Scalability features built-in. Any incident or outage in such applications can have huge implications – like business loss or legal issues faced by the company. Clustering helps in application scalability (through load balancing) as well as high availability (through failover).


Clustering J2EE Applications
Never assume that stand-alone applications can be transmit transparently to a cluster structure.
Most of the leading application server vendors like IBM (Websphere) and Oracle (BEA Weblogic) support clustering their servers and provide for built-in load balancing among them.



Tuesday, October 5, 2010

Generate QJML from Java Bean class...

Quick tool by IBM is a very useful tool for creating parsing logic for conversion from XML to java.

Have a look at the following link...

http://www.ibm.com/developerworks/library/x-quick/index.html

But this converts from DTD -> QJML -> Java.

I have eliminiated the need for creating DTD.
You can create QJML directly from java Bean class if you have.
Just provide the java class and it will generate 90% code for QJML.
You can use it with minor tweeking...


Thursday, September 30, 2010

Pitfalls in replaceAll function of String class

Lets have a look at the replaceAll function.

String s = "Yogesh C:\\test3.xml vaibhav";
s = s.replaceAll("C:\\test3.xml", "test");
System.out.println(s);


You might be expecting that it would replace the string c:\\test3.xml, but it doesn't happens.
Reason :
The regex parser has backslash (\) and dollar ($) as keywords, so it treats it differently.
If your string contains these characters, you can use Matcher.quoteReplacement to skip these characters.

Solution:

String s = "Yogesh C:\\test3.xml vaibhav";
s = s.replaceAll(Matcher.quoteReplacement("C:\\test3.xml"), "test");
System.out.println(s);

Sunday, September 26, 2010

JAVASSIST (Java programming Assistant)

JAVASSIST (Java programming Assistant) is a utility that allows one to inspect, edit and create Java binary classes. It enables Java programs to define a new class at runtime and to modify a given class file when the JVM loads it. Its best feature is its ease of use since it allows developers to fully exploit byte code manipulation with little or no knowledge of byte code, giving them a degree of fine-grained control.

Javassist provides two levels of API: Source level and Byte code level. If the users use source level API, they can edit a class file without knowledge of the specifications of the Java byte code. The whole API is designed with only the vocabulary of the Java language. You can even specify inserted byte code in the form of source text; Javassist compiles it on the fly. On the other hand, the byte code level API allows the users to directly edit a class file as other editors.

Javassist uses the javassist.ClassPool class to track and control the classes being manipulated. Classes loaded in a class pool are represented by javassist.CtClass instances where as fields, methods and constructors are represented by javassist.CtField, javassist.CtMethod and javassist.CtConstructor instances, respectively.

An Example of Javassist

The below example depicts the usage of few of the Javassist basic APIs. All that is required is to just download ‘javassist.jar’ and add the same to the class path.

Wednesday, September 22, 2010

Reflections

Some imports that you may require

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


A generic method which can print any bean class, provided all the getter methods are there.


public static void printObject(Object app) throws
IllegalArgumentException, IllegalAccessException, 
InvocationTargetException
{
    Method[] m = app.getClass().getMethods();
    for(Method method : m)
    {
        if(method.getName().startsWith("get"))
        {
            // if getClass then ignore this method.
            if(method.getName().equals("getClass"))
                continue;
            if(method.getReturnType().isArray())
            {
                System.out.print(method.getName() + "=[ ");
                Object[] values = (Object[])method.invoke(app, null);

                for(Object v : values)
                {
                    System.out.print(v + ", " );
                }
                System.out.print(" ]\n");
            }          
            else
                System.out.println(method.getName() + " = " + method.invoke(app, null));
        }
    }  
}



If you would like to learn more about Reflections, you can visit this link: http://java.sun.com/developer/technicalArticles/ALT/Reflection/

Wednesday, September 8, 2010

Premature end of file when running junits

Problem:

Premature end of file error when running Junits

[junitreport] [Fatal Error] :-1:-1: Premature end of file.
[junitreport] The file /tmp/repository/Yogesh/task2652_story1984/modulesmgr/junit_report/out/xml/TEST-com.coresecurity.ctrlsvc.modules.ModulesImportAndBasicCRUDTest.xml is not a valid XML document. It is possibly corrupted.



Observations:
1) TESTS-testsuites.xml was coming out to be empty.
2) The resulting xml file was getting too large in size.


Solution:
Hibernate logging was enabled which was leading to large size of XML.
We disabled logging in config.xml as given below
Earlier it was true, we made it false




<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<qualifier value ="DataSource" />
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.coresecurity.datamanager"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.transaction">true</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">20</prop>
<prop key="hibernate.c3p0.timeout">300</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
<prop key="hibernate.c3p0.idle_test_period">3000</prop>
</props>
</property>
</bean>

Thursday, August 12, 2010

Opening IE in existing window problem

Visit this URL

http://support.microsoft.com/?kbid=241911

This tells how to fix, if IE opens in existing window.

Friday, June 25, 2010

Sendkeys

A VB Script to run outlook and send some specified keys to it.

To send Ctrl+n, use "^{n}" as given below, for Alt use %

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "Outlook"
WScript.Sleep 2500 ' Give Notepad some time to load
WshShell.SendKeys "^{n}"
WScript.Sleep 1000
WshShell.SendKeys "Yogesh_Gandhi@infosys.com"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys " Hi Yogesh, I accept that I am a FOOL ...and you made a fool out of me today ... I don’t think God planted brains in my head!!!!...otherwise I would have checked out the code first! you are great. hats off for you. With Regards"
WshShell.SendKeys "%{s}"

Thursday, June 24, 2010

Quick batch file to check OS version…

How to check the Operation System version
if OS is 32 bit or 64 bit

Quick batch file to check OS version…




@echo off

Set RegQry=HKLM\Hardware\Description\System\CentralProcessor\0

REG.exe Query %RegQry% > checkOS.txt

Find /i "x86" < CheckOS.txt > StringCheck.txt

If %ERRORLEVEL% == 0 (

Echo "This is 32 Bit Operating system"

) ELSE (

Echo "This is 64 Bit Operating System"

)

pause

Saturday, May 22, 2010

use OnClick with caution

JSP Code :

<a href="abc.jsp" onclick='<% session.invalidate(); %>'>LOGOUT</a>


The above statement gets converted to Servlet CODE :
out.write("<a href=\"abc.jsp\" onclick='");
session.invalidate();
out.write("'>LOGOUT</a>");


Conclusion:

What ever scriplet you write in onclick, will get executed every time the JSP is called. Not only on onclick as can be wrongly assumed.

Thursday, May 20, 2010

BUG in struts2

Actually I used

Now, I have specified type as button, so I expected that it will not go to action on click on the button.

But what happens is

when I click on button, it asks if I want to close the window,
Now, even I click NO, it still goes to action specified in form.

Solution : This is a BUG in struts2.

the HTML tag that is generated is something like:

<button type="submit" id="test_0" value="Submit" class="button positive save">Submit</button>

Please note that we have given type=button in s:submit tag, and the HTML generated still contains type=submit.

Can get some information from http://www.ericmmartin.com/struts-2-bug-submit-button-tag-rendering/

Sunday, May 16, 2010

Internationalization tips for JSP

In order to display the complex script characters like Japanese, Chinese, etc in the browser window, the following changes need to be made at the beginning of each JSP file:

<%@ page language="java" 
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


Wherever input controls are present, the following additional steps need to be taken:
Add the following code before reading any parameters in the previous JSP file:

request.setCharacterEncoding("UTF-8"); // Set the request encoding



While sending output to a browser:

response.setContentType ("charset=UTF-8");

Saturday, April 24, 2010

OpenDatabase function gives error

Problem:
OpenDatabase function which is a standard function in VB
gives the following error







Solution:
Modify the code to

Set db = DBEngine.OpenDatabase(cd1.FileName)

VB with Access 2000

Problem :
How to make VB 6.0 work with Access 2000



Solution :
Select Microsoft DAO 3.6 Object Library in Project References

Friday, April 23, 2010

Color of Error Messages in struts 2

Problem:

I am working on struts 2.
I have one text field and have put validation (with xml)on the text field if its blank, throw an error.
But the field error I am getting is in black colour.
Does anyone have idea how to display the field error in red colour.


Solution:

U can the use the following tag in your .css Stylesheet file

.errorMessage {
color: red;
font-size: 0.8em;
}

And include this Stylesheet in the file where u have the text field.


Source : http://www.roseindia.net/struts/struts2/validations/Struts2-annotations.shtml

Thursday, April 15, 2010

How to put two S:submit button in one line, but its not working

How to put two S:submit button in one line??

Solution :

There is attribute theme in button.you have to put it as theme=”simple” and put the two button in one tr (that means one row).

Tuesday, April 6, 2010

File count VBS

I created this VB Script file to count the number of files in a folder (recursively)
for example you need to count how many C, how many .h, how many .pl etc etc...
and you need a report folder wise also..

'******************************************************************************
'---------------------------------------------------------------------------------------
'
' Name:  FileCount.vbs
' Version: 1.0
' Date:  7-7-2009
' Author:  Yogesh Gandhi
' Description: FileCount.vbs calculates the Code files (.cc, .h, .c) files in subfolders within
'   a folder and puts the folder wise summary excel workbook
' 
' This can be used on our 9.1.0 spectrum folder, to check how many files are there
'   in which folder
'   This utility requires Microsoft Excel to be present on that machine.
'   If Microsoft Excel is not installed on that machine, you can get a tab seperated summary
'   Just uncomment/comment the relevant/irrelevant code 
' It will generate a filelist.txt file in the specified folder.
'---------------------------------------------------------------------------------------
FolderToBeAnalysed = BrowseFolder( "", False )
Call CountCCAndh(FolderToBeAnalysed, false)
'**********************************************************************
Sub CountCCAndh(sFolder, bIncludeDirInCount)
Dim objFolder, objSubFolders, objFso, o, n 
Set objFso = Createobject( "Scripting.FileSystemObject" )  
Set objDialog = CreateObject( "SAFRCFileDlg.FileSave" )

'Get the file name and path from the user.
dim xlfilename
' Note: If no path is specified, the "current" directory will
'       be the one remembered from the last "SAFRCFileDlg.FileOpen"
'       or "SAFRCFileDlg.FileSave" dialog!
objDialog.FileName = "test.xls"
' Note: The FileType property is cosmetic only, it doesn't
'       automatically append the right file extension!
'       So make sure you type the extension yourself!
objDialog.FileType = "Excel file(*.xls)"
If objDialog.OpenFileSaveDlg Then
xlfilename = objDialog.FileName
End If

set objXL = CreateObject( "Excel.Application" )
objXL.Visible = False
objXL.WorkBooks.Add
dim pcount
dim objNewFile
'Set objNewFile = objFso.CreateTextFile(sFolder & "\filelist.txt", True)  
Set objFolder = objFso.GetFolder(sFolder) 
ObjXL.ActiveSheet.Cells(1,1).Value = "Folder name"
ObjXL.ActiveSheet.Cells(1,2).Value = "C/CC/h files"
ObjXL.ActiveSheet.Cells(1,3).Value = "java files"
ObjXL.ActiveSheet.Cells(1,4).Value = "JSP files"
ObjXL.ActiveSheet.Cells(1,5).Value = "JS files"
ObjXL.ActiveSheet.Cells(1,6).Value = "XML files"
ObjXL.ActiveSheet.Cells(1,7).Value = "WSDL files"
ObjXL.ActiveSheet.Cells(1,8).Value = "PL files"
ObjXL.ActiveSheet.Cells(1,9).Value = "BAT files"
ObjXL.ActiveSheet.Cells(1,10).Value = "SH files"
ObjXL.ActiveSheet.Cells(1,11).Value = "RPT files"
ObjXL.ActiveSheet.Cells(1,12).Value = "CUS files"
ObjXL.ActiveSheet.Cells(1,13).Value = "CFG files"

pcount = 2
For Each o In objFolder.SubFolders 
' objNewFile.Write(o.Name)
' objNewFile.Write(vbTab)
' objNewFile.WriteLine(cntFiles(o, false))
ObjXL.ActiveSheet.Cells(pcount,1).Value = o.Name
ObjXL.ActiveSheet.Cells(pcount,2).Value = cntCFiles(o, false)
ObjXL.ActiveSheet.Cells(pcount,3).Value = cntFiles(o, false, ".java")
ObjXL.ActiveSheet.Cells(pcount,4).Value = cntFiles(o, false, ".jsp")
ObjXL.ActiveSheet.Cells(pcount,5).Value = cntFiles(o, false, ".js")
ObjXL.ActiveSheet.Cells(pcount,6).Value = cntFiles(o, false, ".xml")
ObjXL.ActiveSheet.Cells(pcount,7).Value = cntFiles(o, false, ".wsdl")
ObjXL.ActiveSheet.Cells(pcount,8).Value = cntFiles(o, false, ".pl")
ObjXL.ActiveSheet.Cells(pcount,9).Value = cntFiles(o, false, ".bat")
ObjXL.ActiveSheet.Cells(pcount,10).Value = cntFiles(o, false, ".sh")
ObjXL.ActiveSheet.Cells(pcount,11).Value = cntFiles(o, false, ".rpt")
ObjXL.ActiveSheet.Cells(pcount,12).Value = cntFiles(o, false, ".cus")
ObjXL.ActiveSheet.Cells(pcount,13).Value = cntFiles(o, false, ".cfg")

pcount = pcount + 1
Next 

'Finally close the workbook
ObjXL.ActiveWorkbook.SaveAs(xlfilename)
ObjXL.Application.Quit
Set ObjXL = Nothing 
msgbox xlfilename & " Saved"
End Sub
'***********************************************************************************
Function cntFiles( strFolder, bIncludeDirInCount, ext ) 
Dim objFolder, objSubFolders, objFso, o, n
On Error Resume Next
cntFiles = -1
Set objFso = Createobject( "Scripting.FileSystemObject" ) 
Set objFolder = objFso.GetFolder(strFolder) 
If( Err.Number <> 0 ) Then 
Exit Function 
End If 
'n = objFolder.files.count 
for each fl in ObjFolder.files
if Right(fl.name, len(ext))=ext then
n = n + 1
end if
next
Set objSubFolders = objFolder.SubFolders 
For Each o In objSubFolders 
n = n + cntFiles( o, bIncludeDirInCount, ext ) 
If( bIncludeDirInCount ) Then 
n = n + 1 
End If 
Next
Set objSubFolders = Nothing 
Set objFolder = Nothing
cntFiles = n 
End Function
'*************************************************************************************************
Function cntCFiles( strFolder, bIncludeDirInCount ) 
Dim objFolder, objSubFolders, objFso, o, n
On Error Resume Next
cntCFiles = -1
Set objFso = Createobject( "Scripting.FileSystemObject" ) 
Set objFolder = objFso.GetFolder(strFolder) 
If( Err.Number <> 0 ) Then 
Exit Function 
End If 
'n = objFolder.files.count 
for each fl in ObjFolder.files
if Right(fl.name, 3)=".cc" or Right(fl.name,2) = ".h" or Right(fl.name, 2) = ".c" then
n = n + 1
end if
next
Set objSubFolders = objFolder.SubFolders 
For Each o In objSubFolders 
n = n + cntCFiles( o, bIncludeDirInCount ) 
If( bIncludeDirInCount ) Then 
n = n + 1 
End If 
Next
Set objSubFolders = Nothing 
Set objFolder = Nothing
cntCFiles = n 
End Function
'**********************************************************************************************************
Function cntJavaFiles( strFolder, bIncludeDirInCount ) 
Dim objFolder, objSubFolders, objFso, o, n
On Error Resume Next
cntJavaFiles = -1
Set objFso = Createobject( "Scripting.FileSystemObject" ) 
Set objFolder = objFso.GetFolder(strFolder) 
If( Err.Number <> 0 ) Then 
Exit Function 
End If 
'n = objFolder.files.count 
for each fl in ObjFolder.files
if Right(fl.name, 5)=".java" then
n = n + 1
end if
next
Set objSubFolders = objFolder.SubFolders 
For Each o In objSubFolders 
n = n + cntJavaFiles( o, bIncludeDirInCount ) 
If( bIncludeDirInCount ) Then 
n = n + 1 
End If 
Next
Set objSubFolders = Nothing 
Set objFolder = Nothing
cntJavaFiles = n 
End Function
'***********************************************************************************************
Function BrowseFolder( myStartLocation, blnSimpleDialog )
' This function generates a Browse Folder dialog
' and returns the selected folder as a string.
'
' Arguments:
' myStartLocation   [string]  start folder for dialog, or "My Computer", or
'                             empty string to open in "Desktop\My Documents"
' blnSimpleDialog   [boolean] if False, an additional text field will be
'                             displayed where the folder can be selected
'                             by typing the fully qualified path
'
' Returns:          [string]  the fully qualified path to the selected folder
'
' Based on the Hey Scripting Guys article
' "How Can I Show Users a Dialog Box That Only Lets Them Select Folders?"
' http://www.microsoft.com/technet/scriptcenter/resources/qanda/jun05/hey0617.mspx
'
' Function written by Rob van der Woude
' http://www.robvanderwoude.com
Const MY_COMPUTER   = &H11&
Const WINDOW_HANDLE = 0 ' Must ALWAYS be 0
Dim numOptions, objFolder, objFolderItem
Dim objPath, objShell, strPath, strPrompt
' Set the options for the dialog window
strPrompt = "Select a folder:"
If blnSimpleDialog = True Then
numOptions = 0      ' Simple dialog
Else
numOptions = &H10&  ' Additional text field to type folder path
End If

' Create a Windows Shell object
Set objShell = CreateObject( "Shell.Application" )
' If specified, convert "My Computer" to a valid
' path for the Windows Shell's BrowseFolder method
If UCase( myStartLocation ) = "MY COMPUTER" Then
Set objFolder = objShell.Namespace( MY_COMPUTER )
Set objFolderItem = objFolder.Self
strPath = objFolderItem.Path
Else
strPath = myStartLocation
End If
Set objFolder = objShell.BrowseForFolder( WINDOW_HANDLE, strPrompt, _
numOptions, strPath )
' Quit if no folder was selected
If objFolder Is Nothing Then
BrowseFolder = ""
Exit Function
End If
' Retrieve the path of the selected folder
Set objFolderItem = objFolder.Self
objPath = objFolderItem.Path
' Return the path of the selected folder
BrowseFolder = objPath
End Function 

Friday, April 2, 2010

Get the size of subfolders in a folder

'--------------------------------------------------------------------------------
'
' Name:  getfoldersize.vbs
' Version: 1.0
' Date:  7-5-2002
' Author:  Hans van der Zaag
' Description: getfoldersize.vbs calculates the size of all subfolders within
'   a folder and sorts this data in an excel workbook
' 
'----------------------------------------------------------------------------------
'rootfolder = Inputbox("Enter directory/foldername: " & _
'                         chr(10) & chr(10) & "(i.e. C:\Program Files or " & _
'                        "\\Servername\C$\Program Files)" & chr(10) & chr(10), _
'                       "Getfoldersize", "C:\Program Files")
outputfile = "d:\foldersize_" & Day(now) & Month(now) & Year(now) & ".xls"

'Parse the passed parameters.
const FIRST_ITEM=0
dim LAST_ITEM
dim args_index
dim command_line_args
set command_line_args = wscript.Arguments
'Check if any Arguments have been passed to our script.
'rootfolder=command_line_args(FIRST_ITEM)
rootfolder = BrowseFolder( "", False )
Set fso = CreateObject("scripting.filesystemobject")
if fso.fileexists(outputfile) then fso.deletefile(outputfile)
'Create Excel workbook
set objXL = CreateObject( "Excel.Application" )
objXL.Visible = False
objXL.WorkBooks.Add
'Counter 1 for writing in cell A1 within the excel workbook
icount = 1
'Run checkfolder
CheckFolder (FSO.getfolder(rootfolder))
Sub CheckFolder(objCurrentFolder)
For Each objFolder In objCurrentFolder.SubFolders
FolderSize = objFolder.Size
Tmp = (FormatNumber(FolderSize, 0, , , 0)/1024)/1024
ObjXL.ActiveSheet.Cells(icount,1).Value = objFolder.Path
ObjXL.ActiveSheet.Cells(icount,2).Value = Tmp
'Wscript.Echo Tmp & " " & objFolder.Path
'raise counter with 1 for a new row in excel 
icount = icount + 1
Next
'Recurse through all of the folders
'       For Each objNewFolder In objCurrentFolder.subFolders
'               CheckFolder objNewFolder
'       Next

End Sub
if icount=1 then 
MsgBox "No Subfolders are present in this folder", vbInformation, "No subfolders"
WScript.Quit
end if
'sort data in excel
objXL.ActiveCell.CurrentRegion.Select
objXL.Selection.Sort objXL.Worksheets(1).Range("B1"), _
2, _
, _
, _
, _
, _
, _
0, _
1, _
False, _
1
'Lay out for Excel workbook 
objXL.Range("A1").Select
objXL.Selection.EntireRow.Insert
objXL.Selection.EntireRow.Insert
objXL.Selection.EntireRow.Insert
objXL.Selection.EntireRow.Insert
objXL.Selection.EntireRow.Insert
objXL.Columns(1).ColumnWidth = 60
objXL.Columns(2).ColumnWidth = 15
objXL.Columns(2).NumberFormat = "#,##0.0"
objXL.Range("B1:B1").NumberFormat = "d-m-yyyy"
objXL.Range("A1:B5").Select
objXL.Selection.Font.Bold = True
objXL.Range("A1:B3").Select
objXL.Selection.Font.ColorIndex = 5
objXL.Range("A1:A1").Select
objXL.Selection.Font.Italic = True
objXL.Selection.Font.Size = 16
ObjXL.ActiveSheet.Cells(1,1).Value = "Survey FolderSize " 
ObjXL.ActiveSheet.Cells(1,2).Value = Day(now) & "-" & Month(now) & "-"& Year(now)
ObjXL.ActiveSheet.Cells(3,1).Value = UCase(rootfolder)
ObjXL.ActiveSheet.Cells(5,1).Value = "Folder"
ObjXL.ActiveSheet.Cells(5,2).Value = "Total (MB)"

'Finally close the workbook
ObjXL.ActiveWorkbook.SaveAs(outputfile)
ObjXL.Application.Quit
Set ObjXL = Nothing
'Message when finished
Set WshShell = CreateObject("WScript.Shell")
Finished = Msgbox ("Script executed successfully, results can be found in " & Chr(10) _
& outputfile & "." & Chr(10) & Chr(10) _
& "Do you want to view the results now?", 65, "Script executed successfully!")
if Finished = 1 then WshShell.Run "excel " & outputfile
'**************************************************************************
Function BrowseFolder( myStartLocation, blnSimpleDialog )
' This function generates a Browse Folder dialog
' and returns the selected folder as a string.
'
' Arguments:
' myStartLocation   [string]  start folder for dialog, or "My Computer", or
'                             empty string to open in "Desktop\My Documents"
' blnSimpleDialog   [boolean] if False, an additional text field will be
'                             displayed where the folder can be selected
'                             by typing the fully qualified path
'
' Returns:          [string]  the fully qualified path to the selected folder
'
' Based on the Hey Scripting Guys article
' "How Can I Show Users a Dialog Box That Only Lets Them Select Folders?"
' http://www.microsoft.com/technet/scriptcenter/resources/qanda/jun05/hey0617.mspx
'
' Function written by Rob van der Woude
' http://www.robvanderwoude.com
Const MY_COMPUTER   = &H11&
Const WINDOW_HANDLE = 0 ' Must ALWAYS be 0
Dim numOptions, objFolder, objFolderItem
Dim objPath, objShell, strPath, strPrompt
' Set the options for the dialog window
strPrompt = "Select a folder:"
If blnSimpleDialog = True Then
numOptions = 0      ' Simple dialog
Else
numOptions = &H10&  ' Additional text field to type folder path
End If

' Create a Windows Shell object
Set objShell = CreateObject( "Shell.Application" )
' If specified, convert "My Computer" to a valid
' path for the Windows Shell's BrowseFolder method
If UCase( myStartLocation ) = "MY COMPUTER" Then
Set objFolder = objShell.Namespace( MY_COMPUTER )
Set objFolderItem = objFolder.Self
strPath = objFolderItem.Path
Else
strPath = myStartLocation
End If
Set objFolder = objShell.BrowseForFolder( WINDOW_HANDLE, strPrompt, _
numOptions, strPath )
' Quit if no folder was selected
If objFolder Is Nothing Then
BrowseFolder = ""
Exit Function
End If
' Retrieve the path of the selected folder
Set objFolderItem = objFolder.Self
objPath = objFolderItem.Path
' Return the path of the selected folder
BrowseFolder = objPath
End Function

How to send e-mails using Java

How to send e-mails using java

Just visit the link

http://java.sun.com/products/javamail/


Java Beans Activation Framework is available at

http://java.sun.com/beans/glasgow/jaf.html

If your SMTP Server need you to do Authentication using Username and Password before Sending out mail, download the complete code from here SendMailUsingAuthentication.java

Also visit the following URL
http://www.javacommerce.com/displaypage.jsp?name=javamail.sql&id=18274

I feel all this information is sufficient for sending mails

Wednesday, March 31, 2010

Internet sharing without hub/router.....

THOUGH I HAVE NOT TRIED IT BY MYSELF. GOT THIS INFORMATION FROM A FRIEND....CHECK THIS OUT....


To share Internet Connection between different systems connected in an ad-Hoc wireless network without any router/hub….
Follow these steps…
Prerequisite:
All the systems to be connected has to be in an ad-hoc wireless network (to create one u can run create home wireless network wizard and follow ….)

For Host computer…
1. Host computer : computer i.e connected to the internet directly through modem…(or so…)
Generally configured through Lan (has its ip/dns server settings provided by Service providers….)(leave it as such)
2. Run ( create a small home/office network wizard ) in network connections panel…..(find it in control panel)
3. Follow the steps in it…
4. In internet connection setting step
Check->( tick it)this computer connects directly to the internet(for Host PC)
5. Make sure u all have same home network like (MSHOME or whatever ur pC’s home name is…)
6. Next step (Important )Wizard asks u to create a disk where setting will be stored……
so save the settings in a pen-Drive and finish the wizard .
Now settings is nothing but a netsetup.exe file saved in Pen-D….
What to do next….
Now the host part is done….
For Shared Systems…

1.Insert the drive having settings file….
2.run it…(don’t think too much…)
Just check In internet connection setting step
Check->( tick it)
(For shared PC’s in n/w) this computer connects to the internet using other computer
And have home network as MSHOME or whatever value u gave in….step
3.
And u r done …….
--------------------------------------
All the systems will now have access to internet …… (nJoy!)

Tuesday, March 16, 2010

Problem making DSN with SQL server from other machine.

I faced this problem when I was trying to connect to SQL server 2005 from another machine.

The error message said, that SQL server does not exist or access denied.

Solution :

1. Start SQL Server Configuration Manager
2. Expand SQL Server network configuration
3. Select Protocols for MSSQLSERVER
4. Double click TCP/IP in the right pane.
5. Change enabled to true
6. Click IP Addresses Tab and change the IP address to the IP address of the client.

Start SQL Server Area Configuration
Select Surface area configuration for services and connections.
Go to Database Engine -> Remote Connections and verify that remote connections are enabled. (The correct radio button is selected)

Monday, March 15, 2010

Can wait be resume without Notify??

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:
synchronized (obj) {

while (someCondition()==false)

obj.wait(timeout);

... // Perform action appropriate to condition

}

Saturday, February 27, 2010

Reading data from Internet

This URL seems to be pretty useful for this purpose.

http://java.sys-con.com/node/39248

Always use BufferedReader while reading InputStreams. Not using BufferedReader would lead to corrupt data and may not give correct results.

Code snippet is as given below :


HttpURLConnection hpCon;
hp = new URL(url);
hpCon = (HttpURLConnection)hp.openConnection();
InputStream in = hpCon.getInputStream();
InputStreamReader inStream = new InputStreamReader(in);
BufferedReader input = new BufferedReader(inStream);

String tempString="";
while(true)
{

tempString = input.readLine();
if(tempString == null) break;
output.append(tempString);
}
hp = null;
hpCon = null;

Tuesday, February 9, 2010

Not all named parameters have been set

Problem : I am getting one exception while trying to execute a query using hibernate

org.hibernate.QueryException: Not all named parameters have been set: [] [from FunctionPointDO f where f.workPackage='work package : id1' and f.workPackageIdentifier='work : ref1' and f.startDate='03-Jan-2010' and f.goLiveDate='04-Feb-2010' and f.id!='1000100']
at org.hibernate.impl.AbstractQueryImpl.verifyParameters(AbstractQueryImpl.java:114)
at org.hibernate.impl.AbstractQueryImpl.verifyParameters(AbstractQueryImpl.java:101)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:70)
at com.bt.fp.server.Utils.Utils.listAndCast(Unknown Source)
at com.bt.fp.server.database.dao.FunctionPointDAO.isDuplicate(Unknown Source)
at com.bt.fp.server.AddUpdateFPData.doPost(Unknown Source)

It seems that this error is due to the “:” which is used as a value in f.workPackage='work package : id1' and f.workPackageIdentifier='work : ref1'. I checked on net and hibernate considers anything starting with colon (: ) as a variable, and here id1 and ref1 are treated as variable whose value is not set anywhere. This error comes only when colon has spaces around it.

How can I escape colon. As these values are entered by users, I don’t have any control over whatever input they provide.

Thursday, January 28, 2010

How to connect Hibernate with Microsoft Access


1. Go to Control Panel
2. Go to Administrative Tools
3. Go to ODBC Data sources
4. Create a DSN (say mydb), give the path to .mdb file.
5. Get hibernate.jar

6. Extract contents of access.zip and get Access_JDBC30.jar

7. Create a new Java Project in NetBeans 6.7 or greater. and give the above 2 jars in classpath of the project





8. Create the employee class inside demo package with the following contents

package demo;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;

/**
*
* @author Yogi
*/
@Entity
public class Employee implements Serializable {
    @Id
    int empId;
    String empIbu;
    String empName;
    int empSalary;


    public Employee() {
    }
    public String toString()
    {
        return empName;
    }
    public Employee(int empId, String empIbu, String empName, int empSalary) {
        this.empId = empId;
        this.empSalary = empSalary;
        this.empName = empName;
        this.empIbu = empIbu;
    }

    public String getEmpIbu() {
        return empIbu;
    }

    public void setEmpIbu(String empIbu) {
        this.empIbu = empIbu;
    }

    public int getEmpId() {
        return empId;
    }

    public void setEmpId(int empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public int getEmpSalary() {
       return empSalary;
    }

    public void setEmpSalary(int empSalary) {
        this.empSalary = empSalary;
    }

}

9. Create hibernate.cfg.xml in the root directory of the application (outside all packages)

<?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.connection.driver_class">com.hxtt.sql.access.AccessDriver</property>
<property name="hibernate.connection.url">jdbc:odbc:mydb</property>
<property name="hibernate.dialect">com.hxtt.support.hibernate.HxttAccessDialect</property>
<!-- Please note, here the value update is not working with MS-Access
Although it should work theoretically, but practically, the value 
update is able to create the table for the first time 
and after that it fails every time -->
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>
<mapping class="demo.Employee"/>
</session-factory>
</hibernate-configuration>

10. Create EmployeeClient.java file inside client package (Though not mandatory)

/**
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package client;

import demo.Employee;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;

/**
*
* @author Yogi
*/
public class EmployeeClient {
    public static void main(String args[])
    {
        /* Here we have used AnnotationConfiguration because, we have used Annotations in         
         * Employee class to map the class fields with the table fields.
         * If Employee.hbm.xml is used for this mapping then here we would have used  
         * Configuration (which we normally do) 
         */

        SessionFactory factory=new AnnotationConfiguration().configure().buildSessionFactory();
        Session session = factory.openSession();
        Transaction tx=null;
        try
        {

            Criteria c = session.createCriteria(Employee.class);
            List l = c.list();
            Iterator it = l.iterator();
            while(it.hasNext())
            {
                System.out.println(it.next());
            }
//          Employee e = new Employee(234, "IVS", "Vinay", 6500);
//          tx = session.beginTransaction();
//          session.save(e);
//          tx.commit();
//          tx=null;
        }
        catch(HibernateException ex)
        {
            System.out.println("Exception occured : " + ex.getMessage());
        }
        finally
        {
            System.out.println("Closing the session");
            session.close();
        }
    }
}


Please note the text in red in EmployeeClient class.
Here we have used AnnotationConfiguration because, we have used Annotations in Employee class to map the class fields with the table fields.
If Employee.hbm.xml is used for this mapping then here we would have used Configuration (which we normally do)
SessionFactory factory=new Configuration().configure().buildSessionFactory();