Friday, April 27, 2012

What is serialVersionUID in Java


What is serialVersionUID?
Before we start discussing about the solution for this problem, lets first see what is actually causing this problem? Why should any change in a serialized class throw InvalidClassException? During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. All this information is stored as part of the serialized object. When you deserialize the object, this information is read to reconsitute the object. But to perform the deserialization, the object needs to be identified first and this will be done by serialVersionUID. So everytime an object is serialized the java serialization mechanism automatically computes a hash value using ObjectStreamClass’s computeSerialVersionUID() method by passing the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value, the serialVersionUID.
When should you update serialVersionUID?
Adding serialVersinUID manually to the class does not mean that it should never be updated and never need not be updated. There is no need to update the serialVersionUID if the change in the class is compatible but it should be updated if the change is incompatible. What are compatible and incompatible changes? A compatible change is a change that does not affect the contract between the class and the callers.
The compatible changes to a class are handled as follows:
  • Adding fields - When the class being reconstituted has a field that does not occur in the stream, that field in the object will be initialized to the default value for its type. If class-specific initialization is needed, the class may provide a readObject method that can initialize the field to nondefault values.
  • Adding classes - The stream will contain the type hierarchy of each object in the stream. Comparing this hierarchy in the stream with the current class can detect additional classes. Since there is no information in the stream from which to initialize the object, the class’s fields will be initialized to the default values.
  • Removing classes - Comparing the class hierarchy in the stream with that of the current class can detect that a class has been deleted. In this case, the fields and objects corresponding to that class are read from the stream. Primitive fields are discarded, but the objects referenced by the deleted class are created, since they may be referred to later in the stream. They will be garbage-collected when the stream is garbage-collected or reset.
  • Adding writeObject/readObject methods - If the version reading the stream has these methods then readObject is expected, as usual, to read the required data written to the stream by the default serialization. It should call defaultReadObject first before reading any optional data. The writeObject method is expected as usual to call defaultWriteObject to write the required data and then may write optional data.
  • Removing writeObject/readObject methods - If the class reading the stream does not have these methods, the required data will be read by default serialization, and the optional data will be discarded.
  • Adding java.io.Serializable - This is equivalent to adding types. There will be no values in the stream for this class so its fields will be initialized to default values. The support for subclassing nonserializable classes requires that the class’s supertype have a no-arg constructor and the class itself will be initialized to default values. If the no-arg constructor is not available, the InvalidClassException is thrown.
  • Changing the access to a field - The access modifiers public, package, protected, and private have no effect on the ability of serialization to assign values to the fields.
  • Changing a field from static to nonstatic or transient to nontransient - When relying on default serialization to compute the serializable fields, this change is equivalent to adding a field to the class. The new field will be written to the stream but earlier classes will ignore the value since serialization will not assign values to static or transient fields.

How to generate a serialVersionUID?
There are two ways to generate the serialVersionUID.
  • Go to commanline and type "serialver <>. SerialVersionUID wil be generated. Copy, paste the same into your class. 
    In Windows, generate serialVersionUID using the JDK's graphical tool like so : use Control Panel | System | Environment to set the classpath to the correct directory
    run serialver -show from the command line
    point the tool to the class file including the package, for example, finance.stock.Account - without the .class
    (here are the serialver docs for both Win and Unix)
  • One way is through Eclipse IDE. After you implement Serializable interface and save the class, eclipse will show a warning asking you to add the serialVersionUID and it provides you the option to generate it or use the default one. Click on the link to generate the serialVersionUID and it will generate it for you and adds it to the class.

How to override hbm LAZY loading conf programmatically in Hibernate?

 //1. create conf object
  Configuration cfg = new Configuration();
cfg.configure();
cfg.buildMappings();
Iterator iter;
/*
* iter= cfg.getClassMappings(); while (iter.hasNext()) {
* PersistentClass persistentClass = (PersistentClass) iter.next();
* persistentClass.setLazy(true); Iterator iter2 =
* persistentClass.getPropertyIterator(); while (iter2.hasNext()) {
* Property prop = (Property) iter2.next(); prop.setLazy(true);
* org.hibernate.mapping.Value val = prop.getValue(); if (val != null &&
* val instanceof Fetchable) { Fetchable f = (Fetchable) val;
* f.setLazy(true); } } }
*/

