Raible's Wiki

Raible Designs
Wiki Home
News
Recent Changes

AppFuse

Homepage
  - Korean
  - Chinese
  - Italian
  - Japanese

QuickStart Guide
  - Chinese
  - French
  - German
  - Italian
  - Korean
  - Portuguese
  - Spanish
  - Japanese

User Guide
  - Korean
  - Chinese

Tutorials
  - Chinese
  - German
  - Italian
  - Korean
  - Portuguese
  - Spanish

FAQ
  - Korean

Latest Downloads

Other Applications

Struts Resume
Security Example
Struts Menu

Set your name in
UserPreferences


Referenced by
Articles
Articles_pt
CreateActions
CreateDAO
CreateDAO_sp
CreateDAOiBATIS
CreateDAOiBATIS_ko
CreateManager_es
JSFBeans
SpringControllers
...and 3 more




JSPWiki v2.2.33

[RSS]


Hide Menu

CreateManager


Difference between version 80 and version 30:

At line 1 changed 1 line.
__Part II:__ [Creating new Managers|CreateManager] - A HowTo for creating [Business Delegates|http://java.sun.com/blueprints/corej2eepatterns/Patterns/BusinessDelegate.html] that talk to the database tier (DAOs) and the web tier (Struts Actions).
__Part II:__ [Creating new Managers|CreateManager] - A HowTo for creating Business Facades that talk to the database tier (DAOs) and handle transaction management.
At line 6 changed 1 line.
This tutorial will show you how to create a Business Delegate class (and a JUnit Test) to talk to the [DAO we created in Part I|CreateDAO].
This tutorial will show you how to create a Business Facade class (and a JUnit Test) to talk to the [DAO we created in Part I|CreateDAO].
At line 8 changed 1 line.
In the context of [AppFuse], this is called a Manager class. It's main responsibility is converting backend data (POJOs) into front-end data (Struts ActionForms). The main reason I even use Managers, rather than just calling the DAOs directly is testability. It's nice to be able to populate a Form manually (in the test) and call the DAO to persist it, and verify the database gets the proper results. The [Business Delegate|http://java.sun.com/blueprints/corej2eepatterns/Patterns/BusinessDelegate.html] pattern from Sun says that these objects are usefull for de-coupling your presentation layer from your database layer. Managers should also be where you put any business logic for your application.
In the context of [AppFuse], this is called a Manager class. Its main responsibility is to act as a bridge between the persistence (DAO) layer and the web layer. It's also useful for de-coupling your presentation layer from your database layer (i.e. for Swing apps). Managers should also be where you put any business logic for your application.
At line 17 changed 1 line.
* [3] Run the ManagerTest
* [3] Configure Spring for this Manager and Transactions
* [4] Run the ManagerTest
At line 20 changed 1 line.
In [Part I|CreateDAO], we created a Person object and PersonDao - so let's continue developing this entity. First, let's create a JUnit test for the PersonManager. Create PersonManagerTest in the test/web/**/service directory. We'll want to test the same basic methods (get, save, remove) that our DAO has.
In [Part I|CreateDAO], we created a Person object and PersonDao - so let's continue developing this entity. First, let's create a JUnit test for the PersonManager. Create PersonManagerTest in the test/service/**/service directory. We'll want to test the same basic methods (get, save, remove) that our DAO has.
At line 24 changed 1 line.
This class should extend [BaseManagerTestCase|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/webapp/service/BaseManagerTestCase.java.html], which already exists in the ''service'' package. The parent class (BaseManagerTestCase) serves the same functionality as the BaseDaoTestCase - to load a properties file that has the same name as your *Test.class.
This class should extend [BaseManagerTestCase|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/service/BaseManagerTestCase.java.html], which already exists in the ''service'' package. The parent class (BaseManagerTestCase) serves similar functionality as the BaseDaoTestCase.
At line 28 changed 1 line.
The code below is what we need for a basic JUnit test of our Managers. It created and destroys our PersonManager. The "conn" object is initialized (and obtains a connection) in the [BaseManagerTestCase|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/webapp/service/BaseManagerTestCase.java.html] class.
The code below is what you need for a basic JUnit test of your Manager. Unlike the DaoTest, this test uses [jMock|http://jmock.org] to isolate the Manager from its dependencies and make it a ''true'' "unit" test. This can be very helpful because it allows you to test your business logic w/o worrying about other dependencies. The code below simply sets up the Manger and its dependencies (as Mocks) for testing.
At line 32 changed 1 line.
package org.appfuse.webapp.service;
package org.appfuse.service;
At line 34 changed 2 lines.
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.List;
import java.util.ArrayList;
At line 37 changed 1 line.
import org.appfuse.webapp.form.PersonForm;
import org.appfuse.dao.PersonDao;
import org.appfuse.model.Person;
import org.appfuse.service.impl.PersonManagerImpl;
At line 42 added 3 lines.
import org.jmock.Mock;
import org.springframework.orm.ObjectRetrievalFailureException;
At line 40 changed 1 line.
//~ Instance fields ========================================================
private final String personId = "1";
private PersonManager personManager = new PersonManagerImpl();
private Mock personDao = null;
private Person person = null;
At line 42 removed 12 lines.
private PersonManager mgr = null;
private Log log = LogFactory.getLog(PersonManagerTest.class);
private PersonForm personForm;
//~ Constructors ===========================================================
public PersonManagerTest(String name) {
super(name);
}
//~ Methods ================================================================
At line 56 changed 1 line.
mgr = new PersonManagerImpl(conn);
personDao = new Mock(PersonDao.class);
personManager.setPersonDao((PersonDao) personDao.proxy());
At line 61 changed 1 line.
mgr = null;
personManager = null;
At line 63 removed 4 lines.
public static void main(String[] args) {
junit.textui.TestRunner.run(PersonManagerTest.class);
}
At line 70 changed 1 line.
Now that we have the JUnit framework down for this class, let's add the meat: the test methods to make sure everything works in our Manager. Here's a snippet from the [DAO Tutorial|CreateDAO] tutorial to help you understand what we're about to do.
Now that you have the skeleton done for this class, you need to add the meat: the test methods to make sure everything works. Here's a snippet from the [DAO Tutorial|CreateDAO] tutorial to help you understand what we're about to do.
At line 79 changed 8 lines.
personForm = (PersonForm) mgr.getPerson("1");
if (log.isDebugEnabled()) {
log.debug(personForm);
}
assertTrue(personForm != null);
assertTrue(personForm.getFirstName() != null);
// set expected behavior on dao
personDao.expects(once()).method("getPerson")
.will(returnValue(new Person()));
person = personManager.getPerson(personId);
assertTrue(person != null);
personDao.verify();
At line 90 changed 2 lines.
personForm = (PersonForm) mgr.getPerson("1");
personForm.setFirstName("Joe");
// set expected behavior on dao
personDao.expects(once()).method("savePerson")
.with(same(person)).isVoid();
At line 93 changed 3 lines.
if (log.isDebugEnabled()) {
log.debug("saving person with updated firstName: " + personForm);
}
personManager.savePerson(person);
personDao.verify();
}
At line 97 removed 4 lines.
personForm = (PersonForm) mgr.savePerson(personForm);
assertTrue(personForm.getFirstName().equals("Joe"));
}
At line 102 changed 1 line.
personForm = new PersonForm();
person = new Person();
At line 104 changed 3 lines.
// call populate method in super class to populate test data
// from a properties file matching this class name
personForm = (PersonForm) populate(personForm);
// set required fields
person.setFirstName("firstName");
person.setLastName("lastName");
At line 108 changed 2 lines.
personForm = (PersonForm) mgr.savePerson(personForm);
assertTrue(personForm.getLastName().equals("Raible"));
// set expected behavior on dao
personDao.expects(once()).method("savePerson")
.with(same(person)).isVoid();
personManager.savePerson(person);
personDao.verify();
At line 111 changed 3 lines.
if (log.isDebugEnabled()) {
log.debug("removing person...");
}
// reset expectations
personDao.reset();
At line 115 changed 1 line.
mgr.removePerson(personForm);
personDao.expects(once()).method("removePerson").with(eq(new Long(personId)));
personManager.removePerson(personId);
personDao.verify();
At line 110 added 7 lines.
// reset expectations
personDao.reset();
// remove
Exception ex = new ObjectRetrievalFailureException(Person.class, person.getId());
personDao.expects(once()).method("removePerson").isVoid();
personDao.expects(once()).method("getPerson").will(throwException(ex));
personManager.removePerson(personId);
At line 118 changed 8 lines.
personForm = (PersonForm) mgr.getPerson("1");
fail("Expected 'Exception' not thrown");
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(e);
}
assertTrue(e != null);
personManager.getPerson(personId);
fail("Person with identifier '" + personId + "' found in database");
} catch (ObjectRetrievalFailureException e) {
assertNotNull(e.getMessage());
At line 123 added 1 line.
personDao.verify();
At line 130 changed 1 line.
This class won't compile at this point because we have not created our PersonManager nor the PersonManagerImpl. Unlike the DAO class, I'm not using a Factory pattern. Rather, I'm instantiating new Managers using:
This class won't compile at this point because we have not created our PersonManager interface.
At line 132 removed 14 lines.
[{Java2HtmlPlugin
Manager mgr = new ManagerImp(conn);
}]
If I followed recommended patterns a bit more, I'd do:
[{Java2HtmlPlugin
Manager mgr = ManagerFactory.getInstance(conn, PersonManager.class);
}]
I don't have any reason for ''not doing'' the factory pattern on Managers, I just simply haven't done it. I __am__ creating Interfaces for the Managers - in case I decide I need new ManagerImpls someday. Then it'd be easy to create a Factory and different implementations. Someday I hope to dig into <a href="http://www.springframework.org/">Spring</a> to see if it can be my Factory to determine Managers for clients (Tests and Actions).
At line 149 removed 1 line.
First off, create a PersonManager.java interface in the src/web/**/service directory and specify the basic CRUD methods for any implementation classes. ''I've eliminated the JavaDocs in the class below for display purposes.''
At line 133 added 2 lines.
First off, create a PersonManager.java interface in the src/service/**/service directory and specify the basic CRUD methods for any implementation classes. ''I've eliminated the JavaDocs in the class below for display purposes.'' The ''setPersonDao()'' method is not used in most cases - its just exists so the PersonManagerTest can set the DAO on the interface.
At line 155 changed 1 line.
package org.appfuse.webapp.service;
package org.appfuse.service;
At line 157 changed 1 line.
public interface PersonManager {
import org.appfuse.model.Person;
import org.appfuse.dao.PersonDao;
At line 159 changed 5 lines.
public Object getPerson(String id) throws Exception;
public Object savePerson(Object person) throws Exception;
public void removePerson(Object Person) throws Exception;
public interface PersonManager {
public void setPersonDao(PersonDao dao);
public Person getPerson(String id);
public void savePerson(Person person);
public void removePerson(String id);
At line 167 changed 2 lines.
Now let's create a PersonManagerImpl class that implements the methods in PersonManager and uses [BeanUtils.copyProperties|http://jakarta.apache.org/commons/beanutils/api/org/apache/commons/beanutils/BeanUtils.html#copyProperties(java.lang.Object,%20java.lang.Object)]
to convert POJOs &rarr; ActionForms and ActionForms &rarr; POJOs. To do this, create a new class in src/web/**/service and name it PersonManagerImpl.java. It should extend BaseManager and implement PersonManager.
Now let's create a PersonManagerImpl class that implements the methods in PersonManager. To do this, create a new class in src/service/**/service/impl and name it PersonManagerImpl.java. It should extend BaseManager and implement PersonManager.
At line 170 removed 2 lines.
;:''The [BaseManager|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/webapp/service/BaseManager.java.html] is for registering different Converters (i.e. [DateConverter|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/common/util/DateConverter.java.html]) so that BeanUtils.copyProperties knows how to convert Strings &rarr; Objects. It currently does not have any convenience methods, but does provide a nice place to add them for all your managers.''
At line 174 changed 1 line.
package org.appfuse.webapp.service;
package org.appfuse.service.impl;
At line 176 changed 4 lines.
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.appfuse.model.Person;
import org.appfuse.dao.PersonDao;
import org.appfuse.service.PersonManager;
At line 181 removed 5 lines.
import org.appfuse.persistence.DAOFactory;
import org.appfuse.persistence.Person;
import org.appfuse.persistence.PersonDao;
import org.appfuse.webapp.form.PersonForm;
At line 187 removed 3 lines.
//~ Instance fields ========================================================
private Log log = LogFactory.getLog(PersonManagerImpl.class);
At line 191 removed 2 lines.
private Person person;
private PersonForm personForm;
At line 194 changed 5 lines.
//~ Constructors ===========================================================
public PersonManagerImpl(Object conn)
throws Exception {
dao = (PersonDao) DAOFactory.getInstance(conn, PersonDao.class);
public void setPersonDao(PersonDao dao) {
this.dao = dao;
At line 201 changed 9 lines.
//~ Methods ================================================================
public Object getPerson(String id) throws Exception {
person = dao.getPerson(Long.valueOf(id));
personForm = new PersonForm();
BeanUtils.copyProperties(personForm, person);
return personForm;
public Person getPerson(String id) {
return dao.getPerson(Long.valueOf(id));
At line 212 changed 21 lines.
public Object savePerson(Object obj) throws Exception {
if (person == null) {
person = new Person();
}
personForm = (PersonForm) obj;
// copy form properties to person
try {
BeanUtils.copyProperties(person, personForm);
} catch (IllegalArgumentException i) {
log.error("Exception occured copying properties", i);
throw new ConversionException();
}
// BeanUtils.copyProperties converts empty Strings to
// Longs with a value of 0 to prevent a NPE.
// Setting the defaultLong to null (in BaseManager) is another solution
if (ObjectUtils.equals(person.getId(), new Long(0))) {
person.setId(null);
}
public void savePerson(Person person) {
At line 234 removed 3 lines.
return getPerson(person.getId().toString());
At line 239 changed 12 lines.
public void removePerson(Object obj) throws Exception {
if (person == null) {
person = new Person();
}
personForm = (PersonForm) obj;
if (log.isDebugEnabled()) {
log.debug("removing person: " +
personForm.getFirstName() + " " +
personForm.getLastName());
}
dao.removePerson(person);
public void removePerson(String id) {
dao.removePerson(Long.valueOf(id));
At line 255 changed 1 line.
You should be able to compile everything now using "ant compile-web"...
One thing to note is the {{setPersonDao()}} method. This is used by Spring to bind the PersonDao to this Manager. This is configured in the applicationContext-service.xml file. We'll get to configuring that in Step 3[3]. You should be able to compile everything now using "ant compile-service".
At line 257 changed 8 lines.
__Doh!__ I guess not:
{{{
PersonManagerImpl.java:11: cannot resolve symbol
[javac] symbol : class PersonForm
[javac] location: package form
[javac] import org.appfuse.webapp.form.PersonForm;
}}}
We need to add XDoclet tags to the Person.java Object to create our Struts ActionForm. In the JavaDoc for the Person.java file, add the following @struts.form tags (use User.java if you need an example):
Now you need to edit Spring's config file for our services layer so it will know about this new Manager.
At line 187 added 4 lines.
!!Configure Spring for this Manager and Transactions [#3]
To notify Spring of this our PersonManager interface and its implementation, open the src/service/**/service/applicationContext-service.xml file. Add the following to the bottom of this file.
At line 268 changed 1 line.
* @struts.form include-all="true" extends="BaseForm"
<bean id="personManager" class="org.appfuse.service.impl.PersonManagerImpl">
<property name="personDao" ref="personDao"/>
</bean>
At line 271 changed 1 line.
;:''We extend org.appfuse.webapp.form.BaseForm because it has a toString() method that allows us to call log.debug(formName) to print out a reader-friendly view of the Form object.''
This bean must have a name that ends in "Manager". This is because there is AOP advice applied at the top of this file for all *Manager beans.
{{{<aop:advisor id="managerTx" advice-ref="txAdvice" pointcut="execution(* *..service.*Manager.*(..))" order="2"/>}}} For more information on transactions with Spring, see [Spring's documentation|http://www.springframework.org/docs/reference/transaction.html].
At line 273 changed 1 line.
Now, running "ant compile-web" should work just fine.
!!Run the ManagerTest [#4]
At line 275 changed 1 line.
Finally, we need to create the PersonManagerTest.properties file in test/web/**/service so that {{personForm = (PersonForm) populate(personForm);}} will work in our test.
Save all your edited files and try running __ant test-service -Dtestcase=PersonManager__.
At line 277 changed 11 lines.
;:''Duplicating (and renaming) the PersonDaoTest.properties is the easy route. Alternatively, you could set the properties manually. Make sure and add an __id__ property.''
{{{
id=1
firstName=Matt
lastName=Raible
}}}
!!Run the ManagerTest [#3]
Save all your edited files and try running "ant test-web -Dtestcase=PersonManager" one more time.
__Yeah Baby, Yeah:__
''Yeah Baby, Yeah:''
At line 289 changed 1 line.
Total time: 13 seconds%%
Total time: 9 seconds%%
At line 291 removed 2 lines.
;:''You'll notice a nice long StackTrace for an ObjectNotFound error - caused by the last part of the "testAddAndRemovePerson" method in PersonManagerTest. You can remove it by removing the e.printStackTrace() in BaseDaoHibernate.retrieveObject(Session ses, Class clazz, Long id).''
At line 211 added 2 lines.
The files that were modified and added to this point are [available for download|https://appfuse.dev.java.net/files/documents/1397/7484/appfuse-tutorial-managers-1.6.zip].

Back to CreateManager, or to the Page History.