Friday, August 5, 2016

Why for each loop doesn't throw ConcurrentModification exception in case List has only 2 elements


List<Person> first = new ArrayList<Person>();
        Person p1=new Person("p1", 1);
        Person p2=new Person("p2", 2);
        Person p3=new Person("p3", 3);
        
        first.add(p1);
        first.add(p2);
        first.add(p3);
        
        for(Person p: first)
        {
            first.remove(p);
        }

The above code will throw ConcurrentModificationException

Now remove the following code

first.add(p3);

And re-execute the code...

Now you'll see that no exception will be thrown...

What's the reason behind this?

Actually for-each loop uses Iterator behind the scenes

which gets converted to the following

        Iterator i = first.iterator();
        while(i.hasNext())
        {
            Person px = (Person)i.next();
            first.remove(px);
        } 

In case of two elements, here are the steps that are followed
  • Iterator is created
  • hasNext returns true
  • .next method returns the first element of the list
  • First element is removed. Now list contains only 1 element.
  • As iterator has already traversed one element and also list has 1 element, hasNext method will return false
  • Hence the loop terminates.
In case of three elements, here are the steps that are followed
  • Iterator is created
  • hasNext returns true
  • .next method returns the first element of the list
  • First element is removed. Now list contains 2 elements.
  • As iterator has already traversed one element and list has 2 elements, hasNext method will return true
  • control will enter the loop
  • .next method will see that iterator has been modified and hence throw a ConcurrentModificationException




Tuesday, January 19, 2016

Java exception handling best practices

Thanks to Java exception handling best practices

Before we dive into deep concepts of exception handling best practices, lets start with one of the most important concepts which is to understand that there are three general types of throwable classes in Java: checked exceptions, unchecked exceptions, and errors.

Type of exceptions





Checked exceptions are exceptions that must be declared in the throws clause of a method. They extend Exception and are intended to be an “in your face” type of exceptions. Java wants you to handle them because they somehow are dependent on external factors outside your program. A checked exception indicates an expected problem that can occur during normal system operation. Mostly these exception happen when you try to use external systems over network or in file system. Mostly, the correct response to a checked exception should be to try again later, or to prompt the user to modify his input.

Unchecked exceptions are exceptions that do not need to be declared in a throws clause. JVM simply doesn’t force you to handle them as they are mostly generated at runtime due to programmatic errors. They extend RuntimeException. The most common example is a NullPointerException [Quite scary.. Isn’t it?]. An unchecked exception probably shouldn’t be retried, and the correct action should be usually to do nothing, and let it come out of your method and through the execution stack. At a high level of execution, this type of exceptions should be logged.

Errors are serious runtime environment problems that are almost certainly not recoverable. Some examples are OutOfMemoryError, LinkageError, and StackOverflowError. They generally crash you program or part of program. Only a good logging practice will help you in determining the exact causes of errors.



User defined custom exceptions

Anytime when user feels that he wants to use its own application specific exception for some reasons, he can create a new class extending appropriate super class (mostly its Exception.java) and start using it in appropriate places. These user defined exceptions can be used in two ways:

1) Either directly throw the custom exception when something goes wrong in application

throw new DaoObjectNotFoundException("Couldn't find dao with id " + id);

2) Or wrap the original exception inside custom exception and throw it
catch (NoSuchMethodException e) {
  throw new DaoObjectNotFoundException("Couldn't find dao with id " + id, e);
}

Wrapping an exception can provide extra information to the user by adding your own message/ context information, while still preserving the stack trace and message of the original exception. It also allows you to hide the implementation details of your code, which is the most important reason to wrap exceptions.

Now lets start exploring the best practices followed for exception handling industry wise.




Best practices you must consider and follow

1) Never swallow the exception in catch block

catch (NoSuchMethodException e) {
   return null;
}
Doing this not only return “null” instead of handling or re-throwing the exception, it totally swallows the exception, losing the cause of error forever. And when you don’t know the reason of failure, how you would prevent it in future? Never do this !!

2) Declare the specific checked exceptions that your method can throw

public void foo() throws Exception { //Incorrect way
}
Always avoid doing this as in above code sample. It simply defeats the whole purpose of having checked exception. Declare the specific checked exceptions that your method can throw. If there are just too many such checked exceptions, you should probably wrap them in your own exception and add information to in exception message. You can also consider code refactoring also if possible.

public void foo() throws SpecificException1, SpecificException2 { //Correct way
}

3) Do not catch the Exception class rather catch specific sub classes

try {
   someMethod();
} catch (Exception e) {
   LOGGER.error("method has failed", e);
}
The problem with catching Exception is that if the method you are calling later adds a new checked exception to its method signature, the developer’s intent is that you should handle the specific new exception. If your code just catches Exception (or Throwable), you’ll never know about the change and the fact that your code is now wrong and might break at any point of time in runtime.

4) Never catch Throwable class

Well, its one step more serious trouble. Because java errors are also subclasses of the Throwable. Errors are irreversible conditions that can not be handled by JVM itself. And for some JVM implementations, JVM might not actually even invoke your catch clause on an Error.

5) Always correctly wrap the exceptions in custom exceptions so that stack trace is not lost

catch (NoSuchMethodException e) {
   throw new MyServiceException("Some information: " + e.getMessage());  //Incorrect way
}
This destroys the stack trace of the original exception, and is always wrong. The correct way of doing this is:
catch (NoSuchMethodException e) {
   throw new MyServiceException("Some information: " , e);  //Correct way
}

6) Either log the exception or throw it but never do the both

catch (NoSuchMethodException e) {
   LOGGER.error("Some information", e);
   throw e;
}
As in above example code, logging and throwing will result in multiple log messages in log files, for a single problem in the code, and makes life hell for the engineer who is trying to dig through the logs.

7) Never throw any exception from finally block

try {
  someMethod();  //Throws exceptionOne
} finally {
  cleanUp();    //If finally also threw any exception the exceptionOne will be lost forever
}
This is fine, as long as cleanUp() can never throw any exception. In the above example, if someMethod() throws an exception, and in the finally block also, cleanUp() throws an exception, that second exception will come out of method and the original first exception (correct reason) will be lost forever. If the code that you call in a finally block can possibly throw an exception, make sure that you either handle it, or log it. Never let it come out of the finally block.

8) Always catch only those exceptions that you can actually handle

catch (NoSuchMethodException e) {
   throw e; //Avoid this as it doesn't help anything
}

Well this is most important concept. Don’t catch any exception just for the sake of catching it. Catch any exception only if you want to handle it or, you want to provide additional contextual information in that exception. If you can’t handle it in catch block, then best advice is just don’t catch it only to re-throw it.


9) Don’t use printStackTrace() statement or similar methods

Never leave printStackTrace() after finishing your code. Chances are one of your fellow colleague will get one of those stack traces eventually, and have exactly zero knowledge as to what to do with it because it will not have any contextual information appended to it.


10) Use finally blocks instead of catch blocks if you are not going to handle exception

try {
  someMethod();  //Method 2
} finally {
  cleanUp();    //do cleanup here
}
This is also a good practice. If inside your method you are accessing some method 2, and method 2 throw some exception which you do not want to handle in method 1, but still want some cleanup in case exception occur, then do this cleanup in finally block. Do not use catch block.

11) Remember “Throw early catch late” principle

This is probably the most famous principle about Exception handling. It basically says that you should throw an exception as soon as you can, and catch it late as much as possible. You should wait until you have all the information to handle it properly.

This principle implicitly says that you will be more likely to throw it in the low-level methods, where you will be checking if single values are null or not appropriate. And you will be making the exception climb the stack trace for quite several levels until you reach a sufficient level of abstraction to be able to handle the problem.


12) Always clean up after handling the exception

