Export File name in servlet/jsp

Thursday, 26 April 2007, 13:49 | Category : Internet, J2EE, Java, Technology
Tags :

While giving a link for export as a file, you may also want to give it a name that should come in save-as dialog or browser. To do so, you have to just set Content-Disposition header and content type of response
e.g. for saving as an excel file, following can be used:

response.setHeader(“Content-Disposition”,”attachment; filename=”" + filename + “”");
response.setContentType(“application/vnd.ms-excel”);

Debugging problems related to the JDBC API

Thursday, 26 April 2007, 0:57 | Category : Database, J2EE, Java, Technology
Tags :

A good way to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC trace contains a detailed listing of the activity occurring in the system that is related to JDBC operations.

If you use the DriverManager facility to establish your database connection, you use the DriverManager.setLogWriter method to enable tracing of JDBC operations. If you use a DataSource object to get a connection, you use the DataSource.setLogWriter method to enable tracing. (For pooled connections, you use the ConnectionPoolDataSource.setLogWriter method, and for connections that can participate in distributed transactions, you use the XADataSource.setLogWriter method.)

Which jar

Monday, 23 April 2007, 23:22 | Category : Java, Technology
Tags :

How to know from which jar file a class has been loaded?

public static String whichJAR(Class clazz){
String name = clazz.getName();
name = name.substring(name.lastIndexOf(‘.’) + 1);
String jar = clazz.getResource(name + “.class”).toString(); //NOI18N
return jar.substring(0, jar.indexOf(‘!’));
}

Number of processors on a machine

Monday, 23 April 2007, 23:20 | Category : Java, Technology
Tags : ,

How to get Number of processors on a machine in java

public class GetNoOfProcessors
{
public static void main(String[] args)
{
System.out.println(“No. of processors found in the system: ” + getNoOfProcessors());
}
/**
* Gets the no. of processors.
* @return The no. of processors
*/
public static int getNoOfProcessors()
{
int noOfProcessors = 0;
try
{
Runtime runtime = Runtime.getRuntime();
Class runtimeClass = runtime.getClass();
java.lang.reflect.Method availProcessorsMethod = runtimeClass.getMethod(“availableProcessors”, null);
noOfProcessors = ((Integer)availProcessorsMethod.invoke(runtime, null)).intValue();
}
catch (Throwable e)
{
// Ignore this exception as this method is only supported in JDK > 1.4
}
return noOfProcessors;
}
}

Sample java code to read mails from your gmail account

Monday, 23 April 2007, 23:13 | Category : Internet, J2EE, Java, Technology
Tags : ,

Sample java code to read mails from your gmail account

import java.io.UnsupportedEncodingException;
import java.io.FileWriter;
import java.security.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.pop3.POP3SSLStore;
import java.util.Date;

public class GmailFetch {

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

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String <strong>SSL</strong>_FACTORY = "javax.net.ssl.SSLSocketFactory";

// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.<strong>pop3</strong>.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.pop3.socketFactory.fallback", "false");
props.setProperty("mail.pop3.port", "<strong>995</strong>");
props.setProperty("mail.pop3.socketFactory.port", "995");
props.setProperty("mail.pop3.host", "<strong>pop.gmail.com</strong>");
props.setProperty("mail.pop3.<strong>user</strong>", args[0]);
props.setProperty("mail.pop3.passwd", args[1]);
props.setProperty("mail.pop3.ssl", "true");

Session session = Session.getInstance(props,null);
<strong>URLName </strong>urln = new URLName("pop3","pop.gmail.com",995,null,args[0], args[1]);
<strong>Store </strong>store = new <strong>POP3SSLStore</strong>(session, urln);
//session.setDebug(true);

store.connect("pop.gmail.com",args[0],args[1]);
<strong>Folder </strong>folder = store.getDefaultFolder();
folder = folder.getFolder("<strong>INBOX</strong>");
folder.open(Folder.READ_ONLY);

System.out.println("<strong>Message </strong>Count "+folder.getMessageCount());
System.out.println("New Message Count "+folder.getNewMessageCount());
System.out.println("=========================================");

Message[] messages = folder.getMessages();

FetchProfile fp = new <strong>FetchProfile</strong>();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(messages, fp);

for (int i = 0; i &lt; messages.length; i++) { System.out.println("From:"+ <strong>messages</strong>[i].getFrom()); } <strong>folder</strong>.close(true); store.close(); } }

Covariant return types

Friday, 20 April 2007, 12:44 | Category : Java, Technology
Tags :

You cannot have two methods in the same class with signatures that only differ by return type. Until the J2SE 5.0 release, it was also true that a class could not override the return type of the methods it inherits from a superclass. In this tip you will learn about a new feature in J2SE 5.0 that allows covariant return types. What this means is that a method in a subclass may return an object whose type is a subclass of the type returned by the method with the same signature in the superclass. This feature removes the need for excessive type checking and casting.

Let’s start with the following class, ConfusedClass. The class tries to declare two methods with the same signature. One of the methods returns a JTextField, and the other returns a JPasswordField.

 
import javax.swing.JTextField;
import javax.swing.JPasswordField;
public class ConfusedClass {
public JTextField getTextField(){
return new JTextField();
}
public JPasswordField getTextField(){
return new JPasswordField();
}
}

