Tuesday, February 13, 2007

How can I read the status code of a HTTP request?

If you use the URL.openStream() method, there's no way to determine whether a request was successful or not. The only alternative is to use the URL.openConnection() method, which returns a URLConnection instance. The URLConnection is an abstract class, meaning that it provides a template of methods which other classes will implement. Even though the URL.openConnection() method returns a URLConnection instance, it is actually returning a concrete implementation of that class.

When a request is made for a resource using the Hypertext Transfer Protocol, the implementation of URLConnection that is returned is a java.net.HttpURLConnection. This class defines additional methods, one of which allow you to access the response status code. To find out the status of a request, you need to cast the URLConnection to a HttpURLConnection, and invoke the int HttpUrlConnection.getResponseCode() method.

URL url = new URL ( some_url );
URLConnection connection = url.openConnection();

connection.connect();

// Cast to a HttpURLConnection
if ( connection instanceof HttpURLConnection)
{
HttpURLConnection httpConnection = (HttpURLConnection) connection;

int code = httpConnection.getResponseCode();

// do something with code .....
}
else
{
System.err.println ("error - not a http request!");
}


SOURCE : www.referjava.com

How can I create an event handling mechanism in Java? I'm used to ActiveX controls, which fire asynchronous events (i.e. when a control is finished a

The most common mechanism for this is the callback, where one class calls the method of another to notify it of an action or event. The class to be notified defines methods that will respond to specific events, such as when a mouse is clicked, dragged, or released. The AWT makes heavy use of this, with Listener interfaces. A class implements the event handling methods of a listener, and can then be registered with a component that generates these types of events. Classes that are event sources provide methods which register a listener, and at a later time when the event is generated, will invoke listener methods. The Abstract Windowing Toolkit (AWT) and Swing APIs would be a good place to start, to see if this suits your needs.


SOURCE : www.referjava.com

How can I poll a remote server, to see if it is still available? I'd like to check to see if the server has crashed, and if so, record the time.

If your application is a TCP server, the easiest way to do this is for a client to connect to it, using the java.net.Socket class. When the Socket is connected, if the server is down an IOException will be thrown, indicating that the server is not accepting connections.

However, this may not be a sufficient test for mission critical applications. What if the server has stalled, and will accept connections but not respond to them? In this situation, you'll need to write a valid request to the server (using the appropriate network protocol, such as HTTP or FTP). It doesn't matter what type of request is made, or what data is really returned (unless it is an error message). The only purpose of the request is to see if the server will response, and is still available for use.


SOURCE : www.referjava.com

Who created Java?

Java is still a relatively new language, so it is quite amusing to some to think that Java has a "history" behind it. One of the most frequent questions I've been getting lately though is about the origins of Java.

Java was created by engineers working at Sun Microsystems. The figure that stands out most of all is James Gosling, widely regarded as the "father" of Java. James and his team were working on a language whose original name was Oak. Oak was designed for embedded devices, such as mobile phones. The first publicly available version of Java, however, was as Java applets, in the original HotJava browser. From there, Java grew to what it is today.


SOURCE : www.referjava.com

How do I pass a primitive data type by reference? For example, how do I make an int passed to a function modifiable.

Java passes all primitive data types by value. This means that a copy is made, so that it cannot be modified. When passing Java objects, you're passing an object reference, which makes it possible to modify the object's member variables. If you want to pass a primitive data type by reference, you need to wrap it in an object.

The easiest of all is to pass it as an array (or even a Vector). Your array only needs to contain a single element, but wrapping it in an array means it can be changed by a function. Here's a simple example of it in action.

public static void increment(int[] array, int amount)
{
array[0] = array[0] + amount;
}

public static void main(String args[])
{
int[] myInt = { 1 };

increment (myInt, 5);

System.out.println ("Array contents : " + myInt[0]);
}
Of course, if you're modifying the contents of parameters passed to a method, you really should try to avoid this behavior. It increases the complexity of code, and really should be avoided. The preferred way is to return a value from a method, rather than modifying parameter values directly.


