<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" ><channel><title>ViralPatel.net &#187; Java</title> <atom:link href="http://viralpatel.net/blogs/category/java/feed" rel="self" type="application/rss+xml" /><link>http://viralpatel.net/blogs</link> <description>Tutorials, Java, J2EE, Struts, AJAX, JavaScript, CSS, Web 2.0, MySQL, Articles</description> <lastBuildDate>Tue, 24 Jan 2012 13:45:10 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <item><title>Convert Arrays to Set in Java</title><link>http://viralpatel.net/blogs/2012/01/convert-array-to-set-java-arraylist.html</link> <comments>http://viralpatel.net/blogs/2012/01/convert-array-to-set-java-arraylist.html#comments</comments> <pubDate>Tue, 24 Jan 2012 13:45:10 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[arraylists]]></category> <category><![CDATA[java collections]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2655</guid> <description><![CDATA[Java Collection API is one of the most useful APIs used in any Java application. In my day to day Java coding routine, I have to deal with these APIs quite often. However sometime while working with Collection API, lot of developers end up writing unnecessary and mostly inefficient code. For example, to convert an [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/java-logo1.gif" alt="java-logo" title="java-logo" width="100" height="160" class="alignright size-full wp-image-620" />Java Collection API is one of the most useful APIs used in any Java application. In my day to day Java coding routine, I have to deal with these APIs quite often.</p><p>However sometime while working with Collection API, lot of developers end up writing unnecessary and mostly inefficient code. For example, to convert an <strong>Java Array to ArrayList</strong>, I have seen people writing loops instead of simple <code>Arrays.asList()</code>.</p><p>Here is a simple writeup on <a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html"><strong>Converting Java Arrays to ArrayList</strong></a> that I wrote a while ago.</p><p>One of such simple requirement is to convert Java <strong>Arrays to Set</strong>. While working with Hibernate, I once had to convert a Java Arrays that we used to populate from UI and convert it into <code>Set</code>. While this is a simple task, most often one may end up writing for loop.</p><p>Here is a dead simple trick. Use below code to <strong>Convert Arrays to Set</strong> in Java.</p><pre class="brush: java; gutter: false; title: ; notranslate">
Set&lt;T&gt; mySet = new HashSet&lt;T&gt;(Arrays.asList(someArray));
</pre><p>Tanaa!!! Simple isn&#8217;t it. Its like <em>&#8220;I already knew that&#8221;</em> stuff.</p><p>Notice how we have used Generics also in above code snippet. Thus if you have an <code>ArrayList<Foo></code> than you can convert it to Set<Foo> with one simple line of code.</p><p>Checkout below example:</p><h3>Example: Java Array to Set</h3><pre class="brush: java; title: ; notranslate">
String [] countires = {&quot;India&quot;, &quot;Switzerland&quot;, &quot;Italy&quot;}; 

Set&lt;String&gt; set = new HashSet&lt;String&gt;(Arrays.asList(countires));
System.out.println(set);
</pre><p><strong>Output:</strong></p><pre class="brush: plain; gutter: false; title: ; notranslate">
[Italy, Switzerland, India]
</pre><p>Hope this is useful.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html" title="Convert ArrayList to Arrays in Java">Convert ArrayList to Arrays in Java</a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-tip-how-to-sort-array-in-java-java-util-arrays.html" title="Java Tip: How to Sort Arrays in Java using java.util.Arrays class">Java Tip: How to Sort Arrays in Java using java.util.Arrays class</a></li><li><a href="http://viralpatel.net/blogs/2011/12/spring-mvc-multi-row-submit-java-list.html" title="Spring MVC: Multiple Row Form Submit using List of Beans">Spring MVC: Multiple Row Form Submit using List of Beans</a></li><li><a href="http://viralpatel.net/blogs/2011/01/java-convert-exponential-decimal-double-number.html" title="Java: Convert Exponential form to Decimal number format in Java ">Java: Convert Exponential form to Decimal number format in Java </a></li><li><a href="http://viralpatel.net/blogs/2010/10/convert-string-to-enum-instance-string-enum-java.html" title="Convert String to Enum Instance in Java">Convert String to Enum Instance in Java</a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html" title="Calculate Free Disk Space in Java using Apache Commons IO">Calculate Free Disk Space in Java using Apache Commons IO</a></li><li><a href="http://viralpatel.net/blogs/2010/02/generate-pie-chart-bar-graph-in-pdf-using-itext-jfreechart.html" title="Generate Pie Chart/Bar Graph in PDF using iText &#038; JFreeChart">Generate Pie Chart/Bar Graph in PDF using iText &#038; JFreeChart</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/01/convert-array-to-set-java-arraylist.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>How To Create QR Codes in Java &amp; Servlet</title><link>http://viralpatel.net/blogs/2012/01/create-qr-codes-java-servlet-qr-code-java.html</link> <comments>http://viralpatel.net/blogs/2012/01/create-qr-codes-java-servlet-qr-code-java.html#comments</comments> <pubDate>Mon, 16 Jan 2012 17:04:11 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[android]]></category> <category><![CDATA[java code]]></category> <category><![CDATA[QR Code]]></category> <category><![CDATA[servlet]]></category> <category><![CDATA[Servlets]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2621</guid> <description><![CDATA[Nowadays, Quick Response (QR) Codes are becoming more and more useful as they have gone mainstream, thanks to the smart phones. Right from the bus shelter, product packaging, home improvement store, automobile, a lot of internet websites are integrating QR Codes on their pages to let people quickly reach them. With increase in number of [...]]]></description> <content:encoded><![CDATA[<p>Nowadays, Quick Response (QR) Codes are becoming more and more useful as they have gone mainstream, thanks to the smart phones. Right from the bus shelter, product packaging, home improvement store, automobile, a lot of internet websites are integrating QR Codes on their pages to let people quickly reach them. With increase in number of users of smart phones day by day, the QR codes usage is going up exponentially.</p><p>Let us see a quick overview of Quick Response (QR) codes and also how to generate these codes in Java.</p><h2>Introduction to QR Codes</h2><p>A QR code (abbreviated from Quick Response code) is a type of matrix barcode (or two-dimensional code) first designed for the automotive industry. More recently, the system has become popular outside of the industry due to its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of four standardized kinds (&#8220;modes&#8221;) of data (numeric, alphanumeric, byte/binary, Kanji), or by supported extensions virtually any kind of data.</p><p><img src="http://img.viralpatel.net/2012/01/qr-code-viralpatel-net.png" alt="" title="qr-code-viralpatel-net" width="149" height="149" class="aligncenter size-full wp-image-2624" /></p><p>Created by Toyota subsidiary Denso Wave in 1994 to track vehicles during the manufacturing process, the QR code is one of the most popular types of two-dimensional barcodes. It was designed to allow its contents to be decoded at high speed.</p><h2>Hello World QR Code in Java</h2><p><a rel="nofollow" target="_new" href="http://code.google.com/p/zxing/">Zebra Crossing (ZXing)</a> is an awesome open source library that one can use to generate / parse QR Codes in almost all the platforms (Android, JavaSE, IPhone, RIM, Symbian etc). But if you have to generate simple QR Codes, I found it a bit clumsy to implement.</p><p>However <a rel="nofollow" target="_new" href="http://kenglxn.github.com/QRGen/">QRGen</a> is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake. It has a dependency on ZXing, so you would need ZXing jar files along with QRGen to create QR Codes in Java.</p><p>On the download page of ZXing, you will not find the JAR files. Instead we have to create JAR files using the source code. I have already generated these JAR files. Here are the links:</p><p><a href="http://viralpatel.net/blogs/download/jar/zxing-core-1.7.jar">zxing-core-1.7.jar (346 KB)</a><br /> <a href="http://viralpatel.net/blogs/download/jar/zxing-j2se-1.7.jar">zxing-javase-1.7.jar (21 KB)</a></p><p>Also download the QRGen JAR File from their <a rel="nofollow" href="https://github.com/kenglxn/QRGen/blob/master/dist/qrgen-1.0.jar">download page</a>.</p><p>Include these JAR files in your Classpath and execute following Java code to generate QR Code.</p><pre class="brush: java; highlight: [14,15]; title: ; notranslate">
package net.viralpatel.qrcode;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class Main {
	public static void main(String[] args) {
		ByteArrayOutputStream out = QRCode.from(&quot;Hello World&quot;)
										.to(ImageType.PNG).stream();

		try {
			FileOutputStream fout = new FileOutputStream(new File(
					&quot;C:\\QR_Code.JPG&quot;));

			fout.write(out.toByteArray());

			fout.flush();
			fout.close();

		} catch (FileNotFoundException e) {
			// Do Logging
		} catch (IOException e) {
			// Do Logging
		}
	}
}
</pre><p>The code is pretty straight forward. We used <code>QRCode</code> class to generate QR Code Stream and write the byte stream to a file <strong>C:\QR_Code.JPG</strong>.</p><h3>Download Source Code</h3><h4><a rel="nofollow" href="http://viralpatel-net-tutorials.googlecode.com/files/QR_Code_Java.zip">QR_Code_Java.zip (339 KB)</a></h4><p>If you open this JPEG file and scan using your iPhone or Android QR scanner, you&#8217;ll find a cool &#8220;Hello World&#8221; in it <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><p>Apart from generating Sterams of data using QRGen API, we can also use below APIs to create QR Codes:</p><pre class="brush: java; title: ; notranslate">
// get QR file from text using defaults
File file = QRCode.from(&quot;Hello World&quot;).file();
// get QR stream from text using defaults
ByteArrayOutputStream stream = QRCode.from(&quot;Hello World&quot;).stream();

