Monday, December 3, 2012

how to use Jquery datataable

1. add jquery.dataTables.js and jquery.dataTables.css in your html. keep these files in proper folder.




2. keep below code in your html code.

AJax call with json response


Set Json response in Controller:

PrintWriter writer = response.getWriter();
JSONArray storeList = new JSONArray();
JSONObject store = null;
List list = new ArrayList();
list.add("RS");
list.add("EUR");
list.add("DOLLER");
for (String string : list) {
    store = new JSONObject();
    store.put("storeName", string);
    storeList.put(store);
}
JSONObject json = new JSONObject();
json.put("storeList", storeList);
sb = json.toString();
writer.write(sb);












ajax call:

Way 1:
$.ajax({
        url : currentPath+'/appName/partnerStoreAddress',
        data : 'store='+selectedValue+'&cbn='+cbnValue,
        dataType : 'json',
        success : function(json) {
            createAdressTable(json);
            $.unblockUI();
        },
        error:function(xhr,errorThrown){
              var r = jQuery.parseJSON(xhr.responseText);
              alert("Message: " + r.Message);
              alert("StackTrace: " + r.StackTrace);
              alert("ExceptionType: " + r.ExceptionType);
              alert(xhr.status);
              alert(errorThrown);
        }
    });

Way 2:

function setupAjaxForm(form_id, form_validations){
    var form = '#' + form_id;
   
    // setup jQuery Plugin 'ajaxForm'    
    var options = {
        target : '#refresh',  //if you want to refresh any div only
        dataType:  'json',
        beforeSubmit: function(){
        $.unblockUI();
         $.blockUI({
                message : ''
            })
            //pageRefresh = 'Y';
        },
        timeout:8000,
        success: function(json){
            $.unblockUI();
            $("#refresh").html($(html).find("#refresh"));
            $('#HPContactEmailList_filter').appendTo($('.themeheader'));
                       
            new setupAjaxForm('dummyForm'); 
           
        },
        error:function(xhr,errorThrown){
            $.unblockUI();
            alert('Selected item was not saved');
           
        }
    };
    $(form).ajaxForm(options);
}


$(document).ready( function () {
   
    $('#HPContactEmailList_filter').appendTo($('.themeheader'));
    new setupAjaxForm('dummyForm'); 
    }
);

Tuesday, October 2, 2012

Common mistake with Date



Use ‘dd/MM/yyyy’ instead of ‘dd/mm/yyyy’ when you are working with SimpleDateFormat to format. otherwise 'mm' will be considered as mints.

Can we access private methods in other class?..yes we can using reflection api


Yes...We can access private methods in other class using reflection API

Example code:

MyClass.java with private method
public class MyClass {

private String myPrivateMethod(String name) {
//Do something private
return "Hello "+;
}
}

Test class:  MainTest.java public class MainTest class{

private MyClass underTest;


public static void main(String []args)throws Exception {

MyClass underTest= new MyClass();

Class[] parameterTypes = new Class[1];
parameterTypes[0] = java.lang.String.class;

Method m = underTest.getClass().getDeclaredMethod("myPrivateMethod", parameterTypes);
m.setAccessible(true);

Object[] parameters = new Object[1];
parameters[0] = "Shekhar Reddy!";

String result = (String) m.invoke(underTest, parameters);
System.out.println(result )//Shekhar Reddy!

}


}
outPut: Hello Shekhar Reddy!

JUnit test case using Mock API

Mock API helps to create dummy object and returns back something to program when we are calling any method on that dummy object instead calling actual object.
Ex:
context.checking(new Expectations() {{
      oneOf (accountDAO).selectAccount(with("1234")); 
      will(returnValue(null));
  }});
 
 
Here we are asking Mock api return "null" value when I Call  
selectAccount method with 1234 value on AccountDAO object.

You can find very good example with maven integration in the below link.

http://onjavahell.blogspot.in/2009/05/good-unit-testing-with-jmock.html

Singleton object using Enum type

