Monday, September 29, 2014

Spring Interview Question: How to make Spring beans of type prototype by default.


Spring Interview Question: How to make Spring beans of type prototype by default.

In spring springs are of 5 types,

1. Singleton (Default)
2. Prototype
3. Request Scope
4. Session Scope
5. Global Scope

Singleton: there will be only one instance of a bean will exist in the Spring context.

Prototype beans: there will be seperate bean to fullfill all dependencies in a spring context, in other words more than one instances of bean will exist in spring context.

By default all beans are of singleton type.

Recently in an interview, a question was asked to one of my friend, what are the types of bean in spring and what is default type.

The above explanation is pretty sufficient to answer this, but the next subsequent question was a bit trickky, "How can you make all the beans in spring prototype" or "How can you make default type of beans prototype in spring".

This question can only be answered if one is fully aware of spring bean lifecycle. This can be achieved by implementing BeanFactoryPostProcessor and overriding postProcessBeanFactory method.

Below is the code snippet to do this.

public class PrototypePostProcessor implements BeanFactoryPostProcessor {

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
for(String bean : beanFactory.getBeanDefinitionNames() ) {
beanFactory.getBeanDefinition(bean).setScope("prototype");
}
}
}

Hope this will help.

Feel free post your suggestions in comments.

Wednesday, January 29, 2014

Exception handling in java

Exception handling is one of important aspect of programming. In java, many developers catch Exception as below

try{
// Code 
} catch (Exception ex) {}

Which is wrong because it catches RuntimeException or un-checked exceptions as well.

Few things which a developer needs to take care while exception handling are as below:
  • Always do resource clean up, use finally block for resource clean up. like closing database or network connections.
  • Do not use Parent Exception class or Throwable (untill and unless necessary), because it handles un checked exceptions as well.
  • log exceptions just once, don't log exceptions multiple times in multiple layers.
  • Do not suppress or ignore exceptions.

Hope this will help.

Sunday, September 29, 2013

how to select a schema and list all tables in mysql?

In this post i will explain how to select a schema and list down all tables in mysql DB.

First login to mysql command using  below command,

c:\mysqlDB\bin>mysql -u -p
Enter your password:

and then by use command select schema as below,

mysql>use test;

this command will select schema. Now use show tables command to list all tables.

mysql> show tables;

this will list down all tables in test schema, as shown in below screenshot.


How to check all the schemas present in mysql?

In mysql how to check all the schemas present?

First login using root user, and then use show databases command which will list down all the schemas present on server.

mysql> show databases;

this command will list down all the schemas/databses present on server, as shown in attached screenshot.
















Hope this will help some of you.

Tuesday, February 26, 2013

Singleton Design Pattern in java

Singleton Design Pattern in Java

One of the most frequently asked question in java interviews. Interview will start discussion about singleton by “what is singleton design pattern” or “what all design patterns you have used or knowledge about”. Once you tell them the definition of singleton they will ask for writing a class with singleton implementation and will be followed by related question. Overall it depends on how you handle these questions. Here I will try to explain all the questions which I was asked in interviews.

Singleton definition: This design pattern ensures that for every singleton class there will be only one instance present in JVM. This design pattern involves only one class, which has its own private reference and provide a method to access it from outside so that this same instance will be used every time.

There are number of ways to implement it, but I will explain just 2 ways which are simplest and least confusing.
1. Early instantiation using static keyword.

/*Early instantiation using static field */
class SingletonExample {
private static SingletonExample instance = new SingletonExample();

private SingletonExample() {
System.out.println("SingletonExample(): Initializing instance eagerly");
}

public static SingletonExample getInstance() {    
return instance;
}
}

By method instance will be created when the class first get loaded by classloader.

2. Lazy initialization using synchronization
/*Lazy instantiation*/
class SingletonEx {
private static SingletonEx instance;
private SingletonEx() {
System.out.println("SingletonEx (): Initializing instance");
}

public static SingletonEx getInstance() {
if (instance == null) {
synchronized(SingletonEx.class) {
if (instance == null) {
System.out.println("getInstance(): First time getInstance was invoked!");
instance = new SingletonEx();
}
}
}
return instance;
}
}

By this method instance will be created when instance was called for the first time by calling getInstance() method, and here we are doing this using double locking mechanism.

We are using synchronization to ensure that in case if two different threads access getInstance method simultaneously, it will not end up creating two different instances. 

As synchronization is very expensive when we talk about performance, that is why synchronized block is placed inside the conditional block which will be executed only when instance is null/not initialized.


This is all about Singleton, if you feel i have missed some aspect or question about singleton, pls let me know. Suggestions are always welcome ;-)

Tuesday, February 19, 2013

VI editor on Unix and Linux commands for beginners

For software developers its normal to work on UNIX or Linux environment, because most of the time Prod servers are deployed on Unix machines.

VI is just like notepad in Windows, but it is very powerful. Most of the times we use very limited functions of it. I myself also know only those command which i require to get my work done.

Below are the commands which we use very frequently.

Open a file: vi

If you want to open a file in read-only mode use: vi -R

There are few mode of VI editors like command mode, insertion mode, replace mode and append mode.

