Saturday, May 30, 2009

Host Your Own Website on Dynamic IP Address


Now you can host your website on own local machine with a Dynamic IP Address. I have hosted on my local machine and yes you can do too!!!

I am not just writing this blog for hosting your websites on your local machine with dynamic ip address but also you can configure your machine to host repositories of your code and other software’s like Trac, CruiseControl, Svn, etc. I Hope you know about these software’s... :)

This is helpful for those guys who want to start with small team working in different places …

First of all the required things you have to have are:

1.Desktop or Laptop where you want to host the applications with good configuration.

2.Broadband Connection … it will be work with your dial up too...for that god only can help you ;)

3.Off-course software’s that to be installed. I am demonstrating with Apache 2.2 to host your static web application, Svn for code repository, Cruise-Control for automating build process of your code base and Trac for code browse and bug management.

4.And for hosting then website you need to register yourself on

http://www.dyndns.com

(Just for connecting to your machine to DNS server).

First let see how to get the domain name registered on DynDns.com.

After registeration on DydnDNS ,follow these steps:

1. Login to website and go My Services.


2. And from there you click on "Add Hostname".



3. Add the hostname and the choose the domain name which will get suffix to your hostname.Like I choose hostname as “ideeksha” and the domain as “gotdns.com”.So you access your website as

http://ideeksha.gotdns.com/ .


4. DynDNS will detect your ip address ,so click on autp detect link which will fill your ip address field. Finally click on “Create Host ” button. This will lead you towards checkout of this service and as it is free service you will be charged “Zero” dollars. Happily do the checkout and activate the service.

5. After this you have to edit your host file. As I am on Windows XP machine ,you will find your host file in “C:\WINDOW\system32\drivers\etc” directory. Open your hosts file and add the highlighted entry and save the file.


192.168.1.2 is the ip address assigned to my machine by the router ,as the router is connected to my modem. So the ip address that you entered on DynDNS is modem ip address and to route the request from modem to your machine ,this is entry is needed.

Now time is come when you can install Apache or tomcat on your machine and hosts the application there. So install the Apache and put the application under your apache htdocs folder and mine is here “C:\Program Files\Apache Software Foundation\Apache2.2\htdocs”.

Start your apache and excess the website as http://ideeksha.gotdns.com/. And you can see your website hosted on your local machine with dynamic ip address.



And there is one mystery about who will update the ip address on DynDns for you updated ip address when you get new ipaddress from your ISP. This can be solved by two means ,you can install the DynDns Auto Update Client which automatically update your dns entry in DynDNS or yor modem may have the facilty to do the same. You can see both settings images below.

Last thing which is remaining is to integrate svn and trac with your apache so you can access them.

Install svn and trac with their default settings and change the httpd.conf file of apache with these settings:

<Location /svn/iDeekshaMailClient>

DAV svn

SVNPath C:/SVNREPO/iDeekshaMailClient

AuthType Basic

AuthName "Subversion iDeekshaMailClient repository"

AuthUserFile c:/etc/svn-auth-file

Require valid-user

</Location>

<LocationMatch "/Trac/[^/]+/login">

AuthType Basic

AuthName "Trac"

AuthUserFile C:/etc/svn-auth-file

Require valid-user

</LocationMatch>

<Location /Trac>

SetHandler mod_python

PythonInterpreter main_interpreter

PythonHandler trac.web.modpython_frontend

PythonOption TracEnvParentDir C:/TRACREPO

PythonOption TracUriRoot /Trac

</Location>

Now you can access your svn as http://ideeksha.gotdns.com/svn/iDeekshaMailClient and trac as http://ideeksha.gotdns.com/Trac/iDeekshaMailClient Integration of svn and trac in detail you get from googling :)

For svn installation and integration with apache (http://www.trajiklyhip.com/blog/index.cfm/2007/3/13/Part-2-Installing-Subversion-142-and-Integrating-Subversion-With-Apache)

For your cruise-control you have install Cruise-Control first and for that you have to register for different domain name like I have done .You have to do redirect as apache is running on 80 port and cruise control is running on 7070 port , so have to do port forwarding on your modem for 7070 for cruise control application.

So, this concludes with our integration of trac and svn with apache and running the cruise-control build on your code base .So now from any member of your team can take check out of your code and do code browsing using trac and off-course do the build on code base using cruise-control.

Happy Coding!!!

Cheers!

Thursday, May 28, 2009

Spring + Hibernate


Spring + Hibernate


This article is for those who know spring and hibernate but never integrated or run them together. I hope you know both of these technologies as I am not going in detail of these :)

