Friday, August 20, 2010

Java Common Mistakes (Part 1)

1. Returning Null, a method which returns a collection or an array,
Null should never be returned from a method returning a collection or an array. Instead return a empty array (a static final empty array) or one of the empty collections (e.g. Collections.EMPTY_LIST assuming the client should not be modifying the collection).

2. Unnecessary use of thread safety of StringBuffer
Use StringBuilder rather then StringBuffer, unless synchronization is required. StringBuilder is not thread safe, and therefore avoids the synchronization overhead of StringBuffer.

3. Not taking advantage of ‘toString()’
Overriding toString() method gives you a cheap way to provide human-readable labels for objects in output.

Bad:
System.out.println("Author: "+person.getName());

Good:
class Person {
...
public String toString() {
return this.getName();
}
}
...
System.out.println("Author: "+person);

4. Instatiation of immutable objects
Creating new instances of immutable primitive type wrappers (such as Number subclasses and Booleans) wastes the memory and time needed for allocating new objects. Static valueOf() method works much faster than a constructor and saves the memory, as it caches frequently used instances.

Bad:
Integer i = new Integer(0);
Boolean b = new Boolean(true);

Good:
Integer i = Integer.valueOf(0);
Boolean b = Boolean.valueOf(true); // or Boolean.TRUE

5. Unbuffered I/O
Reading and writing I/O streams byte-by-byte is too expensive, as every read()/write() call refers to the underlying native (JNI) I/O subsystem. Usage of buffered streams reduces the number of native calls and improves I/O performance considerably.

Bad:
InputStream in = new FileInputStream(f); int b; while ((b = in.read()) != -1) {     ... }
Good:
InputStream in = new BufferedInputStream(new FileInputStream(f));
...


6. ‘equals()’ does not check for null argument

If you override equals() method in your class, always check if an argument is null. If a null value is passed, equals() must unconditionally return false (no NullPointerException should be thrown!).

Bad:
class Person {
...
public boolean equals(Object o) {
return (o instanceof Person) &&
this.getName().equals(((Person)o).getName());
}
...
}

Good:
class Person {
...
public boolean equals(Object o) {
return (o != null) &&
(o instanceof Person) &&
this.getName().equals(((Person)o).getName());
}
...
}

class Person {



public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Person))
return false;

Person that = (Person)o;
….

7. ‘equals()’ is overridden while ‘hashCode()’ is not
If you override equals() in your class, always provide a custom implementation of hashCode() that returns the same hash code value for two or more equal objects:

a.equals(b) ? a.hashCode() == b.hashCode()

This is, in fact, a general contract defined by Java API Specification. Violation of this rule (which is likely the case if equals() method is overridden while hashCode() is inherited from Object) may cause numerous bugs and unexpected behaviours.

Note that the reverse rule: two or more unequal objects must have different hash codes, or

!a.equals(b) ? a.hashCode() != b.hashCode()


8. Difference between == and .Equals() Method

Value Type: == and .Equals() methods compare two objects by value.

Ex: int a = 5; int b = 5;

Console.WriteLine(a==b); Output: true
Console.writeLine(a.Equals(b)); Output: true

Reference Type: == performs an identity comparison, i.e. it will only return true if both references point to the same object.

While Equals() method is expected to perform a value comparison.

Ex: StringBuilder s1 = new StringBuilder(“Yup”);

StringBuilder s2 = new StringBuilder(“Yup”);

Console.WriteLine(s1==s2); Output : false

Console.WriteLine(s1.Equals(s2)); Output: true

In above example, s1 and s2 are different objects hence “==” returns false, but they are equivalent hence “Equals()” method returns true.

Note: There is an exception of this rule, i.e. when you use “==” operator with string class it compares value rather than identity.

When To use:

For value comparison, with Value Tyep use “==” operator and use “Equals()” method while performing value comparison with Reference Type.


HTTP DIGEST Authentication

HTTP digest authentication is performed by the browser upon request by the web server and based on a username, password, and realm. However, in this case your password is digested with the secure MD5 algorithm before it is sent by the browser.

Digest Authentication is just like HTTP BASIC Authentication. The only difference between basic and digest authentication is the specification of the authentication method and password encryption method.

Digest authentication is specified in an application's deployment descriptor as follows:

<login-config>
<auth-method>DIGEST</auth-method>
<realm-name>Digest Authentication Example</realm-name>
</login-config>

Hope this is useful! Enjoy!

HTTP Form Authentication