// override the image type to be JPG
QRCode.from(&quot;Hello World&quot;).to(ImageType.JPG).file();
QRCode.from(&quot;Hello World&quot;).to(ImageType.JPG).stream();

// override image size to be 250x250
QRCode.from(&quot;Hello World&quot;).withSize(250, 250).file();
QRCode.from(&quot;Hello World&quot;).withSize(250, 250).stream();

// override size and image type
QRCode.from(&quot;Hello World&quot;).to(ImageType.GIF).withSize(250, 250).file();
QRCode.from(&quot;Hello World&quot;).to(ImageType.GIF).withSize(250, 250).stream();
</pre><h2>Website Link (URLs) QR Code in Java</h2><p>One of the most common use of a QR Code is to bring traffic to a particular webpage or download page of website. Thus QR Code encodes a URL or website address which a user can scan using phone camera and open in their browser. URLs can be straight forward included in QR Codes. In above Java Hello World example, just replace &#8220;Hello World&#8221; string with the URL you want to encode in QR Code. Below is the code snippet:</p><pre class="brush: java; gutter: false; title: ; notranslate">
ByteArrayOutputStream out = QRCode.from(&quot;http://viralpatel.net&quot;)
				.to(ImageType.PNG).stream();
</pre><h2>QR Code in Servlet</h2><p>Most of the time you would need to generate QR Codes dynamically in some website. We already saw how easy it is to generate QR code in Java. Now we will see how to integrate this QR Code generation in a Java Servlet.</p><p>Following is a simple Http Servlet that creates QR Code using QRGen and ZXing library. User provides the text for which QR Code is generated.</p><p>The index jsp file contains a simple html form with a textbox and submit button. User can enter the text that she wishes to generate QR code of and presses submit.</p><p><em>File: index.jsp</em></p><pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;QR Code in Java Servlet - viralpatel.net&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

	&lt;form action=&quot;qrservlet&quot; method=&quot;get&quot;&gt;
		&lt;p&gt;Enter Text to create QR Code&lt;/p&gt;
		&lt;input type=&quot;text&quot; name=&quot;qrtext&quot; /&gt;
		&lt;input type=&quot;submit&quot; value=&quot;Generate QR Code&quot; /&gt;
	&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>The magic happens in <code>QRCodeServlet.java</code>. Here we uses QRGen library along with ZXing and generates QR Code for given text (Text we get from request.getParameter). Once the QR Stream is generated, we write this to response and set appropriate content type.</p><p><em>File: QRCodeServlet.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.qrcodes;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class QRCodeServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String qrtext = request.getParameter(&quot;qrtext&quot;);

		ByteArrayOutputStream out = QRCode.from(qrtext).to(
				ImageType.PNG).stream();

		response.setContentType(&quot;image/png&quot;);
		response.setContentLength(out.size());

		OutputStream outStream = response.getOutputStream();

		outStream.write(out.toByteArray());

		outStream.flush();
		outStream.close();
	}
}
</pre><p>The below web.xml simply maps <code>QRCodeServlet.java</code> with <code>/qrservlet</code> URL.</p><p><em>File: web.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
		xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
		xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
		xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
		id=&quot;WebApp_ID&quot; version=&quot;2.5&quot;&gt;

  &lt;display-name&gt;QR_Code_Servlet&lt;/display-name&gt;
  &lt;welcome-file-list&gt;
    &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
  &lt;/welcome-file-list&gt;

	&lt;servlet&gt;
		&lt;servlet-name&gt;QRCodeServlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;net.viralpatel.qrcodes.QRCodeServlet&lt;/servlet-class&gt;
	&lt;/servlet&gt;
	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;QRCodeServlet&lt;/servlet-name&gt;
		&lt;url-pattern&gt;/qrservlet&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;

