How EJB home implements the Factory Method pattern
Written by Chintan Rajyaguru
Saturday, 28 March 2009 06:07
We had an
interesting discussion at work about design patterns and EJB Home
interface was used as an example of the Factory Method pattern as
defined in the GoF book. I have heard this before. Upon googling, I
found more places where EJB Home interface is used as the example of
the Factory Method pattern. See here,
here
and here.
The factory method
UML diagram is shown below.
The explanation
typically given is, "home interface provides methods to create bean
instances" or "EJB home interface, which creates new EJBObjects"
or "XxxHome creates instances of Xxx and YyyHome creates instances
of Yyy." This is incomplete and even inaccurate explanation of the
Factory Method pattern.
To make my point, I
turn to the design pattern bible - the GoF book. The book clearly
says, "Use the Factory Method pattern when, a
class wants its subclasses to specify the objects it creates."
It is easy to think that in case of EJB Home, javax.ejb.EJBHome wants
its subclass (say) AccountHome to specify the objects (say)
AccountRemote it creates.
So far so good.
However, as shown in the figure above, the factory method is defined
by the abstract super class or interface and implemented by the
subclass. In case of EJBHome, it does NOT define any create methods
for its subclasses to implement. See for yourself here.
Create method is a 'special' method defined by the J2EE specification
as a means to return an implementation of the business interface.
There is also
another issue.
The figure above
shows multiple subclasses that provide factory methods. They all
create objects of type Figure (LineFigure or TextFigure). When you
apply this concept to EJBHome interface, multiple subclasses such as
AccountHome and OrderHome do NOT create objects of the same super
type. AccountHome creates AccountRemote and OrderHome creates
OrderRemote. These business interfaces don't implement the same
contract.
The correct explanation
With
EJB home interfaces, factory method is used when the 'container'
implements the interface.
When
you define the AccountHome interface, you don't know how to create
the objects that implement Account business interface. So, you leave
it up to the subclass or the implementation of your interface to
decide how to create those objects. You define a factory method and
let the implementation provide the method. When you deploy your bean
in a 'different container,' you may have Container2AccountHome that
implements the factory method create () and creates Container2Account
classes when invoked by the client. In yet another container, you may
have Container3AccountHome and so on.
In
case of the home interface example of the Factory Method Pattern, you
will NOT have a situation shown in the second figure (Figure and
Manipulator classes) above.
I fell in love with WebSphere mediations the first time I saw them. Okay, didn't fall in love but I did think... "Nice! What a cool way of going above and beyond what soap handlers offer!" For those who don't know, WebSphere mediations run in WAS runtime messaging engine, which treats any request or response flowing through as a message (could be a soap or jms message or even a request to an ejb) and any message consumer as a destination. Since we are [over] simplifying already, in simple terms WebSphere mediations are components that can intercept these messages, inspect them, route them to a different location or even change them.
Now, I wouldn't be writing this blog if everything about WebSphere mediations was so cool (yeah, I know, I have love hate relationship with IBM products!). Just note that the discussion in this blog entry refers to mediations available within WebSphere Application Server.
First of all, did you notice I call them WebSphere mediations? You won't see that term being used on any IBM website. I use that term because they use WebSphere specific APIs. You have to implement com.ibm.websphere.sib.mediation.handler.MediationHandler interface to create a mediation. This makes your code... well, not so portable. Mediations - woops, sorry - WebSphere mediations are very much like soap handlers. They can intercept the incoming requests and/or response and do things with it. There should have been some effort to make them part of the specification. I mean the whole concept of messaging engine is cool, even that should be part of the specification. The term 'messaging engine' doesn't refer to JMS messaging engine. It refers to the messaging infrastructure on which WAS runtime and service integration BUS are built.
Second, they only support one method public boolean handle (javax.xml.rpc.handler.MessageContext context) method. Why can't they support both handleRequest and handleResponse like soap handlers do? Being able to handle response would be really convenient. For example, if I had a requirements to process an incoming message and forward it to a queue for further processing ONLY IF the initial processing was successful, I would catch the response message in the handleResponse method and then send the message for further processing. Without the ability to capture responses, you have to be little bit creative to implement this requirement (you can still do it though).
Third, they use SDO APIs. This is not a problem in itself but I don't like IBM's implementation of this API. Just try creating a soap header within mediation if no header exists already and you will know what I am talking about. In plain English, I find IBM's implementation of SDO very 'read' friendly as opposed to 'read and manipulate' friendly. It is not easy to create/add new elements.
Forth, they can't be developed. Seriously! You cannot create mediations in RAD 7.0 - not even after installing some fixpacks. Now, I know this is not a problem with the mediations themselves, it's a problem with the tooling but hey I am in the mood to rant. To develop a mediation, you create an ejb project, create a class [say] MyMediation and implement the interface, go to ejb deployment descriptor and click Add button in Mediation Handlers tab. A dialog box should pop up and the class you created should show up in it. You select the class and the necessary ejb code is generated automatically. In RAD 7, nothing happens if you click the Add button. When I used Application Server Toolkit at my last client, the dialog box popped up but my class never showed up in it. I had to create mediation project in RAD 6 (yes, it works in the previous version!) and then open it in RAD 7. Nice way to take away some functionality!
Fifth, you can't register your service in the SDO repository - something you have to do when you have an outbound service that you want to mediate using mediation. I have blogged about this in detail in this and this blog entries.
Sixth, you can customize the behavior of your mediations using mediation properties - that's a good thing. But, you have to define and change these properties using admin console. This is not flexible, and boring too if you have many properties to define. It requires a technical resource to make a change - doesn't sound like providing business agility to me.
I use a mind mapping tool called Freemind. It is available here. It's a great tool for capturing ideas. I like seeing all my ideas grouped together right in front of me and this tool (written in Java) makes it possible. It's easier than a creating and reading a list.
Anyway, I want to talk about its installation. I have always used this tool on windows and it always installed itself without any problems. You can download an exe file from here. But things aren't as easy on Linux (isn't that why most of the people still find windows easier to use?). Freemind requires several packages to be installed successfully on Linux. The easiest way to deal with these dependencies is to download Freemind freemind-0.8.0-6.noarch.rpm file from here. Become root using su command and install the file using rpm -ivh <file_name> command. It will fail with a message that looks like:
error: Failed dependencies: jakarta-commons-lang is needed by freemind-0.8.0-6.noarch relaxngDatatype is needed by freemind-0.8.0-6.noarch msv-xsdlib is needed by freemind-0.8.0-6.noarch jgoodies-forms is needed by freemind-0.8.0-6.noarch xml-commons-apis is needed by freemind-0.8.0-6.noarch ws-jaxme is needed by freemind-0.8.0-6.noarch jakarta-commons-codec is needed by freemind-0.8.0-6.noarch
Now, go to JPackage website. Download and install every missing package listed above and then try installing Freemind again. Do you have to go through the pain of installing all these packages when all you need is a simple mind mapping tool? Not really! In the past I have used kdissert at http://www.kde.org.uk/apps/kdissert/, which is relatively easy to install but I am used to Freemind so I will stick to it.
This entry is a follow up on using Apache Directory Server (Apache DS) and WAS 6.1 to implement security. If you haven't already, review Apache DS installation and configuration here and how to create users and groups here. In this entry, I will describe how to configure WAS 6.1 to use Apache DS and enable security.
Starting v6.1, WebSphere separates administrative security from application security. The term administrative security means you need username and password to administer the server. This includes getting server status, stopping the server (somehow it doesn't include starting the server, you can start the server without supplying username and password) and administer the server through admin console or through wsadmin scripts. The term application security means you can protect resources in your application (e.g. you can protect /profile url), assign application security roles to those protected resources and map users or groups from ldap to those roles. It is important to note that starting WebSphere 6.1, you can choose to enable only administrative security or only application security or both. In previous versions you were required to enable or disable both at the same time. For now, we will only enable administrative security, we will talk about application security in the future when we have a sample application. This assumes that
you have already created a WebSphere 6.1 profile with security disabled (if you want to know how to do that Send me an email)
Go to WAS admin console http://<host>:port/admin. For example, http://localhost:9060/admin
Click on Security > Secure administration, applications, and infrastructure
Select Standalone LDAP registry in Available realm definitions dropdown and click Configure
Enter the following values in the screen:
Primary administrative username: wasadmin (the admin user already created in ldap)
Select Server identity that is stored in the repository radio button (because we don't want WebSphere to generate an id for us)
Type of LDAP server: Custom (Apache DS is NOT one of the supported ldap servers)
Host: localhost
Port: 10389 (port on which Apache DS is listening)
Base distinguish name (DN): dc=example,dc=com (all our groups and users are under this base dn)
Bind distinguish name (DN): uid=wasadmin,ou=people,dc=example,dc=com (entry that uniquely identifies wasadmin user)
Bind password: <password for wasadmin user you used in when you created user in LDAP>
Leave default values for other options
Click Apply
Click Save directly to the master configuration link
Click Advanced Lightweight Directory Access Protocol (LDAP) user registry settings link under Additional Properties section
User filter: (&(uid=%v)(objectclass=inetOrgPerson))
Group filter: (&(cn=%v)(|(objectclass=groupOfNames)(objectclass=groupOfUniqueNames)))
User ID map: *:uid
Group ID map: groupOfNames:member;groupOfUniqueNames:uniqueMember
Click OK
Click Save directly to the master configuration link at the top of the page
Click OK and Save again
Click Security > Secure administration, applications, and infrastructure link on the left hand panel
Select Enable administrative security checkbox
Unselect Enable application security checkbox
Unselect Java 2 security checkbox
Select Standalone LDAP registry in Available realm definitions dropdown and click Set as current button
Click Apply button
Click Save directly to the master configuration link
We have enabled administrative security but the change will not take effect until we restart the server. Restart the server and go to admin console. Since security is enabled, you will be asked to accept a certificate and login using the WAS admin username and password you specified in ldap. From this point on, Apache DS must be running before you can administer the server.
Edit on Sunday Feb 18, 2007: Corrected the value of Bind distinguish name (DN): to read
Bind distinguish name (DN): uid=wasadmin,ou=people,dc=example,dc=com (entry that uniquely identifies wasadmin user)
Last time , we talked about installing and configuring Apache DS. Now, we will add users and groups to it. We need to create the following users: wasadmin: This is the WebSphere 6.1 administrator user. Once security is configured, we will log into WAS admin console using this user bob: This is a test application user. We will log into the 'security enabled' application using this test user
Users are typically placed in LDAP groups so that groups can be mapped to application roles as opposed to mapping individual users (users come and go, groups they belong to stay in the organization). We will create the following groups: admins: This group will hold all administrators. For now, we have only one administrator - wasadmin endusers: This group will hold all the application users. For now, we have only one end user - bob
Organizations typically organize their data in organizational units. A user could be part of multiple organizational units. For example, the user bob may be part of ou=HR as well as ou=people. We will create 2 organizational units: groups: This organizational unit will hold ALL the groups in Apache DS people: This organizational unit will hold ALL users. Both bob and wasadmin will be under this unit even though wasadmin is just a system user
As we will see shortly, a user may be part part of an organizational unit AND may belong to a group.
Creating groups and users
The high level steps to create users and groups are:
Create organizational units to hold users and groups
Create wasadmin user
Create application user
Create groups
To create the above items, you can specify all the information in a text file, commonly known as ldif file and load the file in the ldap server. Create a file called organizational_units.ldif and put the following content in it. If you are completely unfamiliar with LDAP concepts, this article may be a good start.
# An ldif file that creates people and groups organizational units dn: ou=people,dc=example,dc=com cn: people description: An organizational unit to store all people/users including system users objectClass: top objectClass: organizationalUnit
dn: ou=groups,dc=example,dc=com cn: groups description: An organizational unit to store all people/users including system users objectClass: top objectClass: organizationalUnit
In JXplorer, select LDIF > Import File, select this file and click Open. This will result in two new organizational units, ou=people and ou=groups under dc=example,dc=com.
We will put all users (including system users) in people ou and all groups in groups ou. Let's create users first. Create a file called users.ldif and put the following content in it.
dn: uid=wasadmin,ou=people,dc=example,dc=com cn: wasadmin cn: WebSphere Administrator cn: WAS administrator sn: wasadmin objectclass: top objectclass: person objectclass: organizationalPerson objectclass: inetOrgPerson uid: wasadmin userpassword: wasadmin
dn: uid=bob,ou=people,dc=example,dc=com cn: Bob sn: User objectclass: top objectclass: person objectclass: organizationalPerson objectclass: inetOrgPerson uid: bob userpassword: password
Importing the file above creates 2 users under ou=people,dc=example,dc=com. For example, the dn of the wasadmin users becomes, uid=wasadmin,ou=people,dc=example,dc=com. We will use this dn to login to WAS admin console after we enable administrative security.
To create groups, create a text file called groups.ldif and put the following content in it:
dn: cn=admins,ou=groups,dc=example,dc=com description: admins group, WebSphere administrator will be part of this group cn: Administrators group objectClass: top objectClass: groupOfNames member: uid=wasadmin,ou=people,dc=example,dc=com
dn: cn=endusers,ou=groups,dc=example,dc=com description: application users group cn: Users group objectClass: top objectClass: groupOfNames member: uid=bob,ou=people,dc=example,dc=com
Notice how both the groups use the member attribute and point to the dn of its members. This attribute is required because our groups use groupOfNames object class. Since the member attribute is required, we created users first and then the groups. At this point, your ldap settings in JXplorer should look like this:
That's it! We are now ready to enable security in WebSphere 6.1. I will describe that process in the next entry.
Apache DS and WAS 6.1: Installing and Configuring Apache DS
Written by Chintan Rajyaguru
Wednesday, 14 February 2007 14:57
I recently came across the problem of creating EJB based web services on WebSphere V6.1 with security enabled in the EJB layer. Since I also needed to support role based security, I decided to use a directory server to store users and simulate the real world scenario. This blog entry shares the installation and configuration of Apache Directory Server (Apache DS); I will describe WAS configuration to use Apache DS the next time.
Apache DS is a lightweight ldap server written in Java. You can think of it as an open source competitor to open ldap, IBM Tivoli Directory Server, SunOne Directory Server etc. We will install ApacheDS, make some configuration changes and use JXplorer to view/create entries in it.
Installation and setup
Installing Apache DS is easy, configuring it after installation is little tricky:
First of all, download apacheds-1.0.0-win32-setup.exe from here
Double click the exe and follow the screens. I will call the installation directory <ds_home>. For example, <ds_home> could mean C:\apacheds-1.0.0
At the end of the installation, run the configuration, which allows you to set logging behavior and server startup properties of the directory server. I accepted all the defaults, clicked Start button to start the server and clicked OK button to close configuration wizard
Installation of JXplorer is simple too. Download JXplorer from here, double click the exe and follow the screens accepting all the defaults. Out of the box, Apache DS comes with an administrative account with 'secret' as the password. We will change this password using JXplorer and by changing a configuration xml file.
Start JXplorer, click on File > Connect and enter the following values
Host: localhost, Port: 10389, Protocol: LDAP v3, Base DN: leave blank, Level: User + Password, User DN: 'uid=admin,ou=system' (without quotes), Password: secret
Expand System tree, select admin user and click on Table Editor tab on the right hand panel
Click the value column on userPassword field and a User Password Data dialog pops up
Change the password in the dialog and click OK. Remember this password, you will need it in the future!
Click Submit button
Disconnect from Apache DS in JXplorer using File > Disconnect
Stop Apache DS using Service Settings menu option in the Start menu of windows
Change the value of java.naming.security.credentials property in <apache_ds>\conf\server.xml to the new password you entered in JXplorer (yes the password is stored as clear text in Apache DS; this will change in a future version though)
Save the file and start Apache DS
Use JXplorer to login with new password and make sure it works
A quick LDAP and Apache DS primer
While the discussion of ldap concepts is NOT the intent of this article, here is a quick primer so that the discussion that follows will make more sense. Information is can be organized in ldap primarily using 2 styles: geographic and domain-based. Geographic style, typically used by multinational organizations, have information organized in trees that look like c=us,o=ibm etc. where c stands for country and o stands for organization. Domain based trees contain entries that look like dc=com,dc=ibm etc. where dc stands for domain component.
Once you have decided on a style, you can put your data under the tree. For example, an organization may divide its people in organizational units (represented as ou in LDAP). In that case, you will create hierarchy of ou entries. For example, ou=HR and under ou=HR, ou=benefits, ou=recruiting.
Start JXplorer to make more sense of the information in this paragraph. Apache DS comes with ou=system, which stores the admin user for Apache DS. This is why we logged in with uid=admin,ou=system in JXplorer. Under ou=system, there are two organizational units: ou=groups and ou=users. You would put users as in bob, mike etc. under ou=users and you would create groups as in admins, users etc. under ou=groups.
The term Access Control refers to the configuration that allows an ldap user access to a limited view of the entire tree (admin user has access to the entire tree). By default, access control is off in Apache DS, so a user (e.g. bob) created somewhere in the tree, will be able to see all other users in the tree. The term 'see all other users' means when bob logs in, he will see other users in the tree and make changes to them even though bob is not admin. This can be prevented by configuring access control in Apache DS OR by putting bob in ou=users and bob's group in ou=groups. In Apache DS, ou=users and ou=groups have special meanings. Users and groups created under those organizational units will NOT have access to other users in the tree even if access control is off and not configured.
Why is this discussion important to us? We are going to create a WebSphere administrator in ldap and we are going to map J2EE application roles to ldap groups in WAS admin console. This is possible ONLY IF, the WebSphere admin user is able to search and view other users in the tree. To do this without configuring access control (and hence make our lives simpler), we will create ALL users and groups outside ou=users and ou=groups. Apache DS comes with dc=example,dc=com base dn entry. We will create our users and groups under this base dn. If you want to use something other than 'example' as a domain component (e.g. dc=yourorg, dc=com), replace ALL occurrences of example by yourorg in server.xml file.
Next time, we will add organizational units, users and groups to Apache DS.