Monday, May 28, 2012

Eclipse plugin for HTML and JavaScript editor with validations

Do below steps to add Eclipse plugin for HTML and JavaScript validations
1. Please click here to download Eclipse plugin for HTML and JavaScript validations.
2. Put the downloaded JAR file into ECLIPSE_HOME/plugins or ECLIPSE_HOME/dropins.
3.Then restart your Eclipse
Enjoy with new plugin!

Wednesday, May 23, 2012

Eclipse Tip: Static Imports

One of the great features of Java 1.5 is Static Imports. In order to configure Eclipse to search for static imports in a particular class, you have to perform the following steps:

  1. Navigate to Preferences by clicking on the Window -> Preferences Menu Item
  2. Navigate to Java -> Editor -> Content Assist -> Favorites using the menu tree (or search for Favorites using the search bar at the top)
  3. Click the New Type button
  4. Type in the name of the Class that has static methods that you would like to be used when using Eclipse's Content Assist / Code Completion (eg Assert)
  5. Click on the Browse button which will bring up the Open Type Dialog using what you entered previously as the search criteria
  6. Find the class that you would like to add, and then click Okay on the Open Type Dialog
  7. Then Click Okay on the New Type Favorite Dialog.
Now when you are editing Java code, instead of typing Assert.assertEquals, you only need to type assertEquals, with Ctrl-Space, and the Assert Type will be searched for in order to resolve the static import.

NoClassDefFoundError vs ClassNotFoundException


Difference between ClassNotFoundException vs NoClassDefFoundErrorBefore seeing the differences between ClassNotFoundException and NoClassDefFoundError let's see some similarities which are main reason of confusion between these two errors:

1) Both NoClassDefFoundError and ClassNotFoundException are related to unavailability of a class at run-time.
2) Both ClassNotFoundException and NoClassDefFoundError are related to java classpath.

Now let's see the difference between NoClassDefFoundError and ClassNotFoundException:

1) ClassNotFoundException comes in java if we try to load a class at run-time using with Class.forName() or ClassLoader.loadClass() or ClassLoader.findSystemClass() method and requested class is not available in Java. the most of the time it looks like that we have the class in classpath but eventually it turns out to be issue related to classpath and application may not be using classpath what we think it was using e.g. classpath defined in jar's manifest file will take precedence over CLASSPATH or -cp option, for more details see How classpath works in java. On the other hand NoClassDefFoundError is little different than ClassNotFoundException, in this case culprit class was present during compile time and let's application to compile successfully and linked successfully but not available during run-time due to various reason.

2) ClassNotFoundException is a checked Exception derived directly from java.lang.Exception class and you need to provide explicit handling for it while NoClassDefFoundError is an Error derived from LinkageError.

3) If you are using classloaders in Java and have two classloaders then if a classloader tries to access a class which is loaded by another classloader will result in ClassNoFoundException.

4) ClassNotFoundException comes up when there is an explicit loading of class is involved by providing name of class at runtime using ClassLoader.loadClass, Class.forName while NoClassDefFoundError is a result of implicit loading of class because of a method call from that class or any variable access.


Tuesday, May 22, 2012

How to find current directory in Java with Example

public class CurrentDirectoryExample {

    public static void main(String args[]) {
    
        String current = System.getProperty("user.dir");
        System.out.println("Current working directory in Java : " + current);
    
    }
}



If you run above program from C:\Test it will print C:\Test as current working directory

C:\Test> java CurrentWorkingDirectoryExample
Current working directory in Java : C:\Test


If you run it from C:\ then it will print C:\ as current working directory as shown in below example

C:\> java -cp ./Test  CurrentWorkingDirectoryExample
Current working directory in Java : C:\


How to reverse number in Java - Example

import java.util.Scanner;

/**
 * Simple Java program to reverse a number in Java using loop and operator
 * This program also shows example of using division operator(/) and Remainder Operator(%)
 */