If you are using resources like database connections or network connections, make sure you clean them up. If the API you are invoking uses only unchecked exceptions, you should still clean up resources after use, with try -- finally blocks. Inside try block access the resource and inside finally close the resource. Even if any exception occur in accessing the resource, then also resource will be closed gracefully.

13) Throw only relevant exception from a method

Relevancy is important to keep application clean. A method which tries to read a file; if throws NullPointerException then it will not give any relevant information to user. Instead it will be better if such exception is wrapped inside custom exception e.g. NoSuchFileFoundException then it will be more useful for users of that method.

14) Never use exceptions for flow control in your program

We have read it many times but sometimes we keep seeing code in our project where developer tries to use exceptions for application logic. Never do that. It makes code hard to read, understand and ugly.

15) Validate user input to catch adverse conditions very early in request processing

Always validate user input in very early stage, even before it reached to actual controller. It will help you to minimize the exception handling code in your core application logic. It also helps you in making application consistent if there is some error in user input.

For example: If in user registration application, you are following below logic:

1) Validate User
2) Insert User
3) Validate address
4) Insert address
5) If problem the Rollback everything

This is very incorrect approach. It can leave you database in inconsistent state in various scenarios. Rather validate everything in first place and then take the user data in dao layer and make DB updates. Correct approach is:

1) Validate User
2) Validate address
3) Insert User
4) Insert address
5) If problem the Rollback everything


16) Always include all information about an exception in single log message

LOGGER.debug(“Using cache sector A”);
LOGGER.debug(“Using retry sector B”);

Don’t do this.

Using a multi-line log message with multiple calls to LOGGER.debug() may look fine in your test case, but when it shows up in the log file of an app server with 400 threads running in parallel, all dumping information to the same log file, your two log messages may end up spaced out 1000 lines apart in the log file, even though they occur on subsequent lines in your code.

Do it like this:

LOGGER.debug(“Using cache sector A, using retry sector B”);

17) Pass all relevant information to exceptions to make them informative as much as possible

This is also very important to make exception messages and stack traces useful and informative. What is the use of a log, if you are not able to determine anything out of it. These type of logs just exist in your code for decoration purpose.

18) Always terminate the thread which it is interrupted

while (true) {
  try {
    Thread.sleep(100000);
  } catch (InterruptedException e) {} //Don't do this
  doSomethingCool();
}

InterruptedException is a clue to your code that it should stop whatever it’s doing. Some common use cases for a thread getting interrupted are the active transaction timing out, or a thread pool getting shut down. Instead of ignoring the InterruptedException, your code should do its best to finish up what it’s doing, and finish the current thread of execution. So to correct the example above:
while (true) {
  try {
    Thread.sleep(100000);
  } catch (InterruptedException e) {
    break;
  }
}
doSomethingCool();

19) Use template methods for repeated try-catch

There is no use of having a similar catch block in 100 places in your code. It increases code duplicity which does not help anything. Use template methods for such cases.

For example below code tries to close a database connection.
class DBUtil{
    public static void closeConnection(Connection conn){
        try{
            conn.close();
        } catch(SQLException ex){
            throw new RuntimeException("Cannot close connection", ex);
        }
    }
}
This type of method will be used in thousands of places in your application. Don’t put whole code in every place rather define above method and use it everywhere like below:
public void dataAccessCode() {
    Connection conn = null;
    try{
        conn = getConnection();
        ....
    } finally{
        DBUtil.closeConnection(conn);
    }
}

20) Document all exceptions in your application in javadoc

Make it a practice to javadoc all exceptions which a piece of code may throw at runtime. Also try to include possible course of action, user should follow in case these exception occur.

That’s all i have in my mind for now. If you found anything missing or you does not relate to my view on any point, drop me a comment. I will be happy to discuss.

Thursday, March 19, 2015

How to create a table with fixed columns and headers


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style type="text/css">
        table.main
        {
            width: 700px;
            height: 221px;
            table-layout: fixed;
        }
        table.root
        {
            table-layout: fixed;
        }
        table.content
        {
            table-layout: fixed;
            width: 1890px;
        }
        table.head
        {
            table-layout: fixed;
            width: 1890px;
        }
        table.frozen
        {
            table-layout: fixed;
        }
        td
        {
            line-height: 28px;
        }
        div.horizontal-scroll
        {
            width: 703px;
            height: 22px;
            overflow: hidden;
            overflow-x: scroll;
            border: solid 1px #666;
        }
        div.horizontal-scroll div
        {
            width: 2173px;
            height: 1px;
        }
        div.vertical-scroll
        {
            height: 227px;
            width: 22px;
            overflow: hidden;
            overflow-y: scroll;
            border: solid 1px #666;
        }
        div.vertical-scroll div
        {
            height: 377px;
            width: 1px;
        }
        td.inner
        {
            border-left: 1px solid #666;
            border-bottom: 1px solid #666;
            padding: 3px;
            height: 28px;
        }
        td.frozencol
        {
            border-right: 1px double #666;
            width: 200px;
        }
        td.col1
        {
            border-left: none;
            width: 100px;
        }
        td.bottomcol
        {
            /*border-bottom: 1px solid #666;*/
        }
        .col2, .col3, .col4, .col5, .col6, .col7, .col8, .col9, .col10
        {
            width: 200px;
            overflow: hidden;
            text-overflow: ellipses;
            white-space: nowrap;
        }
        td.head
        {
            /*border-bottom: 1px solid #666;*/
            background-color: #efefef;
            border-top: 1px solid #666;
        }
        .rightcol
        {
            border-right: 1px solid #666;
        }
        .toprow
        {
            border-top: 0px;
        }
        div.root
        {
            margin-left: 0px;
            overflow: hidden;
            width: 200px;
            height: 28px;
            border-bottom: 1px solid #666;
        }
        div.frozen
        {
            overflow: hidden;
            width: 200px; /*border-bottom: 1px solid #666;*/
            height: 200px;
        }
        div.divhead
        {
            overflow: hidden;
            height: 28px;
            width: 500px;
            border-left: 1px solid #666;
            border-right: 1px solid #666; /*border-bottom: 0px solid #666;*/
            border-bottom: 1px solid #666;
        }
        div.content
        {
            overflow: hidden;
            width: 500px;
            height: 200px;
            border-left: 1px solid #666;
            border-right: 1px solid #666; /*border-bottom: 1px solid #666;*/
        }
        td.tablefrozencolumn
        {
            width: 200px;
            border-right: 3px solid #666;
        }
        td.tablecontent
        {
            width: 501px;
        }
        td.tableverticalscroll
        {
            width: 24px;
        }
        div.ff-fill
        {
            height: 23px;
            width: 23px;
            background-color: #ccc;
            border-right: 1px solid #666;
            border-bottom: 1px solid #666;
        }
    </style>
    <!--[if LT IE 7]>
<style type="text/css"> 
    div.ff-fill
    {
       height: 10px;
       width:20px;
    }
    td.tablecontent
    {
       width: 500px;
    }
    div.horizontal-scroll 
    { 
       width:700px; 
       height:20px;
    } 
    div.horizontal-scroll div
    {
       width: 2100px;
    }
    div.vertical-scroll 
    { 
       height:228px; 
       width:20px;
    } 
    div.vertical-scroll div
    { 
       height:306px; 
    } 
    td.tableverticalscroll
    {
       width:22px;
    }
