Monday, February 21, 2011

Interview questions -- Serializable

Suppose I have 2 classes
1) Person having person name = "Yogesh";
2) User having username = "User" extends Person and implements Serializable.

What will be the values printed if I serialize and deserialize the User object?

I guessed it wrongly and answered that personname will not get printed as Person class is not serializable. BUT THAT WAS WRONG !!!

Both the values will be stored and retrieved correctly. The reason I don't know, but, this scenario, I have tested on PC

Saturday, February 19, 2011

What is serialVersionUID?

Source : http://www.javablogging.com/what-is-serialversionuid/

What is serialVersionUID?


Most people learn about serialVersionUID after they write their first serializable object (I know I did). You add ‘implements Serializable’ and in the next moment your IDE starts complaining… so what’s up?

Lets look at a simple example to see what meaning that variable has. In the example we will use the class SerializeMe shown below:

class SerializeMe implements Serializable {
    private static final long serialVersionUID = 1L;

    private int data;

    public SerializeMe (int data) {
        this.data = data;
    }

    public int getData() {
        return data;
    }
}

Field data represents some information stored in the class. Class implements the Serializable interface, so my IDE automatically offered me to declare the serialVersionUID field. Lets start with value 1 set there.

We will also need some class that will serialize and deserialize the SerializeMe class. Here it is:

public class UIDTester {
    public static void main(String... strings) throws Exception {
        File file = new File("out.ser");
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        SerializeMe serializeMe = new SerializeMe(1);
        oos.writeObject(serializeMe);
        oos.close();

        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(fis);

        SerializeMe dto = (SerializeMe) ois.readObject();
        System.out.println("data : " + dto.getData());
        ois.close();
    }
}

This code will serialize an instance of class SerializeMe to a file and then deserialize it back. Now let’s run the main function! You should get output that says:


data : 1

Tuesday, February 15, 2011

Best practices in Collections

If you do need a synchronized map, you can use the static method synchronizedMap(...) in class Collections to add synchronization to a regular map. Don't use the legacy collection classes, such as Hashtable. Example:

// A regular, unsynchronized map  
Map<Integer, String> map = new HashMap<Integer, String>();  
  
// Wrap it to add synchronization  
Map<Integer, String> synchedMap = Collections.synchronizedMap(map); 

Common Mistakes in Collections

Source : http://javabeanz.wordpress.com/2007/07/13/treemap-vs-hashmap/

Classes like Integer, String, Double etc implements Comparable interface. So if we are to use an object of a custom class as the key, ensure that it’ s class implements the Comparable interface.

public class MyCustomKey implements Comparable
{
    private int value;
    public MyCustomKey(int value)
    {
       this.value = value;
    }           

    public int compareTo (MyCustomKey key)
    {
       int comparison = 0;           

       // Note:
       // Return -1 if this.value < key.value
       // Return  0 if this.value = key.value
       // Return  1 if this.value > key.value           

       return (comparison);
    }
}


A common mistake that everyone does is not to override the hashcode(). If we are failing to do so, map.get(new MyCustomKey()); may not give you what you were expecting. So it is always advised to override the hashCode() if objects of that class is being used as a key.

public class MyCustomKey implements Comparable
{
    private int value;
    public MyCustomKey(int value)
    {}
    public int compareTo (MyCustomKey key)
    {}        

    public int hashCode()
    {
        // Note:
        // If two objects are equal then their corresponding hashCode ()
        // should return the same value too.
        return (this.value * 199);
    }
}


When you are using your custom object as a key to a HashMap, make sure you do the following

1) implement Comparable
2) override compareTo method, and give its implementation
3) override hashCode and equals method, and give their implementation.
4) Always, make your key object as immutable, so that it is not changed after you add it to a HashMap as key.

Sunday, February 13, 2011

Struts2 vs. Struts1