&lt;/web-app&gt;
</pre><h3>Download Source Code</h3><h4><a rel="nofollow" href="http://viralpatel-net-tutorials.googlecode.com/files/QR_Code_Servlet.zip">QR_Code_Servlet.zip (340 KB)</a></h4><h3>Output</h3><p><img src="http://img.viralpatel.net/2012/01/qr-code-java-servlet-index.png" alt="qr-code-java-servlet-index" title="qr-code-java-servlet-index" width="370" height="251" class="aligncenter size-full wp-image-2628" /></p><p><img src="http://img.viralpatel.net/2012/01/qr-code-java-servlet-image.png" alt="qr-code-java-servlet-image" title="qr-code-java-servlet-image" width="370" height="251" class="aligncenter size-full wp-image-2630" /></p><p><br/></p><h2>Conclusion</h2><p>Generating QR Codes in Java is not only easy, but quite straight forward. Integrating this functionality with any existing Java based app is just a piece of cake! In this tutorial we saw how to generate these QR codes in Java and also with Servlet.</p><p>Hope you&#8217;ll like this <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/08/jsp-servlet-session-listener-tutorial-example-in-eclipse-tomcat.html" title="JSP Servlet Session Listener tutorial example in Eclipse &#038; Tomcat">JSP Servlet Session Listener tutorial example in Eclipse &#038; Tomcat</a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html" title="Calculate Free Disk Space in Java using Apache Commons IO">Calculate Free Disk Space in Java using Apache Commons IO</a></li><li><a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html" title="Convert ArrayList to Arrays in Java">Convert ArrayList to Arrays in Java</a></li><li><a href="http://viralpatel.net/blogs/2009/06/double-brace-initialization-in-java.html" title="Double Brace Initialization in Java!">Double Brace Initialization in Java!</a></li><li><a href="http://viralpatel.net/blogs/2009/05/varargs-in-java-variable-argument-method-in-java-5.html" title="Varargs in Java: Variable argument method in Java 5">Varargs in Java: Variable argument method in Java 5</a></li><li><a href="http://viralpatel.net/blogs/2009/05/20-useful-java-code-snippets-for-java-developers.html" title="20 very useful Java code snippets for Java Developers">20 very useful Java code snippets for Java Developers</a></li><li><a href="http://viralpatel.net/blogs/2009/04/http-proxy-setting-java-setting-proxy-java.html" title="HTTP Proxy setting in Java. Setting up proxy.">HTTP Proxy setting in Java. Setting up proxy.</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/01/create-qr-codes-java-servlet-qr-code-java.html/feed</wfw:commentRss> <slash:comments>6</slash:comments> </item> <item><title>Hibernate Hello World example using Annotation</title><link>http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html</link> <comments>http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html#comments</comments> <pubDate>Wed, 09 Nov 2011 12:39:16 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[annotation]]></category> <category><![CDATA[apache maven]]></category> <category><![CDATA[hibernate-orm]]></category> <category><![CDATA[maven]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[Tutorial]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2197</guid> <description><![CDATA[In this tutorial we will write a CRUD application in Hibernate using Java 5 Annotation. For this we will use our previous tutorial Hibernate Maven MySQL hello world example (XML Mapping) as base and convert it from XML Mapping to Annotation. Tools and Technologies used: Java JDK 5 or above Eclipse IDE 3.2 or above [...]]]></description> <content:encoded><![CDATA[<p>In this tutorial we will write a CRUD application in Hibernate using Java 5 Annotation. For this we will use our previous tutorial <a target="_new" href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html">Hibernate Maven MySQL hello world example (XML Mapping)</a> as base and convert it from XML Mapping to Annotation.<br /><style>#hibernate_tutorial_list{background-color:#EF9;padding:5px;border-radius:10px;color:#222;width:98%;font-size:90%}#hibernate_tutorial_list ul
li{padding:3px
0px}#hibernate_tutorial_list ul li
li{padding:2px
0px}</style><div id="hibernate_tutorial_list"><h3>Hibernate Tutorial Series</h3><ul><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html">Introduction to Hibernate Framework</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html">Hibernate Maven MySQL Hello World example (Annotation)</a></li><li>Understanding Relationship Mapping<ul><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html">One To One Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation">One To One Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html">One To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html">One To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html">Many To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html">Many To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html">Self-Join One To Many Annotations Mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html">Self-Join Many To Many Annotations Mapping example</a></li></ul></li><li>Inheritance in Hibernate<ul><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html">One Table Per Class Hierarchy (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html">One Table Per Subclass (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html">One Table Per Concrete Class (Annotation & XML mapping)</a></li></ul></li></ul></div></p><p>Tools and Technologies used:</p><ol><li>Java JDK 5 or above</li><li>Eclipse IDE 3.2 or above</li><li>Maven 3.0 or above</li><li>Hibernate 3.0 or above</li><li>MySQL 5.0 or above</li></ol><h2>1. Database Creation</h2><p>For this tutorial, we will create a simple table &#8220;employee&#8221; in MySQL. Use following script to create the table.</p><pre class="brush: sql; title: ; notranslate">
CREATE TABLE `employee` (
    `id` BIGINT(10) NOT NULL AUTO_INCREMENT,
    `firstname` VARCHAR(50) NULL DEFAULT NULL,
    `lastname` VARCHAR(50) NULL DEFAULT NULL,
    `birth_date` DATE NOT NULL,
    `cell_phone` VARCHAR(15) NOT NULL,
    PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=606
</pre><h2>2. Create Project Structure</h2><p>Follow the steps in <a target="_new" href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html">Hibernate Maven MySQL hello world example (XML Mapping)</a> to create project structure.</p><p>Or you can directly download the source code from above tutorial in Eclipse.</p><p><b><a href="">Download: HibernateHelloWorldXML.zip (8 kb)</a></b></p><h2>3. Update Hibernate dependency in Maven pom.xml</h2><p>We are going to use Annotation mapping in Hibernate. Update the maven&#8217;s pom.xml file and add following dependencies.</p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;project&gt;
  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
  &lt;groupId&gt;HibernateCache&lt;/groupId&gt;
  &lt;artifactId&gt;HibernateCache&lt;/artifactId&gt;
  &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
  &lt;description&gt;&lt;/description&gt;
  &lt;dependencies&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
      &lt;artifactId&gt;ejb3-persistence&lt;/artifactId&gt;
      &lt;version&gt;1.0.1.GA&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
      &lt;artifactId&gt;hibernate-annotations&lt;/artifactId&gt;
      &lt;version&gt;3.3.1.GA&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;mysql&lt;/groupId&gt;
      &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
      &lt;version&gt;5.1.10&lt;/version&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;
&lt;/project&gt;
</pre><p>Once we update the Hibernate dependency, run following command in your project folder to update classpath in eclipse to that errors are removed.</p><pre class="brush: xml; title: ; notranslate">
mvn eclipse:eclipse
</pre><p><br/></p><h2>4. Delete unused Employee.hbm.xml</h2><p>The Employee.hbm.xml file under /src/main/java/net/viralpatel/hibernate is no more required. Delete this file from project.</p><h2>5. Update Employee entity</h2><p>The Employee class is simple POJO. We will add Annotations in this class. Update it as follows:</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name=&quot;EMPLOYEE&quot;)
public class Employee {

	@Id
	@GeneratedValue
	private Long id;

	@Column(name=&quot;firstname&quot;)
	private String firstname;

	@Column(name=&quot;lastname&quot;)
	private String lastname;

	@Column(name=&quot;birth_date&quot;)
	private Date birthDate;

	@Column(name=&quot;cell_phone&quot;)
	private String cellphone;

	public Employee() {

	}

	public Employee(String firstname, String lastname, Date birthdate, String phone) {
		this.firstname = firstname;
		this.lastname = lastname;
		this.birthDate = birthdate;
		this.cellphone = phone;

	}

	// Getter and Setter methods
}
</pre><h2>6. Update Hibernate Utility</h2><p>In our previous example, we were using Configuration class to generate SessionFactory object. In HibernateUtil we had following line of code:</p><pre class="brush: java; title: ; notranslate">
return new Configuration()
            		.configure()
                    .buildSessionFactory();
</pre><p>Change this line and use AnnotationConfiguration instead of Configuration(). Replace this line with below code.</p><pre class="brush: java; title: ; notranslate">
// import org.hibernate.cfg.AnnotationConfiguration;

return new AnnotationConfiguration()
            		.configure()
                    .buildSessionFactory();
</pre><p><br/></p><h2>7. Update Hibernate Configuration file</h2><p>The hibernate.cfg.xml configuration file needs to be changed to add the new Annotation based entity class Employee.java instead of old XML Mapping Employee.hbm.xml.</p><p>Open /src/main/resources/hibernate.cfg.xml and replace following line:</p><pre class="brush: xml; title: ; notranslate">
&lt;mapping resource=&quot;net/viralpatel/hibernate/Employee.hbm.xml&quot;/&gt;
</pre><p>Replace above line with following:</p><pre class="brush: xml; title: ; notranslate">
&lt;mapping class=&quot;net.viralpatel.hibernate.Employee&quot;/&gt;
</pre><p><br/></p><h2>8. Review Final Project Structure</h2><p>Review your project structure. It should be like:<br /> <img src="http://img.viralpatel.net/2011/11/hibernate-annotation-hello-wold-project-structure.png" alt="hibernate-annotation-hello-wold-project-structure" title="hibernate-annotation-hello-wold-project-structure" width="262" height="291" class="aligncenter size-full wp-image-2198" /></p><p></br></p><h2>9. Execute project</h2><p>Execute the Main.java class and see output.</p><pre class="brush: java; title: ; notranslate">
******* READ *******
Total Employees: 200
******* WRITE *******
201 Jack Bauer
******* UPDATE *******
Name Before Update:Paula
Name Aftere Update:James
******* DELETE *******
Object:null
</pre><p></br></p><h2>That&#8217;s All Folks</h2><p>Today we saw how to write our first Hibernate hello world example using Annotations. We used Maven to generate Java project and added Hibernate dependencies into it. Also we saw how to do different CRUD operations in Hibernate.</p><h2>Download Source</h2><p><b><a href="http://viralpatel.net/blogs/download/hibernate/HibernateHelloWorldAnnotation.zip">HibernateHelloWorldAnnotation.zip (15 kb)</a></b></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation" title="Hibernate One To One Annotation Mapping Tutorial">Hibernate One To One Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html" title="Hibernate Self Join Many To Many Annotations mapping example">Hibernate Self Join Many To Many Annotations mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html" title="Hibernate One To Many XML Mapping Tutorial">Hibernate One To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html" title="Hibernate One To One Mapping Tutorial (XML Mapping)">Hibernate One To One Mapping Tutorial (XML Mapping)</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>How to iterate HashMap using JSTL forEach loop</title><link>http://viralpatel.net/blogs/2011/04/iterate-hashmap-using-jstl-foreach.html</link> <comments>http://viralpatel.net/blogs/2011/04/iterate-hashmap-using-jstl-foreach.html#comments</comments> <pubDate>Fri, 01 Apr 2011 07:41:53 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[How-To]]></category> <category><![CDATA[JSP]]></category> <category><![CDATA[jstl]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2175</guid> <description><![CDATA[JavaServer Tag library is one of the most used JSP tag library out there. I have used it almost in all of my JEE based projects. The best feature probably is the Iterator API in JSTL tag library. Here is a small code snippet which you might not know. Its very easy to iterate Lists [...]]]></description> <content:encoded><![CDATA[<p>JavaServer Tag library is one of the most used JSP tag library out there. I have used it almost in all of my JEE based projects. The best feature probably is the Iterator API in JSTL tag library.</p><p>Here is a small code snippet which you might not know. Its very easy to iterate Lists using JSTL. For example:</p><pre class="brush: java; title: ; notranslate">
//Java
List&lt;String&gt; cityList = new ArrayList&lt;String&gt;();
cityList.add(&quot;Washington DC&quot;);
cityList.add(&quot;Delhi&quot;);
cityList.add(&quot;Berlin&quot;);
cityList.add(&quot;Paris&quot;);
cityList.add(&quot;Rome&quot;);

request.setAttribute(&quot;cityList&quot;, cityList);

//JSP
&lt;c:forEach var=&quot;city&quot; items=&quot;cityList&quot;&gt;
	&lt;b&gt; ${city} &lt;/b&gt;
&lt;/c:forEach&gt;
</pre><p>But what if you want to iterate a Hashmap? Well that too is piece of cake. Here is the example:</p><pre class="brush: java; title: ; notranslate">
//Java
Map&lt;String, String&gt; countryCapitalList = new HashMap&lt;String, String&gt;();
countryCapitalList.put(&quot;United States&quot;, &quot;Washington DC&quot;);
countryCapitalList.put(&quot;India&quot;, &quot;Delhi&quot;);
countryCapitalList.put(&quot;Germany&quot;, &quot;Berlin&quot;);
countryCapitalList.put(&quot;France&quot;, &quot;Paris&quot;);
countryCapitalList.put(&quot;Italy&quot;, &quot;Rome&quot;);

request.setAttribute(&quot;capitalList&quot;, countryCapitalList);

//JSP
&lt;c:forEach var=&quot;country&quot; items=&quot;${capitalList}&quot;&gt;
	Country: ${country.key}  - Capital: ${country.value}
&lt;/c:forEach&gt;
</pre><p>Happy iterating <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/10/according-to-tld-or-attribute-directive-in-tag-file-issue.html" title="Solving &#8220;According to TLD or attribute directive in tag file&#8221; issue">Solving &#8220;According to TLD or attribute directive in tag file&#8221; issue</a></li><li><a href="http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html" title="How To Reset MySQL Autoincrement Column">How To Reset MySQL Autoincrement Column</a></li><li><a href="http://viralpatel.net/blogs/2011/02/jquery-get-text-element-without-child-element.html" title="jQuery: Get the Text of Element without Child Element">jQuery: Get the Text of Element without Child Element</a></li><li><a href="http://viralpatel.net/blogs/2011/01/java-convert-exponential-decimal-double-number.html" title="Java: Convert Exponential form to Decimal number format in Java ">Java: Convert Exponential form to Decimal number format in Java </a></li><li><a href="http://viralpatel.net/blogs/2010/12/dynamically-shortened-text-show-more-link-jquery.html" title="Dynamically shortened Text with &#8220;Show More&#8221; link using jQuery">Dynamically shortened Text with &#8220;Show More&#8221; link using jQuery</a></li><li><a href="http://viralpatel.net/blogs/2010/11/multiple-checkbox-select-deselect-jquery-tutorial-example.html" title="Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example">Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html" title="Calculate Free Disk Space in Java using Apache Commons IO">Calculate Free Disk Space in Java using Apache Commons IO</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/04/iterate-hashmap-using-jstl-foreach.html/feed</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>Spring Roo: Saving/Retreving BLOB object in Spring Roo</title><link>http://viralpatel.net/blogs/2011/02/spring-roo-save-read-blob-object-spring-roo-tutorial.html</link> <comments>http://viralpatel.net/blogs/2011/02/spring-roo-save-read-blob-object-spring-roo-tutorial.html#comments</comments> <pubDate>Tue, 01 Feb 2011 10:13:33 +0000</pubDate> <dc:creator>Jose Delgado</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[Spring]]></category> <category><![CDATA[Spring Roo]]></category> <category><![CDATA[blob]]></category> <category><![CDATA[spring-roo]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2148</guid> <description><![CDATA[After reading the excellent article titled Saving/Retreving BLOB object in Spring MVC/Hibernate immediately came to my mind: How would it be the process of recreating the same example but using Spring Roo. What would it be the similarities/differences in the projects source code. The article assumes the Reader is a Developer with some familiarity with [...]]]></description> <content:encoded><![CDATA[<p>After reading the excellent article titled <a href="http://viralpatel.net/blogs/2011/01/tutorial-save-get-blob-object-spring-3-mvc-hibernate.html">Saving/Retreving BLOB object in Spring MVC/Hibernate</a> immediately came to my mind:</p><ol><li>How would it be  the process of recreating the same example but using Spring Roo.</li><li>What would it be the similarities/differences in the projects source code.</li></ol><p>The article  assumes  the Reader is a Developer with some familiarity with Spring Roo. For introductory information about Spring Roo vist <a rel="nofollow" target="_new" href="http://www.ibm.com/developerworks/java/library/os-springroo1/index.html?ca=drs-">http://www.ibm.com/developerworks/java/library/os-springroo1/index.html?ca=drs-</a>.</p><h2>Project setup</h2><p>Spring Roo brings alternatives for setting up a project: a) Entering project using  a script file or b) Creating the database first and reverse engineering it using Roo DBRE commands.</p><p>For this article I am using option a), via an script file.  Option b) is specially convenient for projects with an database already in place.  I&#8217;ll vist Roo DBRE in a coming article in the near future.</p><p><em>Script File</em></p><pre class="brush: xml; title: ; notranslate">
project --topLevelPackage org.pragmatikroo.roodocman
persistence setup --provider HIBERNATE --database MYSQL --databaseName roodocman --userName &amp;lt;username&amp;gt; --password &amp;lt;password&amp;gt;
entity		--class ~.domain.Document
field string 	--fieldName name 		--notNull --sizeMax 30
field string 	--fieldName description 	--sizeMax 500
field string 	--fieldName filename 		--notNull
//field blob 	--fieldName content		--notNull //Type not supported by Roo
field string 	--fieldName contentType 	--notNull
field numbert	--fieldName size -
controller all 	--package ~.web
perform clean
perform eclipse
</pre><p>Notice <code>content</code> field  is of  type blob. This field would have to be entered manually into the entity class. You can use the IDE of  your choice. I use STS. Either you use STS or the native Roo shell, the project would need to be synced by Roo after the change. More on this later.</p><h2>Generate Entity Class</h2><pre class="brush: java; title: ; notranslate">
package org.pragmatikroo.roodocman;

@RooJavaBean
@RooToString
@RooEntity
public class Document {

    @NotNull
    @Size(max = 30)
    private java.lang.String name;

    @NotNull
    @Size(max = 500)
    private java.lang.String description;

    private java.lang.String filename;

    @NotNull
    @Lob
    @Basic(fetch = FetchType.LAZY)
    private byte[] content;

    private java.lang.String contentType;

    private java.lang.Long size;

    @Transient
    @Size(max = 100)
    private String url ;
}
</pre><p>Please review the seminal article for more information about the example entity fields.  All highlighted code is manually added to the original file created by Roo. Why I added field size and url  directly into the entity class?. I could have entered referred fields using the shell too. Right?.  I did it  in purpose to mentioned that Spring Roo is a <u>round-trip tool</u>.  There are two more fields not shown in the entity class. They are the  id and version fields,  Roo automatically handle them using an ITD. Details about round-trip capabilities and how Roo uses ITDs, please visit Spring Roo website at http://www.springsource.org/roo.  One more thing about the blob field. DBMS have different type of  blobs. Verify that your project database is using the right one for your purposes.</p><p>As mention before: always make sure that Roo synced  your latest changes. That would save you a lot of confusion.</p><p>It  is a good time to deploy the application and verify that everything is working find to this point.</p><h2>Required Source code changes</h2><p>Well, to this point Spring Roo has done a lot for us. Properly setup the project. Created a Maven pom.xml with all required dependencies -well, almost; more on this below-.  Generate all the code necessary for having a working web app. If this not enough, Roo is there in the background monitoring the project against any possible change.</p><p>With exception of  the  blob field -content- all the other fields are ready to go. Roo took care of them. In order to save/retrieve data from the blob field, we need to modify code in the client and in the server side  for  allowing  file uploads.</p><h2>Server Side Changes</h2><p>Basically we need code that allows us to save/retrieve documents that include a blob field. The documents are entered using a web form. Typically Roo by default, generates client and server side code for having CRUD operations for every entity. I am not allowing updates in this version of  the application. So, I disabled it, by setting the update=false in the <code>@RooWebScaffold</code> annotation. Please make sure next code is  included in the <code>DocumentController</code> project file.</p><pre class="brush: java; title: ; notranslate">
@RooWebScaffold(path = &amp;quot;documents&amp;quot;, formBackingObject = Document.class, update=false)
@InitBinder
protected void initBinder(HttpServletRequest request,
    				   ServletRequestDataBinder binder)
				   throws ServletException {
	binder.registerCustomEditor(byte[].class,   	newByteArrayMultipartFileEditor());
    }
@RequestMapping(value=&amp;quot;savedoc&amp;quot;,  method = RequestMethod.POST)
public String createdoc(@Valid Document document,
    				BindingResult result,
    				Model model,
    				@RequestParam(&amp;quot;content&amp;quot;) MultipartFile content,
    					 	HttpServletRequest request) {

    	document.setContentType(content.getContentType());
    	document.setFilename(content.getOriginalFilename());
    	document.setSize(content.getSize());

    	log.debug(&amp;quot;Document: &amp;quot;);
    	log.debug(&amp;quot;Name: &amp;quot;+content.getOriginalFilename());
    	log.debug(&amp;quot;Description: &amp;quot;+document.getDescription());
    	log.debug(&amp;quot;File: &amp;quot; +content.getName());
    	log.debug(&amp;quot;Type: &amp;quot;+content.getContentType());
    	log.debug(&amp;quot;Size: &amp;quot;+content.getSize());
        if (result.hasErrors()) {
            model.addAttribute(&amp;quot;document&amp;quot;, document);
            return &amp;quot;documents/create&amp;quot;;
        }
        document.persist();

        return &amp;quot;redirect:/documents?page=1&amp;amp;size=10&amp;quot; +   			encodeUrlPathSegment(document.getId().toString(), request);
    }

@RequestMapping(value = &amp;quot;/{id}&amp;quot;, method = RequestMethod.GET)
    public String show(@PathVariable(&amp;quot;id&amp;quot;) Long id, Model model) {
    	Document doc = Document.findDocument(id);
    	doc.setU(&amp;quot;/documents/showdoc/&amp;quot;+id);
        model.addAttribute(&amp;quot;document&amp;quot;, Document.findDocument(id));
        model.addAttribute(&amp;quot;itemId&amp;quot;, id);
        return &amp;quot;documents/show&amp;quot;;
    }

@RequestMapping(value = &amp;quot;/showdoc/{id}&amp;quot;, method = RequestMethod.GET)
public String showdoc(	@PathVariable(&amp;quot;id&amp;quot;) Long id,
    				HttpServletResponse response,
    				Model model) {
   Document doc = Document.findDocument(id);

   try {
          response.setHeader(&amp;quot;Content-Disposition&amp;quot;, &amp;quot;inline;filename=\&amp;quot;&amp;quot; +doc.getFilename()+ &amp;quot;\&amp;quot;&amp;quot;);

          OutputStream out = response.getOutputStream();
          response.setContentType(doc.getContentType());
          IOUtils.copy( new ByteArrayInputStream(doc.getContent()),out);
            out.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
</pre><p>The code above allows CRUD operations with all the document fields including the blob. Very-very important: all this source code must be placed in the <code>DocumentControler.java</code> file to avoid been removed by Roo when the project is synced for changes.</p><h2>Client Side Changes</h2><p>On client side, I created a create custom form. Please replace the content of the create.jspx, with:</p><p><em>Create.jpsx Form</em></p><pre class="brush: xml; title: ; notranslate">
&amp;lt;form:multi id=&amp;quot;fc_org_pragmatikroo_roodocman_domain_Document&amp;quot; modelAttribute=&amp;quot;document&amp;quot; path=&amp;quot;/documents/savedoc&amp;quot; render=&amp;quot;${empty dependencies}&amp;quot; z=&amp;quot;O7jiRGyhKQOUnBT8yJ9W4XU6VrQ=&amp;quot;&amp;gt;
      &amp;lt;field:input field=&amp;quot;name&amp;quot; id=&amp;quot;c_org_pragmatikroo_roodocman_domain_Document_name&amp;quot; max=&amp;quot;30&amp;quot; required=&amp;quot;true&amp;quot; z=&amp;quot;K3YncHn7F+HtBX/zgCZMYM6VO7k=&amp;quot;/&amp;gt;
      &amp;lt;field:textarea field=&amp;quot;description&amp;quot; id=&amp;quot;c_org_pragmatikroo_roodocman_domain_Document_description&amp;quot; required=&amp;quot;true&amp;quot; z=&amp;quot;/RLpJWAf9zVjHtRapWIFve8JB8Y=&amp;quot;/&amp;gt;
      &amp;lt;field:input field=&amp;quot;filename&amp;quot; id=&amp;quot;c_org_pragmatikroo_roodocman_domain_Document_filename&amp;quot; render=&amp;quot;false&amp;quot; z=&amp;quot;u4EclOEjQnID4g34VPv9zu9+qPo=&amp;quot;/&amp;gt;
      &amp;lt;field:file field=&amp;quot;content&amp;quot; id=&amp;quot;c_org_pragmatikroo_roodocman_domain_Document_content&amp;quot; required=&amp;quot;true&amp;quot; z=&amp;quot;GZHlfc+o4h7EBA/SZ8/yXMVenOw=&amp;quot;/&amp;gt;
      &amp;lt;field:input field=&amp;quot;contentType&amp;quot; id=&amp;quot;c_org_pragmatikroo_roodocman_domain_Document_contentType&amp;quot; render=&amp;quot;false&amp;quot; z=&amp;quot;jtq5/DHhBTgNImjac/d4AIfpCzA=&amp;quot;/&amp;gt;
      &amp;lt;field:input field=&amp;quot;size&amp;quot; id=&amp;quot;c_org_pragmatikroo_roodocman_domain_Document_size&amp;quot; render=&amp;quot;false&amp;quot; validationMessageCode=&amp;quot;field_invalid_integer&amp;quot; z=&amp;quot;ONDmhU5Eg5pw1j8LgTz9sXjOm6E=&amp;quot;/&amp;gt;
      &amp;lt;field:textarea field=&amp;quot;url&amp;quot; id=&amp;quot;c_org_pragmatikroo_roodocman_domain_Document_url&amp;quot; render=&amp;quot;false&amp;quot; z=&amp;quot;bQ3FUVGL01nfWselK7WDPUD65Rw=&amp;quot;/&amp;gt;
&amp;lt;/form:multi&amp;gt;
</pre><p>As you can see, the form depends on two custom tagx files -multi.tagx and file.tagx- not included in the Spring Roo tag library. These two tags handle the blob field input.<br /><div id="attachment_2152" class="wp-caption aligncenter" style="width: 583px"><img src="http://img.viralpatel.net/2011/02/spring-roo-blob-object.png" alt="spring-roo-blob-object" title="spring-roo-blob-object" width="573" height="222" class="size-full wp-image-2152" /><p class="wp-caption-text">Create Form</p></div></p><p><em>Show.jpx Form</em></p><pre class="brush: xml; title: ; notranslate">
&amp;lt;page:show id=&amp;quot;ps_org_pragmatikroo_roodocman_domain_Document&amp;quot; object=&amp;quot;${document}&amp;quot; path=&amp;quot;/documents&amp;quot; update=&amp;quot;false&amp;quot; z=&amp;quot;J8X2O2T06x6jYb3WAyaNiTPGVZ0=&amp;quot;&amp;gt;
      &amp;lt;field:display field=&amp;quot;name&amp;quot; id=&amp;quot;s_org_pragmatikroo_roodocman_domain_Document_name&amp;quot; object=&amp;quot;${document}&amp;quot; z=&amp;quot;VZEPJgXqYkqaHpDDPTcYr6DAjsM=&amp;quot;/&amp;gt;
      &amp;lt;field:display field=&amp;quot;description&amp;quot; id=&amp;quot;s_org_pragmatikroo_roodocman_domain_Document_description&amp;quot; object=&amp;quot;${document}&amp;quot; z=&amp;quot;CeXQhSyEDeLn1Iu2hblanNbVc+A=&amp;quot;/&amp;gt;
      &amp;lt;field:display field=&amp;quot;filename&amp;quot; id=&amp;quot;s_org_pragmatikroo_roodocman_domain_Document_filename&amp;quot; object=&amp;quot;${document}&amp;quot; z=&amp;quot;2HT3+zT1+1ft5kN4KhvXFWT9QnM=&amp;quot;/&amp;gt;
      &amp;lt;field:display field=&amp;quot;contentType&amp;quot; id=&amp;quot;s_org_pragmatikroo_roodocman_domain_Document_contentType&amp;quot; object=&amp;quot;${document}&amp;quot; z=&amp;quot;FgCNUQ2KCygzKpUbP06Nxyjyfd8=&amp;quot;/&amp;gt;
      &amp;lt;field:display field=&amp;quot;size&amp;quot; id=&amp;quot;s_org_pragmatikroo_roodocman_domain_Document_size&amp;quot; object=&amp;quot;${document}&amp;quot; z=&amp;quot;WdQ4wob2LThzMpucODZRa275TBc=&amp;quot;/&amp;gt;
      &amp;lt;field:frame field=&amp;quot;url&amp;quot; id=&amp;quot;s_org_pragmatikroo_roodocman_domain_Document_url&amp;quot; object=&amp;quot;${document}&amp;quot; render=&amp;quot;true&amp;quot; z=&amp;quot;user-managed&amp;quot;/&amp;gt;
&amp;lt;/page:show&amp;gt;
</pre><p>This form depends on a custom tag frame.tagx. Basically is a iframe html for rendering images.<br /><div id="attachment_2150" class="wp-caption aligncenter" style="width: 585px"><img src="http://img.viralpatel.net/2011/02/spring-roo-blob-show-form.png" alt="spring-roo-blob-show-form" title="spring-roo-blob-show-form" width="575" height="266" class="size-full wp-image-2150" /><p class="wp-caption-text">Show Form</p></div></p><div id="attachment_2151" class="wp-caption aligncenter" style="width: 586px"><img src="http://img.viralpatel.net/2011/02/spring-roo-blob-list-form.png" alt="spring-roo-blob-list-form" title="spring-roo-blob-list-form" width="576" height="144" class="size-full wp-image-2151" /><p class="wp-caption-text">List Form</p></div><p>Little issue with a missed dependency: When you deploy the app -after the file upload changes- you will find a  missing dependence error.</p><pre class="brush: xml; title: ; notranslate">
&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;commons-io&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;commons-io&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;2.0.1&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
</pre><p>This is it!.</p><h2>Download Source</h2><p><a href="http://viralpatel.net/blogs/download/spring/spring-roo-blob-documentmanager.zip">Click here to download source code (ZIP, 94kb).</a></p><h2>Conclusion</h2><p>Well, the Reader has been exposed to two pretty close but at the same time different ways of  implementing a particular web application project.  Both are using the same  high quality open source code Java-based development stack: Spring 3.X. I believe both ways are good and valid. There is a significant difference in Spring Roo approach though. Roo advocates for removing the &#8220;<strong>unnecessary abstractions</strong>&#8221; from web development. So, you won&#8217;t find Daos or Services classes in a  typical Roo project. This is totally fine with me. However,  it  is a subject still in revision by the community at large. Not to mention that nothing stops you for implementing them if you need/want them.  If you allow me one final point, I like better Roo approach because it gives me more time for thinking and figuring our how to solve the problem.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/02/spring-roo-customizing-web-mvc-ui-forms.html" title="Spring Roo: Customizing Web MVC UI Forms">Spring Roo: Customizing Web MVC UI Forms</a></li><li><a href="http://viralpatel.net/blogs/2011/01/spring-roo-implement-masterdetail-forms.html" title="How to implement Master/Detail forms using Spring Roo">How to implement Master/Detail forms using Spring Roo</a></li><li><a href="http://viralpatel.net/blogs/2011/01/tutorial-save-get-blob-object-spring-3-mvc-hibernate.html" title="Tutorial:Saving/Retreving BLOB object in Spring 3 MVC and Hibernate">Tutorial:Saving/Retreving BLOB object in Spring 3 MVC and Hibernate</a></li><li><a href="http://viralpatel.net/blogs/2205/change-spring-servlet-filename-configuration" title="Change spring-servlet.xml Filename (Spring Web Contenxt Configuration Filename)">Change spring-servlet.xml Filename (Spring Web Contenxt Configuration Filename)</a></li><li><a href="http://viralpatel.net/blogs/2011/02/cache-support-spring-3-1-m1.html" title="Introducing Cache support in Spring 3.1 M1">Introducing Cache support in Spring 3.1 M1</a></li><li><a href="http://viralpatel.net/blogs/2011/01/spring-roo-two-database-configuration.html" title="Spring Roo: Two Databases Configuration">Spring Roo: Two Databases Configuration</a></li><li><a href="http://viralpatel.net/blogs/2010/11/spring3-mvc-hibernate-maven-tutorial-eclipse-example.html" title="Tutorial:Create Spring 3 MVC Hibernate 3 Example using Maven in Eclipse">Tutorial:Create Spring 3 MVC Hibernate 3 Example using Maven in Eclipse</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/02/spring-roo-save-read-blob-object-spring-roo-tutorial.html/feed</wfw:commentRss> <slash:comments>46</slash:comments> </item> <item><title>Java: Convert Exponential form to Decimal number format in Java</title><link>http://viralpatel.net/blogs/2011/01/java-convert-exponential-decimal-double-number.html</link> <comments>http://viralpatel.net/blogs/2011/01/java-convert-exponential-decimal-double-number.html#comments</comments> <pubDate>Mon, 10 Jan 2011 16:13:04 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[How-To]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2133</guid> <description><![CDATA[While working with Doubles and Long numbers in Java you will see that most of the value are displayed in Exponential form. For example : In following we are multiplying 2.35 with 10000 and the result is printed. Result: 1) 2.85E-4 2) 2.85E8 Thus you can see the result is printed in exponential format. Now [...]]]></description> <content:encoded><![CDATA[<p>While working with Doubles and Long numbers in Java you will see that most of the value are displayed in Exponential form.</p><p>For example : In following we are multiplying 2.35 with 10000 and the result is printed.</p><pre class="brush: java; title: ; notranslate">
//Division example
Double a = 2.85d / 10000;
System.out.println(&quot;1) &quot; + a.doubleValue());

//Multiplication example
a = 2.85d * 100000000;
System.out.println(&quot;2) &quot; + a.doubleValue());
</pre><p><strong>Result:</strong></p><pre>
1)  2.85E-4
2)  2.85E8
</pre><p>Thus you can see the result is printed in exponential format. Now you may want to display the result in pure decimal format like: 0.000285 or 285000000. You can do this simply by using class <code>java.math.BigDecimal</code>. In following example we are using <code>BigDecimal.valueOf()</code> to convert the <code>Double</code> value to <code>BigDecimal</code> and than <code>.toPlainString()</code> to convert it into plain decimal string.</p><pre class="brush: java; title: ; notranslate">
import java.math.BigDecimal;
//..
//..