www.referjava.com

How do I debug my Java applets to see what's going wrong?

Often, when an applet behaves strangely or fails to work, the problem is hard to diagnose. Many applets behave fine under Netscape Navigator, only to fail under Internet Explorer (or vice versa). Sometimes a different Java Virtual Machine (JVM) will have less tolerance for a bug, and other times the fault lies in the actual JVM implementation.

The lack of information provided by the browser can be frustrating. However, there is a way to display a debugging console, which will provide developers with additional information. For example, an uncaught exception will generate an exception trace, telling you which method and which exception were involved. Both the later versions of Netscape Communicator and Internet Explorer support these debugging consoles.

To view the Java Console in Netscape Communicator
Load any page with an applet, and then select the following menu option
Communicator -> Tools -> Java Console


www.referjava.com

How do I get parameters from a HTML form when using servlets?

When extending javax.servlet.http.HttpServlet, you should override either of the following two methods: -

public void doGet(HttpServletRequest req,
HttpServletResponse res)
public void doPost(HttpServletRequest req,
HttpServletResponse res)
Both of these methods accept as a parameter a HttpServletRequest instance. This allows the servlet to obtain information about the browser request, including the parameters passed to the servlet. By using the String getParameter(String) method, you can request any parameter you need. If the parameter is not present, a null value will be returned.


www.referjava.com

How do I gray out components, and prevent users from using them?

Every AWT & Swing component inherits methods that will enable and disable it, from java.awt.Component. The setEnabled(boolean) method allows a component to be disabled, and later enabled. Previously, AWT components could be enabled and disabled by calling their enable() and disable() methods. However, these methods have been deprecated, and should no longer been used.

// Disable button (b)
b.setEnabled ( false );
// Enable button (b)
b.setEnabled ( true );


www.referjava.com

How do I make cookies expire after a set time period? For example, in five minutes time for security reasons

Depending on how you use the data stored in a cookie, it is often a good idea to make the cookie expire. Since anyone using the browser will have the cookie sent on their behalf, it may appear to be a legitimate user when in actual fact it is not. This often happens in places like Internet cafes, school or university computing labs, or libraries. If your cookie sends a user identifier that facilitates access to sensitive data, or allows changes to be made (for example, a web-based email service), then you should expire cookies after a small time period. If the user keeps using your servlet, you always have the option of resending the cookie with a longer duration.

To specify an expiration time, you can use the setMaxTime(int) method of javax.servlet.http.Cookie. It takes as a parameter the number of seconds before the cookie will expire. For example, for a five minute expiration, we would do the following :-

// Create a new cookie for userID from a fictitious
// method called getUserID
Cookie cookie = new Cookie ("userID", getUserID());

// Expire the cookie in five minutes (5 * 60)
cookie.setMaxTime( 300 );
When the cookie is sent back to the browser, using HttpServletResponse.addCookie(Cookie), it will only be returned by the browser until the expiration date occurs. If you'd prefer, you can also specify a negative value for setMaxTime(int), and the cookie will expire as soon as the browser exits. Note however that not everyone will shutdown their browser, and it might be available for minutes, hours even days. Finally, specifying a value of zero will expire the cookie instantly.


www.referjava.com

How do I read browser cookies from a servlet?

Reading cookies from a servlet is quite easy. You can gain access to any cookies sent by the browser from the javax.servlet.http.HttpServletRequest passed to the servlet's doGet, doPost, etc methods. HttpServletResponse offers a method, Cookies[] getCookies() which returns an array of Cookie objects. However, if no cookies are available, this value may be null, so be sure to check before accessing any array elements.

// Check for cookies
Cookie[] cookie_jar = request.getCookies();

// Check to see if any cookies exists
if (cookie_jar != null)
{
for (int i =0; i< cookies.length; i++)
{
Cookie aCookie = cookie_jar[i];
pout.println ("Name : " + aCookie.getName());
pout.println ("Value: " + aCookie.getValue());
}
}


