Wednesday, November 30, 2011

Invalid set of fields set for XMLGregorianCalendar

Exception in thread "main" java.lang.IllegalStateException: com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl#getXMLSchemaType() :Invalid set of fields set for XMLGregorianCalendar
 at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl.getXMLSchemaType(XMLGregorianCalendarImpl.java:1928)
 at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl.toXMLFormat(XMLGregorianCalendarImpl.java:1764)
 at javax.xml.datatype.XMLGregorianCalendar.toString(XMLGregorianCalendar.java:866)


I was getting the above exception when I try to run the following code...

XMLGregorianCalendar tmStamp = new XMLGregorianCalendarImpl();
        tmStamp.setYear(2011);
        tmStamp.setMonth(Calendar.NOVEMBER);
        tmStamp.setDay(30);
        tmStamp.setHour(10);
        tmStamp.setMinute(59); 
        System.out.println(tmStamp.toString());


Solution:
Set the seconds as well
tmStamp.setSeconds(30);

Setting the seconds is mandatory when you set hours and minutes.

JAXB and JDK1.6

Use JDK 1.6 to convert from Java to XML


http://www.javabeat.net/articles/14-java-60-features-part-2-pluggable-annotation-proce-3.html

Thursday, November 24, 2011

Building Java Web Services with NetBeans 7.0

Create web services using Netbeans 7.0


Here is a complete tutorial with screenshots and very well explained.

http://www.theserverside.com/tip/Building-Java-Web-services-with-NetBeans-7

How to create a sample Web Service using JDeveloper

Thanks to Hussain for creating this tutorial. I am just extending his learning with some additions of mine.

The Sample WebService will return Credit Rating of the customer if the customer Id is Valid else it will give response as Invalid Customer Id

1) Open JDeveloper, Create New Application and Project as shown below






2) Create a Java Class, Right Click on Project->New->General->JavaClass


3) Enter Class Name as CreditRating and Package name as com.ws


4) Write a Method called getCreditRating inside the class CreditRating class.
the method should accept customer id and return a CreditRating of the customer.

package com.ws;
import java.io.Serializable;

public class CreditRating implements Serializable
{
    public CreditRating()
    {
    }
    /**
     * Do read this link for help 
     * in case of issues : http://programming.itags.org/development-tools/123309/
     * @webmethod 
     */
    public String getCreditRating(String customerId)
    {
        String rating;
        if("abc".equalsIgnoreCase(customerId) ||
           "xyz".equalsIgnoreCase(customerId) )
           {
               rating="1000";
           }
           else if("pqr".equalsIgnoreCase(customerId))
           {
               rating="2000";
           }
           else
           {
                rating = "Invalid Customer id";
           }
           return rating;
    }
}

5) Compile your Project, After Successful Compilation, Right Click your Project->Business Tier-> Web Services-> Java Web Service


6)Enter WebService Name and Select the CreditRating Class as Component to Publish and click Next











7) Once You Successfully generate the Java Web Service, You need to deploy it and Test the working of the Web Service
8) Right Click on MyWebService1 and Select Run. You'll see a URL in the Log window as shown below.











Method getCreditRating: The following parameter types do not have an XML Schema mapping and/or seralizer specified:

I was getting the following error message when trying to create web service from this URL

Error Message:
Method getCreditRating: The following parameter types do not have an XML Schema mapping and/or seralizer specified:

java.lang.Object


Solution :
The java.io.Serializable marker is not consulted when determining whether a Java object can be transmitted in a web service invocation. Instead, each parameter and return value of a web service method must conform to one of the 3 rules below:

1. It is a Java primitive (int, long, byte etc.), Java primitive wrapper (java.lang.Integer etc.), or a java.lang.String.
2. It is a Java bean with a zero-argument constructor, and a pair of "get" and "set" methods for each property to be exposed. Each property must itself conform to one of these 3 rules.
3. It is an array of a type that meets either rule 1 or rule 2.

Tuesday, November 22, 2011

How to make hover effects work in Internet Explorer

Thanks to http://www.bernzilla.com/item.php?id=762 for the post. :)

I spent about an hour this morning trying to figure out how in the world to get IE7 to apply my :hover styling to a non-anchor (<a>) element. Amazingly enough, numerous searches on Google turned up absolutely nothing. I found one forum post that looked promising, but it was one of those depressing forum posts that states the exact same problem you're having, but doesn't have any replies.

What made things more frustrating was that there are blog posts galore touting IE7's addition of support for :hover on all elements, yet no matter what I tried I couldn't get it to work!

Eventually, I recalled reading something on the IEBlog about how a web page's DOCTYPE would dictate the CSS support in IE7. The gist of it is, if you want support for :hover on all elements and not just the <a> tag, make sure you're using a strict DOCTYPE so IE7 doesn't kick in to quirks mode.

Whereas the following HTML resulted in my hover effects working in Firefox but not IE7