1.  Servlet Dependency:
Actions in Struts1 have dependencies on the servlet API since theHttpServletRequest and HttpServletResponse objects are passed to the execute method when an Action is invoked but in case of Struts 2, Actions are not container dependent because they are made simple POJOs. In struts 2, the servlet contexts are represented as simple Maps which allows actions to be tested in isolation. Struts 2 Actions can access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly

Struts 2 Iterator tag example

Source : http://www.mkyong.com/struts2/struts-2-iterator-tag-example/

Struts 2 Iterator tag example


Struts 2 Iterator tag is used to iterate over a value, which can be any of java.util.Collection or java.util.Iterator. In this tutorials, you will create a list variable, use Iterator tag to loop over it and get the iterator status with IteratorStatus.

1. Action
An Action class with a List property , which contains variety of delicious “KFC combo meals”.

IteratorKFCAction
package com.mkyong.common.action;
 
import java.util.ArrayList;
import java.util.List;
 
import com.opensymphony.xwork2.ActionSupport;
 
public class IteratorKFCAction extends ActionSupport{
 
 private List<String> comboMeals;
 
 public Listlt;String> getComboMeals() {
  return comboMeals;
 }
 
 public void setComboMeals(List<String> comboMeals) {
  this.comboMeals = comboMeals;
 }
 
 public String execute() {
 
  comboMeals = new ArrayList<String>();
  comboMeals.add("Snack Plate");
  comboMeals.add("Dinner Plate");
  comboMeals.add("Colonel Chicken Rice Combo");
  comboMeals.add("Colonel Burger");
  comboMeals.add("O.R. Fillet Burger");
  comboMeals.add("Zinger Burger");
 
  return SUCCESS;
 }
}

Friday, February 4, 2011

Column names in hbm.xml

When i added a field in my pojo class, with name xMoveCompatibleItem and I used eclipse's inbuilt feature to generate getter and setter methods

Eclipse generated methods with the following names:
getXMoveCompatible()
setXMoveCompatible(String)

Note that X and M are both capital and consecutive, which was creating a problem for weblogic. It was not able to find the getter method for that property.

Do take care while adding a property, if the second letter of the property name is in CAPITAL

Monday, January 31, 2011

How to use logger in your Java application

How to log Messages in your application?


Java's logging facility has two parts: a configuration file, and an API for using logging services. It is suitable for simple and moderate logging needs. Log entries can be sent to the following destinations, as either simple text or as XML:
· The console
· A file
· A stream
· Memory
· TCP socket on a remote host

The LEVEL class defines seven levels of logging enlightenment :
FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE .ALL and OFF are defined values as well

The levels in code may be modified as required :
· Upon startup, by using CONFIG to log configuration parameters
· During normal operation, by using INFO to log high-level "heartbeat" information
· When bugs or critical conditions occur, by using SEVERE.
· Debugging information might default to FINE, with FINER and FINEST used occasionally, according to user need.


There is flexibility in how logging levels can be changed at runtime, without the need for a restart:
· By simply changing the configuration file and calling LogManager.readConfiguration.
· By changing the level in the body of code , using the logging API ;
For example, one might automatically increase the logging level in response to unexpected events



The logging levels are in descending order SEVERE, WARNING, INFO, CONFIG, FINE, FINER and FINEST. If we specify log level as

INFO then all the log messages which are equal to INFO and greater (WARNING, SEVERE) levels will be logged.


Levels are attached to the following items:
· An originating logging request (from a single line of code)
· A Logger (usually attached to the package containing the above line of code)
· A Handler (attached to an application)

Here is an example of a logging configuration file :
# Properties file which configures the operation of the JDK
# logging facility. # The system will look for this config file, first using
# a System property specified at startup:
# >java -Djava.util.logging.config.file=myLoggingConfigFilePath #
# If this property is not specified, then the config file is retrieved
# from its default location at:
# JDK_HOME/jre/lib/logging.properties
# Global logging properties.
# ------------------------------------------
# The set of handlers to be loaded upon startup.
# Comma-separated list of class names.
# (? LogManager docs say no comma here, but JDK example has comma.)
handlers=java.util.logging.FileHandler, java.util.logging.ConsoleHandler