Form-based authentication is defined in the servlet specification. Form-based authentication allows you to control the look and feel of the login page and login-error page. When a client attempts to access a protected web resource, the web container activates the Form based authentication mechanism that has been configured for that resource and a login page is displayed. If the login is successfull then the pretected resource is displayed or an error page is displayed if login fails.

Form-based authentication is not secure because passwords are transmitted as clear text.

Form-based authentication works like basic authentication. Form-based Authentication with Tomcat Server 6 requires the following steps:

1. Create a login page.
In a Form-based authentication, username, password form fields and form action are defined in the Servlet Specification. They are j_username, j_password, and j_security_check respectively. They must be used for Form-based login.

Example /login.jsp:
<form action='j_security_check' method='post'>
<table>
<tr><td>Name:</td>
<td><input type='text' name='j_username'></td></tr>
<tr><td>Password:</td>
<td><input type='password' name='j_password' size='8'></td>
</tr>
</table>
<input type='submit' value='login'>
</form>

2. Create an error page that will be displayed if login fails.
The error page displays an error message and provides a link back to the login page.

Example /error.jsp:
<html> <head> <title>Error!</title></head>
<body>
<font size='4' color='red'>
The username and password you supplied are not valid.
</p>
Click <a href='<%= response.encodeURL("login.jsp") %>'>here</a> to retry login </body> </form> </html> 3. In the deployment descriptor, specify FORM as the authentication method, login page and error page. Page is only accessed by role1 and role2 Example /WEB-INF/web.xml: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> <web-app> <security-constraint>
<web-resource-collection>
<web-resource-name>protected resource page</web-resource-name>
<url-pattern>/protected-page.jsp</url-pattern>
</web-resource-collection>

<auth-constraint>

<role-name>role1</role-name>
<role-name>role2</role-name>
</auth-constraint>
</security-constraint>

<login-config>
<auth-method>FORM</auth-method>
<realm-name>Form Authentication Example</realm-name>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-config>
</login-config>
</web-app>

4. In Tomcat 6 Server, usernames and passwords are associated with roles in $TOMCAT_HOME/conf/tomcat-users.xml,

<tomcat-users>
<user name="user1" password="password" roles="role1" />
<user name="user2" password="passwd" roles="role2" />
</tomcat-users>

5. You are done. Now, restart the Tomcat 6 Server and try to access the protected resource from Browser.

Hope this is useful! Enjoy!

HTTP Basic Authentication

Basic authentication is defined by the HTTP/1.1 specification. It is very simple HTTP authentication method. When a client attempts to access a protected web resource, the web container activates the HTTP authentication mechanism that has been configured for that resource and the server prompts for a username and password. If the server will be able to authenticate client, then provides access to the resource otherwise the it will not be granted access to the resource and the process repeats.

HTTP basic authentication is not particularly secure. It sends user names and passwords over the Internet as text that is uu-encoded (Unix-to-Unix encoded) but not encrypted.

Basic authentication follows the steps below
1. An attempt is made to access a protected JSP page—/protected-page.jsp.

Example JSP page /protected-page.jsp:
<html><head><title>A Protected Page</title></head>
<body>
<p>
User principal: <%= request.getUserPrincipal().getName() %>.<br/>
User name: <%= request.getRemoteUser() %>.<br/>
Request Authenticated with: <%= request.getAuthType() %>.<br/>
</p>
<p>
<% if(request.isUserInRole("role1")) { %>
You are in role1<br/>
<% } else {%>
You are not in role2<br/>
<% } %>

<% if(request.isUserInRole("role2")) { %>
You are in role2<br/>
<% } else {%>
You are not in role1<br/>
<% } %>
</p>
</body>
</html>

The client is presented with a dialog box asking for name and password. The client submits the user name and password to the server. After authentication, the JSP page is displayed.

2. The protected JSP page is specified as a protected resource in the application's deployment descriptor file, web.xml. Also, specified BASIC as the authentication method and page is only accessed by role1 and role2.

Example deployment descriptor /WEB-INF/web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>

<security-constraint>

<web-resource-collection>
<web-resource-name>protected resource page</web-resource-name>
<url-pattern>/protected-page.jsp</url-pattern>
</web-resource-collection>

<auth-constraint>

<role-name>role1</role-name>
<role-name>role2</role-name>
</auth-constraint>
</security-constraint>

<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Basic Authentication Example</realm-name>
</login-config>
</web-app>


3. In Tomcat 6 Server, usernames and passwords are associated with roles in $TOMCAT_HOME/conf/tomcat-users.xml,

<tomcat-users>
<user name="user1" password="password" roles="role1" />
<user name="user2" password="passwd" roles="role2" />
</tomcat-users>