//Division example
Double a = 2.85d / 10000;
System.out.println(&quot;1) &quot; + BigDecimal.valueOf(a).toPlainString());

//Multiplication example
a = 2.85d * 100000000;
System.out.println(&quot;2) &quot; + BigDecimal.valueOf(a).toPlainString());
</pre><p><strong>Result:</strong></p><pre>
1)  0.000285
2)  285000000
</pre><p>The only disadvantage of the above method is that it generates lonnnnggg strings of number. You may want to restrict the value and round off the number to 5 or 6 decimal point. For this you can use <code>java.text.DecimalFormat</code> class. In following example we are rounding off the number to 4 decimal point and printing the output.</p><pre class="brush: java; title: ; notranslate">
import java.text.DecimalFormat;
//..
//..

Double a = 2.85d / 10000;
DecimalFormat formatter = new DecimalFormat(&quot;0.0000&quot;);
System.out.println(formatter .format(a));
</pre><p><strong>Result:</strong></p><pre>
0.0003
</pre><p>Happy converting <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html" title="Calculate Free Disk Space in Java using Apache Commons IO">Calculate Free Disk Space in Java using Apache Commons IO</a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-tip-how-to-sort-array-in-java-java-util-arrays.html" title="Java Tip: How to Sort Arrays in Java using java.util.Arrays class">Java Tip: How to Sort Arrays in Java using java.util.Arrays class</a></li><li><a href="http://viralpatel.net/blogs/2009/07/static-import-java-example-tutorial.html" title="Static Import in Java: New way to Import things in Java!">Static Import in Java: New way to Import things in Java!</a></li><li><a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html" title="Convert ArrayList to Arrays in Java">Convert ArrayList to Arrays in Java</a></li><li><a href="http://viralpatel.net/blogs/2009/05/how-to-execute-command-prompt-command-view-output-java.html" title="How to execute a command prompt command &#038; view output in Java">How to execute a command prompt command &#038; view output in Java</a></li><li><a href="http://viralpatel.net/blogs/2009/05/inspect-your-code-in-eclipse-using-eclipse-scrapbook-feature.html" title="Inspect your code in Eclipse using Eclipse Scrapbook feature">Inspect your code in Eclipse using Eclipse Scrapbook feature</a></li><li><a href="http://viralpatel.net/blogs/2009/05/getting-jvm-heap-size-used-memory-total-memory-using-java-runtime.html" title="Getting JVM heap size, used memory, total memory using Java Runtime">Getting JVM heap size, used memory, total memory using Java Runtime</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/01/java-convert-exponential-decimal-double-number.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Convert String to Enum Instance in Java</title><link>http://viralpatel.net/blogs/2010/10/convert-string-to-enum-instance-string-enum-java.html</link> <comments>http://viralpatel.net/blogs/2010/10/convert-string-to-enum-instance-string-enum-java.html#comments</comments> <pubDate>Wed, 27 Oct 2010 08:37:33 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[enum]]></category> <category><![CDATA[java 5]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2112</guid> <description><![CDATA[Recently while working in one of the requirement, I had to convert String values to Enum. I didn&#8217;t realize there is a simplest way of doing this. Here is the solution. Whenever an ENUM is complied in Java, two static methods are added by compiler called valueOf() and values(). We can use valueOf() method to [...]]]></description> <content:encoded><![CDATA[<p>Recently while working in one of the requirement, I had to convert String values to Enum. I didn&#8217;t realize there is a simplest way of doing this. Here is the solution.</p><p>Whenever an ENUM is complied in Java, two static methods are added by compiler called valueOf() and values(). We can use valueOf() method to convert any String value to ENUM. For example lets say we have an ENUM called Weekdays.</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.java.enum;