# Default global logging level.
# Loggers and Handlers may override this level
.level=INFO

# Loggers
# ------------------------------------------
# Loggers are usually attached to packages.
# Here, the level for each package is specified.
# The global level is used by default, so levels
# specified here simply act as an override.
myapp.ui.level=ALL
myapp.business.level=CONFIG
myapp.data.level=SEVERE

# Handlers
# -----------------------------------------
# --- ConsoleHandler ---
# Override of global logging level
java.util.logging.ConsoleHandler.level=SEVERE
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter

# --- FileHandler ---
# Override of global logging level
java.util.logging.FileHandler.level=ALL
# Naming style for the output file:
# (The output file is placed in the directory
# defined by the "user.home" System property.)
java.util.logging.FileHandler.pattern=%h/java%u.log

# Limiting size of output file in bytes:
java.util.logging.FileHandler.limit=50000

# Number of output files to cycle through, by appending an
# integer to the base file name:
java.util.logging.FileHandler.count=1

# Style of output (Simple or XML):
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter

Here is an example of using the logging API :

package myapp.business;
import java.util.logging.*;
/**
* Demonstrate Java's logging facilities, in conjunction
* with a logging config file.
*/
public final class SimpleLogger {

  public static void main(String argv[]) {
    SimpleLogger thing = new SimpleLogger();
    thing.doSomething();
  }
   public void doSomething() {
   //Log messages, one for each level
   //The actual logging output depends on the configured
    //level for this package. Calls to "inapplicable"
    //messages are inexpensive.
     fLogger.finest("this is finest");
    fLogger.finer("this is finer");
    fLogger.fine("this is fine");
    fLogger.config("this is config");
    fLogger.info("this is info");
    fLogger.warning("this is a warning");
    fLogger.severe("this is severe");

    //In the above style, the name of the class and
    //method which has generated a message is placed
    //in the output on a best-efforts basis only.
    //To ensure that this information is always
    //included, use the following "precise log"
    //style instead :
    fLogger.logp(Level.INFO, this.getClass().toString(), "doSomething", "blah");

    //For the very common task of logging exceptions, there is a
    //method which takes a Throwable :
    Throwable ex = new IllegalArgumentException("Some exception text");
    fLogger.log(Level.SEVERE, "Some message", ex);

    //There are convenience methods for exiting and
    //entering a method, which are at Level.FINER :
    fLogger.exiting(this.getClass().toString(), "doSomething");

    //Display user.home directory, if desired.
    //(This is the directory where the log files are generated.)
    //System.out.println("user.home dir: " + System.getProperty("user.home") );
  }

  // PRIVATE //

  //This logger will inherit the config of its parent, and add
  //any further config as an override. A simple style is to use
  //all config of the parent except, perhaps, for logging level.

  //This style uses a hard-coded literal and should likely be avoided:
  //private static final Logger fLogger = Logger.getLogger("myapp.business");

  //This style has no hard-coded literals, but forces the logger
  //to be non-static.
  //private final Logger fLogger=Logger.getLogger(this.getClass().getPackage().getName());

  //This style uses a static field, but hard-codes a class literal.
  //This is probably acceptable.
  private static final Logger fLogger = Logger.getLogger(SimpleLogger.class.getPackage().getName());

}

Friday, January 28, 2011

How to log an exception's stackTrace to log file using logger

Manytimes, we use logger to log messages that help us while debugging our application.
But, do you know, how do we write exception stackTrace to log file?

I tried to look for methods in Exception object, there is a method that writes to PrintWriter. Now how do I get PrintWriter's Object? Definitely, i could use reponse.getWriter(), but what if i want to log stacktrace from a java file, where I do not have access to response object. Moreover in many scenario's I would not like to write the stacktrace to browser, visible to end user.

Then I found a very useful over loaded method, which got skipped everytime before today.