//2. get all collection mappings
iter = cfg.getCollectionMappings();
while (iter.hasNext()) {
Collection collection = (Collection) iter.next();
 //3. set Lazy load to true or false as you wish
collection.setLazy(true);
}
//4. create SessionFactory object
SessionFactory sessionFactor = cfg.buildSessionFactory();

//5. create session object

Session session = sf.openSession();

//6. query to DB using get method. here you will get only  Employee object and remaining all objects proxy's will be created. Untill you call getXXX() the second query won't execute
Employee emp=( Employee ) session.get(Employee.class, 11356L);

Spring dynamic data source Routing

Wednesday, February 29, 2012

Linux frequently used commands

Linux frequently used commands

grep -r "/opt/webhost/logs/tandl/tomcat/tnlBasic.log" /opt/webhost
grep -r "tnlBasic.log" /opt/webhost
grep -r "tandl" /opt/webhost/paytteme/tomcat/webapps/test/WEB-INF/classes/log4j.properties

tar -cvf /var/tmp/ToCopy2.tar ./config ./ghrms ./log
tar -xvf ROOT.tar

scp shekharreddy@shekhar.houston.com:/opt/webhost/tomcat/webapps/servlet_app/WEB-INF/lib/tnl.jar /opt/webhost/tomcat/webapps/jsp_app/WEB-INF/lib

find /opt/webhost/ -name "daily_time_data_msg_ENG.js"
find /home/webhost/ -name "hibernate.cfg.xml"
find / -type d -name "java*"
find /opt/webhost/paytteme/apache/conf/ -type f -name "mod_autoindex.so"
find / -type f -name "mod_autoindex.so"

chmod 777 -R ROOT


1. tar command examples

Create a new tar archive.
$ tar cvf archive_name.tar dirname/

Extract from an existing tar archive.
$ tar xvf archive_name.tar

View an existing tar archive.
$ tar tvf archive_name.tar



2. grep command examples
Search for a given string in a file (case in-sensitive search).
$ grep -i "the" demo_file

Print the matched line, along with the 3 lines after it.
$ grep -A 3 -i "example" demo_text

Search for a given string in all files recursively
$ grep -r "ramesh" *


3. find command examples
Find files using file-name ( case in-sensitve find)
# find -iname "MyCProgram.c"

Execute commands on files found by the find command
$ find -iname "MyCProgram.c" -exec md5sum {} \;

Find all empty files in home directory
# find ~ -empty


4. ssh command examples
Login to remote host
ssh -l jsmith remotehost.example.com

Debug ssh client
ssh -v -l jsmith remotehost.example.com

Display ssh client version
$ ssh -V
OpenSSH_3.9p1, OpenSSL 0.9.7a Feb 19 2003



5. sed command examples

When you copy a DOS file to Unix, you could find \r\n in the end of each line. This example converts the DOS file format to Unix file format using sed command.

$sed 's/.$//' filename
Print file content in reverse order

$ sed -n '1!G;h;$p' thegeekstuff.txt
Add line number for all non-empty-lines in a file

$ sed '/./=' thegeekstuff.txt | sed 'N; s/\n/ /'
More sed examples: Advanced Sed Substitution Examples

6. awk command examples

Remove duplicate lines using awk
$ awk '!($0 in array) { array[$0]; print }' temp

Print all lines from /etc/passwd that has the same uid and gid
$awk -F ':' '$3==$4' passwd.txt

Print only specific field from a file.
$ awk '{print $2,$5;}' employee.txt


7. vim command examples
Go to the 143rd line of file

$ vim +143 filename.txt
Go to the first match of the specified

$ vim +/search-term filename.txt
Open the file in read only mode.

$ vim -R /etc/passwd
More vim examples: How To Record and Play in Vim Editor

8. diff command examples
Ignore white space while comparing.

# diff -w name_list.txt name_list_new.txt