</style>
<![endif]-->
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table border="0" cellpadding="0" cellspacing="0" class='main'>
            <tr>
                <td class='tablefrozencolumn'>
                    <div id='divroot' class='root'>
                        <table border="0" cellpadding="0" cellspacing="0" width="100%" class='root'>
                            <tr>
                                <td class='inner frozencol colwidth head'>
                                    Head0
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div id='divfrozen' class='frozen'>
                        <table border="0" cellpadding="0" cellspacing="0" width="100%" class='frozen'>
                            <tr>
                                <td class='inner frozencol toprow'>
                                    Col0Row2
                                </td>
                            </tr>
                            <tr>
                                <td class='inner frozencol'>
                                    Col0Row3
                                </td>
                            </tr>
                            <tr>
                                <td class='inner frozencol'>
                                    Col0Row4
                                </td>
                            </tr>
                            <tr>
                                <td class='inner frozencol'>
                                    Col0Row5
                                </td>
                            </tr>
                            <tr>
                                <td class='inner frozencol'>
                                    Col0Row6
                                </td>
                            </tr>
                            <tr>
                                <td class='inner frozencol'>
                                    Col0Row7
                                </td>
                            </tr>
                            <tr>
                                <td class='inner frozencol'>
                                    Col0Row8
                                </td>
                            </tr>
                            <tr>
                                <td class='inner frozencol'>
                                    Col0Row9
                                </td>
                            </tr>
                            <tr>
                                <td class='inner frozencol'>
                                    Col0Row10
                                </td>
                            </tr>
                            <tr>
                                <td class='inner frozencol bottomcol rightcol'>
                                    Col1Row11
                                </td>
                            </tr>
                        </table>
                    </div>
                </td>
                <td class='tablecontent'>
                    <div id='headscroll' class='divhead'>
                        <table border="0" cellpadding="0" cellspacing="0" class='head'>
                            <tr>
                                <td class='inner col1 head'>
                                    Head 1
                                </td>
                                <td class='inner col2 head'>
                                    Head 2
                                </td>
                                <td class='inner col3 head'>
                                    Head 3
                                </td>
                                <td class='inner col4 head'>
                                    Head 4
                                </td>
                                <td class='inner col5 head'>
                                    Head 5
                                </td>
                                <td class='inner col6 head'>
                                    Head 6
                                </td>
                                <td class='inner col7 head'>
                                    Head 7
                                </td>
                                <td class='inner col8 head'>
                                    Head 8
                                </td>
                                <td class='inner col9 head'>
                                    Head 9
                                </td>
                                <td class='inner col10 head rightcol'>
                                    Head 10
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div id='contentscroll' class='content' onscroll='reposHead(this);'>
                        <table border="0" cellpadding="0" cellspacing="0" class='content' id='innercontent'>
                            <tr>
                                <td class='inner col1 toprow'>
                                    Col1Row2
                                </td>
                                <td class='inner col2'>
                                    Col2Row2
                                </td>
                                <td class='inner col3'>
                                    Col3Row2
                                </td>
                                <td class='inner col4'>
                                    Col4Row2
                                </td>
                                <td class='inner col5'>
                                    Col5Row2
                                </td>
                                <td class='inner col6'>
                                    Col6Row2
                                </td>
                                <td class='inner col7'>
                                    Col7Row2
                                </td>
                                <td class='inner col8'>
                                    Col8Row2
                                </td>
                                <td class='inner col9'>
                                    Col9Row2
                                </td>
                                <td class='inner col10 rightcol'>
                                    Col10Row2
                                </td>
                            </tr>
                            <tr>
                                <td class='inner col1'>
                                    Col1Row3
                                </td>
                                <td class='inner'>
                                    Col2Row3
                                </td>
                                <td class='inner'>
                                    Col3Row3
                                </td>
                                <td class='inner'>
                                    Col4Row3
                                </td>
                                <td class='inner'>
                                    Col5Row3
                                </td>
                                <td class='inner'>
                                    Col6Row3
                                </td>
                                <td class='inner'>
                                    Col7Row3
                                </td>
                                <td class='inner'>
                                    Col8Row3
                                </td>
                                <td class='inner'>
                                    Col9Row3
                                </td>
                                <td class='inner rightcol'>
                                    Col10Row3
                                </td>
                            </tr>
                            <tr>
                                <td class='inner col1'>
                                    Col1Row4
                                </td>
                                <td class='inner'>
                                    Col2Row4
                                </td>
                                <td class='inner'>
                                    Col3Row4
                                </td>
                                <td class='inner'>
                                    Col4Row4
                                </td>
                                <td class='inner'>
                                    Col5Row4
                                </td>
                                <td class='inner'>
                                    Col6Row4
                                </td>
                                <td class='inner'>
                                    Col7Row4
                                </td>
                                <td class='inner'>
                                    Col8Row4
                                </td>
                                <td class='inner'>
                                    Col9Row4
                                </td>
                                <td class='inner rightcol'>
                                    Col10Row4
                                </td>
                            </tr>
                            <tr>
                                <td class='inner col1'>
                                    Col1Row5
                                </td>
                                <td class='inner'>
                                    Col2Row5
                                </td>
                                <td class='inner'>
                                    Col3Row5
                                </td>
                                <td class='inner'>
                                    Col4Row5
                                </td>
                                <td class='inner'>
                                    Col5Row5
                                </td>
                                <td class='inner'>
                                    Col6Row5
                                </td>
                                <td class='inner'>
                                    Col7Row5
                                </td>
                                <td class='inner'>
                                    Col8Row5
                                </td>
                                <td class='inner'>
                                    Col9Row5
                                </td>
                                <td class='inner rightcol'>
                                    Col10Row5
                                </td>
                            </tr>
                            <tr>
                                <td class='inner col1'>
                                    Col1Row6
                                </td>
                                <td class='inner'>
                                    Col2Row6
                                </td>
                                <td class='inner'>
                                    Col3Row6
                                </td>
                                <td class='inner'>
                                    Col4Row6
                                </td>
                                <td class='inner'>
                                    Col5Row6
                                </td>
                                <td class='inner'>
                                    Col6Row6
                                </td>
                                <td class='inner'>
                                    Col7Row6
                                </td>
                                <td class='inner'>
                                    Col8Row6
                                </td>
                                <td class='inner'>
                                    Col9Row6
                                </td>
                                <td class='inner rightcol'>
                                    Col10Row6
                                </td>
                            </tr>
                            <tr>
                                <td class='inner col1'>
                                    Col1Row7
                                </td>
                                <td class='inner'>
                                    Col2Row7
                                </td>
                                <td class='inner'>
                                    Col3Row7
                                </td>
                                <td class='inner'>
                                    Col4Row7
                                </td>
                                <td class='inner'>
                                    Col5Row7
                                </td>
                                <td class='inner'>
                                    Col6Row7
                                </td>
                                <td class='inner'>
                                    Col7Row7
                                </td>
                                <td class='inner'>
                                    Col8Row7
                                </td>
                                <td class='inner'>
                                    Col9Row7
                                </td>
                                <td class='inner rightcol'>
                                    Col10Row7
                                </td>
                            </tr>
                            <tr>
                                <td class='inner col1'>
                                    Col1Row8
                                </td>
                                <td class='inner'>
                                    Col2Row8
                                </td>
                                <td class='inner'>
                                    Col3Row8
                                </td>
                                <td class='inner'>
                                    Col4Row8
                                </td>
                                <td class='inner'>
                                    Col5Row8
                                </td>
                                <td class='inner'>
                                    Col6Row8
                                </td>
                                <td class='inner'>
                                    Col7Row8
                                </td>
                                <td class='inner'>
                                    Col8Row8
                                </td>
                                <td class='inner'>
                                    Col9Row8
                                </td>
                                <td class='inner rightcol'>
                                    Col10Row8
                                </td>
                            </tr>
                            <tr>
                                <td class='inner col1'>
                                    Col1Row9
                                </td>
                                <td class='inner'>
                                    Col2Row9
                                </td>
                                <td class='inner'>
                                    Col3Row9
                                </td>
                                <td class='inner'>
                                    Col4Row9
                                </td>
                                <td class='inner'>
                                    Col5Row9
                                </td>
                                <td class='inner'>
                                    Col6Row9
                                </td>
                                <td class='inner'>
                                    Col7Row9
                                </td>
                                <td class='inner'>
                                    Col8Row9
                                </td>
                                <td class='inner'>
                                    Col9Row9
                                </td>
                                <td class='inner rightcol'>
                                    Col10Row9
                                </td>
                            </tr>
                            <tr>
                                <td class='inner col1'>
                                    Col1Row10
                                </td>
                                <td class='inner'>
                                    Col2Row10
                                </td>
                                <td class='inner'>
                                    Col3Row10
                                </td>
                                <td class='inner'>
                                    Col4Row10
                                </td>
                                <td class='inner'>
                                    Col5Row10
                                </td>
                                <td class='inner'>
                                    Col6Row10
                                </td>
                                <td class='inner'>
                                    Col7Row10
                                </td>
                                <td class='inner'>
                                    Col8Row10
                                </td>
                                <td class='inner'>
                                    Col9Row10
                                </td>
                                <td class='inner rightcol'>
                                    Col10Row10
                                </td>
                            </tr>
                            <tr>
                                <td class='inner col1 bottomcol'>
                                    Col1Row11
                                </td>
                                <td class='inner bottomcol'>
                                    Col2Row11
                                </td>
                                <td class='inner bottomcol'>
                                    Col3Row11
                                </td>
                                <td class='inner bottomcol'>
                                    Col4Row11
                                </td>
                                <td class='inner bottomcol'>
                                    Col5Row11
                                </td>
                                <td class='inner bottomcol'>
                                    Col6Row11
                                </td>
                                <td class='inner bottomcol'>
                                    Col7Row11
                                </td>
                                <td class='inner bottomcol'>
                                    Col8Row11
                                </td>
                                <td class='inner bottomcol'>
                                    Col9Row11
                                </td>
                                <td class='inner bottomcol rightcol'>
                                    Col10Row11
                                </td>
                            </tr>
                        </table>
                    </div>
                </td>
                <td class='tableverticalscroll' rowspan="2">
                    <div class='vertical-scroll' onscroll='reposVertical(this);'>
                        <div>
                        </div>
                    </div>
                    <div class='ff-fill'>
                    </div>
                </td>
            </tr>
            <tr>
                <td colspan="3">
                    <div class='horizontal-scroll' onscroll='reposHorizontal(this);'>
                        <div>
                        </div>
                    </div>
                </td>
            </tr>
        </table>
    </div>

    <script language='javascript' type='text/javascript'>
        function reposHead(e) {
            var h = document.getElementById('headscroll');
            h.scrollLeft = e.scrollLeft;
            var f = document.getElementById('divfrozen');
            f.scrollTop = e.scrollTop;
        }
        function reposHorizontal(e) {
            var h = document.getElementById('headscroll');
            var c = document.getElementById('contentscroll');
            h.scrollLeft = e.scrollLeft;
            c.scrollLeft = e.scrollLeft;

            var sh = document.getElementById('hscrollpos');
            sh.innerHTML = e.scrollLeft;

            var ch = document.getElementById('contentwidth');
            var ic = document.getElementById('innercontent');
            ch.innerHTML = ic.clientWidth;  //c.scrollWidth;

            var ch2 = document.getElementById('contentheight');
            ch2.innerHTML = ic.clientHeight;  //c.scrollWidth;

            var sp = document.getElementById('scrollwidth');
            sp.innerHTML = e.scrollWidth;
        }
        function reposVertical(e) {
            var h = document.getElementById('divfrozen');
            var c = document.getElementById('contentscroll');
            h.scrollTop = e.scrollTop;
            c.scrollTop = e.scrollTop;

            var sh = document.getElementById('vscrollpos');
            sh.innerHTML = e.scrollTop;

            var ch = document.getElementById('contentheight');
            ch.innerHTML = c.scrollHeight;

            var sp = document.getElementById('scrollheight');
            sp.innerHTML = e.scrollHeight;

        }
    </script>

    <br />
    <br />
    Horizonal scroll pos:<span id='hscrollpos'>0</span>px<br />
    Vertical scroll pos:<span id='vscrollpos'>0</span>px<br />
    Height of inner content elt:<span id='contentheight'>0</span>px<br />
    Width of inner content elt:<span id='contentwidth'>0</span>px<br />
    Height of scroll elt:<span id='scrollheight'>0</span>px<br />
    Width of scroll elt:<span id='scrollwidth'>0</span>px<br />
    </form>