Steps to integrate hibernate and spring are as follows:
1. Jars for hibernate, spring and the dependencies (Use maven for this, I will be adding pom.xml file for your reference).
2. Mapping and Configuration files of hibernate.
3. And off-course you have to have the spring bean xml file.

I will split this tutorial into three parts:
1. Develop Hibernate Application
2. Using hibernate with Spring Framework.
3. Running the Example Application.


Developing Hibernate Application:
We will have employee as entity with which we are going play with.

First will look into how we do this in traditional way means with standalone client:
1. Will have Employee POJO class
Employee.java
---------------------------------------------
package com.ideeksha;

public class Employee {

private Long employeeCode;
private String employeeName;
private int employeesalary;

public Long getEmployeeCode() {
return employeeCode;
}
public void setEmployeeCode(Long employeeCode) {
this.employeeCode = employeeCode;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public int getEmployeesalary() {
return employeesalary;
}
public void setEmployeesalary(int employeesalary) {
this.employeesalary = employeesalary;
}
}

2. Then will have the mapping file

Employee.hbm.xml
---------------------------------------------

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.ideeksha">
<class name="Employee" table="EMP">
<id name="employeeCode" column="EMP_CODE" type="long">
<generator class="increment"></generator>
</id>
<property name="employeeName" column="NAME" type="string"></property>
<property name="employeesalary"></property>
</class>
</hibernate-mapping>

3. And the configuration file :

Hibernate.cfg.xml
---------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">tiger</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:machinename</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9iDialect</property>

<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>

<mapping resource="Employee.hbm.xml"/>

</session-factory>
</hibernate-configuration>
4. Offcourse the main class to run this :

PersistEmployee.java
--------------------------------------------------------


package com.ideeksha;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class PersistEmp {

/**
* @param args
*/
public static void main(String[] args) {
SessionFactory factory=null;
Session session = null;
Transaction tx = null;

try
{
factory = new Configuration().configure().buildSessionFactory();
session = factory.openSession();
tx = session.beginTransaction();

Employee emp = new Employee();
emp.setEmployeeName("Anil Verma");

session.save(emp);


tx.commit();

}catch (Exception e) {
tx.rollback();
e.printStackTrace();
}finally
{
session.close();
factory.close();
}


}

}


Yes!! you have developed your simple hibernate application.

2. Using hibernate with Spring Framework.

And now time is come to integrate this to Spring.Configuring the Hibernate SessionFactory in Spring.Here is an example Hibernate SessionFactory configured in Spring. You will be using this instead of the typical hibernate-config.xml. All we are doing here is telling Hibernate/Spring what our Hibernate mapping files are:

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>

<value>Employee.hbm.xml</value>
</list>
</property>
</bean>

If you have a hibernate.properties in your classpath, the Spring LocalSessionFactoryBean will use that file to configure the database connections, dialect and pooling. Alternatively, you can define a DataSource in Spring (any class that implements javax.sql.DataSource) and explicity set all of your Hibernate properties in the LocalSessionFactoryBean:

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>

</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle9iDialect
</prop>
</props>

</property>
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName">
<value> oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value> jdbc:oracle:thin:@localhost:1521:machinename</value>

</property>
<property name="username"><value>scott</value></property>
<property name="password"><value>tiger</value></property>
</bean>


Extending HibernateDaoSupport for the Actual DAO Implementation
The Spring HibernateDaoSupport class provides all kinds of convenience methods for working with Hibernate. Most of these are accessible via the HibernateTemplate object that this class exposes.
Anyway, here is our EmployeeDAO implemented by extending HibernateDaoSupport:

EmployeeDAOImpl.java
-----------------------------------------
package com.ideeksha;
public class EmployeeDAOImpl
extends HibernateDaoSupport
implements EmployeeDAO
{
/**
* Returns a java.util.List of all Employees in the system.
* @return
*/
public Collection getEmployees()
{
return getHibernateTemplate().loadAll(Employee.class);
}

/**
* Get a Employee Object given the id
* @param id
* @return
*/
public Employee getEmployeeById(Long id)
{
return (Employee)
getHibernateTemplate().load(Employee.class, id);
}

/**
* Save a Employee Object, if the given Employee
* is not in the data store,it should insert it,
* if it is in the data store, it should update it.
* @param employee
*/
public Employee saveEmployee(Employee employee)
{
getHibernateTemplate().saveOrUpdate(employee);
return employee;
}
}

3. Running the Example Application.

Now we are done with the spring configuration. We will write a client for Spring DAO now.
PersistEmp.java
--------------------------------

package com.ideeksha;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PersistEmp {

public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("spring2beans.xml");
EmployeeDAO dao=( EmployeeDAO)context.getBean("employeeDAO");
Employee emp = new Employee();
emp.setEmployeeName("Anil Verma");
dao.save(group);

}
}

