Observer design pattern example

Observale class
-----------------------------------------------

package com.anil.observable;

import java.util.Observable;

public class DataObject extends Observable {

private String txt;

public DataObject(String s) {
this.txt=s;
}

public String getTxt() {
return txt;
}

public void setTxt(String txt) {
this.txt = txt;
setChanged();
}

}
------------------------------------------------
Observer classes
------------------------------------------------
package com.anil.observer;

import java.util.Observable;
import java.util.Observer;

import com.anil.observable.DataObject;

public class FirstObserver implements Observer{

@Override
public void update(Observable o, Object arg) {

System.out.println("FirstObserver----"+((DataObject)o).getTxt());
}

}
-----------------------------------------------------------------------------------
package com.anil.observer;

import java.util.Observable;
import java.util.Observer;

import com.anil.observable.DataObject;

public class SecondObserver implements Observer {

@Override
public void update(Observable o, Object arg) {

System.out.println("SecondObserver----"+((DataObject)o).getTxt());

}

}
-----------------------------------------------------------------------------------
test classes
-----------------------------------------------------------------------------------
package com.anil.data;

import com.anil.observable.DataObject;
import com.anil.observer.FirstObserver;
import com.anil.observer.SecondObserver;

public class ObserverTest {

public static void main(String[] args) {

DataObject db = new DataObject("anil");
FirstObserver fo=new FirstObserver();
SecondObserver so=new SecondObserver();
db.addObserver(fo);
db.addObserver(so);
db.setTxt("Data Updated");
db.notifyObservers();

}

Singleton java object

For those who haven't heard of design patterns before, or who are familiar with the term but not its meaning, a design pattern is a template for software development. The purpose of the template is to define a particular behavior or technique that can be used as a building block for the construction of software - to solve universal problems that commonly face developers. Think of design code as a way of passing on some nifty piece of advice, just like your mother used to give. "Never wear your socks for more than one day" might be an old family adage, passed down from generation to generation. It's common sense solutions that are passed on to others. Consider a design pattern as a useful piece of advice for designing software.

Design patterns out of the way, let's look at the singleton. By now, you're probably wondering what a singleton is - isn't jargon terrible? A singleton is an object that cannot be instantiated. At first, that might seem counterintuitive - after all, we need an instance of an object before we can use it. Well yes a singleton can be created, but it can't be instantiated by developers - meaning that the singleton class has control over how it is created. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by prevent direct instantiation we can ensure that developers don't create a second copy.

So why would this be useful? Often in designing a system, we want to control how an object is used, and prevent others (ourselves included) from making copies of it or creating new instances. For example, a central configuration object that stores setup information should have one and one only instance - a global copy accessible from any part of the application, including any threads that are running. Creating a new configuration object and using it would be fairly useless, as other parts of the application might be looking at the old configuration object, and changes to application settings wouldn't always be acted upon. I'm sure you can think of a other situations where a singleton would be useful - perhaps you've even used one before without giving it a name. It's a common enough design criteria (not used everyday, but you'll come across it from time to time). The singleton pattern can be applied in any language, but since we're all Java programmers here (if you're not, shame!) let's look at how to implement the pattern using Java.
Preventing direct instantiation

We all know how objects are instantiated right? Maybe not everyone? Let's go through a quick refresher.

Objects are instantiated by using the new keyword. The new keyword allows you to create a new instance of an object, and to specify parameters to the class's constructor. You can specify no parameters, in which case the blank constructor (also known as the default constructor) is invoked. Constructors can have access modifiers, like public and private, which allow you to control which classes have access to a constructor. So to prevent direct instantiation, we create a private default constructor, so that other classes can't create a new instance.

We'll start with the class definition, for a SingletonObject class. Next, we provide a default constructor that is marked as private. No actual code needs to be written, but you're free to add some initialization code if you'd like.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
}

So far so good. But unless we add some further code, there'll be absolutely no way to use the class. We want to prevent direct instantiation, but we still need to allow a way to get a reference to an instance of the singleton object.
Getting an instance of the singleton

We need to provide an accessor method, that returns an instance of the SingletonObject class but doesn't allow more than one copy to be accessed. We can manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one). To do this, provide a public static method called getSingletonObject(), and store a copy of the singleton in a private member variable.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

private static SingletonObject ref;
}

So far, so good. When first called, the getSingletonObject() method creates a singleton instance, assigns it to a member variable, and returns the singleton. Subsequent calls will return the same singleton, and all is well with the world. You could extend the functionality of the singleton object by adding new methods, to perform the types of tasks your singleton needs. So the singleton is done, right? Well almost.....
Preventing thread problems with your singleton

We need to make sure that threads calling the getSingletonObject() method don't cause problems, so it's advisable to mark the method as synchronized. This prevents two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. To change the method, just add the synchronized keyword as follows to the method declaration :-

public static synchronized
SingletonObject getSingletonObject()

Are we finished yet?

There, finished. A singleton object that guarantees one instance of the class, and never more than one. Right? Well.... not quite. Where there's a will, there's a way - it is still possible to evade all our defensive programming and create more than one instance of the singleton class defined above. Here's where most articles on singletons fall down, because they forget about cloning. Examine the following code snippet, which clones a singleton object.

public class Clone
{
public static void main(String args[])
throws Exception
{
// Get a singleton
SingletonObject obj =
SingletonObject.getSingletonObject();

// Buahahaha. Let's clone the object
SingletonObject clone =
(SingletonObject) obj.clone();
}
}

Okay, we're cheating a little here. There isn't a clone() method defined in SingletonObject, but there is in the java.lang.Object class which it is inherited from. By default, the clone() method is marked as protected, but if your SingletonObject extends another class that does support cloning, it is possible to violate the design principles of the singleton. So, to be absolutely positively 100% certain that a singleton really is a singleton, we must add a clone() method of our own, and throw a CloneNotSupportedException if anyone dares try!

Here's the final source code for a SingletonObject, which you can use as a template for your own singletons.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}

private static SingletonObject ref;
}

