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










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

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.

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

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());
}

}

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));

}

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.

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.

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?

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.

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;
}
}

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;
}

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());

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.

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.

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.

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.

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.

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.

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.

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?

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.

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.

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.

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.

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.

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.