Friday, December 30, 2011

java.sql.SQLException: ORA-03115: unsupported network datatype or representation

java.sql.SQLException: ORA-03115: unsupported network datatype or representation


I was getting the above exception when I was trying to set a CLOB data in the database using java.

More understanding about this exception can be get from

http://www.coderanch.com/t/302117/JDBC/java/java-sql-SQLException-ORA-unsupported

The mistake I was doing and getting the same exception was
While preparing the PreparedStatement Object, i was passing the query like this

pstmt = conn.prepareStatement(sqlQuery.toString());  

And while executing it, again I was giving the query in the overloaded method.

// Please note that DO NOT USE pstmt.executeUpdate(String) overloaded method   
// That will give you this exception : 
// java.sql.SQLException: ORA-03115: unsupported network datatype or representation
int rowsUpdated = pstmt.executeUpdate();  

Use the executeUpdate method without arguments and not the one with a String argument

After making this change, I didn't get this exception.

Exact root cause is still unknown to me as well.

If someone understands it better, please explain it to me as well.




Also to set the clob data in the database you can use the following

String xml= getXml();   
InputStream is = new ByteArrayInputStream(xml.getBytes());   
pstmt.setAsciiStream(++psCount, is, xml.length()); 

Thursday, December 29, 2011

How to fill a increasing values in a column of a table?

How to fill a increasing values in a column of a table?

Lets assume we have a table
Table name : test

NameValue
Yogesh0
Yogesh0
Yogesh0
Yogesh0
Yogesh0
Suresh0
Suresh0

Requirement : to insert 1, 2, 3 .... corresponding to values Yogesh

Query to Update :
create sequence seq start with 1 increment by 1;
update test set Value=seq.nextval where Name='Yogesh';
commit;

Output :
NameValue
Yogesh1
Yogesh2
Yogesh3
Yogesh4
Yogesh5
Suresh0
Suresh0

Wednesday, December 21, 2011

Classes in Javascript

Source : >http://www.phpied.com/3-ways-to-define-a-javascript-class/

3 ways to define a JavaScript class


Introduction


JavaScript is a very flexible object-oriented language when it comes to syntax. In this article you can find three ways of defining and instantiating an object. Even if you have already picked your favorite way of doing it, it helps to know some alternatives in order to read other people's code.

It's important to note that there are no classes in JavaScript. Functions can be used to somewhat simulate classes, but in general JavaScript is a class-less language. Everything is an object. And when it comes to inheritance, objects inherit from objects, not classes from classes as in the "class"-ical languages.


1. Using a function

This is probably one of the most common ways. You define a normal JavaScript function and then create an object by using the new keyword. To define properties and methods for an object created using function(), you use the this keyword, as seen in the following example.

function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = getAppleInfo;
}

// anti-pattern! keep reading...
function getAppleInfo() {
    return this.color + ' ' + this.type + ' apple';
}

To instantiate an object using the Apple constructor function, set some properties and call methods you can do the following:

var apple = new Apple('macintosh');
apple.color = "reddish";
alert(apple.getInfo());

1.1. Methods defined internally

In the example above you see that the method getInfo() of the Apple "class" was defined in a separate function getAppleInfo(). While this works fine, it has one drawback – you may end up defining a lot of these functions and they are all in the "global namespece". This means you may have naming conflicts if you (or another library you are using) decide to create another function with the same name. The way to prevent pollution of the global namespace, you can define your methods within the constructor function, like this:

function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    };
}

Using this syntax changes nothing in the way you instantiate the object and use its properties and methods.

1.2. Methods added to the prototype

A drawback of 1.1. is that the method getInfo() is recreated every time you create a new object. Sometimes that may be what you want, but it's rare. A more inexpensive way is to add getInfo() to the prototype of the constructor function.

function Apple (type) {
    this.type = type;
    this.color = "red";
}

Apple.prototype.getInfo = function() {
    return this.color + ' ' + this.type + ' apple';
};
Again, you can use the new objects exactly the same way as in 1. and 1.1.


2. Using object literals

Literals are shorter way to define objects and arrays in JavaScript. To create an empty object using you can do:
var o = {};
instead of the "normal" way:
var o = new Object();
For arrays you can do:
var a = [];
instead of:
var a = new Array();
So you can skip the class-like stuff and create an instance (object) immediately. Here's the same functionality as described in the previous examples, but using object literal syntax this time:

var apple = {
    type: "macintosh",
    color: "red",
    getInfo: function () {
        return this.color + ' ' + this.type + ' apple';
    }
}