public enum Weekdays {
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday,
	Sunday
}
</pre><p>Now we want to get an instance of Weekdays enum from string values lets say &#8220;Monday&#8221;, &#8220;Tuesday&#8221; etc. We can get this as follow:</p><pre class="brush: java; title: ; notranslate">
Weekdays weekday = Weekdays.valueOf(&quot;Monday&quot;);
System.out.println(weekday);
</pre><p><strong>Output:</strong></p><pre>
Monday
</pre><p>One thing we need to take care here is if we pass an invalid string to valueOf() method like &#8220;XYZ&#8221;, the method will give a runtime exception.</p><pre class="brush: java; title: ; notranslate">
Weekdays weekday = Weekdays.valueOf(&quot;XYZ&quot;);
System.out.println(weekday);
</pre><p><strong>Output:</strong></p><pre>
Exception in thread "main" java.lang.IllegalArgumentException:
        No enum const class net.viralpatel.java.enum.Weekdays.XYZ
	at java.lang.Enum.valueOf(Enum.java:192)
</pre><p>Happy converting <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/07/static-import-java-example-tutorial.html" title="Static Import in Java: New way to Import things in Java!">Static Import in Java: New way to Import things in Java!</a></li><li><a href="http://viralpatel.net/blogs/2009/05/varargs-in-java-variable-argument-method-in-java-5.html" title="Varargs in Java: Variable argument method in Java 5">Varargs in Java: Variable argument method in Java 5</a></li><li><a href="http://viralpatel.net/blogs/2012/01/convert-array-to-set-java-arraylist.html" title="Convert Arrays to Set in Java">Convert Arrays to Set in Java</a></li><li><a href="http://viralpatel.net/blogs/2011/12/spring-mvc-multi-row-submit-java-list.html" title="Spring MVC: Multiple Row Form Submit using List of Beans">Spring MVC: Multiple Row Form Submit using List of Beans</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation" title="Hibernate One To One Annotation Mapping Tutorial">Hibernate One To One Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/01/java-convert-exponential-decimal-double-number.html" title="Java: Convert Exponential form to Decimal number format in Java ">Java: Convert Exponential form to Decimal number format in Java </a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html" title="Calculate Free Disk Space in Java using Apache Commons IO">Calculate Free Disk Space in Java using Apache Commons IO</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2010/10/convert-string-to-enum-instance-string-enum-java.html/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Creating Dynamic Web Project using Maven in Eclipse</title><link>http://viralpatel.net/blogs/2010/07/generate-dynamic-web-project-maven-eclipse-wtp.html</link> <comments>http://viralpatel.net/blogs/2010/07/generate-dynamic-web-project-maven-eclipse-wtp.html#comments</comments> <pubDate>Wed, 28 Jul 2010 13:41:20 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[JavaEE]]></category> <category><![CDATA[apache maven]]></category> <category><![CDATA[eclipse]]></category> <category><![CDATA[eclipse plugins]]></category> <category><![CDATA[maven]]></category> <category><![CDATA[maven plugins]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2096</guid> <description><![CDATA[While using Maven as build tool in our project, I found it very difficult to create a Dynamic Web Project which supports Maven dependencies and can execute in Eclipse! I have seen lot of people using Maven just as build tool and for local setup uses jar files in some /lib directory. I wanted to [...]]]></description> <content:encoded><![CDATA[<p>While using Maven as build tool in our project, I found it very difficult to create a Dynamic Web Project which supports <a href="http://viralpatel.net/blogs/2009/04/introduction-apache-maven-build-framework-build-automation-tool.html">Maven dependencies</a> and can execute in Eclipse! I have seen lot of people using Maven just as build tool and for local setup uses jar files in some /lib directory. I wanted to remove this dependencies on local /lib for jar files and resolve everything with Maven. My project should be a Dynamic web project with Maven dependencies enabled.</p><p>Here is a simple tutorial which you can go through to create Dynamic Web Project having Maven enabled in Eclipse. This project can be used as base project and can be easily converted to most kind of project like Struts based, Spring MVC based etc.</p><h2>Required Tools</h2><p>For this tutorial, I assume you have following setup in your machine.<br /> 1. JDK 1.5 or above (<a rel="nofollow" target="_new" href="http://java.sun.com/javase/downloads/index.jsp">download</a>)<br /> 2. Eclipse 3.2 or above (<a rel="nofollow" target="_new" href="http://www.eclipse.org/downloads/">download</a>)<br /> 3. Maven 2.0 or above (<a rel="nofollow" target="_new" href="http://maven.apache.org/download.html">download</a>)<br /> 4. M2Eclipse Plugin (<a rel="nofollow" target="_new" href="http://m2eclipse.sonatype.org/installing-m2eclipse.html">download</a>)</p><h2>Step 1: Create Maven Project in Eclipse</h2><p>Create a new project in Eclipse. Goto <strong>File > New > Project.. </strong>and select <strong>Maven Project</strong> from the list. Click Next.<br /> <img src="http://img.viralpatel.net/2010/07/eclipse-maven-new-project.png" alt="eclipse-maven-new-project" title="eclipse-maven-new-project" width="363" height="353" class="aligncenter size-full wp-image-2097" /></p><p>Enter <strong>&#8220;MavenWeb&#8221;</strong> as Project name and click Next. On Configuration screen, select <strong>war</strong> in Packaging and also check the checkbox for <strong>src/main/webapp</strong>.</p><p><img src="http://img.viralpatel.net/2010/07/new-maven-project.png" alt="new-maven-project" title="new-maven-project" width="361" height="447" class="aligncenter size-full wp-image-2098" /></p><p>Once done, click Finish. This will create a Maven project in Eclipse.</p><h2>Step 2: Generate Eclipse Project with WTP</h2><p>Let us convert the Maven project to Dynamic Web Project for Eclipse. For this we will use following maven command.</p><pre class="brush: xml; title: ; notranslate">
mvn eclipse:eclipse -Dwtpversion=1.5
</pre><p>Goto the folder where the new project is created and execute above command.</p><pre>
C:\Workspace\Test\MavenWeb>mvn eclipse:eclipse -Dwtpversion=1.5