2c2,3
< John Doe --- > John M Doe
> Jason Bourne


9. sort command examples

Sort a file in ascending order
$ sort names.txt

Sort a file in descending order
$ sort -r names.txt

Sort passwd file by 3rd field.
$ sort -t: -k 3n /etc/passwd | more

10. export command examples

To view oracle related environment variables.
$ export | grep ORACLE
declare -x ORACLE_BASE="/u01/app/oracle"
declare -x ORACLE_HOME="/u01/app/oracle/product/10.2.0"
declare -x ORACLE_SID="med"
declare -x ORACLE_TERM="xterm"

To export an environment variable:
$ export ORACLE_HOME=/u01/app/oracle/product/10.2.0

11. xargs command examples

Copy all images to external hard-drive
# ls *.jpg | xargs -n1 -i cp {} /external-hard-drive/directory

Search all jpg images in the system and archive it.
# find / -name *.jpg -type f -print | xargs tar -cvzf images.tar.gz

Download all the URLs mentioned in the url-list.txt file
# cat url-list.txt | xargs wget –c

12. ls command examples

Display filesize in human readable format (e.g. KB, MB etc.,)
$ ls -lh
-rw-r----- 1 ramesh team-dev 8.9M Jun 12 15:27 arch-linux.txt.gz
Order Files Based on Last Modified Time (In Reverse Order) Using ls -ltr

$ ls -ltr
Visual Classification of Files With Special Characters Using ls -F

$ ls -F
More ls examples: Unix LS Command: 15 Practical Examples

13. pwd command

pwd is Print working directory. What else can be said about the good old pwd who has been printing the current directory name for ages.

14. cd command examples

Use “cd -” to toggle between the last two directories
Use “shopt -s cdspell” to automatically correct mistyped directory names on cd


15. gzip command examples

To create a *.gz compressed file:
$ gzip test.txt

To uncompress a *.gz file:
$ gzip -d test.txt.gz

Display compression ratio of the compressed file using gzip -l
$ gzip -l *.gz
compressed uncompressed ratio uncompressed_name
23709 97975 75.8% asp-patch-rpms.txt

Tuesday, December 6, 2011

Decode VS Case in Oracle

Decode: In Oracle/PLSQL, the decode function has the functionality of an IF-THEN-ELSE statement.

select decode(col1, 1,one,2,two) from table_name


if col1 value 1 then it will print as 'one' in result
if col1 value 2 then it will print as 'two' in result

decode will give performance issue. so now CASE came with same funtionality with better performance.

Case:

select main_acnt_code as code, main_acnt_name as name
from fm_main_account
where MAIN_FRZ_FLAG = 'N'
and case in_Code
when 'CAPEX' THEN main_class_code_05 = 'Y';
when 'MAIN_ACC2' THEN main_class_code_02 = 'Y';
end case;

select statements

Below two select statements will give same results

select *from employee where 10=emplid
select *from employee where emplid=10

Decode in Oracle

In Oracle/PLSQL, the decode function has the functionality of an IF-THEN-ELSE statement.

For example:

You could use the decode function in an SQL statement as follows:

SELECT supplier_name,
decode(supplier_id, 10000, 'IBM',
10001, 'Microsoft',
10002, 'Hewlett Packard',
'Gateway') result
FROM suppliers;

The above decode statement is equivalent to the following IF-THEN-ELSE statement:

IF supplier_id = 10000 THEN
result := 'IBM';

ELSIF supplier_id = 10001 THEN
result := 'Microsoft';

ELSIF supplier_id = 10002 THEN
result := 'Hewlett Packard';

ELSE
result := 'Gateway';

END IF;


Question: I would like to know if it's possible to use decode for ranges of numbers, ie 1-10 = 'category 1', 11-20 = 'category 2', rather than having to individually decode each number.

Answer: Unfortunately, you can not use the decode for ranges of numbers. However, you can try to create a formula that will evaluate to one number for a given range, and another number for the next range, and so on.

For example:

