In Oracle, when we store a empty string i.e. "" through JDBC, then Oracle stores it as a NULL value. This causes a lot of confusion to Java developers. In Java a null and a "" are 2 different entities.
Hence even if you store an "" string when inserting into the database, when you retrieve the results, you would get the string as null.
If we do a getInt(), getFloat() etc. then we would get 0.
Saturday, July 14, 2007
Friday, July 13, 2007
Dynamically making a field as readOnly using Javascript
I was looking for a sleek solution that would make all the fields of my form read-only dynamically - or atleast make them appear to be readonly.
I decided to use the powerful JQuery library to make this happen. Here is the code that can be put in a JSP/ASP page and included in any page that needs to have all fields as readonly.
$(document).ready(function(){
$(":input,checkbox,radio").addClass("readonlytextbox");
$(":input").focus(function() {this.blur();} );
$("input[@type=checkbox]").click(function()
{alert("Cannot change this field.");
return false;} );
$("input[@type=checkbox]").keydown(function()
{return false;} );
$("input[@type=radio]").click(function()
{return false;} );
$("input[@type=radio]").keydown(function()
{return false;} );
$("select").focus(function()
{alert("Cannot change this field.");
return false;} );
//-- end of code
});
I decided to use the powerful JQuery library to make this happen. Here is the code that can be put in a JSP/ASP page and included in any page that needs to have all fields as readonly.
$(document).ready(function(){
$(":input,checkbox,radio").addClass("readonlytextbox");
$(":input").focus(function() {this.blur();} );
$("input[@type=checkbox]").click(function()
{alert("Cannot change this field.");
return false;} );
$("input[@type=checkbox]").keydown(function()
{return false;} );
$("input[@type=radio]").click(function()
{return false;} );
$("input[@type=radio]").keydown(function()
{return false;} );
$("select").focus(function()
{alert("Cannot change this field.");
return false;} );
//-- end of code
});
ReadOnly and Disabled fields
In HTML, we have two options if we want non-editable fields. Mark the fields as readonly or make them disabled.
The difference between the two is that a diabled field is not send as a HTTP parameter to the server when the form is submitted, whereas a readonly field is send back to the server.
This may be important when you use frameworks such as Struts where the formbeans may expect nested properties to come back to the server.
The difference between the two is that a diabled field is not send as a HTTP parameter to the server when the form is submitted, whereas a readonly field is send back to the server.
This may be important when you use frameworks such as Struts where the formbeans may expect nested properties to come back to the server.
Thursday, June 21, 2007
Snoop on Solaris and Ethereal
I am a big fan of Ethereal tool and use it frequently for analysis of network traffic.
The GUI is great and we can decode HTTP traffic from the TCP packet frames.
Recently I had to capture the traffic on a remote production box running on Solaris and did not have the time to install Ethereal there. I knew about the 'snoop' command on Solaris and had used it in the past to capture network calls.
But I did not know that the snoop command can write all captured network packets to a file that is RFC 1761- compliant. What that means is that I can write the packets to a file and then open that file anywhere in Ethereal :)
This was just what I needed for my scenario. Quick listing of snoop commands:
- To capture packets to a file and only those on port 9080
snoop -o fileName.cap port 9080
- To format a captured file in ASCII
snoop -i fileName.cap -x0
The GUI is great and we can decode HTTP traffic from the TCP packet frames.
Recently I had to capture the traffic on a remote production box running on Solaris and did not have the time to install Ethereal there. I knew about the 'snoop' command on Solaris and had used it in the past to capture network calls.
But I did not know that the snoop command can write all captured network packets to a file that is RFC 1761- compliant. What that means is that I can write the packets to a file and then open that file anywhere in Ethereal :)
This was just what I needed for my scenario. Quick listing of snoop commands:
- To capture packets to a file and only those on port 9080
snoop -o fileName.cap port 9080
- To format a captured file in ASCII
snoop -i fileName.cap -x0
Time complexity and Space complexity of algorithms
I had just downloaded the SAP Memory Analyser and was impressed with its performance.
More information on this tool can be found here. Going thru their wiki, I read how they had taken pains to make critical operations have a time complexity of O(1).
Time complexity and Space complexity are terms used when dealing with algorithms. If the input size (problem size) for a algorithm increases, then how does it affect the time taken for the algorithm to complete and how how much more memory does it take?
If the time consumed by the algorithm is independant of the input size then the algorithm is said to be a complexity of O(1); i.e. a constant-time method. If the time taken is linear then it is known as linear-time method - O(n).
More information can be found at the following links:
http://pages.cs.wisc.edu/~hasti/cs367-common/
notes/COMPLEXITY.html
http://www.leda-tutorial.org/en/official/ch02s02s03.html
More information on this tool can be found here. Going thru their wiki, I read how they had taken pains to make critical operations have a time complexity of O(1).
Time complexity and Space complexity are terms used when dealing with algorithms. If the input size (problem size) for a algorithm increases, then how does it affect the time taken for the algorithm to complete and how how much more memory does it take?
If the time consumed by the algorithm is independant of the input size then the algorithm is said to be a complexity of O(1); i.e. a constant-time method. If the time taken is linear then it is known as linear-time method - O(n).
More information can be found at the following links:
http://pages.cs.wisc.edu/~hasti/cs367-common/
notes/COMPLEXITY.html
http://www.leda-tutorial.org/en/official/ch02s02s03.html
Tuesday, June 05, 2007
Generating GUIDs on the client side web browser
If your application requires that a GUID be created to identify the client, then we have 2 options:
- If we are sure that the end users use only IE, then we can use the ActiveX function:
Basically the function uses the random numbers and padding to generate a unique number.
Snippet of the JS function:
- If we are sure that the end users use only IE, then we can use the ActiveX function:
return new ActiveXObject("Scriptlet.TypeLib").
GUID.substr(1,36);For other browsers, we can write a JS function as shown here.Basically the function uses the random numbers and padding to generate a unique number.
Snippet of the JS function:
function generateGuid()
{
var result, i, j;
result = '';
for(j=0; j<32; j++)
{
if( j == 8 || j == 12|| j == 16|| j == 20)
result = result + '-';
i = Math.floor(Math.random()*16).
toString(16).toUpperCase();
result = result + i;
}
return result
}
Friday, June 01, 2007
4 GB memory limitation for 32 bit machines
What is the maximum heap size that U can allocate to a JVM or a .NET runtime?
The answer is dependant on the operating system and hardware. On a 32-bit machine, the CPU can use only 32 bits to refer to a memory pointer. Hence 2^32 = 4 gb.
Out of this, 2gb is reserved for the kernel and 2 gb for the applications. Hence we can allocate only 2gb memory to an application. More info on this can be found here.
For a JVM, if we need to allocate more than 2 gb of heap, then we need to install the 64 bit version of the JDK. Also on a solaris box, start the java process with the -d64 option.
The answer is dependant on the operating system and hardware. On a 32-bit machine, the CPU can use only 32 bits to refer to a memory pointer. Hence 2^32 = 4 gb.
Out of this, 2gb is reserved for the kernel and 2 gb for the applications. Hence we can allocate only 2gb memory to an application. More info on this can be found here.
For a JVM, if we need to allocate more than 2 gb of heap, then we need to install the 64 bit version of the JDK. Also on a solaris box, start the java process with the -d64 option.
Sunday, May 20, 2007
servletContext.getRealPath() issue
Our application was using getRealPath() method to obtain the base path of the web application on the server. I noticed that the method was not behaving consistently across JEE containers.
On Windows/Tomcat5.5, getRealPath returned the path with a '/' at the end.
But on Solaris/Websphere, getRealPath returned the path without a '/' at the end.
The best way to handle this is to have a utility method that would handle all cases :-
On Windows/Tomcat5.5, getRealPath returned the path with a '/' at the end.
But on Solaris/Websphere, getRealPath returned the path without a '/' at the end.
The best way to handle this is to have a utility method that would handle all cases :-
String realPath =Also check if using getRealPath is really required. The Servlet API specifies a temp directory that can be accessed using the following code:
getServletContext.getRealPath(path);
if ((realPath != null)
&& !realPath.endsWith("/"))
realPath += "/";
File dir=(File)getServletContext().getAttribute
("javax.servlet.context.tempdir");
Tuesday, May 15, 2007
Silently print PDFs on the browser
If your web application needs to print PDF's silently on the browser, then check out this blog.
Of all options given, I found the iText trick the simplest to use. The concept is quite simple:
- Create a PDF on the fly using iText
- Embed Acrobat Javascript into the PDF that would print it automatically to the default printer.
- Open the PDF document in a iFrame that is hidden (size 0*0)
A live example can be found here.
Of all options given, I found the iText trick the simplest to use. The concept is quite simple:
- Create a PDF on the fly using iText
- Embed Acrobat Javascript into the PDF that would print it automatically to the default printer.
- Open the PDF document in a iFrame that is hidden (size 0*0)
A live example can be found here.
Thursday, May 03, 2007
Modal Dialog submit issue
In our application we were using a modal window pop-up. The user has to enter some fields and submit the form. The strange thing was that whenever I submitted the form, a new window was getting poped up.
I knew there was nothing wrong with the javascript code...so I googled around a bit and found the soultion here.
All that is needed is to add the following line inside the "head" tag of the modal page :
<base target=_self>
I knew there was nothing wrong with the javascript code...so I googled around a bit and found the soultion here.
All that is needed is to add the following line inside the "head" tag of the modal page :
<base target=_self>
Generating PDFs on the fly
If we need to generate PDFs on the fly in a JEE web application , then we have 2 open-source options: using Apache FOP or iText.
The approach used by both the leading projects is different. Apache FOP uses XML/XSL to create a XSL-FO file using XSLT Transformation. This XSL-FO is then rendered into a PDF using the PDF FO processor. This is a pretty neat solution as there is a clear separation of concerns. But the only caveat is that U need to have a pretty good hold over the XSL language, which in my personal opinion is very arcane and difficult to learn. But if you gain mastery over XSL, then there is pretty much nothing U cannot do with FOP :)
iText is a pure Java API that allows developers to create PDFs on the fly. For e.g. the iText API would have methods such as 'addPara','addBlock','addImage' etc. etc. So U end up embedding the presentation logic in Java code...but it may not be a big deal for anyone except design purists. It is also possible to use absolute coordinates while creating your PDF's, but I would advice against if there is a possibility of the look&feel of reports changing often.
iText is hugely popular and has been ported to .NET (C-Sharp port known as iTextSharp and the J-Sharp port known as iText.NET)
The popular JasperReports open-source reporting tool uses iText in the background to make PDF documents. Also iText boasts of superb speed - (Creating a 1000 page PDF takes only a few seconds). Even on the FOP site, they recommend iText as a post-processor tool for merging, encrypting, changing PDF documents.
If someone is looking only for a PDF manipulation tool then they should have a look at pdftk. It is also based on iText.
The approach used by both the leading projects is different. Apache FOP uses XML/XSL to create a XSL-FO file using XSLT Transformation. This XSL-FO is then rendered into a PDF using the PDF FO processor. This is a pretty neat solution as there is a clear separation of concerns. But the only caveat is that U need to have a pretty good hold over the XSL language, which in my personal opinion is very arcane and difficult to learn. But if you gain mastery over XSL, then there is pretty much nothing U cannot do with FOP :)
iText is a pure Java API that allows developers to create PDFs on the fly. For e.g. the iText API would have methods such as 'addPara','addBlock','addImage' etc. etc. So U end up embedding the presentation logic in Java code...but it may not be a big deal for anyone except design purists. It is also possible to use absolute coordinates while creating your PDF's, but I would advice against if there is a possibility of the look&feel of reports changing often.
iText is hugely popular and has been ported to .NET (C-Sharp port known as iTextSharp and the J-Sharp port known as iText.NET)
The popular JasperReports open-source reporting tool uses iText in the background to make PDF documents. Also iText boasts of superb speed - (Creating a 1000 page PDF takes only a few seconds). Even on the FOP site, they recommend iText as a post-processor tool for merging, encrypting, changing PDF documents.
If someone is looking only for a PDF manipulation tool then they should have a look at pdftk. It is also based on iText.
Tuesday, May 01, 2007
Setting Cache headers for Gifs, Css and JS files
By default, browser and servers use the "if-modified-since" header to check if the file should be downloaded from the server or given from the cache.
Though this default behaviour is good for performance, we can increase the performance by giving a cache expiry period. This would make the browser cache the content for that period - i.e. the browser won't even make "if-modified-since" conditional fetch requests.
The best place to set these headers in a J2EE application is thru a filter.
Suppose you want to cache GIFs, CSS and JPEG for 2 hours, just add this header in the response:
Cache-Control: max-age=120
Though this default behaviour is good for performance, we can increase the performance by giving a cache expiry period. This would make the browser cache the content for that period - i.e. the browser won't even make "if-modified-since" conditional fetch requests.
The best place to set these headers in a J2EE application is thru a filter.
Suppose you want to cache GIFs, CSS and JPEG for 2 hours, just add this header in the response:
Cache-Control: max-age=120
Setting nocache headers in Struts Applications
In older versions of struts, it was a common practise to extend the ActionServlet and set the no-cache response headers there, so that they are applied to all requests.
In Struts 1.2.x, there is a easier way - without writing a single line of Java code.
Just add the "nocache" attribute to the controller element in struts-config.xml file.
<controller
processorClass="MyRequestProcessor"
nocache="true" />
In Struts 1.2.x, there is a easier way - without writing a single line of Java code.
Just add the "nocache" attribute to the controller element in struts-config.xml file.
<controller
processorClass="MyRequestProcessor"
nocache="true" />
Disabling keep-alive connections in Tomcat
I was using TcpTrace utility to dump my HTTP requests/responses. But the problem was that my Server (Tomcat) was using keep-alive connections and bcoz of this, the output in TcpTrace was all muddled up.
Disabling keep-alive connections in Tomcat 5.5 was quite simple:
Just add the maxKeepAliveRequests="1" attribute to the Connector tag in server.xml
Disabling keep-alive connections in Tomcat 5.5 was quite simple:
Just add the maxKeepAliveRequests="1" attribute to the Connector tag in server.xml
CSS caching in IE
A strange problem regarding CSS caching had frustrated me for a whole 2 hours today.
The problem was reported by one of the developers that even if the CSS on the server was changed, IE was still used the cached version. I checked the application and found that there were no Cache headers that were set. This meant that IE should have made a GET "if-modified-since" request everytime for the CSS.
I even dumped the requests using the TcpTrace sniffer. I could see that IE did send a request for the CSS file and also the server responding with the new CSS file. Still no change on the page ?? This really baffled me ...If I hit F5/refresh, then the new CSS was loaded, but if I revisited the page, then still the old CSS was being used..
Then I learned from some site, that IE behaves a bit oddly here : IE usually caches CSS files by browser session (until you exit the browser). With a new session, the browser does a head request to see if the file has been modified, if so it reloads. So if I logged off the application and logged in again, the CSS would be reloaded. Strangely, this would not always happen...But if I close the browser and open the application again, I always get the new CSS..
It seems that IE is a bit erratic in this respect...so to be absolutely sure that U get the new CSS, you may have to close the browser and open it again :)
The problem was reported by one of the developers that even if the CSS on the server was changed, IE was still used the cached version. I checked the application and found that there were no Cache headers that were set. This meant that IE should have made a GET "if-modified-since" request everytime for the CSS.
I even dumped the requests using the TcpTrace sniffer. I could see that IE did send a request for the CSS file and also the server responding with the new CSS file. Still no change on the page ?? This really baffled me ...If I hit F5/refresh, then the new CSS was loaded, but if I revisited the page, then still the old CSS was being used..
Then I learned from some site, that IE behaves a bit oddly here : IE usually caches CSS files by browser session (until you exit the browser). With a new session, the browser does a head request to see if the file has been modified, if so it reloads. So if I logged off the application and logged in again, the CSS would be reloaded. Strangely, this would not always happen...But if I close the browser and open the application again, I always get the new CSS..
It seems that IE is a bit erratic in this respect...so to be absolutely sure that U get the new CSS, you may have to close the browser and open it again :)
Monday, April 30, 2007
Magic of JQuery
We know that in IE, a form gets submitted whenever we press 'Enter' in a text-field. To disable it would require trapping the event in Javascript and disabling the default behaviour.
<input onkeydown="if (event.keyCode == 13){returnfalse;}" name="email">
But to do this in all text fields across hundreds of html pages would be a impossible task. Then suddenly I got the idea of using JQuery's powerful selector concept to apply this to all textfields across all pages. I just needed to add the following lines to the JS file that was present in all pages.
<script src="jquery-1.1.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input[@type=text]").keypress( function() {
if (event.keyCode == 13){return false;}
} );
});
</script>
<input onkeydown="if (event.keyCode == 13){returnfalse;}" name="email">
But to do this in all text fields across hundreds of html pages would be a impossible task. Then suddenly I got the idea of using JQuery's powerful selector concept to apply this to all textfields across all pages. I just needed to add the following lines to the JS file that was present in all pages.
<script src="jquery-1.1.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input[@type=text]").keypress( function() {
if (event.keyCode == 13){return false;}
} );
});
</script>
Friday, April 27, 2007
Mean, Median, Mode, Midrange and Standard Deviation
A definition of terms to help my frail memory when I need it most :)
The arithmetic mean is the sum of the numbers, divided by the quantity of the numbers.
The geometric mean of two numbers is the square root of their product.The geometric mean of three numbers is the cubic root of their product.
The quantity obtained by adding the largest and smallest values and dividing by 2, statisticians call the midrange.
The median is the central point of a data set. To find the median, you would list all data points in ascending order and simply pick the entry in the middle of that list. If there are an even number of observations, the median is not unique, so one often takes the mean of the two middle values.
The standard deviation is the most common measure of statistical dispersion, measuring how widely spread the values in a data set are. If the data points are close to the mean, then the standard deviation is small. Conversely, if many data points are far from the mean, then the standard deviation is large. If all the data values are equal, then the standard deviation is zero.It is defined as the square root of the variance.
For lists, the mode is the most common (frequent) value. A list can have more than one mode. For histograms, a mode is a relative maximum ("bump"). A data set has no mode when all the numbers appear in the data with the same frequency. A data set has multiple modes when two or more values appear with the same frequency.A distribution with two modes is called bimodal. A distribution with three modes is called trimodal.
The arithmetic mean is the sum of the numbers, divided by the quantity of the numbers.
The geometric mean of two numbers is the square root of their product.The geometric mean of three numbers is the cubic root of their product.
The quantity obtained by adding the largest and smallest values and dividing by 2, statisticians call the midrange.
The median is the central point of a data set. To find the median, you would list all data points in ascending order and simply pick the entry in the middle of that list. If there are an even number of observations, the median is not unique, so one often takes the mean of the two middle values.
The standard deviation is the most common measure of statistical dispersion, measuring how widely spread the values in a data set are. If the data points are close to the mean, then the standard deviation is small. Conversely, if many data points are far from the mean, then the standard deviation is large. If all the data values are equal, then the standard deviation is zero.It is defined as the square root of the variance.
For lists, the mode is the most common (frequent) value. A list can have more than one mode. For histograms, a mode is a relative maximum ("bump"). A data set has no mode when all the numbers appear in the data with the same frequency. A data set has multiple modes when two or more values appear with the same frequency.A distribution with two modes is called bimodal. A distribution with three modes is called trimodal.
Wednesday, April 25, 2007
DST implementations in Operating Systems and Java
I often wondered how operating systems knew about Day light saving offsets. Recently USA decided to change its DST settings and it immediately crossed my mind as to how Operating Systems and Applications would react to this.
Some basics first - In what format does a OS store date/time information ? All machines keep their clocks in synch with the GMT using Network Time Protocol. Then the machine calculates it local time using the local time zone settings that are stored on the machine.
Local time is always computed as = GMT + timezone offset + DST offset
But where does the OS get information about DST. All DST information is stored in a binary database called ZoneInfo database or TimeZone DB. On Solaris this database can be found at "/usr/share/lib/zoneinfo"
In Java, the JRE picks up DST information from the Timezone database stored at "%JRE_HOME%/lib/zi"
Tip: In Java, U can change the default timezone that the application uses by setting the user.timezone property
e.g. java -Duser.timezone=Area/City
or
java -Duser.timezone=GMT[+5.30]
Some basics first - In what format does a OS store date/time information ? All machines keep their clocks in synch with the GMT using Network Time Protocol. Then the machine calculates it local time using the local time zone settings that are stored on the machine.
Local time is always computed as = GMT + timezone offset + DST offset
But where does the OS get information about DST. All DST information is stored in a binary database called ZoneInfo database or TimeZone DB. On Solaris this database can be found at "/usr/share/lib/zoneinfo"
In Java, the JRE picks up DST information from the Timezone database stored at "%JRE_HOME%/lib/zi"
Tip: In Java, U can change the default timezone that the application uses by setting the user.timezone property
e.g. java -Duser.timezone=Area/City
or
java -Duser.timezone=GMT[+5.30]
web.xml SAXParseException in Websphere v6.1
I encountered a wierd problem while re-deploying a war file on Websphere v6.1. I started getting a SAXParseException in web.xml. The only change I had made was to introduce the "error-page" tag.
The war file was working fine in Tomcat, Weblogic and Geronimo. Digging into the logs of Websphere, I found this message:
org.xml.sax.SAXParseException: The content of element type "web-app"
must match "(icon?,display-name?,description?,distributable?,
context-param*,filter*,filter-mapping*,listener*,servlet*,
servlet-mapping*,session-config?,mime-mapping*,welcome-file-list?,
error-page*,taglib*,resource-env-ref*,resource-ref*,security-constraint*,
login-config?,security-role*,env-entry*,ejb-ref*,ejb-local-ref*)". [wsjspc]
I wondered if the order of the tags was important to WAS. So I placed the error-page tag between the welcome-file-list and taglib tags..and the SAXException disappeared :)
But I found it rather strange that the order of the tags should be important..not sure if it is part of the servlet spec.
The war file was working fine in Tomcat, Weblogic and Geronimo. Digging into the logs of Websphere, I found this message:
org.xml.sax.SAXParseException: The content of element type "web-app"
must match "(icon?,display-name?,description?,distributable?,
context-param*,filter*,filter-mapping*,listener*,servlet*,
servlet-mapping*,session-config?,mime-mapping*,welcome-file-list?,
error-page*,taglib*,resource-env-ref*,resource-ref*,security-constraint*,
login-config?,security-role*,env-entry*,ejb-ref*,ejb-local-ref*)". [wsjspc]
I wondered if the order of the tags was important to WAS. So I placed the error-page tag between the welcome-file-list and taglib tags..and the SAXException disappeared :)
But I found it rather strange that the order of the tags should be important..not sure if it is part of the servlet spec.
Tuesday, April 24, 2007
Cool tools - Squirrel SQL Client, IzPack Java Installer
Came across 2 tools that I liked :)
Squireel SQL client: Use it to connect to any database using JDBC.
http://squirrel-sql.sourceforge.net/
IzPack Java Installer: A simple opensource free installer for Java. But this requires that JDK be present on the installation machine.
http://izpack.org/
Squireel SQL client: Use it to connect to any database using JDBC.
http://squirrel-sql.sourceforge.net/
IzPack Java Installer: A simple opensource free installer for Java. But this requires that JDK be present on the installation machine.
http://izpack.org/
Show friendly HTTP error messages in IE
In web.xml, I added the tag to redirect to an error page when ever a 500 internal server error occurs. But in IE, the page was still not getting displayed.
I added a sniffer to check what was going on. I could see that the custom error page was returned by the server in the HTTP response, yet IE was ignoring it. Googling around, I found out that IE has a feature turned on by default - Show friendly HTTP error messages (goto tools-> internet options-> advanced -> uncheck show friendly HTTP error message)
If I unchecked this checkbox, then the custom page was getting displayed correctly. But this was obviously not a solution that was practical. I perused thru more info about this IE feature here. IE uses this feature only if the response content for a 500 status-code response was less than 512 bytes.
So now, I suddenly had 2 solutions to the above problem (without having to change IE settings on the client)
Solution 1: Increase the content of the error page to more than 512 bytes.
Solution 2: Change the HTTP status code sent in the response header of the error page to HTTP 200.
Code snippet (at the top of the error jsp page):
response.setStatus(200);
I added a sniffer to check what was going on. I could see that the custom error page was returned by the server in the HTTP response, yet IE was ignoring it. Googling around, I found out that IE has a feature turned on by default - Show friendly HTTP error messages (goto tools-> internet options-> advanced -> uncheck show friendly HTTP error message)
If I unchecked this checkbox, then the custom page was getting displayed correctly. But this was obviously not a solution that was practical. I perused thru more info about this IE feature here. IE uses this feature only if the response content for a 500 status-code response was less than 512 bytes.
So now, I suddenly had 2 solutions to the above problem (without having to change IE settings on the client)
Solution 1: Increase the content of the error page to more than 512 bytes.
Solution 2: Change the HTTP status code sent in the response header of the error page to HTTP 200.
Code snippet (at the top of the error jsp page):
response.setStatus(200);
Monday, April 23, 2007
UnsatisfiedLinkError while loading native libraries
I encountered the following problem when calling native code from a Java application deployed on Websphere.
Whenever I was redeploying the WAR file, I started getting UnsatisfiedLinkError - native library already loaded by a classloader.
I knew that the call to "System.loadLibrary" should occur only once in a classloader context. We typically put this code in a static block of a class. But it seemed that in Websphere, when the web application context (classloader) was reloaded, the native libraries were not unloaded. Hence whenever I reloaded the webapp, the above error manifested itself.
To solve the above problem, there were 2 options:
- Put the call to System.loadLibrary inside a static block of a class and load this class as a shared library in Websphere. This will load the class using the System classloader and not the web-application classloader.
- Restart the application server everytime the war/ear file was updated. This solution may or may not be feasible depending on your infrastructure setup.
Imp Caveat: Any crash in the call to the native library crashes the JVM itself. Hence for critical applications, other design alternatives should be thought of. For e.g. writing a separate application that will have a RMI/SOAP/XML interface that will do all the JNI plumbing. This separate application would run in a separate JVM outside of the JEE container JVM. Your webapp would then call this application.
Whenever I was redeploying the WAR file, I started getting UnsatisfiedLinkError - native library already loaded by a classloader.
I knew that the call to "System.loadLibrary" should occur only once in a classloader context. We typically put this code in a static block of a class. But it seemed that in Websphere, when the web application context (classloader) was reloaded, the native libraries were not unloaded. Hence whenever I reloaded the webapp, the above error manifested itself.
To solve the above problem, there were 2 options:
- Put the call to System.loadLibrary inside a static block of a class and load this class as a shared library in Websphere. This will load the class using the System classloader and not the web-application classloader.
- Restart the application server everytime the war/ear file was updated. This solution may or may not be feasible depending on your infrastructure setup.
Imp Caveat: Any crash in the call to the native library crashes the JVM itself. Hence for critical applications, other design alternatives should be thought of. For e.g. writing a separate application that will have a RMI/SOAP/XML interface that will do all the JNI plumbing. This separate application would run in a separate JVM outside of the JEE container JVM. Your webapp would then call this application.
Friday, April 20, 2007
Sequence numbers from a Oracle RAC cluster
Today, I faced a peculiar problem. Our application was using a Sequence to autogenerate unique numbers required for a particular functionality. When testing the application against a standalone Oracle server, the sequence numbers generated were in order.
But in the production evnironment, where we were using a Oracle RAC cluster, the sequence numbers returned were not in order..This was creating a lot of confusion. The reason was that by default sequences in 10g RAC are created without ordering. This is to reduce performance bottleneck as there would be synchronization requried across all nodes of the cluster. Each node creates a cache of the sequence as specified in the SQL.
If we need to maintain the order then we need to add the ORDER argument to the sequence.
Example of Sequence Syntax in Oracle RAC:
CREATE SEQUENCE "MY_DEV"."CON_SEQ" MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 111785 CACHE 500 ORDER NOCYCLE ;
But in the production evnironment, where we were using a Oracle RAC cluster, the sequence numbers returned were not in order..This was creating a lot of confusion. The reason was that by default sequences in 10g RAC are created without ordering. This is to reduce performance bottleneck as there would be synchronization requried across all nodes of the cluster. Each node creates a cache of the sequence as specified in the SQL.
If we need to maintain the order then we need to add the ORDER argument to the sequence.
Example of Sequence Syntax in Oracle RAC:
CREATE SEQUENCE "MY_DEV"."CON_SEQ" MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 111785 CACHE 500 ORDER NOCYCLE ;
Thursday, April 12, 2007
NTLM authentication using Commons HttpClient
Recently I wanted to access a site outside the firewall thru Apache commons HttpClient. The proxy server was using NTLM authentication.
Thankfully, HttpClient had support for NTLM authentication. Here's the code snippet for the same:
--------------------------------------------------------------
HostConfiguration hConf= httpClient.getHostConfiguration();
hConf.setProxy("proxy.mycompany.com", 8080);
httpClient.getState().setProxyCredentials(
new AuthScope("proxy.mycompany.com", 8080, "domainName"),
new NTCredentials("username", "password","my_localhost","domainName")
);
--------------------------------------------------------------
Thankfully, HttpClient had support for NTLM authentication. Here's the code snippet for the same:
--------------------------------------------------------------
HostConfiguration hConf= httpClient.getHostConfiguration();
hConf.setProxy("proxy.mycompany.com", 8080);
httpClient.getState().setProxyCredentials(
new AuthScope("proxy.mycompany.com", 8080, "domainName"),
new NTCredentials("username", "password","my_localhost","domainName")
);
--------------------------------------------------------------
Reset method of FormBeans in Struts
We all know that FormBeans in Struts can have either a 'request' scope or a 'session' scope.
In earlier versions of Struts, I recollect that the reset method of the FormBean was called by the Struts framework whenever the scope is request and not called for session scope. This was because, for 'Request' scope, a pool of FormBean objects were created.
But with new versions of JDK (especially since JDK1.4) object creation is no longer a performance penalty. In fact, short-lived objects are quickly garbage collected because they are allocated in the younger generation of the heap.
Looking at the latest Struts source code (v1.9), I saw that if the scope of the FormBean is Request, then a new FormBean object is created for each request.
Also the reset method is called for both request and session scope FormBeans.
But there is an important difference - if the scope is request, then the constructor of the formbean is also called everytime (for each request), where as for session scope the constructor would be called only once.
So, now what to do? The default reset method does nothing. We only need to override it in the following cases:
1. There are checkboxes and form-bean scope is session: In the reset method we need to reset the checkbox fields, because the browser does not submit a checkbox value if it is clear.
2. Nested beans, arrayLists are used and scope is request: In this case, we need to create a arrayList with the correct size.
In earlier versions of Struts, I recollect that the reset method of the FormBean was called by the Struts framework whenever the scope is request and not called for session scope. This was because, for 'Request' scope, a pool of FormBean objects were created.
But with new versions of JDK (especially since JDK1.4) object creation is no longer a performance penalty. In fact, short-lived objects are quickly garbage collected because they are allocated in the younger generation of the heap.
Looking at the latest Struts source code (v1.9), I saw that if the scope of the FormBean is Request, then a new FormBean object is created for each request.
Also the reset method is called for both request and session scope FormBeans.
But there is an important difference - if the scope is request, then the constructor of the formbean is also called everytime (for each request), where as for session scope the constructor would be called only once.
So, now what to do? The default reset method does nothing. We only need to override it in the following cases:
1. There are checkboxes and form-bean scope is session: In the reset method we need to reset the checkbox fields, because the browser does not submit a checkbox value if it is clear.
2. Nested beans, arrayLists are used and scope is request: In this case, we need to create a arrayList with the correct size.
Wednesday, April 11, 2007
JQuery Javascript library
Came across this cool cool Javascript library that adds that extra jazz to Javascript programming.
Some concepts I liked in this library:
- Separation of presentation markup with behavior (event handling etc.)
- Cool implementation of Chain of Responsibility pattern.
- Good effects such as slow show etc.
Overall, a good library that can be used in web projects.
URL: http://jquery.com/
Some concepts I liked in this library:
- Separation of presentation markup with behavior (event handling etc.)
- Cool implementation of Chain of Responsibility pattern.
- Good effects such as slow show etc.
Overall, a good library that can be used in web projects.
URL: http://jquery.com/
Friday, March 09, 2007
Private network addresses
Can U look at an IP addresses and guess whether it belongs to a private network or is on the internet? The answer is yes.
The Internet Assigned Numbers Authority (IANA) has reserved thefollowing three blocks of the IP address space for private networks:
10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255
Earlier the IP range was divided as ClassA, ClassB , Class C etc. but now we have CIDR (Class less inter-domain routing) which allows us to slice and dice networks the way we want to.
The Internet Assigned Numbers Authority (IANA) has reserved thefollowing three blocks of the IP address space for private networks:
10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255
Earlier the IP range was divided as ClassA, ClassB , Class C etc. but now we have CIDR (Class less inter-domain routing) which allows us to slice and dice networks the way we want to.
Labels:
IP addresses
Tuesday, February 27, 2007
Ruminating on dates, DST and days-between calculations
In one of my programs, I needed to calculate the difference between 2 dates in days. Ironically I could not find any method for the same in the core Java API of Calendar and Date.
So, I decided to write a utility method for the same. But then it struck me that I need to take care of DST and leap seconds. Googling around led me to a interesting journey of Atomic clocks, Quartz clocks, leap secs, etc.
Some cool links to get started with the concepts:
http://www.xmission.com/~goodhill/dates/deltaDates.html
http://www.exit109.com/%7Eghealton/y2k/yrexamples.html
Finally the algorithm I used to calculate the days-between 2 dates was:
1. Get the UTC time of both dates (imp if dates are from different locales)
2. Set the time on both dates as 12 noon. (good practice as it avoids DST and leap sec issues)
3. Calculate the milli-sec difference between the dates.
4. Divide the difference with 24*60*60 and take a Math.abs
So, I decided to write a utility method for the same. But then it struck me that I need to take care of DST and leap seconds. Googling around led me to a interesting journey of Atomic clocks, Quartz clocks, leap secs, etc.
Some cool links to get started with the concepts:
http://www.xmission.com/~goodhill/dates/deltaDates.html
http://www.exit109.com/%7Eghealton/y2k/yrexamples.html
Finally the algorithm I used to calculate the days-between 2 dates was:
1. Get the UTC time of both dates (imp if dates are from different locales)
2. Set the time on both dates as 12 noon. (good practice as it avoids DST and leap sec issues)
3. Calculate the milli-sec difference between the dates.
4. Divide the difference with 24*60*60 and take a Math.abs
Thursday, February 22, 2007
Programming to interfaces
We all know that as a good programming practice we should always program against interfaces and not actual subclasses. That's the reason when libraris are designed, they return an interface to an collection and not the actual implementation class.
Recently the developers in my team were facing a problem regarding ClassCast exceptions using Spring JDBC when they upgraded the commons-collection package. After analysis of the source code, it was revealed that the developer was type-casting the List interface to a solid class, i.e. the LinkedHashMap class.
Spring JDBC decides at runtime what Map implementation should be returned. If the latest version of jakarta-commons is available in the classpath, an implementation of org.apache.commons.collections.map.ListOrderedMap is returned, else java.util.LinkedHashMap is used.
Hence the program would start throwing ClassCastExceptions ...See log below comparing what happens depending on the classpath jars:
-- When the latest version of jakarta-commons is not there in the classpath
16-Feb-2007 14:29:47 DEBUG (CollectionFactory.java:142)
org.springframework.core.CollectionFactory -
Falling back to [java.util.LinkedHashMap] for linked case-insensitive map
-- When the latest version of jakarata commons is present
16-Feb-2007 14:31:36 DEBUG (CollectionFactory.java:138) org.springframework.core.CollectionFactory -
Creating [org.apache.commons.collections.
map.ListOrderedMap/CaseInsensitiveMap]
Moral of the story: Always program to interfaces.
Recently the developers in my team were facing a problem regarding ClassCast exceptions using Spring JDBC when they upgraded the commons-collection package. After analysis of the source code, it was revealed that the developer was type-casting the List interface to a solid class, i.e. the LinkedHashMap class.
Spring JDBC decides at runtime what Map implementation should be returned. If the latest version of jakarta-commons is available in the classpath, an implementation of org.apache.commons.collections.map.ListOrderedMap is returned, else java.util.LinkedHashMap is used.
Hence the program would start throwing ClassCastExceptions ...See log below comparing what happens depending on the classpath jars:
-- When the latest version of jakarta-commons is not there in the classpath
16-Feb-2007 14:29:47 DEBUG (CollectionFactory.java:142)
org.springframework.core.CollectionFactory -
Falling back to [java.util.LinkedHashMap] for linked case-insensitive map
-- When the latest version of jakarata commons is present
16-Feb-2007 14:31:36 DEBUG (CollectionFactory.java:138) org.springframework.core.CollectionFactory -
Creating [org.apache.commons.collections.
map.ListOrderedMap/CaseInsensitiveMap]
Moral of the story: Always program to interfaces.
Starting a java daemon on Solaris
We were using Quartz as a scheduler to run our cron-like java programs on Solaris. Quartz gives us much more flexibility than the cron-tab, as we can add listeners and plug-ins.
Normally, when we exit a shell, all the programs that were started in the shell are terminated.
To avoid this, we made use of the 'nohup' command that keeps running the program even if the shell is closed. nohup = no-hang-up.
Also important thing to remember is that if the Std. input is kept open, then the shell does not exit. In the Java program, the main method automatically opens the Std input stream. Hence we need to close it. Here is the complete syntax.
nohup java com.domain.main_class <&- &
The ampersand at the end, starts the program in the background. nohup creates a file called nohup.log that contains the output to the standard stream.
Normally, when we exit a shell, all the programs that were started in the shell are terminated.
To avoid this, we made use of the 'nohup' command that keeps running the program even if the shell is closed. nohup = no-hang-up.
Also important thing to remember is that if the Std. input is kept open, then the shell does not exit. In the Java program, the main method automatically opens the Std input stream. Hence we need to close it. Here is the complete syntax.
nohup java com.domain.main_class <&- &
The ampersand at the end, starts the program in the background. nohup creates a file called nohup.log that contains the output to the standard stream.
Subscribe to:
Posts (Atom)