<html>
 <head>
  <title>Test</title>
  <style type="text/css">
  <!--
   table { background-color: #DDD; }
   tr:hover { background-color: #000; color: #FFF; }
   p { background-color: #EEE; }
   p:hover { background-color: #CCC; }
  //-->
  </style>
 </head>
 <body>
  <p>
   This is just one of those paragraph things.
  </p>
  <table cellpadding="0" cellspacing="0">
   <tr>
    <td>This here is a table row.</td>
   </tr>
   <tr>
    <td>This is a table row too.</td>
   </tr>
  </table>
 </body>
</html>

...simply adding the HTML 4.01 Strict DOCTYPE to the top of the HTML document made IE7 obey my :hover rules as well:

WORKING CODE

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
  <title>Test</title>
  <style type="text/css">
  <!--
   table { background-color: #DDD; }
   tr:hover { background-color: #000; color: #FFF; }
   p { background-color: #EEE; }
   p:hover { background-color: #CCC; }
  //-->
  </style>
 </head>
 <body>
  <p>
   This is just one of those paragraph things.
  </p>
  <table cellpadding="0" cellspacing="0">
   <tr>
    <td>This here is a table row.</td>
   </tr>
   <tr>
    <td>This is a table row too.</td>
   </tr>
  </table>
 </body>
</html>

Internet Explorer 7 and later, in standards-compliant mode (strict !DOCTYPE), can apply the :hover pseudo-class to any element, not merely links.


How to highlight table rows on mouseOver

Please note that if you are using IE, don't forget to add the DOCTYPE to your HTML document


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

For more details, you can refer to this link or this link

Put this inside your <HEAD> section

<style type="text/css">
  tr:hover
  {
    background-color:#317082;
    color:#FFF;
  }
  table
  {
    border:1px solid #000;
    border-collapse: collapse;
  }
  thead td
  {
   font-weight:bold;
   color:#000;
   background-color:#E2EBED;
  }
  td
  {
   padding:2px;
  }  
 </style>

Put this into your <BODY> section

<h1>Table example 1</h1>
<table id="myTable">
 <thead>
  <tr>
   <td>Name</td>
   <td>Age</td>
   <td>Position</td>
   <td>Income</td>
   <td>Gender</td>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>John</td>
   <td>37</td>
   <td>Managing director</td>
   <td>90.000</td>
   <td>Male</td>
  </tr>
  <tr>
   <td>Susan</td>
   <td>34</td>
   <td>Partner</td>
   <td>90.000</td>
   <td>Female</td>
  </tr>
  <tr>
   <td>David</td>
   <td>29</td>
   <td>Head of production</td>
   <td>70.000</td>
   <td>Male</td>
  </tr>
 </tbody>
</table>




Table example 1

Name Age Position Income Gender
John 37 Managing director 90.000 Male
Susan 34 Partner 90.000 Female
David 29 Head of production 70.000 Male

Sunday, November 20, 2011

More about regular expressions in Javascript

Aah !! Regular expressions

I have got confused most of the times, I need to escape special characters when specifying a regular expression.

Let us take an example of simple date format
dd/mm/yyyy

There are two ways, you can specify your regular expression

// Please note that your regular expression literal object must be surrounded
// between forward slashes as is done below.

// Since forward slash (/) has a special meaning in regular expressions
// it need to be escaped by a backslash (\)
var regex = /^\d{2}\/\d{2}\/\d{4}$/
regex.test("01/04/1975");

/*  / -- Used to signify that a regex literal follows.
 *  ^ - Starts with
 * \d{2} - 2 digits (date)
 * \/  - Escaping the forward slash
 * \d{2} - 2 digits (Month)
 * \/ - Escaping the forward slash
 * \d{4} - 4 digits (Year)
 * $ - end of string.
 * / - specifies the end of regex literal.
 */

// Things become more complex when you want to specify 
// regular expression in a String

// Please note the difference between the regex literal and the string regex
// Here we have to escape the backslash as well. 
// So the  number of backslashes are doubled.

var regex = new RegExp("^\\d{2}\\/\\d{2}\\/\\d{4}");


/*  
 *  ^ - Starts with
 * \\d{2} - 2 digits (date)
 * \\/  - Escaping the forward slash
 * \\d{2} - 2 digits (Month)
 * \\/ - Escaping the forward slash
 * \\d{4} - 4 digits (Year)
 * $ - end of regex.
 */


Please note that you have to escape all those characters which have a special meaning in Regular expressions.
Just place a backslash before that character. (2 backslashes if you are specifying regex as a string literal)
List of characters that need to be escaped are :

[, ], ., ?, *, +, /, \, {, }, |, (, )

Related Post : http://javakafunda.blogspot.com/2011/06/10-java-regular-expression-examples-you.html

Saturday, November 19, 2011

Weblogic specific issue abt custom Tags

Dear Friends,

I was facing an issue specifically on weblogic and the same JSP was working fine on Oracle Application Server.
I thought it is worth sharing with all.

ERROR MESSAGE :
The method setTabindex (String) in the type NumericNewTextTag is not applicable for the arguments (int)

After seeing the error message, the obvious thought that came to my mind was, that we are passing an int and it is expecting a String.

Then I thought, why and how it is getting compiled on Oracle AS?
Is JSP to Servlet compilation, vendor specific?
What abt the theory that Java says? write once, run anywhere? Doesn't this theory apply here?


You'll get the answers to all these questions at the end of this post.

Problematic code

int tabindex=0;
<nuchtml:numbertextbox 
         property="txtGrossRevenues" 
         displayClass="<%= flag %>" 
         mode="<%= vMode %>" 
         value="<%=Format.getFormatDbl(value,DECIMAL_PRECISION)%>" 
         onchange="fnOnChange()" 
         maxlength="13" 
         onkeypress="checkNumericsNew(event)" 
         onblur="addCommaCurrencyFormat(this);" 
         onfocus=" callCurrencyFocus(this)" 
         onmousedown="Disable_Copy_Paste();" 
         onkeydown="Disable_Copy_Paste();" 
         tabindex="<%=tabIndex%>" <%-- That's the problematic line --%>
         style="width:200"/>

tabindex++;


Code with Problem resolved.

int tabindex=0;
// Please note the change in tabindex attribute.
<nuchtml:numbertextbox 
         property="txtGrossRevenues" 
         displayClass="<%= flag %>" 
         mode="<%= vMode %>" 
         value="<%=Format.getFormatDbl(value,DECIMAL_PRECISION)%>" 
         onchange="fnOnChange()" 
         maxlength="13" 
         onkeypress="checkNumericsNew(event)" 
         onblur="addCommaCurrencyFormat(this);" 
         onfocus=" callCurrencyFocus(this)" 
         onmousedown="Disable_Copy_Paste();" 
         onkeydown="Disable_Copy_Paste();" 
         tabindex="<%=Integer.toString(tabIndex)%>"
         style="width:200"/>

tabindex++;


Key Points
===========

On Oracle this custom tag gets translated to somewhat like the following.

// Please note that whatever is the return type 
// of the expression is wrapped into String and then sent to setTabIndex method.
// So even if the developer sends a primitive int, oracle will convert it
// to String before sending it to method.
// Hence no compilation problem on Oracle server.
__jsp_taghandler_33.setTabindex(OracleJspRuntime.toStr(Integer.toString(tabIndex));

Note that, the oracle server converts the argument passed by the user to a String explicitly, which is not the case with weblogic.
So, if you are using a request-time expression value in the attribute of a custom-tag, Make sure that return type of the expression is a String.

Here are the answers to the questions:

Why and how it is getting compiled on Oracle AS?
The above explanation clearly explains that.
Is JSP to Servlet translation, vendor specific?
Yes, JSP to servlet translation varies across vendors.
What abt the theory that Java says? write once, run anywhere? Doesn't this theory apply here?
This theory still works. Because, it was the mistake on developer's end, not to comply with the syntax of JSP, which luckily worked on Oracle.

JSP always say, you must pass a String to an custom-tag's attribute.


Some questions are still boggling my mind?

  1. Is it good that Oracle converts every passed expression to String before passing to the setTabindex method? What should be the ideal translation that is expected from a container?
  2. how abt the literals that are passed like tabindex="1", how that were working on weblogic? Why those didn't create an issue? Did weblogic converted them to String before passing it to method?

Friday, November 11, 2011

Generating dynamic elements in struts !!

Thanks to http://www.techtamasha.com/generate-dynamic-ids-for-struts-html-tags/



Do you use struts tags to generate html content?
If yes, then sooner or later you'll come across a scenario where you would generate html elements in an array
I faced a similar predicament recently. I had no other option but to use scriptlets to generate id's for the html elements



However, I soon found out using scriptlets within the struts html tags isn't really straight forward.

Here's the code I tried in my first attempt:

<%int i=0;%>
//iteration logic here
<html:text property="example[<%=i%>]" styleid="example<%=i%>"/>


Well, if you write the code as shown above, the html code generated would be :

<input type="text" name="example[<%=i%>]" id = "example<%=i%>">

and not

<input type="text" name="example[0]" id="example0">

To get the expected result, i.e. for the scriptlet to work inside the struts html tag, write as below:

<html:text property='<%="example["+i+"]"%>'
        styleid='<%="example"+i%>'/>


Please note that the name of the elements should be like this if you want them to read in Action Class via Action Form.
example[0], example[1], example[2], example[3]......and so on...

What do one needs to retrieve these values in Action Class

  1. Create a property in Action Form with the name example of type String[]. (Though ArrayList may also work, but I have not tried it yet)
  2. Create the corresponding getter setters for the property defined above.

STRUTS : java.lang.IllegalAccessException

STRUTS : java.lang.IllegalAccessException: Class org.apache.struts.util.RequestUtils can not access a member of class view.myAction with modifiers "

PROBLEM

When I hit action class, I get the following exception.

java.lang.IllegalAccessException: Class org.apache.struts.util.RequestUtils can not access a member of class view.myAction with modifiers ""

All the member functions of the Action class are public.(There is only one method execute in the class and it was public)

SOLUTION

The problem was that I had not made myAction class public. It was made with default access specifier.

Make sure that your Action and ActionForm class is public.

Cannot find bean org.apache.struts.taglib.html.BEAN in any scope

I was getting the following exception when I tried to execute an Action Class...
Everything in struts-config.xml, web.xml, the TLDs in place seem to be perfect.
But still I got the following exception.


500 Internal Server Error (Click for full stack trace)
javax.servlet.jsp.JspException: Cannot find bean org.apache.struts.taglib.html.BEAN in any scope

at org.apache.struts.util.RequestUtils.lookup(RequestUtils.java:938)
at org.apache.struts.taglib.html.BaseFieldTag.doStartTag(BaseFieldTag.java:176)
at _clientSide._jspService(clientSide.jsp:12) [/clientSide.jsp]
at com.orionserver[Oracle Application Server Containers for J2EE 10g (10.1.2.2.0)].http.OrionHttpJspPage.service(OrionHttpJspPage.java:57)
at oracle.jsp.runtimev2.JspPageTable.service(JspPageTable.java:356)
at oracle.jsp.runtimev2.JspServlet.internalService(JspServlet.java:498)
at oracle.jsp.runtimev2.JspServlet.service(JspServlet.java:402)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.2.0)].server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
at oracle.security.jazn.oc4j.JAZNFilter.doFilter(Unknown Source)
at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.2.0)].server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:673)
at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.2.0)].server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:340)
at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.2.0)].server.http.ServletRequestDispatcher.forward(ServletRequestDispatcher.java:229)
at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1069)
at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:455)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:279)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1485)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:509)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.2.0)].server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
at oracle.security.jazn.oc4j.JAZNFilter.doFilter(Unknown Source)
at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.2.0)].server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:673)
at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.2.0)].server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:340)
at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.2.0)].server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:830)
at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.2.0)].server.http.HttpRequestHandler.run(HttpRequestHandler.java:285)
at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.2.0)].server.http.HttpRequestHandler.run(HttpRequestHandler.java:126)
at com.evermind[Oracle Application Server Containers for J2EE 10g (10.1.2.2.0)].util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)
at java.lang.Thread.run(Thread.java:534)


