1. Up-gradation to class loader architecture to avoid deadlocks in non-hierarchical class-loader topologies.
2. A method has been added to free the underlying resources, such as open files, held by a URLClassLoader.
3. A lightweight fork/join framework, flexible and reusable synchronization barriers, transfer queues, a concurrent-reference HashMap, and thread-local pseudo-random number generators.
4. Upgraded to supported version of Unicode 6.0 for more from internationalization.
5. the java.util.Locale class to support IETF BCP 47 and UTR 35 now.
6. Now there will be a two separate locale for user and user-interface.
7. New APIs for filesystem access, scalable asynchronous I/O operations, socket-channel binding and configuration, and multicast datagrams
8. New fully functional file system provider NIO.2 for zip/jar archiving.
9. JDBC upgraded to 4.1 and Rowset to 1.1
10. XML stack is upgraded to new stable version for more on web.
11. JSR 292 providing support for dynamically typed language.
Java, Struts, Spring, Hibernate, Unix,IT, Software, Jobs, Interview, Aptitude, Learning, Algorithms
Friday, November 19, 2010
Thursday, November 18, 2010
OutOfMemoryError: PermGen space while reloading webapp in tomcat
This annoying error of PermGen space OOMs when reloading the webapp in tomact is because in tomcat the class loader only loads the classes and this class loader and loaded classes are never garbage collected. Each time you reload your webapp, copies of classes will be added to memory, basically the permanent heap space used by tomcat. This eventually makes tomcat run out of memory to further carry out operation.
This is common and can happen with other containers also until unless in some version the owner have made changes to take care of this. Try reloading the application again and again until unless your container cry of Out of Memory Error. What we can do in such a situation is to restart the container which basically clean up the heap and load the application again.
Additionally try no putting your JDBC and commons jar in the WEB-INF. Instead you can put them in the TOMCAT-HOME/common/lib folder because these are already bootstrapped by tomcat. If you face issue of 'No suitable driver' Exception after placing your jdbc jar in tomcat common/lib, try adding you jndi db definition in context.xml like
<\Context path="/test" reloadable="true" debug="1">
<\Resource name="jdbc/db" auth="Container" type="javax.sql.DataSource" maxActive="30" maxIdle="3"
maxWait="10000" username="testing" password="testing" driverClassName="net.sourceforge.jtds.jdbc.Driver" url="jdbc:testdburl;lastupdatecount=true" />
This is common and can happen with other containers also until unless in some version the owner have made changes to take care of this. Try reloading the application again and again until unless your container cry of Out of Memory Error. What we can do in such a situation is to restart the container which basically clean up the heap and load the application again.
Additionally try no putting your JDBC and commons jar in the WEB-INF. Instead you can put them in the TOMCAT-HOME/common/lib folder because these are already bootstrapped by tomcat. If you face issue of 'No suitable driver' Exception after placing your jdbc jar in tomcat common/lib, try adding you jndi db definition in context.xml like
<\Context path="/test" reloadable="true" debug="1">
<\Resource name="jdbc/db" auth="Container" type="javax.sql.DataSource" maxActive="30" maxIdle="3"
maxWait="10000" username="testing" password="testing" driverClassName="net.sourceforge.jtds.jdbc.Driver" url="jdbc:testdburl;lastupdatecount=true" />
Sunday, October 31, 2010
equals and hashcode
Object equals will just compare references and hashcode is native which always return difference integer even if objects are same but different instances. So of you override equals and not hashcode for any object being used as a key in hashmap, then I will not get value corresponding to key because it wont be able to find hashcode for new instance of key. As it will look into the wrong bucket (new bucket) if I override hashcode and not equals, even there I wont be able to get the value because I can find the bucket but objects equal check references which will be different for stored object and my key object (new instance of old key object).
DB Connection class
DriverManager.getConnection (url, user, pwd).getClass().getName().equals("java.sql.Connection") = false
This is false because left hand side will return a class of the underlying database connection class i.e. oracle.jdbc.driver.OracleConnection in case of oracle. So this will be a instance of java.sql.Connection but can not be equal.
This is false because left hand side will return a class of the underlying database connection class i.e. oracle.jdbc.driver.OracleConnection in case of oracle. So this will be a instance of java.sql.Connection but can not be equal.
Cut rectangular cake half
Given a rectangular cake with rectangular piece removed (any size, any orientation), how would you cut remainder cake in two equal haves with one straight cut of knife.
Serializable Singleton
In a class write below code to prevent singleton class from losing its behavior if you make it serializable.
protected Object readResolve(){
return singletonObj;
}
Deserialization creates another object instance, so to avoid that situation this needs to be done.
protected Object readResolve(){
return singletonObj;
}
Deserialization creates another object instance, so to avoid that situation this needs to be done.
Java Threading
public static void myMethod(){
synchronized(this){
//do stuff
}
}
This will not get a class level lock, many threads can enter this static method of class and with individual object lock can execute code in it.
public static synchronized void myMethod() {
//do stuff
}
-----is equivalent to-----
public void myMethod(){
synchronized(MyClass.class){
//do stuff
}
}
In both the case, threads will obtain a class level lock butt there will just be a difference of timing for how long lock is being obtained.
1. Threads that synchronize on the same object will block each other. Threads that synchronize on different objects will not.
2. A static synchronized method and a non-static synchronized method will not block each other, ever. The static method locks on a class instance while non-static method locks on this instance these actions do not interfere with each other at all.
3. Threads calling static synchronized methods in the same class will always block each other - they all lock the same class instance.
4. Threads calling non-static synchronized methods in the same class will only block each other if they are invoked using same instance.
5. A thread can acquire more that one lock. A thread can enter a synchronized method, acquiring a lock and then immediately invoke a synchronized method on a different object, acquiring that locak as well. A thread acquires a lock and then attempts to call a synchronized method on the same object, no problem because thread already have lock of this object.
6. If a class has both synchronized and non-synchronized methods, multiple threads can still access the class's non-synchronized methods.
Thread Join-
If you have a thread B that can't do its work until another thread A has completed its work, then you want B to join thread A.
This means that thread B will not become runnable until thread A has finished.
Thread t = new Thread();
t.start();
t.join();
This code take currently running thread and joins it to the end of thread t. Current thread become runnable after thread t is no longer alive.
synchronized(this){
//do stuff
}
}
This will not get a class level lock, many threads can enter this static method of class and with individual object lock can execute code in it.
public static synchronized void myMethod() {
//do stuff
}
-----is equivalent to-----
public void myMethod(){
synchronized(MyClass.class){
//do stuff
}
}
In both the case, threads will obtain a class level lock butt there will just be a difference of timing for how long lock is being obtained.
1. Threads that synchronize on the same object will block each other. Threads that synchronize on different objects will not.
2. A static synchronized method and a non-static synchronized method will not block each other, ever. The static method locks on a class instance while non-static method locks on this instance these actions do not interfere with each other at all.
3. Threads calling static synchronized methods in the same class will always block each other - they all lock the same class instance.
4. Threads calling non-static synchronized methods in the same class will only block each other if they are invoked using same instance.
5. A thread can acquire more that one lock. A thread can enter a synchronized method, acquiring a lock and then immediately invoke a synchronized method on a different object, acquiring that locak as well. A thread acquires a lock and then attempts to call a synchronized method on the same object, no problem because thread already have lock of this object.
6. If a class has both synchronized and non-synchronized methods, multiple threads can still access the class's non-synchronized methods.
Thread Join-
If you have a thread B that can't do its work until another thread A has completed its work, then you want B to join thread A.
This means that thread B will not become runnable until thread A has finished.
Thread t = new Thread();
t.start();
t.join();
This code take currently running thread and joins it to the end of thread t. Current thread become runnable after thread t is no longer alive.
Fibonacci
public void fibonacci(){
int curr = 1;
int prv = 0;
int prvHolder=0;
for(int c = 0; c <= 30; c++){
Sysout (curr);
prvHolder=prv;
prv=curr;
curr += prvHolder;
}
}
int curr = 1;
int prv = 0;
int prvHolder=0;
for(int c = 0; c <= 30; c++){
Sysout (curr);
prvHolder=prv;
prv=curr;
curr += prvHolder;
}
}
Prime factorization
public void primeFactor (int num){
List factors = new ArrayList();
for (int i = 2; i <= n; i++){
while (n % i == 0){
factors.add(i);
n /= i;
}
}
}
List factors = new ArrayList();
for (int i = 2; i <= n; i++){
while (n % i == 0){
factors.add(i);
n /= i;
}
}
}
Greatest Common Divisor
public int gcd (int p, int q){
if (q=-=0){
return p;
}
return gcd (q, p%q);
}
if (q=-=0){
return p;
}
return gcd (q, p%q);
}
Annotation
It releives java developer from sumbersome configuration. Declarative programming style - programmer says what should be done & tools emit the code to do it. These are meta-tag information.
DisplayTag
<display:table export="true" is="data" name="sessionScope.UserForm.forbesList" requestURI="/userAction.do" poagesize="10" >
<display:column property="rank" title="Rank" sortable="true" />
....
</display:table>
export - to export table data as excel, csv or xml
sortable - makes column sortable by providing clickable title
pagesize - for pagination
<display:column property="rank" title="Rank" sortable="true" />
....
</display:table>
export - to export table data as excel, csv or xml
sortable - makes column sortable by providing clickable title
pagesize - for pagination
Hibernate mapping
Event table (LocationID - FK, EventID - PK)
Attendee Table (AttendeeID - PK)
SpeakerID (SpeakerID - PK, EventID - FK)
Event_Attendee (EventID, AttendeeID)
An event can have many attendee and speakers. An attendee can attend many events. One location can also have many events.
<hibernate-mapping>
<class name="Event" table="events">
<id name="id" column="uid" type="long">
<generator class="increment">
</id>
<property name="name" type="string" length="100"/>
<many-to-one name="location" column="locationID" class="Location"/>
<set name="speakers" cascade="all">
<key column="eventID"/>
<one-to-many class=Speakers"/>
</set>
<set name="attendee" table="event_attendee" cascade="all">
<key column="eventID"/>
<many-to-many column="AttendeeID" class=Attendee"/>
</set>
</class>
</hibernate-mapping>
Attendee Table (AttendeeID - PK)
SpeakerID (SpeakerID - PK, EventID - FK)
Event_Attendee (EventID, AttendeeID)
An event can have many attendee and speakers. An attendee can attend many events. One location can also have many events.
<hibernate-mapping>
<class name="Event" table="events">
<id name="id" column="uid" type="long">
<generator class="increment">
</id>
<property name="name" type="string" length="100"/>
<many-to-one name="location" column="locationID" class="Location"/>
<set name="speakers" cascade="all">
<key column="eventID"/>
<one-to-many class=Speakers"/>
</set>
<set name="attendee" table="event_attendee" cascade="all">
<key column="eventID"/>
<many-to-many column="AttendeeID" class=Attendee"/>
</set>
</class>
</hibernate-mapping>
Find circular linked list
Start with two pointers. Increase one ptr by 1 and second ptr by 2. If they meet then list is circular.
Reverse a string
To reverse a string in java, tokenize the string and starting printing from len-1 to 0.
Summing column value in SQL
To sum the columns' of a record in table use '+' operator like -
select col1+col2 from table test
select col1+col2 from table test
Saturday, September 25, 2010
Do you work with presentation
If you work with powerpoint presentation you must see this clip to get best out of it.
http://www.youtube.com/watch?v=lpvgfmEU2Ck&feature=player_embedded
http://www.youtube.com/watch?v=lpvgfmEU2Ck&feature=player_embedded
Saturday, August 14, 2010
Macrodef in Ant Script
Very frequently we invoke the same task repeatedly with a small variance. Mostly, we parameterize the variance, then such tasks can be refactored and invoked with different argument repeatedly, just like a Java method call that is invoked with different arguments. Prior to Ant 1.6, the and tasks came in handy. For most part these two core tasks are similar, except the task allows invoking targets in another build file whereas restricted the invoked targets to the local file.
The point to consider is re-parses the build file and re-runs the targets, even though all that changes from one call to another is, in most cases, just the parameter values. Since Ant 1.6 a smarter alternative is available: the task. It offers all the benefits of without the overhead of reparsing. It offers additional features such as ordered execution of nested tasks using the construct. Optional attributes can be supplied with default values, and the caller may omit them.
Sample Code
The point to consider is
Sample Code
Sunday, August 1, 2010
Clustering
J2EE application server vendors define a cluster as a group of machines working together to transparently provide enterprise services (support for JNDI, EJB, JSP, HttpSession and component failover, and so on). They leave the definition purposely vague because each vendor implements clustering differently. At one end of the spectrum rest vendors who put a dispatcher in front of a group of independent machines, none of which has knowledge of the other machines in the cluster. In this scheme, the dispatcher receives an initial request from a user and replies with an HTTP redirect header to pin the client to a particular member server of the cluster. At the other end of the spectrum reside vendors who implement a federation of tightly integrated machines, with each machine totally aware of the other machines around it along with the objects on those machines.
Purpose -
1. Reducing downtime - Another machine in cluster transperently takeover in case of failure of a particular machine.
2. Scalibility - More server can be added to handle the increased users.
3. Spreading load - Different machines in the cluster will be responsible for the indivudual module of the application hence decreasing the load on individual machine.
A cluster is a group of application servers that transparently run your J2EE application as if it were a single entity. To scale, you should include additional machines within the cluster. To minimize downtime, make sure every component of the cluster is redundant.
For More Information - Java World - Clustering
Purpose -
1. Reducing downtime - Another machine in cluster transperently takeover in case of failure of a particular machine.
2. Scalibility - More server can be added to handle the increased users.
3. Spreading load - Different machines in the cluster will be responsible for the indivudual module of the application hence decreasing the load on individual machine.
A cluster is a group of application servers that transparently run your J2EE application as if it were a single entity. To scale, you should include additional machines within the cluster. To minimize downtime, make sure every component of the cluster is redundant.
For More Information - Java World - Clustering
Runtime exception in JSP
How does JSP handle run-time exceptions?
Runtime exceptions are easy to handle in a JSP application, because they are stored one at a time in the implicit object named exception. You can use the exception object in a special type of JSP page called an error page, where you display the exception's name and class, its stack trace, and an informative message for your user.
We can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:
<\%@ page errorPage="error.jsp" %>
redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing.
Within error.jsp, if you indicate that it is an error-processing page, via the directive:
<\%@ page isErrorPage="true" %>
the Throwable object describing the exception may be accessed within the error page via the exception implicit object.
Note: You must always use a relative URL as the value for the errorPage attribute.
Runtime exceptions are easy to handle in a JSP application, because they are stored one at a time in the implicit object named exception. You can use the exception object in a special type of JSP page called an error page, where you display the exception's name and class, its stack trace, and an informative message for your user.
We can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:
<\%@ page errorPage="error.jsp" %>
redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing.
Within error.jsp, if you indicate that it is an error-processing page, via the directive:
<\%@ page isErrorPage="true" %>
the Throwable object describing the exception may be accessed within the error page via the exception implicit object.
Note: You must always use a relative URL as the value for the errorPage attribute.
Simply Singleton
Singleton Design Pattern is the among the most widely used design patterns in IT world. It addresses the problem of creating exactly one instance of a class which can be globally accessible. This instance or object of class is singleton.
Singletons maintain a static reference to the sole singleton instance and return a reference to that instance from a static instance() method.
public class MySingleton {
private static MySingleton instance = null;
protected MySingleton() {
// Exists only to defeat instantiation.
}
public static MySingleton getInstance() {
if(instance == null) {
instance = new MySingleton();
}
return instance;
}
}
public class SingletonInstantiator {
public SingletonInstantiator() {
ClassicSingleton instance = ClassicSingleton.getInstance();
ClassicSingleton anotherInstance =
new ClassicSingleton();
...
}
}
This technique of implementing Singleton is known as lazy loading as the object is instantiated when getInstance() method is called for the first time.
Why constructor is protected?? - First thing first. Protected constructor can be called by subclasses or by other classes in the same package. So keeping the MySingleton and SingletonInstantiator in the same package allows the former class to create instance of singleton class. So what should be done? First, make the constructor of MySingleton private, but then this class can not be subclassed. Second, declare MySingleton as final. Third, put your singleton class in explicit package.
A third interesting point about ClassicSingleton: it's possible to have multiple singleton instances if classes loaded by different classloaders access a singleton. That scenario is not so far-fetched; for example, some servlet containers use distinct classloaders for each servlet, so if two servlets access a singleton, they will each have their own instance.
Fourth, if ClassicSingleton implements the java.io.Serializable interface, the class's instances can be serialized and deserialized. However, if you serialize a singleton object and subsequently deserialize that object more than once, you will have multiple singleton instances.
Finally, and perhaps most important, Example 1's ClassicSingleton class is not thread-safe. If two threads—we'll call them Thread 1 and Thread 2—call ClassicSingleton.getInstance() at the same time, two ClassicSingleton instances can be created if Thread 1 is preempted just after it enters the if block and control is subsequently given to Thread 2. The solution to this is to synchronize the getInstance() method in our MySingleton class or just the block where we are creating the instance to improve performance by locking the object for short time.
For more information -
Java World - Simply Singleton
Singletons maintain a static reference to the sole singleton instance and return a reference to that instance from a static instance() method.
public class MySingleton {
private static MySingleton instance = null;
protected MySingleton() {
// Exists only to defeat instantiation.
}
public static MySingleton getInstance() {
if(instance == null) {
instance = new MySingleton();
}
return instance;
}
}
public class SingletonInstantiator {
public SingletonInstantiator() {
ClassicSingleton instance = ClassicSingleton.getInstance();
ClassicSingleton anotherInstance =
new ClassicSingleton();
...
}
}
This technique of implementing Singleton is known as lazy loading as the object is instantiated when getInstance() method is called for the first time.
Why constructor is protected?? - First thing first. Protected constructor can be called by subclasses or by other classes in the same package. So keeping the MySingleton and SingletonInstantiator in the same package allows the former class to create instance of singleton class. So what should be done? First, make the constructor of MySingleton private, but then this class can not be subclassed. Second, declare MySingleton as final. Third, put your singleton class in explicit package.
A third interesting point about ClassicSingleton: it's possible to have multiple singleton instances if classes loaded by different classloaders access a singleton. That scenario is not so far-fetched; for example, some servlet containers use distinct classloaders for each servlet, so if two servlets access a singleton, they will each have their own instance.
Fourth, if ClassicSingleton implements the java.io.Serializable interface, the class's instances can be serialized and deserialized. However, if you serialize a singleton object and subsequently deserialize that object more than once, you will have multiple singleton instances.
Finally, and perhaps most important, Example 1's ClassicSingleton class is not thread-safe. If two threads—we'll call them Thread 1 and Thread 2—call ClassicSingleton.getInstance() at the same time, two ClassicSingleton instances can be created if Thread 1 is preempted just after it enters the if block and control is subsequently given to Thread 2. The solution to this is to synchronize the getInstance() method in our MySingleton class or just the block where we are creating the instance to improve performance by locking the object for short time.
For more information -
Java World - Simply Singleton
How to get Remote Machine Name
In order to get machine name or the computer name of the remote system, the system which is send some http request to your server, you just need to get IP from the request and using that IP and the InetAddress class of java.net package, we can very well get the name of that machine. Here is the code.
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
byte ipAddr[] = {0,0,0,0};
String ipAddress = req.getRemoteAddr();
if(ipAddress != null && !ipAddress.equals("")){
StringTokenizer tokenize = new StringTokenizer(ipAddress,".");
int iLen = tokenize.countTokens();
for(int i = 0 ; i < iLen;i++){
int temp = Integer.parseInt(tokenize.nextToken());
ipAddr[i] = (byte)temp;
}
InetAddress nIpAddress = InetAddress.getByAddress(ipAddr);
if(nIpAddress != null && nIpAddress.isReachable(5000) && nIpAddress.isSiteLocalAddress()){
System.out.println("Servlet - "+InetAddress.getByAddress(ipAddr).getHostName());
req.setAttribute("IP", InetAddress.getByAddress(ipAddr).getHostName());
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
byte ipAddr[] = {0,0,0,0};
String ipAddress = req.getRemoteAddr();
if(ipAddress != null && !ipAddress.equals("")){
StringTokenizer tokenize = new StringTokenizer(ipAddress,".");
int iLen = tokenize.countTokens();
for(int i = 0 ; i < iLen;i++){
int temp = Integer.parseInt(tokenize.nextToken());
ipAddr[i] = (byte)temp;
}
InetAddress nIpAddress = InetAddress.getByAddress(ipAddr);
if(nIpAddress != null && nIpAddress.isReachable(5000) && nIpAddress.isSiteLocalAddress()){
System.out.println("Servlet - "+InetAddress.getByAddress(ipAddr).getHostName());
req.setAttribute("IP", InetAddress.getByAddress(ipAddr).getHostName());
}
}
Java 1.5 - Nothing un-official about it!!
Features in Java 1.5
1. For/Each loop
Instead of looping with a numeric index, set a local variable to each item of a collection or array in order.
public void goThis(String[] strArray){
for(String obj:strArray){
System.out.println(obj);
}
}
2. Scanner Class - Scanner class is easily used to read the input from console.
Scanner inputScanner = new Scanner(System.in);
String s = inputScanner.nextLine();
int i = inputScanner.nextInt();
double d = inputScanner.nextDouble();
But you can also attach a Scanner to a File, a Socket, a Process, and more
3. Autoboxing - To insert java primitive into tables, list or anything expecting Object can be done using Java wrappers.
Although its a useful feature of java5 still its a performance hit because -
1. Every insert converts to wrapper type.
2. Every retrieval converts to primitive type
List arrayList = new ArrayList();
int i = 12;
arrayList.add(i);
int num = arrayList.get(0);
arrayList.add(num+1);
4. Varargs - A way to pass any number of a particular type of argument to the method. It becomes an array of that type. It should be te last in the list of arguments like
public static String method (String name, int ... numbers);
Sample code -
public class MathUtils {
public static int min(int ... numbers) {
int minimum = Integer.MAX_VALUE;
for(int number: numbers) {
if (number < minimum) {
minimum = number;
}
}
return(minimum);
}
public static void main(String[] args) {
System.out.printf("Min of 2 nums: %d.%n",min(2,1));
System.out.printf("Min of 7 nums: %d.%n",min(2,4,6,8,1,2,3));
}
1. For/Each loop
Instead of looping with a numeric index, set a local variable to each item of a collection or array in order.
public void goThis(String[] strArray){
for(String obj:strArray){
System.out.println(obj);
}
}
2. Scanner Class - Scanner class is easily used to read the input from console.
Scanner inputScanner = new Scanner(System.in);
String s = inputScanner.nextLine();
int i = inputScanner.nextInt();
double d = inputScanner.nextDouble();
But you can also attach a Scanner to a File, a Socket, a Process, and more
3. Autoboxing - To insert java primitive into tables, list or anything expecting Object can be done using Java wrappers.
Although its a useful feature of java5 still its a performance hit because -
1. Every insert converts to wrapper type.
2. Every retrieval converts to primitive type
List
int i = 12;
arrayList.add(i);
int num = arrayList.get(0);
arrayList.add(num+1);
4. Varargs - A way to pass any number of a particular type of argument to the method. It becomes an array of that type. It should be te last in the list of arguments like
public static String method (String name, int ... numbers);
Sample code -
public class MathUtils {
public static int min(int ... numbers) {
int minimum = Integer.MAX_VALUE;
for(int number: numbers) {
if (number < minimum) {
minimum = number;
}
}
return(minimum);
}
public static void main(String[] args) {
System.out.printf("Min of 2 nums: %d.%n",min(2,1));
System.out.printf("Min of 7 nums: %d.%n",min(2,4,6,8,1,2,3));
}
Collect all about Garbage Collection
>>> The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused.
>>> An unreachable object is subjected to gc. Unreachable objects are those which can not be referenced.
>>> Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory.
>>> Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists.
>>> In Java, it is good idea to explicitly assign null into a variable when no more in use.
>>> In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.
>>> Garbage collection is an automatic process and can't be forced.
>>> gc thread is a dameon thread.
>>> An unreachable object is subjected to gc. Unreachable objects are those which can not be referenced.
>>> Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory.
>>> Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists.
>>> In Java, it is good idea to explicitly assign null into a variable when no more in use.
>>> In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.
>>> Garbage collection is an automatic process and can't be forced.
>>> gc thread is a dameon thread.
Except exceptions!!
Exception in layman term is abnormal behaviour of your program. A bunch of things can lead to exceptions, including hardware failures, resource exhaustion, and good old bugs. When an exceptional event occurs in Java, an exception is said to be thrown. The code that’s responsible for doing something about the exception is called an exception handler, and it catches the thrown exception.
>>> Order of catch block matters.
>>> The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
>>> A checked exception is some subclass of Exception (or Exception itself) excluding class RuntimeException and its subclasses, which are forced by compiler to be checked. Example: IOException.
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. The compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBoundsException. Errors are often irrecoverable conditions.
>>> Throwable is the base class of Error and Exception.
>>> The throw keyword denotes a statement that causes an exception to be initiated. The throws keyword is a modifier of a method that denotes that an exception may be thrown by the method.
>>> Error's are generally system's error and Excepion are programmer's error.
>>> Finally block get executed whether exception is thrown or not. Even if there is return statement in try block, finally block get executed after the return statement.
Defensive Coding for NPE -
1. If name is null
don't do - if(name.equals("Peter")) - chances to get NPE
do - if("Peter".equals(name))
2. Always return empty collection instead of null like
return Collections.EMPTY_LIST;
3. Always check for null before carrying out operation on the object and define alternate course of action.
>>> Order of catch block matters.
>>> The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
>>> A checked exception is some subclass of Exception (or Exception itself) excluding class RuntimeException and its subclasses, which are forced by compiler to be checked. Example: IOException.
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. The compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBoundsException. Errors are often irrecoverable conditions.
>>> Throwable is the base class of Error and Exception.
>>> The throw keyword denotes a statement that causes an exception to be initiated. The throws keyword is a modifier of a method that denotes that an exception may be thrown by the method.
>>> Error's are generally system's error and Excepion are programmer's error.
>>> Finally block get executed whether exception is thrown or not. Even if there is return statement in try block, finally block get executed after the return statement.
Defensive Coding for NPE -
1. If name is null
don't do - if(name.equals("Peter")) - chances to get NPE
do - if("Peter".equals(name))
2. Always return empty collection instead of null like
return Collections.EMPTY_LIST;
3. Always check for null before carrying out operation on the object and define alternate course of action.
Threads revisited
>>> Each threads have separate stack and share common java heap. Stack elements are method and method level variables.
>>> Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time.
>>> Daemon threads are threads with low priority and runs in the back ground doing the garbage collection operation for the java runtime system. The setDaemon() method is used to create a daemon thread.
>>> The wait(), notify() and notifyAll() methods are used to provide an efficient way for thread inter-communication.
>>> After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
>>> Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
Implement Runnable vs Extends Thread
1. Implementing Runnable allows multiple inheritance.
2. If you are not extending any class, better extend Thread class as it will save few lines of coding.
3. Performance wise, there is no distinguishable difference.
What is Thread Pool? How it is implemented?
>>> Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time.
>>> Daemon threads are threads with low priority and runs in the back ground doing the garbage collection operation for the java runtime system. The setDaemon() method is used to create a daemon thread.
>>> The wait(), notify() and notifyAll() methods are used to provide an efficient way for thread inter-communication.
>>> After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
>>> Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
Implement Runnable vs Extends Thread
1. Implementing Runnable allows multiple inheritance.
2. If you are not extending any class, better extend Thread class as it will save few lines of coding.
3. Performance wise, there is no distinguishable difference.
What is Thread Pool? How it is implemented?
Abstract classes vs Interface
Differences -
1. If new method added to interface all implementing classes needs to add that and give an implementation whereas its not the case with abstract class.
2. Class implementing an interface needs to implement all methods which is not the case with abstract classes.
3. An Interface can only have public members whereas an abstract class can contain private as well as protected members.
4. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.
5. Abstract class does not support Multiple Inheritance whereas an Interface supports multiple Inheritance.
6. Abstract class can have constructor which can be accessed by subclass.
Similarities -
1. Both can't be instantiated.
2. Fully abstract class and interface ares similar.
Which one to be used and when -
When we need implementing class to follow some rules in method signature, use interface. And when some common base functionality needs to be implemented then use abstract classes. Mostly interfaces are used when frequent design changes needs to be done.
1. If new method added to interface all implementing classes needs to add that and give an implementation whereas its not the case with abstract class.
2. Class implementing an interface needs to implement all methods which is not the case with abstract classes.
3. An Interface can only have public members whereas an abstract class can contain private as well as protected members.
4. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.
5. Abstract class does not support Multiple Inheritance whereas an Interface supports multiple Inheritance.
6. Abstract class can have constructor which can be accessed by subclass.
Similarities -
1. Both can't be instantiated.
2. Fully abstract class and interface ares similar.
Which one to be used and when -
When we need implementing class to follow some rules in method signature, use interface. And when some common base functionality needs to be implemented then use abstract classes. Mostly interfaces are used when frequent design changes needs to be done.
Immutable Object
Java has two Immutable classes - String and BigDecimal
Properties of Immutable java object -
1. Class as final so that no method can be overridden to provide mutable behavior to class.
2. All fields final and private
3. No setter or mutable methods
4. Normal getter methods
5. constructor to create the object of this class and that all fields should be passed as arguments.
public class MyImmutableClass{
private final String name;
private final int number;
public MyImmutableClass(String name, int number){
this.name=name;
this.number=number;
}
public int getNumber(){
return number;
}
public String getName(){
retutn name;
}
}
Properties of Immutable java object -
1. Class as final so that no method can be overridden to provide mutable behavior to class.
2. All fields final and private
3. No setter or mutable methods
4. Normal getter methods
5. constructor to create the object of this class and that all fields should be passed as arguments.
public class MyImmutableClass{
private final String name;
private final int number;
public MyImmutableClass(String name, int number){
this.name=name;
this.number=number;
}
public int getNumber(){
return number;
}
public String getName(){
retutn name;
}
}
String equals() method
Its about how String's equals() method works -
1. Firstly it compare references of two string objects to be compared. If references are same then two string object' value are equal and no need for further comparision.
2. If references are not equal, then it compare the value of two string object by comparing the string's on character by character basis.
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
1. Firstly it compare references of two string objects to be compared. If references are same then two string object' value are equal and no need for further comparision.
2. If references are not equal, then it compare the value of two string object by comparing the string's on character by character basis.
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
Some tits-bits
>>> String.split("delimeter") - This will split the string on delimeter passed and return a String array.
>>> Synchronizing a static method or static block of a class is obtaining the lock on the class instead of instance. The lock on class can also be obtained by
synchronize(ABC.class){
}
>>> String.indexOf("abc") - This will return the index in int of the first occurrence of the string 'abc' in the string.
>>> Convert String to Number - Use wrapper class like Integer, Long, Float, Double.
int i = Integer.parseInt(String);
or,
int i = Integer.valueOf(String).intValue();
>>> Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized.
>>> Swap two variables without using a third variable
int a=5,b=10;a=a+b; b=a-b; a=a-b;
>>> Java object are stored in Heap.
>>>To get system name using java code print -
System.out.println(InetAddress.getLocalHost().getHostName());
>>> Synchronizing a static method or static block of a class is obtaining the lock on the class instead of instance. The lock on class can also be obtained by
synchronize(ABC.class){
}
>>> String.indexOf("abc") - This will return the index in int of the first occurrence of the string 'abc' in the string.
>>> Convert String to Number - Use wrapper class like Integer, Long, Float, Double.
int i = Integer.parseInt(String);
or,
int i = Integer.valueOf(String).intValue();
>>> Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized.
>>> Swap two variables without using a third variable
int a=5,b=10;a=a+b; b=a-b; a=a-b;
>>> Java object are stored in Heap.
>>>To get system name using java code print -
System.out.println(InetAddress.getLocalHost().getHostName());
Overridding - let's visit it again
Overriding is directly related to OOP with inheritance and subclassing.
Why to override - It is used to modify the behavior by redefining the inherited method in the subclass.
Late binding of method - Java determines the method to be executed based on the type of actual object at runtime. At compile time no object is created yet, hence Java does not predetermine the method to be called at compile time just by looking at the method call. The decision of which method to call is delayed to the runtime as the type of actual object (that the reference variable will hold) is often not known at compile time. When a call is made to overridden method by the variable of superclass and object of subclass, then that method call is determined at runtime.
class MySuperClass{
public void method(){
System.out.println("Super class");
}
}
class MySubClass{
public void method(){
System.out.println("Sub class");
}
}
class MyImplClass{
public static void main(){
MySuperClass obj = new MySubClass();
obj.method();
/*this call is determined at runtime, whether to call super class method or sub class. This will print 'Sub Class', depending on the object used for call which will be created and available at runtime.*/
}
}
Rule for overriding -
1. Same method name along with same type and order of argument. If type and order of argument are not same than its considered as overloading.
2. Return type in java 5 can be narrower mean a subclass, can be returned in the overriding method, of the return type class of overridden method.
3. Access modifier must be less restrictive. This rule is imposed because Java assumes that you do subclassing for extending a class. If Java had allowed you to override a method to be more private, you could have easily made the public methods of superclass inaccessible (in subclass). Effectively you would have restricted the class instead of extending it. Since in Java subclassing is done only to extend a class, you are not allowed to restrict its behavior by overriding the methods to be more private. Private method are not accessible to the subclass hence does not make sense to override.
4. The overridden method may not throw any checked exceptions at all. If it throws, the exception must be either same as the exception thrown by the superclass method or the exception must be a subclass of the exception thrown by the superclass method.
5. final method of super class. Overridding method can be made final.
Why to override - It is used to modify the behavior by redefining the inherited method in the subclass.
Late binding of method - Java determines the method to be executed based on the type of actual object at runtime. At compile time no object is created yet, hence Java does not predetermine the method to be called at compile time just by looking at the method call. The decision of which method to call is delayed to the runtime as the type of actual object (that the reference variable will hold) is often not known at compile time. When a call is made to overridden method by the variable of superclass and object of subclass, then that method call is determined at runtime.
class MySuperClass{
public void method(){
System.out.println("Super class");
}
}
class MySubClass{
public void method(){
System.out.println("Sub class");
}
}
class MyImplClass{
public static void main(){
MySuperClass obj = new MySubClass();
obj.method();
/*this call is determined at runtime, whether to call super class method or sub class. This will print 'Sub Class', depending on the object used for call which will be created and available at runtime.*/
}
}
Rule for overriding -
1. Same method name along with same type and order of argument. If type and order of argument are not same than its considered as overloading.
2. Return type in java 5 can be narrower mean a subclass, can be returned in the overriding method, of the return type class of overridden method.
3. Access modifier must be less restrictive. This rule is imposed because Java assumes that you do subclassing for extending a class. If Java had allowed you to override a method to be more private, you could have easily made the public methods of superclass inaccessible (in subclass). Effectively you would have restricted the class instead of extending it. Since in Java subclassing is done only to extend a class, you are not allowed to restrict its behavior by overriding the methods to be more private. Private method are not accessible to the subclass hence does not make sense to override.
4. The overridden method may not throw any checked exceptions at all. If it throws, the exception must be either same as the exception thrown by the superclass method or the exception must be a subclass of the exception thrown by the superclass method.
5. final method of super class. Overridding method can be made final.
Spring autowire funda
To get dependencies automatically inject in the required class without declaring them as a property (setter injection) or constructor-args (constructor injection), this autowire attribute can be used in the bean.
<\bean class="com.inc.arun.Myclass" id="mybean" autowire="byName">
<\/bean>
<\bean class="com.inc.arun.Myclass2" id="mybean2">
Now, Myclass is using the object of Myclass2 and is declared as a field therein. But in my configuration file I have not declared it as a property. It will be automaticall looked for the name with which Myclass2 is declared in Myclass. As the bean declaration for Myclass2 have id as 'mybean2' so in Myclass the object my Myclass2 should have the same attribute name.
Other ways of autowiring is byType, constructor, autodetect. byType work on the basis of Type of the object declared in the required class. It has a limitation in case of interface type declaration. Similarly constructor autowiring is based on the types and parameters of constructor and its limitation is that only one constructor cab be declared.
<\bean class="com.inc.arun.Myclass" id="mybean" autowire="byName">
<\/bean>
<\bean class="com.inc.arun.Myclass2" id="mybean2">
Now, Myclass is using the object of Myclass2 and is declared as a field therein. But in my configuration file I have not declared it as a property. It will be automaticall looked for the name with which Myclass2 is declared in Myclass. As the bean declaration for Myclass2 have id as 'mybean2' so in Myclass the object my Myclass2 should have the same attribute name.
Other ways of autowiring is byType, constructor, autodetect. byType work on the basis of Type of the object declared in the required class. It has a limitation in case of interface type declaration. Similarly constructor autowiring is based on the types and parameters of constructor and its limitation is that only one constructor cab be declared.
Struts Error - org.apache.jasper.JasperException: Module 'null' not found.
For an exception like this -
org.apache.jasper.JasperException: Module 'null' not found.
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:370)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362)
root cause
java.lang.NullPointerException: Module 'null' not found.
org.apache.struts.taglib.TagUtils.getModuleConfig(TagUtils.java:743)
org.apache.struts.taglib.TagUtils.getModuleConfig(TagUtils.java:723)
org.apache.struts.taglib.html.FormTag.lookup(FormTag.java:742)
org.apache.struts.taglib.html.FormTag.doStartTag(FormTag.java:417)
org.apache.jsp.insert_jsp._jspx_meth_html_form_0(insert_jsp.java:107)
org.apache.jsp.insert_jsp._jspService(insert_jsp.java:83)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362)
Specify <\load-on-startup>2<\load-on-startup> in the stanza that defines the Struts ActionServlet in your web.xml file because that's the problem. If you did specified that, there may be some other problem that is preventing the Struts ActionServlet from loading properly when the server first starts up. Look at the logs created when the server is first starting and see if there are any errors related to Struts.
org.apache.jasper.JasperException: Module 'null' not found.
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:370)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362)
root cause
java.lang.NullPointerException: Module 'null' not found.
org.apache.struts.taglib.TagUtils.getModuleConfig(TagUtils.java:743)
org.apache.struts.taglib.TagUtils.getModuleConfig(TagUtils.java:723)
org.apache.struts.taglib.html.FormTag.lookup(FormTag.java:742)
org.apache.struts.taglib.html.FormTag.doStartTag(FormTag.java:417)
org.apache.jsp.insert_jsp._jspx_meth_html_form_0(insert_jsp.java:107)
org.apache.jsp.insert_jsp._jspService(insert_jsp.java:83)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362)
Specify <\load-on-startup>2<\load-on-startup> in the stanza that defines the Struts ActionServlet in your web.xml file because that's the problem. If you did specified that, there may be some other problem that is preventing the Struts ActionServlet from loading properly when the server first starts up. Look at the logs created when the server is first starting and see if there are any errors related to Struts.
Interview with TRAVEL GURU
Two rounds and they expected everything from me....Java, JSP, Servlets, Struts, Hibernate, XML, Ant, Validation Framework, JDBC, SQL and what else you can think of....Spring unhe nahin aati thi nahin to wo bhi hota discussion mein...
Questions
First Round-
1. In SQL, order by, joins, self join.
2. In Struts, life cycle, actionform, validate(), action mapping, validator framework, dyna form.
3. In JSP & Servlets, request processing, tlds, error page, implicit objects, pageContext, web folder structure,
4. In Java, io package classes, why to use bufferedreader and writer instead of streamreader writer, threads & synchronization, exception handling, collection, abstract classes and interfaces.
5. In Hibernate, which all file needs to be there, what are benefits of using it.
Second Round -
Scheduler, windows task scheduler, log4j (debugEnabled() method), custom exception (used to wrap exceptions), interfaces(DB 2 webservice), discussion on Americhoice application and its framework and some more.
for making a dictionary with word-meaning, how you will maintaing the data. (ANS - Map)
If I have to store two meaning for the same word, how I will do that. (ANS - for every key store arraylist of meanings).
Why not array. (ANS - array is of fixed lenght, restriction. ArrayList have in build method to operate on data, flexible.)
Use of properties file in servlets. We need to pass full path to load() method. getContextPath("\") - will give path of working dir and getContextPath("/WEB-INF") will give path upto webinf of application - use these.
Questions
First Round-
1. In SQL, order by, joins, self join.
2. In Struts, life cycle, actionform, validate(), action mapping, validator framework, dyna form.
3. In JSP & Servlets, request processing, tlds, error page, implicit objects, pageContext, web folder structure,
4. In Java, io package classes, why to use bufferedreader and writer instead of streamreader writer, threads & synchronization, exception handling, collection, abstract classes and interfaces.
5. In Hibernate, which all file needs to be there, what are benefits of using it.
Second Round -
Scheduler, windows task scheduler, log4j (debugEnabled() method), custom exception (used to wrap exceptions), interfaces(DB 2 webservice), discussion on Americhoice application and its framework and some more.
for making a dictionary with word-meaning, how you will maintaing the data. (ANS - Map)
If I have to store two meaning for the same word, how I will do that. (ANS - for every key store arraylist of meanings).
Why not array. (ANS - array is of fixed lenght, restriction. ArrayList have in build method to operate on data, flexible.)
Use of properties file in servlets. We need to pass full path to load() method. getContextPath("\") - will give path of working dir and getContextPath("/WEB-INF") will give path upto webinf of application - use these.
Interview with DRISHTI SOFT
DRISHTI SOFT - If you have heard of DACX, you must be knowing this company, else this is a telcome domain company, majorily. This was the second time I was there for interview and second time also I was out in second round.
The interview this time started with a writted aptitude test for which they gave enough time to attempt all the question and I attempted them all but one.
I can only brief them here with some particular question or those which i remember.
1. 2 trains, one travlling from mumbai to delhi at 60kmph started at 6pm, another at 90kmph from mumbai to delhi started at 9 pm, third one from delhi to mumbai started at 9pm....all three met some where in between, to distance between two places is 1260km. fin speed of third train. (ANS - 120)
2. Milk water mixture of 3:1, what portion should be replaced with water to make it 50:50.(ANS _ 1/3rd)
3. setting arrangement question.
4. probability question. whats the probability of getting even no. greater than 2 at the roll of single dice. (ANS - 1/3)
5. 8 pipes in a tank. filler pipe can fill tank in 8 hrs and emptier one empty it in 6 hrs. how many filler pipes out of 8 if fully filled tank got empty in 6 hrs, all pipe opened togther.
6. first day of 1999 is sunday. whats last?
Those all I remember..
After this was technical round and questions based on algos and I need to write programs for them.
1. input - {1,3,4,5,1,2,3,9,8,0}
outpuut - 1,1 7,2 5,1 6,3 9,1 8,1 0,1
that is if some consecutive number is there, sum them up and prinout with count, else like first one, number and 1.
2. int[] searchAllOccurences(String parent, String seach) - write this program to search all occurence of search string in parent string.like
parent - testest
search - test
output - {0,3}
3. This was modeling question.
The interview this time started with a writted aptitude test for which they gave enough time to attempt all the question and I attempted them all but one.
I can only brief them here with some particular question or those which i remember.
1. 2 trains, one travlling from mumbai to delhi at 60kmph started at 6pm, another at 90kmph from mumbai to delhi started at 9 pm, third one from delhi to mumbai started at 9pm....all three met some where in between, to distance between two places is 1260km. fin speed of third train. (ANS - 120)
2. Milk water mixture of 3:1, what portion should be replaced with water to make it 50:50.(ANS _ 1/3rd)
3. setting arrangement question.
4. probability question. whats the probability of getting even no. greater than 2 at the roll of single dice. (ANS - 1/3)
5. 8 pipes in a tank. filler pipe can fill tank in 8 hrs and emptier one empty it in 6 hrs. how many filler pipes out of 8 if fully filled tank got empty in 6 hrs, all pipe opened togther.
6. first day of 1999 is sunday. whats last?
Those all I remember..
After this was technical round and questions based on algos and I need to write programs for them.
1. input - {1,3,4,5,1,2,3,9,8,0}
outpuut - 1,1 7,2 5,1 6,3 9,1 8,1 0,1
that is if some consecutive number is there, sum them up and prinout with count, else like first one, number and 1.
2. int[] searchAllOccurences(String parent, String seach) - write this program to search all occurence of search string in parent string.like
parent - testest
search - test
output - {0,3}
3. This was modeling question.
Action in Struts
Struts is based on MVC2 framework which separated the responsibilities of holding the data and working on it to MODEL(BusinessLogic class), then presenting the data to VIEW(JSP and Other presentation components) and flow of data and control of application to CONTROLLER(ActionServlet and ActionMapping). As compared to this in MVC 1 the responsibility of view and controller was with controller itself.
Trick yourself
1. A class have two synchronized methods. Can two different thread access them simultaneously?
A. Yes, provided methods are not static.
2. Why internationalization or localization are named as i18n or l10n?
A. starting with i, then 18 alphabets and ending with n. Its a usage coined at DEC in the 1970s or 80s[1].
3. A super class A and a subclass B have same variable name and getter setter in both the class.
A a = new B();
a.variable;
a.getVariable();
A. a.variable return value from class A and a.getVariable() will call method in class B because its been overridden there but this method should be there in class A as well otherwise it will be an error. In case of overridding, always child is called.
The compiler looks only at the reference type, not the instance type. Polymorphism
lets you use a more abstract supertype (including an interface) reference to refer to
one of its subtypes (including interface implementers).
Still method of super class can be called by calling it using super.
4. Why constructor are overloaded and not overridden?
A. Constructor are with class name and can not be overridden in subclass, can only be overloaded in same class.
5. Overload vs Overridding
A. Overloaded methods and constructors let you use the same method name (or constructor) but with different argument lists. Overriding lets you redefine a method in a subclass, when you need new subclass-specific behavior.
6. Rules to override
A. 1. overriding method cannot have a more restrictive access modifier. If a subclass were allowed to sneak in and change the access modifier on the overriding method, then suddenly at runtime—when the JVM invokes the true
object’s (Horse) version of the method rather than the reference type’s (Animal)
version—the program would die a horrible death. 2. The argument list must exactly match that of the overridden method. 3. The return type must exactly match that of the overridden method. 4. The access level can be less restrictive than that of the overridden method. 5. The overriding method must not throw new or broader checked exceptions than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it’s a subclass of FileNotFoundException. 6. The overriding method can throw narrower or fewer exceptions. Just because an overridden method “takes risks” doesn’t mean that the overriding subclass’ exception takes the same risks. Bottom line: An overriding method doesn’t have to declare any exceptions that it will never throw, regardless of what the overridden method declares. 7. You cannot override a method marked final.
8. If a method can’t be inherited, you cannot override it.
7. Rules to overload
A. 1. Argument list must change. 2. Return type, access modifier and thrown exceptions can change. 3. A method can be overload in same or any subclass.
Which overridden method to call (in other words, from which class in the inheritance tree) is decided at runtime based on object type, but which overloaded version of the method to call is based on the reference type passed at compile time.
A. Yes, provided methods are not static.
2. Why internationalization or localization are named as i18n or l10n?
A. starting with i, then 18 alphabets and ending with n. Its a usage coined at DEC in the 1970s or 80s[1].
3. A super class A and a subclass B have same variable name and getter setter in both the class.
A a = new B();
a.variable;
a.getVariable();
A. a.variable return value from class A and a.getVariable() will call method in class B because its been overridden there but this method should be there in class A as well otherwise it will be an error. In case of overridding, always child is called.
The compiler looks only at the reference type, not the instance type. Polymorphism
lets you use a more abstract supertype (including an interface) reference to refer to
one of its subtypes (including interface implementers).
Still method of super class can be called by calling it using super.
4. Why constructor are overloaded and not overridden?
A. Constructor are with class name and can not be overridden in subclass, can only be overloaded in same class.
5. Overload vs Overridding
A. Overloaded methods and constructors let you use the same method name (or constructor) but with different argument lists. Overriding lets you redefine a method in a subclass, when you need new subclass-specific behavior.
6. Rules to override
A. 1. overriding method cannot have a more restrictive access modifier. If a subclass were allowed to sneak in and change the access modifier on the overriding method, then suddenly at runtime—when the JVM invokes the true
object’s (Horse) version of the method rather than the reference type’s (Animal)
version—the program would die a horrible death. 2. The argument list must exactly match that of the overridden method. 3. The return type must exactly match that of the overridden method. 4. The access level can be less restrictive than that of the overridden method. 5. The overriding method must not throw new or broader checked exceptions than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it’s a subclass of FileNotFoundException. 6. The overriding method can throw narrower or fewer exceptions. Just because an overridden method “takes risks” doesn’t mean that the overriding subclass’ exception takes the same risks. Bottom line: An overriding method doesn’t have to declare any exceptions that it will never throw, regardless of what the overridden method declares. 7. You cannot override a method marked final.
8. If a method can’t be inherited, you cannot override it.
7. Rules to overload
A. 1. Argument list must change. 2. Return type, access modifier and thrown exceptions can change. 3. A method can be overload in same or any subclass.
Which overridden method to call (in other words, from which class in the inheritance tree) is decided at runtime based on object type, but which overloaded version of the method to call is based on the reference type passed at compile time.
Analyze your analytical Skill
1. Calculate the number of degrees between the hour hand and the minute hand of a clock (nondigital) that reads 3:15.
2. You have eight balls, one of which is slightly heavier than the others. You have a two-armed scale, which you are allowed to use only twice. Your challenge: find the ball that's heavier.
3. Involves water instead of balls. You have two containers, one holds five gallons, the other holds three. You can have as much water as you want. Your task: measure exactly four gallons of water into the five-gallon container.
4.You wake up one morning and there's been a power outage. You know you have 12 black socks and 8 blue ones. How many socks do you need to pull out before you've got a match?
5. the truthtellers and the liars. It goes like this: You're trying to get to Truthtown. You come to a fork in the road. One road leads to Truthtown (where everyone tells the truth), the other to Liartown (where everyone lies). At the fork is a man from one of those towns -- but which one? You get to ask him one question to discover the way. What's the question?
Answers -
1. In one hour(60 min), hour hand move 30 deg and in 1 min it will move .5 deg and in 15 mins it will move 7.5 deg. So 7.5 deg is the answer.
2. Put three balls on each side of the scale. If the arms are equal, you know the heavy ball is one of the two remaining. If the arms are unequal, take the three balls on the heavier side, pick two and weigh them against each other.
3. Fill up the three-gallon container and pour it into the five-gallon container. Do it again -- and there will be one gallon left in the three-gallon container. Empty the five, pour in the one, fill the three again and pour it into the five-gallon container -- and you've got four.
4. To get matching socks, you need to pick three -- there are only two colors, after all.
5. To find the way to Truthtown, simply ask the man, "Which way is your hometown?" Then go whichever way he points: if he's from Liartown, he'll point to Truthtown and if he's from Truthtown, well, you get it.
2. You have eight balls, one of which is slightly heavier than the others. You have a two-armed scale, which you are allowed to use only twice. Your challenge: find the ball that's heavier.
3. Involves water instead of balls. You have two containers, one holds five gallons, the other holds three. You can have as much water as you want. Your task: measure exactly four gallons of water into the five-gallon container.
4.You wake up one morning and there's been a power outage. You know you have 12 black socks and 8 blue ones. How many socks do you need to pull out before you've got a match?
5. the truthtellers and the liars. It goes like this: You're trying to get to Truthtown. You come to a fork in the road. One road leads to Truthtown (where everyone tells the truth), the other to Liartown (where everyone lies). At the fork is a man from one of those towns -- but which one? You get to ask him one question to discover the way. What's the question?
Answers -
1. In one hour(60 min), hour hand move 30 deg and in 1 min it will move .5 deg and in 15 mins it will move 7.5 deg. So 7.5 deg is the answer.
2. Put three balls on each side of the scale. If the arms are equal, you know the heavy ball is one of the two remaining. If the arms are unequal, take the three balls on the heavier side, pick two and weigh them against each other.
3. Fill up the three-gallon container and pour it into the five-gallon container. Do it again -- and there will be one gallon left in the three-gallon container. Empty the five, pour in the one, fill the three again and pour it into the five-gallon container -- and you've got four.
4. To get matching socks, you need to pick three -- there are only two colors, after all.
5. To find the way to Truthtown, simply ask the man, "Which way is your hometown?" Then go whichever way he points: if he's from Liartown, he'll point to Truthtown and if he's from Truthtown, well, you get it.
Interview with THOUGHTFOCUS
1. If we need to you collection for two different purpose. One is for easy search and other for frequent insertion/deletion, which collection class should be used?
A - ArrayList for later and LinkedList for former.
2. Difference between List and Set?
A - Set does not allows duplicate and List allows.
3. What are singleton class and its features?
4. What are Hashtable and Map?
5. Difference between String, StringBuffer and StringBuilder?
A - Strings are immutable and StringBuffer are mutable. StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized. StringBuilder does not handle thread-safety issue and none of its methods is synchronized.
6. Two classes as given below -
public class A{
public String id;
public String name;
//getter/setter
}
public class B extends A{
public String id;
public String name;
//getter/setter
}
creating a new instance of B using reference for A and calling name getter on it, which name getter will be called? A or B?
A - A
7. Life cycle of servlet?
8. How JSP bean tags work?
9. How custom tags are written?
10. Struts validator framework?
11. What if some validation fails in struts and I want to forward the application to some error page. Where should I configure that?
A - ArrayList for later and LinkedList for former.
2. Difference between List and Set?
A - Set does not allows duplicate and List allows.
3. What are singleton class and its features?
4. What are Hashtable and Map?
5. Difference between String, StringBuffer and StringBuilder?
A - Strings are immutable and StringBuffer are mutable. StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized. StringBuilder does not handle thread-safety issue and none of its methods is synchronized.
6. Two classes as given below -
public class A{
public String id;
public String name;
//getter/setter
}
public class B extends A{
public String id;
public String name;
//getter/setter
}
creating a new instance of B using reference for A and calling name getter on it, which name getter will be called? A or B?
A - A
7. Life cycle of servlet?
8. How JSP bean tags work?
9. How custom tags are written?
10. Struts validator framework?
11. What if some validation fails in struts and I want to forward the application to some error page. Where should I configure that?
Abort JSP
JSP is just a servlet method, you can just put (whereever necessary) a < % return; % > to abort JSp page processing.
OR,
Create a page called exit.jsp etc. with only this content:
<\%@page language="java"%>
Then EXIT your page this way:
<\% out.flush(); %>
<\jsp:forward page="exit.jsp" />
This works great within dynamically included JSP-pages and outputs the content processed this far.
OR,
Create a page called exit.jsp etc. with only this content:
<\%@page language="java"%>
Then EXIT your page this way:
<\% out.flush(); %>
<\jsp:forward page="exit.jsp" />
This works great within dynamically included JSP-pages and outputs the content processed this far.
JSP error page from servlet
We can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only within controller servlets.
If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error:
java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained.
The following code snippet demonstrates the invocation of a JSP error page from within a controller servlet:
protected void sendErrorRedirect(HttpServletRequest request,
HttpServletResponse response, String errorPageURL, Throwable e) throws
ServletException, IOException {
request.setAttribute ("javax.servlet.jsp.jspException", e);
getServletConfig().getServletContext().
getRequestDispatcher(errorPageURL).forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try {
// do something
} catch (Exception ex) {
try {
sendErrorRedirect(request,response,"/jsp/MyErrorPage.jsp",ex);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Some More Information -
1. Error page is jsp page and there is tag called IsErrorPage = True.
2. To set the port for server, you just go to server /default/deploy/tomacat5.5.rar/server.xml. Inside server.xml you can see Tag
8080 . Give some other name apart from 8080.
If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error:
java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained.
The following code snippet demonstrates the invocation of a JSP error page from within a controller servlet:
protected void sendErrorRedirect(HttpServletRequest request,
HttpServletResponse response, String errorPageURL, Throwable e) throws
ServletException, IOException {
request.setAttribute ("javax.servlet.jsp.jspException", e);
getServletConfig().getServletContext().
getRequestDispatcher(errorPageURL).forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try {
// do something
} catch (Exception ex) {
try {
sendErrorRedirect(request,response,"/jsp/MyErrorPage.jsp",ex);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Some More Information -
1. Error page is jsp page and there is tag called IsErrorPage = True.
2. To set the port for server, you just go to server /default/deploy/tomacat5.5.rar/server.xml. Inside server.xml you can see Tag
GET vs POST
A GET request is a request to get a resource from the server. Choosing GET as the "method" will append all of the data to the URL and it will show up in the URL bar of your browser. The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters.
A POST request is a request to post (to send) form data to a resource on the server. A POST on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar. You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
In Get method data is send via URL.So,the transaction is very fast.In Post method data is send as packets via sockets.So the process is very slow.
Get method Unsecured. Since,any one can see the data in the address bar.Post method is very secure.
A POST request is a request to post (to send) form data to a resource on the server. A POST on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar. You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
In Get method data is send via URL.So,the transaction is very fast.In Post method data is send as packets via sockets.So the process is very slow.
Get method Unsecured. Since,any one can see the data in the address bar.Post method is very secure.
forward vs include
Both forward() and include() are concrete methods of the RequestDispatcher class in the Servlet context.
forward() - this method is used to show a different resource in place of the servlet originally requested. This resource may be a jsp, a servlet etc. When a request is sent from the client to the web server through an url , the web container intercepts the request and sends it to another resource without the knowledge of the client browser. And a response is received from that resource after processing of the request is done.
include() - this method is used to tag in the contents of a resource as a part of the response flow as if it were part of the calling servlet. If you include a jsp or a servlet, it must not attempt to change the response status code or the http headers, as any such request will be ignored.
forward() - this method is used to show a different resource in place of the servlet originally requested. This resource may be a jsp, a servlet etc. When a request is sent from the client to the web server through an url , the web container intercepts the request and sends it to another resource without the knowledge of the client browser. And a response is received from that resource after processing of the request is done.
include() - this method is used to tag in the contents of a resource as a part of the response flow as if it were part of the calling servlet. If you include a jsp or a servlet, it must not attempt to change the response status code or the http headers, as any such request will be ignored.
ServletContext Vs. ServletConfig
Both are interfaces :)
SevletContext
The ServletContext interface provides information to servlets regarding the environment in which they are running. ServletContext represent's your web application,so there is only one sevletContext for your application. ServletContext is a window given to a servlet to view its environment.It contains the global information,which are name/value pair.
ServletConfig
For particular servlet in your application there is one ServletConfig so,if 10 servlets are there in your application then there are 10 ServletConfigs. The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. ServletConfig contains information(name/value pair) specific to particular servlet used during initializing servlet.
When we deploy a web application the webcontainer reads the deployment descriptor(i.e,web.xml). If there is no problem then the webcontainer creates a ServletContext object for that web-application. The webcontainer removes the ServletContext object when the web application is stopped. So the no. of ServletContext objects present in web container depends on no.of web applications present. For every web application a ServletContext object is created by web container. And WebContainer creates ServletConfig object for every servlet that is a part of web application. As part of web application there will be only one ServletContext object,but there can be multiple ServletConfig objects.
SevletContext
The ServletContext interface provides information to servlets regarding the environment in which they are running. ServletContext represent's your web application,so there is only one sevletContext for your application. ServletContext is a window given to a servlet to view its environment.It contains the global information,which are name/value pair.
ServletConfig
For particular servlet in your application there is one ServletConfig so,if 10 servlets are there in your application then there are 10 ServletConfigs. The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. ServletConfig contains information(name/value pair) specific to particular servlet used during initializing servlet.
When we deploy a web application the webcontainer reads the deployment descriptor(i.e,web.xml). If there is no problem then the webcontainer creates a ServletContext object for that web-application. The webcontainer removes the ServletContext object when the web application is stopped. So the no. of ServletContext objects present in web container depends on no.of web applications present. For every web application a ServletContext object is created by web container. And WebContainer creates ServletConfig object for every servlet that is a part of web application. As part of web application there will be only one ServletContext object,but there can be multiple ServletConfig objects.
Customized export to excel in displaytag
Have you ever thought of what if your displaytag table contain more that 66000 records and you want to export to excel which actually have maximum rows less that that?
I have a solution for you. Solution is to write your customized excel export code and configure it with the display tag.
I have a solution for you. Solution is to write your customized excel export code and configure it with the display tag.
Saturday, July 31, 2010
Playing around with UNIX
Some commands that you can play around with in unix
1.ps -ef - This command will list all the running processes. 'e' is for each process, 'f' is for full format display.
2. ps -ef | grep java - This command will list all the running java processes.
3. chmod nnn filename - To change the access rights on the file.
4. pwd - Present working directory.
5. date - current date and time at the location of the server.
6. who - will list all the logged in user.
7. who am i - will list your username and logged in time.
8. tar cf file.tar file1 file2 … fileN - to create a tar file from combination of files.
9. zip filename - To zip a file.
10. unzip filename - To unzip a file.
11. kill -3 PID - to create the dump of the process. PID is process id can be seen using the first command.
12. cd dir-path - change directory.
13. grep pattern filename- search for a pattern in file. Pattern can be any string you need to look into file.
14. ls - to list the dir and file.
15. man command - to see manual for a command.
16. ftp hostname - to ftp file from unix.
17. grep -c pattern filename - Searches and prints only the number of matches to the screen.
18. grep -i pattern filename - Searches without regard to letter case.
19. grep -n pattern filename - Prints to the screen preceded by the line number.
20. grep -v pattern filename - All lines that do not match are printed.
21. grep -x pattern filename - Only exact matches are printed.
Executing shell script - On the command prompt type sh filename.sh
Executing perl script - On the command prompt type ./filename.pl
1.ps -ef - This command will list all the running processes. 'e' is for each process, 'f' is for full format display.
2. ps -ef | grep java - This command will list all the running java processes.
3. chmod nnn filename - To change the access rights on the file.
4. pwd - Present working directory.
5. date - current date and time at the location of the server.
6. who - will list all the logged in user.
7. who am i - will list your username and logged in time.
8. tar cf file.tar file1 file2 … fileN - to create a tar file from combination of files.
9. zip filename - To zip a file.
10. unzip filename - To unzip a file.
11. kill -3 PID - to create the dump of the process. PID is process id can be seen using the first command.
12. cd dir-path - change directory.
13. grep pattern filename- search for a pattern in file. Pattern can be any string you need to look into file.
14. ls - to list the dir and file.
15. man command - to see manual for a command.
16. ftp hostname - to ftp file from unix.
17. grep -c pattern filename - Searches and prints only the number of matches to the screen.
18. grep -i pattern filename - Searches without regard to letter case.
19. grep -n pattern filename - Prints to the screen preceded by the line number.
20. grep -v pattern filename - All lines that do not match are printed.
21. grep -x pattern filename - Only exact matches are printed.
Executing shell script - On the command prompt type sh filename.sh
Executing perl script - On the command prompt type ./filename.pl
Friday, July 23, 2010
Writing Your Own Struts PlugIn
A plugin is a configuration wrapper for a module-specific resource or service that needs to be notified about application startup and shutdown events." What this means is that you can create a class implementing the PlugIn interface to do something at application startup or shutdown like we want to initialize Hibernate as soon as the application starts up, so that by the time my web application receives the first request, Hibernate is already configured and ready to use. We also want to close down Hibernate when the application is shutting down. We write a plugin for this requirement with as Hibernate PlugIn.
1.Write a class implementing the PlugIn interface
public class HibernatePlugIn implements PlugIn{
private String configFile;
// This method will be called at application shutdown time
public void destroy() {
System.out.println("Entering HibernatePlugIn.destroy()");
//Put hibernate cleanup code here
System.out.println("Exiting HibernatePlugIn.destroy()");
}
//This method will be called at application startup time
public void init(ActionServlet actionServlet, ModuleConfig config)
throws ServletException {
System.out.println("Entering HibernatePlugIn.init()");
System.out.println("Value of init parameter " +
getConfigFile());
System.out.println("Exiting HibernatePlugIn.init()");
}
public String getConfigFile() {
return name;
}
public void setConfigFile(String string) {
configFile = string;
}
}
1.Write a class implementing the PlugIn interface
public class HibernatePlugIn implements PlugIn{
private String configFile;
// This method will be called at application shutdown time
public void destroy() {
System.out.println("Entering HibernatePlugIn.destroy()");
//Put hibernate cleanup code here
System.out.println("Exiting HibernatePlugIn.destroy()");
}
//This method will be called at application startup time
public void init(ActionServlet actionServlet, ModuleConfig config)
throws ServletException {
System.out.println("Entering HibernatePlugIn.init()");
System.out.println("Value of init parameter " +
getConfigFile());
System.out.println("Exiting HibernatePlugIn.init()");
}
public String getConfigFile() {
return name;
}
public void setConfigFile(String string) {
configFile = string;
}
}
Sunday, July 18, 2010
Creating Your own RequestProcessor in Struts
We will change our sample application in two steps to implement the content type and user login in.
1. Create your own CustomRequestProcessor class, which will extend the RequestProcessor class, like :
public class CustomRequestProcessor extends RequestProcessor {
protected boolean processPreprocess (HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(false);
//If user is trying to access login page
// then don't check
if( request.getServletPath().equals("/loginInput.do")
|| request.getServletPath().equals("/login.do") )
return true;
//Check if userName attribute is there is session.
//If so, it means user has allready logged in
if( session != null &&
session.getAttribute("userName") != null)
return true;
else{
try{
//If no redirect user to login Page
request.getRequestDispatcher
("/Login.jsp").forward(request,response);
}catch(Exception ex){
}
}
return false;
}
protected void processContent(HttpServletRequest request, HttpServletResponse response) {
//Check if user is requesting ContactImageAction
// if yes then set image/gif as content type
if( request.getServletPath().equals("/contactimage.do")){
response.setContentType("image/gif");
return;
}
super.processContent(request, response);
}
}
In the processPreprocess method of our CustomRequestProcessor class, we are checking for the userName attribute of the session and if it's not found, redirect the user to the login page.
For our requirement of generating images as output from the ContactImageAction class, we have to override the processContent method and first check if the request is for the /contactimage path. If so, we set the contentType to image/gif; otherwise, it's text/html.
1. Create your own CustomRequestProcessor class, which will extend the RequestProcessor class, like :
public class CustomRequestProcessor extends RequestProcessor {
protected boolean processPreprocess (HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(false);
//If user is trying to access login page
// then don't check
if( request.getServletPath().equals("/loginInput.do")
|| request.getServletPath().equals("/login.do") )
return true;
//Check if userName attribute is there is session.
//If so, it means user has allready logged in
if( session != null &&
session.getAttribute("userName") != null)
return true;
else{
try{
//If no redirect user to login Page
request.getRequestDispatcher
("/Login.jsp").forward(request,response);
}catch(Exception ex){
}
}
return false;
}
protected void processContent(HttpServletRequest request, HttpServletResponse response) {
//Check if user is requesting ContactImageAction
// if yes then set image/gif as content type
if( request.getServletPath().equals("/contactimage.do")){
response.setContentType("image/gif");
return;
}
super.processContent(request, response);
}
}
In the processPreprocess method of our CustomRequestProcessor class, we are checking for the userName attribute of the session and if it's not found, redirect the user to the login page.
For our requirement of generating images as output from the ContactImageAction class, we have to override the processContent method and first check if the request is for the /contactimage path. If so, we set the contentType to image/gif; otherwise, it's text/html.
How a Request is Processed in Struts
ActionServlet is the servlet class in Struts which is configured in web.xml and read by the web application server. This is the entry point into struts framework and is responsible for handling all of the requests. Whenever it receives a request, it first tries to find a sub-application for the current request. Once a sub-application is found, it creates a RequestProcessor object for that sub-application and calls its process() method by passing it HttpServletRequest and HttpServletResponse objects.
The RequestProcessor.process() method is where most of the request processing takes place. The process() method is implemented using the Template Method design pattern, in which there is a separate method for performing each step of request processing, and all of those methods are called in sequence from the process() method. The RequestProcessor class in the Struts distribution provides a default implementation for each of the request-processing steps. That means you can override only the methods that interest you, and use default implementations for rest of the methods. For example, by default Struts calls request.isUserInRole() to find out if the user has one of the roles required to execute the current ActionMapping, but if you want to query a database for this, then then all you have to do is override the processRoles() method and return true or false, based whether the user has the required role or not.
Lets have a look at the default implementation of process() method first.
public void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Wrap multipart requests with a special wrapper
request = processMultipart(request);
// Identify the path component we will
// use to select a mapping
String path = processPath(request, response);
if (path == null) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Processing a '" + request.getMethod() +
"' for path '" + path + "'");
}
// Select a Locale for the current user if requested
processLocale(request, response);
// Set the content type and no-caching headers
// if requested
processContent(request, response);
processNoCache(request, response);
// General purpose preprocessing hook
if (!processPreprocess(request, response)) {
return;
}
// Identify the mapping for this request
ActionMapping mapping =
processMapping(request, response, path);
if (mapping == null) {
return;
}
// Check for any role required to perform this action
if (!processRoles(request, response, mapping)) {
return;
}
// Process any ActionForm bean related to this request
ActionForm form =
processActionForm(request, response, mapping);
processPopulate(request, response, form, mapping);
if (!processValidate(request, response, form, mapping)) {
return;
}
// Process a forward or include specified by this mapping
if (!processForward(request, response, mapping)) {
return;
}
if (!processInclude(request, response, mapping)) {
return;
}
// Create or acquire the Action instance to
// process this request
Action action =
processActionCreate(request, response, mapping);
if (action == null) {
return;
}
// Call the Action instance itself
ActionForward forward =
processActionPerform(request, response,
action, form, mapping);
// Process the returned ActionForward instance
processForwardConfig(request, response, forward);
}
The RequestProcessor.process() method is where most of the request processing takes place. The process() method is implemented using the Template Method design pattern, in which there is a separate method for performing each step of request processing, and all of those methods are called in sequence from the process() method. The RequestProcessor class in the Struts distribution provides a default implementation for each of the request-processing steps. That means you can override only the methods that interest you, and use default implementations for rest of the methods. For example, by default Struts calls request.isUserInRole() to find out if the user has one of the roles required to execute the current ActionMapping, but if you want to query a database for this, then then all you have to do is override the processRoles() method and return true or false, based whether the user has the required role or not.
Lets have a look at the default implementation of process() method first.
public void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Wrap multipart requests with a special wrapper
request = processMultipart(request);
// Identify the path component we will
// use to select a mapping
String path = processPath(request, response);
if (path == null) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Processing a '" + request.getMethod() +
"' for path '" + path + "'");
}
// Select a Locale for the current user if requested
processLocale(request, response);
// Set the content type and no-caching headers
// if requested
processContent(request, response);
processNoCache(request, response);
// General purpose preprocessing hook
if (!processPreprocess(request, response)) {
return;
}
// Identify the mapping for this request
ActionMapping mapping =
processMapping(request, response, path);
if (mapping == null) {
return;
}
// Check for any role required to perform this action
if (!processRoles(request, response, mapping)) {
return;
}
// Process any ActionForm bean related to this request
ActionForm form =
processActionForm(request, response, mapping);
processPopulate(request, response, form, mapping);
if (!processValidate(request, response, form, mapping)) {
return;
}
// Process a forward or include specified by this mapping
if (!processForward(request, response, mapping)) {
return;
}
if (!processInclude(request, response, mapping)) {
return;
}
// Create or acquire the Action instance to
// process this request
Action action =
processActionCreate(request, response, mapping);
if (action == null) {
return;
}
// Call the Action instance itself
ActionForward forward =
processActionPerform(request, response,
action, form, mapping);
// Process the returned ActionForward instance
processForwardConfig(request, response, forward);
}
Extending Struts
Struts is a very powerful framework and also very extensible. You can extend Struts in three ways.
1. PlugIn: Create your own PlugIn class if you want to execute some business logic at application startup or shutdown.
2. RequestProcessor: Create your own RequestProcessor if you want to execute some business logic at a particular point during the request-processing phase. For example, you might extend RequestProcessor to check that the user is logged in and he has one of the roles to execute a particular action before executing every request.
3. ActionServlet: You can extend the ActionServlet class if you want to execute your business logic at either application startup or shutdown, or during request processing. But you should use it only in cases where neither PlugIn nor RequestProcessor is able to fulfill your requirement.
1. PlugIn: Create your own PlugIn class if you want to execute some business logic at application startup or shutdown.
2. RequestProcessor: Create your own RequestProcessor if you want to execute some business logic at a particular point during the request-processing phase. For example, you might extend RequestProcessor to check that the user is logged in and he has one of the roles to execute a particular action before executing every request.
3. ActionServlet: You can extend the ActionServlet class if you want to execute your business logic at either application startup or shutdown, or during request processing. But you should use it only in cases where neither PlugIn nor RequestProcessor is able to fulfill your requirement.
Sunday, July 11, 2010
How to find missing elements from the array of consecutive integers?
The problem says that if you have n consecutive integers array and n-x, n-y and n-z values are missing from the array how we can find those numbers.
In case only one number would have been missing, its easier to find by summing the numbers in this array and comparing it with the sum of n consecutive integer array.
Now in case when two or more than two elements are missing, then the solution goes like this. Create another array of n size. Start putting 1 at the index position in new array which is equal to the value of the element in the old array. Example, if the first element value in the old array is 43, put 1 in the new array at the index position of 43. Like this populate the new array for all the elements in old array. Now the indexes with zero values in the new array are the missing values in the old array.
In case only one number would have been missing, its easier to find by summing the numbers in this array and comparing it with the sum of n consecutive integer array.
Now in case when two or more than two elements are missing, then the solution goes like this. Create another array of n size. Start putting 1 at the index position in new array which is equal to the value of the element in the old array. Example, if the first element value in the old array is 43, put 1 in the new array at the index position of 43. Like this populate the new array for all the elements in old array. Now the indexes with zero values in the new array are the missing values in the old array.
Java constant values are resolved at compile time or runtime?
Java constants are basically variables defined as static final in any class or interface. At compile time when java classes are generated constant values are placed at all the places where the constant is referred. At runtime the defined constant or the class in which constant is defined does not come into picture at all. So if at sometime you change some constant in any file and just try to replace the class file in the jar or in production, it will not work because the value need to be replace where that constant is referred which is done at compile time.
Overridding instance variable in java
Always remember, instance variable can not be overridden. Try below example.
public class A{
public int i = 1;
}
public class B{
public int i=2;
}
public class C{
public static void main(String[] arg){
A a = new B();
System.out.println(a.i);//The output will be 1 and not 2
}
}
public class A{
public int i = 1;
}
public class B{
public int i=2;
}
public class C{
public static void main(String[] arg){
A a = new B();
System.out.println(a.i);//The output will be 1 and not 2
}
}
Summing column value in a sql query
To sum value of two columns in a sql query use + operator as shown below
select column1+column2 from tableA
select column1+column2 from tableA
General hibernate configuration - for quick reference
<hibernate-configuration>
<session-factory>
<property name="connection.driver.class">
org.hsqldb.jdbcDriver
 </property>
<property name="connection.url">
url
 </property>
<property name="connection.username">
username
 </property>
<property name="connection.password">
password
 </property>
<property name="connection.dialect">
HSQLDialect
 </property>
<property name="connection.pool_size">
1
 </property>
<property name="connection.show_sql">
true
 </property>
<mapping resource="test.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Do we always normalize database?
One word answer is No. Although most of the time we normalize our tables but there can be scenarios when our query performance is diminished. Normalization in database calls for the joins in the query on the tables which may reduce the performance of queries by increasing the execution time.
Which fields are indexed in reporting databases?
We, mainly, create index on date fields in databases (basically tables) which are frequently used in reporting. This is because most of the time reports are created on the date bases. So because we will be fetching data from the tables mostly on the basis of date field creating index on it will reduce the execution time of the query as index on the date field will help in easily sorting of the rows in the table.
Swapping object in java
In java, when you are trying to swap two objects, it cannot be swapped by creating a temporary variable in a different method as given below.
public static void main (String[] arg){
//creating two objectsto be swapped
ClassA a1 = new ClassA();
ClassA b1 = new ClassA();
.....
swap(a1,b1);
}
public void swap(ClassA a, ClassA b){
ClassA temp = a;
a=b;
b=temp;
}
One line answer to why objects will not get swapped is that java is a pass by value.
public static void main (String[] arg){
//creating two objectsto be swapped
ClassA a1 = new ClassA();
ClassA b1 = new ClassA();
.....
swap(a1,b1);
}
public void swap(ClassA a, ClassA b){
ClassA temp = a;
a=b;
b=temp;
}
One line answer to why objects will not get swapped is that java is a pass by value.
Open a new web browser window without back button
Using javascript we can do that easily.
window.open(url,window title,"status=1,toolbar=0");
There are more options that you can use while writing a javascript to open a new window
window.open(url,window title,"status=1,toolbar=0");
There are more options that you can use while writing a javascript to open a new window
| status | The status bar at the bottom of the window. |
| toolbar | The standard browser toolbar, with buttons such as Back and Forward. |
| location | The Location entry field where you enter the URL. |
| menubar | The menu bar of the window |
| directories | The standard browser directory buttons, such as What's New and What's Cool |
| resizable | Allow/Disallow the user to resize the window. |
| scrollbars | Enable the scrollbars if the document is bigger than the window |
| height | Specifies the height of the window in pixels. (example: height='350') |
| width | Specifies the width of the window in pixels. |
Disable back button functionality on web client (IE)
To disable back functionality on any web page, we can do it using javascript.
window.history.forward();
window.history.forward();
Subscribe to:
Comments (Atom)