[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'eclipse'.
[INFO] ------------------------------------------------------------------------
[INFO] Building Unnamed - MavenWeb:MavenWeb:war:0.0.1-SNAPSHOT
[INFO]    task-segment: [eclipse:eclipse]
[INFO] ------------------------------------------------------------------------
[INFO] Preparing eclipse:eclipse
[INFO] No goals needed for project - skipping
[INFO] [eclipse:eclipse]
[INFO] Adding support for WTP version 1.5.
[INFO] Using Eclipse Workspace: C:\Workspace\Test
[INFO] no substring wtp server match.
[INFO] Using as WTP server : Apache Tomcat v5.5
[INFO] Adding default classpath container: org.eclipse.jdt.launching.JRE_CONTAINER
[INFO] Not writing settings - defaults suffice
[INFO] Wrote Eclipse project for "MavenWeb" to C:\Workspace\Test\MavenWeb.
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4 seconds
[INFO] Finished at: Wed Jul 28 13:55:09 CEST 2010
[INFO] Final Memory: 7M/30M
[INFO] ------------------------------------------------------------------------
</pre><p>That&#8217;s it. We just created Dynamic Web Project from Maven project. Now refresh the project in Eclipse.</p><h2>Step 3: Change Project Facet</h2><p>The above step by default set the project facet to JDK 1.4. We need to modify this and set project facet to JDK 5. Right click on MavenWeb project and select Properties (shortcut: Alt+Enter). From the Properties dialog box, select Project Facets. Now click on &#8220;Modify Project&#8230;&#8221; button and change the project facet to Java 5.0<br /> <img src="http://img.viralpatel.net/2010/07/project-facet-maven-eclipse.png" alt="project-facet-maven-eclipse" title="project-facet-maven-eclipse" width="368" height="432" class="aligncenter size-full wp-image-2100" /></p><h2>Step 4: Setting Build Path</h2><p>We need to specify the Maven jar dependencies in Java Build Path of our MavenWeb project. Open Properties.. dialog box (Alt+Enter) and select <strong>Java Build Path</strong>. Click &#8220;Add Library..&#8221; button and select <strong>&#8220;Maven Managed Dependencies&#8221;</strong> and click Finish.<br /> <img src="http://img.viralpatel.net/2010/07/maven-eclipse-build-path.png" alt="maven-eclipse-build-path" title="maven-eclipse-build-path" width="598" height="447" class="aligncenter size-full wp-image-2099" /></p><h2>Step 5: Hello World Servlet</h2><p>Our dynamic web project with maven support is done now. Let us add a small Hello World servlet to this project and see how it works.</p><p>Open pom.xml from root folder and copy following content into it.</p><p><em>File: pom.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project&gt;
	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
	&lt;groupId&gt;MavenWeb&lt;/groupId&gt;
	&lt;artifactId&gt;MavenWeb&lt;/artifactId&gt;
	&lt;packaging&gt;war&lt;/packaging&gt;
	&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
	&lt;description&gt;&lt;/description&gt;
	&lt;build&gt;
                &lt;plugins&gt;
                        &lt;plugin&gt;
                                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
                                &lt;configuration&gt;
                                        &lt;source&gt;1.5&lt;/source&gt;
                                        &lt;target&gt;1.5&lt;/target&gt;
                                &lt;/configuration&gt;
                        &lt;/plugin&gt;
			&lt;plugin&gt;
				&lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt;
				&lt;version&gt;2.0&lt;/version&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;
	&lt;dependencies&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
			&lt;artifactId&gt;servlet-api&lt;/artifactId&gt;
			&lt;version&gt;2.5&lt;/version&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;
&lt;/project&gt;
</pre><p>Also create a servlet file HelloWorldServlet.java. We will add this servlet in <strong>net.viralpatel.maven</strong> package.</p><p><em>File: /src/main/java/net/viralpatel/maven/HelloWorldServlet.java</em></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.maven;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet {

	private static final long serialVersionUID = 1031422249396784970L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		resp.setContentType(&quot;text/html&quot;);

		PrintWriter out = resp.getWriter();
		out.print(&quot;Hello World from Servlet&quot;);
		out.flush();
		out.close();
	}
}
</pre><p>Once the servlet is created, let us configure this in web.xml. Note that in our maven project no web.xml is present. We will create one at /src/main/webapp/WEB-INF/ location.</p><p><em>File: /src/main/webapp/WEB-INF/web.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
	xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
	id=&quot;WebApp_ID&quot; version=&quot;2.5&quot;&gt;
	&lt;display-name&gt;HelloWorldServlet&lt;/display-name&gt;
	&lt;welcome-file-list&gt;
		&lt;welcome-file&gt;hello-world&lt;/welcome-file&gt;
	&lt;/welcome-file-list&gt;

	&lt;servlet&gt;
		&lt;servlet-name&gt;HelloWorldServlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;
			net.viralpatel.maven.HelloWorldServlet
		&lt;/servlet-class&gt;
		&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
	&lt;/servlet&gt;
	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;HelloWorldServlet&lt;/servlet-name&gt;
		&lt;url-pattern&gt;/hello-world&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
