CreateManager |
|
Your trail: |
This is version 55.
It is not the current version, and thus it cannot be edited.
[Back to current version]
[Restore this version]
Part II: Creating new Managers - A HowTo for creating Business Delegates that talk to the database tier (DAOs) and the web tier (Struts Actions).
- This tutorial depends on Part I: Creating new DAOs and Objects in AppFuse.
About this Tutorial
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.
In the context of AppFuse, this is called a Manager class. It's main responsibility to act as a bridge between the persistence (DAO) layer and the
web layer. The Business Delegate pattern from Sun says that these objects are 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.
- I will tell you how I do stuff in the Real World in text like this.
Let's get started by creating a new ManagerTest and Manager in AppFuse's architecture.
Table of Contents
- Create a new ManagerTest to run JUnit tests on the Manager
- Create a new Manager to talk to the DAO
- Configure Spring for this Manager and Transactions
- Run the ManagerTest
Create a new ManagerTest to run JUnit tests on the Manager
In Part I, 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.
- This may seem redundant (why all the tests!), but these tests are GREAT to have 6 months down the road.
This class should extend BaseManagerTestCase, 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, as well as to initialize Spring's ApplicationContext.
- I usually copy (open → save as) an existing test (i.e. UserManagerTest.java) and find/replace [Uu]ser with [Pp]erson, or whatever the name of my object is.
The code below is what we need for a basic JUnit test of our Managers. It created and destroys our PersonManager. The "ctx" object is initialized in the BaseManagerTestCase class.
package org.appfuse.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.appfuse.model.Person;
public class PersonManagerTest extends BaseManagerTestCase {
//~ Static fields/initializers =============================================
private Person person;
//~ Instance fields ========================================================
private PersonManager mgr = null;
private Log log = LogFactory.getLog(PersonManagerTest.class);
//~ Methods ================================================================
protected void setUp() throws Exception {
mgr = (PersonManager) ctx.getBean("personManager");
}
protected void tearDown() throws Exception {
mgr = null;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(PersonManagerTest.class);
}
}
|
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 tutorial to help you understand what we're about to do.
- ...we create methods that begin with "test" (all lower case). As long as these methods are public, have a void return type and take no arguments, they will be called by our <junit> task in our Ant build.xml file. Here's some simple tests for testing CRUD. An important thing to remember is that each method (also known as a test), should be autonomous.
Add the following methods to your PersonManagerTest.java file:
public void testGetPerson() throws Exception {
person = (Person) mgr.getPerson("1");
assertTrue("person.firstName not null",
person.getFirstName() != null);
}
public void testSavePerson() throws Exception {
person = (Person) mgr.getPerson("1");
String name = person.getFirstName();
person.setFirstName("test");
person = (Person) mgr.savePerson(person);
assertTrue("name updated", person.getFirstName().equals("test"));
person.setFirstName(name);
mgr.savePerson(person);
}
public void testAddAndRemovePerson() throws Exception {
person = new Person();
person = (Person) populate(person);
person = (Person) mgr.savePerson(person);
assertTrue(person.getFirstName().equals("Bill"));
assertTrue(person.getId() != null);
if (log.isDebugEnabled()) {
log.debug("removing person, personId: " +
person.getId());
}
mgr.removePerson(person.getId().toString());
assertNull(mgr.getPerson(person.getId().toString()));
}
|
This class won't compile at this point because we have not created our PersonManager interface.
- I think it's funny how I've followed so many patterns to allow extendibility in AppFuse. In reality, on most projects I've been on - I learn so much in a year that I don't want to extend the architecture - I want to rewrite it. Hopefully by keeping AppFuse up to date with my perceived best practices, this won't happen as much. Each year will just be an upgrade to the latest AppFuse, rather than a re-write. ;-)
Create a new Manager to talk to the DAO
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.
- As usual, I usually duplicate (open → save as) an existing file (i.e. UserManager.java).
package org.appfuse.service;
public interface PersonManager {
public Object getPerson(String id) throws Exception;
public Object savePerson(Object person) throws Exception;
public void removePerson(String id) throws Exception;
}
|
Now let's create a PersonManagerImpl class that implements the methods in PersonManager. To do this, create a new class in src/service/**/service and name it PersonManagerImpl.java. It should extend BaseManager and implement PersonManager.
package org.appfuse.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.appfuse.model.Person;
import org.appfuse.persistence.PersonDao;
public class PersonManagerImpl extends BaseManager implements PersonManager {
private static Log log = LogFactory.getLog(PersonManagerImpl.class);
private PersonDao dao;
public void setPersonDao(PersonDao dao) {
this.dao = dao;
}
public Object getPerson(String id) throws Exception {
return dao.getPerson(Long.valueOf(id));
}
public Object savePerson(Object obj) throws Exception {
Person person = (Person) obj;
dao.savePerson(person);
return person;
}
public void removePerson(String id) throws Exception {
dao.removePerson(Long.valueOf(id));
}
}
|
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.
You should be able to compile everything now using "ant compile-service"...
Finally, we need to create the PersonManagerTest.properties file in test/service/**/service so that personForm = (PersonForm) populate(personForm); will work in our test.
- Duplicating (and renaming) the PersonDaoTest.properties is the easy route. Alternatively, you could set the properties manually.
firstName=Bill
lastName=Joy
Now we need to edit Spring's config file for our services layer so it will know about this new Manager.
To notify Spring of this our PersonManager interface and it's implementation, open the src/service/**/service/applicationContext-service.xml file. In here, you will see an existing configuration for the UserManager. You should be able to copy that and change a few things to get the XML fragment below. Add the following to the bottom of this file.
<!-- Person Manager -->
<!-- Person Manager -->
<bean id="personManagerTarget" class="org.appfuse.service.PersonManagerImpl" singleton="false">
<property name="personDao"><ref bean="personDAO"/></property>
</bean>
<!-- Transaction declarations for business services. To apply a generic transaction proxy to
all managers, you might look into using the BeanNameAutoProxyCreator -->
<bean id="personManager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager"><ref bean="transactionManager"/></property>
<property name="target"><ref local="personManagerTarget"/></property>
<property name="transactionAttributeSource"><ref local="defaultTxAttributes"/></property>
</bean>
|
Note: I had SAX throw an error because defaultTxAttributes was not defined so I replaced the transactionAttributeSource with this instead, which allowed my unit test to run successfully.
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
|
Run the ManagerTest
Save all your edited files and try running "ant test-service -Dtestcase=PersonManager" one more time.
Yeah Baby, Yeah:
BUILD SUCCESSFUL
Total time: 9 seconds
Next Up: Part III: Creating Actions and JSPs - A HowTo for creating Actions and JSPs in the AppFuse architecture.
|