All below commands work in command mode, other modes are for writing code to file.

Insertion mode(i - insert before cursor), replace mode(r replace 1 char, R), Append Mode (a - append after cursor).

To come back to command mode from any other mode just press ESC.

Commands for deletion:

dw : deletes a word under cursor
db : deletes word before cursor
dd: deletes current line
ndd: deletes n lines
x - deletes character under cursor

Navigation:

shift + g: last line of file
0 : start of line
$ : end of file
e : end of next word
w: start of next word

Exiting VI file:

:wq - save the changes and exit
:q! - discard the changes and exit
:wq! - save changes from read-only file and exit
:w - save changes to file.

Searching contents in VI editor:
?keyword : searches keyword in file from bottom to top.
/keyword : searches keyword in file from top to bottom.
Navigation while searching
n for next occurrence and N for previous occurrence.

UNDO Command:
u: undo last command

yy (yank)'copies' line which may then be put by the p(put) command. (Precede with a count for multiple lines eg: nyy)

These are sufficient for working on VI editor.. I will keep on updating this list, as i will come across or learn new command.

You are also requested to leave comments if want to add something to this post.

Saturday, November 17, 2012

HTML hide a row or column of table dynamically

This is a normal html trick or tip to hide or show an html element. use below mentioned javascript to hide or show such elements.

document.getElementById(id).style.display='none';
document.getElementById(id).style.display='block';

for example: if we want to hide a row of html table based on click of a button,

Col11Col12
Col21Col22



function hideRow(id) {
document.getElementById(id).style.display='none';
}

<table border="1" cellpadding="1" cellspacing="0" style="width: 200px;">
<tr id="row1"><td scope="col">Col11</td><td>Col12</td></tr>
<tr><td>Col21</td><td>Col22</td></tr>
</table>
<input onclick="hideRow('row1') type="button" value="Hide Row1" />

Replace < with < and > with > sign.

function hideRow is accepting id of row which you want to hide, inside the method we are setting CSS style display to none which hides an html element.

likewise you can do for column and other elements by replacing id with the id of element.

Thursday, October 18, 2012

How to sort a Map based on values in java?

Once i had an requirement to sort an HashMap based on the values, how i achieved this is explained below,

First stored the entryset as an ArrayList and then used Comparator to sort that List. After that created new LinkedHashMap, as LinkedHashMap preserves the insertion order, so inserted the List values in LinkedHashMap, which is now sorted based on Values.

==============================================
Map unSortedMap = new HashMap();
unSortedMap.put("w", "e");
unSortedMap.put("d", "z");
unSortedMap.put("q", "g");
unSortedMap.put("f", "t");
unSortedMap.put("s", "m");

List> list = new LinkedList>();
for (Entry entry : unSortedMap.entrySet()) {
System.out.println(entry.getKey() + " -- " + entry.getValue());
list.add(entry);
}

Collections.sort(list, new Comparator>() {
public int compare(Entry o1,
Entry o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Map sortedMap = new LinkedHashMap();
for (Entry entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
for (Entry entry : sortedMap.entrySet()) {
System.out.println(entry.getKey() + " -- " + entry.getValue());
}
==============================================

this will be the output
==========UnSorted Map===============
f -- t
w -- e
d -- z
s -- m
q -- g
==========Sorted Map===============
w -- e
q -- g
s -- m
f -- t
d -- z

Note: This will fail if you use null values in Map. I am trying to figure out the solution for that, if you have any then please comment.

Wednesday, October 17, 2012

How to set classpath in java on Unix and Windows?


One of the most basic issue faced by novice learners..

Classpath in java points to a directory or list of directory where class loader searches for referenced classes to load. In java classpath can be specified using CLASSPATH environmental variable (which is case insensitive) or -cp option of java command.

Usually people got confuse between CLASSPATH and PATH, both are environment variables but in PATH is looks for commands while in CLASSPATH it looks for class files.

Setting CLASSPATH on Windows:
On windows you need to set CLASSPATH environment variable, name "CLASSPATH" is case insensitive.

To set an environment variable you need to login as administrator of that system and then right click on "my computer" -> advanced tab -> environment variables and then click on new and then specify name as CLASSPATH and value as  "JAVA_HOME\lib;."

To verify the value type "echo %CLASSPATH" on command prompt.

Setting CLASSPATH on unix:
use the below command to set classpath
setenv CLASSPATH=/home/test/first:/home/test/second

Now run program using below command,
java Test

Now JVM will search Test.java first in /home/test/first and then in /home/test/second.


Friday, July 27, 2012

Difference between load and get method in Hibernate?

In this post i am going to explain the difference between load and get methods to retrieve an object from database,


Use load when you are sure that object with given id is present in database, and if you are not sure in that case use get to retrieve object from database.


Load throws ObjectNotFoundException, if object is not found on cache as well as in database, while get returns null, when object is not found on cache or database.


load returns proxy to object which is lazy initialized, that means it will not hit database immediately, it will fetch the object from database when for the first time non identifier property is access.. get method returns a fully initialized object and hits database immediately.


Performance wise load is slightly better than get, due to lazy initialization.