&lt;/web-app&gt;
</pre><h2>That&#8217;s All Folks</h2><p>Our dynamic web project with Maven support in Eclipse is completed. Run the web project in eclipse (Alt+Shirt+X, R)<br /> <img src="http://img.viralpatel.net/2010/07/hello-world-maven-eclipse-web-project.png" alt="hello-world-maven-eclipse-web-project" title="hello-world-maven-eclipse-web-project" width="320" height="230" class="aligncenter size-full wp-image-2101" /></p><h2>Download Source</h2><p><a href="http://viralpatel.net/blogs/download/j2ee/maven/MavenWeb.zip">Click here to download the source code (7.0 kb)</a></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/04/introduction-apache-maven-build-framework-build-automation-tool.html" title="Introduction to Apache Maven: A build framework &#038; build automation tool">Introduction to Apache Maven: A build framework &#038; build automation tool</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li><li><a href="http://viralpatel.net/blogs/2009/04/google-android-adt-sdk-and-eclipse-ide-integration-on-linux.html" title="Google Android ADT, SDK and Eclipse IDE integration on Linux ">Google Android ADT, SDK and Eclipse IDE integration on Linux </a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation" title="Hibernate One To One Annotation Mapping Tutorial">Hibernate One To One Annotation Mapping Tutorial</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2010/07/generate-dynamic-web-project-maven-eclipse-wtp.html/feed</wfw:commentRss> <slash:comments>13</slash:comments> </item> <item><title>Calculate Free Disk Space in Java using Apache Commons IO</title><link>http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html</link> <comments>http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html#comments</comments> <pubDate>Mon, 12 Jul 2010 15:54:50 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[apache]]></category> <category><![CDATA[How-To]]></category> <category><![CDATA[java code]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2087</guid> <description><![CDATA[As a Java developer, lot of times I have to play around with file system. Sometimes I have to copy files/directories from one location to another; sometimes have to process certain files depending on certain pattern. In one of my test program, I wanted to calculate available disk space using Java. Lot of code snippets [...]]]></description> <content:encoded><![CDATA[<p><img alt="java logo" src="http://viralpatel.net/blogs/wp-content/uploads/java-logo2.gif" title="java logo" class="alignright" width="152" height="168" />As a Java developer, lot of times I have to play around with file system. Sometimes I have to copy files/directories from one location to another; sometimes have to process certain files depending on certain pattern. In one of my test program, I wanted to calculate available disk space using Java. Lot of code snippets are available for this task. I liked the one using Apache Commons IO library.</p><p>Here is a simple trick for Java developers to calculate free diskspace. We have used Apache Commons IO library to calculate this.</p><p>Apache Commons IO library contains a class <code>org.apache.commons.io.FileSystemUtils</code> which can be used to calculate the free disk space in any system. Let us see the Java code for this.</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.java;