Solution

The mistake I was doing was that I had used <html:text> tag without using <html:form> in the JSP file.

Always remember that you should have <html:text tag inside <html:form

Best Practices to improve Performance in JSP

This topic illustrates the performance improvement best practices in JSP with the following sections:

Overview of JSP

When the user requests a JSP page for the first time, A JSP converts into servlet java source file and compiles into servlet class file that is called as translation phase, then onwards it works like pure servlet for all requests this is called execution/request process phase. But the method signatures are different for both Servlet and JSP. Servlet has init(), service() and destroy() methods where as JSP has jspInit(), _jspService() and jspDestroy() methods. JSP has some advantages over servlet. JSP gives good separation between presentation (html) and business logic. See Overview of Servlets for more details. Here I use JSP's Servlet instead of Servlet to differentiate between both.

Note: This Section assumes that reader has some basic knowledge of JSP.

Use jspInit() method as cache

The default mechanism of a JSP Engine is to load a JSP's servlet in multithreaded environment, that is the default value of page directive in JSP's
<%@ page isTheadSafe="true" %>
In this environment, a JSP's jspInit() method is called only once in its life time.
Here is a trick that you can use to improve performance using jspInit() method.
You can use this method to cache static data.
Generally a JSP generates not only dynamic data but also static data.
Programmers often make a mistake by creating both dynamic and static data from JSP page. Obviously there is a reason to create dynamic data because of its nature but there is no need to create static data every time for every request in JSP page.
For example, normally you would write a JSP page like this
//creating static data and pass it to client
out.print("<html>");
out.print("<head><title>Hello world</title></head>");
out.print("<body>");
// create the dynamic data and pass it to client here
//creating static data again and passing it to client
out.print("</body>");
out.print("</html>");