Summary

A singleton is an class that can be instantiated once, and only once. This is a fairly unique property, but useful in a wide range of object designs. Creating an implementation of the singleton pattern is fairly straightforward - simple block off access to all constructors, provide a static method for getting an instance of the singleton, and prevent cloning.

hibernate mappinigs

db queries
------------

  CREATE TABLE TEST1
   (    "ID" NUMBER NOT NULL ENABLE,
    "DESC" VARCHAR2(20 BYTE),
     CONSTRAINT "TEST1_PK" PRIMARY KEY ("ID")

   ) ;


  CREATE TABLE "SYSTEM"."TEST2"
   (    "T2ID" NUMBER NOT NULL ENABLE,
    "T1FKID" NUMBER NOT NULL ENABLE,
    "T2DESC" VARCHAR2(20 BYTE),
     CONSTRAINT "TEST2_PK" PRIMARY KEY ("T2ID")
      CONSTRAINT "TEST2_TEST1_FK1" FOREIGN KEY ("T2ID")
     REFERENCES TEST1 ("ID") ON DELETE CASCADE ENABLE
   );


  CREATE TABLE "SYSTEM"."TEST3"
   (    "T3ID" NUMBER NOT NULL ENABLE,
    "T11FK1D" NUMBER NOT NULL ENABLE,
    "T2FK1D" NUMBER NOT NULL ENABLE,
    "T3DESC" VARCHAR2(20 BYTE),
     CONSTRAINT "TEST3_PK" PRIMARY KEY ("T3ID", "T11FK1D", "T2FK1D"),
      CONSTRAINT "TEST3_TEST1_FK1" FOREIGN KEY ("T11FK1D")
      REFERENCES TEST1 ("ID") ENABLE,
     CONSTRAINT "TEST3_TEST2_FK1" FOREIGN KEY ("T2FK1D")
      REFERENCES TEST2 ("T2ID") ENABLE
   ) ;






test1.hbm.xml
----------------
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="comjava.Test1" table="TEST1" schema="SYSTEM">
        <id name="id" type="java.math.BigDecimal">
            <column name="ID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="desc" type="java.lang.String">
            <column name="DESC" length="20" />
        </property>
        <set name="test3s" inverse="true">
            <key>
                <column name="T11FK1D" precision="22" scale="0" not-null="true" />
            </key>
            <one-to-many class="comjava.Test3" />
        </set>
        <one-to-one name="test2" class="comjava.Test2"></one-to-one>
    </class>
</hibernate-mapping>