public class ReverseNumberExample {

    public static void main(String args[]) {
       //input number to reverse
        System.out.println("Please enter number to be reversed using Java program: ");
        int number = new Scanner(System.in).nextInt();
     
        int reverse = reverse(number);
        System.out.println("Reverse of number: " + number + " is " + reverse(number));  
   
    }
 
    /*
     * reverse a number in Java using iteration
     * @return reverse of number
     */

    public static int reverse(int number){
        int reverse = 0;
        int remainder = 0;
        do{
            remainder = number%10;
            reverse = reverse*10 + remainder;
            number = number/10;
         
        }while(number > 0);
     
        return reverse;
    }

}

Output:
Please enter number to be reversed using Java program:
1234
Reverse of number: 1234 is 4321

What's new with JUnit4

1. @Test

Mark your test cases with @Test annotations. You don’t need to prefix your test cases with “test”. In addition, your class does not need to extend from “TestCase” class.



@Test

public void addition() {

assertEquals(12, simpleMath.add(7, 5));

}



@Test

public void subtraction() {

assertEquals(9, simpleMath.substract(12, 3));

}

2. @Before and @After

Use @Before and @After annotations for “setup” and “tearDown” methods respectively. They run before and after every test case.



@Before

public void runBeforeEveryTest() {

simpleMath = new SimpleMath();

}



@After

public void runAfterEveryTest() {

simpleMath = null;

}

3. @BeforeClass and @AfterClass

Use @BeforeClass and @AfterClass annotations for class wide “setup” and “tearDown” respectively. Think them as one time setup and tearDown. They run for one time before and after all test cases.



@BeforeClass

public static void runBeforeClass() {

// run for one time before all test cases

}



@AfterClass

public static void runAfterClass() {

// run for one time after all test cases

}

4. Exception Handling

Use “expected” paramater with @Test annotation for test cases that expect exception. Write the class name of the exception that will be thrown.



@Test(expected = ArithmeticException.class)

public void divisionWithException() {

// divide by zero

simpleMath.divide(1, 0);

}

5. @Ignore

Put @Ignore annotation for test cases you want to ignore. You can add a string parameter that defines the reason of ignorance if you want.



@Ignore(“Not Ready to Run”)

@Test

public void multiplication() {

assertEquals(15, simpleMath.multiply(3, 5));

}

6. Timeout

Define a timeout period in miliseconds with “timeout” parameter. The test fails when the timeout period exceeds.



@Test(timeout = 1000)

public void infinity() {

while (true)

;

}

7.New Assertions

Compare arrays with new assertion methods. Two arrays are equal if they have the same length and each element is equal to the corresponding element in the other array; otherwise, they’re not.



public static void assertEquals(Object[] expected, Object[] actual);

public static void assertEquals(String message, Object[] expected, Object[] actual);



@Test

public void listEquality() {

List expected = new ArrayList();

expected.add(5);



List actual = new ArrayList();

actual.add(5);



assertEquals(expected, actual);

}

JUnit4Adapter

Run your Junit 4 tests in Junit 3 test runners with Junit4Adapter.



public static junit.framework.Test suite() {

return new JUnit4TestAdapter(SimpleMathTest.class);

}

Servlet and Struts Junit test case with Mock objects

Thursday, May 3, 2012

java script hide and show funcation


Here id is div or span id

function shoh(id) {
if (document.getElementById) { // DOM3 = IE5, NS6
if (document.getElementById(id).style.display == "none"){
document.getElementById(id).style.display = 'block';
} else {
document.getElementById(id).style.display = 'none';
}
} else {
if (document.layers) {
if (document.id.display == "none"){
document.id.display = 'block';
} else {
document.id.display = 'none';
}
} else {
if (document.all.id.style.visibility == "none"){
document.all.id.style.display = 'block';
} else {
document.all.id.style.display = 'none';
}
}
}
}

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