Here you are generating both static data and dynamic data from _jspService() method. Instead what you can do is
<%!      char[] header;
char[] navbar;
char[] footer;
char[] otherStaticData;
public void jspInit(){
//create all the static data here
StringBuffer sb = new StringBuffer(); // better to initialize the StringBuffer with some size to improve performance
sb.append("<html>");
sb.append("<head><title>Hello world</title></head>");
sb.append("<body>");
header = sb.toString().toCharArray();
// do same for navbar if its data is static
// do same for footer if its data is static
} // end jspInit() method
%>
out.print(header);
out.print(navbar);                   
// write dynamic data here
out.print(footer);
}

Here the static data is created in jspInit() method which means that it is created only once in the life time of JSP and it is used in _jspService() method to pass the data to the client. When you send a large amount of static data, then you can use this technique to see a considerable increase in performance.

Optimization techniques in _jspService() method

When you use implicit out object to pass the data to the client from JSP, the JSP Engine/container creates a JSPWriter object and put it in the _jspService() method. You don't need to bother about writing _jspService() method in your JSP, JSP Engine does that work for you. You can improve performance by using the following techniques.

  1. Use StringBuffer rather than using + operator when you concatenate multiple strings
  2. Use print() method instead of println() method of out (implicit) object
  3. Use ServletOutputStream instead of JSPWriter
  4. Initialize out with proper size in the page directive
  5. Flush the data partly
  6. Minimize the amount of code in the synchronized block
  7. Set the content length
  1. Use StringBuffer for concatenation rather than using + operator. See Concatenating Strings for detailed information.
  2. println() method internally calls print() method and there is no need for a new line separation when generating html pages. So a small overhead of calling one more method is reduced if you use print() method directly.
  3. There is a small overhead involved in JSPWriter because it is meant for character output stream and it encodes data to bytes, rather you can directly use ServletOutputStream whenever you want to send binary data.
  4. Initialize the out object with proper size in the page directive. It is discussed in detail in later part of this section.
  5. If you want to pass huge data to the client from your servlet, user may need to wait till the ServletOutputStream or JSPWriter flushes the data. This happens generally whenever you have a number of gifs per page and you want to pass it to the client. The better approach is to flush the data partly using flush() method rather than flushing whole data at a time. You can initially flush header, then navigation bar, then body content and finally footer so that the user need not wait for whole data and he sees the header data immediately and so on with navigation bar, body content and footer.