</body>
</html>

Friday, August 29, 2014

How to create multilevel menu's in JSP using recursion..

There was a requirement where in I need to create multi-level menu's in a JSP

A role has certain set of Privileges.
Each privilege may or may not have child privileges..

Where Privilege has child privileges, it was desired to display a sub menu..

So this is how I have achieved...
First thing you need to know about this is how to create multi level menu's using HTML and CSS.
(http://javakafunda.blogspot.in/2014/08/how-to-create-multi-level-menus-using.html)

and once you learn that you'll have to use recursion in JSP to achieve the above requirement.

I'll just put the core logic here which is the base of this..

Create a parent jsp (lets say LoginSuccess.jsp)

<ul id="nav">
<c:forEach var="role" items="${userDbObject.roles}"> 
  <li><a href="#item1">${role.roleName}</a>
   <ul> 
   <c:forEach var="priv" items="${role.privileges}">
     <c:set value="${priv}" var="myPriv" scope="request"/>
     <jsp:include page="showPrivileges.jsp"/>
   </c:forEach>
   </ul>
 </li>   
</c:forEach>
</ul>


Create a showPrivileges.jsp as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:if test="${empty myPriv.childPrivileges}">
  <c:set var="url" value="${myPriv.privUrl}" />
  <c:if test="${not empty url}">
   <li><a href="${url}" >${myPriv.privilegeName}</a></li>
  </c:if>
  <c:if test="${empty url}">
   <li><a href="unimplemented.jsp" >unimplemented.jsp</a></li>
  </c:if>
</c:if>
<c:if test="${not empty myPriv.childPrivileges}">
   <li><a href="#" >${myPriv.privilegeName}</a>
    <ul> 
    <c:forEach var="childPriv" items="${myPriv.childPrivileges}">
      <c:set value="${childPriv}" var="myPriv" scope="request"/>
      <jsp:include page="showPrivileges.jsp"/>
    </c:forEach>
    </ul>
   </li>
</c:if>

Thursday, August 28, 2014

How to create multi-level menu's using HTML and CSS

Create a style.css as follows

body {
 font: normal .8em/1.5em Arial, Helvetica, sans-serif;
 background: #ebebeb;
 width: 900px;
 margin: 100px auto;
 color: #666;
}

a {
 color: #333;
}
#nav {
 margin: 0;
 padding: 7px 6px 0;
 /*background: #7d7d7d  repeat-x 0 -110px;*/
 background:#7d7d7d;
 line-height: 100%;

 border-radius: 2em;
 -webkit-border-radius: 2em;
 -moz-border-radius: 2em;

 -webkit-box-shadow: 0 1px 3px rgba(0,0,0, .4);
 -moz-box-shadow: 0 1px 3px rgba(0,0,0, .4);
}
#nav li {
 margin: 0 5px;
 padding: 0 0 8px;
 float: left;
 position: relative;
 list-style: none;
}


/* main level link */
#nav a {
 font-weight: bold;
 color: #e7e5e5;
 text-decoration: none;
 display: block;
 padding:  8px 20px;
 margin: 0;

 -webkit-border-radius: 1.6em;
 -moz-border-radius: 1.6em;
 
 text-shadow: 0 1px 1px rgba(0,0,0, .3);
}
#nav a:hover {
 background: #000;
 color: #666;
}

