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


2. Using object literals


3. Singleton using a function


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.

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


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


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


Put this into your <BODY> section





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



Code with Problem resolved.



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


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

SOLUTION

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



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

Use jspInit() method as cache

Optimization techniques in _jspService() method

Optimization techiques in jspDestroy() method

Optimization techniques in page directive

Choosing right include mechanism

Choosing right session scope in useBean action

Choosing the custom tags versus non custom tags

Cache the static and dynamic data

Choosing the right session mechanism

Control session

Disable JSP auto reloading

Control Thread pool

Key Points

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.


Step 2:


Step 3:


Step 4:

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

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:




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