out.write(header);
    out.flush(); // flush the header
    out.write(navbar);                                   
    out.flush(); // flush the navigation bar
    // write dynamic data here
    out.flush(); // flush the dynamic data
    out.write(footer);
    out.flush(); // finally flush the footer

Optimization techiques in jspDestroy() method

The jspDestroy() method is called only once in JSP's servlet life time, when the JSP Engine removes the JSP's servlet from memory. It is always better to remove instance variable resources such as JDBC connections, sockets, other physical resources in this method to avoid memory leaks.

Optimization techniques in page directive

Page directive defines attributes that apply to an entire JSP page. Here is an example of page directive.
<%@ page session="true|false" buffer="none|8kb|size in kb" %>
true and 8kb are default values. Here I have shown only a few attributes, these attributes have an impact on the performance so we will discuss about them here. By default JSP Engine creates session object. If you don't want to use built in HttpSession for a JSP, then make session attribute value as false. It avoids unnecessary creation of session (implicit) object, reduces overhead on memory and garbage collector and increases performance. By default the size of out (implicit object of JSPWriter) object is 8kb. You can increase the size if you are sending a large amount of data. so set
<%@ page session="false" buffer="12kb" %>  
Here you need to set the size as per page response data if it crosses 8kb.

Choosing right include mechanism

There are two include mechanisms available to insert a file in a JSP page. They are
  1. include directive <%@ include file="child.jsp" %>
  2. include action <jsp:include page="child.jsp" flush="true" />
The include directive includes the content of the file during the translation phase where as include action includes the content of the file during execution/request processing phase. For include directive, JSP Engine adds the content of the inserted page at translation phase, so it does not have an impact on performance. For include action, JSP Engine adds the content of the inserted page at run time which imposes extra overhead.

Choosing right session scope in useBean action

When you want to create a bean using useBean action tag you can set scope for that bean
<jsp:useBean id="objectName" scope="page|request|session|application" />  
default value is 'page' for any bean if you don't specify the scope explicitly. By defining scope attribute, you are defining the life time of that object, when it has to be created and when its life time ends. To be precise, you are defining the availability of that object to a page, request, session (that is across multiple requests to a user) or application (across multiple users ). Here the scope effects the performance if you don't specify exact scope as per your requirement. What will happen if you set a session scope for an object which is needed only a request? The object will unnecessary reside in the memory even after your work is done. When using the session or application scope object you have to explicitly remove it after you are done. Otherwise the session object will be there in the memory till you explicitly remove the object or your server removes it after a configured time limit ( typically it is 30 minutes). It reduces the performance by imposing overhead on memory and garbage collector. The same is the problem with the application scope objects. So set exact scope for an object and also remove those scope objects immediately whenever you are done with them.

Choosing the custom tags versus non custom tags

Custom tags in JSP gives you reusability and simplicity. Simplicity means that you need not write java code in JSP rather you write custom tags for that. Reusability means that once you write a piece of code as custom tag handler, you can use this tag handler in any JSP. But what will happen if you write a tag handler that is not reused often and is not simple? In such cases it is better not to use custom tags since you need to use classes, interfaces of javax.servlet.jsp.tagext, deployment descriptor file and also you need to override methods of those classes and interfaces in order to write a tag handler. JSP Engine has to look at descriptor file to figure out tag handler class and execute that handler. All these operations do not come for free. It reduces performance and it is proportional to the number of tag handlers you use in JSP. So don't use custom tags unless you are sure of its reusability.

Cache the static and dynamic data