/* main level link hover */
#nav .current a, #nav li:hover > a {
 background: #000  ;
 color: #fff;
 border-top: normal 0px #f8f8f8;

 -webkit-box-shadow: 0 1px 1px rgba(0,0,0, .2);
 -moz-box-shadow: 0 1px 1px rgba(0,0,0, .2);
 box-shadow: 0 1px 1px rgba(0,0,0, .2);

 text-shadow: 0 0px 0 rgba(255,255,255, 1);
}

/* sub levels link hover */
#nav ul li:hover a, #nav li:hover li a {
 background: none;
 border: none;
 color: #666;

 -webkit-box-shadow: none;
 -moz-box-shadow: none;
}
#nav ul a:hover {
 background: #0078ff  repeat-x 0 -100px !important;
 color: #fff !important;

 -webkit-border-radius: 0;
 -moz-border-radius: 0;

 text-shadow: 0 0px 0px rgba(0,0,0, .1);
}

/* dropdown */
#nav li:hover > ul {
 display: block;
}

/* level 2 list */
#nav ul {
 display: none;

 margin: 0;
 padding: 0;
 width: 185px;
 position: absolute;
 top: 35px;
 left: 0;
 background: #ddd  repeat-x 0 0;
 border: solid 1px #b4b4b4;

 -webkit-border-radius: 10px;
 -moz-border-radius: 10px;
 border-radius: 10px;

 -webkit-box-shadow: 0 1px 3px rgba(0,0,0, .3);
 -moz-box-shadow: 0 1px 3px rgba(0,0,0, .3);
 box-shadow: 0 1px 3px rgba(0,0,0, .3);
}
#nav ul li {
 float: none;
 margin: 0;
 padding: 0;
}

#nav ul a {
 font-weight: normal;
 text-shadow: 0 1px 0 #fff;
}

/* level 3+ list */
#nav ul ul {
 left: 181px;
 top: -3px;
}

/* rounded corners of first and last link */
#nav ul li:first-child > a {
 -webkit-border-top-left-radius: 9px;
 -moz-border-radius-topleft: 9px;

 -webkit-border-top-right-radius: 9px;
 -moz-border-radius-topright: 9px;
}
#nav ul li:last-child > a {
 -webkit-border-bottom-left-radius: 9px;
 -moz-border-radius-bottomleft: 9px;

 -webkit-border-bottom-right-radius: 9px;
 -moz-border-radius-bottomright: 9px;
}

/* clearfix */
#nav:after {
 content: ".";
 display: block;
 clear: both;
 visibility: hidden;
 line-height: 0;
 height: 0;
}
#nav {
 display: inline-block;
} 
html[xmlns] #nav {
 display: block;
}
 
* html #nav {
 height: 1%;
}

Create body of your HTML as follows

<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
                <!-- Navigation -->  
                <ul id="nav"> 
                    <li><a href="#">Home</a></li>  
                    <li><a href="#">Categories</a>  
                        <ul>  
                            <li><a href="#">All</a>  
                                <ul>  
                                    <li><a href="#">Category 1</a>  
                                        <ul class="droprightMenu">  
                                            <li>
            <a href="#">Category 1.2</a>
                                                 <ul> 
                                                    <li><a href="#">Category 1.2.1</a></li>
                                                 </ul>                                                  
                                            </li>  
                                            <li>
            <a href="#">Category 1.3</a>
            <ul> 
                                                    <li><a href="#">Category 1.3.1</a></li>
                                                 </ul>  
           </li> 
                                            <li><a href="#">Category 1.4</a></li>  
                                        </ul>
         </li>  
                                    <li><a href="#">Category 2</a></li>  
                                    <li><a href="#">Category 3</a></li>  
                                    <li><a href="#">Category 4</a></li>  
                                </ul>
       </li>  
                            <li><a href="#">Manage</a></li>  
                        </ul>
     </li>  
      
                    <li><a href="#">Profile</a>  
                        <ul>  
                            <li><a href="#">Login</a></li>  
                            <li><a href="#">Register</a></li>  
                            <li><a href="#">Edit Profile</a></li>  
                            <li><a href="#">My Posts</a></li>  
                            <li><a href="#">Logout</a></li>  
                        </ul>
     </li>  
                    <li><a href="#">Help</a></li>  
                </ul>  
</body>



And the output will look like:










Tuesday, August 26, 2014

How to implement a self join in hibernate

Source : http://viralpatel.net/blogs/hibernate-self-join-annotations-one-to-many-mapping/

We have a create table in the database.

CREATE TABLE employee (
employee_id NUMBER(10) NOT NULL,
firstname VARCHAR2(50) NULL DEFAULT NULL,
lastname VARCHAR(50) NULL DEFAULT NULL,
manager_id NUMBER(10) NULL DEFAULT NULL,
PRIMARY KEY ('employee_id'),
CONSTRAINT 'FK_MANAGER' FOREIGN KEY ('manager_id') REFERENCES 'employee' ('employee_id')
);

Here in Employee table, we defined a column MANAGER_ID which is mapped to the same table’s primary key. Thus for each employee we will store its manager’s id also. Manager will be yet another employee in this table

We will be using annotations to implement this in hibernate:


@Entity
@Table(name="EMPLOYEE")
public class Employee {
    @Id
    @Column(name="EMPLOYEE_ID")
    @GeneratedValue
    private Long employeeId;
     
    @Column(name="FIRSTNAME")
    private String firstname;
     
    @Column(name="LASTNAME")
    private String lastname;
     
    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name="manager_id")
    private Employee manager;
 
    @OneToMany(mappedBy="manager")
    private Set<Employee> subordinates = new HashSet<Employee>();
 
    public Employee() {
    }
 
    public Employee(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }
         
    // Getter and Setter methods
}


Note that in Employee entity class, we defined two new attributes: Employee manager and Set subordinates. Attribute manager is mapped with @ManyToOne annotation and subordinates is mapped with @OneToMany. Also within @OneToMany attribute we defined mappedBy="manager" making manager as the relationship owner and thus which manages the foreign relationship within table.

Also the annotation @JoinColumn is defined on manager making it the relationship owner. @JoinColumn defines the joining column which in our case is manager_id.

Monday, August 25, 2014

How to integrate Spring and Hibernate

Here are the few tips I have gathered on how to integrate spring and hibernate.

Create your bean.xml something like this...

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


<bean id="usrMgmtServiceImpl"   class="com.usermanagement.service.impl.UserManagementServiceImpl">
<property name="privService" ref="privService"/>
<property name="roleService" ref="roleService"/>
<property name="userService" ref="userService"/>
</bean>

<!--               DB CONFIGURATION BEGINS  -->

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>Connection.properties</value></property>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
<property name="driverClassName">  
<value>${db.driverClassName}</value>
</property>  
<property name="url">  
<value>${db.url}</value>
</property>
<property name="username">  
<value>${db.username}</value>
</property>
<property name="password">  
<value>${db.password}</value>
</property>
</bean>

<bean id="mysessionFactory"  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- These are the POJO objects, you have to mention these here... -->
<property name="annotatedClasses">
<list>
<value>com.usermanagement.pojo.User</value>
<value>com.usermanagement.pojo.Role</value>
<value>com.usermanagement.pojo.Privilege</value>
<value>com.usermanagement.pojo.Password</value>
<value>com.usermanagement.pojo.PasswordPolicy</value>
</list>
</property>  

<property name="hibernateProperties">  
<props>  
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>

<prop key="hibernate.cache.use_second_level_cache">true</prop> 
<!--<prop key="hibernate.cache.provider_class">org.hibernate.cache.SingletonEhCacheProvider</prop>-->
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> 
</props>  
</property>  
</bean>  
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">  
<property name="sessionFactory" ref="mysessionFactory"></property>  
</bean>      
<!--               DB CONFIGURATION ENDS  --> 


