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 :

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.
     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));


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;
            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

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 :

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: = 123;    

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

The value can be retrieved with either of:  

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)

            FileOutputStream fos = new FileOutputStream("test.txt");
            Writer out = new OutputStreamWriter(fos, "UTF-8");
   catch (IOException e) 

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


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 :

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).

id int(20) auto_increment key,
file_data text,
file_date datetime

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

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

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.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
 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 =, 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";
   StringBuilder contents = new StringBuilder();
   BufferedReader input = new BufferedReader(new FileReader(saveFile));
   while (( line = input.readLine()) != null){
   value = contents.toString();
   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+"'";



   val = pstatement.executeUpdate();

<b>File <% out.println(saveFile); %> has been uploaded and inserted into Database at <%=strDateNew%>.</b>
  catch(Exception e)

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

(i). To import*,java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat packages. 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.