import java.io.IOException;

import org.apache.commons.io.FileSystemUtils;

public class DiskSpace {
	public static void main(String[] args) {
		try {

			//calculate free disk space
			double freeDiskSpace = FileSystemUtils.freeSpaceKb(&quot;C:&quot;); 

			//convert the number into gigabyte
			double freeDiskSpaceGB = freeDiskSpace / 1024 / 1024;

			System.out.println(&quot;Free Disk Space (GB):&quot; + freeDiskSpaceGB);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
</pre><p><strong>Output:</strong></p><pre>
Free Disk Space (GB): 40.145268
</pre><p>In above code we used <code>FileSystemUtils.freeSpaceKb( )</code> method to get the free space in kilo byte. This method invokes the command line to calculate the free disk space. You may want to call this method in following way to get free disk space in Windows and Linux.</p><pre class="brush: java; title: ; notranslate">
 FileSystemUtils.freeSpaceKb(&quot;C:&quot;);       // Windows
 FileSystemUtils.freeSpaceKb(&quot;/volume&quot;);  // *nix
 </pre><p>The free space is calculated via the command line. It uses <strong>&#8216;dir /-c&#8217;</strong> on Windows, <strong>&#8216;df -kP&#8217;</strong> on AIX/HP-UX and &#8216;<strong>df -k&#8217;</strong> on other Unix.</p><p>In order to work, you must be running Windows, or have a implementation of Unix df that supports GNU format when passed -k (or -kP). If you are going to rely on this code, please check that it works on your OS by running some simple tests to compare the command line with the output from this class.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html" title="Convert ArrayList to Arrays in Java">Convert ArrayList to Arrays in Java</a></li><li><a href="http://viralpatel.net/blogs/2011/01/java-convert-exponential-decimal-double-number.html" title="Java: Convert Exponential form to Decimal number format in Java ">Java: Convert Exponential form to Decimal number format in Java </a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-tip-how-to-sort-array-in-java-java-util-arrays.html" title="Java Tip: How to Sort Arrays in Java using java.util.Arrays class">Java Tip: How to Sort Arrays in Java using java.util.Arrays class</a></li><li><a href="http://viralpatel.net/blogs/2009/07/static-import-java-example-tutorial.html" title="Static Import in Java: New way to Import things in Java!">Static Import in Java: New way to Import things in Java!</a></li><li><a href="http://viralpatel.net/blogs/2009/06/double-brace-initialization-in-java.html" title="Double Brace Initialization in Java!">Double Brace Initialization in Java!</a></li><li><a href="http://viralpatel.net/blogs/2009/05/how-to-execute-command-prompt-command-view-output-java.html" title="How to execute a command prompt command &#038; view output in Java">How to execute a command prompt command &#038; view output in Java</a></li><li><a href="http://viralpatel.net/blogs/2009/05/inspect-your-code-in-eclipse-using-eclipse-scrapbook-feature.html" title="Inspect your code in Eclipse using Eclipse Scrapbook feature">Inspect your code in Eclipse using Eclipse Scrapbook feature</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html/feed</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Java Tip: How to Sort Arrays in Java using java.util.Arrays class</title><link>http://viralpatel.net/blogs/2010/07/java-tip-how-to-sort-array-in-java-java-util-arrays.html</link> <comments>http://viralpatel.net/blogs/2010/07/java-tip-how-to-sort-array-in-java-java-util-arrays.html#comments</comments> <pubDate>Fri, 09 Jul 2010 04:00:45 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[arraylists]]></category> <category><![CDATA[How-To]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2085</guid> <description><![CDATA[Here is a small but very useful tip that every Java programmer should be aware of. Have you ever tried sorting arrays in Java? Well, java.util.Arrays class has built in method to make your job easy. You can use following method to sort any array in Java. Let us check an example were we will [...]]]></description> <content:encoded><![CDATA[<p>Here is a small but very useful tip that every Java programmer should be aware of. Have you ever tried sorting arrays in Java? Well, <code>java.util.Arrays</code> class has built in method to make your job easy. You can use following method to sort any array in Java.</p><pre class="brush: java; title: ; notranslate">
import java.util.Arrays;
...
...
Arrays.sort (int [])
Arrays.sort (String [])
Arrays.sort (float [])
Arrays.sort (double [])
Arrays.sort (long [])
Arrays.sort (Object [])
...
</pre><p>Let us check an example were we will sort an array of String in ascending as well as descending order. Here is a string array we defined in Java.</p><pre class="brush: java; title: ; notranslate">
String [] stringArray = {&quot;ab&quot;, &quot;aB&quot;, &quot;c&quot;, &quot;0&quot;, &quot;2&quot;, &quot;1Ad&quot;, &quot;a10&quot;};

System.out.println(&quot;****** Unsorted String Array *******&quot;);
for (String str : stringArray) {
	System.out.println(str);
}
</pre><p><strong>Output:</strong></p><pre>
****** unsorted string *******
ab
aB
c
0
2
1Ad
a10
</pre><p>In above code we simple define an array of String and printed its value. Now lets sort this array in ascending order using <code>Arrays.sort()</code> method.</p><h3>Sort in Ascending Order</h3><pre class="brush: java; title: ; notranslate">
//Sort array in ascending order
Arrays.sort(stringArray);

System.out.println(&quot;****** Sorted String Array *******&quot;);
for (String str : stringArray) {
	System.out.println(str);
}
</pre><p><strong>Output:</strong></p><pre>
****** Sorted String Array *******
0
1Ad
2
a10
aB
ab
c
</pre><p>Note that we just sorted an array of String in ascending order using sort method. Wasn&#8217;t it easy..</p><h3>Sort in Descending Order</h3><p>Now lets try to sort the array in reverse order. For this we will use a different signature of sort method.</p><pre class="brush: java; title: ; notranslate">
Arrays.sort (Object [], Comparator)
</pre><p>Following is the code to sort array in reverse order.</p><pre class="brush: java; title: ; notranslate">
//Sort array in reverse order
Arrays.sort(stringArray, Collections.reverseOrder());

System.out.println(&quot;****** Reverse Sorted String Array *******&quot;);
for (String str : stringArray) {
	System.out.println(str);
}
</pre><p><strong>Output:</strong></p><pre>
****** Reverse Sorted String Array *******
c
ab
aB
a10
2
1Ad
0
</pre><h3>Selective Sorting</h3><p>Using Arrays.sort() method it is possible to sort an array selectively. i.e. if you want a subpart of array to be sorted, that is possible using following method.</p><pre class="brush: java; title: ; notranslate">
Arrays.sort (Object [], int startIndex, int endIndex)
</pre><p>In following code we are sorting the array starting from index 3 till the end.</p><pre class="brush: java; title: ; notranslate">
//Sorting array starting from index 3 till 6
Arrays.sort(stringArray, 3, 6);

System.out.println(&quot;****** Selective Sort String Array *******&quot;);
for (String str : stringArray) {
	System.out.println(str);
}
</pre><p><strong>Output:</strong></p><pre>
****** Selective Sort String Array *******
ab
aB
c
0
1Ad
2
a10
</pre><p>Happy sorting.. <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html" title="Convert ArrayList to Arrays in Java">Convert ArrayList to Arrays in Java</a></li><li><a href="http://viralpatel.net/blogs/2012/01/convert-array-to-set-java-arraylist.html" title="Convert Arrays to Set in Java">Convert Arrays to Set in Java</a></li><li><a href="http://viralpatel.net/blogs/2011/01/java-convert-exponential-decimal-double-number.html" title="Java: Convert Exponential form to Decimal number format in Java ">Java: Convert Exponential form to Decimal number format in Java </a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html" title="Calculate Free Disk Space in Java using Apache Commons IO">Calculate Free Disk Space in Java using Apache Commons IO</a></li><li><a href="http://viralpatel.net/blogs/2009/07/static-import-java-example-tutorial.html" title="Static Import in Java: New way to Import things in Java!">Static Import in Java: New way to Import things in Java!</a></li><li><a href="http://viralpatel.net/blogs/2009/05/how-to-execute-command-prompt-command-view-output-java.html" title="How to execute a command prompt command &#038; view output in Java">How to execute a command prompt command &#038; view output in Java</a></li><li><a href="http://viralpatel.net/blogs/2009/05/inspect-your-code-in-eclipse-using-eclipse-scrapbook-feature.html" title="Inspect your code in Eclipse using Eclipse Scrapbook feature">Inspect your code in Eclipse using Eclipse Scrapbook feature</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2010/07/java-tip-how-to-sort-array-in-java-java-util-arrays.html/feed</wfw:commentRss> <slash:comments>5</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced

Served from: viralpatel.net @ 2012-02-08 21:30:29 -->