In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.

apple.color = "reddish";
alert(apple.getInfo());

Such an object is also sometimes called singleton. It "classical" languages such as Java, singleton means that you can have only one single instance of this class at any time, you cannot create more objects of the same class. In JavaScript (no classes, remember?) this concept makes no sense anymore since all objects are singletons to begin with.

3. Singleton using a function

Again with the singleton, eh?

The third way presented in this article is a combination of the other two you already saw. You can use a function to define a singleton object. Here's the syntax:

var apple = new function() {
    this.type = "macintosh";
    this.color = "red";
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' apple';
    };
}

So you see that this is very similar to 1.1. discussed above, but the way to use the object is exactly like in 2.

apple.color = "reddish";
alert(apple.getInfo());

new function(){...} does two things at the same time: define a function (an anonymous constructor function) and invoke it with new. It might look a bit confusing if you're not used to it and it's not too common, but hey, it's an option, when you really want a constructor function that you'll use only once and there's no sense of giving it a name.


You saw three (plus one) ways of creating objects in JavaScript. Remember that (despite the article's title) there's no such thing as a class in JavaScript. Looking forward to start coding using the new knowledge? Happy JavaScript-ing!

Tuesday, December 20, 2011

Making the input file box readonly in IE

Is it possible to prevent a user from typing in a file input text box in IE? The reason I ask is that if a user enters text that does not look like a file system path (eg. doesn't start with something like c:...) then when the user clicks the submit button nothing will happen.

I would either like to not allow the user to type in the box


SOLUTION

<input 
type="file" 
name="file" 
onKeyDown="this.blur()" 
onContextMenu="return false;">

In IE 7.0 and IE8.0 this fix is not required. As it has already been made readonly by Microsoft. This fix is specifically required for IE 6.0

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");
    }
}

Monday, October 24, 2011

How to get old Value with onchange() event in text box




You'll need to store the old value manually. You could store it a lot of different ways. You could use a javascript object to store values for each textbox, or you could use a hidden field (I wouldn't recommend it - too html heavy), or you could use an expando property on the textbox itself, like this:


<input type="text" onfocus="this.oldvalue = this.value;" 
onchange="onChangeTest(this);this.oldvalue = this.value;" />

Then your javascript function to handle the change looks like this:



Source : http://stackoverflow.com/questions/1909992/how-to-get-old-value-with-onchange-event-in-text-box

Saturday, October 15, 2011

How to replace in Javascript, when replacement string is a variable


How to replace in Javascript, when replacement string is a variable

Very often we use replace method in javascript while replacing a string literal by another string literal.
But what if we need to replace a string whose value is held in a variable.

Here is the solution...

You can use a regular expression (often referred to as a RegEx or a RegExp). Regular expressions are much more powerful than standard string matching as they can use very complicated logic

// Let's take a look at the above example using regular expressions.
strReplaceSimple = strText.replace( new RegExp( "th", "" ), "[X]" );
 
alert( strReplaceSimple );

As you can see, we have the same replace happening. So let's take a look at what's going on. Instead of passing simple target string to the replace() method, we are passing in a regular expression (new RegExp()) object instance. The RegExp() takes two arguments, the expression and the search flags (left blank in our example). There are two universally valid flags: [g] which means globally replace and [i] which
means case INsensitive. By default, the regular expression is NOT global and case sensitive.

// So let's try to do a global replace using regular expressions.
strReplaceAll = strText.replace( new RegExp( "th", "g" ), "[X]" );
 
alert( strReplaceAll );

We just did a global replace in ONE line of code.

strReplaceAll = strText.replace( new RegExp( "th", "gi" ), "[X]" );
 
alert( strReplaceAll );

We just replaced out that additional "Th" simply by adding the flag [i] into the regular expression. That's how powerful regular expressions are. But there's more. Regular expressions are more than just flags. Much more!

Image that for some reason, you knew about regular expressions, but you didn't know about the case insensitive flag [i]. You could have performed the same replace using this:

strReplaceAll = strText.replace( new RegExp( "(T|t)(H|h)", "g" ), "[X]" );
 
alert( strReplaceAll );

This groups the two letters together, and for each letter it tells the replacing algorithm to match t OR T followed by h OR H. There is sooo much more that regular expressions can do. Unfortunately, that is outside the scope of this entry. You should really look into regular expression both in Javascript and in ColdFusion / Java. They are amazing.

