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

Wednesday, February 26, 2014

SOAP Version Mismatch: SOAP Version "SOAP 1.2 Protocol" in request does not match the SOAP version "SOAP 1.1 Protocol" of the Web service.

We were getting the below error in our project, when trying to invoke a web service.

[Server:server-one] 07:29:12,927 ERROR [stderr] (http-/10.99.12.28:8080-13) org.springframework.ws.soap.client.SoapFaultClientException: [ISS.0088.9168] SOAP Version Mismatch: SOAP Version "SOAP 1.2 Protocol" in request does not match the SOAP version "SOAP 1.1 Protocol" of the Web service.
[Server:server-one] 07:29:12,928 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:37)
[Server:server-one] 07:29:12,929 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:774)
[Server:server-one] 07:29:12,929 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:600)
[Server:server-one] 07:29:12,929 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:537)
[Server:server-one] 07:29:12,930 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:384)
[Server:server-one] 07:29:12,930 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:378)
[Server:server-one] 07:29:12,931 ERROR [stderr] (http-/10.99.12.28:8080-13)   at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:370)

Solution:
The solution lies in the configuration files used by spring.
Here in our project, the version specified in this file was 1.2 where as the web service was expecting 1.1

<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
    <property name="soapVersion">
        <util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_11" />
    </property>
</bean>



How to break a list into smaller sublists of equal size

// chops a list into non-view sublists of length L
static <T> List<List<T>> chopped(List<T> list, final int L) {
    List<List<T>> parts = new ArrayList<List<T>>();
    final int N = list.size();
    for (int i = 0; i < N; i += L) {
        parts.add(new ArrayList<T>(
            list.subList(i, Math.min(N, i + L)))
        );
    }
    return parts;
}

Usage:
List<Integer> numbers = Collections.unmodifiableList(
    Arrays.asList(5,3,1,2,9,5,0,7)
);
List<List<Integer>> parts = chopped(numbers, 3);
System.out.println(parts); // prints "[[5, 3, 1], [2, 9, 5], [0, 7]]"
parts.get(0).add(-1);
System.out.println(parts); // prints "[[5, 3, 1, -1], [2, 9, 5], [0, 7]]"
System.out.println(numbers); // prints "[5, 3, 1, 2, 9, 5, 0, 7]" (unmodified!)

Monday, February 24, 2014

Generate java classes using xjc

Source : Generate java class from xml schema using jaxb xjc command


Before using JAXB to create or access an XML document from Java application, we have to do the following steps:

1.Binding the schema
* Binding a schema means generating a set of Java classes that represents the schema for the XML document (Schema is not required for simple marshalling and unmarshalling).

2.Marshal the content tree /Unmarshal the XML document.
* After binding the schema, you can convert Java objects to and from XML document.
In this example we will see how to bind the schema. For that, we use Java Architecture for XML Binding (JAXB) binding compiler tool, xjc, to generate Java classes from XML schema.

‘xjc’ Command Line Options

Usage:

xjc [-options ...] … [-b ] …
If dir is specified, all schema files in it will be compiled.
If jar is specified, /META-INF/sun-jaxb.episode binding file will be compiled.


Complete list of options for ‘xjc’ is available in the help option.

xjc -help

Generate Java classes using ‘xjc’

Follow the steps below to generate a set of Java source files from XML schema.
  1. Create a new Java project folder and name it as “JAXBXJCTool”.
  2. Create a new XSD file and name it as “employee.xsd” and copy the following lines. This is the XML schema in our example which is to be bound to java classes
  3. Employee.xsd

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
      <xs:element name="employee" type="employee"/> 
      <xs:complexType name="employee"> 
        <xs:sequence> 
          <xs:element name="name" type="xs:string" minOccurs="0"/> 
          <xs:element name="salary" type="xs:double"/> 
          <xs:element name="designation" type="xs:string" minOccurs="0"/> 
          <xs:element name="address" type="address" minOccurs="0"/> 
        </xs:sequence> 
        <xs:attribute name="id" type="xs:int" use="required"/> 
      </xs:complexType> 
      
      <xs:complexType name="address"> 
        <xs:sequence> 
          <xs:element name="city" type="xs:string" minOccurs="0"/> 
          <xs:element name="line1" type="xs:string" minOccurs="0"/> 
          <xs:element name="line2" type="xs:string" minOccurs="0"/> 
          <xs:element name="state" type="xs:string" minOccurs="0"/> 
          <xs:element name="zipcode" type="xs:long"/> 
        </xs:sequence> 
      </xs:complexType> 
    </xs:schema>
    
  4. Save the file
  5. Create a new folder ‘src’ inside the project folder.
  6. In Windows open Command Prompt (Windows button + R and type cmd) or Terminal in Linux and go to the project folder (use cd command) where it exists in your machine and type the following command
  7. C:\Users\iByteCode\Desktop\JAXBXJCTool>xjc -d src -p com.theopentutorials.jaxb.beans employee.xsd
  8. This will generate set of Java source files with appropriate annotation inside ‘src’ folder



Wednesday, February 19, 2014

How to make ajax call in spring framework

Write a server side method, with a mapping something as follows:


@RequestMapping("/getKids.html")   
public @ResponseBody  
String getChildren(@RequestParam(value = "ocn") String ocn, 
HttpServletRequest request, HttpServletResponse response) 
{
       return ocn.toUpperCase();   
}
Here @ResponseBody tells the framework to return value of the method to the browser and not lookup for a view with that name.
You can optionally omit request and response parameters in the signature of the method, if you like to.

After removal of request and response the method will look like

@RequestMapping("/getKids.html")   
public @ResponseBody  
String getChildren(@RequestParam(value = "ocn") String ocn) 
{
       return ocn.toUpperCase();   
}



Write a javascript method as follows (This uses jquery to fire ajax request)

function populateSubAgents(obj)
{
   $.ajax({
    url: "getKids.html?ocn="+obj.value,
    success: function(data) {
      $("#subAgentName").html(data);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
      if (XMLHttpRequest.status == 0) {
        alert(' Check Your Network.');
      } else if (XMLHttpRequest.status == 404) {
        alert('Requested URL not found.');
      } else if (XMLHttpRequest.status == 500) {
        alert('Internel Server Error.');
      }  else {
         alert('Unknown Error.\n' + XMLHttpRequest.responseText);
      }     
    }
  });   
}