Now we can run this client application directly. This will be the final spring conf file :
spring2beans.xml
-------------------------------
<!-- from the file 'context.xml' -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">


<bean id="employeeDAO" class="com.ideeksha.EmployeeDAOImpl">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>


<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/hibernate"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>com/ideeksha/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
</value>
</property>
</bean>
</beans>


And yes the last part remaining is the pom.xml file :

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ideeksha</groupId>
<artifactId>SpringHibernate</artifactId>
<name>SpringHibernate</name>
<version>0.0.1-SNAPSHOT</version>
<description/>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.5.ga</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>

</project>



Check the database table, is your employee is been persisted or not ...If Yes ..I can say now you have successfully integrated hibernate and spring. If "No" ...Its time to go to bed ...try next morning :)


And off-course if you feel lazy to do the coding ...this is the link were you will get the code ..

http://www.mediafire.com/download.php?jydgwgmhynw

Cheers!!!

Wednesday, May 27, 2009


The Spring Framework: Understanding IoC

In Spring, the Inversion of Control (IoC) principle is implemented using the Dependency Injection (DI) design pattern. IoC or Inversion of Control is one of the core features of Spring. It helps in simplifying the implementation of business logic. To use the Spring Framework to its full potential, understanding the IoC container of the framework is essential.

Let's understand dependency injection with the help of an example. First we will see a java version of the example and later we will add spring functionalities to it. As far as the example go, its pretty simple. The Quiz interface exposes the getQuestion() method. To keep things simple, our Quiz will generate only one question.

Quiz.java
----------------
package com.ideeksha;

public interface Quiz {

public String getQuestion();
}

The StrutsQuiz and the SpringQuiz class implements Quiz interface and they generate questions related to struts and spring respectively.

StrutsQuiz.java
----------------------
package com.ideeksha;

public class StrutsQuiz implements Quiz {

@Override
public String getQuestion() {
return "Are you new to Struts?";
}

}

SpringQuiz.java
----------------------
package com.ideeksha;

public class SpringQuiz implements Quiz {

@Override
public String getQuestion() {
return "Are you new to Spring?";
}

}

We have a QuizService class that displays the question to the user. The QuizService class holds reference to the Quiz.

QuizService.java
-----------------------
package com.ideeksha;

public class QuizService {

private Quiz quiz = new SpringQuiz ();

public void askQuestion()
{
System.out.println(quiz.getQuestion());
}
}

Finally we create the QuizProgram class to conduct quiz.
QuizProgram.java
----------------
package com.ideeksha;

public class QuizProgram {

public static void main(String[] args) {
QuizService quizService = new QuizService();
quizService.askQuestion();
}

}

As you can see it is pretty simple, here we create an instance of the QuizService class and call the askQuestion() method. When you run the program as expected "Are you new to Spring?" gets printed in the console.




Spring Dependency Injection

Let's have a look at the class diagram of this example. The green arrows indicate generalization and the blue arrows indicates association.




As you can see this architecture is tightly coupled. We create an instance of the Quiz in the QuizService class in the following way.
private Quiz quiz = new SpringQuiz();

To make our quiz master Struts genius we need to make modifications to the QuizService class like this.
private Quiz quiz = new StrutsQuiz();

So it is tightly coupled. Now lets see how we can avoid this by using the Dependency Injection design pattern. The Spring framework provides prowerful container to manage the components. The container is based on the Inversion of Control (IoC) principle and can be implemented by using the Dependency Injection (DI) design pattern. Here the component only needs to choose a way to accept the resources and the container will deliver the resource to the components.
In this example instead of we, directly creating an object of the Quiz bean in the QuizService class, we make use of the container to do this job for us. Instead of hard coding any values we will allow the container to inject the required dependancies.
We can inject the dependancies using the setter or constructor injection. Here we will see how we can do this using the setter injection.
QuizService.java
-----------------------
package com.ideeksha;

