Java @ Desk

Tuesday, December 31, 2013

Redirect a Page or URL using javascript

7:12 AM 0
Redirect a Page or URL using javascript

What is Redirect?
Redirect is something, the user requests for some JSP page but internally the user gets redirected to some other page within the application or outside the application.

Reasons for redirect:
1) Domain Name change - There arise a case where a registered domain need to be changed. In that case, the JSP pages that are build up need to be redirected to a new domain so that users do not see the old website.

2) Single Domain Usage - Every application uses domain region wise. Like for India, URL will end with ".in". In order to keep all the users at ".com" domain, redirect comes into usage

3) Payment Gateways - During online bill payments, the application needs to be redirected to third party payment sites. Consider you want to pay Vodafone Bill. So as soon as you fill in all the details and proceed to payment, the website redirects to a third party website for payment process. Here redirects comes into picture.

This side of redirection is termed as Client Side Redirect since it happens through Javascript which occurs at browser side.

There are different ways to implement the Redirection using Javascript:
1) window.localtion.replace - The replace method on the other hand navigates to the URL without adding a new record to the history. You cannot click the back button in this case
2) window.localtion.href - Work like assign
3) window.localtion.assign - The assign method does add a new record to the history.
4) window.location - Work like assign

Sample implementation for JSP:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="redirect">
<h2>Redirecting to another Page</h2>
</div>
<script>
 // JavaScript using localtion.replace
 window.location.replace("http://javacodeimpl.blogspot.com");
 // JavaScript using localtion.href
 //window.location.href="http://javacodeimpl.blogspot.com";
 // JavaScript using localtion.assign
 //window.location.assign("http://javacodeimpl.blogspot.com");
</script>
</body>
</html>

Wednesday, December 25, 2013

Spring InitializingBean interface init bean annotation

9:21 AM 0
Spring InitializingBean interface init bean annotation

A bean configured in spring configuration file gets initialized when the file gets loaded in the spring container. There may arise a case where something needs to be initialized on bean initialization or needs to be destroyed before the bean nullifies.

Consider an example, the Properties file need to be loaded as soon as bean gets initialized. What happens to this property file when the bean gets destroyed. The best practice is to clear this property file. Also if the property file gets loaded on first client request, it would take additional time for the first request.

In order to resolve both, the property file gets loaded on bean initialization itself plus gets destroyed once the bean is destroyed using the following annotations :
1) Override afterPropertiesSet - Belongs to org.springframework.beans.factory.InitializingBean package. Override the function to provide a callback function (afterPropertiesSet()) which the ApplicationContext will invoke when the bean is constructed
2) @PreDestroy - Belongs to javax.annotation.PreDestroy package

In case of annotation, Spring container will not be aware of @PreDestroy annotation. To enable it, either of the following things need to be taken care of in apring configuration file:
 1) Specify the <context:annotation-config />  
 2) Specify the <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />  

Below is the sample implementation for this:
1) Spring Configuration file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-2.5.xsd">

 <context:annotation-config />

 <bean id="springInitDestroy" class="com.spring.SpringInitDestroy">
 </bean>

</beans>
2) SpringInitDestroy Bean
package com.spring;

import javax.annotation.PreDestroy;

import org.springframework.beans.factory.InitializingBean;

public class SpringInitDestroy implements InitializingBean {
 @PreDestroy
 public void cleanUp() throws Exception {
  System.out.println("Init method called on bean destroy");
 }

 @Override
 public void afterPropertiesSet() throws Exception {
  System.out
    .println("Init method called on bean initialization - afterPropertiesSet");
 }
}
3) SprintInitDestroyTest Client File
package com.spring;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SprintInitDestroyTest {
 public static void main(String[] args) {
  ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
    new String[] { "com//spring//appContext.xml" });

  SpringInitDestroy initDestroy = (SpringInitDestroy) context
    .getBean("springInitDestroy");

  System.out.println("Bean Created : " + initDestroy);

  context.close(); // @PreDestory method gets called here
 }
}

Output :
Init method called on bean initialization - afterPropertiesSet
Bean Created : com.spring.SpringInitDestroy@197bb7
Init method called on bean destroy

Spring @PostConstruct & @PreDestroy init bean method annotation

8:57 AM 0
Spring @PostConstruct & @PreDestroy init bean method annotation