But what happens if you don't want to do a simple replace? The replace method allows some very interesting flexibility. Up until now, we have been passing a simple string in a the "replace-in" argument ([X]). But, you don't have to. You can pass in a function pointer instead.

For this example, let's replace out the target string with a random letter in the brackets, not necessarily the X. First we have to create a function that will return the resultant random string

function RandomString(){
    // Create an array of letters.
    var arrLetters = ["A","B","C","D","E","V","W","X","Y","Z"];
 
    // Use the random() method and the modulus (%) operator to
    // pick a random letter from the above array.
    var intLetter = (Math.floor( Math.random() * 10 ) % 9);
 
    // Return the random letter string we get from the
    // array of letters above.
    return( "[" + arrLetters[ intLetter ] + "]" );
}

Try calling the function on its own a few times, just to see how it behaves.
alert(
     RandomString() + "\n" + RandomString() + "\n" +
     RandomString() + "\n" + RandomString() + "\n" +
     RandomString() + "\n" + RandomString() + "\n" +
     RandomString() + "\n" + RandomString() + "\n"
);

As you can see, it randomly (as random as possible) picks a letter to return. Now, let's call the replace with the RandomString() method sent as the second argument. We will do this a few times so you can see the randomness in effect.

alert( strText.replace( "th", RandomString ) );
alert( strText.replace( "th", RandomString ) );
alert( strText.replace( "th", RandomString ) );

Notice that we are passing in a POINTER to the function but not actually calling it. RandomString vs. RandomString(). There's one thing I did not mention yet. Not only can you pass in a function as an argument, but when the replace method is taking place, it passes in the target match as an argument to this function. We could have re-written the function as such:

function RandomString2( strTargetInstance) // This is the target string match instance.
{
     var arrLetters = ["A","B","C","D","E","V","W","X","Y","Z"];
     var intLetter = (Math.floor( Math.random() * 10 ) % 9);
 
     // Return the random letter string we get from the
     // array of letters above. This time, though, we are
     // going to include the target string to demonstrate
     // that it has been passed in.
     return( "[" + strTargetInstance + " : " + arrLetters[ intLetter ] + "]" );
}

Now, we will run it again, just once, so you can see it in action.

alert( strText.replace( "th", RandomString2 ) );

Want to read more on this? do VISIT HERE

Friday, October 14, 2011

Comparable vs Comparator !!!


Comparable vs Comparator !!!


There are many articles available on internet for this. But still I would write something about it.

What when and why?

A Comparable class is a class, which can be compared with the objects of its own type. Let us take an example of a book.
public class Book implements Comparable {
    String title;
    int    isbn;

    Book(String title, int isbn) {
        this.title = title;
        this.isbn  = isbn;
    }
    /* This method will be the default method used to sort Book objects in a list or Array */
    public int compareTo(Object object) {
    // It should throw NullPointerException if object passed is null
    if (object==null)
    {
        throw new NullPointerException("compareTo: Argument passed is null");
    }
        Book other = (Book) object;
        if (this.title.equals(other.title)) {
            return this.isbn - other.isbn;
        }
        return this.title.compareTo(other.title);
    }
}

The moment your class implements Comparable, you can then use

List list = new LinkedList();
        list.add(new Book("Patterns", 12345));
        list.add(new Book("Apples", 34567));
        list.add(new Book("Examples", 23456));

        Collections.sort(list);

Using this you can sort your list.

But what if now, you want to add or use another sorting criteria defined in Book class... Here comes the need of Comparator.
There are two ways listed here to use the Comparator class.

First method

We create a anonymous class that implements Comparator and overrides compare method.
Collections.sort(list, new Comparator() {
            public int compare(Object obj1, Object obj2) {
                if(obj1 == null || obj2 == null){
                    throw new NullPointerException("compareTo: Argument passed is null");
                }
                Book book1 = (Book) obj1;
                Book book2 = (Book) obj2;
                return book1.isbn - book2.isbn;
            }
        });

Second Method

You define a class that implements Comparator like as below.
class BookComparator implements Comparator{
   
    public int compare(Object book1, Object book2){
   
        int b1= ((Book)book1).isbn;        
        int b2= ((Book)book2).isbn;
       
        if(b1> b2)
            return 1;
        else if(b1< b2)
            return -1;
        else
            return 0;    
    }
   
}
And use this newly defined comparator class as an argument to Collections.sort.
Arrays.sort(list, new BookComparator ());

Good reasons to use Comparator interface

  • I do not have permissions to edit the Book class.
  • Book class already implements Comparable interface, but I want to sort the objects using a different criteria
  • I want to have more than 1 criterias to sort the objects in different orders.