<bean id="privService" class="com.usermanagement.service.impl.PrivilegeServiceImpl">
<property name="privDao" ref="privDao"/>
</bean>
<bean id="roleService" class="com.usermanagement.service.impl.RoleServiceImpl">
<property name="roleDao" ref="roleDao"/>
</bean>
<bean id="userService" class="com.usermanagement.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>



<bean id="privDao" class="com.usermanagement.dao.impl.PrivilegeDAOImpl" >
<property name="template" ref="template"></property>
</bean>
<bean id="roleDao" class="com.usermanagement.dao.impl.RoleDAOImpl" >
<property name="template" ref="template"></property>
</bean>
<bean id="userDao" class="com.usermanagement.dao.impl.UserDAOImpl">
<property name="template" ref="template"></property>
</bean>

</beans>

The list of jars that you might need are
  1. antlr-2.7.6.jar
  2. asm-1.5.3.jar
  3. axis2-spring-1.6.1.jar
  4. cglib-2.1_3.jar
  5. commons-collections-3.1.jar
  6. commons-dbcp-1.4.jar
  7. commons-logging-1.0.4.jar
  8. commons-pool-1.6.jar
  9. dom4j-1.6.1.jar
  10. hibernate-3.2.0.ga.jar
  11. hibernate-3.2.6.jar
  12. hibernate-annotations-3.4.0.GA.jar
  13. hibernate-commons-annotations-3.1.0.GA.jar
  14. hibernate-core-3.3.0.SP1.jar
  15. hibernate-entitymanager.jar
  16. hibernate-jpa-2.0-api-1.0.0.Final.jar
  17. jta-1.1.jar
  18. log4j-1.2.14.jar
  19. ojdbc14.jar
  20. org.springframework.asm-3.0.0.RELEASE.jar
  21. org.springframework.beans-3.0.0.RELEASE.jar
  22. org.springframework.context-3.0.0.RELEASE.jar
  23. org.springframework.core-3.0.0.RELEASE.jar
  24. org.springframework.expression-3.0.0.RELEASE.jar
  25. org.springframework.jdbc-3.0.0.RELEASE.jar
  26. org.springframework.orm-3.0.0.RELEASE.jar
  27. org.springframework.web.servlet-3.0.1.RELEASE-A.jar
  28. slf4j-api-1.6.1.jar
  29. spring-tx-3.0.0.RELEASE.jar


Wednesday, July 30, 2014

Two player game program - e.g. TIC TAC TOE...

This is an abstract State class
public abstract class State {
 
  // This method is abstract, the extending class has to give the implementation
  // It will return a list of all the possible children from the current state.
  public abstract List<State> getChildren();
  public abstract String getTurn();
  public abstract void setTurn(String turn);
 
  // Find out who is the winner from the current state.
  public abstract String getWinner();
 
  // Check if the game has been finished or not.
  public abstract boolean isGameOver();
 
  // I have given the implementation specifically for TIC-TAC-TOE.
  // You can override this functionality in the extending class according to your game requirements.
  // 
  // This function will give the score of the current state.
  // Then you can compare it with its siblings to check which state will be better to move to..
  //
 public int minimax()
 {
  
  if(!getWinner().equals(""))
  {
   if("X".equalsIgnoreCase(getWinner()))
   {
    return 1;
   }
   if("O".equalsIgnoreCase(getWinner()))
   {
    return -1;
   }
   if("draw".equalsIgnoreCase(getWinner()))
   {
    return 0;
   }
  }
  List<State> children = getChildren();
  if(getTurn().equals("X"))
  {
   int maxScore = -100;
   for(State child : children)
   {
    int childScore = child.minimax();
    if(childScore > maxScore)
    {
     maxScore = childScore;
    }
   }
   return maxScore;
  }
  else
  {
   int minScore = 100;
   for(State child : children)
   {
    int childScore = child.minimax();
    if(childScore < minScore)
    {
     minScore = childScore;
    }
   }
   return minScore;   
  }

 }
}

Extend the above State class and give some implementations...as follows:
Lets assume the class to be TttState...
We'll override the abstract methods of the parent class State..

Give a member variable that'll hold the current state of your game...In my case, I have taken it as array..

// This variable is going to hold the current state of your game.
 // It can be any depending on your game requirements...
 private String state[][] = null ;

Give a copy constructor

public TttState(State x)
 {
  TttState tState = (TttState)x;
  state = new String[3][3];
  for(int i=0;i<=2; i++)
  {
   for(int j=0; j<=2;j++)
   {
    this.state[i][j]=tState.state[i][j];
   }
  }
  this.turn = x.getTurn();
 }
Give a default constructor
public TttState() {
  state = new String[3][3];
  for(int i=0;i<=2; i++)
  {
   for(int j=0; j<=2;j++)
   {
    this.state[i][j]="";
   }
  }
  this.turn = "X";
 }
Give a toString implementation, so that you can print the current state
public String toString()
 {
  StringBuilder sb = new StringBuilder("");
  for(int i=0;i<=2; i++)
  {
   for(int j=0; j<=2;j++)
   {
    if(state[i][j].equals(""))
    {
     sb.append("-");
    }
    else
    {
     sb.append(state[i][j]);
    }
    sb.append("\t");
   }
   sb.append("\n");
  }
  return sb.toString();
 }
Override the method getWinner() as follows
public String getWinner()
 {
  // ROW CHECK BEGINS 
  if(state[0][0].equalsIgnoreCase("X") && state[0][1].equalsIgnoreCase("X") && state[0][2].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[0][0].equalsIgnoreCase("O") && state[0][1].equalsIgnoreCase("O") && state[0][2].equalsIgnoreCase("O"))
  {
   return "O";
  }
  if(state[1][0].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[1][2].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[1][0].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[1][2].equalsIgnoreCase("O"))
  {
   return "O";
  }
  if(state[2][0].equalsIgnoreCase("X") && state[2][1].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[2][0].equalsIgnoreCase("O") && state[2][1].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
  {
   return "O";
  }
  
  // COLUMN CHECK BEGINS 
  if(state[0][0].equalsIgnoreCase("X") && state[1][0].equalsIgnoreCase("X") && state[2][0].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[0][0].equalsIgnoreCase("O") && state[1][0].equalsIgnoreCase("O") && state[2][0].equalsIgnoreCase("O"))
  {
   return "O";
  }
  if(state[0][1].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][1].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[0][1].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][1].equalsIgnoreCase("O"))
  {
   return "O";
  }
  if(state[0][2].equalsIgnoreCase("X") && state[1][2].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[0][2].equalsIgnoreCase("O") && state[1][2].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
  {
   return "O";
  }
  // DIAGNONAL CHECKS 
  if(state[0][0].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[0][0].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
  {
   return "O";
  }
  
  if(state[0][2].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][0].equalsIgnoreCase("X"))
  {
   return "X";
  }
  if(state[0][2].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][0].equalsIgnoreCase("O"))
  {
   return "O";
  }  
  int nonBlank = 0;
  for(int i=0;i<=2;i++)
  {
   for(int j=0;j<=2;j++)
   {
    if(!state[i][j].equals(""))
    {
     nonBlank++;
    }
   }
  }
  if(nonBlank==9)
  {
   return "draw";
  }
  
  return "";
 }
Override the method isGameOver()
public boolean isGameOver()
 {
  if(!getWinner().equals("") && !getWinner().equals("draw"))
  {
   return true;
  }
  else
  {
   return false;
  }
 }