If you try to compile ConfusedClass, you get the following compile error:
ConfusedClass.java:10: getTextField() is already defined in ConfusedClass
public JPasswordField getTextField(){
^
1 error

Looking at this situation from the perspective of a class calling getTextField(), you can see the reason for the compile time error. How would you indicate which of the two methods you are targeting? Consider, for example, this snippet:

 
ConfusedClass cc = new ConfusedClass();
JTextField field = cc.getTextField();

Because a JPasswordField extends JTextField, either version of the method could correctly be called.

Next, create two classes, each of which having a different version of the getTextField() methods. The two methods differ by implementation and return type. Start with the following base:

import javax.swing.JTextField;
public class ConfusedSuperClass {
public JTextField getTextField(){
System.out.println(“Called in ” + this.getClass());
return new JTextField();
}
}

Compile ConfusedSuperClass. You’ll see that it compiles without error. Now create a derived class, one that extends ConfusedSuperClass. The derived class attempts to return an instance of JPasswordField instead of the JTextField returned by the getTextField() method in ConfusedSuperClass.

import javax.swing.JPasswordField;
public class ConfusedSubClass extends ConfusedSuperClass {
public JPasswordField getTextField(){
System.out.println(“Called in ” + this.getClass());
return new JPasswordField();
}
}

If you use a version of the JDK prior to J2SE 5.0, ConfusedSubClass will not compile. You will see an error like this.

ConfusedSubClass.java:5: getTextField() in ConfusedSubClass cannot override getTextField() in ConfusedSuperClass; attempting to use incompatible return type
found : javax.swing.JPasswordField
required: javax.swing.JTextField
public JPasswordField getTextField(){
^
1 error

The error reported is that you are attempting to use an incompatible return type. In fact, the JPasswordField you are attempting to return is a subtype of JTextField. This same code compiles correctly under J2SE 5.0. You are now allowed to override the return type of a method with a subtype of the original type. In the current example, the getTextField() method in ConfusedSuperClass returns an instance of type JTextField. The getTextField() method in the ConfusedSubClass returns an instance of type JPasswordField.

You can exercise these two classes with the following NotConfusedClient class. This class creates an instance of type ConfusedSuperClass and of type ConfusedSubClass. It then calls getTextField() on each instance, and displays the type corresponding to the object returned by the method.

 
import javax.swing.JTextField;
public class NotConfusedClient {
static JTextField jTextField;
public static void main(String[] args) {
System.out.println(“===== Super Class =====”);
jTextField = new ConfusedSuperClass().getTextField();
System.out.println(“Got back an instance of “+ jTextField.getClass());
System.out.println(“===== Sub Class =====”);
jTextField = new ConfusedSubClass().getTextField();
System.out.println(“Got back an instance of “+ jTextField.getClass());
}
}

Compile and run NotConfusedClient. When you run it, you should see the following output:

===== Super Class =====
Called in class ConfusedSuperClass
Got back an instance of class javax.swing.JTextField
===== Sub Class =====
Called in class ConfusedSubClass
Got back an instance of class javax.swing.JPasswordField

In fact, you will get the same output if you change the return type of getTextField() to JTextField in ConfusedSubClass. The payoff comes when you use the object that is returned by the call to getTextField(). Before J2SE 5.0, you needed to downcast to take advantage of methods that are present in the derived class but not in the base class. As you’ve seen, in J2SE 5.0 ConfusedSubClass compiles with a different return type specified for getTextField() than is present in the superclass. You can now use your covariant return type to call a method that is only available in the subtype. First, recast the supertype like this:

 
public class SuperClass {
public SuperClass getAnObject(){
return this;
}
}

Add the exclusive method to the corresponding subclass, and change the return type of the getAnObject() method:

public class SubClass extends SuperClass {
public SubClass getAnObject(){
return this;
}
public void exclusiveMethod(){
System.out.println(“Exclusive in Subclass.”);
}
public static void main(String[] args) {
System.out.println(“===== Call Exclusive method =====”);
new SubClass().getAnObject().exclusiveMethod();
}
}

Compile SuperClass and SubClass, then run SubClass. You should see the following output:

===== Call Exclusive method =====
Exclusive in Subclass.

The main() method creates an instance of the subclass. It then calls getAnObject(). It follows this with a call to exclusiveMethod() on the returned object of type SubClass. If the return type of getAnObject() was SuperClass in SubClass.java, the code would not have compiled.

Java Interview questions

Friday, 20 April 2007, 12:41 | Category : Interview questions, Java, Technology
Tags :

Q. How to create Immutable class?
Immutable objects are simply objects whose state (the object’s data) does not change after construction. Always construct an object completely, instead of using a no-argument constructor combined with subsequent calls to setXXX methods. Do not provide any methods which can change the state of the object in any way – not just setXXX methods, but any method which can change state. ensure no methods can be overridden – make the class final, or use static factories and keep constructors private, make fields final


Q. Why SingleThreadModel in servlets is depreceated?
A. SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used. It is recommended that a developer take other means to resolve those issues instead of implementing this interface, such as avoiding the usage of an instance variable or synchronizing the block of the code accessing those resources. This interface is deprecated in Servlet API version 2.4.

Q. How will u synchronise list?
A. use Collections.synchronizedCollection( Collection c) or Collections.synchronizedList( list l)

Hashmap allows more than one null insertion also, it overwrites the existing one. At max there will be one null key. On get(null) it will return the last inserted value.

HashMap :- This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. TO maintain order of insertion:
In JDK1.4, LinkedHashMap can be used. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.