Since Java 1.5, there is a new approach to implement Singletons. Simply make it an enum type :
public enum MySingleton {

  INSTANCE;

  //Singleton method
  public void someMethod( ) {...}
}
Accessing the enum singleton :
MySingleton.INSTANCE.someMethod( );

New in spring 2.5 and Dependencies injection with Spring annotations (@Repository, @Service, @Autowired)

Click on below link to know what is new in spring 2.5

http://www.infoq.com/articles/spring-2.5-part-1
 Click below link to find simple example code with old and new bean configuration Dependencies injection with Spring annotations (@Repository, @Service, @Autowired). 
http://onjavahell.blogspot.in/2009/04/dependencies-injection-with-spring.html

Wednesday, July 18, 2012

How to test Restlet webservice using JUnit without deploying webservice in webserver

How to test Restlet web service using JUnit without deploying web service in web server


1. create a class to load all bean xml files extending Application

public class WebServiceServer extends Application {

    /**
     * Creates a root Restlet that will receive all incoming calls.
     */
    @Override
    public synchronized Restlet createInboundRoot() {
        // Create a router Restlet that routes each call to a
        // new instance of HelloWorldResource.

        File contextDir = new File(System.getProperty("user.dir"));
        if (!contextDir.getName().equals("context")) {
            contextDir = new File(contextDir, "context");
        }

        if (!contextDir.isDirectory()) {
            throw new IllegalStateException("Could not find context directory");
        }
        FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(
                new String[] {contextDir + "\\WEB-INF\\beans\\WebService-servlet.xml" });
        SpringRouter router = context.getBean("root", SpringRouter.class);

        // Defines only one route
        router.attach("/webservice", ActualRestletClass.class);

        return router;
    }
}


2. WebService-servlet.xml file config


       
           
               
               
                   
                       
                   

               

           

       

   


   
     


3. Actual restlet webservice

public class ServiceResource extends ServerResource {
@Override
    protected Representation get(Variant variant) throws ResourceException {


Representation resource = new StringRepresentation(content, mediaType);
    return resource;
    }}

}

4. Now test your restlet

 public class TestWebService {
    public static void main(String[] args) throws Exception {
        // Create a new Component.
        Component component = new Component();
        // Add a new HTTP server listening on port 8182.
        component.getServers().add(Protocol.HTTP, 8182);
    
        // Attach the sample application.
        component.getDefaultHost().attach("/WebService",
                new WebServiceServer());
        // Start the component.
        component.start();
    }
}




Wednesday, July 11, 2012

How to use ENUM in Hibernate

Using ENUM in Hibernate
1. create enum type
public enum LoginStatus {

ACTIVE,
INACTIVE
}

2. add property with Enum type
private LoginStatus status;

public LoginStatus getStatus() {
return status;
}

public void setStatus(LoginStatus status) {
this.status = status;
}

3. if we use the above code this will insert the entries as index of ENUM values (0,1) in DB insteade of ACTIVE,INACTIVE values

if we want to insert as values then we need to create new table with ENUM values.

How to generate hbm POJO and DAO files from table using Eclipse

How to generate hbm POJO and DAO files from table using Eclipse

First we need to install "Hibernate prespectives" if you don't have already

1. go to 'help'  in eclipse
2. install new software and click on add button
3. provide this site in pop-up
for Galileo 3.5 :http://download.jboss.org/jbosstools/updates/JBossTools-3.1.1.GA

for Ganymede 3.4: http://download.jboss.org/jbosstools/updates/JBossTools-3.0.3.GA

for indigo: http://download.jboss.org/jbosstools/updates/stable/indigo/

4. install all software starting with 'Hibernate' name.

5. after installation you should be able to see Hibernate prespectives.