www.referjava.com

How do I send cookies from a servlet?

HTTP is a stateless protocol, which makes tracking user actions difficult. One solution is to use a cookie, which is a small piece of data sent by a web browser every time it requests a page from a particular site. Servlets, and CGI scripts, can send cookies when a HTTP request is made - though as always, there is no guarantee the browser will accept it.

Cookies are represented by the javax.servlet.http.Cookie class. Cookie has a single constructor, which takes two strings (a key and a value).

// Create a new cookie
Cookie cookie = new Cookie ("counter", "1");
Adding a cookie to a browser is easy. Cookies are sent as part of a HTTPServletResponse, using the addCookie( Cookie ) method. You can call this method multiple times, but remember that most browsers impose a limit of ten cookies, and 4096 bytes of data per hostname.

public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException
{
response.addCookie(new Cookie("cookie_name", "cookie_value"));
}


www.referjava.com

How do I get the length of a string?

Working with strings under Java is far easier than with other languages. Most languages represent a string as a data type, or as an array of characters. Java however treats strings as an actual object, and provides methods that make string manipulation far easier.

Strings under Java are represented by the java.lang.String class. Since the java.lang package is imported by every Java application or applet, we can refer to it just as String. To determine the length of a String, simply call the String.length() method, which returns an int value.

String aString = "this is a string. what is my length?";
int length = aString.length();

System.out.println (aString);
System.out.println (length);
TIP - Remember that the String class is zero-indexed. Even though the String is of length n, you can only access characters in the range 0..n-1


www.referjava.com

How do I minimize and restore frames and JFrames?

This question stumped me when I first took a look at it. There is no minimize or restore method in JFrame, or java.awt.Frame for that matter. However, I knew there had to be a way - as JFrames frequently need to be restored programmatically. I suspected that the problem was a difference in terminology, and after a little searching, found the answer.

JFrame inherits the setState method from java.awt.Frame. This method allows you to change the state of a window from "iconified", back to "normal". This is, in actual fact, minimize and restore - but the documentation uses different terms. To minimize or restore a window, we simply call the setState method, and pass it a state parameter to indicate whether we want to minimize or restore the window..

For example, to minimize a Frame (or subclass, such as JFrame), we pass the 'iconified' parameter

myFrame.setState ( Frame.ICONIFIED );
To restore the frame to its normal state, we call the setState method with the 'normal' parameter

myFrame.setState ( Frame.NORMAL );
To demonstrate this effect, I've written a small demonstration, which you can compile and run. In the following example, a new frame is created, and then minimized. After a short delay, it is restored again.

import java.awt.*;

public class FrameTest
{
public static void main (String args[]) throws Exception
{
// Create a test frame
Frame frame = new Frame("Hello");
frame.add ( new Label("Minimize demo") );
frame.pack();

// Show the frame
frame.setVisible (true);

// Sleep for 5 seconds, then minimize
Thread.sleep (5000);
frame.setState ( Frame.ICONIFIED );

// Sleep for 5 seconds, then restore
Thread.sleep (5000);
frame.setState ( Frame.NORMAL );

// Sleep for 5 seconds, then kill window
Thread.sleep (5000);
frame.setVisible (false);
frame.dispose();

// Terminate test
System.exit(0);
}
}


www.referjava.com

Is Java Y2K compliant? Where can I find more information?

I'd like to give a big unconditional yes, but its not quite that simple. Java is more than a language - its a platform. There are many different virtual machines, by many different vendors, running on many different hardware and software architectures. Does that present a Y2K threat? Yes.

However, work is being done to prevent problems. Sun takes its commitments very seriously - for a comprehensive list of products and their Y2K status visit

http://www.sun.com/y2000/cpl.html