Reasons to implement Comparable interface

  • I want my class to have a default sorting criteria that can be used by the users of my class
  • Usually, one would like to sort the objects based on primary key
Few good links on this topic are here http://www.javadeveloper.co.in/java-example/java-comparator-example.html http://grdurand.com/static/presentation_four/comparable.html http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html

Thursday, October 13, 2011

Dynamically generate HTML elements using javascript and save them on server


Dynamically generate HTML elements using javascript and save them on server


Today while working in office, I had a requirement where I was required to generate dynamic elements in HTML form and then later on submit the form to a server and save the filled in data.

Though it was not very difficult to generate dynamic elements using javascript, but when I tried to save the data by submitting the form, i got an message from the server that the fields I had submitted are not provided.

But I had provided the fields, I was able to see the HTML elements on screen.

I tried to look on internet, might be possible that as disabled fields are not sent to server, similarly there is a chance that dynamically generated fields are also not sent to the server.
And unfortunately I found a link which was supporting my above statement. Here is the link

Actually, I converted a text box to a drop down which got populated using an ajax call. I kept the same ID for the already present textbox and the newly created drop down.
But the values of newly created dropdown were not submitted to the server. So what went wrong???

The mistake I was doing in my project was that I had set the ID of the dynamically generated dropdown, but I forgot to set the name. and in struts if you remember, Action form elements are synched with the elements of the same name in HTML form.

Map in Javascript



Source : http://www.coderanch.com/t/121097/HTML-JavaScript/Map-Javascript

Map in Javascript


var output = {}; 

Sort of. That just creates an empty instance of a JavaScript Object. It's identical to:

var output = new Object();   

There really isn't any implementation of Map in JavaScript.

But... JavaScript objects can be assigned properties on the fly, so an Object acts a lot like a map.

For example, after declaring your variable as shown above, you could write:

output.abc = 123;    

and now the object has a property named abc that contains the value 123.

The value can be retrieved with either of:
output.abc  
   
output['abc']  
 


Tuesday, October 11, 2011

Internationalization tips -- I/O operations

I/O Operations


Whenever text is being read from / written to a file, the encoding should be specified. (Preferably as UTF-8 but need to keep in mind the OS / Language / Locale)

try
   {
            FileOutputStream fos = new FileOutputStream("test.txt");
            Writer out = new OutputStreamWriter(fos, "UTF-8");
            out.write(strInputString);
            out.close();
    } 
   catch (IOException e) 
   {
            e.printStackTrace();
    }
}

Internationalization tips for XML

In order for the XML to support Unicode, the following statement needs to be mentioned at the start of the XML:

<?xml version="1.0" encoding="UTF-8"?>


Apart from these there is BOM issue while saving the XMLs with Unicode characters. Many Windows based text editors add the bytes 0xEF,0xBB,0xBF at the start of document saved in UTF-8 encoding. These set of bytes are Unicode byte-order mark (BOM) though are not relevant to byte order. The BOM can also appear if another encoding with a BOM is translated to UTF-8 without stripping it.

The presence of the UTF-8 BOM may cause interoperability problems with existing software that could otherwise handle UTF-8, for example:

  • Older text editors may display the BOM as "" at the start of the document, even if the UTF-8 file contains only ASCII and would otherwise display correctly.
  • Programming language parsers can often handle UTF-8 in string constants and comments, but cannot parse the BOM at the start of the file.
  • Programs that identify file types by leading characters may fail to identify the file if a BOM is present even if the user of the file could skip the BOM. Or conversely they will identify the file when the user cannot handle the BOM. An example is the UNIX shebang syntax.
  • Programs that insert information at the start of a file will result in a file with the BOM somewhere in the middle of it (this is also a problem with the UTF-16 BOM). One example is offline browsers that add the originating URL to the start of the file
If compatibility with existing programs is not important, the BOM could be used to identify if a file is UTF-8 versus a legacy encoding, but this is still problematical due to many instances where the BOM is added or removed without actually changing the encoding, or various encodings are concatenated together. Checking if the text is valid UTF-8 is more reliable than using BOM. It’s better to omit the BOM while saving the Unicode files. One of the solutions and some discussion surrounding the problem can be found here

Wednesday, October 5, 2011

Forcing SaveAs using the HTTP header

Forcing SaveAs using the HTTP header


In order to force the browser to show SaveAs dialog when clicking a hyperlink you have to include the following header in HTTP response of the file to be downloaded:

Content-Disposition: attachment; filename=<file name.ext>