Logger has an overloaded method, with 2 arguments, the second one is object of Throwable or Exception class.

This can be achieved as follows

 ...
 } catch( Exception e ) {
 logger.debug( e.getMessage(), e );
 }
 ...

Wednesday, January 26, 2011

How to download a file using AJAX

I struggled for half of my day finding this.

Actually in our project, there is a CART. The requirement is when we click on downloadCart button, it should download the contents of the cart and clear the cart as well.

The first issue that I faced was...

As the response has a zip file to be downloaded, hence in our Action class, they were writing bytes to the response, and in the end, when they return SUCCESS, (I forgot to tell u, we are using struts in our project) it gives an exception : java.lang.illegalStateException, that is expected.

So, what's the solution...

After discussing this with my friend Sukhbir, he suggested that we can't return any view after we have committed the response. But how to handle this scenario.

He suggested, make 2 calls, using javascript, and put it on onClick event of the button.
One for downloading, and the second one for re-loading the cart (So that it gets refreshed).

I did the code for downloading using AJAX.... $.get and $.ajax
But the issue now came up was....

Ajax calls work in background and it doesn't lets the user see that something has downloaded......no response, no prompt.......nothing........

Now what??

Then I came to know that there are APIs available in jquery for handling binary data when data is coming from server. I googled this also a lot, but, couldn't find anything that worked for me.

I found a very pretty and simple solution on internet now...Here it is...
Thanks to Eric for this help

Source : Google Group Forums Link

Final Solution
function test(url){ 
  var elemIF = document.createElement("iframe"); 
  elemIF.src = url; 
  elemIF.style.display = "none"; 
  document.body.appendChild(elemIF); 
} 



Related posts : http://particletree.com/notebook/ajax-file-download-or-not/

How to reload an iframe from within its source

Hi,

Today I had a requirement where it was desired that on click of a button an iframe should get re-loaded and that button was within the source of that iframe.

I tried everything else on google, but nothing worked.

Finally I found this and it worked

self.location.reload();

Here is the complete code...

abc.html
=========
<html>
<head>
</head>
<body>
 <iframe src="def.html" id="cartFrame"></iframe><BR><BR>
</body>
</html>


def.html
=========
<html>
 <head>
  <!-- Remember, you must be connected to internet to make it work -->
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  <script type="text/javascript">
   $(document).ready(function()
   {
    var d = new Date();
    // set the HTML content of the element with id=time
    $("#time").html(d.getTime());
    
    // define what happens on click of the element with id="download"
    $("#download").click(function()
    {
     // Simply re-load myself :)
     self.location.reload();
    });
    
   });
  </script>
 </head>

 <body>
  <div id="time"></div><BR><BR>
  <button id="download">Download</button>
 </body>
</html>

Thursday, January 20, 2011

Find bugs in your java program

You must be wondering, how to check errors and problems in your application.

Now your worry has come to an end..

Here is a tool, that can analyze compiled versions of your java programs and lets you know, what needs to be fixed in your application.

Have a look

http://findbugs.sourceforge.net/

Sunday, January 16, 2011

How to write this in jquery “window.parent.document.getElementById('parentPrice').innerHTML”?

I have an iframe and I wrote this code

window.parent.document.getElementById('parentPrice').innerHTML

to access parent element. How to get the same result using jquery?
UPDATE: Or how to access iFrame parent page using jquery?

Solution
To find in the parent of the iFrame use:

$('#parentPrice', window.parent.document).html();

The second parameter for the $() wrapper is the context in which to search. This defaults to document.

Courtesy : http://stackoverflow.com/questions/726816/how-to-write-this-in-jquery-window-parent-document-getelementbyidparentprice

Thursday, January 13, 2011

Common pitfalls in Javascript

When you defined script tag in JS

Define it as follows
<script type="text/javascript" src="jquery.js"></script>

And not as
<script type="text/javascript" src="jquery.js"/>


In the second case, it'll not interpret the script tag appropriately and the function defined inside <script>