A bean configured in spring configuration file gets initialized when the file gets loaded in the spring container. There may arise a case where something needs to be initialized on bean initialization or needs to be destroyed before the bean nullifies.

Consider an example, the Properties file need to be loaded as soon as bean gets initialized. What happens to this property file when the bean gets destroyed. The best practice is to clear this property file. Also if the property file gets loaded on first client request, it would take additional time for the first request.

In order to resolve both, the property file gets loaded on bean initialization itself plus gets destroyed once the bean is destroyed using the following annotations :
1) @PostConstruct - Belongs to javax.annotation.PostConstruct package
2) @PreDestroy - Belongs to javax.annotation.PreDestroy package

In case of annotation, Spring container will not be aware of @PostConstruct and @PreDestroy annotation. To enable it, either of the following things need to be taken care of in apring configuration file:
 1) Specify the <context:annotation-config />  
 2) Specify the <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />  

Below is the sample implementation for this:
1) Spring Configuration file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-2.5.xsd">

 <context:annotation-config />

 <bean id="springInitDestroy" class="com.spring.SpringInitDestroy">
 </bean>

</beans>
2) SpringInitDestroy Bean
package com.spring;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class SpringInitDestroy {

 @PostConstruct
 public void initIt() throws Exception {
  System.out.println("Init method called on bean initialization");
 }

 @PreDestroy
 public void cleanUp() throws Exception {
  System.out.println("Init method called on bean destroy");
 }
}
3) SprintInitDestroyTest Client File
package com.spring;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SprintInitDestroyTest {
 public static void main(String[] args) {
  ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
    new String[] { "com//spring//appContext.xml" });

  SpringInitDestroy initDestroy = (SpringInitDestroy) context
    .getBean("springInitDestroy");

  System.out.println("Bean Created : " + initDestroy);

  context.close(); // @PreDestory method gets called here
 }
}

Output :
Init method called on bean initialization
Bean Created : com.spring.SpringInitDestroy@1a897a9
Init method called on bean destroy

Sunday, December 22, 2013

JSP implicit objects REQUEST with example

8:57 AM 0
JSP implicit objects REQUEST with example
In all there are 9 implicit JSP objects.

In our last posts, we have learned
JSP implicit objects OUT with example,
JSP Implicit Object CONFIG with example ,
JSP Implicit Object APPLICATION with example ,
JSP Implicit object session with example ,
JSP implicit object PageContext with example,
JSP implicit object RESPONSE with example,

The request object is an instance of class implementing an javax.servlet.http.HttpServletRequest interface. This object holds the client request that is being sent either through Post or Get request.

Request object is used to fetch the following information:
1) Request Parameters - Returns the value of a request parameter as a String, or null if the parameter does not exist. It uses the getParameter() method to access the request parameter.
2) Header Information - Returns the value of an HTTP header. The method getHeaderNames() can be used to determine what headers are available.
3) Cookies - Get the array of cookies from the request using getCookies() method.
4) Query String - Uses the getQueryString() method to get the query string, if any, passed in the request. Returns null if no query string is passed. Query String is passed after the URL by appending a '?' mark. Multiple query strings are seperated using the '&' symbol.
For ex : Consider a URL : http://localhost:8080/StockQuote/jsp/ImplicitObjectRequest.jsp?firstName=Kumar&secondName=Bhatia
In this, request.getQueryString() will give "firstName=Kumar&secondName=Bhatia"
5) Request URI - Method getRequestURI() gives the "/StockQuote/jsp/ImplicitObjectRequest.jsp" from above URL. It helps in getting which page is getting called. Gets the URI to the current JSP page.
etc.

Below is the sample example usage of few methods from the request object:
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Implicit Object 'request' Example</title>  
 </head>  
 <body>  
 <%-- request object example --%>  
 <strong>Request User-Agent</strong>: <%=request.getHeader("User-Agent") %><br><br>  
 <strong>Request Parameter Names</strong>: <%=request.getParameterNames() %><br><br>  
 <strong>Request Cookies</strong>: <%=request.getCookies() %><br><br>  
 <strong>Request Query String</strong>: <%=request.getQueryString() %><br><br>  
 <strong>Request URI</strong>: <%=request.getRequestURI() %><br><br>  
 </body>  
 </html>  
 

Output is :

Request User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)

Request Parameter Names: org.apache.tomcat.util.http.Parameters$NamesEnumeration@ac86bb