Where <file name.ext> is the filename you want to appear in SaveAs dialog (like finances.xls or mortgage.pdf) - without < and > symbols.

You have to keep the following in mind:
  • The filename should be in US-ASCII charset.
  • The filename should not have any directory path information specified.
  • The filename should not be enclosed in double quotes even though most browsers will support it.
  • Content-Type header should be before Content-Disposition.
  • Content-Type header should refer to an unknown MIME type (at least until the older browsers go away).
There is something more about it, you must read

THIS

before you use this header.

CLEARCASE : Quickly retrieve change set

R:\>cleartool lsactivity -l yogesh_cdg_cod_dhfl_cas3.7_2@\cascd1_datavob activity "P_1783_DocumentUploadFunctionality" > D:\Yogesh\List.txt



yogesh_cdg_cod_dhfl_cas3.7_2 --> This is the View Name
cascd1_datavob --> This is your datavob
P_1783_DocumentUploadFunctionality --> This is your activity name

Saturday, October 1, 2011

To Upload and insert the file into Database with Current Date and Time In JSP

Source : http://www.roseindia.net/jsp/fileupload.shtml



In this tutorial, you will learn how to upload a file through JSP and insert it into the database. For this, we have created two jsp pages page.jsp and upload_page.jsp. The page.jsp is created for presentation where a file component is created to let the user select the file to be uploaded and a button to submit the request. The action is performed on upload_page.jsp. Before proceeding further, we need table in database. We created table named 'file' for our example.


Step 1 : Create a Table structure for file (mysql for our case).

CREATE TABLE file (
id int(20) auto_increment key,
file_data text,
file_date datetime
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


Step 2:Create a Page ("page.jsp") To Upload a file.

<%@ page language="java" %>
<html>
    <HEAD>
        <TITLE>Display file upload form to the user</TITLE>
    </HEAD> 
    <BODY> 
        <FORM ENCTYPE="multipart/form-data" ACTION="upload_page.jsp" METHOD=POST>
            <center>
            <table border="0" bgcolor=#ccFDDEE>
                <tr>
                        <td colspan="2" align="center"><B>UPLOAD THE FILE</B></td>
                </tr>
                <tr>
                    <td colspan="2" align="center">&nbsp;</td>
                </tr>
                <tr>
                    <td><b>Choose the file To Upload:</b></td>
                    <td><INPUT NAME="file" TYPE="file"></td>
               </tr>
               <tr>
                   <td colspan="2" align="center">&nbsp;</td>
               </tr>
               <tr>
                   <td colspan="2" align="center"><INPUT TYPE="submit" VALUE="Send File" ></td>
               </tr>
           </table>
           </center> 
       </FORM>
    </BODY>
</HTML>



Step 3: Create a page of upload_page.jsp to upload and insert the file in database with current date and time.

<%@ page import="java.io.*,java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
<html>
<%
 int val =0;
 String contentType = request.getContentType();
 if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) 
        {
  DataInputStream in = new DataInputStream(request.getInputStream());
  int formDataLength = request.getContentLength();
  byte dataBytes[] = new byte[formDataLength];
  int byteRead = 0;
  int totalBytesRead = 0;

  while (totalBytesRead < formDataLength) {
   byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
   totalBytesRead += byteRead;
  }
  String file = new String(dataBytes);
  String saveFile = file.substring(file.indexOf("filename=\"") + 10);
  System.out.println("saveFile=" + saveFile);
  saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));
  System.out.println("saveFile" + saveFile);
  saveFile = file.substring(file.indexOf("filename=\"") + 10);
  saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
  saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));
  int lastIndex = contentType.lastIndexOf("=");
  String boundary = contentType.substring(lastIndex + 1,contentType.length());
  int pos;

  pos = file.indexOf("filename=\"");
  pos = file.indexOf("\n", pos) + 1;
  pos = file.indexOf("\n", pos) + 1;
  pos = file.indexOf("\n", pos) + 1;
  int boundaryLocation = file.indexOf(boundary, pos) - 4;
  int startPos = ((file.substring(0, pos)).getBytes()).length;
  int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

  FileOutputStream fileOut = new FileOutputStream(saveFile);
  fileOut.write(dataBytes, startPos, (endPos - startPos));
%>

