tag:blogger.com,1999:blog-54284013974735778812024-03-05T13:20:06.827+05:30Blog by Rakesh.AA techie who love to read, code and share ...Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.comBlogger25125tag:blogger.com,1999:blog-5428401397473577881.post-55506623559796721022012-11-15T13:18:00.000+05:302012-11-15T16:43:57.561+05:30Creating java.awt.Color instance using hex color codes<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
Most of you are familiar with <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Color.html" target="_blank">java.awt.Color</a> constructor which takes the RGB values to create its instance, but <b class="greenText">java.awt.Color</b> class also allows one to create its instances using hex color codes through very less known static method ‘<a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Color.html#decode(java.lang.String)" target="_blank">Color.decode(String)</a>’.<br />
<br />
<pre> </pre>
<pre>Color obj = Color.decode("#006699");</pre>
<pre> </pre>
<br />
Very simple isn’t it.</div>
</div>
Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com0tag:blogger.com,1999:blog-5428401397473577881.post-86242126822547662622012-06-12T15:40:00.000+05:302012-06-12T19:28:29.319+05:30Changing Style tag content using JQuery & IE8<div dir="ltr" style="text-align: left;" trbidi="on">
Generally you might not need/want to do this, in fact you’ll rarely change elements of ‘head’ tag using Java script. But this is for those who are left with no other choice. It is really simple, <a href="http://api.jquery.com/" target="_blank">JQuery</a> provides a methods ‘<a href="http://api.jquery.com/text/" target="_blank">text()</a> / <a href="http://api.jquery.com/html/" target="_blank">html()</a>’ which will allow you to change content of any DOM element. To change the ‘Style’ tag content we can use ‘<a href="http://api.jquery.com/text/" target="_blank">text()</a>’ method, sample code is provided below.<br />
<br />
<pre><html></pre>
<pre> <head></pre>
<pre> <style id="myStyles" type="text/css"></pre>
<pre> .header {</pre>
<pre> color: blue;</pre>
<pre> }</pre>
<pre> </style></pre>
<pre> <script type="text/javascript"></pre>
<pre> $("#myButton").click(function(e) {</pre>
<pre> $("#myStyles").text(".header { color: green }");</pre>
<pre> });</pre>
<pre> </script></pre>
<pre> </head></pre>
<pre> <body></pre>
<pre> <h2 class="header">My Page Heading</h2></pre>
<pre> <input type="button" id="myButton" value="Click Me"/></pre>
<pre> </body></pre>
<pre> </html></pre>
<pre> </pre>
Ideally you’d expect this code to work, but this code will not work in IE8; for some reason it seems you can not use ‘text()’ method to change ‘style’ tag contents in IE8. So work around for it - remove the ‘style’ completely and add it again with new content as shown below<br />
<br />
<br />
<pre><html>
<head>
<style id="myStyles" type="text/css">
.header { color: blue; }
</style>
<script type="text/javascript">
$("#myButton").click(function(e) {
// $("#myStyles").text(".header { color: green }");
var headerEl = $("#myStyles").parent();
$("#myStyles").remove();
$(headerEl).append("<style id='myStyles' type='text/css'> .header {color: green;}</style>");
});
</script>
</head>
<body>
<h2 class="header">My Page Heading</h2>
<input type="button" id="myButton" value="Click Me"/>
</body>
</html></pre>
<pre></pre>
<br />
To test follow this link: <a href="http://jsfiddle.net/tM96J/1/" title="http://jsfiddle.net/tM96J/1/" target="_blank">http://jsfiddle.net/tM96J/1/</a></div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com0tag:blogger.com,1999:blog-5428401397473577881.post-84966426383600341692011-11-17T16:19:00.001+05:302011-11-17T16:35:34.658+05:30File Copy Using Java NIO<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
I wanted to post this small piece of code for those who are looking for it. Copying file contents using Streams is old way of doing, Java New IO is the way to go; using <strong class="greenText">Java NIO</strong> is better in terms of performance.<br />
Following is the code to do file copy using Java NIO.<br />
<br />
<pre>public static void copyFile(File src, File dest) throws IOException {
if (!src.exists()) {
// either return quietly OR throw an exception
return;
}
if (!dest.exists()) {
dest.createNewFile();
}
FileChannel source = new FileInputStream(src).getChannel();
try {
FileChannel destination = new FileOutputStream(dest).getChannel();
try {
source.transferTo(0, source.size(), destination);
// destination.transferFrom(source, 0, source.size());
} finally {
if (destination != null) {
destination.close();
}
}
} finally {
if (source != null) {
source.close();
}
}
} </pre>
<br />
By using NIO classes, we don’t need to create those byte buffers, loop through and copy in chunks, etc. NIO code is clean and simple, below line of code is the one responsible for copying file content.<br />
<br />
<pre>source.transferTo(0, source.size(), destination); </pre>
<br />
Quite simple isn’t it. It gets even simpler in Java7, all we need is one line of code as given below<br />
<br />
<pre>Files.copy(src, dest);
// OR
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);</pre>
<br />
In the above line of code ‘src’ and ‘dest’ are not instances of java.io.File class, but they are of type "<strong class="greenText">java.nio.file.Path</strong>". You can get Path object instance either by calling "<strong>toPath()</strong>" method on "java.iolFile" class object, OR creating one by calling the "getPath()" method on "java.nio.file.FileSystem" object.<br />
<br />
<pre>FileSystems.getDefault().getPath("logs", "access.log");</pre>
<br />
The above line of code will give you an instance of ‘java.nio.file.Path’, which points to a file ‘access.log’ available in ‘logs’ directory, path is relative to current directory ["./logs/access.log"]. You can find more information @ <a href="http://today.java.net/pub/a/today/2008/07/03/jsr-203-new-file-apis.html">http://today.java.net/pub/a/today/2008/07/03/jsr-203-new-file-apis.html</a></div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com0tag:blogger.com,1999:blog-5428401397473577881.post-86049379846976354502011-07-18T10:00:00.002+05:302011-12-22T16:57:48.322+05:30JVM Heap Fragmentation<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
Recently I read about this topic and wanted to share it, I couldn’t recollect the source where I read it first to give a reference link, so just writing it here. <br />
When JVM requires memory, Operating System always allocates continuous memory blocks. When objects get created and destroyed frequently, JVM allocates memory where ever available. Think of a situation where 1000 [each of size 5bytes] objects got allocated in some ‘x’ time span and only 500 of them are killed/de-allocated. Memory occupied by these 500 objects might not be continuous, the de-allocated memory might me scattered across heap memory. Each de-allocated block is of size 5bytes – so, you might be having free memory block of size 5bytes across heap, if JVM wants to allocate a 10byte memory block it cannot use these 5bytes blocks, it has to find a continuous 10byte free space in heap and allocate it. This situation is called as "<b class="greenText">Heap Fragmentation</b>" [same as ‘<b>Disk Fragmentation</b>’], where the heap memory is fragmented. This results JVM not to release the continuous memory to Operating System.<br />
Well, that is about the problem – how can we avoid it, here it is.<br />
<ul>
<li>Identify places and avoid them where the objects are unnecessarily getting created and destroyed frequently. </li>
<li>Keep the maximum Heap memory Size setting to as close as possible to the maximum memory required by your JVM. </li>
<li>You can compact the Heap memory, using the JVM option "-compactGc", but remember that this option might result performance reduction.</li>
</ul>
That is all for now :)</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com0tag:blogger.com,1999:blog-5428401397473577881.post-81560792305728860912011-07-15T14:26:00.000+05:302011-12-22T16:58:22.199+05:30Ant Script to make Executable JAR<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
Recently I observed search patterns about <b class="greenText">Ant script to make executable JAR</b> files, many end up on wrong pages of my blog. This blog post is for those who are searching for it. Its fairly easy and simple to use Ant Script, to make an executable JAR file, see the script below.<br />
<pre><jar destfile="_dist/my-executable-jar.jar"><br />
<fileset dir="_bin" /><br />
…
<manifest>
<attribute name="Main-Class" value="com.mypackage.ClassWithMain" />
</manifest><br />
</jar></pre>
As you can see, we usee the ‘jar’ ant task to create a JAR file, we want to create the JAR file with the name ‘my-executable-jar.jar’ – which is given as ‘destfile’ attribute value of ‘jar’ task and we wanted to include all the compiled classes which are available at ‘_bin’ directory – which is provided using ‘fileset’ tag in the second line of the script.<br />
Then comes the important part – the ‘manifest’ tag. If you want to make a JAR file executable – you’ve to add a ‘Main-Class’ attribute to the MANIFEST file of your JAR file. As we wanted to specify an attribute of MANIFEST file – that is why the ‘manifest’ tag. In this tag we’ve a ‘attribute’ tag with ‘name’ and ‘value’ tag attributes. ‘name’ attribute says which attribute of the MANIFEST file you want to set and with which value, value is provided using ‘value’ attribute. In the above sample script we mentioned ‘Main-Class’ as attribute name and the value for this attribute as ‘com.mypackage.ClassWithMain’ – by this we are saying that the class which need to be used when we execute the JAR file is ‘com.mypackage.ClassWithMain’ [which means this class has the main() method and is the starting point for execution]. <br />
That is all – Happy Scripting :)</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com0tag:blogger.com,1999:blog-5428401397473577881.post-38134501809118403742011-07-13T14:36:00.001+05:302011-12-22T16:58:44.481+05:30JAR Dependency and Ant Jar Task [Merging Archives]<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
Ever had a situation where you are using Ant to build a JAR file and this JAR uses classes from other JAR OR needs few other JAR files to be in class path. Placing dependent JARs in class path manually is one way of doing it, but what if you want to generate/deliver/use only one JAR [may be executable] which includes all the dependent JARs in it. ‘<b class="greenText">zipfileset</b>’ attribute of the ‘<b class="greenText">jar</b>’ ANT task is the one to use.<br />
Say, you are trying to generate a JAR file with name ‘<b>my-application.jar</b>’, which needs/depends on another JAR with the name ‘<b>some-dependency.jar</b>’. Assuming all the compiled classes are available under ‘_bin’ directory, the dependent JAR is available under ‘lib’ directory and you want to place the generated JAR under ‘_dist’ directory, ANT script might look as given below<br />
<pre><jar destfile="_dist/my-application.jar">
<fileset dir="_bin" />
<zipfileset src="lib/some-dependency.jar" includes="**/*.class" excludes="META-INF/**/*" />
</jar></pre>
That is all you need, only extra line you’ve is ‘<b>zipfileset</b>’ attribute. This attribute takes the JAR file [some-dependency.jar] to be added to the target JAR. You can mention what files from this JAR need to included OR excluded using the ‘includes’ and ‘excludes’ attributes. The above code says to include all ‘.class’ files and exclude all files under ‘META-INF’ directory.<br />
What if you have more than one JAR to include, say all the JAR files under ‘lib’ directory, one way is to add multiple ‘zipfileset’ tag for each of those JAR files, if you’ve a big list of JARs under your ‘lib’ directory then, you can use the ANT script given below<br />
<pre><unjar dest="_unjar" overwrite="false">
<fileset dir="lib" includes="**/*.jar"/>
</unjar><br />
<jar destfile="_dist/my-application.jar">
<fileset dir="_bin" />
<fileset dir="_unjar" includes="**/*.class"/>
</jar></pre>
What we did here is, we un-jared all the JAR files under ‘lib’ directory to a temporary directory ‘_unjar’, and include all the ‘.class’ files using the ‘fileset’ tag, simple isn’t it!</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com0tag:blogger.com,1999:blog-5428401397473577881.post-24389563294064639022011-03-29T15:01:00.000+05:302011-12-22T16:59:22.031+05:30Java Communications API – Configuration How To<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
Java Communication API is an extension from Sun to program for Serial/Parallel ports. Sun’s implementation of this specification can be found at "<a href="http://java.sun.com/products/javacomm" title="http://java.sun.com/products/javacomm">http://java.sun.com/products/javacomm</a>", there is also a third party Open Source implementation available at "<a href="http://rxtx.qbang.org/wiki/index.php/Main_Page" title="http://rxtx.qbang.org/wiki/index.php/Main_Page">http://rxtx.qbang.org/wiki/index.php/Main_Page</a>". Java is platform Independent, but you need some platform specific implementation to access Serial/Parallel ports, and that is why you need to do some extra work to use Java Communication API.<br />
First download the API binaries from "<a href="http://rxtx.qbang.org/wiki/index.php/Download" title="http://rxtx.qbang.org/wiki/index.php/Download">http://rxtx.qbang.org/wiki/index.php/Download</a>" page. Extract it and follow the steps given below for Windows platform.<br />
If you are just trying execute programs already written using just JRE, then <br />
<ul>
<li>Copy <span class="greenText">rxtxParallel.dll</span> to <span class="greenText">JRE_HOME\bin\</span> </li>
<li>Copy <span class="greenText">rxtxSerial.dll</span> to <span class="greenText">JRE_HOME\bin\</span> </li>
<li>Copy <span class="greenText">RXTXcomm.jar</span> to <span class="greenText">JRE_HOME\lib\ext\</span> </li>
</ul>
If you are writing you own applications/programs, compiling and executing them, then<br />
<ul>
<li>Copy <span class="greenText">rxtxParallel.dll</span> to <span class="greenText">JDK_HOME\jre\bin\</span> </li>
<li>Copy <span class="greenText">rxtxSerial.dll</span> to <span class="greenText">JDK_HOME\jre\bin\</span> </li>
<li>Copy <span class="greenText">RXTXcomm.jar</span> to <span class="greenText">JDK_HOME\jre\lib\ext\</span> </li>
</ul>
You can skip the last step of copying "RXTXcomm.jar" to "..\jre\lib\ext" directory and adding it to your CLASSPATH yourself and bundling it with your application itself.<br />
That is it, you can find more information about RXTX implementation at "<a href="http://rxtx.qbang.org/wiki/index.php/Main_Page" title="http://rxtx.qbang.org/wiki/index.php/Main_Page">http://rxtx.qbang.org/wiki/index.php/Main_Page</a>" and about installation for different platforms like Linux, Mac at "<a href="http://rxtx.qbang.org/wiki/index.php/Installation" title="http://rxtx.qbang.org/wiki/index.php/Installation">http://rxtx.qbang.org/wiki/index.php/Installation</a>".<br />
Simple example about using Java Communications API will follow soon.</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com0tag:blogger.com,1999:blog-5428401397473577881.post-48511481788035761162011-01-17T22:29:00.000+05:302011-12-22T16:59:48.043+05:30Calculating Domain URL in Java Web Applications<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
When you are developing web applications, its obvious that you’ll write code to generate paths for resources like images, stylesheets, scripts, etc. You can do this by simply using relative paths. In your JSP application, you can do this using ‘getContextPath()’ method of ‘HttpServletRequest’ object. <br />
Lets see what this method gives you. It returns a String value, the returned string will always have a leading ‘/’ character and will never have a trailing ‘/’. This method returns an empty string when you deploy your application as ROOT context and returns the subdomain context when deployed as subdomain. <br />
For example, if you name your WAR file as ‘myExample.war’ and deploy it in TOMCAT [by placing the WAR file in ‘webapps’ directory]. The ‘getContextPath()’ method will return ‘/myExample’.<br />
In your JSP page, if you’ve a image tag pointing to an image resource and you want it to work even when deployed as subdomain you can do that by using this ‘getContextPath()’ method as used below.<br />
<pre><img src=”<%=request.getContextPath()%>/images/sample.jpeg” alt=”Sample Image” /></pre>
There will be situations where you want to use complete path instead of relative path, and you still want the code to work in all the cases when deployed as ROOT and subdomain in your development environment and even in production sever without any changes. The following code will do that exactly for you. It’ll calculate the complete URL dynamically using the servlet API.<br />
<pre>public static String getBaseUrl(HttpServletRequest request) {
StringBuilder sb = new StringBuilder(27);
sb.append("http://").append(request.getServerName());<br />
<blockquote>
int port = request.getServerPort();
</blockquote>
if (port != 80) {
sb.append(':').append(port);
} <br />
sb.append(request.getContextPath()).append('/');
return sb.toString();
}</pre>
Its really simple code, the above method takes the request object [HttpServletRequest instance] as parameter and uses it to calculate the URL. First we’ll append the protocol to the URL string then use the ‘getServerName()’ method, to get the server host name. For example on production server you might get this value as ‘www.xyz.com’ and in development environment you might get this value as ‘localhost’. After this we’ll use ‘getServerPort()’ method to get the port number to which the request was sent. We’ll compare this port number and see whether its not the default port ‘80’. If it is not then append the port number to the URL. Then call the ‘getContextPath()’ method to get the subdomain value. Finally append a trailing ‘/’ to the URL before returning the calculated URL.<br />
That’s all for now!</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com0tag:blogger.com,1999:blog-5428401397473577881.post-49176105377145389492010-10-27T20:21:00.002+05:302011-12-22T17:00:06.107+05:30Using Multiple Struts Config Files<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
If you are working on a big web application which uses Struts and has huge number of action classes in it, action mappings for these classes will result a huge “struts-config.xml'” file. You might always find it difficult to change the struts config file that big. And it might be really helpful if you split the action mappings and put them in multiple config files, splitting can be based on any criteria – based on functionality or authorization levels, etc. Lets see how we can do this and use multiple ‘struts-config.xml’ files.<br />
Lets say that you’ve three struts config files namely “<b>struts-config-1.xml</b>”, “<b>struts-config-2.xml</b>”, and “<b>struts-config-3.xml</b>”. All you need to do is specify these configuration files as initialization parameter ‘config’ for “ActionServlet” in your ‘<b>web.xml</b>’ file. Make sure that all your config files should be separated with ‘comma’, see the example given below.<br />
<pre><servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<b class="greenText"><init-param>
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config-1.xml,/WEB-INF/struts-config-2.xml,/WEB-INF/struts-config-3.xml
</param-value>
</init-param>
</b> …<br />
</servlet></pre>
That’s it, quite easy isn’t it!</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com0tag:blogger.com,1999:blog-5428401397473577881.post-22704376126236920562010-09-28T14:30:00.000+05:302011-12-22T17:00:28.544+05:30Tooltip Component Using Java Script & CSS<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
A simple, small Java Script Component, which you can use to have custom Tooltips on your web page. Well why wait, let get right on to it. First lets see the styles used by the Tooltip popup box.<br />
<pre>.toolTipDef, .toolTip {
position: absolute;
background-color: #ccc;
border: 1px solid #000;
padding: 3px;
}
.toolTipDef { display: none; }
.toolTip { display: block; }
</pre>
All together we’ve to CSS classes, one ‘toolTipDef’ and ‘toolTip’. ‘toolTipDef’ is used when the tooltip need to be hidden, and when user mouse over the text, we’ll use ‘toolTip’ class to make the tooltip popup visible. These styles set standard attributes like background color for the tooltip popup, its border and text padding inside tooltip popup. ‘toolTipDef’ set the ‘display’ property to ‘none’ so that by default the popup is hidden and ‘toolTip’ sets the ‘display’ property to ‘block’ so that when used the tooltip popup gets displayed.<br />
<div class="fullpost">
To display tooltip text, we need a container to be used as popup with the given text for this we need to add the below given empty ‘div’ tag to the HTML page.<br />
<pre><div id="toolTip" class="toolTipDef"></div></pre>
If you observe, the default CSS style class used for this ‘div’ is ‘toolTipDef’ which makes this ‘div’ hidden by default. We need to give some value for the ‘id’ attribute of this container div, so that we can access it using the java script and change its content and CSS styles. Here its given as ‘toolTip’, this value will be used while initializing Tooltip Java Script Component. <br />
The last and core part of this component is the Java Script, lets see what we’ve here.<br />
<pre>(function() {
Tooltip = {
init: function(elId) {
if (!elId)
return;
var el = document.getElementById(elId);
if(!el)
return; <br />
this.el = el;
this.isIE = document.all? true : false;
}, // End of init() <br />
showTip: function(anchor, text) {
this.el.innerHTML = text;
this.el.className = "toolTip"; <br />
var pos = this.getElPosition(anchor); <br />
this.el.style['left'] = pos.x + "px";
this.el.style['top'] = (pos.y + anchor.offsetHeight - 1) + "px";
}, // End of showTip() <br />
hideTip: function (anchor) {
this.el.className = "toolTipDef";
}, // End of hideTip() <br />
getElPosition: function(anchor) {
for(var zx=zy=0; anchor!=null; zx+=anchor.offsetLeft,zy+=anchor.offsetTop,anchor=anchor.offsetParent);
return {x:zx,y:zy}
} // End of getElPosition()
} // End of Tooltip
})(); </pre>
This ‘Tooltip’ Java Script class has 4 methods init, ‘<b>init()</b>’, ‘<b>showTip()</b>’, ‘<b>hideTip()</b>’, and ‘<b>getElPoistion()</b>’. The ‘init()’ method initializes the component, it takes the ‘id’ attribute value of the tooltip popup container ‘div’ element. In this example we’ve given it as ‘toolTip’ as mentioned in the above HTML code. This ‘init()’ method checks the given value, if its not provided returns immediately, otherwise it tries to get the DOM reference of this element. If it fails to get the DOM reference, it returns with out giving any error, otherwise keeps this reference in ‘el’ object of this component.<br />
The ‘getElPosition()’ method is used to get the position of the element on the screen for which the tooltip is being displayed, it takes the element as parameter and uses ‘<b>offsetLeft</b>’, ‘<b>offsetTop</b>’, and ‘<b>offsetParent</b>’ attribute values to give the top, left positions of the given element.<br />
The ‘<b>showTip()</b>’ method is used to display the tool tip popup when user, mouse over an element. This method takes the element and the tool tip text as parameters. It sets the ‘innerHTML’ of the popup container ‘div’ with the given text, and sets the CSS class name of the container ‘div’ to ‘toolTip’ which makes it visible. Then it tries to get the position of the given element by calling ‘getElPosition()’ method, and changes the ‘top’ and ‘left’ CSS style attributes with the values returned by the ‘getElPosition()’ method.<br />
The last method ‘hideTip()’, is used to hide the tool tip popup when user, mouse out from an element. This method takes the element for which the tooltip was displayed. This method simply changes the CSS class name of the given element to ‘toolTipDef’ which hides the tool tip container ‘div’. <br />
The last step is to initialize this component on window ‘onload’ event. You can use the sample code given below OR have your own way of doing it.<br />
<pre>window.onload = function () { Tooltip.init('toolTip'); };</pre>
Only thing you need to make sure is, the parameter to the ‘init()’ method, it should be the ‘id’ attribute value of the popup container ‘div’.<br />
To show tool tip for a HTML element you call the ‘showTip()’ and ‘hideTip()’ method on ‘mouseover’ and ‘mouseout’ events. Sample code on how to do it is given below<br />
<pre><h2 onmouseover="Tooltip.showTip(this, 'This is a Sample Tooltip');"
onmouseout="Tooltip.hideTip(this);">Move your mouse on to me!!!</h2></pre>
That is all you need to do, Simple isn’t it!</div>
</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com0tag:blogger.com,1999:blog-5428401397473577881.post-86686608865863016402010-09-13T11:32:00.000+05:302011-12-22T17:01:32.535+05:30Ant Script To Sign A JAR File<div dir="ltr" style="text-align: left;" trbidi="on">
To sign a JAR file you need a ‘keystore” first. You can create a sample keystore using the following simple command.<br />
<pre>keytool -genkey -keystore <filename.store> -alias <aliasname></pre>
After creating the keystore, you can add the following Ant tag to sign the JAR file using it.<br />
<pre><signjar jar="<JAR file to be signed>" alias="<Keystore Alias Name>"
keystore="<Keystorefile.store>" storepass="<Keystore password>"/></pre>
Attributes used are<br />
<ul>
<li>jar – The JAR file path which needs to be signed.</li>
<li>alias – Keystore alias name, given in the ‘keytool’ command to create the keystore.</li>
<li>keystore – Path to the keystore file, which was created using the ‘keytool’ command.</li>
<li>storepass – Keystore password used while creating the keystore using ‘keytool’ command.</li>
</ul>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com2tag:blogger.com,1999:blog-5428401397473577881.post-68927961034384303972010-09-06T11:35:00.000+05:302011-12-22T17:01:53.586+05:30Ajax Form Submit GET/POST Methods<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
This example explains GET and POST methods of form submit using AJAX. Only code is posted for now, will try to update it later some time. Complete example can be downloaded using the link at the end of the post.<br />
<div class="fullpost">
<pre>package com.rakesh.ex.dto; <br />
public class EmployeeDTO {
private String empId;
private String name, email;
private String designation, department; <br />
public EmployeeDTO(String empId) {
this.empId = empId;
} <br />
public String getEmpId() {
return empId;
} <br />
public void setEmpId(String empId) {
this.empId = empId;
} <br />
public String getName() {
return name;
} <br />
public void setName(String name) {
this.name = name;
} <br />
public String getEmail() {
return email;
} <br />
public void setEmail(String email) {
this.email = email;
} <br />
public String getDesignation() {
return designation;
} <br />
public void setDesignation(String designation) {
this.designation = designation;
} <br />
public String getDepartment() {
return department;
} <br />
public void setDepartment(String department) {
this.department = department;
}
}</pre>
<br />
<pre>package com.rakesh.ex.dao; <br />
import java.util.ArrayList;
import java.util.List; <br />
import com.rakesh.ex.dto.EmployeeDTO;<br />
public class EmployeeDAO { <br />
/**
* sample method to get list of employees. This method creates sample list
* of employees data.
*/
public List<EmployeeDTO> getEmployees() {
List<EmployeeDTO> empList = new ArrayList<EmployeeDTO>();
for (int i=1; i<=10; i++)
empList.add(createSampleData(i, i%2));
return empList;
} <br />
private static EmployeeDTO createSampleData(int i, int j) {
EmployeeDTO emp = new EmployeeDTO(String.valueOf(1000 + i));
emp.setName("Employee" + i);
emp.setEmail(emp.getName() + "@company.com");
emp.setDesignation("Designation" + i);
emp.setDepartment("Department" + j);
return emp;
} <br />
/**
* create dummy employee information. You can replace this method to query the
* database for actual employee information in your implementation.
*/
public EmployeeDTO getEmployeeInfo(String empCode) {
EmployeeDTO emp = new EmployeeDTO(empCode);
emp.setName("Employee-" + empCode);
emp.setEmail(emp.getName() + "@company.com");
emp.setDesignation("Designation" + empCode);
emp.setDepartment("Department" + empCode);
return emp;
}
}</pre>
<br />
<pre>package com.rakesh.ex.web; <br />
import java.io.IOException; <br />
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; <br />
import com.rakesh.ex.dao.EmployeeDAO;
import com.rakesh.ex.dto.EmployeeDTO; <br />
<br />
public class AjaxExample extends HttpServlet {
private static final long serialVersionUID = -6377586508833712244L; <br />
private EmployeeDAO empDAO; <br />
@Override
public void destroy() {
super.destroy();
this.empDAO = null;
} <br />
@Override
public void init() throws ServletException {
super.init();
this.empDAO = new EmployeeDAO();
} <br />
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
} <br />
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final String empCode = req.getParameter("empCode");
// get employee info
EmployeeDTO empInfo = empDAO.getEmployeeInfo(empCode);
// set employee list in to request
req.setAttribute("emp_info", empInfo); <br />
// forward to jsp which generates table out of employee list
req.getRequestDispatcher("emp_info.jsp").forward(req, resp);
return;
} <br />
}</pre>
<br />
<pre><%@page import="java.util.List" %>
<%@page import="com.rakesh.ex.dto.EmployeeDTO" %>
<%
EmployeeDTO empInfo = (EmployeeDTO) request.getAttribute("emp_info");
if (empInfo == null) {
%>
<p>Could not find employee information!</p>
<% } else { %>
<div class="data">Employee ID: <%=empInfo.getEmpId()%></div>
<div class="data">Name : <%=empInfo.getName()%></div>
<div class="data">Email : <%=empInfo.getEmail()%></div>
<div class="data">Designation: <%=empInfo.getDesignation()%></div>
<div class="data">Department : <%=empInfo.getDepartment()%></div>
<% } %></pre>
<br />
<pre>(function() {
AjaxEx = {
init: function(url, elId) {
if (!url || !elId) {
alert("Invalid input!");
return;
}
this.url = url;
var el = document.getElementById(elId);
if (!el) {
alert("Container Element, to place Ajax response doesn't exists!");
return;
}
this.el = el;
this.sampleHtml = "<p>This will be replaced with AJAX response!</p>";
// create xml http request object for AJAX requests
this.xmlHttp = this.initXmlHttp();
}, // End of init()
initXmlHttp : function () {
if (window.XMLHttpRequest)
// Firefox, Opera, IE7, etc.
return new XMLHttpRequest();
if (window.ActiveXObject)
// IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}, // End of initXmlHttp()
resetContent : function () {
this.el.innerHTML = this.sampleHtml;
}, // End of resetContent()
sendAjaxRequest : function () {
// initialize XML Http object if not available
if (!this.xmlHttp)
this.xmlHttp = this.initXmlHttp();
if (this.xmlHttp) {
var ajaxObj = this;
this.xmlHttp.onreadystatechange = function() {
if (ajaxObj.xmlHttp.readyState==4 && ajaxObj.xmlHttp.status==200) {
// 4 = "loaded", 200 = "OK"
ajaxObj.el.innerHTML = ajaxObj.xmlHttp.responseText;
}
};
var selBox = document.getElementById("empCode");
// prepare parameters
var empCode = selBox.options[selBox.selectedIndex].value;
if (empCode == "") {
alert("Please select employee code to get employee information!");
return;
}
var params = "empCode=" + empCode;
// for multiple parameters separate them by '&' as given below
// var params = "empCode=E1001&dept=TestDept"
this.makePOSTRequest(params);
// this.makeGETRequest(params);
} else
alert("Your browser does not support AJAX.");
}, // End of sendAjaxRequest() <br />
makePOSTRequest : function (params) {
this.xmlHttp.open("POST", this.url, true);
//Send the proper header information along with the request
this.xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
this.xmlHttp.setRequestHeader("Content-length", params.length);
this.xmlHttp.setRequestHeader("Connection", "close");
this.xmlHttp.send(params);
}, // End of makePOSTRequest() <br />
makeGETRequest : function (params) {
this.xmlHttp.open("GET", this.url + "?" + params, true);
this.xmlHttp.send(null);
} // End of makeGETRequest() <br />
} // End of AjaxEx
})();</pre>
<br />
<pre><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd%22">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"</a>>
<html xmlns="<a href="http://www.w3.org/1999/xhtml%22">http://www.w3.org/1999/xhtml"</a> xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <br />
<title>Simple Ajax Example</title> <br />
<script type="text/javascript" src="js/ajax-example.js"></script>
<style type="text/css">
body {
width: 800px;
height: 600px;
}
.top_block {
text-align: center;
}
.top_block input {
font-weight: bold;
}
.ajax_content {
border: 2px solid #000;
padding: 2em;
}
.data { margin-bottom: 0.5em; }
</style>
</head>
<body>
<div class="top_block">
Select Employee Code: <select id="empCode" name="empCode">
<option value="">Select</option>
<option value="E1001">E1001</option>
<option value="E1002">E1002</option>
<option value="E1003">E1003</option>
<option value="E1004">E1004</option>
<option value="E1005">E1005</option>
<option value="E1006">E1006</option>
<option value="E1007">E1007</option>
</select>
<input type="button" onclick="javascript:AjaxEx.sendAjaxRequest();" value="Get Data"/>&nbsp;&nbsp;
<input type="button" onclick="javascript:AjaxEx.resetContent();" value="Reset Content"/>
</div>
<div id="ajax_content" class="ajax_content">
<p>This will be replaced with AJAX response!</p>
</div>
<script type="text/javascript">
<!--
// view source of this page after it loads in browser
// and check this variables value
var url = "<%=request.getContextPath()%>/ajaxServlet";
AjaxEx.init(url, "ajax_content");
// -->
</script>
</body>
</html></pre>
<br />
Resources:<br />
<a href="http://sattvah.com/im-blog/examples/ajax-form-submit-ex.rar">Download the Source code</a>.</div>
</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com10tag:blogger.com,1999:blog-5428401397473577881.post-90562031930903919632010-08-15T16:28:00.000+05:302011-12-22T17:02:21.042+05:30File Uploading Using Servlets, JSP and Commons File Upload API<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
I’ve seen many developers who are at the early stages of their career have problems with this topic and seen many posts in forums asking how to do it – File Uploading using Servlets, JSP!; this article will provide an example using Commons File Upload API. I tried to make the example as simple as possible, hope it helps those early birds. Example uses JSP to provide the pages with form where user can select the file to upload with other form fields, Commons File Upload API to process submitted form and read form fields separately, and Servlets as middle layer between JSP and Commons File Upload API, example also has ANT build script to generate the distributables. All the code can be downloaded, links to these resources are provided at the end of this post, lets get on with the example then.<br />
<div class="fullpost">
The flow in this example is as depicted in the following picture.<br />
<div style="text-align: center;">
<img alt="Files list" border="0" height="336" src="http://www.sattvah.com/im-blog/examples/commons-file-upload-ex/flow.gif" title="Files list" width="576" /></div>
As you can see, user selects the file to upload and provides normal form data as well, using "index.jsp" and submits the form to "FileUploadServlet" servlet. This servlet passes the request object to one of FormUtils class methods, and this method parses the request and creates "TestForm" class object out of the request object. This "TestForm" class object will be passed to "form-data.jsp" which in turn displays the provided data.<br />
First we’ll go through the JSP files, we’ve two JSP files - "index.jsp", and "form-data.jsp" in this example, one to show the form with fields which user will submit, and another to show the submitted form data. Lets see what "index.jsp" has.<br />
<pre><html xmlns="<a href="http://www.w3.org/1999/xhtml%22">http://www.w3.org/1999/xhtml"</a> xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Commons File Upload Example</title>
<style type="text/css">
body { font: 13px arial,helvetica,clean,sans-serif; text-align: center; }
.container { text-align: left; width: 25em; border: 1px solid #000; padding: 0.5em; }
.form-field { margin-bottom: 0.5em; }
.form-field input { border: 1px solid #aaa; padding: 0.2em; }
.btn-container { text-align: right; }
</style>
</head>
<body>
<div class="container">
<b class="greenText"><form action="uploadServlet" method="post" enctype="multipart/form-data">
</b> <div class="form-field">
<label>Your Name: </label>
<input type="text" name="name" size="20" />
</div>
<div class="form-field">
<label>Your File: </label>
<b class="greenText"><input type="file" name="document" size="25" />
</b> </div>
<div class="btn-container">
<input type="submit" value="Submit"/>
</div>
</form>
</div>
</body>
</html></pre>
Above code has nothing special in it, just plain HTML, you might want to note two parts which are important here, one the "form" tag which has an extra attribute "enctype" and the other "input" tag with 'type' attribute as 'file'. When you want to submit a file to the server you need to have the 'enctype' attribute set to 'multipart/form-data'. And to have a form field where user can select a file and upload, you need to use the input tag with its type as 'file'. If you observe this page has one 'form' tag with 'action' attribute set to 'uploadServlet', which indicates that when user submits this form by clicking on the submit button, it'll submit the form data to a Servlet with its mapping URL ‘uploadServlet’. This form tag has two form fields – one text field with 'name' attribute as 'name' and the other a 'file' input tag with name attribute as 'document'. Now lets see the second JSP - 'form-data.jsp'.<br />
<pre><%@page import="com.rakesh.fileupload.form.TestForm"%>
<html xmlns="<a href="http://www.w3.org/1999/xhtml%22">http://www.w3.org/1999/xhtml"</a> xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Commons File Upload Example</title>
</head>
<body>
<%
String error = (String)request.getAttribute("ERROR");
if (error != null) {
%>
<h3><%= error %></h3>
<%
} else {
TestForm form = (TestForm)request.getAttribute("DATA");
%>
<h2>Data Submitted is:</h2>
<p>
Your Name: <%=form.getName()%><br/>
File Name: <%= form.getDocument().getName() %><br/>
File Size: <%= form.getDocument().getSize() %><br/>
File Type: <%= form.getDocument().getContentType() %><br/>
<% } %>
</p>
</body>
</html></pre>
Even this JSP looks very simple except, its not simple HTML code. This page is supposed to show the data submitted by the user through 'index.jsp'. After the 'body' tag we'll first check for the request attribute 'ERROR' – when user submits the form, we'll check the submitted data and if we find any problem with the submitted data, we'll set this 'ERROR' request attribute and forward to this page. If this request attribute is set that means we have some problem with the submitted data, this error message has to be displayed to the user. We'll compare this request attribute with ‘null’ if its not null, we’ll display the error message. If this request attribute is ‘null’ – which means there is no problem with the submitted data, and we need to display the submitted information to the user, the ‘else’ block in the above code will do this for us. First line in the else block will look for a request attribute “DATA”, when the form is submitted we’ll parse the submitted request data and create one object out the those values – which is represented in our example with ‘TestForm’ class, its a POJO [Plain Old Java Object], with the corresponding fields we have in ‘index.jsp’. As mentioned earlier, ‘index.jsp’ has two form fields - ‘name’ and ‘document’, ‘TestForm’ class will have two fields in it one to hold the ‘name’ text field value and the other to hold the ‘document’ field value. Lets see the ‘TestForm’ class.<br />
<pre>package com.rakesh.fileupload.form; <br />
import org.apache.commons.fileupload.FileItem; <br />
public class TestForm {
private String name;
private FileItem document; <br />
public String getName() {
return name;
} <br />
public void setName(String name) {
this.name = name;
} <br />
public FileItem getDocument() {
return document;
} <br />
public void setDocument(FileItem document) {
this.document = document;
}
}</pre>
Nothing special even here, plain Java class with two fields and setter/getter method for each of them. As the ‘name’ form field in the ‘index.jsp’ represents plain string value, the ‘name’ field in ‘TestForm’ is declared as ‘String’, and ‘document’ form field represents a file, we used “FileItem” class of Commons File Upload API. This class will provide all the information about the file which is uploaded and the provides access to the input stream for the file data. Now lets see the code which actually parses the submitted request and creates object of TestForm class.<br />
<pre>package com.rakesh.fileupload.form; <br />
import java.lang.reflect.InvocationTargetException;
import java.util.List; <br />
import javax.servlet.http.HttpServletRequest; <br />
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload; <br />
public class FormUtils { <br />
private static void processFormField(TestForm form, FileItem item)
throws IllegalArgumentException, IllegalAccessException {
try {
BeanUtils.setProperty(form, item.getFieldName(), item.getString());
} catch (InvocationTargetException e) {
// error while populating bean
return;
}
} <br />
private static TestForm processFileItems(List<FileItem> items)
throws IllegalArgumentException, IllegalAccessException {
TestForm form = new TestForm();
for (FileItem item : items) {
if (item.isFormField()) {
processFormField(form, item);
continue;
}
form.setDocument(item);
}
return form;
} <br />
@SuppressWarnings("unchecked")
public static TestForm getTestForm(HttpServletRequest request,
ServletFileUpload handler) throws FileUploadException,
IllegalArgumentException, IllegalAccessException {
return processFileItems(handler.parseRequest(request));
}
}</pre>
This is a utility class which we use to parse the request object and create ‘TestForm’ class object out of the submitted values. It has two private static methods internally calling others and one public static method, which is the entry point for parsing. We use <b class="greenText">Commons Bean Utils API</b> to populate the fields of ‘TestForm’ with the values submitted by the user. Lets go through these methods one by one. First the ‘processFormField()’ – this method will be called for each form field found in the request object. It takes two parameters.<br />
<ul>
<li>TestForm form – The form object which we are trying to populate with the submitted values. </li>
<li>FileItem item – Form field value we are processing. </li>
</ul>
This method uses <b class="greenText">Commons Bean Utils API</b> to populate the given form field in the given form object. We’ll call the ‘BeanUtils.setProperty()’ method to populate the given field. This method takes three arguments.<br />
<ul>
<li>Object bean – The form object which needs to be populated, in our case its TestForm class object. </li>
<li>String name – The Field name to be populated. </li>
<li>Object value – The value to set. </li>
</ul>
Second method in this class is ‘processFileItems()’ – this method will be called once by passing all form values as a ‘java.util.List’. It takes one parameter ‘List<FileItem'>’ which contains all the form fields submitted. We’ll loop through this list and check whether its a simple form field or a file. This ‘org.apache.commons.fileupload.FileItem’ class provides one method ‘isFormField()’ which returns true if the represented field is simple form field, false otherwise. If its a plain form field we’ll call the ‘processFormField()’ and pass necessary parameters to populate the ‘TestForm’ class object. If its not a plain form field, we’ll set it for ‘document’ field in ‘TestForm’ class object by calling ‘setDocument()’ method.<br />
The only public method available in this class is ‘getTestForm()’ – this method will be called from the Servlet to which the form gets submitted. This method takes two parameters – one ‘HttpServletRequest’ object and the other is ‘ServletFileUpload’ class object which is from Commons File Upload API. This object allows us to process the request object and give all the form field values as instances of ‘FileItem’. We dont have to write any code to process the request object, just by calling the ‘parseRequest()’ on this object will give a ‘List’ of ‘FileItem’ object each representing one form field submitted. ‘getTestForm()’ method does nothing more than calling ‘parseRequest()’ method and passing the returned list to ‘processFileItems()’ method. This method in turn returns ‘TestForm’ class object after populating it with the form field values.<br />
Now lets see the Servlet code<br />
<pre>package com.rakesh.fileupload.web; <br />
import java.io.IOException; <br />
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; <br />
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload; <br />
import com.rakesh.fileupload.form.FormUtils;
import com.rakesh.fileupload.form.TestForm; <br />
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 5334402393174853293L; <br />
private static final String UPLOAD_ERROR = "Error while processing values in request object!";
private static final String FAILURE_MSG = "Error while uploading file!"; <br />
private ServletFileUpload handler; <br />
@Override
public void init() throws ServletException {
super.init();
DiskFileItemFactory factory = new DiskFileItemFactory();
handler = new ServletFileUpload(factory);
} <br />
@Override
public void destroy() {
super.destroy();
handler = null;
} <br />
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
TestForm form = FormUtils.getTestForm(request, handler);
request.setAttribute("DATA", form);
} catch (FileUploadException e) {
e.printStackTrace();
request.setAttribute("ERROR", UPLOAD_ERROR);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("ERROR", FAILURE_MSG);
}
request.getRequestDispatcher("/WEB-INF/jsp/form-data.jsp").forward(
request, response);
}
}</pre>
This ‘FileUploadServlet’ overrides three methods - ‘init()’, ‘destroy()’, and ‘doPost()’. Well you might know that ‘init()’ will be called when the servlet gets initialized, and ‘destroy()’ will be called when the servlet container unloads the servlet. ‘doPost()’ will be called on form submit. As ‘init()’ and ‘destroy()’ are called once in servlet’s lifecycle, they are the best places to initialize resources which are used through out the servlet’s lifecycle. In our case the ‘ServletFileUpload’ object which we’ll be using to parse the request object and get the ‘TestForm’ with submitted form values is being initialized in ‘init()’ method and destroyed in ‘destroy()’ method. Now lets look at the ‘doPost()’ method. This method calls ‘FormUtils.getTestForm()’ method from inside ‘try…catch’ block, this method returns ‘TestForm’ object after populating it with the submitted values. Then we’ll set it as request attribute in the next line, and forward to the ‘form-data.jsp’ page. We’ve two catch blocks one catching ‘FileUploadException’ which will be thrown by the Commons File Upload API’s ‘parseRequest()’ method when it encounters problem parsing the request object. In both the catch blocks we’ll set one error message as request attribute ‘ERROR’ and forward to ‘form-data.jsp’. Well thats all the code we’ve to implement file uploading using Common File Upload API. <br />
If you want to have more form fields, then add them first to the ‘index.jsp’ and then to the ‘TestForm’ class, add corresponding getter/setter methods to those new fields, this is enough have them populated, no other code changes are needed. To display these new fields you might need to change the ‘form-data.jsp’ file. All the files which are part of this example are listed in the below given diagram. <br />
<div style="text-align: center;">
<img alt="Files list" border="0" height="420" src="http://www.sattvah.com/im-blog/examples/commons-file-upload-ex/files.jpg" title="Files list" width="314" /></div>
We need to add three jar files to the application ‘lib’ directory - ‘commons-beanutils-core.jar’, ‘commons-fileupload-1.2.1.jar’ and ‘commons-io-1.4.jar’ which are being used in the example code. I placed ‘form-data.jsp’ in “WEB-INF/jsp” directory, because this page should not accessible directly by typing the URL into the browser address bar. All the files inside ‘WEB-INF’ are not accessible directly for the user, but you can still use them from the servlet – as we did in our servlet. <br />
Please find the links to the source code below in resources section. The ‘file-upload.rar’ file has eclipse project files in it, you can create eclipse project directly from the extracted directory. After creating project from the directory you need to add the ‘servlet-api.jar’ and ‘jsp-api.jar’ to project classpath. The ANT script provided is ready to use, except that you need to update the tomcat server location in it, this is needed to have the ‘servlet-api.jar’ and ‘jsp-api.jar’ in project classpath to compile and build the web application.<br />
<h2 class="greenText">
Resources:</h2>
<a href="http://www.sattvah.com/im-blog/examples/commons-file-upload-ex/file-upload-ex.rar">Download source code</a>. <br />
<br />
<a href="http://www.sattvah.com/im-blog/examples/commons-file-upload-ex/example.war">Example WAR file</a>. <br />
<br />
<a href="http://tomcat.apache.org/">Apache Tomcat</a>. <br />
<br />
<a href="http://commons.apache.org/fileupload/">Commons File Upload API</a></div>
</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com17tag:blogger.com,1999:blog-5428401397473577881.post-7015544306310318352010-06-27T14:48:00.005+05:302011-12-22T17:02:46.089+05:30Simple AJAX [, JSP] Example<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
You will find many examples to learn how AJAX [Asynchronous Java Script And XML] works, but this one is different. Its one of the best way of using AJAX in web applications. The difference - many of the examples you find uses Java Script to parse the AJAX response, this example avoids that parsing Java Script and uses JSP to generate the HTML and uses simple Java Script just to make the asynchronous call and show the response. It shows simple way of using JSP and AJAX with as much less Java Script as possible. This article wont go into details of what AJAX is and how to make AJAX calls, it explains one good way among many to use AJAX. Lets get on with it then!<br />
The flow of this example is like this – A simple JSP page where user performs an action [button click in this example] to get list of employees, on this action we’ll make an Asynchronous call to a Servlet which will prepare the dummy employee data and sends that data to a JSP page. This JSP generates the HTML displaying the employee data in a tabular format. The Java Script which made the asynchronous call will receive this HTML and just inserts into the one of the HTML element in the page. That is it. All the Java Script we’ve is just to make an asynchronous call, receive the response HTML and insert into the current page. You can download the complete source code using the links given at the end of this post. The compressed file is an eclipse project, you can directly create eclipse project from the extracted directory.<br />
Didn’t get the clear picture of it yet? do not worry lets go through code which makes it easier for you to understand. First we’ll see the server side code which prepares the data. In this example I tried to separate the layers clearly so that you can replace this layer where we prepare dummy data with actual database code which prepares data by querying database. The DTO object we are going to use to hold each employee information is “EmployeeDTO”, its code is as follows.<br />
<div class="fullpost">
<pre>public class EmployeeDTO {
private int empId;
private String name, email;
private String designation, department; <br />
public EmployeeDTO(int empId) {
this.empId = empId;
} <br />
public int getEmpId() {
return empId;
} <br />
public void setEmpId(int empId) {
this.empId = empId;
} <br />
public String getName() {
return name;
} <br />
public void setName(String name) {
this.name = name;
} <br />
public String getEmail() {
return email;
} <br />
public void setEmail(String email) {
this.email = email;
} <br />
public String getDesignation() {
return designation;
} <br />
public void setDesignation(String designation) {
this.designation = designation;
} <br />
public String getDepartment() {
return department;
} <br />
public void setDepartment(String department) {
this.department = department;
}
}</pre>
EmployeeDTO is just a class with few fields to hold employee details and getter/setter method for all the fields. The DAO, which prepares dummy data is as follows<br />
<pre>import java.util.ArrayList;
import java.util.List; <br />
import com.rakesh.ex.dto.EmployeeDTO; <br />
<br />
public class EmployeeDAO { <br />
/**
* sample method to get list of employees. This method creates sample list
* of employees data.
*/
public List<EmployeeDTO> getEmployees() {
List<EmployeeDTO> empList = new ArrayList<EmployeeDTO>();
for (int i=1; i<=10; i++)
empList.add(createSampleData(i, i%2));
return empList;
} <br />
private static EmployeeDTO createSampleData(int i, int j) {
EmployeeDTO emp = new EmployeeDTO(1000 + i);
emp.setName("Employee" + i);
emp.setEmail(emp.getName() + "@company.com");
emp.setDesignation("Designation" + i);
emp.setDepartment("Department" + j);
return emp;
}
}</pre>
There’s nothing much in the above code – it has two methods, one public and the other private static method. The private static method, just prepares dummy employee information. The public method ‘getEmployees()’ creates an ArrayList of EmployeeDTO objects with dummy employee information and returns it. It loops for 10 times and calls the private static method ‘createSampleData()’ each time. You might want to replace the code in this DAO with actual code which queries database to get the employee information.<br />
Now the servlet which gets called asynchronously from Java Script, its code is as follows <br />
<pre>import java.io.IOException;
import java.util.List; <br />
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; <br />
import com.rakesh.ex.dao.EmployeeDAO;
import com.rakesh.ex.dto.EmployeeDTO; <br />
<br />
public class AjaxExample extends HttpServlet {
private static final long serialVersionUID = -6377586508833712244L; <br />
private EmployeeDAO empDAO; <br />
@Override
public void destroy() {
super.destroy();
this.empDAO = null;
} <br />
@Override
public void init() throws ServletException {
super.init();
this.empDAO = new EmployeeDAO();
} <br />
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// get employee list
List<EmployeeDTO> empList = empDAO.getEmployees();
// set employee list in to request
req.setAttribute("emp_list", empList); <br />
// forward to jsp which generates table out of employee list
req.getRequestDispatcher("emp_list.jsp").forward(req, resp);
return;
} <br />
}</pre>
This “AjaxExample” servlet extends “HttpServlet” and overrides “init()”, “destroy()”, and “doGet()” methods. We’ll instantiate DAO object in the “init()” method and remove the reference in “destroy()” method. The “doGet()” method uses this DAO object and calls “getEmployees()” method to get employees data. This method returns a list of EmployeeDTO objects. We’ll set this “List” object as request attribute and forward to “emp_list.jsp” page. That is all we do in this servlet. Simple isn’t it? lets see the “emp_list.jsp”.<br />
<pre><%@page import="java.util.List" %>
<%@page import="com.rakesh.ex.dto.EmployeeDTO" %>
<%
List<EmployeeDTO> empList = (List<EmployeeDTO>)request.getAttribute("emp_list");
if (empList == null || empList.isEmpty()) {
%>
<p>Employee list is empty!</p>
<% } else { %>
<table width="100%" border="1">
<tr><th colspan="5" align="center"><h3>Employee Info</h3></th></tr>
<tr>
<th>Emp-Id</th><th>Name</th><th>Email</th><th>Designation</th><th>Department</th>
</tr>
<% for (EmployeeDTO emp : empList) { %>
<tr>
<td><%=emp.getEmpId()%></td>
<td><%=emp.getName()%></td>
<td><%=emp.getEmail()%></td>
<td><%=emp.getDesignation()%></td>
<td><%=emp.getDepartment()%></td>
</tr>
<% } %>
</table>
<% } %></pre>
This JSP generates a ‘HTML table’ with the details of employees. Important thing to observe is, this JSP doesn’t generate complete HTML [I mean HTML, BODY, etc tags], it only generates the ‘table’. It gets the ‘List’ object from request and loops through it and adds ‘<tr>’ tag for each ‘EmployeeDTO’. Even this code block is not complex, plain simple JSP code.<br />
Now the core of this post, the Java Script which makes the asynchronous call.<br />
<pre>AjaxEx = function(url, elId) {
if (!url || !elId) {
alert("Invalid input!");
return;
}
var el = document.getElementById(elId);
if (!el) {
alert("Container Element, to place Ajax response doesn't exists!");
return;
}
this.init(url, el);
}; <br />
AjaxEx.prototype = {
init : function (url, el) {
this.el = el;
this.url = url; <br />
this.sampleHtml = "<p>This will be replaced with AJAX response!</p>"; <br />
// create xml http request object for AJAX requests
this.xmlHttp = this.initXmlHttp(); <br />
}, <br />
initXmlHttp : function () {
if (window.XMLHttpRequest)
// Firefox, Opera, IE7, etc.
return new XMLHttpRequest();
if (window.ActiveXObject)
// IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}, <br />
resetContent : function () {
this.el.innerHTML = this.sampleHtml;
}, <br />
sendAjaxRequest : function () {
// initialize XML Http object if not available
if (!this.xmlHttp)
this.xmlHttp = this.initXmlHttp(); <br />
if (this.xmlHttp) {
var ajaxObj = this;
this.xmlHttp.onreadystatechange = function() {
if (ajaxObj.xmlHttp.readyState==4 && ajaxObj.xmlHttp.status==200) {
// 4 = "loaded", 200 = "OK"
ajaxObj.el.innerHTML = ajaxObj.xmlHttp.responseText;
}
};
this.xmlHttp.open("GET", this.url, true);
this.xmlHttp.send(null);
} else
alert("Your browser does not support AJAX.");
}
}; <br />
function makeAjaxCall(ajaxObj, flag) {
if (flag) {
ajaxObj.sendAjaxRequest();
return;
}
ajaxObj.resetContent();
}</pre>
Above Java Script code might look big, but its really simple. We have a “AjaxEx” class with few methods in it, and a Java Script method “makeAjaxCall()”. First lets see what ‘makeAjaxCall()’ does. It takes two parameters – one ‘ajaxObj’ - the AjaxEx instance and the other ‘flag’ – true/false to decide whether to make Ajax call and update content OR reset the previously displayed content with default text. This ‘makeAjaxCall()’ method checks the ‘flag’ parameter value - if its true, it calls ‘sendAjaxRequest()’ method on ‘ajaxObj’ object and returns, else calls ‘resetContent()’ on ‘ajaxObj’ object.<br />
“AjaxEx” class has four methods in it – ‘init()’, ‘initXmlHttp()’, ‘resetContent()’, and ‘sendAjaxRequest()’. To instantiate ‘AjaxEx’ class you need to pass two values to it – one ‘url’ which is the servlet URL to which we need to make asynchronous requests for employee information, second ‘elId’ – the id attribute of the HTML element in which we need to place the response. When you create instance of ‘AjaxEx’, it validates these two inputs and then calls ‘init()’ method.<br />
The ‘init()’ method sets references to the servlet URL and the DOM reference to the HTML element in which we need to place AJAX response. Then it calls ‘initXmlHttp()’ method. This method does nothing but creating XML Http Request object according to the browser you are using. For IE5 and IE6 it creates instance of ‘ActiveXObject’ and ‘XMLHttpReques’ object for other browsers. The third method in ‘AjaxEx’ is ‘resetContent()’ method, this is very simple one, its just resets the content of the DOM Html element [the one with the ID, which is passed as second parameter to AjaxEx(…)] with default text. Well now the important part of this file – the ‘sendAjaxRequest()’ method.<br />
This method first checks whether the XML Http object is created or not. If not then it calls ‘initXmlHttp()’ method to create it. After this we’ll initialize what to do when we receive the response. The line where we set reference to “xmlHttp.onreadstatechange’ – we created an inline function and in it we check the response status – if the readState is ‘4’ and status is ‘200’ which says we’ve got a valid response, and then we’ll just replace the content of the DOM element in which we need to place the response we got for this request. Rest of the two lines where we call ‘open()’ and ‘send()’ are the method calls where we actually make an asynchronous call. That is it about the Java Script we’ve. Now the last part the JSP which will have the button to make the AJAX call.<br />
<pre><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" <br />
"<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd%22">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"</a>>
<html xmlns="<a href="http://www.w3.org/1999/xhtml%22">http://www.w3.org/1999/xhtml"</a> xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <br />
<title>Simple Ajax Example</title> <br />
<script type="text/javascript" src="js/ajax-example.js"></script>
<style type="text/css">
body {
width: 800px;
height: 600px;
}
.top_block {
text-align: center;
}
.top_block input {
font-weight: bold;
}
.ajax_content {
border: 2px solid #000;
padding: 2em;
}
</style>
</head>
<body>
<div class="top_block">
<input type="button" onclick="javascript:makeAjaxCall(ajaxObj, true);" <br />
value="Get Data"/>&nbsp;&nbsp;
<input type="button" onclick="javascript:makeAjaxCall(ajaxObj, false);" <br />
value="Reset Content"/>
</div>
<div id="ajax_content" class="ajax_content">
<p>This will be replaced with AJAX response!</p>
</div>
<script type="text/javascript">
<!--
// view source of this page after it loads in browser
// and check this variables value
var url = "<%=request.getContextPath()%>/ajaxServlet";
var ajaxObj = new AjaxEx(url, "ajax_content");
// -->
</script>
</body>
</html></pre>
This is a simple JSP, with three parts to observe. One the “ajax-example.js” file import in the ‘head’ tag, second the ‘onclick’ events for the two input tags in first div element, and the ‘script’ block at the end of the page just before the closing ‘body’ tag. What are we doing in this page – this page uses two div elements, the top one shows two buttons - ‘Get Data’ and ‘Reset Content’. Both the buttons call ‘makeAjaxCall()’ method when clicked, but with a difference in the second parameter. ‘Get Data’ button passes ‘true’ to make the AJAX call and ‘Reset Content’ passes ‘false’ to reset the content. <br />
And the Java Script block at the end has code to create object for ‘AjaxEx’ Java Script class. The URL Java Script variable is set to the ‘AjaxExampleServlet’ and then we’ll create AjaxEx object using the ‘new’ keyword, and pass the URL and the id ‘ajax_content’ to it. If you observe the HTML in the body you’ll find the second div element has this id value ‘ajax_content’ assigned to it. Well that is it, isn’t it simple! What I tried here is to show the simple and a good way of using AJAX with less usage of Java Script.<br />
Please download the source code used in this example using the link give below.<br />
<a href="http://sattvah.com/im-blog/examples/ajax-ex.rar" title="Ajax example">Download the source code.</a><br />
The download file is a .rar file, which already have eclipse project files, you might have to update the eclipse class path and update servlet-api.jar. It also has ANT build script to generate the .war file for deployment. I used Tomcat path to have servlet-api.jar file in class path to compile the project, you need to update this path with your local one. Hope this helps to download and start right away :)</div>
</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com6tag:blogger.com,1999:blog-5428401397473577881.post-51749739629581791882010-06-17T16:27:00.004+05:302011-12-22T17:05:05.298+05:30Eclipse Tips<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
In few situations, you want eclipse to refresh the project contents automatically. Its might be required when you changed the one/more files of an eclipse project in some other editor and you wanted eclipse to reflect those changes automatically. If you are using version control and when you get latest changes from repository, you want those changes to be reflected on your eclipse. This can be configured in eclipse easily.<br />
<blockquote>
Go to <b>Window –> Preferences</b>, in this window select <b>General –> Workspace</b> from the tree in the left panel. When you select Workspace, you’ll see workspace related configuration options in the right panel. The top section will have three checkboxes, one of them will "<b>Refresh Automatically</b>". Select this checkbox and click OK.<br />
Another feature which could be handy is to see different Icons for different file types like Interfaces, Classes, Abstract Classes, etc. You can set this in <b>Window –> Preferences</b> window. In this window select <b>General –> Appearance –> Label Decorations</b> option. You’ll see a big list of options in the right panel. Select the check box for "<b>Java Type Indicator</b>".</blockquote>
</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com2tag:blogger.com,1999:blog-5428401397473577881.post-44792122531495214222010-06-07T13:28:00.004+05:302011-12-22T17:05:48.091+05:30Attaching Source/Java Doc - In Eclipse<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
Its really simple to attach Source code/Java Doc in eclipse, for a library you are using in your application. Select the project for which you want to do the changes.<br />
<ol>
<li>Go to Project Menu –> Properties</li>
<li>Select Libraries Tab</li>
<li>Select and expand the Jar file for which you want to add source code/Java doc.</li>
<li>This will show you the options "Source attachment" and "JavaDoc Location".</li>
<li>Select "Source attachment" option, this will enable 'Edit' button.</li>
<li>Click on Edit button, this will open "Source Attachment Configuration" dialog. </li>
<li>Here you need to provide the location of the source code to be attached. You can provide either compressed [jar/zip] file Or directory location of the source code. And after providing the location press OK.</li>
</ol>
<br />
Simple isn't it. For attaching JavaDoc select the option "JavaDoc" instead of "Source attachment" in the above mentioned step, and click on Edit. For JavaDoc you can either provide URL as location Or provide a location of the compressed file. For both "Source attachment" and "JavaDoc" you can also provide location by selecting a directory from the current workspace.</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com2tag:blogger.com,1999:blog-5428401397473577881.post-17598642443746238332010-05-31T21:34:00.004+05:302011-12-22T17:06:09.386+05:30Changing Eclipse Workspace<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
Easy way to do this, go to “<b class="greenText">File->Switch Workspace</b>”. This option will show you previously used workspaces. You can select workspace you want to use, if the one you want to use is listed in it. If not then select “Other” option. This will open “Workspace Launcher” dialog. This dialog will allow you to choose the directory which you want to use as workspace. Simple isn’t it!<br />
Well the hard way of doing this – Open the “<b class="greenText">ECLIPSE_HOME/configuration/.settings</b>” directory, in this directory you’ll find a file “<b class="greenText">org.eclipse.ui.ide.prefs</b>”. Open this file using any text editor like Notepad/Wordpad. This file contains workspace related configuration. “<b>SHOW_WORKSPACE_SELECTION_DIALOG</b>” and “<b>RECENT_WORKSPACES</b>” are the ones concerned to changing workspace.<br />
<ul style="list-type: disc;">
<li> <b>SHOW_WORKSPACE_SELECTION_DIALOG –</b> This property will have either “true/false” value. If this property is set to true, then next time when you open eclipse, it’ll open “Workspace Launcher” dialog through which you can select the directory which you want to use as workspace.<br />
</li>
<li> <b>RECENT_WORKSPACES –</b> This property will have the path to the workspace directory. Specify the directory path which you want to use as workspace for this property and restart eclipse.<br />
</li>
</ul>
</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com0tag:blogger.com,1999:blog-5428401397473577881.post-2516304739990113982010-05-18T14:38:00.003+05:302011-12-22T17:06:36.720+05:30Oracle SQL Developer & Named MSSQL Instance<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
Its a small tip to connect to a ‘<b class="greenText">Named MSSQL Instance</b>’ using Oracle SQL Developer. Oracle SQL Developer allows you to connect to any database which has supported JDBC drivers. You can add these drivers either using “Help –> Check for Updates” and by selecting “Third Party SQL Developer Extensions” option. This will list available updates, from which you can select the needed drivers. Second option is adding these drivers from your local drive using “Tools –> Preferences” and by selecting the “Database –> Third Party JDBC Drivers” option from the tree given in the left column.<br />
If you installed needed driver for MSSQL database you’ll get the tab “SQL Server” on the New Database Connection window. If you observe this window, you’ll see that there is no text field/option to provide “Database Instance Name”. This window is simple to create a Database Connection to Unnamed MSSQL Database Instance. The big question is how do we create a connection to a Named MSSQL Database Instance!<br />
Its really simple – All you need to do is add this information to the “Port” text field.<br />
<pre> <PORT NUMBER>/;instance=<INSTANCE NAME>
Example:-
<b>1433/;instance=MyInstance</b></pre>
In the above example, I’ve used ‘1433’ which is the default port number for MSSQL. And the Instance I am trying to connect to, is ‘MyInstance’. Well that is all you need!, Happy Querying!!!</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com1tag:blogger.com,1999:blog-5428401397473577881.post-47269259837945933662010-05-11T17:52:00.004+05:302011-12-22T17:07:28.132+05:30Auto Scrolling Java Script Component<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
Well after a long break, here I am, back with a component which might be useful for web developers/designers. In this post I’ll try to explain <b class="greenText">Auto Scrolling</b> Java script component. You might think <b>Auto Scrolling</b> is very old topic and you’ll find many examples of this kind. Even I was thinking the same couple of months ago. I was supposed to work on something similar to this, I thought I can use some existing components with out putting effort to write my own. But ended up writing my own Auto Scrolling component. Reason – Those examples I found did not fit my requirement and are really complicated for a common developer to understand and plugin to existing code. This component is small, simple and can be plugged in to any piece of code [at least my perception] with out any effort. All the source code is free for every body to use [this is also one of the constraint I wrote my own], download it using the links provided a the end of this article. Why wait, lets get on with it.<br />
<div class="fullpost">
This component is coded to work with tabular information. This doesn’t mean that you can not use it for other data, with minor changes you can use this component to work with any kind of data. Lets start with the code.<br />
To use this component on tabular data the data has to be in the following format. We need to have one outer table which will have column headers [‘th’ tags] as first row, in the second row, we’ll have one column spanned across all the column, in this column we need to have an inner table with tabular data. Find the template below.<br />
<pre> <table id="col-headers" class="tbl_headers">
<tr class="colNames">
<th>Heading-1</th><th>Heading-2</th><th>Heading-3</th><th>Heading-4</th><th>Heading-5</th>
</tr>
<tr>
<td colspan="5">
<table id="tbl-content" class="tbl_text">
<tr>
<td>Column-1</td><td>Column-2</td><td>Column-3</td><td>Column-4</td><td>Column-5</td>
</tr>
...
</table>
</td>
</tr>
</table></pre>
In the above template 'Heading-1', 'Heading-2', etc are column headings, and ‘Column-1’, ‘Column-2’, etc are data in the table.<br />
<pre> AutoScroller = function (headersTblId, contentTblId) {
// initial delay in milli seconds
this.initDelay = 5000;
// animation delay in milli seconds
this.delay = 50;
// initial relative position of the content
this.position = 0;
// initialize auto scroll - get container references
this.el = document.getElementById(headersTblId);
this.scrollTbl = document.getElementById(contentTblId);
};</pre>
Nothing complex here, its just making the component ready by initializing it. First we’ll set Initial delay – in the above code the initial delay is ‘5000’ milli seconds, which is 5 seconds. This mean when the page/content is loaded, this component waits for 5 seconds before scrolling the text. Then we’ll set the animation delay – in the above code the delay is ‘50’ milli seconds, this value defines how fast/slow you want the scrolling to be. What ever amount of time you give here, component will change the text position by 1px after this amount of time repeatedly. Next value is ‘position’ which is used internally by the code to reference the current position of the text. Next code tries to get DOM references to the headers table and content table. That is all we’ve with initialization of the component, isn’t that simple!, let move on with rest of the code.<br />
<pre> _clearInterval : function () {
if (!this._interval)
return;
clearInterval(this._interval);
this._interval = null;
}</pre>
This method is used internally to clear animation related flags [time intervals]. When interacting code calls this component multiple times, this component takes care of clearing existing flags and have one scrolling sequence per object. This component uses ‘setTimeout()’ method of Java Script to create the scrolling animation which returns a unique value which we can use to cancel the time out value. In this method we do the same, each time we call setTimeout() method we keep the returned unique value in ‘_interval’ variable. In this method we’ll check if this variable has a value, if it has then call ‘clearInterval()’ to cancel the time out which has been set previously.<br />
<pre> _resetPosition : function () {
// reset content position
this.position = 0;
this.scrollTbl.style.top = "0px";
}</pre>
This method will reset the content’s position to default, it resets the variable ‘position’ to ‘0’ and resets the position by updating style attribute ‘top’ to ‘0px’.<br />
<pre> stop : function () {
this._clearInterval();
// reset content position to normal
this._resetPosition();
}</pre>
This method can be used to stop the scrolling. If you’ve other scripts in your page interacting with this component you can use this method to stop scrolling. First we’ll clear the time outs set previously by calling ‘_clearInterval()’ method and reset the content position to default by calling the ‘_resetPosition()’ method.<br />
<pre> resetColWidth : function () {
// if no text to re-align - return
if (!this.el || !this.scrollTbl)
return false;
// get table content height
this.tblHeight = this.scrollTbl.offsetHeight;
var th = this.el.rows[0].cells;
var td = this.scrollTbl.rows[0].cells;
// reset widths for each column header
for (var i=0;i<td.length;i++) {
th[i].style.width = td[i].offsetWidth + "px";
}
return true;
} </pre>
‘resetColWidth()’ method is one of the important methods, it resets the width of the header column widths. The need – as we use two different tables for column headings and tabular content, the columns of both tables might not be aligned properly. We need to have some work around to make the columns of both the tables to be aligned properly. This method is for exactly the same purpose. It loops through the columns of the content table and gets the width for each column and sets this width to the same column in the header table. Say if you have a column named ‘column1’ it gets the width of this column text and sets that width to the ‘column1’ width in the heading table. I used ‘offsetWidth’ attribute to get the width and ‘style.width’ attribute to set the width. Bold text in the above code sets the width of column headers.<br />
<pre> getWindowHeight : function () {
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
return window.innerHeight;
}
if( document.documentElement && ( document.documentElement.clientWidth
|| document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
return document.documentElement.clientHeight;
}
if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
return document.body.clientHeight;
}
}</pre>
This method returns the current browser window height, this is the standard way/code to get the window height using Java Script. This height will be used a deciding factor whether to scroll the content or not. If the content doesn’t span more than the current height of the window, we wont scroll the content. I thought that its logical to scroll the text only when the content spans more than the window height.<br />
<pre>
initScroll : function () {
// clear existing time-outs
this._clearInterval();
// reset column widths
if (!this.resetColWidth())
return;
// reset content position
this._resetPosition();
this.winHeight = this.getWindowHeight();
// if scrolling is needed
if (this.tblHeight > this.winHeight) {
// start scrolling
var obj = this;
this._interval = setTimeout(function () { obj._scroll(); }, this.initDelay);
}
}</pre>
‘initScroll()’ method initializes the scrolling. First it clears any existing time outs by calling ‘_clearInterval()’, which ensures to have one process of scrolling even when this method gets called multiple times on the same object. Then it tries to re-align the column widths by calling the ‘resetColWidth()’, this method returns false if it couldn’t find references to headers table and content table. Then it calls ‘_resetPosition()’ to reset the the position of the content to default. Then it gets the window height by calling ‘getWindowHeight()’ and checks whether scrolling is needed, if needed it schedules the scroll after initial delay using ‘setTimeout()’ and calling ‘_scroll()’ method in it. ‘_scroll()’ method changes the position of the text by ‘1px’ each time and schedules a call to itself after the configured ‘delay’ using setTimeout(). Code block of ‘_scroll()’ method is given below.<br />
<pre> _scroll : function () {
// start at bottom after completing one cycle of scrolling
if (this.position <= (0-this.tblHeight))
this.position = this.winHeight;
this.position = this.position - 1;
this.scrollTbl.style.top = this.position + "px";
// recursive call periodically
var obj = this;
this._interval = setTimeout(function () { obj._scroll(); }, this.delay);
}</pre>
That is all you’ve in this scrolling component. You need to know few more things – basic styles needed for this component. Those simple styles are given below<br />
<pre> <style type="text/css">
table {
width: 100%;
text-align: center;
}
.tbl_headers { overflow: hidden; text-align: center; }
.colnames { background-color: #ccc; }
.colnames th { padding: 1em; }
.tbl_text { position: relative; z-index: -1; }
</style></pre>
Above styles are for the container table, text table and headers. Three important styles classes are 'tbl_headers', 'colNames', and 'tbl_text'. 'tbl_headers' has styles specified for outer table, 'tbl_text' has styles for the inner table which has text to be scrolled, and 'colNames' has styles for column headers. These are very simple styles like back ground color, overflow property, position, and z-index.<br />
Java Script source code and an example HTML page using the above component is available <a href="http://sattvah.com/im-blog/examples/auto-scroller.rar">here</a>.</div>
</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com1tag:blogger.com,1999:blog-5428401397473577881.post-42125387403281520652009-12-17T20:17:00.006+05:302011-12-22T17:07:57.701+05:30Connection Pool Configuration Using DBCP<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
Connection pool configuration, for most of the web applications with data base interaction, is a common process. Either small or big, its always suggested to have connection pool configured for better performance. If your JDBC or DAO code is creating data base connection for each call, it results a lot of overhead and reduces your application performance. Using connection pool will improve application performance a lot. If you are deploying your web application in Application Servers like Weblogic, Webspere, etc. they will allow you to configure connection pool and maintain them for you. But if you are opting for Web Server like <b class="greenText">Tomcat</b>, which is the most common case when you go for shared hosting services, then you have to depend on resources like <b class="greenText">DBCP [Data Base Connection Pool]</b> for connection pooling. Its one of the best options available for connection pooling. By configuring connection pool in <b>Tomcat</b> will relieve lot of responsibilities from your application. We let <b>Tomcat</b> create Connection Pool and let it maintain it for you. In this article I will try to explain how to configure <b class="greenText">DBCP in Tomcat</b>. Well lets start then!<br />
<div class="fullpost">
If we configure connection pool in Tomcat, there needs to be a way for your application to access it. This is where <b class="greenText">JNDI</b> comes in to action. You can use JNDI to access connection pool inside your web application. There are many ways to create connection pool, lets first look at a simple way to do it. First we need to configure pool in Tomcat’s <b>server.xml</b>, lets see the xml code snippet.<br />
<pre><Context path="/sample" debug="0" reloadable="true">
<Resource name="jdbc/samplePool" auth="Container"
type="javax.sql.DataSource" removeAbandoned="true"
removeAbandonedTimeout="30" maxActive="100"
maxIdle="30" maxWait="10000" username="dbUser"
password="dbPassword" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/testDB"/>
</Context></pre>
Lets go through the above configuration. In the above code we tried to configure a context “/sample”, and for this context we’ve configured a JNDI resource which is a connection pool with the name “jdbc/samplePool”. This connection pool is configured for a MySQL database “testDB”, which is accessible locally using the JDBC URL “jdbc:mysql://localhost:3306/testDB”. Lets go through other configuration parameters briefly.<br />
<table align="center" border="0" cellpadding="2" cellspacing="5"><tbody>
<tr>
<td valign="top"><b>removeAbandoned</b></td>
<td valign="top">Flag to remove abandoned connections if they exceed the removeAbandonedTimout. If set to true a connection is considered abandoned and eligible for removal if it has been idle longer than the removeAbandonedTimeout. Setting this to true can recover db connections from poorly written applications which fail to close a connection.</td>
</tr>
<tr>
<td valign="top"><b>removeAbandonedTimeout</b></td>
<td valign="top">Timeout in seconds before an abandoned connection can be removed. Default value for this is 300 sec.</td>
</tr>
<tr>
<td valign="top"><b>maxActive</b></td>
<td valign="top">Maximum number of active connections in pool.</td>
</tr>
<tr>
<td valign="top"><b>maxIdle</b></td>
<td valign="top">The maximum number of connections that can remain idle in the pool. Default is 8.</td>
</tr>
<tr>
<td valign="top"><b>maxWait</b></td>
<td valign="top">The maximum number of milliseconds that the pool will wait</td>
</tr>
<tr>
<td valign="top"><b>username</b></td>
<td valign="top">Database username to be used to create a connection.</td>
</tr>
<tr>
<td valign="top"><b>password</b></td>
<td valign="top">Database password to be used to create a connection.</td>
</tr>
<tr>
<td valign="top"><b>driverClassName</b></td>
<td valign="top">The fully qualified Java class name of the JDBC driver to be used.</td>
</tr>
<tr>
<td valign="top"><b>url</b></td>
<td valign="top">The JDBC connection URL to be used to create a connection.</td>
</tr>
</tbody></table>
<br />
Once we configure connection pool at context level, we need to configure our <b>web application deployment descriptor [web.xml]</b> to get a reference of this pool. Lets see the code snippet to be added in web.xml file.<br />
<pre><resource-ref>
<description>Resource references to connection pool</description>
<res-ref-name>jdbc/samplePool</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref></pre>
The above configuration indicates container to get a reference to the resource "jdbc/samplePool" configured at context level and have it locally available for the web application. Thats it all you have to do is access this connection pool using JNDI lookup in your code. Sample code block might look as the one given below.<br />
<pre>// get environment naming context
Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
// do JNDI lookup for data source
DataSource ds = (DataSource) envCtx.lookup("jdbc/samplePool");</pre>
JNDI look up is a bit expensive in terms of performance, so to avoid JNDI look up every time you need to access connection pool, what you can do is have a Servlet Context Listener class [by implementing ServletContextListener interface] and write the above look up code in its <b>contextInitialized()</b> method, and set the reference in <b>context object</b>, so that you can use this <b>context object</b> to access connection pool. This makes the JNDI lookup be done only once when the context gets deployed.<br />
This is the simple way of configuring connection pool. You will find many articles explaining the simple DBCP configuration [even in more elaborative way] on many other sites/blogs. So, why another one?<br />
If you observe the context tag configuration, we used almost 9 configuration parameters for connection pool creation. It made the <b>XML A BIT COMPLEX</b>. If you are thinking that is OK, let me tell you, DBCP configuration allows you to configure so many other parameters to fine tune it exactly for your situation. If you add all those parameters to the xml, it makes the configuration a lot more complex and makes it difficult to modify.<br />
Alternative! YES, we do have an alternative way for this. <b>Explaining this alternative way is the sole purpose of writing this article</b>. So, lets get on with it. First we need to create a properties file with all the connection pool configuration parameters, and lets name it as "<b>my_db_config.properties</b>". Following is the sample file with few configuration parameters.<br />
<pre># See: http://jakarta.apache.org/commons/dbcp/configuration.html
####################################################################
###################### CONNECTION PROPERTIES #######################
####################################################################
# database username and password
username=root
password=root
# JDBC driver class name
driverClassName=com.mysql.jdbc.Driver
# JDBC connection url
url=jdbc:mysql://localhost:3306/testDB
####################################################################
#################### CONNECTION POOL PROPERTIES ####################
####################################################################
removeAbandoned=true
# Time out in seconds
removeAbandonedTimeout=30
# Maximum number of connections in pool. Set to 0 for no limit.
maxActive=100
# Maximum number of idle connections in pool. Set to -1 for no limit.
maxIdle=30
# Maximum time in milli seconds to wait for a connection to become available
# Set to -1 to wait indefinitely.
maxWait=10000</pre>
For the complete list of configuration parameters please go through this URL: <a href="http://commons.apache.org/dbcp/configuration.html" target="_blank">DBCP Configuration Parameters</a>.<br />
Second thing we need to do is modify the above given connection pool configuration to use this properties file. Following is the modified configuration<br />
<pre><Context path="/sample" debug="0" reloadable="true">
<Resource name="jdbc/samplePool" auth="Container"
type="javax.sql.DataSource" factory="com.rakesh.DataSourceFactory"
configFile="my_db_config.properties"/>
</Context></pre>
If you observe we removed all the connection pool configuration parameters and replaced them with two parameters one "<b>factory</b>" and second "<b>configFile</b>". First parameter "factory" is used to give factory class to create DataSource object, second is used to give the properties file with all connection pool configuration parameters, in our case it is "my_db_config.properties" created above.<br />
It is the factory class "<b>com.rakesh.DataSourceFactory</b>", which is responsible for reading configuration parameters from the properties file "<b>my_db_config.properties</b>" and create connection pool. The last part is the factory class, lets see the code blocks in it which will do the job for us.<br />
<pre> . . .
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable environment)
throws Exception {
// We only know how to deal with <code>javax.naming.Reference</code>s
// that specify a class name of "javax.sql.DataSource"
if ((obj == null) || !(obj instanceof Reference)) {
return null;
}
Reference ref = (Reference) obj;
if (!"javax.sql.DataSource".equals(ref.getClassName())) {
return null;
}
/* ============================================================
* RAKESH: Commented following block
Properties properties = new Properties();
for (int i = 0 ; i < ALL_PROPERTIES.length ; i++) {
String propertyName = ALL_PROPERTIES[i];
RefAddr ra = ref.get(propertyName);
if (ra != null) {
String propertyValue = ra.getContent().toString();
properties.setProperty(propertyName, propertyValue);
}
}
* =============================================================== */
/* =============================================================
* RAKESH: Customized code to use .properties file
* ============================================================= */
RefAddr configFileName = ref.get("configFile");
if (configFileName == null)
throw new IllegalArgumentException(
"configFile attribute used to provide " +
"DB Configuration properties file is missing");
String configValue = configFileName.getContent().toString();
Properties properties = loadProperties(configValue, getClass());
return createDataSource(properties);
}
. . .
static private Properties loadProperties(final String fileName, Class c)
throws IOException {
ClassLoader classLoader = c.getClassLoader();
InputStream in = classLoader.getResourceAsStream(fileName);
if (in == null)
throw new FileNotFoundException("Unable to load properties file: '"
+ fileName + "'");
try {
Properties p = new Properties();
p.load(in);
return p;
} finally {
in.close();
}
}
. . .</pre>
Well do not get scared by looking at the above code, only small blocks were written by me. What I did is downloaded DBCP API source code and modified the class "<b>BasicDataSourceFactory</b>" class, thats it. If you observe I added comment blocks with "<b>RAKESH:</b>" text in it those are the blocks I modified, <b>its hardly 20-30 lines of code</b>, thats it. Whats that code block does is, looks for a configuration attribute "<b>configFile</b>" and calls a private method "<b>loadProperties()</b>" which will read the .properties file and returns a "<b>Properties</b>" object with all the configuration parameters. Complete source code is provided at the end of this post, so that you can download it and have a look in to it.<br />
Now the final part, as the connection pool creation is done by the server, the above class should be available for the server to call. The question: how do we make the above class available for the web server. All you have to do is follow the simple steps given below.<br />
1. Compile the above give java class [<b>DataSourceFactory.java</b>] and make a jar out of it.
<br />2. Place this jar file under <b>TOMCAT_HOME/common/lib</b> directory
<br />3. Place the data base pool configuration file [<b>my_db_config.properties</b>] under <b>TOMCAT_HOME/common/classes</b> directory
<br />
And make sure you download and place <b>DBCP and Commons Pool jar files in TOMCAT_HOME/common/lib directory</b>. You can find links to download pages of these jar files in resources section below.<br />
Thats it, you are done! you are ready with connection pool configured for your application.<br />
<b>Resources:</b><br />
1. Complete source code of <a href="http://sattvah.com/im-blog/examples/dbcp/DataSourceFactory.java" target="_blank">DataSourceFactory.java</a><br />
2. Download <a href="http://commons.apache.org/dbcp/downloads.html" target="_blank">DBCP</a> jar.
<br />3. Download <a href="http://commons.apache.org/pool/download_pool.cgi" target="_blank">Commons Pool</a> jar.
</div>
</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com0tag:blogger.com,1999:blog-5428401397473577881.post-1449800592953367862009-11-06T14:30:00.002+05:302013-01-12T09:55:20.869+05:30Simple DAO API Using JDBC<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
<strong><pre> Update: Source code now available @ <a href="http://code.google.com/p/simple-dao-api/">http://code.google.com/p/simple-dao-api/</a> </pre></strong>
<br />
This article is about the "Simple DAO API" which I wrote using JDBC API to assist database programming. This <b class="greenText">TINY LITTLE API</b> containing 7 classes [Not exactly an API, you can not call a set of 7 classes as API I guess]; is INSPIRED by the <b class="greenText">SPRING DAO</b> classes and is intended for those beginners who just started learning JDBC and trying their small examples, class assignments and for those who are trying to develop small desktop applications, small Servlet based web applications. For this kind of development it'll be difficult to use the those very nice features of APIs like Spring to ease database programming, as it requires bit of time to understand the Spring API, and most of the times you end up not using all the features of the API. You can find the links to download the source code at the end of this article.<br />
<div class="fullpost">
As I mentioned above these classes were written after getting inspired by the Spring DAO API classes, you'll see similarities in naming. Lets see how these classes ease JDBC programming. All you've to do is follow the steps given bellow<br />
<ul>
<li>Create your DAO class and make it extend BaseDAO which is from this API. This will allow you to have access to methods like "queryForInt()", "queryForObject()", "query()", and "update()" to execute queries.</li>
<li>Step-1 will force you to call BaseDAO's constructor. Add a constructor and call super class' constructor. You need to pass two parameters to it.
<ul>
<li>Instance of javax.sql.DataSource</li>
<li>boolean 'readOnly' flag to set read only property of connection, kind of performance related step, which will avoid write locks on tables when your DAO is only reading data.</li>
</ul>
</li>
<li>Create a .properties file, <Your DAO class name>.properties, where we'll place all the queries used in this DAO. This will make your code look lot simpler.</li>
<li>You need to add one field to the DAO class. Instance of 'ClassResources' which is used to read queries from <You DAO class name>.properties file.</li>
</ul>
That's all you need, now you can just call "query(...), queryForInt(...), queryForObject(...) and update(...)" methods and make your code look lot simpler. Above steps will give you an abstract view of how you need to use these classes. Lets see what are the files you'll end up with for one DAO. Lets say I've to create a DAO class "MyDAO.java". Files you need to create are<br />
<ul>
<li>MyDAO.java - Java class file with the code to read data.</li>
<li>MyDAO.properties - Properties file with all the queries needed by MyDAO.java</li>
</ul>
That's it. Lets see the code in MyDAO.java. Say I need to write three methods in this DAO<br />
<ul>
<li>Method to give employee name, using the employee id</li>
<li>Method to give complete employee details, using employee id</li>
<li>Method to give list of employees.</li>
</ul>
Lets code these methods. First make the DAO extend BaseDAO.<br />
<pre> public class MyDAO extends BaseDAO {
...
}
</pre>
Second step - call BaseDAO's constructor<br />
<pre> public class MyDAO extends BaseDAO {
public MyDAO(DataSource ds) {
// data source and read only flag
super(ds, true);
}
}
</pre>
As you can see we are passing 'true' for the read only flag, because all the methods in this DAO are doing read only operations. If you've one write operation then you need to pass 'false' for this 'readOnly' flag.<br />
Third step is adding 'ClassResources' instance to read the queries from the .properties file.<br />
<pre> private static final ClassResources resources = new ClassResources(MyDAO.class);
</pre>
This field is declared as "private static final", as one instance will serve the purpose for all instances of this DAO[if you've multiple instances], and its used only in this class, so declared as 'private'. The constructor takes 'MyDAO.class' as parameter which will be used to get the class name and to read the properties file.<br />
We are done with the required steps. Now let see the actual database related code. The first method which gives employee name by employee id, before writing the code lest add the query to the MyDAO.properties file.<br />
<pre> SELECT_NAME=SELECT name FROM employee WHERE emp_id=?
</pre>
Now the code to execute this query<br />
<pre> public String getEmployeeName(final int empId) throws SQLException {
return queryForObject(GenericMappers.stringRowMapper, resources, "SELECT_NAME", empId);
}
</pre>
Thats all you need to query database for a String. To query one object we use 'queryForObject()' method. As 'String' is also an object we used 'queryForObject()'. If you are querying for an Integer you can use 'queryForInt()'. If you are querying multiple rows then you need to use 'query()'. In the above method 'stringRowMapper' will do the mapping of result set to String.<br />
Now the second method to get employee details using employee id. First the query<br />
<pre> SELECT_EMPLOYEE=SELECT emp_id, name, designation FROM employee WHERE emp_id=?
</pre>
Code to execute this query<br />
<pre> public EmployeeDTO getEmployeeDetails(final int empId) throws SQLException {
return queryForObject(empMapper, resources, "SELECT_EMPLOYEE", empId);
}
</pre>
Its almost similar to the first method except two changes, the first parameter - row mapper and third parameter - the query key. We need to write the code to map employee information to an Object of type 'EmployeeDTO'. This DTO is just a plain java bean with all the needed fields and getter/setter methods for them.<br />
<pre> public class EmployeeDTO {
private int empId;
private String name, designation;
public void setEmpId(final int empId) {
this.empId = empId;
}
public int getEmpId() {
return empId;
}
// other setter/getter methods
}
</pre>
Now the row mapping code, all the row mapper classes must be instances of 'RowMapper' interface, which is declared in 'GenericMappers' class.<br />
<pre> private static final RowMapper<EmployeeDTO> empMapper = new RowMapper<EmployeeDTO>() {
public EmployeeDTO mapRow(ResultSet rs) throws SQLException {
EmployeeDTO dto = new EmployeeDTO();
dto.setEmpId(rs.getInt(1));
dto.setName(rs.getString(2));
dto.setDesignation(rs.getString(3));
return dto;
}
};
</pre>
Simple isn't it!. Now the last one to get list of employees. Each employee is represented by EmployeeDTO, we'll use the same row mapper declared above.<br />
<pre> SELECT_ALL_EMPLOYEES=SELECT emp_id, name, designation FROM employee
</pre>
<pre> public List<EmployeeDTO> getEmployees() throws SQLException {
return query(empMapper, resources, "SELECT_ALL_EMPLOYEES");
}
</pre>
All the three method are single line methods. Code looks really simple and clean. Complete code is give below.<br />
MyDAO.properties<br />
<pre> SELECT_NAME=SELECT name FROM employee WHERE emp_id=?
SELECT_EMPLOYEE=SELECT emp_id, name, designation FROM employee WHERE emp_id=?
SELECT_ALL_EMPLOYEES=SELECT emp_id, name, designation FROM employee
</pre>
MyDAO.java<br />
<pre> import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import com.rakesh.common.db.BaseDAO;
import com.rakesh.common.db.util.GenericMappers;
import com.rakesh.common.db.util.GenericMappers.RowMapper;
import com.rakesh.common.util.ClassResources;
public class MyDAO extends BaseDAO {
private static final ClassResources resources = new ClassResources(
MyDAO.class);
public MyDAO(DataSource ds) {
super(ds, true);
}
public String getEmployeeName(final int empId) throws SQLException {
return queryForObject(GenericMappers.stringRowMapper, resources,
"SELECT_NAME", empId);
}
public EmployeeDTO getEmployeeDetails(final int empId) throws SQLException {
return queryForObject(empMapper, resources, "SELECT_EMPLOYEE", empId);
}
public List<EmployeeDTO> getEmployeeList() throws SQLException {
return query(empMapper, resources, "SELECT_ALL_EMPLOYEES");
}
private static final RowMapper<EmployeeDTO> empMapper = new RowMapper<EmployeeDTO>() {
public EmployeeDTO mapRow(ResultSet rs) throws SQLException {
EmployeeDTO dto = new EmployeeDTO();
dto.setEmpId(rs.getInt(1));
dto.setName(rs.getString(2));
dto.setDesignation(rs.getString(3));
return dto;
}
};
}
</pre>
Now if you have a situation where you need to execute multiple quries, using 'queryXXX()' methods will result one connection for each method call. This is not good, to solve this we need to use Transactions, which will allow you to use one connection for all the queries. Sample code block looks like the one below<br />
<pre> <b class="greenText">TransactionManager trans = TransactionManager.start();</b>
try {
// execute all queries
queryForInt(...);
query(...);
update(...);
<b class="greenText">trans.commit();</b>
} catch (Exception e) {
<b class="greenText">trans.rollback();</b>
// do rest of the work
} finally {
<b class="greenText">trans.finished();</b>
}
</pre>
If you are using DAO object in a Servlet based web application, instead of creating DAO objects in "doGet() OR doPost()" methods, you can create DAO objects in "init()" method and keep the reference in the servlet. Use this reference in "doXXX()" methods. By doing this you can restrict DAO object instances/references.<br />
If you are using DAO objects in Struts based web application, instead of creating DAO objects in "execute()" method, you can override the method "setServlet()", this method will be called twice in struts action class life cycle - When it creates action class instance and when it destroys action class instance. The difference - the parameter. It takes one parameter 'ActionServlet' instance. When the "setServlet()" gets called while creating action instance, this parameter will be a not null, and null in other case. You can have an 'if' condition and create DAO object first time. Example code might look like the one below<br />
<pre> public void setServlet(ActionServlet servlet) {
super.setServlet(servlet);
if (servlet != null) {
// create DAO instance
} else {
// assign null to DAO object and remove reference.
}
}
</pre>
That is all I've! My intention writing these classes is not to provide any solution, but to help those beginners and those who are coding small assignments using JDBC. And also to show, how we can eliminate redundant code like connection management, statement creation, parameter setting, execution, mapping result set to objects, etc. I hope it helps few people who are looking out for some information in this regard.<br />
Please find the links to download the source code and Java documentation for those classes below<br />
<b><a href="http://sattvah.com/im-blog/examples/dao-api/dao-api.rar" rel="nofollow" target="_blank">Download Source Code</a></b><br />
<b><a href="http://sattvah.com/im-blog/examples/dao-api/dao-api.jar" rel="nofollow" target="_blank">Download Jar file</a></b><br />
<b><a href="http://sattvah.com/im-blog/examples/dao-api/doc.rar" rel="nofollow" target="_blank">Download Java Documentation</a></b><br />
Right click on the above links and select Save Target As/Save Link As options.<br />
Do drop a note, I'd love to see what you think about my effort!</div>
</div>
</div>
Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com2tag:blogger.com,1999:blog-5428401397473577881.post-4335712504010769182009-10-16T12:32:00.011+05:302011-12-22T17:08:41.448+05:30Hosting Multiple Domains In Tomcat<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
<a href="http://tomcat.apache.org/tomcat-5.5-doc/index.html" rel="nofollow" target="_blank"><b>Tomcat</b></a> allows us to host multiple domains in one instance, using multiple '<b class="greenText">Host</b>' tags. In this article I will explain how to do it on Tomcat. This is very simple configuration using '<b class="greenText">Host</b>' tags in your <span class="greenText">server.xml</span>. A novice can also understand this configuration very easily.<br />
Before going into the details of the configuration first lets have a look at the '<b class="greenText">Host</b>' tag, '<b class="greenText">Context</b>' tag and '<b class="greenText">Alias</b>' tags first.<br />
<pre> <Host name="domain1" appBase="[application base]" autoDeploy="[true/false]"
unpackWARs="[true/false]">
<Alias>...</Alias>
<Context path="" docBase="" reloadable="[true/false]"/>
</Host>
</pre>
<div class="fullpost">
First lets have a look at '<b>Alias</b>' tag. This tag is used to provide aliases for your actual domain. For example you have a domain called 'domain1.com', and you want to run the same application for 'www.domain1.com' also, then you can use this 'Alias' tag to provide an alias name for the actual domain.<br />
<pre> <Host name="domain1.com" ...>
<Alias>www.domain1.com</Alias>
<Alias>domain1.net</Alias>
<Alias>www.domain1.net</Alias>
...
</Host>
</pre>
As you can see in the above example, if you want to have multiple aliases you can add multiple 'Alias' tags for each domain alias name.<br />
Now lets move on to the '<b>Context</b>' tag. The 'Context' element represents a web application running inside a host. To explain this in an easy way; each directory under 'webapps' directory of your tomcat is one context. Manager and Admin consoles of your tomcat installation are two different contexts running under your 'localhost' domain. <br />
<pre> <Context path="" docBase="" reloadable="[true/false]"/>
</pre>
In the above code snippet I've provided minimum configuration needed for a context. Lets go through the attributes of 'Context' tag.<br />
'<b>path</b>' attribute - here we need to give the relative URL [to the host URL in which this Context is being configured] of the context. Say you want to run the application from "domain.com/beta" then the 'path' attribute needs to be "/beta".<br />
'<b>docBase</b>' - the Document Base directory. Here we need to give the root directory for this context. This can be an absolute path to the directory/WAR file OR relative to the 'appBase' given in the 'Host' tag. If the context root directory is inside the 'appBase' directory of the 'Host' tag then we can give it as <br />
<pre> docBase="."
</pre>
'<b>reloadable</b>', it defaults to 'false'. If you give 'true' to this value, tomcat looks for changes in the 'WEB-INF/classes' or 'WEB-INF/lib' directory and reloads the context automatically. This will useful in development environment, so that a new deployment doesn't result restarting tomcat. But on production server its better to leave the default value as setting it to true results an overhead on the server.<br />
Now the '<b>Host</b>' tag - it represents a host [also called as Virtual Host] running, associated with a domain name in the server. We can have multiple 'Host' tags to host multiple domains in one tomcat. Lets see the attributes.<br />
<pre> <Host name="domain1" appBase="[application base]" autoDeploy="[true/false]"
unpackWARs="[true/false]">
...
<Host/>
</pre>
'<b>name</b>' - Domain Name attribute. Here we need to give the domain name which you are trying to host/deploy.<br />
'<b>appBase</b>' - Application Base Directory attribute. Here we need to give the root directory for this application which contains web applications to be deployed on this host. It can be either an absolute path to the directory OR relative to the 'CATALINA_BASE' directory.<br />
'<b>autoDeploy</b>' - flag to denote newly placed web applications should be deployed automatically. If this attribute is set to true and you place a WAR file OR a Web application directory in 'appBase' then tomcat automatically deploys the application.<br />
'<b>unpackWARs</b>' - if set to true Tomcat will automatically unpack the WAR files placed in to corresponding directory structure.<br />
Now lets look at the configuration to host multiple domains.<br />
<pre> <Engine defaultHost="domain1.com" name="Catalina">
<Host name="<b class="greenText">domain1.com</b>" appBase="/home/user1/domain1">
<Alias>www.domain1.com</Alias>
<Context path="" docBase="."/>
</Host>
<Host name="<b class="greenText">domain2.com</b>" appBase="/home/user1/domain2">
<Alias>www.domain2.com</Alias>
<Context path="" docBase="."/>
</Host>
<Host name="<b class="greenText">domain3.com</b>" appBase="/home/user1/domain3">
<Alias>www.domain2.com</Alias>
<Context path="" docBase="."/>
</Host>
</Engine>
</pre>
In the above configuration we tried to host three domains in Tomcat. We added three 'Host' tags one for each domain we wanted to host. Each domain points to a different ['appBase'] directory [I used absolute paths for 'appBase' attribute, it can be relative to CATALINA_BASE].<br />
That's it for now!<br />
<b>Reference URLs</b><br />
<ul>
<li><a href="http://tomcat.apache.org/tomcat-5.5-doc/index.html" rel="nofollow" target="_blank">Tomcat 5.5 Dcoumentation Reference</a></li>
<li><a href="http://tomcat.apache.org/tomcat-5.5-doc/config/host.html" rel="nofollow" target="_blank">Host Tag Reference</a></li>
<li><a href="http://tomcat.apache.org/tomcat-5.5-doc/config/context.html" rel="nofollow" target="_blank">Context Tag Reference</a></li>
</ul>
</div>
</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com15tag:blogger.com,1999:blog-5428401397473577881.post-1327728403258091612009-10-10T19:03:00.008+05:302011-12-22T17:09:03.668+05:30String manipulation in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
One topic most of the developers in early days of their career overlook while programming is <b class="greenText">STRING MANIPULATION</b>. This article will throw some light on this topic, so that one can make habit of some efficient coding. I am going to give some insight into Java string manipulation and some better ways to do string manipulation.<br />
<div class="fullpost">
In Java String objects are immutable, what it means is once you create a String object in Java, it can not be changed/modified. For example look at the following code.<br />
<pre> String a = "A String Object";
a = "Second String Object";
</pre>
In the above code, we created a String object 'a' at line#1 with the value "A String Object", and in line#2 we tried to change the value of the object 'a' to "Second String Object". As I mentioned little earlier, when you create a String object in Java, it can not be changed. In line#2 when you try to change the value of object 'a', JVM [Java Virtual Machine] will create a new String object with the new value and assign its reference to object 'a', and the old reference will be marked for garbage collection.
Let's look at another piece of code.<br />
<pre> String a = "A String Object, ";
a = a + "created in Java";
</pre>
It looks almost similar to the first piece of code. Difference is after creating a String object at line#1, at line#2 - we tried to append another string "created in Java" to the existing one. Obviously result we expected is "A String Object, created in Java". Internally what JVM does is it creates a new Java object with the new appended string and assigns its reference to object 'a', old references will be marked for garbage collection.<br />
This cost of this string manipulation [above pieces of code] might look negligible to any one, but think about an application with pieces of code like the one above spread all over its source. Think how many String objects gets created and marked for garbage collection at one run. This all results to many CPU cycles allocated for creation of String objects and garbage collecting unreferenced String Objects.<br />
Now let's look at one way of doing String manipulation in a better way. Java provides two classes which allow you to modify String values.<br />
<ul>
<li><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html" rel="nofollow" target="_blank">StringBuilder</a></li>
<li><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html" rel="nofollow" target="_blank">StringBuffer</a></li>
</ul>
<b class="greenText">These two objects are almost same with only one difference. StringBuilder class is unsynchronized, where are StringBuffer is synchronized. In short StringBuffer is thread safe, where as StringBuilder is not</b>. We can use these classes to do String manipulation efficiently in our code. When to use StringBuilder and when to use StringBuffer? Answer to this question is when your code is accessed by single thread at any time then it is better to use StringBuilder, which gives better performance in this scenario. And when your code is accessed by multiple threads then you need to use StringBuffer because its thread safe.<br />
Now lets look at an example using one of these classes. Think of a situation where you have String objects representing parts of address of one user/company or something like that. Think that you've four String objects 'streetAddress', 'city', 'state', and 'country' with values initialized properly, and you want to generate one String with all these values. For example if the above mentioned objects are initialized as given below,<br />
<pre> streetAddress = "Plot#10, Road#7";
city = "Hyderabad";
state = "Andhrapradesh";
country = "India";
</pre>
And you want to have a composite string like "Plot#10, Road#7, Hyderabad, Andhrapradesh, India". One inefficient way of doing is using the overloaded '+' operator like<br />
<pre> streetAddress + "," + city + "," + state + "," + country
</pre>
Now the better way using StringBuilder class is<br />
<pre> StringBuilder sb = new StringBuilder();
sb.append(streetAddress).appent(',').append(city).append(',')
.append(state).append(',').append(country);
</pre>
Most common place where developers can improve string manipulation related code is JSP pages. If you take the above example, to print the address, some developers code it like<br />
<pre> <%=streetAddress + "," + city + "," + state + "," + country %>
</pre>
In a JSP page one object [instance of JSPWriter, 'out' object available on a JSP] will already be created to generate the output. If you write code which is similar to the one above, JVM creates unnecessary String objects for each of the '+' operator you use. After reading this article till this point you can think of using StringBuilder/StringBuffer, but that might not be the correct way to do it. Why?, as I mentioned above there will be one object 'out' created already, creating another StringBuilder/StringBuffer object doesn't make sense. Then obvious solution is to use the 'out'. You can write something like the one below to generate the address string.<br />
<pre> <%=streedAddress%>, <%=city%>, <%=state%>, <%=country%>
</pre>
If you think the above code makes the JSP look little complex, then you can write a static method to do the job for you. This method can take the 'out' object [JSPWriter instance] and the values to be appended. In that method you can call the 'append()' method on JSPWriter object 'out' to append the values.<br />
That is all I have for now, about String manipulation. Hope it helps some guys to do some efficient coding.<br />
<b class="greenText">HAPPY CODING!</b><br />
<a class="hide" href="http://technorati.com/claim/w5y4hx8ird">Technorati Profile</a>
</div>
</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com3tag:blogger.com,1999:blog-5428401397473577881.post-31098616427676950622009-10-09T14:53:00.006+05:302011-12-22T17:09:28.503+05:30Simple Accordion using Java Script and CSS<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
Well you can find many online, but it's difficult to find one with out any dependent API. Most of the available accordions use other APIs for animation and other stuff. For those who just want accordion with out any other stuff, this one is the perfect one. It's very simple and you don't have to be a geek to understand it. Basic knowledge of Java script and CSS will do to understand how this works. In this article I'll take you through the steps of developing an accordion. Couple of minutes you are ready to write your own. Well then let's start developing one.<br />
<br />
<div class="fullpost">
Layout of the HTML block looks something like the one below<br />
<div class="img_container">
<img alt="Layout" src="http://sattvah.com/im-blog/examples/layout.png" style="text-align: center;" /></div>
Lets look at the CSS first which is very simple.<br />
<pre>/** container styles **/
.ra-p, .ra-cp {
padding: 0 0 0.1em;
}
/**** heading styles ****/
.ra-p h2, .ra-cp h2 {
margin: 0px;
padding: 0.2em;
cursor: pointer;
color: #fff;
background-color: #3d80b0;
}
/**** collapsed heading styles ****/
.ra-cp h2 {
Background-color: #3d80b0;
}
/**** content styles *****/
.ra-p .text, .ra-cp .text { overflow: hidden; }
/**** hide collapsed content ****/
.ra-cp .text { display: none; }</pre>
This all you need. Lets go through it.<br />
First you've '.ra-p' and '.ra-cp' which are applied to the container ['ra-p' for expanded one, 'ra-cp' for collapsed one]. Then we've styles for the heading/title, 'ra-p h2', 'ra-cp h2'. As we are going to use 'h2' as heading tags we've styles for 'h2'. Finally we've styles for the content block, '.ra-p .text' and '.ra-cp .text'.<br />
And now we'll go through the java script need for it.<br />
<pre>Accordion = function(el, delay, steps) {
if (!el) {
alert('Element required to make it a Accordion.');
return;
}
this.init(el, delay, steps);
}
</pre>
This code block is self explanatory. This is a constructor which initializes an Accordion. It takes three parameters.<br />
<ul>
<li>el - The element [block which need to work as an accordion].</li>
<li>delay - Time delay in animating the accordion.</li>
<li>steps - Number of steps for the animation.</li>
</ul>
First it checks whether the element is available, if not then gives an alert message and returns. If the element exists then continues by calling the 'init()' method. Before looking into the 'init()' method, lets add some supportive methods needed by the code.<br />
For convention I am going to use '_' as prefix to the method names which are internal to the code, so that you can easily identify which methods are internal and which are available for external code. We need<br />
<ul>
<li>A method to check for applied CSS styles.</li>
<li>A method to get individual elements from the block which works as Accordion.</li>
<li>A method to calculate step height for animation.</li>
</ul>
First lets see the method to check for applied CSS styles.<br />
<pre>_hasClass : function(c, className) {
return c.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}
</pre>
As this is an internal method it is prefixed with '_' as mentioned little earlier. It takes two parameters.<br />
<ul>
<li>The html tag element/node for which we need to check for applied styles.</li>
<li>The CSS class name.</li>
</ul>
This method uses Regular Expression to check CSS styles applied for efficiency. The regular expression used is "new RegExp('(\\s|^)' + className + '(\\s|$)')". In this regular expression '\s' denotes any white-space character, '|' is for alternation [logical OR], '^' is to match for string starting, and the CSS class name we wanted to check for [method parameter 'className'], followed by any white-space character '\s', '|' for alternation [logical OR], and '$' to math for end of string.<br />
I think this explanation gives you good idea how the regular expression works. Now if we see the one line in the method '_hasClass' it uses the DOM attribute 'className' to get the applied CSS classes to the element passed and uses regular expression to find matches. If it finds a match then it returns true, false otherwise.<br />
The next method we have is the one to get elements from an html block [method to get matching child element from the given container element]. Let's name it as '_getElement'.<br />
<pre>_getElement : function(parent, childTag, className) {
var elements = this.el.getElementsByTagName(childTag);
if (!className)
return elements[0];
for (var i=0; i < elements.length; i++) {
if (this._hasClass(elements[i], className))
return elements[i];
}
}
</pre>
This method takes three parameters.<br />
<ul>
<li>The parent/container element in which we are going to look for matching child elements.</li>
<li>The type of the child tag we need to look for.</li>
<li>CSS class name, which is applied to the child tag we are looking for.</li>
</ul>
If we do not pass any CSS class then, this method return the first element matching the given child tag type. We use 'getElementsByTagName ()' method which takes the tag type to be looked for and returns all the matching child tags as an array.<br />
After we get the array of matching child tags, we loop through them and check each element, whether it has the given CSS class applied to it. When it finds a match it returns the element.<br />
Now we need a method to calculate the step height for animation of accordion, let's name it as '_getStepHeight'<br />
<pre>_getStepHeight : function () {
// make sure the content is visible before getting its height
this.contentEl.style.display = "block";
// get the height of the content
var contentHeight = this.contentEl.offsetHeight;
return (contentHeight / this.steps);
},
</pre>
This method is very simple; first it gets the height of the block [accordion block] and divides it by the number of steps. To get the height of the block, first we set the 'display' attribute of it to 'block' so that we get the proper height even if the block is in closed status. <br />
Now lets move on to the 'init()'method.<br />
<pre>init : function(el, delay, steps) {
/** Accordion element**/
this.el = el;
/** Accordion heading tag - mouse events will be attached to this tag **/
this.headingTag = "h2";
/** delay for each step of animation **/
this.delay = delay;
/** no.of animation steps **/
this.steps = steps;
/** CSS classes of container and heading panels **/
this.panelClass = "ra-p";
this.cPanelClass = "ra-cp";
this.textClass = "text";
/** attach mouse click events **/
if (this._hasClass(el, this.panelClass)) {
this.contentEl = this._getElement(el, "div", this.textClass);
this.headerEl = this._getElement(el, "h2");
/** calculate animation step size **/
this.stepHeight = this._getStepHeight();
if (this.contentEl && this.headerEl) {
var panel = this;
this.headerEl.onclick = function() {
panel.animateToggle(panel);
};
}
}
}
</pre>
Most part of this method is just initialization of variables. First half of the method we'll initialize variables used for accordion animation. Important part is the one where we add mouse click event to the block heading. Before adding mouse event to the heading we verify that the container had the necessary CSS ['ra-p' in this case] applied to it. You can see these values initialized in the first half of the method. <br />
Then we'll get the content block element reference and keep its reference ['contentEl' variable], and we'll get the heading element reference ['headerEl' variable]. After this we'll calculate the step height [height in pixels for each step of animation] for animation.<br />
Before proceeding to add mouse click event, we'll verify both content element and header elements are available, finally we'll add mouse click event handler and attaché 'animateToggle ()' method. That's it we are almost done with this. Only thing we are left with is the 'animateToggle ()' method, lets see what it has.<br />
<pre>animateToggle : function(panel) {
// check if you are in the middle of an operation
if (this.key) {
clearInterval(this.key);
this.key = null;
}
// make sure the content is visible before getting its height
this.contentEl.style.display = "block";
var expanding = panel._hasClass(this.el, this.cPanelClass);
// if panel is collapsed and expanding, we must start with 0 height
if (expanding)
panel.contentEl.style.height = "0px";
this.iteration = 1;
this.key = setInterval(function(){panel._animate(panel, expanding)}, panel.delay);
}
</pre>
Surprisingly nothing complex here!; first we'll check whether we are in the middle of an existing opration [expanding/collapsing], if we are, then we'll stop it by calling 'clearInterval()' method and continue with the current one.<br />
Then we'll make sure that the content block is visible by setting its 'display' property to 'block', and then see whether we're expanding the block or collapsing it by checking CSS style applied to it. If it has 'ra-p' then block is expanded and we need to collapse it, expand otherwise. If we're expanding set the content block's height to '0px' and start increasing its height. To increase the height step by step we'll call an internal function '_animate()' repeatedly after specific delay using 'setInterval()' method. 'setInterval()' method is available in java script which can be used to call a method repeatedly after some delay until we call it to stop, using 'clearInterval()'.<br />
Lets see what '_animate()' method has in it.<br />
<pre>_animate : function (panel, expanding) {
if (panel.iteration < panel.steps) {
panel.contentEl.style.height = Math.round(
((expanding) ? panel.iteration :
panel.steps - panel.iteration) * panel.stepHeight) +"px";
panel.iteration++;
} else {
// set class for the panel
panel.el.className = (!expanding) ? panel.cPanelClass : panel.panelClass;
// clear inline styles
panel.contentEl.style.display = panel.contentEl.style.height = "";
// stop animation
clearInterval(this.key);
this.key = null;
}
}
</pre>
At the beginning we specified the number of steps for the animation and this is what we use to stop animation. Fist we check whether the iteration is less that number of steps. If yes we'll proceed with increasing/decreasing the height of the content block. Else we'll reset the CSS styles for the content block and stop animation.<br />
You can download the complete code using the link bellow. <a href="http://sattvah.com/im-blog/examples/simple-accordion.html" rel="nofollow" target="_blank">Click here</a>.<br />
This post might look lengthy, but when you see the code, it's very small and light in size. Hope it's useful for some folks out there looking for similar code.<br />
By the way it's my first posting, I'd love to get some feedback. Do drop a note!</div>
</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com0tag:blogger.com,1999:blog-5428401397473577881.post-19270464205358539972009-10-09T04:20:00.003+05:302011-12-22T17:10:10.604+05:30About Rakesh.A<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="content">
<img alt="Rakesh Reddy" class="profile-img" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcKcyY2QM3YBfgDWXugc0SQc4vDcM0ER7KpAYdc5fwCije-UVIDlB_fjUWh3xWpXOk2dmS_wXblXTaA3OFVBXfNXNj7hj9QT7TBfcwVO5uA2ExQCcntpA4GfolukRfTGx95sv50mp8_Tg/s220/m2-too.jpg" /> <br />
As the URL and other parts of this blog says, I am <b class="greenText">Rakesh.A</b>, a techie form Hyderabad, India. I am working for coMakeIT, Hyderabad as a Sr. Software Engineer, that's about me in short.<br />
<div class="fullpost">
How I ended up in this profession? - Well when I was doing my schooling I never thought I'll be into this profession, infact I wasn't that interested in Information Technology/Software Development, so never concentrated on it even after my parents stressed to get into it. After couple of years, I saw myself doing the same. And now I can't even think of myself being in a different profession. <span class="greenText">Anything I can do with whole heart, that's only PROGRAMMING/DEVELOPMENT</span>.<br />
As every student who got into this profession, I felt my FIRST LOVE with 'C language', and I love coding in C. Then I started learning Object Oriented Programming and got attracted to 'C++ language', but it was '<b class="greenText">JAVA</b>' in which I saw my soul mate. That's it I got married to it and settled. I've been working on various Java Technologies since I started my career, and <b class="greenText">I love to program in Java</b>. When ever I develop an application, I feel like an Artist marvel about his Art work, funny right :), but that's how I feel.<br />
After being into this profession for couple of years, I learnt great deal of things from great people I worked with, and then one day I thought why can't I share this knowledge to others, and be helpful to those who need it!.<br />
I actually have big ideas for this concept, but couldn't find time to fulfill it, so as an initiation towards what I dreamt, I started this blog. I'll be posting about things I learnt about efficient programming to other related things like Web/App servers, build scripts, etc. In short all the things I know, and I learnt. Hope this blog helps few people who are looking for it.<br />
Now so much about technical things, apart from Programming/Development, I love reading books, and love playing Badminton, and Cricket. I spend most of my time at home - reading, coding, watching TV and occasionally get into kitchen :), I don't like to go out and have fun, but I love to go to movies with friends. My favorites - God Father, Lord of the Rings trilogies, Good Fellas, Galdiator... list goes on!</div>
</div>
</div>Rakesh Ahttp://www.blogger.com/profile/06781829337151947902noreply@blogger.com10