test2.hbm.xml
--------------

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="comjava.Test2" table="TEST2" schema="SYSTEM">
        <id name="t2id" type="java.math.BigDecimal">
            <column name="T2ID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
      
        <one-to-one name="test1" class="comjava.Test1" constrained="true"></one-to-one>
      
        <property name="t1fkid" type="java.math.BigDecimal">
            <column name="T1FKID" precision="22" scale="0" not-null="true" />
        </property>
      
        <property name="t2desc" type="java.lang.String">
            <column name="T2DESC" length="20" />
        </property>
      
        <set name="test3s" inverse="true">
            <key>
                <column name="T2FK1D" precision="22" scale="0" not-null="true" />
            </key>
            <one-to-many class="comjava.Test3" />
        </set>
      
      
      
    </class>
</hibernate-mapping>


test3.hbm.xml
-------------

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="comjava.Test3" table="TEST3" schema="SYSTEM">
        <composite-id name="id" class="comjava.Test3Id">
            <key-property name="t3id" type="java.math.BigDecimal">
                <column name="T3ID" precision="22" scale="0" />
            </key-property>
            <key-property name="t11fk1d" type="java.math.BigDecimal">
                <column name="T11FK1D" precision="22" scale="0" />
            </key-property>
            <key-property name="t2fk1d" type="java.math.BigDecimal">
                <column name="T2FK1D" precision="22" scale="0" />
            </key-property>
        </composite-id>
      
      
        <many-to-one name="test1" class="comjava.Test1" update="false" insert="false" fetch="select">
            <column name="T11FK1D" precision="22" scale="0" not-null="true" />
        </many-to-one>
      
        <many-to-one name="test2" class="comjava.Test2" update="false" insert="false" fetch="select">
            <column name="T2FK1D" precision="22" scale="0" not-null="true" />
        </many-to-one>
        <property name="t3desc" type="java.lang.String">
            <column name="T3DESC" length="20" />
        </property>
    </class>
</hibernate-mapping>


java classes
--------------

test1.java
-----------
package comjava;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;


/**
 * Test1 entity. @author MyEclipse Persistence Tools
 */

public class Test1  implements java.io.Serializable {


    // Fields  

     private BigDecimal id;
     private String desc;
     private Set test3s = new HashSet(0);
     private Test2 test2;


    // Constructors

    /** default constructor */
    public Test1() {
    }

    /** minimal constructor */
    public Test1(BigDecimal id) {
        this.id = id;
    }
  
    /** full constructor */
    public Test1(BigDecimal id, String desc, Set test3s, Test2 test2) {
        this.id = id;
        this.desc = desc;
        this.test3s = test3s;
        this.test2 = test2;
    }

 
    // Property accessors

    public BigDecimal getId() {
        return this.id;
    }
  
    public void setId(BigDecimal id) {
        this.id = id;
    }

    public String getDesc() {
        return this.desc;
    }
  
    public void setDesc(String desc) {
        this.desc = desc;
    }

    public Set getTest3s() {
        return this.test3s;
    }
  
    public void setTest3s(Set test3s) {
        this.test3s = test3s;
    }

    public Test2 getTest2() {
        return this.test2;
    }
  
    public void setTest2(Test2 test2) {
        this.test2 = test2;
    }

}


test2.java
-----------
package comjava;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;


/**
 * Test2 entity. @author MyEclipse Persistence Tools
 */

public class Test2  implements java.io.Serializable {


    // Fields  

     private BigDecimal t2id;
     private Test1 test1;
     private BigDecimal t1fkid;
     private String t2desc;
     private Set test3s = new HashSet(0);


    // Constructors

    /** default constructor */
    public Test2() {
    }

    /** minimal constructor */
    public Test2(BigDecimal t2id, Test1 test1, BigDecimal t1fkid) {
        this.t2id = t2id;
        this.test1 = test1;
        this.t1fkid = t1fkid;
    }
  
    /** full constructor */
    public Test2(BigDecimal t2id, Test1 test1, BigDecimal t1fkid, String t2desc, Set test3s) {
        this.t2id = t2id;
        this.test1 = test1;
        this.t1fkid = t1fkid;
        this.t2desc = t2desc;
        this.test3s = test3s;
    }

 
    // Property accessors

    public BigDecimal getT2id() {
        return this.t2id;
    }
  
