<?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>JavaBeat &#187; Mohamed Sanaulla</title>
	<atom:link href="http://www.javabeat.net/author/sanaulla/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Thu, 23 May 2013 01:30:53 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>How to create bounded taskflows in ADF using JDeveloper?</title>
		<link>http://www.javabeat.net/2012/11/how-to-create-bounded-taskflows-in-adf-using-jdeveloper/</link>
		<comments>http://www.javabeat.net/2012/11/how-to-create-bounded-taskflows-in-adf-using-jdeveloper/#comments</comments>
		<pubDate>Wed, 07 Nov 2012 04:19:49 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java Server Faces (JSF)]]></category>
		<category><![CDATA[Web Frameworks]]></category>
		<category><![CDATA[Java Server Faces]]></category>
		<category><![CDATA[Oracle ADF]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4929</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Taskflows are a very useful feature in Oracle ADF which provide a modular approach for defining control flow in an application. It allows to create application flow graphs which can be tied together to build the complete application. So instead of considering an application as a collection of different JSF pages, in ADF we would [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p><strong>Taskflows</strong> are a very useful feature in <a href="http://www.oracle.com/technetwork/developer-tools/adf/overview/index.html" target="_blank">Oracle ADF</a> which provide a modular approach for defining control flow in an application. It allows to create application flow graphs which can be tied together to build the complete application. So instead of considering an application as a collection of different <strong>JSF</strong> pages, in <strong>ADF</strong> we would consider an application as a collection of different <strong>taskflows</strong>.</p>
<p><strong>ADF Taskflows</strong> come in two forms:</p>
<ul>
<li>Bounded Taskflow</li>
<li>Unbounded Taskflow</li>
</ul>
<p><strong>Unbounded Taskflow:</strong> A set of activities (<strong>JSF</strong> Pages/views), control flow rules, and managed beans that interact to allow a user to complete a task. An ADF unbounded task flow consists of all activities and control flows in an application that are not included within any bounded task flow.</p>
<ul>
<li><a href="http://www.flipkart.com/oracle-fusion-developer-guide-0070701938/p/itmczyz77pqunzsh?pid=9780070701939&amp;affid=suthukrish" target="_blank"><strong>Building Rich Internet Applications with Oracle ADF Business Components &amp; ADF Faces</strong></a> (<a href="http://astore.amazon.com/javabeat-20/detail/0071622543" target="_blank">Amazon.com</a>)</li>
</ul>
<p><strong>Bounded Taskflow:</strong> A specialized form of task flow that, in contrast to an unbounded task flow, has a single entry point and zero or more exit points. It contains its own set of private control flow rules, activities, and managed beans.</p>
<p>A bounded taskflow:</p>
<ul>
<li>has single entry point.</li>
<li>zero or more exit points.</li>
<li>may accept input parameters.</li>
<li>may generate return value.</li>
<li>has its own memory scope called pageflow scope.</li>
</ul>
<p>The memory scope of a bounded taskflow called pageflow scope allows the developer to declare java bean classes in that scope making it available/accessible across all the JSF pages within the taskflow.</p>
<p>In this article we will look at how to create ADF bounded taskflow using JDeveloper. I am using JDeveloper Studio Edition Version 11.1.2.1.0 for this article.</p>
<h3>Creating a new ADF Web Application</h3>
<p>:<br />
From the Application Navigator click on <strong>New Application</strong> and you should see this popup:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/11/NewADFApp.jpg"><img class="aligncenter size-medium wp-image-4932" src="http://www.javabeat.net/wp-content/uploads/2012/11/NewADFApp-300x214.jpg" alt="" width="300" height="214" /></a></p>
<p>Select <strong>Fusion Web Application(ADF)</strong> and click on Ok to get the next popup:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/11/NewADFApp_Name.jpg"><img class="aligncenter size-medium wp-image-4933" src="http://www.javabeat.net/wp-content/uploads/2012/11/NewADFApp_Name-300x225.jpg" alt="" width="300" height="225" /></a><br />
Enter the Application name as <strong>BoundedTaskFlowCreation</strong> and then click on <strong>Finish</strong> button to create a new application. Once you have created a new application you would get this view:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/11/NewADFApp_Done.jpg"><img class="aligncenter size-medium wp-image-4935" src="http://www.javabeat.net/wp-content/uploads/2012/11/NewADFApp_Done-300x171.jpg" alt="" width="300" height="171" /></a><br />
With this you have your new ADF application setup. You would see 2 projects: Model and ViewController (assuming you didn&#8217;t change the defaults apart from adding new application name while creating the new application). The Model project contains all the code which deals with ADF Data binding layer called- ADFBC and ViewController project contains all the view related code like the JSF pages, the java classes which act as managed beans for those JSF pages.</p>
<h3>Creating a new bounded taskflow</h3>
<p>Right click on the ViewController project and click on New:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/11/NewBT_Prestart.jpg"><img class="aligncenter size-full wp-image-4937" src="http://www.javabeat.net/wp-content/uploads/2012/11/NewBT_Prestart.jpg" alt="" width="326" height="411" /></a><br />
In the new window select JSF/Facelets from the Web Tier categories in the right and then select <strong>ADF Taskflow</strong> from the right and click on <strong>Ok</strong> as shown below:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/11/NewBT_Start.jpg"><img class="aligncenter size-medium wp-image-4938" src="http://www.javabeat.net/wp-content/uploads/2012/11/NewBT_Start-300x202.jpg" alt="" width="300" height="202" /></a></p>
<p>In the <strong>Create Taskflow</strong> window enter the <strong>File Name</strong> which would be the name of the bounded taskflow, let the Directory be default, check the <strong>Create as Bounded Taskflow</strong> check box and <strong>uncheck</strong> the <strong>Create with Page Fragments</strong> checkbox. After you have entered the details, your screen would be more or less like:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/11/NewBT_First.jpg"><img class="aligncenter size-medium wp-image-4940" src="http://www.javabeat.net/wp-content/uploads/2012/11/NewBT_First-300x206.jpg" alt="" width="300" height="206" /></a><br />
A bounded taskflow is represented by an XML config file which contains the views/pages part of the taskflow, the control flow structure i.e navigation from one page/view to another which can also include conditional flows, any java bean classes which are referenced by the views/pages within the taskflow which are called as Managed beans. And creating a bounded taskflow with pagefragements will not allow it to be launched independently and hence I am creating a bounded taskflow without page fragments. A bounded taskflow with page fragments would allow us to create only JSFF files i.e JSF fragment files.</p>
<p>Once you have clicked on <strong>Ok</strong>, you will be shown the Bounded Taskflow Diagrammatic view as shown below:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/11/NewBT_Done.jpg"><img class="aligncenter size-medium wp-image-4941" src="http://www.javabeat.net/wp-content/uploads/2012/11/NewBT_Done-300x177.jpg" alt="" width="300" height="177" /></a></p>
<p>Generally lot of the work with taskflows can be easily done using the diagrammatic view. Most of us should be familiar with the GUI builders which are used for creating Swing applications or Flex applications. When we drag and drop components on the taksflow diagram, there is code generated in the XML which corresponds to the components added. You should be able to see the <strong>component palette</strong> on the right hand side and the <strong>Properties Inspector</strong> window at the bottom (the screenshot shown above shows the two windows). If you are not able to see these windows, you can always add them from the <strong>View</strong> menu.</p>
<p>In the component palette you can see a plethora of components which can be added to the taskflow. Search for <strong>View</strong> and then drag drop the <strong>View(ADF Task Flow.Components)</strong> on to the taskflow area. And then enter the name of the view as: firstPage. You should now see a view component in the taskflow as shown below:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/11/BT_1.jpg"><img class="aligncenter size-medium wp-image-4942" src="http://www.javabeat.net/wp-content/uploads/2012/11/BT_1-300x171.jpg" alt="" width="300" height="171" /></a></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Note that after adding the View component no JSF/JSP page has been created. To create a JSF page for that view double click on the view component to get the following popup:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/11/BT_2.jpg"><img class="aligncenter size-medium wp-image-4943" src="http://www.javabeat.net/wp-content/uploads/2012/11/BT_2-300x276.jpg" alt="" width="300" height="276" /></a><br />
You can select/choose from the Layouts or just select the Blank option to create a new JSF page. In the same way described above add another view: secondPage.<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/11/BT_After2View.jpg"><img class="aligncenter size-medium wp-image-4944" src="http://www.javabeat.net/wp-content/uploads/2012/11/BT_After2View-300x171.jpg" alt="" width="300" height="171" /></a><br />
One can see a light green shade around firstPage component. This indicates that the default activity for the bounded taskflow is firstPage. One can change the default activity by selecting the bounded taskflow and changing the <strong>Default Activity</strong> property from the <strong>Property Inspector</strong> window.</p>
<p>Now I want to navigate from firstPage to secondPage drag and drop the <strong>Control Flow case</strong> by dragging from firstPage to secondPage and name that navigation as <strong>gotoSecond</strong>. The taskflow diagram would be as shown below:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/11/BT_AfterControlFlow.jpg"><img class="aligncenter size-medium wp-image-4948" src="http://www.javabeat.net/wp-content/uploads/2012/11/BT_AfterControlFlow-300x177.jpg" alt="" width="300" height="177" /></a></p>
<p>And after all this lets have a look at the XML for the first-bounded-task-flow.xml:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;windows-1252&quot; ?&gt;
&lt;adfc-config xmlns=&quot;http://xmlns.oracle.com/adf/controller&quot; version=&quot;1.2&quot;&gt;
  &lt;task-flow-definition id=&quot;first-bounded-task-flow&quot;&gt;
    &lt;default-activity&gt;firstPage&lt;/default-activity&gt;
    &lt;view id=&quot;firstPage&quot;&gt;
      &lt;page&gt;/firstPage.jsf&lt;/page&gt;
    &lt;/view&gt;
    &lt;view id=&quot;secondPage&quot;&gt;
      &lt;page&gt;/secondPage.jsf&lt;/page&gt;
    &lt;/view&gt;
    &lt;control-flow-rule id=&quot;__1&quot;&gt;
      &lt;from-activity-id&gt;firstPage&lt;/from-activity-id&gt;
      &lt;control-flow-case id=&quot;__2&quot;&gt;
        &lt;from-outcome&gt;gotoSecond&lt;/from-outcome&gt;
        &lt;to-activity-id&gt;secondPage&lt;/to-activity-id&gt;
      &lt;/control-flow-case&gt;
    &lt;/control-flow-rule&gt;
  &lt;/task-flow-definition&gt;
&lt;/adfc-config&gt;
</pre>
<p>Now double click on firstPage view to get the firstPage.jsf and switch to the <strong>Source</strong> view. Now add the following code to the firstPage.jsf between the af:form tag:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;af:outputText value=&quot;This is first page&quot; id=&quot;ot1&quot;/&gt;
&lt;af:commandButton text=&quot;Goto Second Page&quot; id=&quot;cb1&quot; action=&quot;gotoSecond&quot;/&gt;
</pre>
<p>The above code shows- an output text to show some text and a button to navigate to the next page. The action attribute above is assigned the name of the control flowcase created above.</p>
<p>Now go back to the first-bounded-task-flow and double click on the secondPage view to get secondPage.jsf. In the secondPage.jsf add the following code between af:form tag:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;af:outputText value=&quot;This is second page&quot; id=&quot;ot1&quot;/&gt;
</pre>
<p>Now you have a bounded taskflow and go to the bounded taskflow and right click and then click on Run for the application to be deployed. It will run an Integrated Web Logic server and deploy the application to it.<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/11/BT_Run.jpg"><img class="aligncenter size-medium wp-image-4950" src="http://www.javabeat.net/wp-content/uploads/2012/11/BT_Run-173x300.jpg" alt="" width="173" height="300" /></a></p>
<p>Once the application runs- you will get a page which shows:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/11/firstPage.jpg"><img class="aligncenter size-full wp-image-4951" src="http://www.javabeat.net/wp-content/uploads/2012/11/firstPage.jpg" alt="" width="211" height="38" /></a><br />
Now clicking on the button would take you to the next page.</p>
<p>I have <a href="http://www.javabeat.net/wp-content/uploads/2012/11/BoundedTaskFlowCreation.zip">uploaded the project</a> for anyone who wants to look into the project.</p>
<p><strong>JSF Books:</strong></p>
<ul>
<li><a href="http://www.flipkart.com/java-server-faces-action-8177224190/p/itmdyufmtyhxpn5p?pid=9788177224191&amp;affid=suthukrish" target="_blank">Java Server Faces in Action</a> (<a href="http://astore.amazon.com/javabeat-20/detail/1932394125" target="_blank">Amazon.com</a>)</li>
<li><a href="http://www.flipkart.com/mastering-java-server-faces-8126505311/p/itmdytmgadkvfgce?pid=9788126505319&amp;affid=suthukrish" target="_blank">Mastering Java Server Faces (JSF)</a></li>
<li><a href="http://www.flipkart.com/core-javaserver-faces-8131761924/p/itmczyqfsafyyf9e?pid=9788131761922&amp;affid=TrackingID" target="_blank">Core Java Server Faces (JSF)</a> (<a href="http://astore.amazon.com/javabeat-20/detail/0131738860" target="_blank">Amazon.com</a>)</li>
</ul>
<p><strong> If you are interested in receiving the future java articles and tips from us, please</strong> <a href="http://www.javabeat.net/subscribe/">subscribe here</a>.</p>
<p><strong><span style="color: #000080;">If you have any doubts on ADF or Java Server faces (JSF), please post it in the comments section.</span> </strong></p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fauthor%2Fsanaulla%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/author/sanaulla/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/author/sanaulla/feed/" data-count="vertical" data-text="" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/11/how-to-create-bounded-taskflows-in-adf-using-jdeveloper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Book Review: Pro Java 7 NIO.2</title>
		<link>http://www.javabeat.net/2012/08/book-review-pro-java-7-nio-2/</link>
		<comments>http://www.javabeat.net/2012/08/book-review-pro-java-7-nio-2/#comments</comments>
		<pubDate>Thu, 23 Aug 2012 17:51:25 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Book Review]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4849</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>The Pro Java 7 NIO.2 book is all about the latest enhancements to the File NIO APIs added as part of Java 7. The book covers New Path and Paths API: A brief overview of the Path and Paths classes and how these can be used to represent a file/directory. Also explained are the different [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>The Pro Java 7 NIO.2 book is all about the latest enhancements to the File NIO APIs added as part of <a href="http://www.javabeat.net/category/java-7-0/">Java 7</a>.</p>
<h3>The book covers</h3>
<ul>
<li><strong>New Path and Paths API: </strong>A <a href="http://www.javabeat.net/2012/07/exploring-the-path-api-java-nio-enhancement-in-java-7/" target="_blank">brief overview of the Path</a> and Paths classes and how these can be used to represent a file/directory. Also explained are the different parts of a Path.</li>
<li><strong>Obtaining the Metadata of a given file: </strong>This covers <a href="http://www.javabeat.net/2012/07/obtaining-and-modifying-the-metadata-of-the-files-in-java-7-nio-2/" target="_blank">obtaining the metadata of the file</a> like ownership, permissions, size, modification, creation time and how this information various between a Unix and Windows platforms.</li>
<li><strong>Managing Symbolic and Hard links for files: </strong><a href="http://www.javabeat.net/2012/07/creating-hard-links-and-soft-links-for-a-file-in-java/" target="_blank">Creating Symbolic and Hard links</a> to files and directories.</li>
<li><strong>New Files API with new utility methods to operate on files and directories:</strong> A <a href="http://www.javabeat.net/2012/06/a-peek-files-utility-part-java-nio-package-java-7/" target="_blank">new Files class</a> is added which provides lot of <a href="http://www.javabeat.net/2012/06/creating-writing-reading-java-files-api-java-7/" target="_blank">utility methods to operate on the files and directories</a>. This book covers few of those APIs by providing simple sample programs.</li>
<li>Recursively visiting the directory using the FileVisitor API: This chapter shows how <a href="http://www.javabeat.net/2012/07/visiting-all-the-files-and-directories-for-a-directory-in-java-using-nio2/" target="_blank">one can recursively visit different directories</a> and also provides sample code for different scenarios where this API can be used.</li>
<li><strong>Watch Service API:</strong> This new API allows the developer to <a href="http://www.javabeat.net/2012/06/watchservice-api-java7-monitor-directory/" target="_blank">watch a given directory for various operations</a> like modify, create and delete and lets developer write code to be notifies of such events.</li>
<li><strong>Random Access Files:</strong> This chapter covers the API support for random access of files.</li>
<li><strong>Socket APIs:</strong> This chapter covers various ways in which one can write Client-Server applications and provides code samples for both blocking and non blocking APIs.</li>
<li><strong>Asynchronous APIs:</strong> This chapters covers performing <a href="http://www.javabeat.net/2012/08/reading-file-asynchronously-in-java/" target="_blank">Asynchronous read and write operations on file</a> and also Asynchronous socket programming.</li>
</ul>
<h3>Salient features of the book</h3>
<ul>
<li>covers all of the NIO enhancements added as part of Java 7.</li>
<li>provides complete code samples to help reader to try out the APIs.</li>
<li>starts chapter with a brief overview of the APIs, but more importance is on the complete code examples.</li>
<li>more of an hands on book and not suitable for reading without trying out the code.</li>
</ul>
<h3>Intended Audience</h3>
<p>This book is for people who are familiar with Java and have experience working or using File APIs. If you are familiar with the NIO APIs then that&#8217;s an added benefit. I would recommend this book if you want to explore the NIO2 enhancements added as part of Java 7. You need not read this book end-to-end in one sitting, one can always use this book as a reference and pick it up as and when you want to explore the API which it covers.</p>
<h3>Buy this book</h3>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank"><img class="alignleft alignnone" src="http://img6.flixcart.com/image/book/1/7/0/pro-java-7-nio-2-275x275-imad7wkerzzjzvnd.jpeg" alt="" width="95" height="125" /></a></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank">Pro Java 7 NIO.2</a> by Anghel Leonard (buy from <a href="http://astore.amazon.com/javabeat-20/detail/1430240113" target="_blank">Amazon.com</a> / <a href="http://astore.amazon.com/javabeat-20/detail/B006JPPN0W" target="_blank">Kindle Edition</a> )</p>
<p>Pro Java 7 NIO.2 addresses the three primary elements that offer new input/output (I/O) APIs in Java 7, giving you the skills to write robust, scalable Java applications.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/08/book-review-pro-java-7-nio-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Reading file asynchronously in Java</title>
		<link>http://www.javabeat.net/2012/08/reading-file-asynchronously-in-java/</link>
		<comments>http://www.javabeat.net/2012/08/reading-file-asynchronously-in-java/#comments</comments>
		<pubDate>Wed, 22 Aug 2012 18:20:21 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>
		<category><![CDATA[nio]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4846</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>We all are familiar with reading/writing file in a synchronous way. In Java 7 a new API was added to read/write the contents of the file asynchronously. The API is AsynchronousFileChannel. In this example lets look at how to read the contents of the file asynchronously. There are two approaches to read the contents asynchronously: [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>We all are familiar with reading/writing file in a synchronous way. In Java 7 a new API was added to read/write the contents of the file asynchronously. The API is <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/channels/AsynchronousFileChannel.html" target="_blank">AsynchronousFileChannel</a>.</p>
<p>In this example lets look at how to read the contents of the file asynchronously. There are two approaches to read the contents asynchronously:<br />
1. To use <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html" target="_blank">Future</a> class to wait for the result of the read operation.<br />
2. To use a callback defined by the <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/channels/CompletionHandler.html" target="_blank">CompletionHandler</a> to process the result of the Asynchronous operation.</p>
<pre class="brush: java; title: ; notranslate">
//Using Future class to read the contents of the file.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.concurrent.*;

public class AsyncFutureRead {

  public static void main(String[] args) {

    //Buffer to read the contents from the file.
    ByteBuffer buffer = ByteBuffer.allocate(100);

    //The file to read the contents from.
    Path path = Paths.get(&quot;D:/tests/test.txt&quot;);

    //Creating the asynchronous channel to the file which allows reading and writing of content.
    try(AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path)){

      //Returns a Future instance which can be used to read the contents of the file.
      Future&lt;Integer&gt; fileResult = asyncChannel.read(buffer, 0);

      //Waiting for the file reading to complete.
      while(!fileResult.isDone()){
        System.out.println(&quot;Waiting to complete the file reading ...&quot;);
      }

      //Print the number of bytes read.
      System.out.println(&quot;Number of bytes read: &quot;+fileResult.get());

      //Reset the current position of the buffer to the beginning and the limit to the current position.
      buffer.flip();

      //Decode the contents of the byte buffer.
      System.out.println(&quot;Contents of file: &quot;);
      System.out.println(Charset.defaultCharset().decode(buffer));

    }catch(IOException | InterruptedException | ExecutionException ex){
      ex.printStackTrace();
    }
  }
}
</pre>
<h3>Buy Pro Java 7 NIO.2</h3>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank"><img class="alignleft alignnone" src="http://img6.flixcart.com/image/book/1/7/0/pro-java-7-nio-2-275x275-imad7wkerzzjzvnd.jpeg" alt="" width="95" height="125" /></a></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank">Pro Java 7 NIO.2</a> by Anghel Leonard (buy from <a href="http://astore.amazon.com/javabeat-20/detail/1430240113" target="_blank">Amazon.com</a> / <a href="http://astore.amazon.com/javabeat-20/detail/B006JPPN0W" target="_blank">Kindle Edition</a> )</p>
<p>Pro Java 7 NIO.2 addresses the three primary elements that offer new input/output (I/O) APIs in Java 7, giving you the skills to write robust, scalable Java applications.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/08/reading-file-asynchronously-in-java/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to use Socket API for creating Client-Server application in Java</title>
		<link>http://www.javabeat.net/2012/08/how-to-use-socket-api-for-creating-client-server-application-in-java/</link>
		<comments>http://www.javabeat.net/2012/08/how-to-use-socket-api-for-creating-client-server-application-in-java/#comments</comments>
		<pubDate>Mon, 20 Aug 2012 17:56:55 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4842</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this example we make use of ServerSocketChannel and SocketChannel to create a simple Echo application where in the Server would print the data sent by the client. The code is explained with the required comments: and the client which connects to the server is:</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In this example we make use of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/channels/ServerSocketChannel.html" target="_blank">ServerSocketChannel</a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/channels/SocketChannel.html" target="_blank">SocketChannel</a> to create a simple Echo application where in the Server would print the data sent by the client. </p>
<p>The code is explained with the required comments:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * This creates a server on a particular IP address and the port.
 *
 */
public class ServerClass {

  public static void main(String[] args) {

    // Create a Server socket channel.
    try (ServerSocketChannel serverSocket = ServerSocketChannel.open()) {

      // Bind the server socket channel to the IP address and Port
      serverSocket.bind(new InetSocketAddress(&quot;127.0.0.1&quot;, 6667));
      System.out.println(&quot;Waiting for client connections&quot;);

      while (true) {
        
        //Wait and Accept the client socket connection. 
        try (SocketChannel socketChannel = serverSocket.accept()) {
          
          //Printing the address of the client.
          System.out.println(&quot;Obtained connection from: &quot;+socketChannel.getRemoteAddress().toString());
          
          //Creating a reader for reading the content on the socket input stream.
          Scanner socketReader = new Scanner(socketChannel.socket().getInputStream());
          while(socketReader.hasNext()){
            
            //Reading the content of the socket input stream.
            System.out.println(socketReader.nextLine());
            
          }

        } catch(IOException ex){
          ex.printStackTrace();
        }
      }

    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

}
</pre>
<p>and the client which connects to the server is:</p>
<pre class="brush: java; title: ; notranslate">
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

public class CilentClass {
  
  public static void main(String[] args) {
    
    //Create a client socket.
    try(SocketChannel socketChannel = SocketChannel.open()){
      
      //Bind the client socket to the server socket.
      socketChannel.connect(new InetSocketAddress(&quot;127.0.0.1&quot;, 6667));
      
      //Writing to the socket channel.
      PrintWriter writer = new PrintWriter(socketChannel.socket().getOutputStream(), true);
      writer.println(&quot;Client sending instruction 1&quot;);
      writer.println(&quot;Client sending instruction 2&quot;);
      writer.println(&quot;Client sending instruction 3&quot;);
      writer.println(&quot;Client sending instruction 4&quot;);
      
    }catch(IOException ex){
      ex.printStackTrace();
    }
    
  }
}
</pre>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/08/how-to-use-socket-api-for-creating-client-server-application-in-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to use ByteBuffer in Java?</title>
		<link>http://www.javabeat.net/2012/08/how-to-use-bytebuffer-in-java/</link>
		<comments>http://www.javabeat.net/2012/08/how-to-use-bytebuffer-in-java/#comments</comments>
		<pubDate>Mon, 06 Aug 2012 19:13:42 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[nio]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4836</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>ByteBuffer API has been in Java since 1.4. The name itself suggests that these contain bytes of data. The data to be stored in the buffer can be Integer (int, long), Characters (char), Floating value (double), all these are converted into bytes before being stored in the buffer array. ByteBuffer can be of two types- [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>ByteBuffer API has been in Java since 1.4. The name itself suggests that these contain bytes of data. The data to be stored in the buffer can be Integer (int, long), Characters (char), Floating value (double), all these are converted into bytes before being stored in the buffer array. ByteBuffer can be of two types- </p>
<ul>
<li>Direct ByteBuffer</li>
<li>Non-Direct ByteBuffer</li>
</ul>
<p><strong>Direct ByteBuffer</strong>: JVM tries to use Native IO operations on buffers which are created as direct i.e it doesnt load the buffer contents into another buffer and instead tries to use the buffer directly.<br />
There are a few essential properties of ByteBuffer:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ul>
<li>Limit: While writing to a buffer, <em>limit</em> indicates how many more bytes can be written, whereas while reading from a buffer <em>limit</em> indicates how many more bytes can be read.</li>
<li>Position: <em>Position</em> tracks how much data is written or can be read from a buffer.</li>
<li>Capacity: <em>Capacity</em> specifies the number of bytes a buffer can store. </li>
</ul>
<p><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html" title="ByteBuffer" target="_blank">ByteBuffer</a> provides plethora of methods to fetch data from the buffer and to add data to the buffer. The below code shows the use of those APIs:</p>
<pre class="brush: java; title: ; notranslate">
import java.nio.ByteBuffer;

public class ByteBufferTest {
  
  public static void main(String[] args) {

    //Create a directBuffer of size 200 bytes
    ByteBuffer directBuffer = ByteBuffer.allocateDirect(200);
    
    //Create a nonDirectBuffer of size 200 bytes
    ByteBuffer nonDirectBuffer = ByteBuffer.allocate(200);
    
    //Get the capacity of the buffer
    System.out.println(&quot;Capacity &quot;+nonDirectBuffer.capacity());
    
    //Get the position of the buffer
    System.out.println(&quot;Position &quot;+nonDirectBuffer.position() );
    
    //Add data of different types to the buffer
    nonDirectBuffer.putChar('A');
    nonDirectBuffer.putInt(10);
    nonDirectBuffer.putDouble(0.98);
    
    //Get the position of the buffer, would print 14 as its has 14 bytes of data
    System.out.println(&quot;Position &quot;+nonDirectBuffer.position() );
    nonDirectBuffer.putFloat(8.9f);
    
    //Fetch the data from buffer
    System.out.println(nonDirectBuffer.getChar(0));
    
    //A char is of 2 bytes, so fetch the integer at index 0+2=2bytes
    System.out.println(nonDirectBuffer.getInt(2));
    
    //A int is of 4 bytes so fetch the double value at index 2+4=6bytes
    System.out.println(nonDirectBuffer.getDouble(6));
    
    //A double is of 8 bytes so fetch the float value at index 6+8=14bytes
    System.out.println(nonDirectBuffer.getFloat(14));
   
  }
}

</pre>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/08/how-to-use-bytebuffer-in-java/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Lazy Initialization, Singleton Pattern and Double Checked locking</title>
		<link>http://www.javabeat.net/2012/07/lazy-initialisation-singleton-and-double-check-locking/</link>
		<comments>http://www.javabeat.net/2012/07/lazy-initialisation-singleton-and-double-check-locking/#comments</comments>
		<pubDate>Tue, 24 Jul 2012 17:21:48 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4779</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Lazy Initialization Lazy Initialization is a technique where one postpones the instantiation of a object until its first use. In other words the instance of a class is created when its required to be used for the first time. The idea behind this is to avoid unnecessary instance creation. But there are concerns related to [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h3>Lazy Initialization</h3>
<p><a href="http://en.wikipedia.org/wiki/Lazy_initialization" target="_blank"><strong>Lazy Initialization</strong></a> is a technique where one postpones the instantiation of a object until its first use. In other words the instance of a class is created when its required to be used for the first time. The idea behind this is to avoid unnecessary instance creation. But there are concerns related to using such approaches in a concurrent scenario. But before that lets see how lazy initialization looks:</p>
<pre class="brush: java; title: ; notranslate">
class ResourceManager{
  private Resource resource;
  public Resource getResource(){
    if ( resource == null ){
      resource = new Resource();
    }
    return resource;
  }
}
</pre>
<p>When the above code is executed in a multi threaded program the concern that immediately comes to the mind is the &#8220;Race condition&#8221;.<br />
Thread A would check that resource == null so it goes inside to create the instance but might go into Runnable status before it creates the Resource instance.<br />
Thread B also checks that resource == null and it goes ahead, creates the instance and uses it for its operations.<br />
Thread A comes back to running status and it also continues to create its own instance and start using it. </p>
<p>Now in the above case suppose we wanted both Thread A and Thread B to work on the same instance, but due to the race condition they would work on different instances. If the Resource instances has state information associated with it then it because a critical problem. Lets stop here and then see how Singleton is related to this.</p>
<h3>Singleton</h3>
<p><strong>Singleton</strong> is one of the Creational Design Patterns discussed in the GoF Design Patterns. The main idea behind the Singleton pattern is to control the creation of objects for a given class such that at any time there&#8217;s only one instance of that particular class. So lets see how we can implement the Singleton pattern:</p>
<pre class="brush: java; title: ; notranslate">
class Resource{
  private static Resource instance;
  public static Resource getInstance(){
    if ( instance == null){
      instance = new Resource();
    }
    return instance;
  }
}
</pre>
<p>where in the above example Resource is a singleton. This is very similar to the concept of lazy initialization and this as well suffers from the issues seen while using this is a multi threaded environment/program. </p>
<h3>Double Checked Locking</h3>
<p>One way to solve the problem with Lazy initialization and singleton in a multi threaded program is to declare the getInstance() or getResource() method as <strong>synchronized</strong>. But its a huge overhead because everytime the method is invoked it has to go through the process of waiting for the lock and then obtaining the lock and its unnecessary because its only once that the instance is created and all subsequent invocations would just return that instance. </p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>To work around this issue, <strong><a href="http://en.wikipedia.org/wiki/Double-checked_locking" target="_blank">Double Checked Locking</a></strong> is the pattern used. In this approach the methods are not synchronized instead the instance creation code is put in a synchronized block. Let me show an example:</p>
<pre class="brush: java; title: ; notranslate">
class Resource{
  private static Resource instance;
  public static Resource getInstance(){
    if ( instance == null ){
      synchronized(Resource.class){
        if ( instance == null ){
          instance = new Resource();
        }
      }/end of synchronized block.
    }
    return instance;
  }
}
</pre>
<p>In the above code there are two null checks- one outside the synchronized block and one within it. The synchronized block is executed at most once and any other thread trying to get instance would have to wait until the instantiation to complete. </p>
<p>The above approach also has some issues. The initialization of an object and the creation of instance of that class are 2 different operations. Once the instance of the class has been created that instance is then used to initialize the values of its state either with default values or some user defined values. Now between these 2 operations another thread might invoke the method to get the instance and sees that the instance is already not null and then proceeds with using that instance. Though its the correct instance we wanted the thread to use but that instance hasn&#8217;t been initialized yet. This issue is called as Unsafe Publication. <a href="http://www.javabeat.net/2012/07/book-review-java-concurrency-practice/" title="Book Review: Java Concurrency in Practice" target="_blank">Java Concurrency in Practice</a> book has a really good chapter on Java Memory Model and issues related to Safe Publication and Unsafe Publication of instances. </p>
<h3>Lazy Initialization holder class idiom</h3>
<p>One can read about this Lazy Initialization holder class Idiom in the interview with Joshua Bloch <a href="http://java.sun.com/developer/technicalArticles/Interviews/bloch_effective_08_qa.html" target="_blank">here</a>. It has been covered in Effective Java by Joshua Bloch and also in <a href="http://www.javabeat.net/2012/07/book-review-java-concurrency-practice/" title="Book Review: Java Concurrency in Practice" target="_blank">Java Concurrency in Practice</a>. Let me just share that idea here:</p>
<pre class="brush: java; title: ; notranslate">
class Resource{
  private static class ResourceHolder{
    static final Resource instance = new Resource();
  }
  public static Resource getInstance(){
    return ResourceHolder.instance;
  }
}
</pre>
<p>This takes advantage of: </p>
<ul>
<li>Eager Initialization</li>
<li>Class not initialized unless its used/loaded by the class loader the first time its used. </li>
</ul>
<p>Another <a href="http://www.coderanch.com/t/500367/threads/java/No-synchronization-there-Lazy-Initialization" target="_blank">interesting discussion</a> related to this on JavaRanch.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/lazy-initialisation-singleton-and-double-check-locking/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Visiting all the files and directories for a directory in Java using NIO2</title>
		<link>http://www.javabeat.net/2012/07/visiting-all-the-files-and-directories-for-a-directory-in-java-using-nio2/</link>
		<comments>http://www.javabeat.net/2012/07/visiting-all-the-files-and-directories-for-a-directory-in-java-using-nio2/#comments</comments>
		<pubDate>Sun, 22 Jul 2012 17:35:06 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>
		<category><![CDATA[nio2]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4769</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>At times we might want to search for some file in a directory traversing recursively into other directories with in that directory, I know getting the recursive program right at the first time is always a challenge. Or we might want to list all the contents of a directory. For all these operations the NIO2 [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>At times we might want to search for some file in a directory traversing recursively into other directories with in that directory, I know getting the recursive program right at the first time is always a challenge. Or we might want to list all the contents of a directory. For all these operations the <a href="http://www.javabeat.net/tag/nio2/" target="_blank">NIO2</a> enhancements in <a href="http://www.javabeat.net/category/java-j2ee/java-7-0/" target="_blank">Java 7</a> provides an API to recursively traverse through a path and another interface which can be extended to provide hooks for performing certain operations when a file is encountered or a directory is encountered. </p>
<p>The method used is: <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#walkFileTree%28java.nio.file.Path,%20java.util.Set,%20int,%20java.nio.file.FileVisitor%29" target="_blank">Files.walkFileTree</a>. There are 2 overloaded versions of this method: </p>
<pre class="brush: java; title: ; notranslate">
public static Path walkFileTree(Path start,
              Set&lt;FileVisitOption&gt; options,
              int maxDepth,
              FileVisitor&lt;? super Path&gt; visitor)
                       throws IOException
</pre>
<p>and </p>
<pre class="brush: java; title: ; notranslate">
public static Path walkFileTree(Path start,
    FileVisitor&lt;? super Path&gt; visitor)
             throws IOException
</pre>
<p>Currently <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileVisitOption.html" target="_blank">FileVisitOption</a> enum provides an option to specify whether or not to follow the symbolic links. The <strong>maxDepth</strong> restricts the number of levels the walkFileTree method would traverse into for a given directory. </p>
<p>The <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileVisitor.html" target="_blank">FileVisitor</a> interface is the major player in this operation. It has the following methods:</p>
<ul>
<li><strong>postVisitDirectory(T dir, IOException exc)</strong>: Invoked for a directory after entries in the directory, and all of their descendants, have been visited.</li>
<li><strong>preVisitDirectory(T dir, BasicFileAttributes attrs)</strong>: Invoked for a directory before entries in the directory are visited.</li>
<li><strong>visitFile(T file, BasicFileAttributes attrs)</strong>: Invoked for a file in a directory.</li>
<li><strong>visitFileFailed(T file, IOException exc)</strong>: Invoked for a file that could not be visited.</li>
</ul>
<p>Each of these methods return a <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileVisitResult.html" target="_blank">FileVisitResult</a>, which is another enum with the following constants:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ul>
<li><strong>CONTINUE</strong>: Continue.</li>
<li><strong>SKIP_SIBLINGS</strong>: Continue without visiting the siblings of this file or directory.</li>
<li><strong>SKIP_SUBTREE</strong>: Continue without visiting the entries in this directory.</li>
<li><strong>TERMINATE</strong>: Terminate.</li>
</ul>
<p>I have created a test dir with the following contents:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/07/Dir11.png"><img src="http://www.javabeat.net/wp-content/uploads/2012/07/Dir11.png" alt="" width="128" height="146" class="aligncenter size-full wp-image-4774" /></a><br />
and the dir1 contains:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/07/Dir21.png"><img src="http://www.javabeat.net/wp-content/uploads/2012/07/Dir21.png" alt="" width="128" height="127" class="aligncenter size-full wp-image-4775" /></a></p>
<p>Lets write a program to list all the text files in the folder: &#8220;D:\nioTestDir&#8221;. First we need to implement the FileVisitor interface. We can make use of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/SimpleFileVisitor.html">SimpleFileVisitor</a> class which implements the FileVisitor interface and provides default operations for all the methods.</p>
<pre class="brush: java; title: ; notranslate">
class TextFileVisitor extends SimpleFileVisitor&lt;Path&gt;{
  
  PathMatcher matcher;
  
  public TextFileVisitor(){
    
    matcher = FileSystems.getDefault().getPathMatcher(&quot;glob:*.txt&quot;);
    
  }
  
  @Override
  public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
      throws IOException {
    
    Path fileName = file.getFileName();
    
    if ( matcher.matches(fileName)){
      System.out.println(&quot;Found: &quot;+ file);
    }
    
    //Continue to search for other txt files
    return FileVisitResult.CONTINUE;
  }
  
}
</pre>
<p>and the complete program to find the &#8220;*.txt&#8221; files is:</p>
<pre class="brush: java; title: ; notranslate">
public class DirectoryScanner {
  
  public static void main(String[] args) throws IOException {
    
    Path rootPath = Paths.get(&quot;D:/nioTestDir&quot;);
    Files.walkFileTree(rootPath, new TextFileVisitor());
    
  }

}
</pre>
<p>the output: </p>
<pre class="brush: bash; title: ; notranslate">
Found: D:\nioTestDir\dir1\dir1Test1.txt
Found: D:\nioTestDir\dir1\dir1Test2.txt
Found: D:\nioTestDir\dir1\dir1Test3.txt
Found: D:\nioTestDir\test1.txt
Found: D:\nioTestDir\test2.txt
Found: D:\nioTestDir\test3.txt
</pre>
<p>This new API has made it really easy to traverse any given path to get the contents of the file/directory represented by the path. The above example was a simple way to list all the &#8220;.txt&#8221; files in the given path. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/visiting-all-the-files-and-directories-for-a-directory-in-java-using-nio2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Listing and filtering directory content using Java NIO2</title>
		<link>http://www.javabeat.net/2012/07/listing-and-filtering-directory-content-using-java-nio2/</link>
		<comments>http://www.javabeat.net/2012/07/listing-and-filtering-directory-content-using-java-nio2/#comments</comments>
		<pubDate>Thu, 19 Jul 2012 18:36:25 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>
		<category><![CDATA[nio2]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4766</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>The Files class provides a method- newDirectoryStream to get the Directory contents for a give path instance. There are other overloaded versions of newDirectoryStream method which take in filters to apply on the directory content. Listing all files in the directory Using Files.newDirectoryStream method gives an instance of DirectoryStream class which is a Iterable i.e [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>The <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html" title="Files" target="_blank">Files</a> class provides a method- <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream%28java.nio.file.Path%29" title="newDirectoryStream" target="_blank">newDirectoryStream</a> to get the Directory contents for a give path instance. There are other overloaded versions of newDirectoryStream method which take in filters to apply on the directory content. </p>
<h3>Listing all files in the directory</h3>
<p>Using <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream%28java.nio.file.Path%29" target="_blank">Files.newDirectoryStream</a> method gives an instance of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html" target="_blank">DirectoryStream</a> class which is a Iterable i.e one can get iterate over its contents. Also it implements AutoCloseable, Closeable which means that one can make use of try with resources to close the directory stream after use. </p>
<pre class="brush: java; title: ; notranslate">
Path basePath = Paths.get(&quot;D:/tests&quot;);

// Listing the files in the directory
System.out.println(&quot;All files:&quot;);
try (DirectoryStream&lt;Path&gt; pathList = Files.newDirectoryStream(basePath)) {
  for (Path path : pathList) {
    System.out.println(path.toString());
  }

} catch (IOException e) {

  e.printStackTrace();
}
</pre>
<p><strong>Output</strong>:</p>
<pre class="brush: bash; title: ; notranslate">
All files:
D:\tests\another_test.txt
D:\tests\DirectoryFilterTest.class
D:\tests\somDoc.docx
D:\tests\test1.txt
</pre>
<h3>Applying Filter using GLOB pattern</h3>
<p>In the above sample we listed all the files, we can even use regular expression strings to restrict the files to be obtained from the directory. This regular expression structure is called as a GLOB pattern. Some rules for Glob pattern are:</p>
<ul>
<li>* represents any number of characters</li>
<li>? represents a single character</li>
<li>{} represents a collection of patterns like {txt,doc}</li>
<li>[] represents a set of single characters like [A-Z], [0-9]</li>
</ul>
<p>Using the Glob pattern we would restrict to fetch only the txt files</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
try (DirectoryStream&lt;Path&gt; pathList = 
  Files.newDirectoryStream(basePath,&quot;*.txt&quot;)) {
  for (Path path : pathList) {
    System.out.println(path.toString());
  }

} catch (IOException e) {

  e.printStackTrace();
}
</pre>
<p><strong>Output</strong>:</p>
<pre class="brush: bash; title: ; notranslate">
All text files[Using Glob pattern]:
D:\tests\another_test.txt
D:\tests\test1.txt
</pre>
<h3>Applying filter using the DirectoryStream.Filter class</h3>
<p>Another approach to apply filter is to extend the <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.Filter.html" target="_blank">DirectoryStream.Filter</a> class and overrides its accept(Path) method. The paths for which the accept(Path) method returns true would be fetched and listed.<br />
The same example above implemented using DirectoryStream.Filter:</p>
<pre class="brush: java; title: ; notranslate">
System.out.println(&quot;All document files[Using Filter class]&quot;);
DirectoryStream.Filter&lt;Path&gt; documentFilter = new DirectoryStream.Filter&lt;Path&gt;() {

  @Override
  public boolean accept(Path entry) throws IOException {
    String fileName = entry.getFileName().toString();
    return fileName != null &amp;&amp; fileName.endsWith(&quot;txt&quot;);
  }

};
try (DirectoryStream&lt;Path&gt; pathList = Files.newDirectoryStream(basePath,
    documentFilter)) {
  for (Path path : pathList) {
    System.out.println(path.toString());
  }

} catch (IOException e) {

  e.printStackTrace();
}
</pre>
<p><strong>Output:</strong></p>
<pre class="brush: bash; title: ; notranslate">
All document files[Using Filter class]
D:\tests\another_test.txt
D:\tests\test1.txt
</pre>
<p>Its clear that for filtering based on file names glob patterns is the preferred approach and for filtering based on other parameters like file size, file attributes using DirectoryStream.Filter is the better approach. </p>
<p>The complete code for this can be found <a href="https://gist.github.com/3145846" target="_blank">here</a>.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/listing-and-filtering-directory-content-using-java-nio2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Playing with reduceLeft, reduceRight, foldLeft, foldRight API in Scala</title>
		<link>http://www.javabeat.net/2012/07/playing-with-reduceleft-reduceright-foldleft-foldright-api-in-scala/</link>
		<comments>http://www.javabeat.net/2012/07/playing-with-reduceleft-reduceright-foldleft-foldright-api-in-scala/#comments</comments>
		<pubDate>Wed, 18 Jul 2012 18:21:40 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4749</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In our previous post we saw in detail about the foreach. map, flatMap and collect methods in the Iterable trait. In this post we will look into detail about reduceLeft, reduceRight, foldLeft, foldRight methods of the Iterable trait. These methods are almost similar in the way the operate on the collection so it should be [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In our <a href="http://www.javabeat.net/2012/07/playing-with-collections-api-in-scala/" title="Playing with Collections API in Scala">previous post</a> we saw in detail about the foreach. map, flatMap and collect methods in the Iterable trait. In this post we will look into detail about reduceLeft, reduceRight, foldLeft, foldRight methods of the Iterable trait. These methods are almost similar in the way the operate on the collection so it should be easier to study them together. </p>
<p><strong>reduceLeft/reduceRight:</strong> The scala doc declares this method as:</p>
<pre class="brush: java; title: ; notranslate">reduceLeft[B &gt;: A](op: (B, A) ⇒ B): B</pre>
<p>which means that this method accepts a function which takes in 2 parameters and returns one value. And the way this method works is that it applies the operation/passed function on 2 elements at a time starting from left, and result of each application is used to compare with the next element until the end of list.<br />
Lets use this reduceLeft to find out the largest and smallest elements in the collection of numbers:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; numbers.reduceLeft((x,a) =&gt; if ( x &lt; a ) a else x)
res86: Int = 42
//smallest element
scala&gt; numbers.reduceLeft((x,a) =&gt; if ( x &lt; a) x else a)
res87: Int = 2
</pre>
<p>reduceRight is exactly similar to reduceLeft the only different being reduceRight applies the operation/passed function on the elements starting from the right of the list. </p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
scala&gt; val numbers = List(4,21,2,4,62,345,67)
numbers: List[Int] = List(4, 21, 2, 4, 62, 345, 67)

//finding maximum
scala&gt; numbers.reduceRight((x,v) =&gt; if (x &gt; v) x else v)
res0: Int = 345

//finding minimum
scala&gt; numbers.reduceRight((x,v) =&gt; if (x &lt; v) x else v)
res1: Int = 2
</pre>
<p><strong>foldLeft/foldRight:</strong> Exactly similar to the way reduceLeft/reduceRight work with a slight difference being foldLeft/foldRight take in an initial value and then apply the initial value to the first element(either leftmost/rightmost) before proceeding like reduceLeft/reduceRight.<br />
Suppose we want to find the sum of the elements in a list (I can use the &#8220;sum&#8221; method directly, but for understanding I would use  foldLeft/reduceLeft):</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; val numbers = List(1,2,3,4,5,6,7,8,9,10)
numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
//initial seed value of 0 gave the correct sum
scala&gt; numbers.foldLeft(0)((sum,x) =&gt; sum + x)
res0: Int = 55

//initial seed value of 10 added 10 to the final sum.
scala&gt; numbers.foldLeft(10)((sum,x) =&gt; sum + x)
res1: Int = 65
</pre>
<p>One another use of foldLeft is to find the factorial:</p>
<pre class="brush: java; title: ; notranslate">
//factorial of 5
scala&gt; 1.to(5).foldLeft(1)((prod,x)=&gt;prod*x)
res3: Int = 120

//factorial of 6
scala&gt; 1.to(6).foldLeft(1)((prod,x)=&gt;prod*x)
res4: Int = 720
</pre>
<p><strong>scanLeft/scanRight:</strong> It functions exactly similar to foldLeft/foldRight, but instead of returning one value these methods return a collection of values. These collection of values are nothing but the intermediate values obtained while the passed function was applied on the list of numbers.<br />
Lets look at the same factorial example using scanLeft/scanRight:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; 1.to(6).scanLeft(1)((prod,x)=&gt;prod*x)
res5: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 1, 2, 6, 24, 120, 720)

scala&gt; 1.to(6).scanRight(1)((prod,x)=&gt;prod*x)
res7: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 6, 30, 120, 360, 720, 720)
</pre>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/playing-with-reduceleft-reduceright-foldleft-foldright-api-in-scala/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Creating Hard links and Soft links for a file in Java</title>
		<link>http://www.javabeat.net/2012/07/creating-hard-links-and-soft-links-for-a-file-in-java/</link>
		<comments>http://www.javabeat.net/2012/07/creating-hard-links-and-soft-links-for-a-file-in-java/#comments</comments>
		<pubDate>Tue, 17 Jul 2012 15:46:13 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4752</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>We have been exploring the NIO enhancements in Java 7 and in this post I will explain about creating links- Hard links and Soft links in Java. And this feature is part of Java 7. A link is kind of substitute name to access a particular file/directory, something like an alias to the file/directory. This [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>We have been exploring the NIO enhancements in <a href="http://www.javabeat.net/category/java-7-0/" target="_blank">Java 7</a> and in this post I will explain about creating links- Hard links and Soft links in Java. And this feature is part of Java 7.</p>
<p>A link is kind of substitute name to access a particular file/directory, something like an alias to the file/directory. This way it allows us to refer to a file/directory by more than one name. There are 2 types of links that can be created:</p>
<ul>
<li><strong>Symbolic Links:</strong> These links refer to the file/directory path. And using these links can be used to directly operate on the path they refer to. In my daily work I use a lot of symbolic links and they are really flexible. In this case if the file to which the link refers to is deleted, the link continues to exist but it is not a valid link.</li>
<li><strong>Hard Links:</strong> These links are more stricter than symbolic links which refer to the physical location of the file. If the content of the original file is changed, the link also gets updated whereas if the original file is deleted, the link continues to exist and is valid file.</li>
</ul>
<h3>Creating Symbolic Links in Java</h3>
<p>Not all operating systems support creating symbolic links. The program I tried on Windows couldn&#8217;t create a symbolic link. But for creating symbolic link we make use of the <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createSymbolicLink(java.nio.file.Path, java.nio.file.Path, java.nio.file.attribute.FileAttribute...)" target="_blank">Files.createSymbolicLink</a> method which takes the link path as well as the target path, where both link and target are instances of type <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html" target="_blank">Path</a>.</p>
<h3>Creating Hard links in Java</h3>
<p>On Windows I was able to create the Hard links and for this we make use of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createLink(java.nio.file.Path, java.nio.file.Path)" target="_blank">Files.createLink</a> method which takes in link path and the target path.<br />
Lets look at the example where both soft link and hard links are created:<br />
Note: I tried this sample on Windows and Linux, but you can get better results in Linux, because I am not sure how to list the links in Windows.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
public class LinkTest {
  public static void main(String[] args) throws IOException {
    Path file1 = Paths.get(&quot;test1&quot;);
    System.out.println(file1.toRealPath());
    Path hLink = Paths.get(&quot;test1.hLink&quot;);
    Path sLink = Paths.get(&quot;test1.symLink&quot;);

    try{
      Files.createSymbolicLink(sLink, file1);

    }catch(UnsupportedOperationException ex){
      System.out.println(&quot;This OS doesn't support creating Sym links&quot;);
    }

    try{
      Files.createLink(hLink, file1);
      System.out.println(hLink.toRealPath());
    }catch(UnsupportedOperationException ex){
      System.out.println(&quot;This OS doesn't support creating Sym links&quot;);
    }

  }
}
</pre>
<h3>Buy Pro Java 7 NIO.2</h3>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank"><img class="alignleft alignnone" src="http://img6.flixcart.com/image/book/1/7/0/pro-java-7-nio-2-275x275-imad7wkerzzjzvnd.jpeg" alt="" width="95" height="125" /></a></p>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank">Pro Java 7 NIO.2</a> by Anghel Leonard (buy from <a href="http://astore.amazon.com/javabeat-20/detail/1430240113" target="_blank">Amazon.com</a> / <a href="http://astore.amazon.com/javabeat-20/detail/B006JPPN0W" target="_blank">Kindle Edition</a> )</p>
<p>Pro Java 7 NIO.2 addresses the three primary elements that offer new input/output (I/O) APIs in Java 7, giving you the skills to write robust, scalable Java applications.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/creating-hard-links-and-soft-links-for-a-file-in-java/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