The use of caching in different areas of your application gives very good performance. Generally every application's database schema will have at least some read only tables. There is no need of accessing these tables every time. You can cache that data in memory and reuse it instead of accessing database every time. It reduces network traffic, consumes less CPU cycles and gives good performance. Caching can be done in three flavors namely static data caching, semi dynamic data caching and dynamic caching. Static data means that it doesn't change the content in its life time, it is always constant. Semi dynamic data means that data changes but not very often. For example the data that changes after every one hour can be called as semi dynamic data but it does not change the data for every request. Dynamic data means that it changes often. Often people use the word dynamic data for semi dynamic data as well so even I followed the same terminology. In this section, dynamic data synonymous with semi dynamic data. It is best to cache static data and dynamic data in order to improve performance.We will discuss here about few caching techniques to improve JSP performance. They are
  1. Caching static and dynamic data
  2. Utilizing application server Caching facilities
  3. Utilizing JSP built in facility, session and application (implicit) objects
  4. Utilizing third party Caching algorithms
As we saw above, Caching at jspInit() method is useful for caching static data and it reduces the creation time of static data. By writing your own algorithms for caching dynamic data, you can maintain dynamic caching for your application. Your application server may support caching facility for dynamic data caching. For example, weblogic server is giving some custom tags for dynamic caching facility. you can use that facility. Look at your server documentation for more information. You can use JSP's built in facility, session and application objects for caching. session object is available for a user session across multiple requests and application object is available for all users using the application. You can cache data into these objects and get this cached data whenever you require. The methods that support caching are.
session.setAttribute(String name, Object cacheableObject);

session.getAttribute(String name);

application.setAttribute(String name, Object cacheableObject);

application.getAttribute(String name);
You can even use third party vendors or open source caching algorithms to achieve caching. One of the good open source is http://www.opensymphony.com. They are offering custom caching tags for free, they are
<cache></cache>

<usecached></usecached>

<flush/>
These ready made tags are used by session and application scope objects internally. You can set cacheable object by key and get those objects using those keys, scope ( either session or application), time for refreshing cacheable objects, and flushing. See this link hhttp://www.opensymphony.com/oscache for detailed information about these tags. Any of these caching techniques gives good performance with some limited scope and you need to utilize depending on your application's requirement.

Choosing the right session mechanism

We use session mechanism to maintain client state across multiple pages. The session starts when the client, such as browser requests for a URL to the web server and it ends when the web server ends the session or web server times out the session or user logs out or user closes the browser. There are few approaches available to maintain session, those are using
  1. session (implicit) object available for any JSP ( this is HttpSession provided by servlet API)
  2. Hidden fields
  3. Cookies
  4. URL rewriting
  5. Persistent mechanism
Obviously it is difficult to select one mechanism out of above mentioned approaches to maintain session data. Each one has an impact on performance depending on amount of the data to be stored as session data and number of concurrent users. The following table gives you an idea of performance about each approach.
Session mechanism Performance Description
session good There is no limit on size of keeping session data
Hidden fields moderate There is no limit on size of passing session data
Cookies moderate There is a limit for cookie size
URL rewriting moderate There is a limit for URL rewriting
Persistent mechanism moderate to poor There is no limit of keeping session data
Here the Persistent mechanism means that you store the session data in the database, file storage or any other persistent storage. There are a few approaches for this mechanism, they are
  1. Using your application server's persistent mechanism for session data storage
  2. Using your own persistent mechanism by maintaining your own database schema
If you use the first approach, generally application server converts the session objects into BLOB data type and stores it in the database. If you use second approach, you need to design the schema as per your session fields and need to store the session data by writing JDBC code for that, this gives better performance than the first approach. Either of persistent mechanisms give moderate to poor performance than other approaches because of overhead involved in database calls through JDBC and it makes calls to database on every request in order to store that session data and finally it needs to retrieve the whole session data from database but it scales well upon increasing session data and concurrent users. URL rewriting gives moderate performance because the data has to pass between the client and server for every request but there is a limitation on amount of data that can pass through URL rewriting. It gives moderate performance because of overhead involved on the network for passing data on every request. Cookies also give moderate performance because they need to pass the session data between client and server. It also has the size limit of 4k for each cookie. Like URL rewriting and Cookies, Hidden fields need to pass the data between client and server and give moderate performance. All these three session mechanisms give moderate performance and is inversely proportional to the amount of session data. Unlike the above mentioned mechanisms, session (implicit) object mechanism gives better performance because it stores the session data in memory and reduces overhead on network. Only session id will be passed between client and server. But it does not scale well up on increasing session data and concurrent users because of increase in memory overhead and also increase in overhead on garbage collection. Remember that choosing the session mechanism out of one of the above approaches not only depends on performance but also scalability and security. The best approach to maintain a balance between performance, scalability and security. Mixture of session mechanism and Hidden fields gives both performance and scalability. By putting secure data in session and non secure data in hidden fields you can achieve better security.

Control session

If you decide to use session (implicit object that represents HttpSession object) for your session tracking, then you need to know how your application server/servlet engine implements session mechanism. You need to take care of the following points
  1. remove session explicitly
  2. session time out value
  3. application server/servelt engine implementation