4. You are done. Now, restart the Tomcat 6 Server and try to access the protected resource from Browser.

Hope this is useful! Enjoy!

Thursday, August 19, 2010

HTTP Authentication

In the context of HTTP transaction, when you try to access a protected web resource, the web container activates the authentication mechanism that has been configured for that resource.
You can specify the following authentication mechanisms:

* HTTP basic authentication
* Form-based login authentication
* Client certificate authentication
* Mutual authentication
* Digest authentication

HTTP basic authentication:
As the name implies, it is the simplest method of authentication and for a long time was the most common authentication method used.

Hope this is useful! Enjoy!


With basic authentication, the following steps occur:

1. A client will request to access a protected resource.
2. The web server returns a dialog box as a response to the client request that requests the user name and password.
3. The client submits the user name and password to the server.
4. The server validates the credentials in the specified realm and, if successful, returns the requested protected resource.

HTTP basic authentication is not particularly secure. Basic authentication sends user names and passwords over the Internet as text that is uu-encoded (Unix-to-Unix encoded) but not encrypted.


Form-based login authentication:
Form-based authentication works like basic authentication, except that you specify a login page that is displayed instead of a dialog and an error page that's displayed if login fails. Also form-based authentication allows you to control the look and feel of the login page.

With form-based authentication, the following steps occur:

1. A client will request to access a protected resource.
2. If the client is unauthenticated, the server redirects the client to a login page.
3. The client submits the login form to the server.
4. The server attempts to authenticate the user.
1. If the authentication succeeds, the authenticated user’s principal is checked to ensure it is in a role that is authorized to access the resource. If the user is authorized, the server redirects the client to the resource using the stored URL path.
2. If authentication fails, the client is forwarded or redirected to an error page.

Like basic authentication, form-based authentication is not secure because passwords are transmitted as clear text.

Client certificate authentication:
HTTPS Client Authentication requires the client to possess a Public Key Certificate (PKC). If you specify client authentication, the web server will authenticate the client using the client’s public key certificate.

HTTPS Client Authentication is a more secure method of authentication than either basic or form-based authentication. It uses HTTP over SSL (HTTPS), in which the server authenticates the client using the client’s Public Key Certificate (PKC). Secure Sockets Layer (SSL) technology provides data encryption, server authentication, message integrity, and optional client authentication for a TCP/IP connection. You can think of a public key certificate as the digital equivalent of a passport. It is issued by a trusted organization, which is called a certificate authority (CA), and provides identification for the bearer.


Mutual authentication:
The server and the client authenticate each other in mutual authentication. There are two types of mutual authentication:

1. Certificate-based mutual authentication
2. User name-password-based mutual authentication

In certificate-based mutual authentication, the following steps occur:

1. A client requests access to a protected resource.
2. The web server presents its certificate to the client.
3. The client verifies the server's certificate.
4. If successful, the client sends its certificate to the server.
5. The server verifies the client's credentials.
6. If successful, the server grants access to the protected resource requested by the client.

In user name-password-based mutual authentication, the following steps occur:

1. A client requests access to a protected resource.
2. The web server presents its certificate to the client.
3. The client verifies the server's certificate.
4. If successful, the client sends its user name and password to the server, which verifies the client's credentials.
5. If the verification is successful, the server grants access to the protected resource requested by the client.


Digest authentication:
HTTP digest authentication is like HTTP basic authentication. HTTP digest authentication authenticates a user based on a user name and a password. However, the authentication is performed by transmitting the password in an encrypted form which is much more secure than the simple base64 encoding used by basic authentication.

With digest-based authentication, the following steps occur:

1. A client will request to access a protected resource.
2. The web server returns a dialog box as a response to the client request that requests the user name and password.
3. The client submits the user name and password to the server.
4. The server validates the credentials in the specified realm and, if successful, returns the requested protected resource.

Tuesday, August 10, 2010

javas...: Java One Liner...

javas...: Java One Liner...: "1. Static methods can not be overwritten. A call to a static method is dependent on the type of the identifier and not on the object's class..."

Thursday, August 5, 2010

Java One Liner...

1. Static methods can not be overwritten. A call to a static method is dependent on the type of the identifier and not on the object's class.

2. String fileContent = new Scanner(new File("test.txt" )).useDelimiter("\\z").next(); it reads in the entire file at once.

3. A Monostate object has static member variables only. So all instances of a Monostate class share the same state. This is a rare pattern and it is used less.

4. Antipatterns -- "a commonly occurring solution to a problem that generates decidedly negative consequences".

5. Use “==” operator while performing value comparison, with Value Type and use “Equals()” method while performing value comparison with Reference Type.