SELECT supplier_id,
decode(trunc ((supplier_id - 1) / 10), 0, 'category 1',
1, 'category 2',
2, 'category 3',
'unknown') result
FROM suppliers;
In this example, based on the formula:

trunc ((supplier_id - 1) / 10

The formula will evaluate to 0, if the supplier_id is between 1 and 10.
The formula will evaluate to 1, if the supplier_id is between 11 and 20.
The formula will evaluate to 2, if the supplier_id is between 21 and 30.

Monday, November 21, 2011

Incremental Update

Using Merge Join:

SQL> MERGE
INTO target_table tgt
USING source_table src
ON ( src.object_id = tgt.object_id )
WHEN MATCHED
THEN
UPDATE
SET tgt.object_name = src.object_name
, tgt.object_type = src.object_type
WHEN NOT MATCHED
THEN
INSERT ( tgt.object_id
, tgt.object_name
, tgt.object_type )
VALUES ( src.object_id
, src.object_name
, src.object_type );



Using SQL%ROWCOUNT (will give last DML updated row count):


SQL> DECLARE
i PLS_INTEGER := 0;
u PLS_INTEGER := 0;
BEGIN
FOR r IN ( SELECT * FROM source_table )
LOOP

UPDATE target_table tgt
SET tgt.object_name = r.object_name
, tgt.object_type = r.object_type
WHERE tgt.object_id = r.object_id;

u := u + SQL%ROWCOUNT;

IF SQL%ROWCOUNT = 0 THEN
INSERT INTO target_table
( object_id, object_name, object_type )
VALUES
( r.object_id, r.object_name, r.object_type );
i := i + 1;
END IF;

END LOOP;
DBMS_OUTPUT.PUT_LINE( u || ' rows updated.' );
DBMS_OUTPUT.PUT_LINE( i || ' rows inserted.' );
END;

Type of Cursors

Two types:

1. Implicit cursor
2. Explicit cursor

Implicit cursor: Are used by oracle.
eg1:
select name into var_name from emp;
eg2:
FOR r IN ( SELECT * FROM source_table )
LOOP

UPDATE target_table tgt
SET tgt.object_name = r.object_name
, tgt.object_type = r.object_type
WHERE tgt.object_id = r.object_id;

u := u + SQL%ROWCOUNT;

IF SQL%ROWCOUNT = 0 THEN
INSERT INTO target_table
( object_id, object_name, object_type )
VALUES
( r.object_id, r.object_name, r.object_type );
i := i + 1;
END IF;

END LOOP;

Explicit Cursors :For explicit cursors developer should do the following things

1. Declare the cursor
CURSOR company_cur IS
SELECT company_id FROM company;

2. Open the cursor (if not already open)
OPEN company_cur ;
3. Fetch one or more rows from the cursor
LOOP
FETCH company_cur INTO var_emplid;

EXIT WHEN company_cur %NOTFOUND;
-- do some data process here

END LOOP;

4. Close the cursor
CLOSE company_cur;

Sunday, November 20, 2011

how many form-bean objects will be created by Web Container?

That depends on scope attribute in action element(struts-config.xml).

if scope= request then WC creates form bean object for each request if object not exist in ServletRequest object otherwise it uses existing object.
if scope= session then WC creates form bean object for each session if object not exist in HttpSession object otherwise it uses existing object.

Monday, June 14, 2010

How to get time zone as IST instead of GMT+05:30

this will display time zone in short like "IST","GMT" etc

TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT)

Configure Tomcat for Debug

Configure Tomcat for Debug:

1. Open your tomcat admin console: /bin/tomcat5w.exe
C:\Apps\tnl\Tomcat5\bin\tomcat5w.exe

2. Click the Java Tab
Add the following arguments to the Java Options

-Xdebug
-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

3. Click the Startup Tab
Add the arguments (on two separate lines, in the order below):
jpda
start
Select Mode -> JVM


After doing above step just run You application in Debug mode

Wednesday, January 27, 2010

jndi configuration with tomcat

Jndi configuration with tomcat example:

http://tomcat.apache.org/tomcat-4.1-doc/jndi-datasource-examples-howto.html

Thanks,
Shekhar.