Then create new java project. file --> New --> java project
1. Right on project select New --> others --> Hibernate Configuration file --> next -->
2. Provide all required URL, driver class, uname and password etc..after these steps you should be able to see hibernate.cfg.xml file in your project
3.   a. Then right click on project New --> other --> select "Hibernate Reverse Engineering" then click on "NEXT" --> "NEXT" .

     b. Then right click on project New --> other --> select "Hibernate Console configuration" then click on "NEXT" --> "Finish" 

4. select "console configuration" and click on "Refresh" button it will take some time to your data scheme.
5. Once the schema available then include required tables to  generate hbm, POJO, DAO etc..
6. click on "finish" button
7. got to "Run" and select "Hibernate Code Generation"  then select "Hibernate Code Generation configuration"
8. Right click on "Hibernate Code Generation" and  "new" then fill required info(out put dir) in "Main" and "Exporter" tab
9. Then Click on "apply" and "Run" buttons

You should be able to see .hbm.xml, Pojo, Dao etc.. in out put directory.



You can find related info in below link
http://download.jboss.org/jbosstools/updates/











Cheers,
Shekhar reddy



Tuesday, July 10, 2012

Volatile keyword in Java

Volatile keyword in Java is used as an indicator to Thread that do not cache value of this variable and always read it from main memory.
Example using Singleton:
public class Singleton{
private static volatile Singleton _instance;

public static Singleton getInstance(){

   if(_instance == null){
            synchronized(Singleton.class){
              if(_instance == null)
              _instance = new Singleton();
            }

   }
   return _instance;

}

If you look at the code carefully you will be able to figure out:
1) We are only creating instance one time
2) We are creating instance lazily at the time of first request comes.

If we do not make _instance variable volatile then Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been

created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be

able to see value of _instance as not null and they will believe its still null.

Notes:
1. Volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal.
2. Volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache.

Monday, June 25, 2012

Future Date Validation in JavaScript

Future Date Validation:            

                       var months = {
                                        Jan : 1,
                                        Feb : 2,
                                        Mar : 3,
                                        Apr : 4,
                                        May : 5,
                                        Jun : 6,
                                        Jul : 7,
                                        Aug : 8,
                                        Sep : 9,
                                        Oct : 10,
                                        Nov : 11,
                                        Dec : 12
                                    };
                                    function futureDateValidation(id) {

                                        var dateStr = '27 Jun 2012';

                                        var dateArr = dateStr.split(' ');// not a perfect solution, but meh

                                        var dateObj = new Date();
                                        var day = parseInt(dateArr[0]);
                                        alert(day);

                                        var month = months[dateArr[1]];
                                        alert(month);

                                        var year = parseInt(dateArr[2]);
                                        alert(year);

                                        if (year < 1970)
                                            year += 100;

                                        dateObj.setFullYear(year, month, day);

                                        if (dateObj > new Date()) {
                                            alert('Too late.');
                                        }
                                    }

Tuesday, June 19, 2012

Basic Log4j info

The rootLogger is the one that resides on the top of the logger hierarchy. Here we set its level to DEBUG and added the console appender (CA) to it. The console

appender can have arbitrary name, here its name is CA.

log4j.rootLogger=DEBUG, CA
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n


Since the rootLogger level is set to DEBUG all the messages are displayed.

The log4j levels follow the following order.


DEBUG
INFO
WARN
ERROR
FATAL

If you set the rootLogger level to WARN then only the WARN, ERROR and FATAL level log messages will be displayed and the rest will be dropped



How can we write our own arraylist without using collections?

You have to use array of Object to store the element and then provide the functionality of adding,seraching and removing the element.This is the way you can create



your own arrayList without using Collections.



1. Make an array of Object holding some predefined number of objects.

2. Take a double variable indicating loadFactor.

3. if the length of the occupied array elements becomes three fourth(or the value of the loadFactor)

3.1 Create an array of Object with size double of the original array.

3.2 copy content of original array to this new array.

3.3 return the new array and delete old array

Wednesday, June 13, 2012

Database Isolation levels

Isolation levels :


TRANSACTION_SERIALIZABLE: Strongest level of isolation. Places a range lock on the data set, preventing other

