<?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>etechGuide . . .</title>
	<atom:link href="http://etechGuide.in/feed/" rel="self" type="application/rss+xml" />
	<link>http://etechGuide.in</link>
	<description>Know more , share more</description>
	<lastBuildDate>Fri, 25 Jun 2010 13:58:23 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Developing GWT-RPC application with a Database support</title>
		<link>http://etechGuide.in/web/gwt-rpc-with-database/</link>
		<comments>http://etechGuide.in/web/gwt-rpc-with-database/#comments</comments>
		<pubDate>Fri, 25 Jun 2010 13:49:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[GWT]]></category>
		<category><![CDATA[Web Technologies]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[rpc]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=587</guid>
		<description><![CDATA[This post is a step-by-step guide to build an application using GWT-RPC . Just to make it more realistic , I have used a back-end database to store the records. I have used <a href="http://mysql.com/downloads/">MySql</a> as a database and <a href="http://tomcat.apache.org/download-60.cgi">Tomcat 6.0</a> as a deployment web server. If you are interested to have a look at the code and then the post , it can be downloaded from <a href="http://etechGuide.in/wp-content/uploads/2010/06/GwtRpcDB.zip">here</a>. Let me start with a small but specific description of GWT-RPC.]]></description>
			<content:encoded><![CDATA[<p>This post is a step-by-step guide to build an application using GWT-RPC . Just to make it more realistic , I have used a back-end database to store the records. I have used <a href="http://mysql.com/downloads/">MySql</a> as a database and <a href="http://tomcat.apache.org/download-60.cgi">Tomcat 6.0</a> as a deployment web server. If you are interested to have a look at the code and then the post , it can be downloaded from <a href="http://etechGuide.in/wp-content/uploads/2010/06/GwtRpcDB.zip">here</a>. Let me start with a small but specific description of GWT-RPC.</p>
<h4> <u>What is GWT-RPC ?</u> </h4>
<p>Google Web Tool-kit (<a href="http://code.google.com/webtoolkit/gettingstarted.html">GWT</a>) provides couple of different ways to communicate with the server using <a href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol">HTTP</a>. GWT-RPC is a framework to make a transparent server-side call where GWT takes care of all other low level details , like , object serialization etc.<br />
      When your application running in the browser , it needs to interact with the server using a Remote Procedure Call (RPC).GWT provides an RPC mechanism based on Java Servlets to provide access to server side. GWT uses <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsDeferred.html">deferred binding</a> to serialize objects across the network. You can read more on GWT-RPC  from <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideServerCommunication.html#DevGuideRemoteProcedureCalls">here</a>.</p>
<h4> <u>The application : User Creation Application</u> </h4>
<p>The funny thing is , My application creates User alone. Yes , it doesn&#8217;t do anything else other than creating user and storing them to the database. But , the important thing is , it uses GWT-RPC and gives enough scope of learning to build an application using GWT-RPC or GWT. My create user screen look like ,</p>
<div id="create_user" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="Create User Screen" src="http://etechGuide.in/wp-content/uploads/2010/06/create_user.png" alt="Create User Screen" width="350" height="275" /><br />
<p class="wp-caption-text">Create User Screen</p></div>
<p><Strong> <u>Setup details :</u> </Strong></p>
<ul>
<li>Launch your favorite Java IDE. I have used eclipse which can be downloaded from <a href="http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/galileor">here</a>. If you are not so comfortable with eclipse , you can learn it from <a href="http://etechguide.in/eclipse/eclipse_shortcuts/">here</a>.</li>
<li>Configure the GWT plug-in for eclipse. Learn how , <a href="http://code.google.com/eclipse/docs/download.html">here</a>. </li>
<li>Download the project from <a href="http://etechGuide.in/wp-content/uploads/2010/06/GwtRpcDB.zip">here</a> and extract into a folder of your choice.</li>
<li><a href="http://dev.mysql.com/downloads/connector/j/5.0.html">Download</a> the MySQL Connector/J and copy the jar to the /war/WEB-INF/lib directory.</li>
<li>Import the extracted project to your eclipse. </li>
</ul>
<p>Once the project is imported to eclipse , the project structure should be like following :<br />
<div id="directory_structure" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="Project Directory Structure" src="http://etechGuide.in/wp-content/uploads/2010/06/project_hier.png" alt="Project Directory Structure" width="330" height="820" /><br />
<p class="wp-caption-text">Project Directory Structure</p></div></p>
<p>Now we are all set to go.  GWT-RPC uses servlets to communicate with the server-side. GWT provides a servlet called , RemoteServiceServlet. This is a base servlet class for your RPC service implementations. It helps you to automatically deserializes incoming requests from the client and serializes outgoing responses for client/server RPCs. </p>
<p>You should do the following to set your GWT-RPC interface ,</p>
<ul>
<li>Create a service interface &#8211; Create an interface for your service that extends RemoteService and lists all RPC methods. </li>
<li>Create a service implementation &#8211; Create a class to implement the server-side logic. The class should extends RemoteServiceServlet and implements the interface you created in the above step.</li>
<li>Create an asynchronous interface to your service to be called from the client-side code.</li>
</ul>
<p><Strong><u>Create a service interface : </u></Strong><br />
Our <i>Create User</i> program requires at least two service methods . One is to check if the user is already exist in the database and other one is to Save the User into the databse. </p>
<pre class="brush: java">
import com.etechguide.project.gwtrpcdb.client.exception.UserException;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

/**
 * The client side stub for the RPC service.
 */
@RemoteServiceRelativePath(&quot;user&quot;)
public interface UserService extends RemoteService {
	 String createUser(User user) throws UserException;
	 boolean checkUserExist(String userName) throws UserException;

}
</pre>
<p>I have defined both the methods in my service interface. The service interface is annotated with the annotation , @RemoteServiceRelativePath(&#8221;user&#8221;). This annotation associates a RemoteService with the relative path(/user). we will use this relative path(/user) in the web.xml file while defining the servlet.</p>
<p><Strong><u>Create a service implementation : </u></Strong><br />
This class should extends RemoteServiceServlet and implements the UserService interface . As this implementation class extends RemoteServiceServlet , it is a servlet class by itself.</p>
<pre class="brush: java">
/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings(&quot;serial&quot;)
public class UserServiceImpl extends RemoteServiceServlet implements
		UserService {

	UserDao userDao = new UserDao();
	@Override
	public String createUser(User user) throws UserException {
		String retVal = &quot;true&quot;;
		if (!Validator.isValidName(user.getUserName())) {
			throw new UserException(
					&quot;User name must be at least 5 characters long&quot;);
		}
		try {
			userDao.createUser(user);
		} catch (ClassNotFoundException e) {
			retVal = &quot;false&quot;;
			throw new UserException(e.getLocalizedMessage());
		} catch (SQLException e) {
			retVal = &quot;false&quot;;
			throw new UserException(e.getLocalizedMessage());
		}

		return retVal;
	}

	@Override
	public boolean checkUserExist(String userName) throws UserException {
		return userDao.checkUserExist(userName);
	}
}
</pre>
<p>The implementation class , UserServiceImpl uses the Data Access Object (DAO) to call the data base related methods. The DAO (UserDao.java) would look like ,</p>
<pre class="brush: java">
public class UserDao {

	Connection connection = null;
	Statement stmt = null;

	public void createUser(User user) throws ClassNotFoundException,
                     SQLException{
		String query = null;
		StringBuilder queryBuilder = null;
		queryBuilder = new StringBuilder();
		queryBuilder.append(&quot;INSERT INTO user(userName,password,&quot;);
		queryBuilder.append(&quot;emailId,address)&quot;);
		queryBuilder.append(&quot; VALUES( &quot;);
		queryBuilder.append(&quot;&#039;&quot;+user.getUserName()+&quot;&#039;&quot;);
		queryBuilder.append(&quot;,&quot;);
		queryBuilder.append(&quot;&#039;&quot;+user.getPassword()+&quot;&#039;&quot;);
		queryBuilder.append(&quot;,&quot;);
		queryBuilder.append(&quot;&#039;&quot;+user.getEmailId()+&quot;&#039;&quot;);
		queryBuilder.append(&quot;,&quot;);
		queryBuilder.append(&quot;&#039;&quot;+user.getAddress()+&quot;&#039;&quot;);
		queryBuilder.append(&quot; )&quot;);

		query = queryBuilder.toString();
		System.out.println(&quot;query from createUser = &quot; + query);
		System.out.println(&quot;user to be created ... &quot; + user.toString());
		connection = DbConnection.createConnection();
		stmt = connection.createStatement();
		stmt.executeUpdate(query);
		DbConnection.closeConnection(connection, stmt);
	}

	public boolean checkUserExist(String userName) throws UserException {
		boolean isExist = false;
		String query = null;
		StringBuilder queryBuilder = null;
		ResultSet rs = null;
	    int rowCount = -1;
		queryBuilder = new StringBuilder();
		queryBuilder.append(&quot;SELECT count(*) FROM user WHERE userName= &#039;&quot;);
		queryBuilder.append(userName);
		queryBuilder.append(&quot;&#039;&quot;);
		query = queryBuilder.toString();
		System.out.println(&quot;query from checkUserExist = &quot; + query);
		try {
			connection = DbConnection.createConnection();
			stmt = connection.createStatement();
			rs = stmt.executeQuery(query);
			rs.next();
			rowCount = rs.getInt(1);
			if(rowCount &gt; 0){
				isExist = true;
			}
		} catch (ClassNotFoundException e) {
			throw new UserException(e.getLocalizedMessage());
		} catch (SQLException e) {
			throw new UserException(e.getLocalizedMessage());
		}finally{
			try {
				DbConnection.closeConnection(connection, stmt,rs);
			} catch (SQLException e) {
				throw new UserException(e.getLocalizedMessage());
			}
		}
		return isExist;
	}

}
</pre>
<p>So , as of now the story is ,  you have  User Service and the Implementation of that. The Implementation is nothing but a servlet. We call all the database related methods from the implementation class. As it is a servlet and we are building a web application , we must declare this servlet in the web.xml file which is the main deployment descriptor file for any web application. The web.xml file is like ,</p>
<pre class="brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE web-app
    PUBLIC &quot;-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN&quot;
    &quot;http://java.sun.com/dtd/web-app_2_3.dtd&quot;&gt;

&lt;web-app&gt;

  &lt;!-- Servlets --&gt;
  &lt;servlet&gt;
    &lt;servlet-name&gt;userServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;
    	com.etechguide.project.gwtrpcdb.server.UserServiceImpl
    &lt;/servlet-class&gt;
  &lt;/servlet&gt;

  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;userServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/gwtrpcdb/user&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;

  &lt;!-- Default page to serve --&gt;
  &lt;welcome-file-list&gt;
    &lt;welcome-file&gt;GwtRpcDB.html&lt;/welcome-file&gt;
  &lt;/welcome-file-list&gt;

&lt;/web-app&gt;
</pre>
<p>Look at the url-pattern , it&#8217;s the MODULE_NAME/user which we have already specified with RemoteServiceRelativePath in the User Service. Now it is the time to write the asynchronous interface so that the client can use the services created by us.</p>
<p><Strong><u>Create an asynchronous interface :</u></Strong></p>
<pre class="brush: java">
import com.google.gwt.user.client.rpc.AsyncCallback;

public interface UserServiceAsync {
	void createUser(User user, AsyncCallback&lt;String&gt; callback)
			throws IllegalArgumentException;

	void checkUserExist(String userName, AsyncCallback&lt;Boolean&gt; callback);
}
</pre>
<p>You should follow certain rules while creating the asynchronous interface.</p>
<ul>
<li>The interface name should be the actual service name suffix with the word &#8216;Async&#8217;</li>
<li>The interface should have the similar methods that the actual service has with some exceptions.<br />
              1. The method should not have any return type other than void.<br />
              2. The methods should have an extra parameter at the end( AsyncCallback&lt;String&gt; callback). Here the &lt;String&gt; is the return type of the method in the actual service(User Service).</li>
<li>The methods in the async interface are allowed to throw Run-time Exceptions only. </li>
</ul>
<p>Lets call out services from a client side code. Have a look at the following code.</p>
<pre class="brush: java">
/**
   * Create a remote service proxy to talk to the server-side User service.
   */
	private final UserServiceAsync userService = GWT
			.create(UserService.class);

userService.createUser(user,
						new AsyncCallback&lt;String&gt;() {
							@Override
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								Window.alert(caught.getLocalizedMessage());

							}
							@Override
							public void onSuccess(String result) {

								if(result.equals(&quot;true&quot;)){
									Window.alert(&quot;User Created Successfully&quot;);
								}else{
									Window.alert(&quot;User Creation failed&quot;);
								}
								clearAll();

							}

						});

nameField.addBlurHandler(new BlurHandler() {
			@Override
			public void onBlur(BlurEvent event) {
				final String userName = nameField.getText();
				if(userName != null
                               &amp;&amp; userName.length() &gt;0){
					userService.checkUserExist(userName,
                                                new AsyncCallback&lt;Boolean&gt;() {
						@Override
						public void onFailure(Throwable caught) {
							Window.alert(caught.getLocalizedMessage());

						}
						@Override
						public void onSuccess(Boolean result) {
							if(result.booleanValue()){
								errorLabel.setText(&quot;&quot;);
								errorLabel.setText(userName+&quot; taken&quot;);
								errorLabel.setStyleName(&quot;errorLabel&quot;);
							}else{
								errorLabel.setText(&quot;&quot;);
								errorLabel.setText(userName+&quot; available&quot;);
								errorLabel.setStyleName(&quot;successLabel&quot;);
							}
						}
					});
				}
			}
		});
</pre>
<p>First we create a remote service proxy to talk to the server side user service. Once the proxy is created we give a call to the service methods. We create an anonymous callback class instance and pass to the service methods. AsyncCallback interface has two methods , onSuccess() and inFailure(). Once a request is success and completed , the onSuccess() method gets called. If there is a failure , onFailure() method gets called. One thing to note here , onSuccess() method&#8217;s parameter&#8217;s type should be same of the service&#8217;s called method&#8217;s parameter type.</p>
<p>Thats all !! <a href="http://etechGuide.in/wp-content/uploads/2010/06/GwtRpcDB.zip">Download</a> the project and start exploring more. Please feel free to write comments if you like it or would like to see any improvement on this post.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fweb%2Fgwt-rpc-with-database%2F&amp;linkname=Developing%20GWT-RPC%20application%20with%20a%20Database%20support"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/web/gwt-rpc-with-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GWT &#8211; How to create a HTML Label</title>
		<link>http://etechGuide.in/web/gwt/gwt-how-to-create-html-label/</link>
		<comments>http://etechGuide.in/web/gwt/gwt-how-to-create-html-label/#comments</comments>
		<pubDate>Mon, 14 Jun 2010 09:35:40 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[GWT]]></category>
		<category><![CDATA[html label]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[label]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=573</guid>
		<description><![CDATA[GWT provides a text-type label by default. You can set a text to a label but it is not possible to set a HTML to a Gwt label unless you do few changes. 

Label myLabel = new Label();
myLabel.setText(&#34;This is my label&#34;);
myLabel.setHtml(&#34;This&#60;br&#62;is&#60;br&#62;my&#60;br&#62;label&#34;); // compilation error

To achieve this , you can create your own customized label which [...]]]></description>
			<content:encoded><![CDATA[<p>GWT provides a text-type label by default. You can set a text to a label but it is not possible to set a HTML to a Gwt label unless you do few changes. </p>
<pre class="brush: java">
Label myLabel = new Label();
myLabel.setText(&quot;This is my label&quot;);
myLabel.setHtml(&quot;This&lt;br&gt;is&lt;br&gt;my&lt;br&gt;label&quot;); // compilation error
</pre>
<p>To achieve this , you can create your own customized label which extends com.google.gwt.user.client.ui.Widget. Have a look at the following code.</p>
<pre class="brush: java">
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Widget;

public class HTMLLabel extends Widget {

	public HTMLLabel(){
		this(null);
	}

	public HTMLLabel(String text)
	{
		setElement(DOM.createLabel());
		if(text != null)
			DOM.setInnerText(getElement(), text);
	}

	public String getText()
	{
		return DOM.getInnerText(getElement());
	}

	public void setHTML(String html){
		DOM.setInnerHTML(getElement(), html);
	}

	public String getHTML(){
		return DOM.getInnerHTML(getElement());
	}
}
</pre>
<p>We have created a class (HtmlLabel) extending the Widget class provided by GWT. At the line 12 ,we created a label by using the DOM class inside the parametrized constructor . Now we should expose a method so that consumer of this class can set a HTML to the created Label element. At the line 22 , we exposed a method where we set the inner HTML of the created label element. </p>
<p>A consumer of the HTMLLabel can create the HTML label in the following way,</p>
<pre class="brush: java">
HTMLLabel htmlLabel = new HTMLLabel();
htmlLabel.setHTML(&quot;This&lt;br&gt;is&lt;br&gt;my&lt;br&gt;label&quot;);
</pre>
<p>The output is a HTML label. As we have extended the Widget class , you can easily associate any event handlers to the HTML label that supported with normal GWT label. You can also create a SPAN element in GWT by following the above methodology of extending Widget class. I will discuss the SPAN element creation in my future post.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fweb%2Fgwt%2Fgwt-how-to-create-html-label%2F&amp;linkname=GWT%20%26%238211%3B%20How%20to%20create%20a%20HTML%20Label"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/web/gwt/gwt-how-to-create-html-label/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring 3.0 &#8211; Java Annotation based Dependency Injection(DI)</title>
		<link>http://etechGuide.in/spring/spring3_annotation_di/</link>
		<comments>http://etechGuide.in/spring/spring3_annotation_di/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 11:51:56 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[annotation]]></category>
		<category><![CDATA[dependency injection]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=553</guid>
		<description><![CDATA[<p>If you have been using Spring Framework for sometime , you will be aware that the Spring Framework has undergone several major changes in the latest Spring version 3.x. Spring Framework is now based on Java 5 and Java  6 fully supported. It has incorporated all the important features of Java latest versions. Spring version 3.0 encourages the developers to use Java Annotations instead of the configuration xml. This post will talk on the Annotation based <a href="http://etechguide.in/spring/dependency-injection-concept/">Dependency Injection</a> mechanism using Spring 3.0.</p>]]></description>
			<content:encoded><![CDATA[<p>If you have been using Spring Framework for sometime , you will be aware that the Spring Framework has undergone several major changes in the latest Spring version 3.x. Spring Framework is now based on Java 5 and Java  6 fully supported. It has incorporated all the important features of Java latest versions. Spring version 3.0 encourages the developers to use Java Annotations instead of the configuration xml. This post will talk on the Annotation based <a href="http://etechguide.in/spring/dependency-injection-concept/">Dependency Injection</a> mechanism using Spring 3.0.</p>
<p>In my one of the post I have discussed on setter injection using Spring 2.5(old method). Going through that <a href="http://etechguide.in/spring/setter-injection-type-of-dependency-injection/">post</a> will help you to find the difference between these two dependency injection approach. Lets get started.</p>
<p> <strong>What is Dependency Injection ?</strong> The answer is , It is a Design Pattern. Inversion of control or dependency injection pattern used to resolve component dependencies by injecting an instantiated component to satisfy dependency as opposed to explicitly requesting a component. So components will not be explicitly requested but components are provided as needed with the help of an Inversion of controller containers. Please read the <a href="http://etechguide.in/spring/dependency-injection-concept">post</a> to know more on it.</p>
<p> Spring has a concept of instantiated component , i.e , bean. Previously , we used to configure bean in the Application Context xml file but with Spring 3.0 , we will be configuring bean and injecting services(dependencies) from our java classes. Lets do it with an example use case.</p>
<p> Have a look at the following class relations </p>
<div id="class_relation" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="Class Relation" src="http://etechGuide.in/wp-content/uploads/2010/01/Annotation_DI.PNG" alt="Class Relation" width="493" height="438" /><br />
<p class="wp-caption-text">Class Relation</p></div>
<p><strong>Use Case :</strong> OpsClient is a normal Java Class which is registered with two services , i.e , Calculator Service and Print Service. Calculator Service is an interface to different calculation services available , like , addition , multiplication etc. Print Service is another interface to different printing services available , like , printing to a file or printing to console etc. The OpsClient makes use of these different services to perform different calculation and print them on different printing interfaces.</p>
<p> <strong>Approach with Spring 3.0 :</strong>
<p> CalculatorService and PrintService are two interfaces. AddCalculatorServiceImpl , MultiplyCalculatorServiceImpl are the implementation of CalculatorService interface and ConsolePrintServiceImpl , FilePrintServiceImpl are the implementation of the PrintService interface. Hence , these implementation classes are the beans in Spring. Lets define them one by one. </p>
<h4><span style="text-decoration: underline;">Listing 1 : CalculatorService.java Interface</span></h4>
<pre class="brush: java">
package com.company.spring.basic.service;

public interface CalculatorService {

	public long calculate(long x,long y);
	public String getOperationName();

}
</pre>
<h4><span style="text-decoration: underline;">Listing 2 : PrintService.java Interface</span></h4>
<pre class="brush: java">
package com.company.spring.basic.service;

public interface PrintService {

	public void print(String result);
}
</pre>
<p> Lets define all the implementation (beans) of the services </p>
<h4><span style="text-decoration: underline;">Listing 3 : AddCalculatorServiceImpl.java </span></h4>
<pre class="brush: java">
package com.company.spring.basic.service.impl;

import javax.inject.Named;

import com.company.spring.basic.service.CalculatorService;
@Named(&quot;AddCalcService&quot;)
public class AddCalculatorServiceImpl implements CalculatorService {

	@Override
	public long calculate(long x, long y) {
		return x+y;
	}

	@Override
	public String getOperationName() {
		return &quot; plus &quot;;
	}
}
</pre>
<h4><span style="text-decoration: underline;">Listing 4 : MultiplyCalculatorServiceImpl.java </span></h4>
<pre class="brush: java">
package com.company.spring.basic.service.impl;

import javax.inject.Named;

import com.company.spring.basic.service.CalculatorService;
@Named(&quot;MultiplyCalcService&quot;)
public class MultiplyCalculatorServiceImpl implements CalculatorService {

	@Override
	public long calculate(long x, long y) {

		return x*y;
	}

	@Override
	public String getOperationName() {

		return &quot; multiplies &quot;;
	}
}
</pre>
<h4><span style="text-decoration: underline;">Listing 5 : ConsolePrintServiceImpl.java </span></h4>
<pre class="brush: java">
package com.company.spring.basic.service.impl;

import javax.inject.Named;

import com.company.spring.basic.service.PrintService;
@Named(&quot;ConsolePrintService&quot;)
public class ConsolePrintServiceImpl implements PrintService {

	@Override
	public void print(String result) {
		System.out.println(result);

	}
}
</pre>
<h4><span style="text-decoration: underline;">Listing 6 : ConsolePrintServiceImpl.java </span></h4>
<pre class="brush: java">
package com.company.spring.basic.service.impl;

import javax.inject.Named;

import com.company.spring.basic.service.PrintService;

@Named(&quot;FilePrintService&quot;)
public class FilePrintServiceImpl implements PrintService{

	@Override
	public void print(String result) {
          // Code to write to a file
	}
}
</pre>
<p>Listing 3 &#8211; Listing 6 shows the normal but special implementation of the interfaces. They are special , because they are to support the Spring Framework&#8217;s Bean concept. To do that , each of this implementation is annotated with @Named(&#8221;SomeName&#8221;) annotation. In Spring 3.x you can use JSR 330&#8217;s @Named annotation in place of stereotype annotations and they will be automatically detected during component-scanning.<br />
The value of the @Named property will be used as the Bean Name. At this time Spring defaults for bean<br />
scope will be applied when using @Named.</p>
<p> This annotation will be available if if the JSR330 jar is present on the classpath. This jar is not part of the Spring 3.0 download. It is available under SpringSource Enterprise Bundle Repository. This annotation will be available under the <a href="http://www.springsource.com/repository/app/bundle/version/detail?name=com.springsource.javax.inject&#038;version=1.0.0">com.springsource.javax.inject-1.0.0.jar</a>. You can find the other jars <a href="http://www.springsource.com/repository/app/bundle">here</a>.</p>
<p>The next task is to build the Application context. Wait , we are not going to build any xml file here. It is going to be a simple Java class annotated with some useful annotations. Have a look at the following code.</p>
<h4><span style="text-decoration: underline;">Listing 7 : ApplicationConfig.java </span></h4>
<pre class="brush: java">
package com.company.spring.basic;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.company.spring.basic.client.OpsClient;
import com.company.spring.basic.service.CalculatorService;
import com.company.spring.basic.service.PrintService;
import com.company.spring.basic.service.impl.AddCalculatorServiceImpl;
import com.company.spring.basic.service.impl.ConsolePrintServiceImpl;
import com.company.spring.basic.service.impl.FilePrintServiceImpl;
import com.company.spring.basic.service.impl.MultiplyCalculatorServiceImpl;

@Configuration
public class ApplicationConfig {
	@Bean
	public PrintService screnPrint(){
		return new ConsolePrintServiceImpl();
	}
	@Bean
	public PrintService filePrint(){
		return new FilePrintServiceImpl();
	}
	@Bean
	public CalculatorService add(){
		return new AddCalculatorServiceImpl();
	}
	@Bean
	public CalculatorService Multiply(){
		return new MultiplyCalculatorServiceImpl();
	}
	@Bean
	public OpsClient result(){
		return new OpsClient();
	}
}
</pre>
<p> The class is annotated with @Configuration annotation. Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. These classes(@ Configuration annotated) consist principally of @Bean-annotated methods that define instantiation,configuration, and initialization logic for objects to be managed by the Spring IoC container.</p>
<p> To declare the beans , we have created methods and annotated with the @Bean annotation. The @Bean annotation plays the same role as the <bean/> element.When @Configuration classes are provided as input, the @Configuration class itself is registered as a bean definition, and all declared @Bean methods within the class are also registered as bean definitions.</P></p>
<p> So we have five beans declared all together. The last bean declared is the OpsClient bean which has two references , i.e , CalculatorService and PrintService(Please refer to the Class Relations diagram above). We will achieve this reference injection with the help of a very special annotation @Inject. Have a look.</p>
<h4><span style="text-decoration: underline;">Listing 8 : OpsClient.java </span></h4>
<pre class="brush: java">
package com.company.spring.basic.client;

import javax.inject.Inject;
import javax.inject.Named;
import com.company.spring.basic.service.CalculatorService;
import com.company.spring.basic.service.PrintService;

public class OpsClient {

	@Inject
	@Named(&quot;FilePrintService&quot;)
	private PrintService printService;

	@Inject
	@Named(&quot;MultiplyCalcService&quot;)
	private CalculatorService calculatorService;

	public void execute(long op1,long op2)  {
		printService.print(&quot;The result of &quot; + op1 +
				calculatorService.getOperationName() + op2 + &quot; is &quot;
	   			+ calculatorService.calculate(op1, op2) + &quot;!&quot;);

	}
}
</pre>
<p> printService and the calculatorCulatorService are the references to the different service implementations which can be injected using the @Inject annotation and @Named annotations. Here @Named annotation work as a mapping of service implementations. The name supplied as a parameter to the @Named annotation should be matched with one of the service implementation annotated with the same @Named annotation.</p>
<p> Like @Named , @Inject annotation can be found under the same package javax.inject.Inject. In the above class we are injecting the multiplication calculator service and the file print service using the annotations. Now the only thing pending is to instantiate the Application Context and call the client. It is explained below ,</p>
<h4><span style="text-decoration: underline;">Listing 9 : OperationTest.java </span></h4>
<pre class="brush: java">
public class OperationTest {
	public static void main(String[] args) {
		ApplicationContext ctx = new AnnotationConfigApplicationContext(
				com.company.spring.basic.ApplicationConfig.class);
		OpsClient opsBean = ctx.getBean(OpsClient.class);
		opsBean.execute(2, 3);
	}
}
</pre>
<p> Once you run the above method , multiplication of the value 2 and 3 will be written in a file.</p>
<p> You would need to add the following jar files to the class-path ,<br />
- cglib-nodep-2.1_3.jar<br />
- classworlds-1.1-alpha-2.jar<br />
- com.springsource.javax.inject-1.0.0.jar<br />
- com.springsource.javax.inject-sources-1.0.0.jar<br />
- jcl-over-slf4j-1.5.10.jar<br />
- log4j-1.2.15.jar<br />
- slf4j-api-1.5.10.jar<br />
- slf4j-log4j12-1.5.10.jar<br />
- spring-aop-3.0.0.RELEASE.jar<br />
- spring-asm-3.0.0.RELEASE.jar<br />
- spring-beans-3.0.0.RELEASE.jar<br />
- spring-context-3.0.0.RELEASE.jar<br />
- spring-core-3.0.0.RELEASE.jar<br />
- spring-expression-3.0.0.RELEASE.jar<br />
- spring-jdbc-3.0.0.RELEASE.jar<br />
- spring-tx-3.0.0.RELEASE.jar</p>
<p>Most of the above jars can be downloaded as part of Spring 3.x download. Other jars can be found <a href="http://www.springsource.com/repository/app/bundle">here</a>.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fspring%2Fspring3_annotation_di%2F&amp;linkname=Spring%203.0%20%26%238211%3B%20Java%20Annotation%20based%20Dependency%20Injection%28DI%29"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/spring/spring3_annotation_di/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Protecting web application from Path Traversal Attack</title>
		<link>http://etechGuide.in/web/protecting_path_traversal_attack/</link>
		<comments>http://etechGuide.in/web/protecting_path_traversal_attack/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 06:27:46 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Web Technologies]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=534</guid>
		<description><![CDATA[<p>A Path Traversal attack targets the files and directories which are saved outside the root folder. An attacker aims for a files path stored in the web server. An attacker use the combination of dot-dot-slash(../) to browse to arbitrary directories and files. The dot-dot-slash sequence helps an attacker to move up in any directory location. The attacker not only can access any arbitrary files/directories from your web server , it is possible to upload some malicious files to some location in your web server , if the proper care is not taken.</p>]]></description>
			<content:encoded><![CDATA[<p><strong>Path Traversal Attack , What it is ?</strong></p>
<p>A Path Traversal attack targets the files and directories which are saved outside the root folder. An attacker aims for a files path stored in the web server. An attacker use the combination of dot-dot-slash(../) to browse to arbitrary directories and files. The dot-dot-slash sequence helps an attacker to move up in any directory location. The attacker not only can access any arbitrary files/directories from your web server , it is possible to upload some malicious files to some location in your web server , if the proper care is not taken.</p>
<p>The attack can be made in several different ways. An attacker might not use the dot-dot-slash patter directly in the url , rather can use the Encoding and double encoding value of dot(.) and slash(/).<br />
..%2f represents ../<br />
..%255c represents ..\<br />
%2e%2e\ represents ..\ and so on.<br />
Hence an attacker can use the following type of urls to play with your web server files and directories,<br />
http://web_site.com/toGetFiles?file=../../../../dir/file<br />
http://web_site.com/toGetFiles?file=&#8230;%255cdir/file<br />
depending on your operating systems.</p>
<p><strong>How to protect the web application from this attack ?</strong></P></p>
<p>Anything from an web application can be accessed using a request to the application. Hence we need a strict sanity check for all the possible dot-dot-slash patterns on each request coming to the web application.<br />
The check should be performed well before a request reaches in a state to have response for it. It means , a web application pre-filter should be written to achieve this.</p>
<p>You need to do modification in the web.xml of your web application. Add the following tag in your web application :</p>
<h4><span style="text-decoration: underline;">Listing 1 : Add filter tag to web.xml file</span></h4>
<pre class="brush: xml">
&lt;filter&gt;
    &lt;filter-name&gt;PTA&lt;/filter-name&gt;
        &lt;display-name&gt;PTA&lt;/display-name&gt;
        &lt;description&gt;This is a Pre-filter for PTA Prevention&lt;/description&gt;
    &lt;filter-class&gt;com.etechGuide.fw.filter.PathTraversalFilter&lt;/filter-class&gt;
&lt;/filter&gt;
&lt;filter-mapping&gt;
         &lt;filter-name&gt; PTA&lt;/filter-name&gt;
         &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;
</pre>
<p>As we are looking for filtering all the request and we would like to pass all the request through the filter. Hence we will be writing a Request Wrapper to code our filter logic. Look at the following filter definition.</p>
<h4><span style="text-decoration: underline;">Listing 2 : The PathTraversalFilter code</span></h4>
<pre class="brush: java">
public class PathTraversalFilter implements Filter {
	private FilterConfig filterConfig;
	public void init(FilterConfig filterConfig)
                              throws ServletException {
		this.filterConfig = filterConfig;
	}

	public void destroy() {
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request,
                 ServletResponse response,FilterChain chain)
                           throws IOException, ServletException {

		chain.doFilter(new RequestWrapper((HttpServletRequest) request),
				response);

	}
}
</pre>
<p> At the line number 16 we wrap the request to filter out all the malicious attacks for Path Traversals. have a look at the RequestWrapper.java file where the actual filtering bypass takes place.</p>
<h4><span style="text-decoration: underline;">Listing 3 : The RequestWrapper code</span></h4>
<pre class="brush: java">
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public final class RequestWrapper extends HttpServletRequestWrapper {

	public RequestWrapper(HttpServletRequest servletRequest) {
		super(servletRequest);
	}

	public String[] getParameterValues(String parameter) {

	  String[] values = super.getParameterValues(parameter);
	  if (values==null)  {
                  return null;
          }
	  int count = values.length;
	  String[] encodedValues = new String[count];
	  for (int i = 0; i &lt; count; i++) {
                 encodedValues[i] = cleanPTA(values[i]);
	   }
	  return encodedValues;
	}

	public String getParameter(String parameter) {
		  String value = super.getParameter(parameter);
		  if (value == null) {
		         return null;
                  }
		  return cleanPTA(value);
	}

	public String getHeader(String name) {
	    String value = super.getHeader(name);
	    if (value == null)
	        return null;
	    return cleanPTA(value);

	}

	private String cleanPTA(String value) {
		// Bypassing all possible dot-dot-slash
                value = value.replaceAll(&quot;%2e&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%2f&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%5c&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%25u002e&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%25u002f&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%25u005c&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%c0&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%ae&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%af&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%c1&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%9c&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%e0&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%80&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%f0&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%81&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%f8&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%fc&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%25uff3C&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%25u002E&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%5C&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%2F&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%25uff0E&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%25uff0F&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%25ufe68&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%00&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%2A&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;%25&quot;, &quot;&quot;);
		value = value.replaceAll(&quot;\\|&quot;, &quot;&quot;); 

                /* File.separator is different from one OS to another.
                    Hence the additional check is done below
                */
		String sFileName = value
				.substring(value.lastIndexOf(File.separator) + 1);

		if (sFileName.indexOf(&quot;..&quot;) &gt;= 0) {
			sFileName = value.substring(value.lastIndexOf(&quot;..&quot;) + 2);
		}
		if (sFileName.indexOf(&quot;\\&quot;) &gt;= 0) {
			sFileName = value.substring(value.lastIndexOf(&quot;\\&quot;) + 1);
		} if (sFileName.indexOf(&quot;/&quot;) &gt;= 0) {
			sFileName = value.substring(value.lastIndexOf(&quot;/&quot;) + 1);
		}
		return sFileName;
	}
}
</pre>
<p> cleanPTA(String value) method of above class does all the bypassing. This method is open for modification to the reader of this post. The logic can be changed as per the need but the basic by passing is all about what is done above.</p>
<p> Once a request reaches your web application , it has to go through the filter. The filter uses a wrapper on each request and filter out all the malicious attacks.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fweb%2Fprotecting_path_traversal_attack%2F&amp;linkname=Protecting%20web%20application%20from%20Path%20Traversal%20Attack"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/web/protecting_path_traversal_attack/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Temporary File</title>
		<link>http://etechGuide.in/java/creating-a-temporary-file/</link>
		<comments>http://etechGuide.in/java/creating-a-temporary-file/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 06:57:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[file]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=524</guid>
		<description><![CDATA[<p>We use temporary file in our day to day applications. This post would talk on how to create a temporary file using Java Programming language. Java gives us a direct API to create a temporary file with some options.</p>
A temporary file can be created depending on certain condition and can be closed and deleted depending on some condition. For an example, lets assume we can upload and install a plug-in(a file) on an application. ]]></description>
			<content:encoded><![CDATA[<p>We use temporary file in our day to day applications. This post would talk on how to create a temporary file using Java Programming language. Java gives us a direct API to create a temporary file with some options.</p>
<p>A temporary file is a normal file that is created to hold the data temporarily. Efficient memory management is one of the important aspect of any normal application. Creation of temporary files and effective use of them help an application to free the memory in need for other purpose.</p>
<p>A temporary file can be created depending on certain condition and can be closed and deleted depending on some condition. For an example, lets assume we can upload and install a plug-in(a file) on an application. This file can be uploaded as a temporary file in a system defined temporary directory and can be installed from there. On a successful installation completion the temp file can be deleted permanently from the temporary directory.</p>
<p> Lets have a look at the following example , </p>
<h4><span style="text-decoration: underline;">Listing 1 : Creating the Temporary file</span></h4>
<pre class="brush: java">
package com.etechGuide.java.features;

import java.io.File;
import java.io.IOException;

public class TempCreation {
	public static void main(String[] args) {
		try {
			File tempFile = File.createTempFile(&quot;mailTogoa&quot;, &quot;.ddd&quot;);
			System.out.print(&quot;Created temporary file with name &quot;);
			System.out.println(tempFile.getAbsolutePath());
			tempFile.deleteOnExit();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
</pre>
<p>The Line number 9 creates a temporary file. Java IO provides an API like ,<br />
createTempFile(String prefix, String suffix) ;<br />
          -Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.<br />
In the above programming example , we have used the API to create a temporary file whose prefix is mailTogoa and suffix is .ddd. This file will be created under the system defined temporary directory.<br />
Java IO provides another API to create a temporary file . With the help of this API , you can create a temporary file in user defined location. The method look like this ,<br />
createTempFile(String prefix, String suffix, File directory)<br />
           -Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name.<br />
Both the above methods are public static method in the java.io.File class.</p>
<p>Line number 12 we call the deleteOnExit() method so that the temporary file can be deleted on JVM exit.</p>
<p>Last thing to be mentioned is , how to get the temporary file location pragmatically. Have a look at the following code list</p>
<h4><span style="text-decoration: underline;">Listing 2 : Detect the Temporary Directory</span></h4>
<pre class="brush: java">
package com.etechGuide.java.features;

public class DetectTempDirectory {

	private static final String SYSTEM_PROPERTY_TEMP_FOLDER = &quot;java.io.tmpdir&quot;;

	public static void main(String[] args) {
		String sTempFolder = System.getProperty(SYSTEM_PROPERTY_TEMP_FOLDER);
		System.out.println(sTempFolder);
	}
}
</pre>
<p> java.io.tmpdir property has the operating system specific temporary directory location. In the above example , we have read the property and printed on console.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fjava%2Fcreating-a-temporary-file%2F&amp;linkname=Creating%20a%20Temporary%20File"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/java/creating-a-temporary-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring DAO &#8211; JDBC Support</title>
		<link>http://etechGuide.in/spring/spring-dao-jdbc-support/</link>
		<comments>http://etechGuide.in/spring/spring-dao-jdbc-support/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 11:05:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[dao]]></category>
		<category><![CDATA[jdbc]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=506</guid>
		<description><![CDATA[Spring framework has a full-fledge support for the Database Access Objects(DAO). Spring’s support of DAO is not limited with the relational database like MySQL , Oracle , etc . It has support for Object Relational Databases like , HSQL , JDO etc. Whan I talk about suppot it means a lot of things.

Before going into the details , let us ask a question to ourselves .What is the real problem in coding a JDBC without a framework support ?]]></description>
			<content:encoded><![CDATA[<h4><span style="text-decoration: underline;">Introduction</span></h4>
<p>Spring framework has a full-fledge support for the Database Access Objects(DAO). Spring&#8217;s support of DAO is not limited with the relational database like MySQL , Oracle , etc . It has support for Object Relational Databases like , HSQL , JDO etc. Whan I talk about suppot it means a lot of things.</p>
<p>Before going into the details , let us ask a question to ourselves .What is the real problem in coding a JDBC without a framework support ?</p>
<p>All of us , who are JDBC programmers know these clearly :</p>
<ul>
<li>DBC is redundant .</li>
<li>Lots of Coding to be done .</li>
<li>Lots of Coding to be repeated (Yes , even after following all the OO academic theories !!).</li>
<li>Extra headache of Opening a connection and Closing a connection .</li>
<li>Maintaining a Connection Pool .</li>
<li>You find yourself doing the same things over and over again .</li>
<li>Yes , you must have to propagate the exception and handle it .</li>
<li>You have to handle transactions .</li>
<li>You have to write statements .</li>
<li>You have to execute the statements .</li>
<li>You have to get the results after executing the statement and iterate through it.</li>
</ul>
<p><span>Waoh !! So many things to take care. Isn&#8217;t it ?</span><span> What do the framework like Spring do then ? How does it help ?<br />
Here is the list of what it does (We will see the <em>HOW</em> shortly) :</span></p>
<ul>
<li>Define connection parameters .</li>
<li>Open the connection .</li>
<li><span><em>Specify the statement . &#8211; Work of an Application Developer.<br />
</em></span></li>
<li><span><em> </em></span>Prepare and execute the statement .</li>
<li>Set up the loop to iterate through the results (if any) .</li>
<li><span><em>Do the work for each iteration . </em></span><span><em>- Work of an Application Developer.</em></span></li>
<li><span><em> </em></span>Process any exception .</li>
<li>Handle transactions .</li>
<li>Close the connection .</li>
</ul>
<p>In the above list , Except specifying the statement and writing the business logic for each iteration , all other services are taken care by the SPRING Framework. Isn&#8217;t it cool ? You don&#8217;t have to worry about many things that would have taken most of your development time otherwise.</p>
<h4><span style="text-decoration: underline;">Know the Spring DAO Module :</span></h4>
<p><span style="text-decoration: underline;">Packages</span></p>
<p>The Spring Framework&#8217;s JDBC abstraction framework consists of four different packages, namely core, datasource, object, and support. Spring community documentation helps you with number of options for selecting an approach to form the basis for your JDBC database access.</p>
<ul>
<li><span><strong>JdbcTemplate</strong></span> &#8211; this is the classic Spring JDBC approach and the most widely used. Works well in a JDK 1.4 and higher environment.</li>
<li><span><strong>NamedParameterJdbcTemplate</strong></span> &#8211; wraps a JdbcTemplate to provide more convenient usage with named parameters instead of the traditional JDBC &#8220;?&#8221; place holders. This provides better documentation and ease of use when you have multiple parameters for an SQL statement. Works with JDK 1.4 and up.</li>
</ul>
<ul>
<li>
<span><strong>SimpleJdbcTemplate</strong></span> &#8211; this class combines the most frequently used features of both JdbcTemplate and NamedParameterJdbcTemplate plus it adds additional convenience by taking advantage of some Java 5 features like varargs, autoboxing and generics to provide an easier to use API. Requires JDK 5 or higher.
</li>
<li>
<span><strong>SimpleJdbcInsert and SimpleJdbcCall</strong></span> &#8211; designed to take advantage of database metadata to limit the amount of configuration needed. This will simplify the coding to a point where you only need to provide the name of the table or procedure and provide a Map of parameters matching the column names. Designed to work together with the SimpleJdbcTemplate. Requires JDK 5 or higher and a database that provides adequate metadata.
</li>
<li>
<span><strong>RDBMS Objects including MappingSqlQuery, SqlUpdate and StoredProcedure</strong></span> &#8211; an approach where you create reusable and thread safe objects during initialization of your data access layer. This approach is modeled after JDO Query where you define your query string, declare parameters and compile the query. Once that is done any execute methods can be called multiple times with various parameter values passed in. Works with JDK 1.4 and higher.
</li>
</ul>
<p>Lets see one example to learn and understand Spring-jdbc configuration. We will use jdbcTemplate style of JDBC approach. Reader of this post is expected to try other approaches as well.</p>
<p><span style="text-decoration: underline;">Setup Details</span></p>
<p>DataBase used : MySQL 5<br />
IDE Used : Eclipse 3.3.1<br />
Jar files needed : Please inclusde the followings jar into project classpath.</p>
<ol>
<li>commons-dbcp.jar &#8211; For DataSource Support.</li>
<li>commons-pool.jar &#8211; For Connection Pool Support.</li>
<li>mysql-connector-java-5.1.5.jar &#8211; Java Connector for MYSQL.</li>
<li>ojdbc14.jar &#8211; Query Support</li>
<li>spring.jar &#8211; The core framework library</li>
</ol>
<p>All the above jar files should be found under lib/ and dist/ directory of the Spring Distribution with Dependencies.</p>
<p>Lsts take an example of a table called User which is created under the data base called demo. The description of the demo.User table is as follows,</p>
<div id="command" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="describe table" src="http://etechGuide.in/wp-content/uploads/2009/12/User_DB_desc.PNG" alt="describe table" title="describe table" width="550" height="71" /><br />
<p class="wp-caption-text">describe table</p></div>
<p>Let us create a domain class called User which is a POJO(Plain old java object) class having the properties and setter / getters for the properties. A User.java look like ,</p>
<h4><span style="text-decoration: underline;">Listing 1 : User.java</span></h4>
<pre class="brush: java">
public class User {

          private Integer uid;
          private String userName;
          private String password;

          public User() {

          }
          public User(Integer uid, String userName, String password) {
                  this.uid = uid;
                  this.userName = userName;
                  this.password = password;
          }
          public Integer getUid() {
                  return uid;
          }
          public void setUid(Integer uid) {
              this.uid = uid;
          }
          public String getUserName() {
             return userName;
          }
          public void setUserName(String userName) {
            this.userName = userName;
          }
          public String getPassword() {
              return password;
          }
          public void setPassword(String password) {
                   this.password = password;
          }

         public String toString(){
              StringBuilder sb = new StringBuilder();
              sb.append(&quot;User ID :&quot;+getUid()+&quot;\n&quot;);
              sb.append(&quot;User Name :&quot;+getUserName());
              return sb.toString();
         }

    }
</pre>
<p>As the design pattern teaches us, we should do all the programming to interfaces and not to implementation . let us create an interface called UserDAO which will declare all the methods to be implemented for a User database operation.</p>
<h4><span style="text-decoration: underline;">Listing 2 : UserDAO.java</span></h4>
<pre class="brush: java">
public interface UserDAO {
    public boolean insertUser(User userRecord);
    public boolean updateUser(User userRecord);
    public boolean deleteUser(int uid);
    public User selectUser(int uid);
}
</pre>
<p>Before going to the implementation of UserDAO interface , we should know the following :<br />
      &#8211; Spring Framework will provide a mechanism to inject TransactionManager and DataSource instance to our implementation class.<br />
      &#8211; A Datasource can contain information like, driverClassName,url,username,password etc and all this information (parameters) will be injected by container to the implementation class.<br />
We will achieve these by coding our ApplicationContext.xml . Here it is .</p>
<h4><span style="text-decoration: underline;">Listing 3 : ApplicationContext.xml</span></h4>
<pre class="brush: xml">
&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-2.0.xsd&quot;&gt;

    &lt;bean id=&quot;dataSource&quot;
         class=&quot;org.apache.commons.dbcp.BasicDataSource&quot;
           destroy-method=&quot;close&quot;&gt;
        &lt;property name=&quot;driverClassName&quot; value=&quot;com.mysql.jdbc.Driver&quot;/&gt;
        &lt;property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost:3306/demo&quot;/&gt;
        &lt;property name=&quot;username&quot; value=&quot;root&quot;/&gt;
        &lt;property name=&quot;password&quot; value=&quot;abcdef&quot;/&gt;
        &lt;property name=&quot;maxActive&quot; value=&quot;10&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;maxIdle&quot; value=&quot;5&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;minIdle&quot; value=&quot;1&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;poolPreparedStatements&quot; value=&quot;true&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;initialSize&quot; value=&quot;1&quot;&gt;&lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;transactionManager&quot;
class=&quot;org.springframework.jdbc.datasource.DataSourceTransactionManager&quot;&gt;
 &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;&gt;&lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;userDao&quot; class=&quot;user.DAO.Impl.UserDaoImpl&quot;&gt;
   &lt;property name=&quot;transactionManager&quot;ref=&quot;transactionManager&quot;&gt;&lt;/property&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
</pre>
<p>Look at the last bean , userDao. This bean instantiate UserDaoImpl which is an implementation os UserDAO interface. As per the setter injection logic , UserDaoImpl.java should have a setter method for the reference property transactionManager. Now , have a look at the transactionManager bean. This is a type of (say , instance of) class org.springframework.jdbc.datasource.DataSourceTransactionManager . This is a class provided by the Spring Framework to the application developer. This class has a public setDataSource(DataSource dataSource) method. Hence you have the scope to inject dataSource object as a refrence to the transactionManager bean. </p>
<p>The dataSource bean is of type org.apache.commons.dbcp.BasicDataSource which has setter for all the properties defined under the bean. Additionaly , the bean described theat close() method will be called as a destroy-method to close the connection.</p>
<p>The Sequence is like this ,<br />
- Get a TransactionManager instance,<br />
- Get a DataSource from TransactionManager.<br />
- Form a jdbcTemplate from the Datasource instance.<br />
- Specify the Query.</p>
<p>All the above steps are taken care in the UserDaoImpl.java class. Have a look.</p>
<h4><span style="text-decoration: underline;">Listing 4 : UserDaoImpl.java</span></h4>
<pre class="brush: java">

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import user.DAO.UserDao;
import user.Domain.User;

public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    // Setter Injection happens here
    public void setTransactionManager(
            DataSourceTransactionManager transactionManager) {
        DataSource dataSource= transactionManager.getDataSource();
        jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public boolean deleteUser(int uid) {
        String sql = &quot;delete from demo.user where UID=?&quot;;
        Object[] params = new Object[]{uid};
        int deleted = jdbcTemplate.update(sql,params);
        if(deleted &gt; 0){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean insertUser(User userRecord) {

		String sql = &quot;insert into demo.user(UID,USERNAME,PASSWORD)&quot;
				+ &quot; values(?,?,?)&quot;;
		Object[] params = new Object[] { userRecord.getUid(),
				userRecord.getUserName(), userRecord.getPassword() };
		int[] types = new int[] { Types.INTEGER, Types.VARCHAR,
                            Types.VARCHAR };
		int inserted = jdbcTemplate.update(sql, params, types);
		if (inserted &gt; 0)
			return true;
		else
			return false;
    }

    @Override
    public User selectUser(int uid) {
        String sql = &quot;select UID,USERNAME from demo.user where UID=?&quot;;
        Object[] params = new Object[]{uid};
        final User user = new User();

        jdbcTemplate.query(sql,params,new RowCallbackHandler(){

            @Override
            public void processRow(ResultSet rs) throws SQLException {
                user.setUid(new Integer(rs.getInt(&quot;UID&quot;)));
                user.setUserName(rs.getString(&quot;USERNAME&quot;));
            }
        });
        return user;
    }

    @Override
    public boolean updateUser(User userRecord) {
        // You Implement
        return false;
    }

}
</pre>
<p>
Inspect the public void setTransactionManager(DataSourceTransactionManager transactionManager) method . The Dependency Injection takes place here. TransactionManager instance will be injected by Spring IOC container using the setter injection methodology. Once the TransactionManager is populated , a datasource instance can be created as ,<br />
DataSource dataSource= transactionManager.getDataSource();<br />
and a jdbcTemplate can be created as,<br />
jdbcTemplate = new JdbcTemplate(dataSource);
</p>
<p>
This jdbcTemplate should be used for all type of query execution. To understand different types of query execution , please refer to the <a href="http://static.springsource.org/spring/docs/2.5.x/reference/jdbc.html">Spring Source Doc on JDO</a> (from section 11.2) after running the above program successfully.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fspring%2Fspring-dao-jdbc-support%2F&amp;linkname=Spring%20DAO%20%26%238211%3B%20JDBC%20Support"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/spring/spring-dao-jdbc-support/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Integrate any J2EE-based web application with Spring</title>
		<link>http://etechGuide.in/spring/integrate-any-j2ee-based-web-application-with-spring/</link>
		<comments>http://etechGuide.in/spring/integrate-any-j2ee-based-web-application-with-spring/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 09:53:38 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[jdbc]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=493</guid>
		<description><![CDATA[Spring is a very good modular framework. Each module of the framework can be used depending on the various need in an application. Lets take an example of a J2EE-based web application which can use Spring-DAO module for it's data base layer or Spring-MVC to make the navigation between Model-View-Controller more modular and testable.
But , there might be a situation where Spring-MVC is not your need , rather you would like to take advantage of Spring-DAO module along with normal servlets and jsps. What to do then ?]]></description>
			<content:encoded><![CDATA[<p>Spring is a very good modular framework. Each module of the framework can be used depending on the various need in an application. Lets take an example of a J2EE-based web application which can use Spring-DAO module for it&#8217;s data base layer or Spring-MVC to make the navigation between Model-View-Controller more modular and testable.</p>
<p>These factors decides which component of the Spring can be used with the J2EE-based web application. If you are using Spring-MVC for your web application , Spring provides a front-controller in form of DispatcherServlet which does loading of of application context , instantiating your beans etc.</p>
<p>But , there might be a situation where Spring-MVC is not your need , rather you would like to take advantage of Spring-DAO module along with normal servlets and jsps. In this scenario , DispatchServlet(the front-controller) is not at all there in picture. But the challenge remain the same. Your application context must be loaded and all the beans should be instantiated.</p>
<p>This post talks on integrating the Spring framework with a J2EE-based web application which has normal servlets and jsps.</p>
<p>Two areas of your web application should be modified to integrate with Spring framework.</p>
<ul>
<li><strong>web.xml file</strong> &#8211; Where you need to specify the path of the Spring&#8217;s application context file and register some listeners.</li>
<li><strong>Your servlet</strong> &#8211; where you need make changes to get the instance of your bean to call bean&#8217;s methods.</li>
</ul>
<p>Lets assume , we have an application context which declares the beans for configuring and connecting to the Database. The application context file will look like this ,</p>
<h4><u>Listing 1 : Application Context Xml &#8211; databaseAppConfig.xml</u></h4>
<pre class="brush: xml">
&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-2.0.xsd&quot;&gt;

	&lt;bean id=&quot;dataSource&quot; class=&quot;org.apache.commons.dbcp.BasicDataSource&quot;&gt;
        &lt;property name=&quot;driverClassName&quot; value=&quot;com.mysql.jdbc.Driver&quot;/&gt;
        &lt;property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost:3306/library&quot;/&gt;
        &lt;property name=&quot;username&quot; value=&quot;root&quot;/&gt;
        &lt;property name=&quot;password&quot; value=&quot;novell&quot;/&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;jdbcTemplate&quot; class=&quot;org.springframework.jdbc.core.JdbcTemplate&quot;&gt;
		&lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;&gt;&lt;/property&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;bookDao&quot; class=&quot;com.etechguide.library.client.dao.BookDaoImpl&quot;&gt;
		&lt;property name=&quot;jdbcTemplate&quot; ref=&quot;jdbcTemplate&quot;&gt;&lt;/property&gt;
	&lt;/bean&gt;

&lt;/beans&gt;
</pre>
<p>Next , add these tags to the top of web.xml</p>
<p>A context-param tag with the param-name contextConfigLocation and it&#8217;s value. contextConfigLocation is the location of Spring&#8217;s application context file. you can define multiple application context files and declare them in space separated manner.</p>
<pre class="brush: xml">
&lt;!-- context-param --&gt;
&lt;context-param&gt;
   &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
   &lt;param-value&gt;/WEB-INF/databaseAppConfig.xml&lt;/param-value&gt;
&lt;/context-param&gt;
</pre>
<p>A listener which would load all these context files and pass it to Spring framework for instantiating the beans defined in the application conext xml file.</p>
<pre class="brush: xml">
&lt;!-- listener --&gt;
  &lt;listener&gt;
    &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener
  &lt;/listener-class&gt;
&lt;/listener&gt;
</pre>
<p>Once you are done with this step , use your servlet to get the instance of the bean created for you. If you look closely to the databaseAppConfig.xml file in the Listing 1 , you have a bean named <em>bookDao</em> which is the bean for the class file , com.etechguide.library.client.dao.BookDaoImpl. Lets assume , BookDaoImpl implements the interface BookDao.java and has definition of the methods like getBookDetails(), updateBook() deleteBook() etc. Hence you have to get the instance of BookDaoImpl if you would like to call the methods.</p>
<p> Have look at the following code , </p>
<pre class="brush: java">

public class BookDetailsSrvlet extends
      javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {

	private ServletConfig servletConfig = null;
	private ServletContext servletContext = null;
	private String state = null;
	private BookDao bookDao = null;

	protected ApplicationContext applicationContext;

	@Override
	public void init(ServletConfig config) throws ServletException {

		super.init(config);
		this.servletConfig = config;
		servletContext = this.servletConfig.getServletContext();
		if (applicationContext == null) {
			applicationContext = WebApplicationContextUtils
					.getWebApplicationContext(servletContext);
		}
		bookDao = (BookDao) applicationContext.getBean(&quot;bookDao&quot;);
	}
 .....
 .....
 // Other codes
 .....
 .....
}
</pre>
<p>The above code is from a servlet which makes use of the servletContext to get the ApplicationContext object and then called the getBean() method passing the bean name to get the instance of BookDaoImpl which is a type of BookDao interface.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fspring%2Fintegrate-any-j2ee-based-web-application-with-spring%2F&amp;linkname=Integrate%20any%20J2EE-based%20web%20application%20with%20Spring"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/spring/integrate-any-j2ee-based-web-application-with-spring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setter Injection &#8211; Type of Dependency Injection</title>
		<link>http://etechGuide.in/spring/setter-injection-type-of-dependency-injection/</link>
		<comments>http://etechGuide.in/spring/setter-injection-type-of-dependency-injection/#comments</comments>
		<pubDate>Wed, 02 Dec 2009 05:25:21 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[setter injection]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=478</guid>
		<description><![CDATA[<p>I have discussed on the concept of Dependency Injection in my <a href="http://etechguide.in/spring/dependency-injection-concept/">last post</a> . This post is about a specific type of Dependency Injection adopted by Spring. It is called <strong>Setter Injection</strong>. In Java POJO(Plain old java object) world , setters and getters are very common terms. A setter which sets an attribute value of a class. A getter which return the attribute value of a class.</p>]]></description>
			<content:encoded><![CDATA[<p>I have discussed on the concept of Dependency Injection in my <a href="http://etechguide.in/spring/dependency-injection-concept/">last post</a> . This post is about a specific type of Dependency Injection adopted by Spring. It is called <strong>Setter Injection</strong>. In Java POJO(Plain old java object) world , setters and getters are very common terms. A setter which sets an attribute value of a class. A getter which return the attribute value of a class.</p>
<p>Dependency can be injected using the setter method of a class. If a class is dependent on another class or primitive variables then the dependency should be declared as a state(variable) of the class and the class should have a setter method for it. </p>
<p>For an example , lets say Employee class is dependent on Address class , Employee class should have a state variable and a setter method , like , </p>
<h4><u>Listing 1 : Class with a setter method</u></h4>
<pre class="brush: java">
private Address address;
public void setAddress(Address address) {
        this.address = address;
}
</pre>
<p>The Spring IOC container should inject the address dependency using the setter method of Address. Whole dependency Injection is push method where a dependency value will be pushed and a client class should not bother about pulling the dependency back from anywhere. Lets learn to set setter dependency injection with following example.</p>
<p>Lets assume , we have a class relation like the following ,</p>
<h4><u>Listing 2 : Class Relations</u></h4>
<div id="class_relation" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="Employee has an Address and a Project" src="http://etechGuide.in/wp-content/uploads/2009/12/StterInjectionClassRelations.PNG" alt="Employee has an Address and a Project" width="350" height="350" /><br />
<p class="wp-caption-text">Employee has an Address and a Project</p></div>
<p>Look at the above class relations. Employee has an Address and Employee has a Project. Employee is dependent on both Address and Project classes directly. Using Spring IOC controller we can inject the dependency values to Employee class . Lets do it.</p>
<p>Spring IOC container needs a bean to be defined for all kind of classes whose object should be created for your application. For the above application we need instance of an Address class , Project Class and at last Employee class to get the employee data. Hence we need three beans to be declared. Beans should be declared in the application context xml file. The
<pre class="brush: xml"> &lt;bean&gt; </pre>
<p>tag should define a bean with it&#8217;s properties and <beans> tag should contain multiple beans in it.</p>
<p>Address class has three properties , i.e , street , city and pincode. Hence the bean for the Address class is defined as follows ,</p>
<h4><u>Listing 3 : Address Bean</u></h4>
<pre class="brush: xml">
&lt;bean id=&quot;addressBean&quot;
class=&quot;com.company.spring.injection.setter.model.Address&quot;&gt;
        &lt;property name=&quot;street&quot;&gt;
            &lt;value&gt;Bagmane Tech park&lt;/value&gt;
        &lt;/property&gt;
        &lt;property name=&quot;city&quot;&gt;
            &lt;value&gt;Bangalore&lt;/value&gt;
        &lt;/property&gt;
        &lt;property name=&quot;pincode&quot;&gt;
            &lt;value&gt;566093&lt;/value&gt;
        &lt;/property&gt;
&lt;/bean&gt;
</pre>
<p>Intention is to instantiate the Address class and populate it&#8217;s properties with respective values. Similar way , a bean definition for Project class could be as,</p>
<h4><u>Listing 4 : Project Bean</u></h4>
<pre class="brush: xml">
&lt;bean id=&quot;projectBean&quot;
class=&quot;com.company.spring.injection.setter.model.Project&quot;&gt;
        &lt;property name=&quot;projectName&quot;&gt;
            &lt;value&gt;iManager&lt;/value&gt;
        &lt;/property&gt;
        &lt;property name=&quot;department&quot;&gt;
            &lt;value&gt;ISM&lt;/value&gt;
        &lt;/property&gt;
        &lt;property name=&quot;teamMemberCount&quot;&gt;
            &lt;value&gt;10&lt;/value&gt;
        &lt;/property&gt;
        &lt;property name=&quot;deliveryDate&quot;&gt;
            &lt;ref bean=&quot;dateBean&quot;/&gt;
        &lt;/property&gt;
&lt;/bean&gt;
</pre>
<p>Point to notice is that the bean id is a logical name which can be any user friendly and non-objectionable <img src='http://etechGuide.in/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  name. Look at these bean definition closely. Each bean has property and each property is populated with some value. But thing is different for deliveryDate bean in projectBean. There is a
<pre class="brush: xml">&lt;ref&gt;</pre>
<p> tag instead of
<pre class="brush: xml">&lt;value&gt;</pre>
<p>. Because deliveryDate property is of type java.util.Date in Project class so we need a java.util.Date reference to set it&#8217;s value. So we need another bean for date. </p>
<h4><u>Listing 5 : Date Bean</u></h4>
<pre class="brush: xml">
&lt;bean id=&quot;dateBean&quot;
class=&quot;java.util.Date&quot;/&gt;
</pre>
<p>Now , lets have a look at the bean for the Employee class.</p>
<h4><u>Listing 6 : Employee Bean</u></h4>
<pre class="brush: xml">
&lt;bean id=&quot;employeeBean&quot;
class=&quot;com.company.spring.injection.setter.model.Employee&quot;&gt;
        &lt;property name=&quot;name&quot; value=&quot;Tapas Adhikary&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;empId&quot; value=&quot;88699&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;address&quot; ref=&quot;addressBean&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;project&quot; ref=&quot;projectBean&quot;&gt;&lt;/property&gt;
&lt;/bean&gt;
</pre>
<p>See the last two properties of the employeeBean bean. We have injected the addressBean and projectBean as a reference to the properties names address and project respectively. So your client code ( Where we have decided to create and instance of Employee and call it&#8217;s getter methods) should not worry about setting all this values. Employee&#8217;s dependencies will be pushed by the Spring IOC container.</p>
<p>The client code should be like this ,</p>
<h4><u>Listing 7 : Setter Injection Java file</u></h4>
<pre class="brush: java">
public class SetterInjection {
  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext(
          &quot;resources/applicationContext.xml&quot;);
    BeanFactory factory = (BeanFactory) context;
    Employee employee = (Employee) factory.getBean(&quot;employeeBean&quot;);
    Address address = employee.getAddress();
    Project project = employee.getProject();
    System.out.println(employee.getName());
    System.out.println(employee.getEmpId());
    System.out.println(address.getCity());
    System.out.println(address.getStreet());
    System.out.println(address.getPincode());
    System.out.println(project.getProjectName());
    System.out.println(project.getDepartment());
    System.out.println(project.getTeamMemberCount());
    System.out.println(project.getDeliveryDate().toString());
   }
}
</pre>
<p>Lets assume the application context file name is applicationContext.xml and it&#8217;s under a folder called resources. An ApplicationContext object should be formed with the help of the xml file. The context object is type of the Bean Factory which uses the Factory Design Pattern concept to create the object. Once you get the factory , you need to query the bean using the bean name , i.e , employeeBean. Thats it. Your Employee class is instantiated. Now you can get all the Employee properties including Address and Project properties injected using the xml file and the setter method of Address , Person and Employee.</p>
<p>The attached source code has the full version of the xml and all java source files. Download the code and import into your favorite IDE.</p>
<p>              I would like to conclude this post with one rule. A property name of a bean in the xml file should be equal to the setter method name of the attribute of the class without the word set at the beginning . Say if the property name of a bean in the application context xml file is departmentName then the corresponding class should have a setter method called </P></p>
<pre class="brush: java">
 public void setDepartmentName(String departMent){
     // Set the value
   }
</pre>
<p>
Note : &#8216;D&#8217; is in capital in the setter method after the word &#8217;set&#8217;.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fspring%2Fsetter-injection-type-of-dependency-injection%2F&amp;linkname=Setter%20Injection%20%26%238211%3B%20Type%20of%20Dependency%20Injection"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/spring/setter-injection-type-of-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dependency Injection Concept</title>
		<link>http://etechGuide.in/spring/dependency-injection-concept/</link>
		<comments>http://etechGuide.in/spring/dependency-injection-concept/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 05:38:49 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[ioc]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=462</guid>
		<description><![CDATA[<p>Java classes and objects should be as much as possible loosely coupled with other java classes and objects. The loosely-coupled behavior allows a Java code to be re-usable ,test-worthy , modular and well maintained. Often , A class depends on another class and arise the coupling .</p>
<p> Dependency Injection(DI) mechanism helps to introduce the loose coupling which makes your code more modular and testable.</p>
<p> The container which supports this dependency injection concept is called the I<strong>OC (Inversion of control) Container</strong>. Spring uses the concept of IOC and dependency injection to locate and inject services for you. </p>
<p> Read more to know more </p>
]]></description>
			<content:encoded><![CDATA[<p>Java classes and objects should be as much as possible loosely coupled with other java classes and objects. The loosely-coupled behavior allows a Java code to be re-usable ,test-worthy , modular and well maintained. Often , A class depends on another class and arise the coupling .</p>
<p>Say a class <em>FetchUserDataFromDB</em> depends on a class called <em>DataBaseAccess</em>, so it is obvious that , one would try to make a coupling by creating an instance of DataBaseAccess class in FetchUserDataFromDB class and call it&#8217;s methods. Here , we introduce a tight coupling and a strong dependency.</p>
<p>Look at the following scenarios :</p>
<h4><strong><span style="text-decoration: underline;">Scenario 1 : Tight Coupling</span> </strong></h4>
<div id="tight_coupling" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="Tight Coupling" src="http://etechGuide.in/wp-content/uploads/2009/11/tight_couple_DI.PNG" alt="Tight Coupling" width="289" height="299" /><br />
<p class="wp-caption-text">Tight Coupling</p></div>
<p><strong>Step 1 :</strong> Get me a database connection object from the pool.<br />
<strong>Step 2 :</strong> Take the database connection object conn.<br />
<strong>Step 3 :</strong> Thanks you , get me the User&#8217;s data whose id is 007.<br />
<strong>Step 4 :</strong> Here it is , His name is James Bond .<br />
<strong>Step 5 :</strong> Enough , Don&#8217;t want the conn anymore. Close it.<br />
<strong>Step 6 :</strong> Ok , closed and conn is taken back to pool.</p>
<h4><strong><span style="text-decoration: underline;">Scenario 2 : Loose Coupling</span> </strong></h4>
<div id="loose_coupling" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="Loose Coupling" src="http://etechGuide.in/wp-content/uploads/2009/11/loose_couple_DI.PNG" alt="Loose Coupling" width="304" height="285" /><br />
<p class="wp-caption-text">Loose Coupling</p></div>
<p><strong>Step 1 :</strong> Oh , you need a connection ? Injecting a connection conn from the Connection Pool.<br />
<strong>Step 2 :</strong> Fine , you need the user&#8217;s Information whose id is 007 ? Injecting the information ; He is James Bond.<br />
<strong>Step 3 :</strong> Look like you are not using the conn anymore. Injecting a service to close the connection and get the conn back to the pool.</p>
<p>Now the million dollar question is , which of these scenarios you would like to see in your code/project. Undoubtedly the scenario 2 where you do not have the burden of keeping a reference to the databaseaccess object and your client class is no more tightly coupled .<br />
Scenario 2 is the depiction of the Dependency Injection. Where the container injects the dependencies to the client classes and takes care of a full life cycle.</p>
<p>There are several advantages of dependency injection.</p>
<ul>
<li>Your code is modular.</li>
<li>Classes are not having any strong reference to another class.</li>
<li>You are able to test your code independently.</li>
</ul>
<p>The container which supports this dependency injection concept is called the I<strong>OC (Inversion of control) Container</strong>. Spring uses the concept of IOC and dependency injection to locate and inject services for you. Spring allows you to write your classes without having any dependency code .</p>
<p>There are three different ways dependencies can be injected.</p>
<ul>
<li>Constructor Injection (CI) - Dependencies (say , other class references) can be injected as a parameter to the constructor of a class. Hence no hard code object creation of the Dependent class is needed.</li>
<li>Setter Injection (SI) - Inject the dependency as a setter method of the class</li>
<li>Interface Injection (II) &#8211; interface injection, in which the exported module provides an interface that its users must implement in order to get the dependencies at runtime.</li>
</ul>
<p>
A design based on independent classes / components increases the re-usability and possibility to test the software. For example if a class A expects a Dao (Data Access object) for receiving the data from a database you can easily create another test object which mocks the database connection and inject this object into A to test A without having an actual database connection.<br />
</P></p>
<p>Have look at the Bean dependency in detail <a href="http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-factory-properties-detailed" target="_blank">Here</a> .</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fspring%2Fdependency-injection-concept%2F&amp;linkname=Dependency%20Injection%20Concept"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/spring/dependency-injection-concept/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Story behind start() and run() methods of Java Thread</title>
		<link>http://etechGuide.in/java/story_behind_start_and_run_method_thread/</link>
		<comments>http://etechGuide.in/java/story_behind_start_and_run_method_thread/#comments</comments>
		<pubDate>Fri, 27 Nov 2009 06:58:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[thread]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=448</guid>
		<description><![CDATA[<p>The basic concept of creating a java thread is to extend the class java.lang.Thread or to implement java.lang.Runnable interface. In both the cases , implementation of run() method is mandatory for your thread to be a meaningful Thread.</p>
<p>The run() method is the most important method in the thread classes, it is also the only method that we need to implement in both cases. Why it's only proper to call the start() method to start the thread instead of calling the run() method directly? What are the problems if we do so ? </P>
<p>Click below to have a look at the detail explanation.</p>]]></description>
			<content:encoded><![CDATA[<p>The basic concept of creating a java thread is to extend the class java.lang.Thread or to implement java.lang.Runnable interface. In both the cases , implementation of run() method is mandatory for your thread to be a meaningful Thread.</p>
<p>But , how do you execute a thread successfully ? Take an example of the class below. This is a thread for installation purpose.</p>
<h4><strong><span style="text-decoration: underline;">Listing 1 : Install Thread</span> </strong></h4>
<pre class="brush: java">
public class InstallThread extends Thread {

	public InstallThread(String threadName){
		super(threadName);
	}

	@Override
	public void run() {
		super.run();
		System.out.println(&quot;installing......&quot;);
	}

}
</pre>
<p>The above class does not install anything but gives you an impression of how to create a basic thread. You must have to give an implementation of the run() method.</p>
<p>Have a look at the following class where the instance of the install thread will be created and <em>started</em>.</p>
<h4><strong><span style="text-decoration: underline;">Listing 2 : Start the Install Thread</span> </strong></h4>
<pre class="brush: java">
public class InstallThreadTest {

	public static void main(String[] args) {
		InstallThread installThread = new InstallThread(&quot;Install Thread;&quot;);
		installThread.start();
		System.out.println(&quot;Installed.&quot;);
	}
}
</pre>
<p> We have started the thread using the start() method of the Thread class rather using the public run() method of the thread we have created.Why it&#8217;s only proper to call the start() method to start the thread instead of calling the run() method directly?</p>
<p>Because the run() method is not an ordinary class method. It should only be called by the Java Virtual Machine(JVM). We write threads because we want multi-threading in most of the cases. Writing thread classes is not about a single sequential thread, it&#8217;s about the use of multiple threads running at the same time and performing different tasks in a single program.
</p>
<p>The JVM needs to work closely with the underneath operating system for the actual implementation of concurrent operations. Improvement in the performance can be achieved by doing so.</p>
<p>You should not invoke the run() method directly. If you call the run() method directly, it will simply execute in the caller&#8217;s thread instead of as its own thread. Instead, you need to call the start() method, which schedules the thread with the JVM. The JVM will call the corresponding run() method when the resources and CPU is ready.<br />
               </P></p>
<p>Here is a twist. Don&#8217;t expect your run method to be executed for all the treads in the same order of start() method execution. The JVM is not guaranteed to call the run() method right way when the start() method is called, or in the order that the start() methods are called. </p>
<p>The JVM must implement a scheduling mechanism that shares the processor among all running threads. This is why when you call the start() methods from more than one thread, the sequence of execution of the corresponding run() methods is random, controlled only by the JVM.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fjava%2Fstory_behind_start_and_run_method_thread%2F&amp;linkname=Story%20behind%20start%28%29%20and%20run%28%29%20methods%20of%20Java%20Thread"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/java/story_behind_start_and_run_method_thread/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
