<?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>DEVHUB.FM</title>
	<atom:link href="http://DEVHUB.FM/feed/" rel="self" type="application/rss+xml" />
	<link>http://DEVHUB.FM</link>
	<description>Programming Articles and Tutorials</description>
	<lastBuildDate>Tue, 10 Jul 2012 22:41:21 +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>Debugging Oracle PL/SQL</title>
		<link>http://DEVHUB.FM/debugging-oracle-plsql/</link>
		<comments>http://DEVHUB.FM/debugging-oracle-plsql/#comments</comments>
		<pubDate>Wed, 14 Mar 2012 17:47:27 +0000</pubDate>
		<dc:creator>Mo</dc:creator>
				<category><![CDATA[ORACLE]]></category>
		<category><![CDATA[PL/SQL]]></category>
		<category><![CDATA[DBMS_DBMS_OUTPUT]]></category>
		<category><![CDATA[Debugging Oracle]]></category>
		<category><![CDATA[Debugging Oracle PL/SQL]]></category>
		<category><![CDATA[Debugging PLSQL]]></category>
		<category><![CDATA[DUAL]]></category>
		<category><![CDATA[EXEC]]></category>
		<category><![CDATA[Oracle 11G]]></category>
		<category><![CDATA[SQL Developer]]></category>
		<category><![CDATA[SQLCODE]]></category>
		<category><![CDATA[SQLERRM]]></category>

		<guid isPermaLink="false">http://DEVHUB.FM/?p=553</guid>
		<description><![CDATA[The purpose of this article is to cover techniques that are useful in debugging PL/SQL code, especially if you don&#8217;t have access to a debugger such as the one that comes packaged with SQL Developer (this has been the case for me &#8230; <a href="http://DEVHUB.FM/debugging-oracle-plsql/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>The purpose of this article is to cover techniques that are useful in debugging PL/SQL code, especially if you don&#8217;t have access to a debugger such as the one that comes packaged with SQL Developer (this has been the case for me a few times).</p>
<p>This article will cover the following topics:</p>
<ul>
<li>Using DBMS_DBMS_OUTPUT + PUT_LINE.</li>
<li>Using SELECT FROM DUAL.</li>
<li>Using raise_application_error + SQLCODE + SQLERRM.</li>
<li>Using the EXEC command.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://DEVHUB.FM/debugging-oracle-plsql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setting up an Oracle 11G Sandbox Development Environment</title>
		<link>http://DEVHUB.FM/setting-up-an-oracle-11g-sandbox-dev-environment/</link>
		<comments>http://DEVHUB.FM/setting-up-an-oracle-11g-sandbox-dev-environment/#comments</comments>
		<pubDate>Mon, 05 Mar 2012 21:22:27 +0000</pubDate>
		<dc:creator>Mo</dc:creator>
				<category><![CDATA[ORACLE]]></category>
		<category><![CDATA[PL/SQL]]></category>
		<category><![CDATA[Oracle 11G]]></category>
		<category><![CDATA[Oracle Development Environment]]></category>
		<category><![CDATA[Oracle Enterprise Manager]]></category>
		<category><![CDATA[Oracle SandBox Environment]]></category>
		<category><![CDATA[Oracle Virtual Machine]]></category>
		<category><![CDATA[SQL Developer]]></category>

		<guid isPermaLink="false">http://DEVHUB.FM/?p=510</guid>
		<description><![CDATA[This article will cover the following topics: Downloading, Installing &#38; Running the Oracle 11G Virtual Machine. Starting up Oracle 11G and launching Enterprise Manager. Logging in with SQL Developer 3.1 EA. Working with the Demo SCHEMA. Note:  I&#8217;m working on &#8230; <a href="http://DEVHUB.FM/setting-up-an-oracle-11g-sandbox-dev-environment/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>This article will cover the following topics:</p>
<ul>
<li>Downloading, Installing &amp; Running the Oracle 11G Virtual Machine.</li>
<li>Starting up Oracle 11G and launching Enterprise Manager.</li>
<li>Logging in with SQL Developer 3.1 EA.</li>
<li>Working with the Demo SCHEMA.</li>
</ul>
<p><em>Note:  I&#8217;m working on an IBM Thinkpad with Windows XP SP2 running at 1.6GHZ with 3.0GB of RAM. The VM is running on RedHat Linux.</em></p>
<p><strong>Downloading, Installing &amp; Running the Oracle 11G Virtual Machine.</strong></p>
<p>Step 1: You will want to download Oracle VM VirtualBox from here (avaliable for Windows/Mac/Solaris/Linux): <a title="Oracle VM VirtualBox Downlaod" href="http://www.oracle.com/technetwork/server-storage/virtualbox/downloads/index.html" target="_blank">Oracle VM VirtualBox Download.</a></p>
<p>If you don&#8217;t have an Oracle account you will have to create one for free.</p>
<p>Once the download is complete continue with the installation process. I used the default installation options throughout the install. Once the instillation is complete run the application and you should see a screen similar to this:</p>
<div id="attachment_513" class="wp-caption aligncenter" style="width: 310px"><a href="http://DEVHUB.FM/wp-content/uploads/2012/03/OracleVMVirtualBoxManager.jpg"><img class="size-medium wp-image-513" title="Oracle VM VirtualBox Manager" src="http://DEVHUB.FM/wp-content/uploads/2012/03/OracleVMVirtualBoxManager-300x226.jpg" alt="Oracle VM VirtualBox Manager" width="300" height="226" /></a><p class="wp-caption-text">Figure 1: Oracle VM VirtualBox Manager</p></div>
<p>Step 2: Next you will need to download the Virtual Image (Oracle Developer Day.ova) from here: <a title="Oracle Developer Days.ova" href="http://download.oracle.com/otn/other/virtualbox/dd/Oracle_Developer_Days.ova">Oracle Developer Day.ova </a></p>
<p>Step 3: Once the download is complete, we are ready to launch the VM.</p>
<ul>
<li>Using VM VirtualBox import your VM: File -&gt; Import Appliance to launch Appliance Import Wizard.</li>
<li>Click Choose&#8230; browse to the which contains Oracle Developer Days.ova (select the file) then click Next&gt; to begin importing the virtual machine.</li>
</ul>
<p>Step 4: Now we can launch the Oracle Dev Virtual Machine. Double-click the OTN Developer Days VM. Click OK to close the Virtualbox Information dialogs. The VM will launch and boot into RedHat Enterprise Linux 5 (this will take few minutes), once booted in you can login using the following credentials:<br />
User Name: oracle<br />
Password: oracle</p>
<div id="attachment_519" class="wp-caption aligncenter" style="width: 310px"><a href="http://DEVHUB.FM/wp-content/uploads/2012/03/OracleVMVirtualBoxManagerRunning.jpg"><img class="size-medium wp-image-519" title="Oracle VM Virtual Box Manager Running" src="http://DEVHUB.FM/wp-content/uploads/2012/03/OracleVMVirtualBoxManagerRunning-300x223.jpg" alt="Oracle VM Virtual Box Manager Running" width="300" height="223" /></a><p class="wp-caption-text">Figure 2: Oracle VM VirtualBox Manager Running</p></div>
<div id="attachment_520" class="wp-caption aligncenter" style="width: 310px"><a href="http://DEVHUB.FM/wp-content/uploads/2012/03/oraclevirtualmachine.jpg"><img class="size-medium wp-image-520" title="Oracle Virtual Machine logged-in" src="http://DEVHUB.FM/wp-content/uploads/2012/03/oraclevirtualmachine-300x162.jpg" alt="Oracle Virtual Machine logged-in" width="300" height="162" /></a><p class="wp-caption-text">Figure 3: Oracle Virtual Machine logged-in</p></div>
<p><strong>Starting up Oracle 11G and launching Enterprise Manager.</strong></p>
<p>Now that the Oracle VM is up and running we can start Oracle and login to the Enterprise Manager. In order to stat Oracle simply type &#8220;emctl start dbconsole&#8221; into the console which appeared on your desktop when you logged into GNOME and hit enter. This will launch Oracle Enterprise Manager 11G. It took a few minutes to bootup for me, but once it is booted up you can log-in by going to the folling URL in your VM&#8217;s web browser:</p>
<p>https://localhost.localdomain:1158/em/console/aboutApplication</p>
<p>User name: system<br />
Password: oracle<br />
Connect As: SYSDBA</p>
<div id="attachment_527" class="wp-caption aligncenter" style="width: 310px"><a href="http://DEVHUB.FM/wp-content/uploads/2012/03/OracleEnterpriseManager-11G.jpg"><img class="size-medium wp-image-527" title="Oracle Enterprise Manager 11G" src="http://DEVHUB.FM/wp-content/uploads/2012/03/OracleEnterpriseManager-11G-300x160.jpg" alt="Oracle Enterprise Manager 11G" width="300" height="160" /></a><p class="wp-caption-text">Figure 4: Oracle Enterprise Manager 11G</p></div>
<p><strong>Logging in with SQL Developer 3.1 EA</strong></p>
<p>The VM comes with oracle SQL Developer EA (the icon is on the desktop). I&#8217;ve been using SQL Developer for a while now and find it just as powerful as TOAD or any of the other mainstream Database IDE&#8217;s.</p>
<p>You can launch SQL Developer and login to the System account, you should see Auto-Generated Local Connections in the Connections pane on the left. Expand the Auto-Generated Local Connections branch, this will allow you to login to the system-oracle account (password: oracle).</p>
<p>Once connected to system-oracle, right click on system-oracle and select Scheme Browser, this will allow you to select the Demo schema which I will be referring to in other articles related to Oracle and PL/SQL.</p>
<div id="attachment_541" class="wp-caption aligncenter" style="width: 310px"><a href="http://DEVHUB.FM/wp-content/uploads/2012/03/OracleSQLDeveloperEA.jpg"><img class="size-medium wp-image-541" title="Oracle SQL Developer EA" src="http://DEVHUB.FM/wp-content/uploads/2012/03/OracleSQLDeveloperEA-300x163.jpg" alt="Oracle SQL Developer EA" width="300" height="163" /></a><p class="wp-caption-text"> Figure 5: Oracle SQL Developer EA</p></div>
<p>At this point you should have everything you need to start learning and experimenting with Oracle and PL/SQL in a consolidated Virtual Machine Environment!</p>
]]></content:encoded>
			<wfw:commentRss>http://DEVHUB.FM/setting-up-an-oracle-11g-sandbox-dev-environment/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IOC and Dependency Injection</title>
		<link>http://DEVHUB.FM/ioc-and-dependency-injection/</link>
		<comments>http://DEVHUB.FM/ioc-and-dependency-injection/#comments</comments>
		<pubDate>Thu, 16 Feb 2012 22:37:32 +0000</pubDate>
		<dc:creator>Mo</dc:creator>
				<category><![CDATA[Web Development Basics]]></category>
		<category><![CDATA[constructor injection example]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[DI Container]]></category>
		<category><![CDATA[Interface Injection example]]></category>
		<category><![CDATA[Inversion Of Control]]></category>
		<category><![CDATA[IOC]]></category>
		<category><![CDATA[IOC Container]]></category>
		<category><![CDATA[setter injection example]]></category>

		<guid isPermaLink="false">http://DEVHUB.FM/?p=255</guid>
		<description><![CDATA[Topics Covered: What is Inversion of Control and Dependency Injection? Lets write our own simple IOC container form scratch using Java and XML. What are some of the practical uses of IOC and DI? In figure 1 we have an &#8230; <a href="http://DEVHUB.FM/ioc-and-dependency-injection/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Topics Covered:</p>
<ul>
<li>What is Inversion of Control and Dependency Injection?</li>
<li>Lets write our own simple IOC container form scratch using Java and XML.</li>
<li>What are some of the practical uses of IOC and DI?</li>
</ul>
<div id="attachment_501" class="wp-caption aligncenter" style="width: 310px"><a href="http://DEVHUB.FM/wp-content/uploads/2012/02/dependencyInjection.jpg"><img src="http://DEVHUB.FM/wp-content/uploads/2012/02/dependencyInjection-300x155.jpg" alt="Figure 1: IOC and Dependency Injection" title="Figure 1: IOC and Dependency Injection" width="300" height="155" class="size-medium wp-image-501" /></a><p class="wp-caption-text">Figure 1: IOC and Dependency Injection</p></div>
<p>In figure 1 we have an arbitrary object called &#8220;AnObject&#8221; (item 1 in the image) and an arbitrary XML configuration defining our object attributes (item 2 in the image).  Inversion of Control describes an object creation flow/process in which objects are created and their attributes set or loaded dynamically at run-time via an IOC container. This is achieved using Dependency Injection (a design pattern).</p>
<p>There are three types of Dependency Injection:</p>
<ul>
<li>Interface injection: Is used when an object is defined by an interface that it must implemented in order to inject dependencies at runtime.</li>
<li>Setter injection: Is used to refer to an object exposing a setter method(s) to inject dependencies at run-time.</li>
<li>Constructor injection: Generally the same concept as setter injection except we utilize the constructor instead (this is what we use in our example below).</li>
</ul>
<p>The example below has been written using all three techniques (setter, constructor, and interface) so you can get a better idea of the differences.  The displayed and discussed code is the one which uses Constructor Injection, but all three versions are available for download at the end of the article.</p>
<p>For our example we will use Dependency Injection to inject object attributes defined in an XML configuration file (IOC-application-context.xml).</p>
<div id="attachment_414" class="wp-caption aligncenter" style="width: 310px"><a href="http://DEVHUB.FM/wp-content/uploads/2012/02/DevHubExampleIOCContainer.jpg"><img class="size-medium wp-image-414" title="DEVHUB Example IOC Container using Java and XML" src="http://DEVHUB.FM/wp-content/uploads/2012/02/DevHubExampleIOCContainer-300x164.jpg" alt="DEVHUB Example IOC Container using Java and XML" width="300" height="164" /></a><p class="wp-caption-text">Figure 2: DEVHUB Example IOC Container using Java and XML</p></div>
<p>Figure 2 above contains the components of our simple IOC Container application. We have the container itself (DevHubContainer.java), our objects Band.java and BandMember.java, and the configuration file defining our object dependencies and attributes (IOC-application-context.xml).</p>
<p><em>IOC-application-context.xml</em></p>
<pre class="crayon-plain-tag"><code>&lt;beans&gt;
	&lt;bean id=&quot;Robert&quot; class=&quot;fm.devhub.objects.BandMember&quot;&gt;
		&lt;property name=&quot;name&quot; value=&quot;Robert Plant&quot; /&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;Jimmy&quot; class=&quot;fm.devhub.objects.BandMember&quot;&gt;
		&lt;property name=&quot;name&quot; value=&quot;Jimmy Page&quot; /&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;John&quot; class=&quot;fm.devhub.objects.BandMember&quot;&gt;
		&lt;property name=&quot;name&quot; value=&quot;John Bonham&quot; /&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;Jones&quot; class=&quot;fm.devhub.objects.BandMember&quot;&gt;
		&lt;property name=&quot;name&quot; value=&quot;John Paul Jones&quot; /&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;Band&quot; class=&quot;fm.devhub.objects.Band&quot;&gt;
		&lt;property name=&quot;name&quot; value=&quot;Led Zeppelin&quot; /&gt;
		&lt;property name=&quot;label&quot; value=&quot;Atlantic&quot; /&gt;
		&lt;property name=&quot;genere&quot; value=&quot;Rock&quot; /&gt;
		&lt;property name=&quot;singer&quot; bean-reference=&quot;Robert&quot; ref-class=&quot;fm.devhub.objects.BandMember&quot;/&gt;
		&lt;property name=&quot;bass&quot; bean-reference=&quot;Jones&quot; ref-class=&quot;fm.devhub.objects.BandMember&quot; /&gt;
		&lt;property name=&quot;guitarist&quot; bean-reference=&quot;Jimmy&quot; ref-class=&quot;fm.devhub.objects.BandMember&quot;/&gt;
		&lt;property name=&quot;drummer&quot; bean-reference=&quot;John&quot; ref-class=&quot;fm.devhub.objects.BandMember&quot;/&gt;
	&lt;/bean&gt;	
&lt;/beans&gt;</code></pre></p>
<p>Lines 2-13:<br />
Here we define our simple Objects, we have members of a musical band belonging to the package fm.devhub.objects.BandMember, and one attribute defined which is the name of the band member.</p>
<p>Lines 14-22:<br />
We define our band Object. Its basically is composed of some attributes defining the name of the band etc. But also notice it defines some Object references, band-members. So when we construct our Band object, the IOC Container will know to include Objecs of type BandMember as well.</p>
<p><em>BandMember.java</em></p>
<pre class="crayon-plain-tag"><code>package fm.devhub.objects;

import java.util.ArrayList;

/*
 * This class resembles a Band Member Bean or POJO.  
 * Properties for our Band Member are injected using
 * our IOC Container &amp; Constructor Injection. 
 */
public class BandMember {

	private String name;
	
	public BandMember(){
	}
	
	public BandMember ( ArrayList&lt;String&gt; name ){
		
		this.name = (String) name.get(0);
	}
	public String toString() {
		return &quot;Member Name: &quot; + name;
	}
}</code></pre><p><p>Here we have a simple Object called BandMember, it has one attribute which defines the name of the band member. Because this example is using Constructor Injection, I didnt include any set or get methods. The object is constructed by our IOC container which injects the constructor value at runtime based on what is defined in IOC-application-context.xml.</p>
<p><em>Band.java</em></p><pre class="crayon-plain-tag"><code>package fm.devhub.objects;

import java.util.ArrayList;

/*
 * This class resembles a Band  Bean or POJO.  
 * Properties for our Band Member are injected using
 * our IOC Containe  and Constructor
 * Injection. 
 */
public class Band {

	private String name;
	private String label;
	private String genere;
	private BandMember singer;
	private BandMember bass;
	private BandMember guitarist;
	private BandMember drummer;

	public Band() {
	}

	public Band( ArrayList&lt;Object&gt; params ) {
		this.name = params.get(0).toString();
		this.label = params.get(1).toString();
		this.genere = params.get(2).toString();
		this.singer = (BandMember) params.get(3);
		this.bass = (BandMember) params.get(4);
		this.guitarist = (BandMember) params.get(5);
		this.drummer = (BandMember) params.get(6);
	}
	public String toString() {
		return &quot;Name: &quot; + name + &quot;\nLabel: &quot; + label + &quot;\nGenre: &quot; + genere + &quot;\nSinger &quot; + singer
				+ &quot;\nBass &quot; + bass + &quot;\nGuitarist &quot; + guitarist + &quot;\nDrummer &quot;
				+ drummer;
	}
}</code></pre><p><p>
<p>Band is very similar to BandMember. The only difference is that there are more attributes being set. Once again our IOC Container will inject those values at runtime based on the relationships defined in IOC-application-context.xml.</p>
<p><em>DevHubContainer.java</em></p>
<pre class="crayon-plain-tag"><code>package fm.devhub.ioccontainer;

//Import the Java classes
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;


//Import the Reflection classes
import java.lang.reflect.Constructor;

//Import the JDOM classes
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

/*
 * This is our simple IOC Container, it parses
 * IOC-application-context.xml and uses DI
 * to create and assemble the beans.
 */
public class DevHubContainer {

	/**
	 * Keeps track of all our bean nodes.
	 */
	private List&lt;Object&gt; beanList;

	

	/**
	 * Creates a new DevHubContainer that is configured by the specified XML
	 * filename, we use JDOM SAX to traverse through our XML document.
	 */
	public DevHubContainer(String application_context) {
		try {
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(application_context);
			Element root = doc.getRootElement();
			this.beanList = root.getChildren(&quot;bean&quot;);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Returns a configured bean based on the name for example: &lt;bean id=&quot;Band&quot;
	 * class=&quot;fm.devhub.objects.Band&quot;&gt; has the name 'Band'
	 */
	public Object getBean(String name) {

		// Iterate over our bean list, this was
		// populated during the instantiation of our
		// IOC container.
		for (Iterator i = this.beanList.iterator(); i.hasNext();) {
			Element bean = (Element) i.next();
			String id = bean.getAttributeValue(&quot;id&quot;);

			if (id.equals(name)) {
				try {
					String className = bean.getAttributeValue(&quot;class&quot;);
					List propertyList = bean.getChildren(&quot;property&quot;);
					ArrayList elementValue = new ArrayList();

					if (propertyList.size() &gt; 0) {
						for (Iterator it = propertyList.iterator(); it.hasNext();) {
							Element propertyElement = (Element) it.next();
							String propertyValue = propertyElement
									.getAttributeValue(&quot;value&quot;);
							String propertyReference = null;
							if (propertyValue == null) {
								propertyReference = propertyElement.getAttributeValue(&quot;bean-reference&quot;);
								Class refbeanClass = Class.forName( propertyElement.getAttributeValue(&quot;ref-class&quot;) );								
								Constructor[] refconstruct = refbeanClass.getConstructors();
								ArrayList&lt;String&gt; propertyReferenceValue = new ArrayList();
								propertyReferenceValue.add( propertyReference );
								Object refbeanInstance = refconstruct[1].newInstance(propertyReferenceValue);
								elementValue.add(refbeanInstance);
							} else {
								elementValue.add(propertyValue);
							}
						}
					}
					Class beanClass = Class.forName(className);
					Constructor[] construct = beanClass.getConstructors();
					Object beanInstance = construct[1].newInstance(elementValue);
					return beanInstance;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		// If no matching objects are found, then return null
		return null;
	}
}</code></pre><p><p><p>
<p>Lines 35-44:<br />
We build a parser using JDOM and pass it our IOC-application-context xml.</p>
<p>Lines 60-90:<br />
Here is the core of our IOC Container, we iterate over our application context, and create the objects defined. The objects are created very simply as follows:</p>
<pre>     Class beanClass = Class.forName(className);
     Constructor[] construct = beanClass.getConstructors();
     Object beanInstance = construct[1].newInstance(elementValue);</pre>
<p>elementValue is an ArrayList containing all of the values that need to be set in the objects constructor.</p>
<p><em>IOCContainerTest.java </em></p>
<pre class="crayon-plain-tag"><code>package fm.devhub.test;

import fm.devhub.ioccontainer.DevHubContainer;
import fm.devhub.objects.Band;
import fm.devhub.objects.BandMember;

public class IOCContainerTest {

	public static void main( String[] args ) {
		   /*
		    * We instantiate our IOC Container, and load our application-context
		    * Then we use IOCContainer.getBean() to inject our Band and BandMember bean 
		    * configuration attributes.
		    */
		   DevHubContainer IOCContainer = new DevHubContainer( &quot;C:\\IOC-application-context.xml&quot; );
		
		   BandMember Jimmy = ( BandMember )IOCContainer.getBean( &quot;Jimmy&quot; );
		   BandMember Robert = ( BandMember )IOCContainer.getBean( &quot;Robert&quot; );
		   BandMember John = ( BandMember )IOCContainer.getBean( &quot;John&quot; );
		   BandMember Jones = ( BandMember )IOCContainer.getBean( &quot;Jones&quot; );
				   
		   System.out.println( &quot;**** Test Band Member Beans****&quot; );
		   System.out.println( Jimmy.toString() );
		   System.out.println( Robert.toString() );
		   System.out.println( John.toString() );
		   System.out.println( Jones.toString() );
		   			
		   Band LedZepplin = (Band) IOCContainer.getBean(&quot;Band&quot;);
		   System.out.println( &quot;**** Test Band Bean****&quot; );
		   System.out.println(LedZepplin);
		   
	}
}</code></pre><p><p><p><p>
<p>The test case simply tests all of the objects defined in IOC-application-context.xml. Our simplest object definitions are the BandMembers where we only a name parameter is set. Slightly more complex is the Band object which is composed of a few attributes and a reference to the BandMembers.</p>
<p>Below is the output that should be generated when you run the test case.</p>
<p><em>Test case output:</em></p>
<pre>Member Name: Jimmy Page
Member Name: Robert Plant
Member Name: John Bonham
Member Name: John Paul Jones
**** Test Band Bean****
Name: Led Zeppelin
Label: Atlantic
Genre: Rock
Singer Member Name: Robert Plant
Bass Member Name: John Paul Jones
Guitarist Member Name: Jimmy Page
Drummer Member Name: John Bonham</pre>
<p><em>Errors I ran into while writing the example:</em></p>
<pre>java.lang.InstantiationException: fm.devhub.objects.BandMember
at java.lang.Class.newInstance0(Class.java:340)
at java.lang.Class.newInstance(Class.java:308)
at fm.devhub.objects.BandMember.main(BandMember.java:29)
Exception in thread "main" java.lang.NullPointerException
at fm.devhub.objects.BandMember.main(BandMember.java:30)

I ran into this error because i didn't use a default
constructor in my BandMember class.
The default constructor is automatically created
by java only when no other constructors
are present.</pre>
<p><strong>When is an IOC Container needed?</strong></p>
<p>The answer to this question is going to vary depending on what you are trying to accomplish as well as your personal programming style and requirements.</p>
<p>Generally you should consider adding Dependency Injection and IOC Container functionality  in the following scenarios:</p>
<ul>
<li>You need to inject configuration data into an object (for example database connection configuration).</li>
<li>You need to inject different implementations of the same object.</li>
<li>You need to inject the same dependency into objects</li>
</ul>
<p>Also, a very powerful side effect using an IOC Container and DI is that it <em>can</em>inherently simplify testing. Envision being able to mock up objects as needed for testing in your configuration (application context) file vs. having to connect to a database or call/stub a service. Also testing objects under multiple configurations is simple using DI and an IOC Container.</p>
<p>You do not need Dependency Injection in the following scenarios:</p>
<ul>
<li>You will not need different configurations for an object.</li>
<li>You will not need different implementations for an object.</li>
</ul>
<p>That said, IOC containers such as Spring IOC offer many useful features which are enabled by DI. After reading this article I would advise familiarizing yourself with Spring IOC (or any other main stream IOC framework) simply because it will give you better insight into best practices and industry standards for IOC implementations and testing approaches.</p>
<p><strong>What are some popular IOC Containers?</strong></p>
<ul>
<li>Spring IOC</li>
<li>Pico Container</li>
</ul>
<p><strong>Download Example Source:</strong><br />
<a href="http://DEVHUB.FM/wp-content/uploads/2012/02/DevHubIOCContainer_src.zip">Click here to download example source.</a></p>
<p><strong>Additional Reading:</strong><br />
<a title="Factory vs. Dependency Injection" href="http://stackoverflow.com/questions/557742/dependency-injection-vs-factory-pattern" target="_blank">Factory Pattern vs. Dependency Injection</a><br />
<a title="why-do-i-need-an-ioc-container-as-opposed-to-straightforward-di-code" href="http://stackoverflow.com/questions/871405/why-do-i-need-an-ioc-container-as-opposed-to-straightforward-di-code" target="_blank">Why do i need an IOC container as opposed to straightforward DI code</a><br />
<a title="http://martinfowler.com/articles/injection.html" href="http://martinfowler.com/articles/injection.html" target="_blank">Martin Fowler: Injection</a></p>
]]></content:encoded>
			<wfw:commentRss>http://DEVHUB.FM/ioc-and-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working with Oracle PL/SQL &#8211; Cursors</title>
		<link>http://DEVHUB.FM/oracle-plsql-cursors/</link>
		<comments>http://DEVHUB.FM/oracle-plsql-cursors/#comments</comments>
		<pubDate>Sun, 12 Feb 2012 23:43:04 +0000</pubDate>
		<dc:creator>Mo</dc:creator>
				<category><![CDATA[ORACLE]]></category>
		<category><![CDATA[PL/SQL]]></category>
		<category><![CDATA[Cursor]]></category>

		<guid isPermaLink="false">http://DEVHUB.FM/?p=201</guid>
		<description><![CDATA[Cursors A Cursor in PL/SQL is used to return rows of data from an SQL query (a ResultSet). You can iterate over a Cursor in a PL/SQL using a LOOP or return a Cursor to a calling entity such as &#8230; <a href="http://DEVHUB.FM/oracle-plsql-cursors/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><strong>Cursors</strong></p>
<p>A Cursor in PL/SQL is used to return rows of data from an SQL query (a ResultSet). You can iterate over a Cursor in a PL/SQL using a LOOP or return a Cursor to a calling entity such as a Java application. There are two types of Cursors in PL/SQL. Implicit and Explicit, the differences are as follows:</p>
<p><em>Implicit Cursors </em><br />
Implicit Cursors are indirectly created by Oracle when an INSERT, UPDATE, DELETE, or SELECT statement is executed. However, in the case of a SELECT statement implicit Cursors are only created when one row is returned, if more than one row is returned we must Explicitly declare a Cursor.</p>
<p><em>Explicit Cursors</em><br />
Explicit Cursors are explicitly declared in PL/SQL code and they return multiple rows from a SELECT statement. Once these rows are returned, the can be itereated over one at time using a LOOP construct inside of a Stored Procedure, Package, Function, etc. Or they can be returned to a calling application or procedure.</p>
<p>Here is an example of an Explicit Cursor being who&#8217;s resulset is be iterated over with a loop construct:</p>
<pre class="crayon-plain-tag"><code>-- Declaring the a Cursor
CURSOR MY_CORSOR is
    SELECT DISTINCT
    userid, username, first_name, last_name
    FROM T_USER WHERE
    username like '%o%'

    -- Looping through and executing when no records
    -- are found
    FOR MY_CURSOR_rec in MY_CORSOR
    LOOP
    EXIT WHEN MY_CORSOR%NOTFOUND;
        -- Execute some logic here for example
        IF MY_CURSOR_rec.username = 'mo' THEN
            -- Do Something
        END IF;
    END LOOP;</code></pre>
<p>If the Cursor above were executed.  A ResultSet similar to what is displayed below (Figure 1) could be returned, and with that ResultSet come a number of attributes that can be used to interact with the Cursor.</p>
<div id="attachment_253" class="wp-caption aligncenter" style="width: 668px"><a href="http://DEVHUB.FM/wp-content/uploads/2012/02/cursor.jpg"><img src="http://DEVHUB.FM/wp-content/uploads/2012/02/cursor.jpg" alt="Figure 1: Oracle PL/SQL Cursor Attributes" title="Figure 1: Oracle PL/SQL Cursor Attributes" width="658" height="264" class="size-full wp-image-253" /></a><p class="wp-caption-text">Figure 1: Oracle PL/SQL Cursor Attributes</p></div>
<p><strong>Cursor State and Status</strong></p>
<p>Oracle provides attributes for Cursors in order to evaluate their state. These attributes can be used in many situations, for example, if you look at Line 12 of the code above you will see we are using the %NOTFOUND attirbute. This is telling our loop to exit when no more rows are found in the Cursor.</p>
<p>Below are all of the attributes provided by ORACLE for identifying Cursor state:</p>
<p><em>%ISOPEN</em></p>
<ul>
<li>Returns TRUE if the cursor is open, FALSE if the cursor is closed.</li>
<li>Look at line 09  (below) for an example of how %ISOPEN can be used.</li>
</ul>
<p><em>%FOUND</em></p>
<ul>
<li>Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed.</li>
<li>Returns NULL if cursor is open, but fetch has not been executed.</li>
<li>Returns TRUE if a successful fetch has been executed.</li>
<li>Returns FALSE if no row was returned.</li>
<li>Look at line 15 (below) for an example of how %FOUND can be used.</li>
</ul>
<p><em>%NOTFOUND</em></p>
<ul>
<li>Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed.</li>
<li>Return NULL if cursor is open, but fetch has not been executed.</li>
<li>Returns FALSE if a successful fetch has been executed.</li>
<li>Returns TRUE if no row was returned.</li>
<li>This was covered in line 12 of the example above.</li>
</ul>
<p><em>%ROWCOUNT</em></p>
<ul>
<li>Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed.</li>
<li>Returns the number of rows fetched.</li>
<li>The ROWCOUNT attribute doesn&#8217;t give the real row count until you have iterated through the entire cursor. In other words, you shouldn&#8217;t rely on this attribute to tell you how many rows are in a cursor after it is opened.</li>
</ul>
<pre class="crayon-plain-tag"><code>DECLARE
CURSOR USERS_CR IS
    SELECT userid,username, useraddress
    FROM user
    WHERE username like '%Mo%';

    USERS_CR_row USERS_CR%ROWTYPE;
    BEGIN
        IF (NOT USERS_CR%ISOPEN) THEN
            OPEN USERS_CR;
        END IF;

    FETCH USERS_CR INTO USERS_CR_row;

    WHILE (USERS_CR_row%FOUND)LOOP

        --Execute some logic here....

        FETCH USERS_CR INTO USERS_CR_row;
    END LOOP;
    IF (USERS_CR%ISOPEN)THEN
        CLOSE USERS_CR;
    END IF;
END;</code></pre><p>
<p><strong>Additional Reading:</strong><br />
<a title="ORACLE PL/SQL Documenation" href="http://docs.oracle.com/cd/B10501_01/appdev.920/a96624/toc.htm">ORACLE PL/SQL Documentation</a></p>
]]></content:encoded>
			<wfw:commentRss>http://DEVHUB.FM/oracle-plsql-cursors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring 3.0 Hibernate Template Utility Project Part 1</title>
		<link>http://DEVHUB.FM/spring-3-0-hibernate-template-utility-project-part-1-2/</link>
		<comments>http://DEVHUB.FM/spring-3-0-hibernate-template-utility-project-part-1-2/#comments</comments>
		<pubDate>Mon, 06 Feb 2012 19:21:50 +0000</pubDate>
		<dc:creator>Mo</dc:creator>
				<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[hibernate utility project]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://DEVHUB.FM/?p=98</guid>
		<description><![CDATA[The following topics will be discussed in this article: Downloading &#38; Installing SpringSource Tool Suite (STS) Version: 2.8.1. Setting up a Spring Hibernate Template Utility project. Executing the packaged Hibernate Test Case. A detailed walk through of the Spring Hibernate &#8230; <a href="http://DEVHUB.FM/spring-3-0-hibernate-template-utility-project-part-1-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>The following topics will be discussed in this article:</p>
<ul>
<li>Downloading &amp; Installing SpringSource Tool Suite (STS) Version: 2.8.1.</li>
<li>Setting up a Spring Hibernate Template Utility project.</li>
<li>Executing the packaged Hibernate Test Case.</li>
<li>A detailed walk through of the Spring Hibernate Template Utility project components.</li>
</ul>
<p><strong>Downloading &amp; Installing SpringSource Tool Suite (STS) Version: 2.8.1.</strong><br />
SpringSource Tool Suite (STS) can be downloaded for free from the Spring website: <a title="Download the latest version of Spring STS" href="http://www.springsource.org/springsource-tool-suite-download">Spring STS Download</a><br />
<em>Note: For this example I am downloading springsource-tool-suite-2.8.1.RELEASE-e3.7.1-win32-installer.exe installed at C:\springsource using java version &#8220;1.6.0_16&#8243;. I followed the default installation options until complete.</em></p>
<p>Once the installation is complete launch STS. Close the welcome screen, your setup should look very similar to this:</p>
<div id="attachment_204" class="wp-caption aligncenter" style="width: 310px"><a href="http://mannyit.files.wordpress.com/2012/02/sts1.jpg"><img class="size-medium wp-image-204" title="Figure 1: Spring Source Tools Home Screen" src="http://mannyit.files.wordpress.com/2012/02/sts1.jpg?w=300" alt="Spring Source Tools Home Screen" width="300" height="211" /></a><p class="wp-caption-text">Figure1: Spring Source Tools Home Screen</p></div>
<p><strong>Setting up the Spring Hibernate Template Utility Project</strong><br />
Next lets create Spring Hibernate Template Utility Project. In STS execute the following steps:</p>
<ol>
<li>Click on File &#8211;&gt; New &#8211;&gt; Spring Template Project. Select Simple Spring Hibernate Utility Project and click Next. (I set my project name to &#8216;SpringHibernateTemplateProject&#8217; and defined the top level package as &#8216;fm.devhub.myspringutility&#8217;).</li>
<li>You will see an alert notifying you to download the necessary resources, click Yes. What this will do is pull down the necessary libraries for your project to build correctly.</li>
</ol>
<p><em>Note: Ensure your proxy settings are configured if you use one. Otherwise the files will not be able to download. You can set them by going to the Window menu &#8211;&gt; Preferences &#8211;&gt; General &#8211;&gt; Network Connections.</em></p>
<div id="attachment_348" class="wp-caption aligncenter" style="width: 310px"><a href="http://mannyit.files.wordpress.com/2012/02/spring3-0hibernateutility.jpg"><img class="size-medium wp-image-348" title="Figure 2: New Spring 3.0 Hibernate Utility Project" src="http://mannyit.files.wordpress.com/2012/02/spring3-0hibernateutility.jpg?w=300" alt="Figure 2: New Spring 3.0 Hibernate Utility Project" width="300" height="82" /></a><p class="wp-caption-text">Figure 2: New Spring 3.0 Hibernate Utility Project</p></div>
<p><strong>Executing the packaged Hibernate Test Case.</strong><br />
The goal of the Hibernate Utility Template is to provide all the libraries you need to get started with using Hibernate and a simple test case with a few beans configured, this will allow you expand/extend Hibernate functionality with ease. Upon execution of the provided test case (OrderPersistenceTests) we can verify that the project as provided is working correctly.</p>
<p>To run the provided test case right click on &#8216;OrderPersistenceTests&#8217; in the fm.devhub.myspringutility package of the src/test/java directory. Click Run as &#8211;&gt; JUnit Test. You should see as JUnit Panel in the left indicating that all of the configured test executed without any errors.</p>
<div id="attachment_352" class="wp-caption aligncenter" style="width: 310px"><a href="http://mannyit.files.wordpress.com/2012/02/spring3-0hibernateutilitytestsuccess.jpg"><img class="size-medium wp-image-352" title="Figure 3: Spring3.0 Hibernate Utility Test Success" src="http://mannyit.files.wordpress.com/2012/02/spring3-0hibernateutilitytestsuccess.jpg?w=300" alt="Figure 3: Spring3.0 Hibernate Utility Test Success" width="300" height="163" /></a><p class="wp-caption-text">Figure 3: Spring3.0 Hibernate Utility Test Success</p></div>
<p><strong>A detailed walk through of the Spring Hibernate Template Utility project components.</strong><br />
In this section we will step through most of the files &amp; code included in the Hibernate Utility Project. Although this should be considered skimming the surface of both Spring and Hibernate, you should come away with a basic understanding of how both frameworks work together. Also, Part 2 of this tutorial will cover both frameworks more deeply as well as incorporating the use of a non-embedded database (MySQL for example).</p>
<p><strong><em>HibernateConfiguration.java</em></strong></p><pre class="crayon-plain-tag"><code>package fm.devhub.myspringutility;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.dialect.H2Dialect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

@Configuration
public class HibernateConfiguration {

@Value(&quot;#{dataSource}&quot;)
private DataSource dataSource;

@Bean
public AnnotationSessionFactoryBean sessionFactoryBean() {
Properties props = new Properties();
props.put(&quot;hibernate.dialect&quot;, H2Dialect.class.getName());
props.put(&quot;hibernate.format_sql&quot;, &quot;true&quot;);

AnnotationSessionFactoryBean bean = new AnnotationSessionFactoryBean();
bean.setAnnotatedClasses(new Class[]{Item.class, Order.class});
bean.setHibernateProperties(props);
bean.setDataSource(this.dataSource);
bean.setSchemaUpdate(true);
return bean;
}

@Bean
public HibernateTransactionManager transactionManager() {
return new HibernateTransactionManager( sessionFactoryBean().getObject() );
}

}</code></pre><p><em>Line 14:</em><br />
The @Configuration annotation denotes that the Bean is a configuration bean. Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions and in this case its being used to configure the Hibernate Datasource. In order to understand how annotations and IOC works, i would recommend reading this article (its also referenced in the additional reading section below): <a title="IOC &amp; Dependency Injection " href="http://martinfowler.com/articles/injection.html" target="_blank">Martin Fowler: IOC &amp; Dependency Injection</a></p>
<p><em>Line 17:</em><br />
@Bean plays the same role as the Bean XML tag in a spring configuration file. We are simply moving the configuration to Java instead of XML. Whether or not you would like to use annotations is completely up to you.</p>
<p><em>Line 21:</em><br />
AnnotationSessionFactoryBean is a factory that produces SessionFactory automatically (Spring handles this internally). So in essence the inclusion of AnnotationSessionFactoryBean ensures that the bean will receive an immutable instance of a Hibernate Session on which Hibernate operations can be executed.</p>
<p><em>Line 35:</em><br />
The HibernateTransactionManager creates a Transaction Manager to manage database transactions for our bean. In Part 2 of this tutorial we will delve further into transaction managers and transaction intercepters.</p>
<p>So in summary the class above using Java annotations have substituted the need for the a Spring bean configuration in XML.</p>
<p><strong><em>Item.java</em></strong></p>
<pre class="crayon-plain-tag"><code>package fm.devhub.myspringutility;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

/**
* An item in an order
*/
@Entity
public class Item {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne
private Order order;

private String product;

private double price;

private int quantity;

/**
* @return the order
*/
public Order getOrder() {
return order;
}

/**
* @return the product
*/
public String getProduct() {
return product;
}

/**
* @param product
* the product to set
*/
public void setProduct(String product) {
this.product = product;
}

/**
* @return the price
*/
public double getPrice() {
return price;
}

/**
* @param price
* the price to set
*/
public void setPrice(double price) {
this.price = price;
}

/**
* @return the quantity
*/
public int getQuantity() {
return quantity;
}

/**
* @param quantity
* the quantity to set
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}

/**
* @return the id
*/
public Long getId() {
return id;
}

}</code></pre><p><p><em>Line 13:</em><br />
This is the Entity Bean declaration. The concept in Spring for an Entity bean mirrors the J2EE concept of an Entity bean in the sense that Entity beans represent a business object in a persistent storage mechanism. Basically an entity defines a table in a relational database where each instance of the bean would correlate to a row in that table.</p>
<p><em>Lines 16-17:</em><br />
The Bean ID is equivalent to a unique ID associated with a row in a database table. There are five different strategies for generating Bean id&#8217;s and they are TABLE, SEQUENCE, IDENTITY, AUTO, and NONE. In this case we are using AUTO.</p>
<p>They are defined as follows:</p>
<pre>AUTO Indicates that the persistence provider should pick an appropriate strategy for the particular database.
IDENTITY Indicates that the persistence provider must assign primary keys for the entity using database identity column.
SEQUENCE Indicates that the persistence provider must assign primary keys for the entity using database sequence column.
TABLE Indicates that the persistence provider must assign primary keys for the entity using an underlying database table to ensure uniqueness.</pre>
<p><em>Line 20:</em><br />
A @ManyToOne annotation is used to denote that the relationship is associated with the Order object, indicating that an Order can contain many Products.</p>
<p><em>Order.java</em></p>
<pre class="crayon-plain-tag"><code>package fm.devhub.myspringutility;

import java.util.Collection;
import java.util.LinkedHashSet;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
* An order.
*/
@Entity
@Table(name=&quot;T_ORDER&quot;)
public class Order {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

private String customer;

@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name=&quot;ORDER_ID&quot;)
private Collection items = new LinkedHashSet();

/**
* @return the customer
*/
public String getCustomer() {
return customer;
}

/**
* @param customer the customer to set
*/
public void setCustomer(String customer) {
this.customer = customer;
}

/**
* @return the items
*/
public Collection getItems() {
return items;
}

/**
* @param items the items to set
*/
public void setItems(Collection items) {
this.items = items;
}

/**
* @return the id
*/
public Long getId() {
return id;
}

}</code></pre><p><p>
<p><em>Line 20:</em><br />
This is the Entity Bean declaration. The concept in Spring for an Entity bean mirrors the J2EE concept of an Entity bean in the sense that Entity beans represents a business object in a persistent storage mechanism. Basically an entity defines a table in a relational database where each instance of the bean would correlate to a row in that table.</p>
<p><em>Line 21:</em><br />
@Table(name=&#8221;T_ORDER&#8221;) creates a table called T_ORDER which is mirrored to our Order.java class.</p>
<p><em>Lines 24-25:</em><br />
As mentioned above, the Bean ID is equivalent to a unique ID associated with a row in a database table. There are five different strategies for generating Bean id&#8217;s and they are TABLE, SEQUENCE, IDENTITY, AUTO, and NONE. In this case we are using AUTO.</p>
<p>They are defined as follows:</p>
<pre>AUTO Indicates that the persistence provider should pick an appropriate strategy for the particular database.
IDENTITY Indicates that the persistence provider must assign primary keys for the entity using database identity column.
SEQUENCE Indicates that the persistence provider must assign primary keys for the entity using database sequence column.
TABLE Indicates that the persistence provider must assign primary keys for the entity using an underlying database table to ensure uniqueness.</pre>
<p><em>Lines 30-31:</em><br />
The cascade option is used to cascade the required operations to the associated entity. If the cascade option is set to CascadeType.ALL then all the operations will be cascaded. For this example we have CascadeType.ALL on the &#8216;private Collection items = new LinkedHashSet();&#8217; object in association with line 31 &#8220;@JoinColumn(name=&#8221;ORDER_ID&#8221;)&#8221;. In other words of an Item is created, then an Order will be created as well.</p>
<p>Specifically Cascade.ALL does the following:</p>
<pre>CascadeType.PERSIST: cascades the persist (create) operation to associated entities persist() is called or if the entity is managed
CascadeType.MERGE: cascades the merge operation to associated entities if merge() is called or if the entity is managed
CascadeType.REMOVE: cascades the remove operation to associated entities if delete() is called
CascadeType.REFRESH: cascades the refresh operation to associated entities if refresh() is called
CascadeType.DETACH: cascades the detach operation to associated entities if detach() is called

CascadeType.ALL: all of the above</pre>
<p>You can find more information on this in the Hibernate Reference Documentation: <a title="Hibernate Reference Documentation" href="http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/" target="_blank">Hibernate Reference Documentation</a></p>
<p><strong><em>OrderPersistenceTests.java</em></strong></p>
<pre class="crayon-plain-tag"><code>package fm.devhub.myspringutility;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class OrderPersistenceTests {

@Autowired
private SessionFactory sessionFactory;

@Test
@Transactional
public void testSaveOrderWithItems() throws Exception {
Session session = sessionFactory.getCurrentSession();
Order order = new Order();
order.getItems().add(new Item());
session.save(order);
session.flush();
assertNotNull(order.getId());
}

@Test
@Transactional
public void testSaveAndGet() throws Exception {
Session session = sessionFactory.getCurrentSession();
Order order = new Order();
order.getItems().add(new Item());
session.save(order);
session.flush();
// Otherwise the query returns the existing order (and we didn't set the
// parent in the item)...
session.clear();
Order other = (Order) session.get(Order.class, order.getId());
assertEquals(1, other.getItems().size());
assertEquals(other, other.getItems().iterator().next().getOrder());
}

@Test
@Transactional
public void testSaveAndFind() throws Exception {
Session session = sessionFactory.getCurrentSession();
Order order = new Order();
Item item = new Item();
item.setProduct(&quot;foo&quot;);
order.getItems().add(item);
session.save(order);
session.flush();
// Otherwise the query returns the existing order (and we didn't set the
// parent in the item)...
session.clear();
Order other = (Order) session
.createQuery( &quot;select o from Order o join o.items i where i.product=:product&quot;)
.setString(&quot;product&quot;, &quot;foo&quot;).uniqueResult();
assertEquals(1, other.getItems().size());
assertEquals(other, other.getItems().iterator().next().getOrder());
}

}</code></pre><p><p><p>
<p><em>Lines 15-16:</em><br />
These annotations load the default configuration context for Spring as well as the &#8216;SpringJUnit4ClassRunner.class&#8217; for JUnit testing. What SpringJUnit4ClassRunner.class does is provide JUnit4.4 functionality alongside with Spring TestContext framework functionality. If you notice on Line 23 for example, we are using the @Transactional annotation which is apart of the TestContext framework. I would recommend reading this article if you are not familiar with Springs TestContext: <a title="Spring 3.0.5 TestContext Framework" href="http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/testing.html#testcontext-framework" target="_blank">Spring 3.0.5 TestContext Framework</a></p>
<p><em>Lines 19-20:</em><br />
@Autowired in this case is basically ensuring that the Hibernate SessionFactory is injected into the Bean prior to the execution of any other Bean configuration items. @AutoWired ensures that fields are injected right after construction of a bean, before any config methods are invoked. In this case we are applying to the SessionFactory which makes sense as none of the test cases can execute without a Hibernate Session available.</p>
<p><em>Lines 22-23:</em><br />
@Test is a JUnit annotation made accessible to us by the SpringJunit4ClassRunner which was loaded on line 16. The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. @Transactional enables transactions for the particular method.</p>
<p><em>Lines 25-30:</em><br />
Here we are executing a basic test case asserting that an Order ID is returned after an order has been added to the database.</p>
<p><strong>Additional Reading:</strong><br />
<a title="Martin Fowler: IOC &amp; Dependency Injection" href="http://martinfowler.com/articles/injection.html" target="_blank">Martin Fowler: IOC &amp; Dependency Injection</a><br />
<a title="Spring 3.0.5 TestContext Framework" href="http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/testing.html#testcontext-framework" target="_blank">Spring 3.0.5 TestContext Framework</a></p>
<p>Thanks for reading! If you find any technical inaccuracies or deficiencies in this article, please make devhub.fm aware by posting a comment. Any feedback is welcome &amp; encouraged.</p>
]]></content:encoded>
			<wfw:commentRss>http://DEVHUB.FM/spring-3-0-hibernate-template-utility-project-part-1-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring 3.0 MVC Template Introduction</title>
		<link>http://DEVHUB.FM/spring-3-0-mvc-template-introduction-2/</link>
		<comments>http://DEVHUB.FM/spring-3-0-mvc-template-introduction-2/#comments</comments>
		<pubDate>Sun, 05 Feb 2012 01:23:56 +0000</pubDate>
		<dc:creator>Mo</dc:creator>
				<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[Spring MVC 3.0]]></category>
		<category><![CDATA[Spring MVC Template]]></category>
		<category><![CDATA[Spring MVC Tutorial]]></category>

		<guid isPermaLink="false">http://DEVHUB.FM/?p=56</guid>
		<description><![CDATA[The following topics will be discussed in this article: Downloading &#38; Installing SpringSource Tool Suite (STS) Version: 2.8.1. Setting up a Spring MVC Template project. Deploying the packaged Hello World application. A walk through of all Spring MVC Template components. &#8230; <a href="http://DEVHUB.FM/spring-3-0-mvc-template-introduction-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>The following topics will be discussed in this article:</p>
<ul>
<li>Downloading &amp; Installing SpringSource Tool Suite (STS) Version: 2.8.1.</li>
<li>Setting up a Spring MVC Template project.</li>
<li>Deploying the packaged Hello World application.</li>
<li>A walk through of all Spring MVC Template components.</li>
</ul>
<p><strong>Downloading &amp; Installing SpringSource Tool Suite (STS) Version: 2.8.1.</strong><br />
SpringSource Tool Suite (STS) can be downloaded for free from the Spring website: <a title="Download the latest version of Spring STS" href="http://www.springsource.org/springsource-tool-suite-download">Spring STS Download</a><br />
<em>Note: For this example I am downloading springsource-tool-suite-2.8.1.RELEASE-e3.7.1-win32-installer.exe installed at C:\springsource using java version &#8220;1.6.0_16&#8243;. I followed the default installation options until complete.</em></p>
<p>Once the installation is complete launch STS. Close the welcome screen, your setup should look very similar to this:</p>
<div id="attachment_204" class="wp-caption aligncenter" style="width: 310px"><a href="http://mannyit.files.wordpress.com/2012/02/sts1.jpg"><img class="size-medium wp-image-204" title="Figure 1: Spring Source Tools Home Screen" src="http://mannyit.files.wordpress.com/2012/02/sts1.jpg?w=300" alt="Spring Source Tools Home Screen" width="300" height="211" /></a><p class="wp-caption-text">Figure1: Spring Source Tools Home Screen</p></div>
<p><strong>Setting up a Spring MVC Template project.</strong><br />
Next lets create an MVC Template project.  In STS execute the following steps:</p>
<ol>
<li>Click on File &#8211;&gt; New &#8211;&gt; Spring Template Project.  Select Spring MVC Project and click Next. (I set my project name to &#8216;SpringMVCTemplateProject&#8217; and defined the top level package as &#8216;fm.devhub.myspringmvc&#8217;).</li>
<li>You will see an alert notifying you to download the necessary resources, click Yes. What this will do is pull down the necessary libraries for your project to build correctly.</li>
</ol>
<p><em>Note: Ensure your proxy settings are configured if you use one. Otherwise the files will not be able to download. You can set them by going to the Window menu &#8211;&gt; Preferences &#8211;&gt; General &#8211;&gt; Network Connections.</em></p>
<div id="attachment_208" class="wp-caption aligncenter" style="width: 310px"><a href="http://mannyit.files.wordpress.com/2012/02/sts2.jpg"><img class="size-medium wp-image-208" title="STS New MVC Template Project" src="http://mannyit.files.wordpress.com/2012/02/sts2.jpg?w=300" alt="STS New MVC Template Project" width="300" height="105" /></a><p class="wp-caption-text">Figure 2: STS New MVC Template Project</p></div>
<p><strong>Deploying the packaged Hello World application.</strong><br />
Next lets deploy and launch the application.</p>
<ol>
<li>Right click on the project and select Run As &#8211;&gt; Run on Server.For this tutorial we are going to use VMware vFabric tc Server Developer Edition v2.6.</li>
<li>Select the server and click Next. This screen indicates that the server is selected and that your project is configured to be deployed. Click Finish.</li>
</ol>
<div id="attachment_211" class="wp-caption aligncenter" style="width: 253px"><a href="http://mannyit.files.wordpress.com/2012/02/runonserver.jpg"><img class="size-medium wp-image-211" title="Run On Server" src="http://mannyit.files.wordpress.com/2012/02/runonserver.jpg?w=243" alt="Run On Server" width="243" height="300" /></a><p class="wp-caption-text">Figure 3: Run On Server</p></div>
<p>The first attempt at starting the server yielded the following error for me, if you didn&#8217;t receive any errors then skip over this section.</p>
<pre>http://localhost:8080/SpringMVCTemplateProject/
HTTP Status 404 - 

------------------------------------------------------

type Status report

message 

description The requested resource () is not available.

------------------------------------------------------

VMware vFabric tc Runtime 2.6.1.RELEASE/7.0.20.B.RELEASE

WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/SpringMVCTemplateProject/] in DispatcherServlet with name appServlet'</pre>
<p>In order to fix the error above right click on the webapp directory in your project explorer and select Build Path &#8211;&gt; Click Use as Source Folder.  What this does is add the webapp directory to the build path which ensures our webapp files are included in the deployment.  I haven&#8217;t had much time to find out exactly why this problem is occurring out of the box, so if you know the root cause please leave a comment.</p>
<p>Once the error is resolved repeat the steps above to deploy the application (if you didn&#8217;t encounter any errors then ignore this step). You should see the following screen indicating that everything is working correctly:</p>
<div id="attachment_216" class="wp-caption aligncenter" style="width: 310px"><a href="http://mannyit.files.wordpress.com/2012/02/mvcapplicationdeploy.jpg"><img class="size-medium wp-image-216" title="Successful Spring MVC Template Deploy" src="http://mannyit.files.wordpress.com/2012/02/mvcapplicationdeploy.jpg?w=300" alt="Successful Spring MVC Template Deploy" width="300" height="212" /></a><p class="wp-caption-text">Figure 4: Successful Spring MVC Template Deploy</p></div>
<p>Now that the application is up and running we can proceed to the next section in this tutorial.</p>
<p><strong>A walk through of all Spring MVC Template components.</strong><br />
In this section we will dissect most of the files provided in the Spring MVC Template project.</p>
<div id="attachment_277" class="wp-caption aligncenter" style="width: 222px"><a href="http://mannyit.files.wordpress.com/2012/02/stsspring3-0projectexplorer.jpg"><img src="http://mannyit.files.wordpress.com/2012/02/stsspring3-0projectexplorer.jpg?w=212" alt="STS Spring 3.0 MVC Template Project Explorer" title="STS Spring 3.0 MVC Template Project Explorer" width="212" height="300" class="size-medium wp-image-277" /></a><p class="wp-caption-text">Figure 5: STS Spring 3.0 MVC Template Project Explorer</p></div>
<p>In order to see the package explorer (as displayed in the picture above) in your STS IDE, you will need to switch the perspective from Java EE to Java.</p>
<p><em><strong>HomeController.java</strong></em></p>
<pre class="crayon-plain-tag"><code>package fm.devhub.myspringmvc;

+import java.text.DateFormat;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	private static final Logger logger = 
            LoggerFactory.getLogger(HomeController.class);

	/**
	 * Simply selects the home view to
         * render by returning its name.
	 */
	@RequestMapping(value = &quot;/&quot;, method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info(&quot;Welcome home! the 
                    client locale is &quot;+ locale.toString());

		Date date = new Date();
		DateFormat dateFormat = 
                    DateFormat.getDateTimeInstance(DateFormat.LONG, 
                    DateFormat.LONG, locale);

		String formattedDate = dateFormat.format(date);

		model.addAttribute(&quot;serverTime&quot;, formattedDate );

		return &quot;home&quot;;
	}

}</code></pre>
<p><em>Line 8:</em><br />
The @Controller annotation defines the class as a controller.  Controller classes in Spring are used to prepare the model that will be mapped to a view for a particular resource.</p>
<p>In the code above we have a <strong>Model</strong> object (line 17) called model, and we are adding an attribute to it called &#8216;serverTime&#8217; (line 25).  What this does is pass the model to our &#8216;home&#8217; <strong>View</strong> which is our home.jsp, and if you look at the home.jsp code, you will see that we are printing the <strong>Model</strong> attribute &#8216;serverTime&#8217;.</p>
<p><em>Line 16:</em><br />
@RequestMapping is used to map an HTTP Request to a specific resource. In this case we are mapping http://localhost:8080/SpringMVCTemplateProject/ as denoted by value = &#8220;/&#8221; to our HomeController.java&#8217;s home method, which returns control to home.jsp.<br />
Therefore any request comming in via localhost:8080/SpringMVCTemplateProject<strong>/</strong> will get returned to home.jsp when line 27 is reached.</p>
<p>Method = RequestMethod.GET is specifying the HTTP method &#8216;GET&#8217; vs. &#8216;POST&#8217; for example.<br />
<em>Note: To understand HTTP Methods better you can read the post &#8220;HTTP Request/Response&#8221; under Web Development Basics.</em></p>
<p><em>Line 17:</em><br />
public String home(Locale locale, Model model) is the a method that gets called when this request comes in:<br />
@RequestMapping(value = &#8220;/&#8221;, method = RequestMethod.GET).</p>
<p>The name itself &#8216;home&#8217; is an arbitrary name that the developers who created the Spring MVC Template chose to use.  If you change the name to homepage for example, the application will still deploy correctly.  Just as the method name &#8216;home&#8217; is arbitrary, as are the arguments being passed &#8220;Locale local, Model model&#8221; we could choose to pass additional arguments if we wanted.</p>
<p>Keep in mind that the Spring MVC Template is setup to be as simple and re-usable/extendable as possible, hence the reason why its using only the most basic of Spring MVC&#8217;s features.</p>
<p><em>Line 25:</em><br />
model.addAttribute(&#8220;serverTime&#8221;, formattedDate ) is basically setting an attribute that will be accessible to our home.jsp (our view). And that attribute is &#8216;serverTime&#8217;.<br />
If you look at home.jsp line 12 you can clearly see the link:</p>
<p>The time on the server is ${serverTime}.</p>
<p><em>Line 27:</em><br />
Return &#8216;home&#8217; is basically returning to our home.jsp view. If you were to modify HomeController.java to return &#8220;home1&#8243; for example, you will get an error saying that Spring cannot locate the resource. Likewise if you change the name of the file to home1.jsp without updating the HomeController, you will receive an error.</p>
<p><strong><em>servlet-context.xml</em></strong></p>
<pre class="crayon-plain-tag"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans:beans xmlns=&quot;http://www.springframework.org/schema/mvc&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns:beans=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd&quot;&gt;

	&lt;!-- DispatcherServlet Context: defines this servlet's 
        request-processing infrastructure --&gt;
	
	&lt;!-- Enables the Spring MVC @Controller programming model --&gt;
	&lt;annotation-driven /&gt;

	&lt;!-- Handles HTTP GET requests for /resources/** by
        efficiently serving up static resources in 
       the ${webappRoot}/resources directory --&gt;
	&lt;resources mapping=&quot;/resources/**&quot; location=&quot;/resources/&quot; /&gt;

	&lt;!-- Resolves views selected for rendering by @Controllers
        to .jsp resources in the /WEB-INF/views directory --&gt;
	&lt;beans:bean 
class=
&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;&gt;
&lt;beans:property name=&quot;prefix&quot; value=&quot;/WEB-INF/views/&quot; /&gt;
&lt;beans:property name=&quot;suffix&quot; value=&quot;.jsp&quot; /&gt;
&lt;/beans:bean&gt;
&lt;context:component-scan base-package=&quot;fm.devhub.myspringmvc&quot; /&gt;
&lt;/beans:beans&gt;</code></pre><p><p><em>Lines 2-9:</em><br />
Defining the namespace and schema for the Spring servlet context file version 3.0.</p>
<p><em>Line 10:</em></p>
<p><em>Line 13:</em><br />
Enables Spring 3.0 MVC annotations, we have used a few of them already such as @Controller and @RequestMapping.  Some others include @SessionAttributes, @ModelAttribute and @InitBinder.</p>
<p><em>Line 14-16</em><br />
Here mvc:resources tag is being declared although it isn&#8217;t currently being used.  What the resources tag does is declare a &#8216;resource&#8217; directory where you would want your publicly accessible static files to reside.  An example would be JavaScript files, images, etc.  One of the benefits of utilizing this tag is that you can specify browser caching settings in order to reduce the number of requests for resources being sent to your server.</p>
<p>If you look at your Package Explorer, you can see Spring MVC Template has this folder created under webapp &#8211;&gt; resources.</p>
<p><em>Line 19:</em><br />
This is the declaration of a ViewResovler, this is basically the Spring component that defines the rules of how to match or resolve an HTTP Request with a View.  so if we look at the code we can see that we are using the &#8220;InternthealResourceViewResolver&#8221;<br />
we are defining the prefix as &#8220;/WEB-INF/views/&#8221;<br />
and the suffix as &#8216;.jsp&#8217;<br />
So, when HellowController.java returns &#8216;home&#8217;, the ViewResolver resolves the view by saying you want to look in &#8220;/WEB-INF/views/&#8221; and the file type is &#8216;.jsp&#8217; so append &#8216;.jsp&#8217; to the name.  In term we end up with path and name of the file &#8216;View&#8217; that we want which ends up being &#8216;/WEB-INF/views/home.jsp&#8217;</p>
<p>Keep in mind that there are many different types of View Resolvers, such as VelocityViewResolver, UrlBasedViewResolver, ResourceBundleViewResolvIemrplementation and XmlViewResolver.  The MVC Spring 3.0 documentation defines InternthealResourceViewResolver as: A &#8220;Convenient  subclass of UrlBasedViewResolver that supports InternalResourceView (in effect, Servlets and JSPs) and subclasses such as JstlView and TilesView. You can specify the view class for all views generated by this resolver by using setViewClass(..).&#8221;</p>
<p><em>Line 20:</em><br />
The prefix is basically where to locate the files</p>
<p><em>Line 21:</em><br />
The suffix is basically the file type, in our case a .jsp.</p>
<p><em>Line 23:</em><br />
component-scan is basically enabling a feature in Spring 3.0 which will automatically search for annotated classes and register their BeanDefinitions to the Application Context.  This is simply an alternative to explicitly declaring the configuration in the application context xml.</p>
<p><em><strong>root-context.xml</strong></em></p>
<pre class="crayon-plain-tag"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&quot;&gt;
	
	&lt;!-- Root Context: defines shared resources visible to all other web components --&gt;
		
&lt;/beans&gt;</code></pre><p><p><p>
<em>Lines 2-4: </em><br />
Defines the namespace and schema for spring beans version 3.0.<br />
<em>Line 6: </em><br />
Here we would have all shared resources for our application defined. For example a hibernate connection, or global bean values which need to be declared at startup.</p>
<p><em><strong>home.jsp</strong></em></p>
<pre class="crayon-plain-tag"><code>&lt;%@ taglib uri=&quot;http://java.sun.com/jsp/jstl/core&quot; prefix=&quot;c&quot; %&gt;
&lt;%@ page session=&quot;false&quot; %&gt;
&lt;html&gt;
&lt;head&gt;
	&lt;title&gt;Home&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;
	Hello world!  
&lt;/h1&gt;

&lt;P&gt;  The time on the server is ${serverTime}. &lt;/P&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></p>
<p>Line 1:<br />
Is the declaration of our JSP taglibrary.  Specifically JSTL1.  I recommend reading more about JSTL if you have the time.</p>
<p>Lines 3-11:<br />
The body of our home.jsp.</p>
<p>Line 12:<br />
Here is where we use the Model attribute (serverTime) which was added in HomeController.java and display it to the user.</p>
<p><em><strong>web.xml</strong></em></p><pre class="crayon-plain-tag"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app version=&quot;2.5&quot; xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;&gt;

	&lt;!-- The definition of the Root Spring Container shared by all Servlets and Filters --&gt;
	&lt;context-param&gt;
		&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
		&lt;param-value&gt;/WEB-INF/spring/root-context.xml&lt;/param-value&gt;
	&lt;/context-param&gt;
	
	&lt;!-- Creates the Spring Container shared by all Servlets and Filters --&gt;
	&lt;listener&gt;
		&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
	&lt;/listener&gt;

	&lt;!-- Processes application requests --&gt;
	&lt;servlet&gt;
		&lt;servlet-name&gt;appServlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
		&lt;init-param&gt;
			&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
			&lt;param-value&gt;/WEB-INF/spring/appServlet/servlet-context.xml&lt;/param-value&gt;
		&lt;/init-param&gt;
		&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
	&lt;/servlet&gt;
		
	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;appServlet&lt;/servlet-name&gt;
		&lt;url-pattern&gt;/&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
&lt;/web-app&gt;</code></pre><p><p><p><p>
<p><em>Lines 2-4:</em><br />
Defines the namespace and schema for web-app version 2.5.</p>
<p><em>Lines 7-10:</em><br />
Defines the &#8216;contextConfigLocation&#8217;.  root-context.xml can be used to define Spring beans which are global to all Servlets.  This could be useful for a database configuration for example.</p>
<p><em>Lines 13-15:</em><br />
Adds a global context listener Spring.  It basically can be viewed as initializing the Spring framework upon our web application start-up.</p>
<p><em>Lines 18-26:</em><br />
A very important component of spring is the DispatcherServlet (look at Figure 6).  The DispatcherServlet basically manages the request/response workflow between our controllers and views.  It is a core component of how Spring MVC works.</p>
<p><em>Lines 28-31:</em><br />
Adds our application servlet arbitrarily named appServlet.</p>
<p>Below is a visual representation of the application flow for our Spring 3.0 MVC Template hello world application.<br />
<div id="attachment_320" class="wp-caption aligncenter" style="width: 236px"><a href="http://mannyit.files.wordpress.com/2012/02/spring3-0mvctemplateflow1.jpg"><img src="http://mannyit.files.wordpress.com/2012/02/spring3-0mvctemplateflow1.jpg?w=226" alt="Figure 6: Spring3.0 MVC Template Request/Response Flow" title="Spring3.0 MVC Template Request/Response Flow" width="226" height="300" class="size-medium wp-image-320" /></a><p class="wp-caption-text">Figure 6: Spring3.0 MVC Template Request/Response Flow</p></div></p>
<p>Thanks for reading!  If you find any technical inaccuracies or deficiencies in this article, please make devhub.fm aware by posting a comment.  Any feedback is welcome &amp; encouraged.</p>
]]></content:encoded>
			<wfw:commentRss>http://DEVHUB.FM/spring-3-0-mvc-template-introduction-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>HTTP Request/Response Basics</title>
		<link>http://DEVHUB.FM/http-requestresponse-basics/</link>
		<comments>http://DEVHUB.FM/http-requestresponse-basics/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 23:22:52 +0000</pubDate>
		<dc:creator>Mo</dc:creator>
				<category><![CDATA[Web Development Basics]]></category>
		<category><![CDATA[HTTP]]></category>
		<category><![CDATA[http connect]]></category>
		<category><![CDATA[http delete]]></category>
		<category><![CDATA[http introduction]]></category>
		<category><![CDATA[http options]]></category>
		<category><![CDATA[http post]]></category>
		<category><![CDATA[http put]]></category>
		<category><![CDATA[http request]]></category>
		<category><![CDATA[http response]]></category>
		<category><![CDATA[http trace]]></category>
		<category><![CDATA[http tutorial]]></category>
		<category><![CDATA[Hypertext Transfer Protocol introduction]]></category>
		<category><![CDATA[Hypertext Transfer Protocol tutorial]]></category>
		<category><![CDATA[internet dns]]></category>

		<guid isPermaLink="false">http://DEVHUB.FM/?p=21</guid>
		<description><![CDATA[The following introductory topics will be discussed in this article: The life-cycle of an HTTP request &#38; response. Anatomy of an HTTP request &#38; response. HTTP Methods &#38; best practices. The life-cycle of an HTTP request commonly looks like this: &#8230; <a href="http://DEVHUB.FM/http-requestresponse-basics/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>The following introductory topics will be discussed in this article:</p>
<ul>
<li>The life-cycle of an HTTP request &amp; response.</li>
<li>Anatomy of an HTTP request &amp; response.</li>
<li>HTTP Methods &amp; best practices.</li>
</ul>
<div id="attachment_10" class="wp-caption alignleft" style="width: 310px"><a href="http://DEVHUB.FM/wp-content/uploads/2012/02/http.jpg"><img class="size-medium wp-image-10" src="http://DEVHUB.FM/wp-content/uploads/2012/02/http-300x275.jpg" alt="Figure 1: HTTP Request/Response" width="300" height="275" /></a><p class="wp-caption-text">Figure 1: HTTP Request/Response</p></div>
<p>The life-cycle of an HTTP request commonly looks like this:</p>
<ol>
<li>A user visits the URL of a website.</li>
<li>This creates a request which is routed to a web server via the internet (a network of DNS&#8217;s, routers and switches) over HTTP (Hypertext Transfer Protocol).</li>
<li>The web server receives the HTTP request and responds to the user with the web page (or content) which was requested.</li>
</ol>
<p>Every time you click on a link and visit a web page, behind the scenes you are making a request, and in turn receiving a response from a web server. Note that HTTP requests can be made via many channels, not just web browsers. For example, an HTTP request could be made using TELNET, or a client written in JAVA or C# etc.</p>
<p>To see an example of what an HTTP request and response looks like do the following:</p>
<ol>
<li>Go to the website <a title="http://web-sniffer.net/" href="http://web-sniffer.net/">http://web-sniffer.net/</a></li>
<li>Type in www.google.com (or any website you wish) in the &#8220;HTTP(S)-URL:&#8221; input field. When you click on &#8220;Submit&#8221; you will see the HTTP request and response data for www.google.com.</li>
</ol>
<p><strong>The anatomy of an HTTP request:</strong><br />
As a web developer, an important area to understand is the method portion of an HTTP request. The method tells the web server what kind of request is being performed on a URI.<br />
So if you type in the URL www.google.com/finance (for example). You are requesting the /finance URI. Within the /finance URI the HTTP request has to define an HTTP method.</p>
<p>The method portion of an HTTP request contains the following definition options:</p>
<pre>       Method         = "OPTIONS"
                      | "GET"
                      | "HEAD"
                      | "POST"
                      | "PUT"
                      | "DELETE"
                      | "TRACE"
                      | "CONNECT"
                      | extension-method
       extension-method = token</pre>
<p><em><strong>OPTIONS</strong></em><br />
Options is useful for finding out which HTTP methods are accessible by a client. Depending on how the web server you are trying to connect to is configured, the administrator may only have the POST and GET HTTP methods accessible. While other HTTP methods such as DELETE, TRACE, etc are disabled.</p>
<p><em><strong>GET</strong></em><br />
A GET request retrieves data from a web server by specifying parameters in the URL portion of the request. If you examine the example HTTP request below, we are asking for index.html, and passing the parameter report_id.</p>
<pre>	GET /index.html?report_id=34543222 HTTP/1.1
	Host: www.awebsite.com
	User-Agent: Safari/4.0</pre>
<p>Examples of when to use GET:</p>
<ol>
<li>You are accessing a URL purely for the sake of viewing data. You could think of it as using an SQL SELECT statement. You are asking for data from the web server without the intent of updating any data.</li>
<li>You need a URL to be &#8216;bookmarkable&#8217;. Basically HTTP GET is considered to be repeatable, which allows requests to be retried safely and responses to be cached.</li>
<li>You don&#8217;t mind the request being repeated. For example a user visiting the same URL more than once.</li>
</ol>
<p>Examples of when not to use GET:</p>
<ol>
<li>You are passing sensitive data such as usernames, passwords, social security numbers, etc.</li>
<li>You are sending large amounts of data. Although there isn&#8217;t a character limit defined in the HTTP specification for the length of a URL, IE 4 for example only supports a max URL length of ~2000 characters using a GET request.</li>
<li>You need to update something on a server, for example submitting a form which will update a users address or shopping cart.</li>
</ol>
<p><em><strong>POST</strong></em><br />
A POST HTTP request utilizes a message body to send data to a web server. If you examine the example HTTP POST request below, you will see that we are passing a POST HTTP request with the message body of &#8216;userid=mo&amp;password=mypassw&#8217; to login.jsp (login.jsp would be an application that the web server forwards requests to).<br />
Examples of when to use POST:</p>
<ol>
<li>You have a large amount of data to send to a web server (the size of data would exceed URL limits of the GET method).</li>
<li>You are sending sensitive data such as uesrnames, passwords, social security numbers etc.</li>
<li>You are altering the state of data in a web application. For example, a shopping cart keeping track of items which you are purchasing.</li>
</ol>
<p>Examples of when not to use POST:</p>
<ol>
<li>The URL that you are passing has a requirement of being &#8216;bookmarkable&#8217;. If the state of the URL changes, then the user will not be able to retrieve, or view the data it it&#8217;s former state.</li>
<li>Your request needs to be idempotent. Note that POST requests can be idempotent, however it&#8217;s better practice to use PUT (if this HTTP request method is supported by your web server and client)</li>
</ol>
<pre>	POST /login.jsp HTTP/1.1
	Host: www.awebsite.com
	User-Agent: Safari/4.0
	Content-Length: 27
	Content-Type: application/x-www-form-urlencoded

	userid=mo&amp;password=mypassw</pre>
<p><em><strong>PUT</strong></em><br />
PUT similar to POST utilizes a message body to transfer data. However, there are some fundamental differences between the two. Firstly PUT is considered to be idempotent, secondly a PUT&#8217;s action is always defined for a specific URI, finally a PUT is for loading the data for that resource. In other words you should know the exact location of where the data you are sending will be retrieved later.<br />
Example of when to use PUT:</p>
<ol>
<li>Put is idempotent, so basically if you need to accommodate for a scenario where a request is submitted multiple times but the result needs to be identical for each submission; use PUT. This could be useful for creating a new user for instance. If you send a PUT request to create a user Joe Smith multiple times, the last request should have the same results as if it were sent first.</li>
<li>You have a specific URI which you are sending data to. For example:</li>
</ol>
<pre>POST URI:

http://hostname.com/users/new

PUT URI:

http://hostname.com/users/joesmith</pre>
<p>Example of when not to use PUT:</p>
<ol>
<li>PUT should not be used for non idempotent requests (if the state of the resource is likely to change each time a request is sent).</li>
<li>It&#8217;s good to keep in mind that in the case of html forms, most browsers do not support the PUT/DELETE methods. It is expected that POST/GET are used. Some Restful frameworks such as Ruby on Rails for example requires the use of PUT/DELETE, however these HTTP Methods are simply tunneled through the HTTP POST Method.</li>
</ol>
<pre>	PUT /somedatabase/some_doc_id HTTP/1.1
	Content-Length: 240
	Content-Type: application/json

	{
	  "Subject":"Resume",
	  "Author":"Mo",
	  "Body":"Find my resume attached"
	}</pre>
<p><em><strong>HEAD</strong></em><br />
The HTTP HEAD Method is used to retrieve information about a URL from a web server. So for example if you sent a HEAD request, you would receive a response from the web server containing the same information as you would with an HTTP POST excluding the body data. Here is an example:</p>
<pre>	HEAD /de HTTP/1.1[CRLF]
	Host: www.google.com[CRLF]
	Connection: close[CRLF]
	User-Agent: Web-sniffer/1.0.37 [CRLF]
	Accept-Encoding: gzip[CRLF]
	Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]
	Cache-Control: no-cache[CRLF]
	Accept-Language: de,en;q=0.7,en-us;q=0.3[CRLF]
	Referer: http://web-sniffer.net/[CRLF]</pre>
<p><em><strong>DELETE</strong></em><br />
The HTTP DELETE method can be used to delete a resource from a server. Generally it is used in two scenarios. Fist scenario is if you are following RESTful standards in developing your web application. Secondly it can be used when DELETE is enabled on a web-server and you would like to follow the HTTP standard for deleting a resource. It&#8217;s important to note however that you can use HTTP POST to handle an HTTP DELETE action also, the decision is narrowed down to the options described above.<br />
<em><strong></strong></em></p>
<p><em><strong>TRACE</strong></em><br />
If you attempt to execute an HTTP TRACE method on most web-servers you will likely see this message:</p>
<pre>	Status: HTTP/1.1 501 Not Implemented</pre>
<p>HTTP TRACE is used to eacho the contents of an HTTP Request back to the requester (which can be useful for debugging). This however may pose a security threat because malicious code can abuse HTTP TRACE functionality to gain access to information in HTTP headers such as cookies and authentication data, if an HTTP TRACE request is sent the original request data will be returned in addition to any user specific data. An example HTTP TRACE response can look like this:</p>
<pre>	TRACE / HTTP/1.1
	Host: www.google.com

	HTTP/1.1 200 OK
	Server: Microsoft-IIS/5.0
	Date: Tue, 31 Oct 2012 03:01:44 GMT
	Connection: close
	Content-Type: message/http
	Content-Length: 39

	TRACE / HTTP/1.1
	Host: www.google.com</pre>
<p><em><strong>CONNECT</strong></em><br />
HTTP CONNECT can be used to establish a network connection to a web server over HTTP. It&#8217;s primarily used in cases where a secure/encrypted HTTP connection (tunnel) needs to be established between a client and a web server such as an SSL connection.<br />
Simple HTTP tunnels are an unencrypted connection through an HTTP proxy to an arbitrary destination. The tunnel takes advantage of the HTTP CONNECT method normally used for HTTPS (secure web traffic) to connect to the destination server. A typical HTTPS connection through a proxy should look like:</p>
<pre>	CONNECT remote-server:443 HTTP/1.0
	User-Agent: Mozilla/4.0 (compatible; MSIE 6.0;..
	Host: remote-server
	Content-Length: 0
	Proxy-Connection: Keep-Alive
	Pragma: no-cach</pre>
<p><em><strong>HTTP Response Codes</strong></em><br />
Whenever a request is made to an HTTP server, a response code is sent back to the client accompanying the requested data. It&#8217;s important to understand what these response codes are as they will be useful for managing errors in your web applications. A list of HTTP response codes and their meanings can be found here:<br />
<a title="HTTP Response Codes" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" target="_blank">HTTP Response Codes</a></p>
<p><strong>Additional Reading:</strong><br />
<a title="(click here to view the HTTP 1.1 specification)" href="http://www.w3.org/Protocols/rfc2616/rfc2616.html" target="_blank">HTTP 1.1 specification</a><br />
<a title="PUT vs. POST" href="http://www.elharo.com/blog/software-development/web-development/2005/12/08/post-vs-put/" target="_blank">PUT vs. POST</a><br />
<a title="HTTP TRACE Vulnerability Blog Post" href="http://jeremiahgrossman.blogspot.com/2007/04/xst-lives-bypassing-httponly.html" target="_blank">HTTP TRACE Vulnerability Blog Post</a><br />
<a title="HTTP PUT/POST Article" href="http://roy.gbiv.com/untangled/2009/it-is-okay-to-use-post" target="_blank">Restful HTTP PUT/POST Article</a><br />
<a title="HTTP CONNECT Security White Paper" href="http://www.sans.org/reading_room/whitepapers/covert/http-tunnels-proxies_1202" target="_blank">HTTP CONNECT Security White Paper</a><br />
<span style="color: #ffffff;">TRA3EQ3SV99B</span></p>
<p>Thanks for reading!  If you find any technical inaccuracies or deficiencies in this article, please make devhub.fm aware by posting a comment.  Any feedback is welcome &amp; encouraged. </p>
]]></content:encoded>
			<wfw:commentRss>http://DEVHUB.FM/http-requestresponse-basics/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Welcome</title>
		<link>http://DEVHUB.FM/hello-world/</link>
		<comments>http://DEVHUB.FM/hello-world/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 20:21:06 +0000</pubDate>
		<dc:creator>admin2012</dc:creator>
				<category><![CDATA[Home]]></category>

		<guid isPermaLink="false">http://DEVHUB.FM/?p=1</guid>
		<description><![CDATA[Welcome to DEVHUB.FM!]]></description>
				<content:encoded><![CDATA[<p>Welcome to DEVHUB.FM!</p>
]]></content:encoded>
			<wfw:commentRss>http://DEVHUB.FM/hello-world/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
