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 3 added 2 lines. |
;:''This tutorial depends on __Part I:__ [Creating new DAOs and Objects in AppFuse|CreateDAO].'' |
|
At line 4 changed 1 line. |
This tutorial will show you how to create a Business Delegate class (and a JUnit) to talk to the [DAO we created in Part I|CreateDAO] of this tutorial. |
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 6 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 10 changed 1 line. |
Let's get started on creating a new ManagerTest and Manager in AppFuse's architecture. |
Let's get started by creating a new ManagerTest and Manager in AppFuse's architecture. |
At line 15 changed 1 line. |
* [3] Run the ManagerTest |
* [3] Configure Spring for this Manager and Transactions |
* [4] Run the ManagerTest |
At line 18 changed 1 line. |
Since we're continuing from [Part I|CreateDAO], 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. 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|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. |
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 20 changed 1 line. |
;:%%(color: blue)''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.''%% |
;:''This may seem redundant (why all the tests!), but these tests are GREAT to have 6 months down the road.'' |
At line 22 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. |
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 24 changed 2 lines. |
{{{ |
package org.appfuse.webapp.service; |
;:%%(color: blue)''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.''%% |
At line 27 changed 2 lines. |
import org.apache.commons.logging.Log; |
import org.apache.commons.logging.LogFactory; |
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 30 changed 1 line. |
import org.appfuse.webapp.form.PersonForm; |
[{Java2HtmlPlugin |
At line 32 changed 2 lines. |
public class PersonManagerTest extends BaseManagerTestCase { |
//~ Instance fields ======================================================== |
package org.appfuse.service; |
At line 35 changed 3 lines. |
private PersonManager mgr = null; |
private Log log = LogFactory.getLog(PersonManagerTest.class); |
private PersonForm personForm; |
import java.util.List; |
import java.util.ArrayList; |
At line 39 changed 1 line. |
//~ Constructors =========================================================== |
import org.appfuse.dao.PersonDao; |
import org.appfuse.model.Person; |
import org.appfuse.service.impl.PersonManagerImpl; |
At line 41 changed 3 lines. |
public PersonManagerTest(String name) { |
super(name); |
} |
import org.jmock.Mock; |
import org.springframework.orm.ObjectRetrievalFailureException; |
At line 45 changed 1 line. |
//~ Methods ================================================================ |
public class PersonManagerTest extends BaseManagerTestCase { |
private final String personId = "1"; |
private PersonManager personManager = new PersonManagerImpl(); |
private Mock personDao = null; |
private Person person = null; |
At line 49 changed 1 line. |
mgr = new PersonManagerImpl(conn); |
personDao = new Mock(PersonDao.class); |
personManager.setPersonDao((PersonDao) personDao.proxy()); |
At line 54 changed 1 line. |
mgr = null; |
personManager = null; |
At line 56 removed 4 lines. |
|
public static void main(String[] args) { |
junit.textui.TestRunner.run(PersonManagerTest.class); |
} |
At line 61 changed 2 lines. |
}}} |
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. |
}] |
At line 64 added 2 lines. |
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 67 removed 3 lines. |
{{{ |
public void testGetPerson() throws Exception { |
personForm = (PersonForm) mgr.getPerson("1"); |
At line 71 changed 3 lines. |
if (log.isDebugEnabled()) { |
log.debug(personForm); |
} |
[{Java2HtmlPlugin |
At line 75 changed 2 lines. |
assertTrue(personForm != null); |
assertTrue(personForm.getRoles().size() == 1); |
public void testGetPerson() throws Exception { |
// 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 80 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 83 changed 3 lines. |
if (log.isDebugEnabled()) { |
log.debug("saving person with updated firstName: " + personForm); |
} |
personManager.savePerson(person); |
personDao.verify(); |
} |
At line 87 removed 4 lines. |
personForm = (PersonForm) mgr.savePerson(personForm); |
assertTrue(personForm.getFirstName().equals("Joe")); |
} |
|
At line 92 changed 1 line. |
personForm = new PersonForm(); |
person = new Person(); |
At line 94 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 98 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 101 changed 3 lines. |
if (log.isDebugEnabled()) { |
log.debug("removing person..."); |
} |
// reset expectations |
personDao.reset(); |
At line 105 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 108 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 118 changed 10 lines. |
}}} |
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: |
{{{ |
Manager mgr = new ManagerImp(conn); |
}}} |
If I followed recommended patterns a bit more, I'd do: |
{{{ |
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. |
}] |
At line 129 changed 1 line. |
;:%%(color: blue)''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 muhc. Each year will just be an upgrade to the latest AppFuse, rather than a re-write. ;-)'' |
This class won't compile at this point because we have not created our PersonManager interface. |
At line 129 added 2 lines. |
;:%%(color: blue)''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. ;-)'' |
|
At line 132 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 134 changed 1 line. |
;:%%(color: blue)''As usual, I usually duplicate (open → save as) an existing file (i.e. UserManager.java).'' |
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 136 changed 1 line. |
package org.appfuse.webapp.service; |
;:%%(color: blue)''As usual, I usually duplicate (open → save as) an existing file (i.e. UserManager.java).''%% |
At line 137 added 7 lines. |
[{Java2HtmlPlugin |
|
package org.appfuse.service; |
|
import org.appfuse.model.Person; |
import org.appfuse.dao.PersonDao; |
|
At line 145 added 6 lines. |
public void setPersonDao(PersonDao dao); |
public Person getPerson(String id); |
public void savePerson(Person person); |
public void removePerson(String id); |
} |
}] |
At line 140 changed 1 line. |
public Object getPerson(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/impl and name it PersonManagerImpl.java. It should extend BaseManager and implement PersonManager. |
At line 142 changed 1 line. |
public Object savePerson(Object person) throws Exception; |
[{Java2HtmlPlugin |
At line 144 changed 1 line. |
public void removePerson(Object Person) throws Exception; |
package org.appfuse.service.impl; |
|
import org.appfuse.model.Person; |
import org.appfuse.dao.PersonDao; |
import org.appfuse.service.PersonManager; |
|
public class PersonManagerImpl extends BaseManager implements PersonManager { |
private PersonDao dao; |
|
public void setPersonDao(PersonDao dao) { |
this.dao = dao; |
} |
|
public Person getPerson(String id) { |
return dao.getPerson(Long.valueOf(id)); |
} |
|
public void savePerson(Person person) { |
dao.savePerson(person); |
} |
|
public void removePerson(String id) { |
dao.removePerson(Long.valueOf(id)); |
} |
At line 146 changed 1 line. |
}}} |
}] |
At line 148 changed 1 line. |
!!Run the ManagerTest [#3] |
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". |
|
Now you need to edit Spring's config file for our services layer so it will know about this new Manager. |
|
!!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. |
|
[{Java2HtmlPlugin |
|
<bean id="personManager" class="org.appfuse.service.impl.PersonManagerImpl"> |
<property name="personDao" ref="personDao"/> |
</bean> |
}] |
|
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]. |
|
!!Run the ManagerTest [#4] |
|
Save all your edited files and try running __ant test-service -Dtestcase=PersonManager__. |
|
''Yeah Baby, Yeah:'' |
%%(color:green)BUILD SUCCESSFUL\\ |
Total time: 9 seconds%% |
|
---- |
|
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]. |
|
''Next Up:'' __Part III:__ [Creating Actions and JSPs|CreateActions] - A HowTo for creating Actions and JSPs in the AppFuse architecture. |