Generally, your application server/servlet engine will have default session time out value as 30 minutes which means that if you don't remove session or manipulate that session for 30 minutes then your servlet engine removes that session from memory. If you set long session time out value such as 1 hour, then it keeps all the session objects till 1 hour. This approach effects the scalability and performance because of overhead on memory and garbage collection. In order to reduce memory overhead and to improve performance, it is better to remove/invalidate session explicitly using session.invalidate() method. And also try to adjust the session time out value as per your application's requirement. Third important point is that your application server may serialize session objects into persistent mechanism after crossing certain memory limit. It is expensive and reduces the performance because it not only serializes the single session object but also serializes the total object hierarchy. Use 'transient' for variables to avoid unnecessary serialization. See Serialization for detailed information. So know about your application server/servlet engine session implementation mechanism and act accordingly.

Disable JSP auto reloading

Most of the application servers/JSP engines have the capability of loading JSP's servlets dynamically, that means you need not restart your server whenever you change the JSP content. Application server/JSP engine loads the JSP's servlet every time when you configure that JSP's servlet. For example, if you configure auto reload time as 1 second, then JSP engine loads that JSP's servlet after every 1 second. This feature is good at development time because it reduces the development time by avoiding restart of the server after every change in JSP. But it gives poor performance in the production due unnecessary loading and burden on class loader. So turn off your auto reloading feature in the configuration file to improve performance.

Control Thread pool

JSP engine creates a separate thread for every request and assigns that thread to _jspService() method in its multithreaded JSP's servlet and finally it removes that thread after completion of _jspService() method execution. It happens for every request. Your JSP engine may create a new thread for every request by default. This default behavior reduces performance because creating and removing threads is expensive. This can be avoided by using the thread pool. JSP engine creates pool of threads at start up and assigns a thread from pool to every request instead of creating a fresh thread every time and it returns that thread to the pool after completion. JSP engine creates the thread pool with some default size depending upon configuration parameters of the configuration file for that pool. The pool will have minimum and maximum number of threads and you can configure these numbers in the configuration file of your JSP engine. The number of maximum and minimum threads in pool depend on concurrent users for your application. You have to estimate number of concurrent users for your application and give the thread pool size based on that. Obviously there is a limit on thread pool which depends upon your hard ware resources. By setting thread pool size correctly, The performance of JSP increases significantly. Your application server/ JSP engine may not give the facility to configure thread pool. Tomcat's JSP Engine gives the facility to configure thread pool. Look at your application server / JSP engine documentation for the information about thread pool.

Key Points

  1. Use jspInit() method to cache static data
  2. Use StringBuffer rather than using + operator when you concatenate multiple strings
  3. Use print() method rather than println() method
  4. Use ServletOutputStream instead of JSPWriter to send binary data
  5. Initialize the 'out' object (implicit object) with proper size in the page directive.
  6. Flush the data partly
  7. Minimize code in the synchronized block
  8. Set the content length
  9. Release resources in jspDestroy() method.
  10. Give 'false' value to the session in the page directive to avoid session object creation.
  11. Use include directive instead of include action when you want to include the child page content in the translation phase.
  12. Avoid giving unnecessary scope in the 'useBean' action.
  13. Do not use custom tags if you do not have reusability.
  14. Use application server caching facility
  15. Use Mixed session mechanisms such as 'session' with hidden fields
  16. Use 'session' and 'application' as cache.
  17. Use caching tags provided by different organizations like openSymphony.com
  18. Remove 'session' objects explicitly in your program whenever you finish the task
  19. Reduce session time out value as much as possible
  20. Use 'transient' variables to reduce serialization overhead if your session tracking mechanism uses serialization process.
  21. Disable JSP auto reloading feature.
  22. Use thread pool for your JSP engine and define the size of thread pool as per application requirement.

Thursday, November 10, 2011

How to expand collapse (toggle) div layer using jQuery

Thanks to http://designgala.com/how-to-expand-collapse-toggle-div-layer-using-jquery

In almost all of my projects, I have been using jQuery to toggle the layer. So, I thought of sharing how easy it is to expand div layer and collapse panel using jQuery. When user clicks on the header, the content gets displayed by sliding down and when you again click on the header, the content collapses.

Step 1: Include jQuery Library in head section of your html file.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>

Step 2:

Come up with your own html elements in body section. I chose div ‘layer1' to be the main container where collapsible/expandable content would reside.

Next, class ‘heading’ is given to header while div ‘content’ holds the show hide layer for that heading

<div class="layer1">
<p class="heading">Header-1 </p>
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit</div>
<p class="heading">Header-2</p>
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit</div>
<p class="heading">Header-3</p>
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit</div>
</div>

Step 3:

CSS: Now it totally depends on you to write css for your heading, div. Here’s my version of CSS for this example.

.layer1 {
margin: 0;
padding: 0;
width: 500px;
}
 
.heading {
margin: 1px;
color: #fff;
padding: 3px 10px;
cursor: pointer;
position: relative;
background-color:#c30;
}
.content {
padding: 5px 10px;
background-color:#fafafa;
}
p { padding: 5px 0; }

Step 4:

Again lets go to head section to add few more javascript codes.


<script type="text/javascript">
jQuery(document).ready(function() {
  jQuery(".content").hide();
  //toggle the componenet with class msg_body
  jQuery(".heading").click(function()
  {
    jQuery(this).next(".content").slideToggle(500);
  });
});
</script>