Request Cookies: [Ljavax.servlet.http.Cookie;@c16890

Request Query String: firstName=Kumar&secondName=Bhatia

Request URI: /StockQuote/jsp/ImplicitObjectRequest.jsp

Saturday, December 21, 2013

JSP implicit objects OUT with example

10:05 PM 0
JSP implicit objects OUT with example

In our last posts, we have learned
JSP implicit objects REQUEST with example,
JSP Implicit Object CONFIG with example ,
JSP Implicit Object APPLICATION with example ,
JSP Implicit object session with example ,
JSP implicit object PageContext with example,
JSP implicit object RESPONSE with example,

The "out" implicit variable of a JSP implementation is of javax.servlet.jsp.JspWriter class type. The data on the JSP page is written using the JspWriter object that is referenced by the implicit variable "out" which is initialized automatically using methods in the PageContext objects.

In all there are 9 implicit JSP objects.

This object is used to print the output content to the client response on browser.

Below are some of the methods used with object out :
1) print(String s) - Print a string. If argument is null, then "null" is printed in the client response.
2) println(String x) - Print a String and then terminate the line.
3) newLine() - Write a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.
Example for JSP implicit object out below:
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="UTF-8"%>  
 <%@ page import="java.util.Date" %>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Implicit Object Out Example</title>  
 </head>  
 <body>  
      <%-- out object example --%>  
      <h4>Implementation of JSP Implicit Object 'out'</h4>  
      <strong>Current Time is </strong>: <% out.print(new Date()); %><br><br>  
      <strong>out.print(String s) </strong>: <% out.print("Print a string."); %><br>  
      <strong>out.println(String s) </strong>: <% out.println("Print a String and then terminate the line."); %><br>  
      <%out.newLine(); %>  
      <% out.println("The difference between print(String s) & println(String s) method is that the second one terminates the line."); %>  
 </body>  
 </html>  


Output is :

Implementation of JSP Implicit Object 'out'
Current Time is : Sun Dec 22 11:38:36 IST 2013

out.print(String s) : Print a string.
out.println(String s) : Print a String and then terminate the line. 
The difference between print(String s) & println(String s) method is that the second one terminates the line. 

Sunday, December 15, 2013

Drools DRL Date comparision syntax in LHS

9:31 AM 0
Drools DRL Date comparision syntax in LHS

There are three ways to compare Date in LHS part of DRL rule as shown below :
a) Using '>' greater than or '>' less than operator
b) Using java.util.Date class methods .after() and .before()
c) Using java.util.Date class methods .compareTo()

Below is the implementation for three different types of rule for date comparision. It includes
1) Sample Pojo class with Date fields dateOne and dateTwo
2) Client file to create the Stateful Knowledge Session in which Pojo class object is created. Date fields are set to some default values.
dateOne is set to - Tue Jun 25 10:30:45 IST 2013
dateTwo is set to - Thu Jun 20 10:30:45 IST 2013
3) DRL file for 3 different rule implementations

Saturday, December 14, 2013

Drools lock-on-active vs no-loop

8:58 PM 1
Drools difference between lock-on-active and no-loop

no-loop & lock-on-active are the two most important features in drools. If oyu are writing complex rules within the application, these two features would be of high use.

Both these features comes into picture when any rule uses either the update or modify in the consequence of the rule.

When update or modify are used in the consequence part, the rule engine re-activates all the rules within the agenda-group that uses the fact that is being updated or modified. This results in an rule execution in an infinite loop. To avoid this, lock-on-active & no-loop are getting used.

Refer to below rule:

Friday, December 13, 2013

Drools Update, Modify Infinite Loop Execution-Resolved

9:19 PM 0
Drools Update, Modify Infinite Loop Execution
When we use update or modify in a DRL file, we fall into the infinite looping issue many number of times.
There arise a case where the update or modify need to get called so that other rules can use the modified value.

But as soon as we update the fact, it either
1) Activates the rule itself
2) Activates other rules that may eventually reactivate the original rule.

Consider first scenario, where the update operation activates the same rule and rule enters in an infinite loop
rule "Rule One"
agenda-group "Name Field"
salience 90
    when
  $pojo : Pojo(name == "Kumar" || address=="Mumbai")
    then
        System.out.println("Rules Name is - " + drools.getRule().getName());
        $pojo.setAddress("Mumbai CST");
        update($pojo);
end