Override the method getChildren()
@Override
 public List<State> getChildren() {
  List<State> children = new ArrayList<State>();
  if(turn.equals("X"))
  {
   for(int i=0;i<=2; i++)
   {
    for(int j=0; j<=2;j++)
    {
     if(state[i][j].equals(""))
     {
      TttState child = new TttState(this);
      child.state[i][j]="X";
      String newTurn = "O";
      child.setTurn(newTurn);
      children.add(child);
     }
    }
   }
  }
  else
  {
   for(int i=0;i<=2; i++)
   {
    for(int j=0; j<=2;j++)
    {
     if(state[i][j].equals(""))
     {
      TttState child = new TttState(this);
      child.state[i][j]="O";
      String newTurn = "X";
      child.setTurn(newTurn);
      children.add(child);
     }
    }
   }
  }
  return children;
 }
Override getTurn and setTurn
public String getTurn() {
  return turn;
 }

 public void setTurn(String turn) {
  this.turn = turn;
 }
Your main program will look something like this:
public static void main(String args[])
 {
  TttState x = new TttState();
  System.out.println("WINNER : " + x.getWinner());
  x.setTurn("X");
  Scanner sc = new Scanner(System.in);
  while(!x.isGameOver())
  {
   String xIndex = sc.nextLine();
   String yIndex = sc.nextLine();
   int xint = Integer.parseInt(xIndex);
   int yint = Integer.parseInt(yIndex);
   x.getState()[xint][yint]="X";
   x.setTurn("O");
   int minScore = 100;
   List<State> children = x.getChildren();
   TttState bestMove = new TttState(x);
   for(State child : children)
   {
    int childScore = child.minimax();
    // We are using < because we are always evaluating
    // the best move from the options that O player has....
    if(childScore < minScore)
    {
     minScore = childScore;
     bestMove = (TttState)child;
     bestMove.setTurn("X");
    }
   }
   System.out.print(bestMove);
   x = bestMove;
  }
  System.out.println("GAME OVER...");

 }


Monday, July 7, 2014

Things to remember while creating Custom Exception in Java

Things to remember while creating Custom Exception in Java

1) Don’t' use Exception to control application behaviour. Exception handling is very expensive as it require native calls to copy stacktrace, each time exception is created.

2) While creating custom exception, prefer to create an unchecked, Runtime exception than a checked exception, especially if you know that client is not going to take any reactive action other than logging.

3) If your custom exception is created by passing another exception, then always contain original Exception as source; use constructor which takes Exception rather than only message String.

4) Apart from providing default no argument constructor on your custom Exception class, consider providing at least two more constructors, one which should accept a failure message and other which can accept another Throwable as cause.

5) If possible avoid creating custom Exception and re-use existing, standard Exception classes from JDK itself. Most of the time you will realize that all you need is a form of IllegalArgumentException or ParseException or something similar.

6) While defining custom Exception, one of the most common mistake programmer make is to think that constructor is inherited from java.lang.Exception class, for example they think that their Exception class will automatically inherit default no argument constructor and the one which takes a String message. This is not true. Constructor is not inherited in Java, not even default constructor. It's actually added by compiler rather than inherited from parent class. That's why I have declared two constructor, one with String parameter and other as Throwable parameter :

public NoSuchProductException(String message, int productId) 
{ 
    super(message); 
    this.productId = productId; 
} 
public NoSuchProductException(String message, int productId, Throwable cause) 
{ 
    super(message, cause); 
    this.productId = productId; 
}

This is actually standard way of creating custom Exception in Java. In order to save time, you can even create template of above class in Eclipse IDE.

7) For readable code, it's good practice to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class e.g. instead of naming your class IncorrectPassword, name it IncorrectPasswordException.

There is lot more given on the following link:
http://javarevisited.blogspot.in/2014/06/how-to-create-custom-exception-in-java.html

How to use decorator pattern, when the class to decorate is final

I have an inbuilt class in java - String
Now I have made 3 classes
  1. AddHashCode
  2. ToLowerCase
  3. AddLength


I want to create a class, which has toString method overridden while selecting one or more of the above classes.

For example:
I want a class, which has toString method, which has the features of AddHashCode and ToLowerCase
or
I want a class, which has toString method, which has the features of all of the above classes.

So, lets do it with Decorator Pattern.

But the problem with Decorator Pattern is, that the classes you create must implement the String class.....But String class is final..
So I have tweaked the Decorator Design Pattern a bit, though it closely resembles the purpose of Decorator design pattern.

Create the following three classes

Class AddHashCode

public class AddHashCode {
	private String t ;
	public AddHashCode(String s)
	{
		t = s;
	}
	public String toString()
	{
		return t.toString() + ":" + t.hashCode();
	}
}

Class ToLowerCase

public class ToLowerCase {
	String ac;
	public ToLowerCase(String ac)
	{
		this.ac = ac;
	}
	public String toString()
	{
		return ac.toString().toLowerCase();
	}
}


Class AddLength

public class AddLength{
	private String t ;
	public AddLength(String s)
	{
		t = s;
	}
	public String toString()
	{
		return t.toString() + ":"+t.toString().length();
	}
}

Use this as follows:
public class Main {
	public static void main(String[] args)
	{
		ToLowerCase x = new ToLowerCase
                                    (new AddHashCode
                                         (new String("YOGESH").toString()).toString());
		System.out.println(x.toString());
		AddHashCode y = new AddHashCode
                                    (new ToLowerCase
                                         (new AddLength(new String("YOGESH").toString())
                                    .toString())
                                .toString());
		System.out.println(y.toString());
	}
}

Friday, March 21, 2014

How to make a dropdown as readonly in html

I encountered a problem where in it was required to make a drop down readonly.

While searching over internet i found THIS
But the solution mentioned there, didn't appeal me much. As i had to make server side code changes while saving the value using the hidden field.

How do we do this? The common thought is to disable the drop down menu. Well, yes, but there's a choice

When you use disabled, it prevents the user from using the drop down, or form element. You can see the year, but it is grayed out. Your mouse can't select or change it, and you can't tab to it with the keyboard. Disabled is used a lot with checkboxes. Sounds like just what we want, but you unknowingly might have caused yourself a small development problem.

The problem is "disabled" does just that. Disabled means that in your $_POST or $_GET that element will not show up in your controller. If you want to use the year in your controller, you won't be able to recover it from that form. All you can do it look at the value on the web page.

What if we want to read the year, prevent the user from changing the year, and recover the year in the form data sent back to the controller. The solution for this is

Make a replica of your dropdown with a different name and different id.

Hide your original drop down with <span style="display:none">
This makes the element available in the form, so it will flow to the server side as well.
At the same time, it will give a look and feel of disabled to the user.

Example :

<span style="display:none">
<select style="width:400px;"  name="agentName">
            <option value="${coltuserprofile.belongsToOcn}">
                  <c:out value="${coltuserprofile.firstName}/${coltuserprofile.belongsToOcn}"/>
            </option>
</select>
</span>
<select style="width:400px;"  name="agentNameDisplay" disabled="disabled">
<option value="${coltuserprofile.belongsToOcn}">
            <c:out value="${coltuserprofile.firstName}/${coltuserprofile.belongsToOcn}"/>
      </option>
</select>


Friday, March 7, 2014

Exception handling in java

Thanks to https://today.java.net/article/2006/04/04/exception-handling-antipatterns#antipatterns

Basic Exception Concepts

One of the most important concepts about exception handling to understand is that there are three general types of throwable classes in Java: checked exceptions, unchecked exceptions, and errors.

Checked exceptions are exceptions that must be declared in the throws clause of a method. They extend Exception and are intended to be an "in your face" type of exceptions. A checked exception indicates an expected problem that can occur during normal system operation. Some examples are problems communicating with external systems, and problems with user input. Note that, depending on your code's intended function, "user input" may refer to a user interface, or it may refer to the parameters that another developer passes to your API. Often, the correct response to a checked exception is to try again later, or to prompt the user to modify his input.

