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.