public class QuizService {

Quiz quiz;

public void setQuiz(Quiz quiz) {
this.quiz = quiz;
}

public void askQuestion()
{
System.out.println(quiz.getQuestion());
}
}

The value for the Quiz will be set using the setQuiz () method. The Quiz object is never instantiated in the QuizService class, but still we access it. Usually this will throw a NullPointerException, but here the container will instantiate the object for us, so it works fine.

After making all the changes, the class diagram of the example look like this.



The container comes into picture and it helps in injecting the dependancies.
The bean configuration is done in the beans.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="springQuiz" class="com.ideeksha.SpringQuiz"></bean>
<bean id="strutsQuiz" class="com.ideeksha.StrutsQuiz"></bean>
<bean id="quizService" class="com.ideeksha.QuizService">
<property name="quiz">
<ref local="springQuiz"/>
</property>
</bean>
</beans>

We define each bean using the bean tag. The id attribute of the bean tag gives a logical name to the bean and the class attribute represents the actual bean class. The property tag is used to refer the property of the bean. To inject a bean using the setter injection you need to use the ref tag.

Here a reference of SpringQuiz is injected to the Quiz bean. When we execute this example, "Are you new to Spring?" gets printed in the console.
To make our Quiz ask questions related to Struts, the only change we need to do is, to change the bean reference in the ref tag.

<bean id="quizService" class="com.ideeksha.QuizService">
<property name="quiz">
<ref local="strutsQuiz"/>
</property>
</bean>

In this way the Dependency Injection helps in reducing the coupling between the components. And yes it says “NO” to ‘new’ operator!!!

To Run This example



QuizExample.java

---------------------------
package com.ideeksha;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class QuizProgram {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
QuizService quizService = (QuizService) context.getBean("quizService");
quizService.askQuestion();
}
}


More things on Spring IOC --Ways to do Spring dependency Injection !!!
Inversion of Control or IoC is one of the techniques used to wire services or components to an application program. By definition, IoC is “A software design pattern and set of associated programming techniques in which the flow of control of a system is inverted in comparison to the traditional interaction mode.” Simply stated, in IoC, instead of an application calling the framework, it is the framework that calls the components specified by the application.
This approach is similar to the one that Hollywood agents adopt with their clients. It is sometimes known as “Don’t call me, I will call you.” This is why IoC is also known as the Hollywood approach.
However, IoC is a broad and generic term. The aspect of IoC that the Spring Framework uses is "Injection of required resources or dependency at Run-time into the dependent resource," which is also known as Dependency Injection. Hence, the service provided by the IoC container of Spring is Dependency Injection. Therefore, I will be using the terms IoC and Dependency Injection in a lax way.
There are three forms or styles of Dependency Injection. They are:
1. Constructor Injection
2. Setter Injection
3. Interface Injection

Of these, the Spring Framework directly supports the first and second forms whereas the third form is supported indirectly. Between the first and the second, the Spring Framework prefers the use of second rather than the first. Here are the details.
1. Constructor Injection: In Constructor Injection, an IoC container uses the constructor to inject the dependency. All the dependencies, whether they are simple values or references to other objects, are declared in the constructor. One of the advantages of Constructor Injection is that all the dependencies are declared in one go. This also helps in understanding whether the class depends on too many services.
2. Setter Injection: This form of Dependency Injection uses Setters, also known as mutators (because they change the value of the corresponding instance variables), to inject the required resources or dependencies. In other words, each of the objects that the class depends upon will have a setter and the IoC container will use the setters to provide the resource at run-time.

The main difference between Constructor Injection and Setter Injection is that in Constructor Injection, the handing over of the dependencies takes place during instantiation of the dependent object, whereas with Setter Injection, it takes place after the dependent object is instantiated. The Spring Framework favors Setter Injection over Constructor Injection.
3. Interface Injection: Interface Injection provides the concrete implementations of an interface to the dependent object according to the configuration. The main difference between Interface Injection and the previous two is that in Interface Injection, any of the implementations of the interface can be injected, whereas with the other two, the object of the class specified is injected. Spring does not provide direct support for Interface Injection.

That completes the overview of IoC.

To execute this example add the following jar files to the classpath.

antlr-runtime-3.0
commons-logging-1.0.4
org.springframework.asm-3.0.0.M3
org.springframework.beans-3.0.0.M3
org.springframework.context-3.0.0.M3
org.springframework.context.support-3.0.0.M3
org.springframework.core-3.0.0.M3
org.springframework.expression-3.0.0.M3