users from updating or inserting rows into the data set until the transaction is

complete. Can produce deadlocks.

TRANSACTION_REPEATABLE_READ: Locks are placed on all data that is used in a query, preventing other users from

updating the data, but new phantom records can be inserted into the data set

by another user and are included in later reads in the current transaction.

TRANSACTION_READ_COMMITTED: Can't read uncommitted data by another transaction. Shared locks are held while

the data is being read to avoid dirty reads, but the data can be changed before

the end of the transaction resulting in non-repeatable reads and phantom

records.

TRANSACTION_READ_UNCOMMITTED:

Can read uncommitted data (dirty read) by another transaction, and nonrepeatable

reads and phantom records are possible. Least restrictive of all

isolation levels. No shared locks are issued and no exclusive locks are

honoured.

Saturday, June 2, 2012

Uploadify code to send parameters to server with Uploaded file

JSP code :
























Comment :





Reference :















 
 
Servlet code to get request parameter:
 
 
package com.hp;




import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;



import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;



public class UploadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;



/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter writer = response.getWriter();

writer.write("call POST with multipart form data");

}



/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*

*/

@SuppressWarnings("unchecked")

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

boolean exit = false;

if (!ServletFileUpload.isMultipartContent(request)) {

throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");

}



ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());

PrintWriter writer = response.getWriter();

response.setContentType("text/plain");

String comments=request.getParameter("comment");

try {

List items = uploadHandler.parseRequest(request);

for (FileItem item : items) {

if (!item.isFormField()) {

System.out.println("Name: " + item.getName());

System.out.println("Size: " + item.getSize());

System.out.println("Type: " + item.getContentType());

File file = File.createTempFile(item.getName(), "");

item.write(file);

writer.write("{\"name\":\""+ item.getName() + "\",\"type\":\"" + item.getContentType() + "\",\"size\":\"" + item.getSize() + "\"}");

break; // assume we only get one file at a time

}

else{

if(item.getFieldName().equalsIgnoreCase("comment")){

String comment = item.getString();

System.out.println("comment "+comment);

if(comment == null

comment.trim().isEmpty()){

writer.write("{\"error\":\""+"yes"+"\",\"errorType\":\""+"NullComment"+"\"}");

exit = true;

}



}

else if(item.getFieldName().equalsIgnoreCase("reference")){

String ref = item.getString();

System.out.println("reference "+ref);

if(ref == null

ref.trim().isEmpty()){

writer.write("{\"error\":\""+"yes"+"\",\"errorType\":\""+"NullReference"+"\"}");

exit = true;

}

}



if(exit == true){

break;

}



}

}

} catch (FileUploadException e) {

throw new RuntimeException(e);

} catch (Exception e) {

throw new RuntimeException(e);

} finally {

writer.close();

}



}



}

Tuesday, May 29, 2012

Log4j levels priority

Log4j levels priority:

Log4J Levels

TRACE LevelDEBUG LevelINFO LevelWARN LevelERROR LevelFATAL Level
TRACE LevelYYYYYY
DEBUG LevelNYYYYY
INFO LevelNNYYYY
WARN LevelNNNYYY
ERROR LevelNNNNYY
FATAL LevelNNNNNY
ALL LevelYYYYYY
OFF LevelNNNNNN

difference between bean id and name attribute in Spring

1. The id gets automatically and stricter validated by the XML parser since it has a special meaning in XML. So for example you can't add twice the same id into the XML, the parser would complain. This helps to edit the file since you can see an error in an XML editor. That's no possible for name. Spring can only complain at runtime about duplicate name.

2. Also, you cannot use certain characters in an XML id attribute: if you're using URLs as bean names, as is common in Spring MVC, then you'll need to use name="/path/somecontroller" instead of id, since the slashes are not legal characters to use for an XML id. That's actually the most common reason to use name instead of id. Others are if you need to specify several aliases using a comma seperated list in the name attribute: comma's are also not allowed inside an XML id.

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