    public void setT2id(BigDecimal t2id) {
        this.t2id = t2id;
    }

    public Test1 getTest1() {
        return this.test1;
    }
  
    public void setTest1(Test1 test1) {
        this.test1 = test1;
    }

    public BigDecimal getT1fkid() {
        return this.t1fkid;
    }
  
    public void setT1fkid(BigDecimal t1fkid) {
        this.t1fkid = t1fkid;
    }

    public String getT2desc() {
        return this.t2desc;
    }
  
    public void setT2desc(String t2desc) {
        this.t2desc = t2desc;
    }

    public Set getTest3s() {
        return this.test3s;
    }
  
    public void setTest3s(Set test3s) {
        this.test3s = test3s;
    }

}


test3.java
----------

package comjava;



/**
 * Test3 entity. @author MyEclipse Persistence Tools
 */

public class Test3  implements java.io.Serializable {


    // Fields  

     private Test3Id id;
     private Test1 test1;
     private Test2 test2;
     private String t3desc;


    // Constructors

    /** default constructor */
    public Test3() {
    }

    /** minimal constructor */
    public Test3(Test3Id id, Test1 test1, Test2 test2) {
        this.id = id;
        this.test1 = test1;
        this.test2 = test2;
    }
  
    /** full constructor */
    public Test3(Test3Id id, Test1 test1, Test2 test2, String t3desc) {
        this.id = id;
        this.test1 = test1;
        this.test2 = test2;
        this.t3desc = t3desc;
    }

 
    // Property accessors

    public Test3Id getId() {
        return this.id;
    }
  
    public void setId(Test3Id id) {
        this.id = id;
    }

    public Test1 getTest1() {
        return this.test1;
    }
  
    public void setTest1(Test1 test1) {
        this.test1 = test1;
    }

    public Test2 getTest2() {
        return this.test2;
    }
  
    public void setTest2(Test2 test2) {
        this.test2 = test2;
    }

    public String getT3desc() {
        return this.t3desc;
    }
  
    public void setT3desc(String t3desc) {
        this.t3desc = t3desc;
    }

}

test3Id.java
--------------
package comjava;

import java.math.BigDecimal;


/**
 * Test3Id entity. @author MyEclipse Persistence Tools
 */

public class Test3Id  implements java.io.Serializable {


    // Fields  

     private BigDecimal t3id;
     private BigDecimal t11fk1d;
     private BigDecimal t2fk1d;


    // Constructors

    /** default constructor */
    public Test3Id() {
    }

  
    /** full constructor */
    public Test3Id(BigDecimal t3id, BigDecimal t11fk1d, BigDecimal t2fk1d) {
        this.t3id = t3id;
        this.t11fk1d = t11fk1d;
        this.t2fk1d = t2fk1d;
    }

 
    // Property accessors

    public BigDecimal getT3id() {
        return this.t3id;
    }
  
    public void setT3id(BigDecimal t3id) {
        this.t3id = t3id;
    }

    public BigDecimal getT11fk1d() {
        return this.t11fk1d;
    }
  
    public void setT11fk1d(BigDecimal t11fk1d) {
        this.t11fk1d = t11fk1d;
    }

    public BigDecimal getT2fk1d() {
        return this.t2fk1d;
    }
  
    public void setT2fk1d(BigDecimal t2fk1d) {
        this.t2fk1d = t2fk1d;
    }
 }


if u want to integrate spring with the ibernate project

the spring configuration will look like this

springConfig.xml
----------------

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="configLocation" value="file:src/hibernate.cfg.xml">
        </property>
    </bean>
</beans>

web service client

public static void main(String args){
String url="http;//localhost:9080/offer/axis/personWS?wsdl";
Service service=new service();
try{
Call cal=(Call) service.createCall();
call.setTargetEndPointAddress(url);

QName qn=new QName(url,"addPerson");
call.setOperationName(qn);
call.registerTypemapping(person.class,qn,
new BeanSerializerFactory(test.class,qn),
new BeanDeserializerFactory(test.class,qn));

// creation a person object

test vo=new test();

vo.setFirstName("FirstName");
vo.setMiddleName("Middlename");

call.invoke();




}catch(ServiceException e){
e.printStracktrace();
}catch(RemoteException e){
e.printStracktrace();
}


}