The problem is - will all Java Virtual Machines be ready in time. Remember that some are third party ports, or completely re-engineered versions. So there is still the potential for problems if you use non-Sun virtual machines. If you use third party class libraries, or code, you're also running some risk. Of course, a quick test to reassure you, might be to turn your computer's clock forward till after Jan 1 2000.


www.referjava.com

What are exceptions, and when should I use them?

Exception handling is an important feature of C++ and Java. Exceptions indicate unusual error conditions that occur during the execution of an application or applet. When you call an object method, and an "exceptional" event occurs (such as being unable to access a file or network resource), the method can stop execution, and "throw" an exception. This means that it passes an object (the exception), back to the calling code. That code can then handle the event, and deal with unusual conditions.

That's the theory of exception handling. Let's look at a practical example. Suppose my application had to read some data from a file. Most times, it will be able to read the data, and continue on without any problems - but what would happen if the file didn't exist? Our program might crash, without reporting any meaningful error message. Let's see how exception handling can help.

The following code snippet shows our code for reading a line of text from a data file. Note the use the try / catch keywords. This indicates that code within this block can throw an exception, and how we will deal it.

String line;

try
{
// This line throws an IOException if file not present
FileInputStream fin = new FileInputStream ("config.ini");

// Create a data input stream for reading a line of text
DataInputStream din = new DataInputStream( fin );

// Read line of text
line = din.readLine();
}
catch (IOException ioe)
{
// Exit gracefully with an error message
System.err.println
("An error occurred while reading config file");
System.exit(0);
}
Exception handling also has other benefits. In the past, programmers would check the return value for a null object, or a special numerical code that indicated failure. But, programmers being human, this value wouldn't always be checked. This lead to strange errors at run-time, and no meaningful error messages. When an exception is specified in the throws clause of an object method, it must be caught, or the compiler will generate an error message. This forces programmers to always provide some form of catch statement (though many choose to leave their catch statement blank).

Finally, exception handling can also make code more legible. Its easy to see where error conditions are being handled, and which error conditions are explicitly being looked at. This also separates programming code for "normal" situations from that of handler code for unusual events. In small applications, the advantages of this are not noticeable, but when debugging large and complex systems, it helps to reduce complexity and track down problems.


www.referjava.com

How can I change the gray background of an applet?

Applets use a default background of gray, which isn't very visually appealing, and very infrequently matches the background of the web page on which it is loaded. So unless you repaint the background yourself in the paint() method of your applet, you'll want to change its background as soon as the applet loads.

The best place to do it will be in your init() method. This means the applet will change color once it has finished loading. To change background color, you need to invoke the setBackground(Color) method. It accepts as a parameter any valid Color.

public void init()
{
setBackground ( Color.black );
}


www.referjava.com

What does certification involve?

Passing the Sun Certified Java Programmer exam involves answering a series of multiple choice questions. Sound easy enough? There's a little more to it though - you must select ALL the right answers, without missing any or adding extra ones. Often the difference between one answer and another is subtle, and it requires a good understanding of the language and the base Java APIs. There's no reference material allowed, and to make it even tougher, a score of 70% or over is required to pass.

The second level of certification involves an additional programming task. You'll be given specifications, and have to implement the system (involving actual coding). This involves a more extensive coverage of the Java APIs, but there's often more than one way to solve a problem.


www.referjava.com

What are the Java Certification exams?

Industry certification helps to distinguish skilled software developers from the pack, and to give employers an idea of the skill level of candidates. There's a certain amount of prestige associated with certification (ask anyone who has studied for, and passed a certification exam), and its usually a good measure of skills. Like other vendors (such as Microsoft), Sun Microsystems offers certification for for its flagship - the Java language. This certification is suited to commercial Java programmers and developers.

There are two levels of Java certification available currently, and there are plans to expand into three levels in the future (in conjunction with Netscape and other vendors). Currently, Sun offers the following :-

Sun Certified Java Programmer for JDK1.05, JDK1.5 & Java 5
Sun Certified Java Developer for JDK1.04, JDK1.4 & Java 4


www.referjava.com