<%
  Connection con=null;
  PreparedStatement pstatement = null;
  String line = null;
  String value=null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "file_upload";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "root"; 
  String password = "root";
  try
                {
   StringBuilder contents = new StringBuilder();
   BufferedReader input = new BufferedReader(new FileReader(saveFile));
   while (( line = input.readLine()) != null){
    contents.append(line);
   }
   value = contents.toString();
   System.out.println("Value:"+value);
   Class.forName("com.mysql.jdbc.Driver");
   con = DriverManager.getConnection(url+dbName,userName,password);
   java.util.Date now = new java.util.Date();
   String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
   SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
   String strDateNew = sdf.format(now) ;

   String queryString = "INSERT INTO file_tbl set file_data='"+value+"',file_date='"+strDateNew+"'";

   //out.println(queryString);

   pstatement=con.prepareStatement(queryString);


   val = pstatement.executeUpdate();

   if(val>0)
   {
%>
<br><br>
<b>File <% out.println(saveFile); %> has been uploaded and inserted into Database at <%=strDateNew%>.</b>
<%
   }
  }
  catch(Exception e)
  {
  }
 }
%>
</html>


This file upload and insert into database with current date and time using JDBC database. This can be done

(i). To import java.io.*,java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat packages. Java.io Packages is used to read and write the file uploaded having classes like DataInputStream, FileOutputStream etc. java.util.*,java.text.*,java.text.SimpleDateFormat is used to retireve the current Date and Time.
(ii). Prepared Statement is used to insert the data into database having used pstatement=con.prepareStatement(queryString);
(iii). Using a Query "INSERT INTO file_tbl set file_data='"+value+"',file_date='"+strDateNew+"'" to insert the data into database.

Step 4: Output when file upload and insert into database with current date and time.

Table Structure after file Upload :



A message has been displayed on the browser.

The file is inserted into the database with current date and time.



Saturday, September 24, 2011

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

The jsp page gives the following error : The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

Even if you include this:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

in your jsp page, it still gives the error.

The reason is that it depends upon the web app version. The web app version is defined in the web.xml file as follows:

Here’s an example of what to look for in web.xml:
<?xml version="1.0" encoding="UTF-8"?>

  web-app-25
...

You can see the version="2.5" designation in here. This means that within this web application, we will be able to use JSP 2.1 and JSTL 1.2 features.


Here, the web app version is 2.3.

So, if you are using web app version 2.3, then we should use :

<%@taglib prefix="c" uri="http://java.sun.com/jsp/core" %>

For Web app versions 2.4 & 2.5, you should use:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


Complete Error Trace:


WARNING: /SpringDemo/customer.htm:
org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application
at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:50)
at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:114)
at org.apache.jasper.compiler.TagLibraryInfoImpl.generateTLDLocation(TagLibraryInfoImpl.java:316)
at org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:147)
at org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:423)
at org.apache.jasper.compiler.Parser.parseDirective(Parser.java:492)
at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1552)
at org.apache.jasper.compiler.Parser.parse(Parser.java:126)
at org.apache.jasper.compiler.ParserController.doParse(ParserController.java:211)
at org.apache.jasper.compiler.ParserController.parse(ParserController.java:100)
at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:155)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:295)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:276)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:264)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:563)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:303)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:428)
at org.mortbay.jetty.servlet.WebApplicationHandler.dispatch(WebApplicationHandler.java:473)
at org.mortbay.jetty.servlet.Dispatcher.dispatch(Dispatcher.java:286)
at org.mortbay.jetty.servlet.Dispatcher.forward(Dispatcher.java:171)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:239)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1072)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:808)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:726)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:636)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:556)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:616)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:428)
at org.mortbay.jetty.servlet.WebApplicationHandler.dispatch(WebApplicationHandler.java:473)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:568)
at org.mortbay.http.HttpContext.handle(HttpContext.java:1530)
at org.mortbay.jetty.servlet.WebApplicationContext.handle(WebApplicationContext.java:633)
at org.mortbay.http.HttpContext.handle(HttpContext.java:1482)
at org.mortbay.http.HttpServer.service(HttpServer.java:909)
at org.mortbay.http.HttpConnection.service(HttpConnection.java:820)
at org.mortbay.http.HttpConnection.handleNext(HttpConnection.java:986)
at org.mortbay.http.HttpConnection.handle(HttpConnection.java:837)
at org.mortbay.http.SocketListener.handleConnection(SocketListener.java:245)
at org.mortbay.util.ThreadedServer.handle(ThreadedServer.java:357)
at org.mortbay.util.ThreadPool$PoolThread.run(ThreadPool.java:534)


Reference : http://www.mularien.com/blog/2008/04/24/how-to-reference-and-use-jstl-in-your-web-application/