Wednesday, July 29, 2009

Accessing protected URL in Java

Come through an elegant code yesterday. Somehow the content needs to be accessed from the database server which is password protected. A simple URL query would fetch the content. I've tried Apache commons. I could managed to access the content via plain java.net classes works for me pretty smoothly.

here is how

Authenticator.setDefault(new MyAuthenticator("user","password"));

URL url = new URL("http://localhost:5300/database?_query='for $a in collection('test')/types return $a'");
InputStream resultStream =url.openStream();

And the simple inner class
class MyAuthenticator extends Authenticator {
private String username, password;

public MyAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}

// This method is called when a password-protected URL is accessed
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
}

Are there any better way?

Monday, July 27, 2009

Returning null from methods in Java

It's best not to return null from a methods that returns an String type. instead return just empty string "". This will actually avoid extra checking in the calling method. Return variables can be created and initialized with empty (""). If any results constructed in the method, can be assigned to this result variable. if nothing constructed, it might fall on the last instruction that simply return the initialized variable.

Another approach can be using an Static String constant when empty string need to be requited.

It's best not to return null from a method that returns anarray type. Always returning an array, even if the array has zero length, greatly improves the generality of algorithms. If you
anticipate that your methods will return zero-length arrays frequently, you might be concerned about the performance implications of allocating many such arrays. To solve that problem, simply allocate a single array, and always return the same one, for example:
<code>private static final int ZERO_LENGTH_ARRAY[] = new int[0];</code>
This array is immutable (it can't be changed), and can be shared throughout the application.

We can return null in case of returning an Object.