Thats it!! Expandible-Collapsible panel is ready.

What? You want to see a demo.......This post is the demo in itself :)

Caution: When using this in blogger


Because the blogger already has a div with class content which is the parent of all the divs in the page. Hence You need to rename the content class to some other suitable name, before you try to use it with blogger.



How to execute a DOS command from a different working directory using java?

At many times we require to execute a DOS command from within a specific directory.
How do we do that? Here is a utility class that I have written for this purpose.
You don't even need to look into the functions to use this.
Simply add the class to your code and call the executeCommand function.

Util.executeCommand("dir", "D:\\Yogesh");

Click to see more

Util.java



package utilties;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Set;

public class Util
{
    public static String executeCommand(String command, String executionDir)
    {
        String steps[]= new String[3];
        steps[0]="cmd.exe";
        steps[1]="/C";
        steps[2]=command ;
        Process proc=null;
        try
        {
            if(executionDir!=null)
            {
                 proc=Runtime.getRuntime().exec(steps, null, new File(executionDir));
            }
            else
            {
                proc=Runtime.getRuntime().exec(steps);
            }
            InputStream stdin = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(stdin);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            StringBuffer bf = new StringBuffer("");
            while ( (line = br.readLine()) != null)
            {
                    bf.append(line+"\r\n");
            }
            br.close();
            isr.close();
            stdin.close();
            return bf.toString();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return "ERROR";
    }
    public static String executeCommand(String command)
    {
        return executeCommand(command, null);
    }

}

Thursday, November 3, 2011

Change set getter....

Tool for Fetching the files changed in an activity from clearcase.

/**
** Author : Yogesh Gandhi 
**/

package changeset;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;



public class myFrame extends JFrame {

    JLabel lblViewName  = new JLabel("View Name");
    JLabel lblActivityName  = new JLabel("Activity Name");
    JLabel lblDataVOB  = new JLabel("Datavob");
    JTextField  txtViewName = new JTextField("yogesh_bankmed_cod_payout", 30);
    JTextField  txtActivityName = new JTextField("P_1783_312227_LastPageIssue_InitiateCalculationScreen", 30);
    JTextField  txtDataVOB = new JTextField("pay_datavob", 30);
    JButton jbutton = new JButton("Get Change List");
 public myFrame(String title) {
        super(title);
        jbutton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                String filePath="C:\\temp.txt";
                String viewName = txtViewName.getText();
                String activityName = txtActivityName.getText();
                String datavob = txtDataVOB.getText();
                String command = "cleartool lsactivity -l " +
                                 viewName + "@\\" +
                                 datavob + " activity \"" +
                                 activityName+"\"";
                String steps[]= new String[3];
                steps[0]="cmd.exe";
                steps[1]="/C";
                steps[2]=command ;
                Process proc=null;
                Process proc2=null;
                try
                {
                    proc=Runtime.getRuntime().exec(steps, null, new File("M:\\"+viewName));//, envp);
                    InputStream stdin = proc.getInputStream();
                    InputStreamReader isr = new InputStreamReader(stdin);
                    BufferedReader br = new BufferedReader(isr);
                    String line = null;
                    StringBuffer bf = new StringBuffer("");
                    Set files = new HashSet();
                    while ( (line = br.readLine()) != null)
                    {
                        if(line.indexOf("@@")!=-1)
                        {
                            line = line.substring(0, line.indexOf("@@"));
                            files.add(line + "\r\n");
                        }
                        else
                        {
                            bf.append(line+"\r\n");
                        }
                    }
                    int exitVal = proc.waitFor();
                    if(proc!=null)
                    {
                        proc.exitValue();
                    }
                    write2File(bf.toString(), files, filePath);
                    proc2 = Runtime.getRuntime().exec("notepad.exe "+filePath);

                    System.out.println("Process exitValue: " + exitVal);

                }
                catch(Exception ee)
                {
                    if(proc!=null)
                    {
                        proc.destroy();
                    }
                    JOptionPane.showMessageDialog(null, ee.getMessage());
                    ee.printStackTrace();;
                }
                finally
                {
                    if(proc!=null)
                    {
                        proc.destroy();
                    }
                    System.exit(0);
                }

            }
        });

        getContentPane().setLayout(new FlowLayout());
  getContentPane().add(lblViewName);
        getContentPane().add(txtViewName);
        getContentPane().add(lblActivityName);
        getContentPane().add(txtActivityName);
        getContentPane().add(lblDataVOB);
        getContentPane().add(txtDataVOB);
        getContentPane().add(jbutton);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
  this.setSize(350, 300);
  setVisible(true);
 }

    private void write2File(String content, Set set, String filePath) throws Exception
    {
        FileWriter writer = new FileWriter(new File(filePath));
        writer.write(content);
        Iterator it = set.iterator();
        while(it.hasNext())
        {
            writer.write(it.next().toString());
        }
        writer.flush();
        writer.close();
    }
    /**
     *
     * @param args
     */
    public static void main(String[] args)
    {
  new myFrame("Developed by Yogesh Gandhi");
    }
}