Unchecked exceptions are exceptions that do not need to be declared in a throws clause. They extend RuntimeException. An unchecked exception indicates an unexpected problem that is probably due to a bug in the code. The most common example is a NullPointerException. There are many core exceptions in the JDK that are checked exceptions but really shouldn't be, such as IllegalAccessException and NoSuchMethodException. An unchecked exception probably shouldn't be retried, and the correct response is usually to do nothing, and let it bubble up out of your method and through the execution stack. This is why it doesn't need to be declared in a throws clause. Eventually, at a high level of execution, the exception should probably be logged (see below).

Errors are serious problems that are almost certainly not recoverable. Some examples are OutOfMemoryError, LinkageError, and StackOverflowError.

Creating Your Own Exceptions

Most packages and/or system components should contain one or more custom exception classes. There are two primary use cases for a custom exception. First, your code can simply throw the custom exception when something goes wrong. For example:

throw new MyObjectNotFoundException("Couldn't find    object id " + id);

Second, your code can wrap and throw another exception. For example:

catch (NoSuchMethodException e) 
{  
    throw new MyServiceException("Couldn't process      request", e);
}

Wrapping an exception can provide extra information to the user by adding your own message (as in the example above), while still preserving the stack trace and message of the original exception. It also allows you to hide the implementation details of your code, which is the most important reason to wrap exceptions. For instance, look at the Hibernate API. Even though Hibernate makes extensive use of JDBC in its implementation, and most of the operations that it performs can throw SQLException, Hibernate does not expose SQLException anywhere in its API. Instead, it wraps these exceptions inside of various subclasses of HibernateException. Using the approach allows you to change the underlying implementation of your module without modifying its public API.

Antipatterns


Log and Throw

catch (NoSuchMethodException e) 
{  
    LOG.error("Blah", e);  
    throw e;
}
catch (NoSuchMethodException e) 
{  
    LOG.error("Blah", e);  
    throw new MyServiceException("Blah", e);
}
catch (NoSuchMethodException e) 
{  
    e.printStackTrace();  
    throw new MyServiceException("Blah", e);
}
All of the above examples are equally wrong. This is one of the most annoying error-handling antipatterns. Either log the exception, or throw it, but never do both. Logging and throwing results in multiple log messages for a single problem in the code, and makes life hell for the support engineer who is trying to dig through the logs.

Throwing Exception

public void foo() throws Exception { 

This is just sloppy, and it completely defeats the purpose of using a checked exception. It tells your callers "something can go wrong in my method." Real useful. Don't do this. Declare the specific checked exceptions that your method can throw. If there are several, you should probably wrap them in your own exception (see "Throwing the Kitchen Sink" below.)

Throwing the Kitchen Sink

Example:

public void foo() throws MyException,    
AnotherException, SomeOtherException,    YetAnotherException{

Throwing multiple checked exceptions from your method is fine, as long as there are different possible courses of action that the caller may want to take, depending on which exception was thrown. If you have multiple checked exceptions that basically mean the same thing to the caller, wrap them in a single checked exception.

Catching Exception

try 
{  
    foo();
} 
catch (Exception e) 
{  
    LOG.error("Foo failed", e);
}

This is generally wrong and sloppy. Catch the specific exceptions that can be thrown. The problem with catching Exception is that if the method you are calling later adds a new checked exception to its method signature, the developer's intent is that you should handle the specific new exception. If your code just catches Exception (or worse, Throwable), you'll probably never know about the change and the fact that your code is now wrong.

Destructive Wrapping

catch (NoSuchMethodException e) 
{  
    throw new MyServiceException("Blah: " + e.getMessage());
}

This destroys the stack trace of the original exception, and is always wrong.

Log and Return Null

Example:

catch (NoSuchMethodException e) 
{  
    LOG.error("Blah", e);  
    return null;
}
catch (NoSuchMethodException e) 
{  
    e.printStackTrace();  
    return null;
} 

Although not always incorrect, this is usually wrong. Instead of returning null, throw the exception, and let the caller deal with it. You should only return null in a normal (non-exceptional) use case (e.g., "This method returns null if the search string was not found.").

Catch and Ignore

Example:

catch (NoSuchMethodException e) 
{  
    return null;
}

This one is insidious. Not only does it return null instead of handling or re-throwing the exception, it totally swallows the exception, losing the information forever.

Throw from Within Finally

Example:
try 
{  
    blah();
} 
finally 
{  
    cleanUp();
}

This is fine, as long as cleanUp() can never throw an exception. In the above example, if blah() throws an exception, and then in the finally block, cleanUp() throws an exception, that second exception will be thrown and the first exception will be lost forever. If the code that you call in a finally block can possibly throw an exception, make sure that you either handle it, or log it. Never let it bubble out of the finally block.


Multi-Line Log Messages

Example:
LOG.debug("Using cache policy A");
LOG.debug("Using retry policy B");

Always try to group together all log messages, regardless of the level, into as few calls as possible. So in the example above, the correct code would look like:

LOG.debug("Using cache policy A, using retry policy B"); 

Using a multi-line log message with multiple calls to log.debug() may look fine in your test case, but when it shows up in the log file of an app server with 500 threads running in parallel, all spewing information to the same log file, your two log messages may end up spaced out 1000 lines apart in the log file, even though they occur on subsequent lines in your code.

Unsupported Operation Returning Null

Example:
public String foo() 
{  
    // Not supported in this implementation.  
    return null;
}

When you're implementing an abstract base class, and you're just providing hooks for subclasses to optionally override, this is fine. However, if this is not the case, you should throw an UnsupportedOperationException instead of returning null. This makes it much more obvious to the caller why things aren't working, instead of her having to figure out why her code is throwing some random NullPointerException




Wednesday, March 5, 2014

In JSTL/JSP when do I have to use and when can I just say ${myVar}

Source : http://stackoverflow.com/questions/6574776/in-jstl-jsp-when-do-i-have-to-use-cout-value-myvar-and-when-can-i-just

In JSTL/JSP when do I have to use <c:out value="${myVar}"/> and when can I just say ${myVar}


I've been doing this the whole time in my JSP code:
<c:out value="${myVar}"/>

Today I just realized for the first time that I seem to be able to use this shorter version just as well:
${myVar}

It works without <c:out>!

Perhaps this is because my page is declared like this:

<%@ page language="java" contentType="text/html; 
charset=utf-8" pageEncoding="utf-8" isELIgnored="false" %>

So, my question is, can I replace in my code with this shorter version? Is there any reason to keep using ? Or are there places where I might still need it?

Solution:


<c:out> does more than simply outputting the text. It escapes the HTML special chars.
Use it (or ${fn:escapeXml()}) every time you're not absolutely sure that the text doesn't contain any of these characters: ", ', <, >, &. Else, you'll have invalid HTML (in the best case), a broken page, or cross-site scripting attacks (in the worst case).

I'll give you a simple example so that you understand.
If you develop a forum, and someone posts the following message, and you don't use <c:out> to display this message, you'll have a problem:

<script>while (true) alert("you're a loser");</script>

Monday, March 3, 2014

duplicate import try, using auto-import="false"

How to use same entity class in two different packages in hibernate?


Source : http://isolasoftware.it/2011/10/14/hibernate-and-jpa-error-duplicate-import-try-using-auto-importfalse/

Using Hibernate and JPA you cannot have two classes with the same name (on different packages) mapped. This raise an error at runtime:
Caused by: org.hibernate.DuplicateMappingException: duplicate import: MyClass refers to both


To solve this issue on the Entity annotation of com.intre.MyClass and com.dummy.Class add the property name.

package com.intre;
@Entity(name = "com.intre.myclass")
@Table(name = "MyClass")
public class MyClass

package com.dummy;
@Entity(name = "com.dummy.myclass")
@Table(name = "MyClass")
public class MyClass