Showing posts with label ADF. Show all posts
Showing posts with label ADF. Show all posts

Thursday, August 23, 2007

White Paper Business Rules in ADF Business Components Revamped!

Finally, the white paper Business Rules in ADF Business Components has been revamped!

As usual it took much more work than anticipated, especially as I made the 'mistake' to ask two subject experts (Steve Muench and Sandra Muller from the JHeadstart Team) to review the first draft. If I had not done that, the paper could have been published a month ago! But no, I could not help myself, I had to be thorough, I had to be me, and of course they provided me with insights that have had a significant impact on its contents. But all for the better, otherwise some of it already would have been obsolete the minute it hit the street.

"So what?", those of you who have not seen it before, might ask yourself. Well let me try to explain without copying too much of what already is explained in the paper itself.

First of all it is our (Oracle Consulting's) experience that analyzing, and implementing business rules takes a significant part of the total effort of creating the average application. Although being a very productive persistence framework as it is, this still holds true for ADF Business Components (which is part of Oracle's ADF), or ADF BC for short. Moreover, despite all our efforts trying to create the ultimate application, most resources still are being put in maintenance rather than in creating the original. So there is a lot to be gained for business rules in this regard, and that is what the white paper intends to address.

Does the paper present 'the right way' for ADF BC? Well, perhaps there is a better way, I don't know. But it is a good way, as it is consistent and makes use of the best that ADF BC has to offer. And because it is consistent (and well documented) maintenance also becomes easier, as when the developers that created the original application used it (and then ran away like lightning to build the next hip thing), they will not have left behind a maintenance nightmare. At least not what the business rules are concerned.

"So, what's new?", those of you who have sleep with the previous version of the paper under their pillow, might ask yourself.

Let me give you this short list and for the rest of it refer you to the paper itself:
  • Capturing business rules using UML class model
    Why? Because plenty of people still want to capture requirements (including business rules) before there are tables and entity objects and therefore cannot make use of an ADF Business Components diagram (see also the article UML Rules! I posted some time ago).
  • Setting up framework extension classes
    Doing so makes introducing generic functionality later on so much easier and therefore is strongly advised in general.
  • Deprecated custom authorization in ADF BC
    This in particular concerns the horizontal authorization rules (restricting the set of rows of an entity you are allowed to insert, update or delete). The reason to do so is that you probably rather use Virtual Private Database for that.
  • 'Other Attribute Rules' dropped
    As I discussed in the article How to Pimp ADF BC Exception Handling, there are no compelling arguments anymore for not using built-in validators or method validators, making that the category Other Attributes Rules could be dropped, and we now suggest implementing them using these validators.
  • New built-in attribute validators
    ADF BC provides the Length, and Regular Expression validators for attributes.
  • 'Other Instance Rules' dropped, 'Delete Rules' added
    The category Other Instance Rules is dropped for the same reason the Other Attribute Rules category has been dropped. This with the exception of rules that make use of the delete() method, which rules are now in the new category 'Delete Rules'.
  • Registered Rules
    Using Registered Rules you can create generic method validators you can use for multiple entities. An example is a reoccurring validation of an end date that must be on or after a begin date.
  • UniqueKey Validator
    Compared with just checking 'Primary Key' for all primary key attributes, this one and only entity-level built-in validator helps to make validation of the primary key predictable and consistent, and also supports providing a user-friendlier error message.
  • 'Change History' and 'Cascade Delete' added
    These two categories are subcategories of Change Event Rules with DML. When using JAAS/JAZN ADF BC offers built-in support for recording date/user created/updated information, which has been documented in the Change History category. As a result of introducing this category, the 'Derivation' category has been renamed to 'Other Derivation'. Furthermore, ADF BC also supports Cascade Delete by defining an association as being a 'composition'.
  • Sending an email using JavaMail API
    The previous version of the paper here and there referred to some 'clex' library which was part of the now long-gone Oracle9iAS MVC Framework for J2EE. If you remember that you really are an Oracle veteran! Anyway, the classical example of a 'Change Event Rule without DML' is sending an email when somebody changes something in the database, which example now is based on the JavaMail API
  • Message handling
    Especially this subject has been revised significantly. Among other things you can specify error message together with the validator, which message will end up in an entity-specific message bundle. By creating custom exceptions you also can use one single message bundle, as I explained in the article How to Pimp ADF BC Exception Handling.
Do you need more in order to get you to download the new white paper? I can hardly imagine.

Friday, August 03, 2007

How to Pimp ADF BC Exception Handling

When you have been doing things in a particular way for a long time, you sometimes find that in the mean time your way has become the slow way. Not necessarily the wrong way as it works (otherwise you would not have kept doing it all the time, would you?), but you're just not fashionable anymore. Like wearing tight pants in the 60's or wide pants in the 80's. Or using vi instead of a state-of-the-art IDE like JDeveloper or Eclipse for that matter (oh yes, I dare!).

I recently discovered that I became unfashionable by using the setAttributeXXX() and validateEntity() method for implementing business rules in ADF BC instead of using Validators. Not that I didn't know of Validators, I just thought that they would not give me proper control over exception and message handling. Because one of the things I would like to have, is one single message bundle in which I could use a consistent coding of my messages, like APP-00001, APP-00002, etc. Even more important, the other thing I would like to have is that I can translate all messages to Kalaallisut the minute I need to make my application available for the Inuit people of Greenland.

As you might know, up till JDeveloper 10.1.3 ADF BC will create an entity-specific message bundle to store the messages you provide with Validators. So with many entity objects big chance you end up with many message bundles, making that keeping error codes consistent becomes a nightmare. And what about all the separate files you need to translate! You might find yourself no longer to be able to tell the messages for the bundles.

But as Steve Muench was very persistent in trying to convince me using Validators I finally gave in and tried finding a way to tackle my problem, and succeeded! No worries, don't expect rocket science from me. I hate complex or obscure code, as building maintainable Information Systems already is hard enough as it is, and therefore always try to practice Simple Design.

I assume that you have created a layer of framework extension classes as described in section 2.5 of the ADF Developers Guide and that your entity base class is called MyAppEntityImpl. If you have not yet created such a layer, do that first and come back after you finished. Chop chop!

Basically the steps are as follows:
  • Create extension classes that extend the exceptions that ADF BC will throw when validation fails
  • Override the constructor of the super class and pass in the message bundle in the call to super()
  • Override the setAttributeInternal() and validateEntity() methods in the MyAppEntityImpl.java entity base class and make they thrown your exceptions instead of the default ones.
Does that sound simple or what? No? OK, let me show you how I did it.

Attribute-level Validators will throw the AttrValException. So what I did was create a MyAppAttrValException as follows:

package myapp.model.exception;

import oracle.jbo.AttrValException;
import myapp.model.ResourceBundle;

public class AttrValException extends AttrValException
{
public MyAppAttrValException(String errorCode, Object[] params)
{
super(ResourceBundle.class, errorCode, params);
}

/**
* When the message contains a semicolon, return the message
* starting with the position after the semicolon and limit the
* text to the message text from the resource bundle.
*
* @return the stripped message
*/
public String getMessage()
{
String message = super.getMessage();
// strip off product code and error code
int semiColon = message.indexOf(":");
if (semiColon > 0)
{
message = message.substring(semiColon + 2);
}
return message;
}

And this is how I override the setAttributeInternal in the MyAppEntityImpl:

/**
* Overrides the setAttributeInternal of the superclass in order to
* pass in a custom message bundle to MyAppAttrValException subclass
* of the AttrValException. To be able to uniquely identify the
* entries in the message bundle, the error code is extended with the
* fully qualified class name of the Impl.
*/
protected void setAttributeInternal(int index, Object val)
{
try
{
super.setAttributeInternal(index, val);
}
catch (AttrValException e)
{
String errorCode = new StringBuffer(getClass().getName())
.append(".")
.append(e.getErrorCode())
.toString();
throw new MyAppAttrValException(errorCode, e.getErrorParameters());
}
}

In a similar way you can handle entity-instance-level Validators and Method Validator by extending the ValidationException and overriding the validateEntity() method to throw your MyAppValidationException.

As said, the message you provided when creating build-in Validators and Method Validators end up in an entity-specific message bundle. I've been told that this is going to change in JDeveloper 11g, but currently there is no stopping ADF BC from doing that.

So, at a convenient point in time (for example when most of your Validators have been implemented and tested), what you need to do is copying the error messages from the entity-specific message bundles to your custom message bundle.

To prevent duplicates in the keys of the custom message bundle, you should extend the key of each message with the fully qualified class name of the Impl.java file of the entity object where it's coming from. Otherwise duplicates might occur whenever you have two different entity objects, both with an attribute with the same name and a build-in Validator specified for them. The overriden setAttributeInternal() method assumes you did.

The entries in the message bundle would look
then similar to this:

{ "myapp.model.adfbc.businessobject.EmployeeImpl.Salary_Rule_0",
"APP-00001 Employee's Salary may not be below zero" },
...


Well that wasn't rocket science, was it?

Wednesday, July 04, 2007

How to Prevent Your Rule Gets Fired in ADF BC?

When using the Oracle ADF (Application Development Framework), implementing data-related business rules in the persistance layer is a good practice. In ADF this business layer is called ADF Business Components (aka BC4J, or Business Components for Java). This article will go briefly into this subject, just enough to let you get an appetite for the upcoming revised white paper Business Rules in ADF BC. So don't eat too much of this apetizer, to leave room for the main course to come!

Implemening business rules in ADF Business Components means implementing them in so-called entity objects. For an application that uses a relational database, to a certain extend you can compare an entity object with an EJB entity bean, as like an entity bean the purpose of the entity object is to manage storage of data in a specific table. Unlike EJB entity beans, ADF entity objects provide hooks to implement business rules that go way beyond what you can do with EJB entity beans.

I won't go into detail about these hooks. When you're interested, enough documentation about the subject can be found on the internet (to begin with the Steve Muench's web log) or read the white paper! I will let you know when it is available and where to find it.

Where I do want to go into detail is one aspect, being how to prevent that rules get fired unneccessarily, for example for reasons of performance. I assume some basic knowledge of ADF Business Components, so if you don't have that, this is where you might want to stop reading.

There are the following typical options, provided as methods on any EntityImpl:
  • The isAttributeChanged() method can be used to check if the value of an attribute has actually changed, before firing a rule that only makes sense when this is the case.
  • Furthermore there is the getEntityState() method that can be used to check the status of an entity object in the current transaction, which can either be new, changed since it has been queried, or deleted. You can use this method to make that a rule that only gets fired, for example when the entity object is new.
  • There is also the getPostState() that does a similiar thing as getEntityState() but which takes into consideration whether the change has been posted to the database.
Sometimes knowing whether or not something has changed does not suffice, for example because you need to be compare the old value of an attribute with the new one. That typically happens in case of status attributes with restrictions on the state changes. Normally you would be able to do so using the getPostedAttribute() method, that will return the original value of an attribute as read from or posted to the database. However, that won't work when you are using the beforeCommit() method to fire your rule, as at that time the change already has been posted, so the value getPostedAttribute() returns will not differ from what the getter will return.

"So what", you might think, "when do I ever want to use the beforeCommit()?". Well, you have to as soon as you are dealing with a rule that concerns two or more entity objects that could trigger the rule, as in that case the beforeCommit() is the only hook of which you can be sure that all changes made are reflected by the entity objects involved.

Suppose you have a Project with ProjectAssignments and you want to make sure that the begin and end date of the ProjectAssignments fall within the begin and end date of the Project. A classical example, I dare say. Now the events that could fire this rule are the creation of a ProjectAssignment, the update of the Project its start or end date or the update of the ProjectAssignment its start or end date.

Regarding the creation of the ProjectAssignment, that you can verify by using the getEntityState() which would return STATUS_NEW in that case. Regarding the change of any of the dates, you can check for STATUS_MODIFIED, but that also returns true when any of the other attributes have been changed.

Now suppose that, as there can be multiple ProjectAssignments for one Project, you only want to validate this rule when one of those dates actually did change. The only way to know is by comparing the old values with the new one. As explained before, as the hook you are using will be the beforeCommit() method, the getPostedAttribute() also will return the new value as that time the changes already have been posted to the database.

Bugger, what now? Well, I wouldn't have raised the question unless I would have some solution to it, would I? The solution involves a bit yet pretty straightforward coding. I will only show how to solve this for the Project, for the ProjectAssignment the problem can be solved likewise. The whole idea behind the work-around is that you will use instance variables to store the old values so that they are still available in the beforeCommit().

Open the ProjectImpl.java and add the following private instance variables:

private Date startDateOldValue;
private Date endDateOldValue;

In general you can use a convention to call this specific type of custom instance variables [attribute name]OldValue, to reflect their purpose clearly. Now you need to make that these variables are initialized at the proper moment. This will not be the validateEntity(), as that can fire more than once with unpredictable results. No, it should be the in the doDML() of the ProjectImpl, as follows:

protected void doDML(int operation, TransactionEvent e)
{
  // store old values to be able to compare them with
  // new ones in beforeCommit()
  startDateOldValue = (Date)getPostedAttribute(STARTDATE);
  endDateOldValue = (Date)getPostedAttribute(ENDDATE);

  super.doDML(operation, e);
}

Now in the beforeCommit() you can compare the startDateOldValue with what will be returned by getStartDate(), etc. Although it might not look like it at first sight, this might be the most trickiest part as you need to deal with null values as well. In JHeadstart the following convenience method has been created to tackle this, in the oracle.jheadstart.model.adfbc.AdfbcUtils class:

public static boolean valuesAreDifferent(Object firstValue
              , Object secondValue)
{
  boolean returnValue = false;
  if ((firstValue == null) || (secondValue == null))
  {
    if (( (firstValue == null) && !(secondValue == null))
        ||
        (!(firstValue == null) && (secondValue == null)))
    {
      returnValue = true;
    }
  }
  else
  {
    if (!(firstValue.equals(secondValue)))
    {
      returnValue = true;
    }
  }
  return returnValue;
}

This method is being used in the beforeCommit() of the ProjectImpl, as follows:

public void beforeCommit(TransactionEvent p0)
{
  if ( getEntityState() == STATUS_MODIFIED &&
       ( AdfbcUtils.valuesAreDifferent(startDateOldValue,
              getStartDate()) ||
         AdfbcUtils.valuesAreDifferent(endDateOldValue,
              getEndDate())
       )
    )
  {
    brProjStartEndDate();
  }
  super.beforeCommit(p0);
}

Finally, the actual rule has been implemented as the brProjStartEndDate() method on the ProjectImpl as follows:

public void brProjStartEndDate()
{
  RowIterator projAssignSet = getProjectAssignments();
  ProjectAssignmentImpl projAssign;
  while (projAssignSet.hasNext())
  {
    projAssign =
      (ProjectAssignmentImpl)projAssignSet.next();
    if (((getEndDate() == null) ||
         (projAssign.getStartDate().
              compareTo(getEndDate()) <= 0)
        ) &&
         (projAssign.getStartDate().
              compareTo(getStartDate()) >= 0)
       )
    {
      // rule is true
    }
    else
    {
      throw new JboException("Project start date must " +
        "be before start date of any Project Assignment");
    }
  }
}

Well that wasn't to difficult, was it?

Friday, May 25, 2007

UML rules!

Currently I'm updating the white paper Business Rules in ADF BC. Doing so it occurred to me that there are still many questions to answer what to do when you want to record business rules in UML. With this posting I will share some of my idea's. JDeveloper 10.1.3 will be my tool and ADF BC4J the targeted persistence layer, but I expect the idea's to more generic and also applicable to EJB 3.0 and POJO's for that matter.

In "the old days" when we were young and still using the function hieararchy diagrammer, business rules were either an intrinsic part of the entity relationship diagram or recorded in function descriptions. As this sometimes resulted in the same business rule being recorded more than once (in different functions) and too often in an inconsistent way, we found it to be a neat idea to record them explicitly, that is as functions of their own, and link them to the functions they applied to. This has been a very succesful approach for quite a few years.

At the same time UML arrived as the modeling language for object-oriented analysis and design, and more recently BPMN for business process modeling. As I have never come upon any information system for which there were no business rules whatsoever, you can imagine that it was quite a shock for me to discover that there was no similar thing in place for UML at that time. Of course, a UML class diagram as such allows for expressing more business rules than an entity relationship diagram, but that covers only part of it, doesn't it? As far as the rest is concerned, we were kind of back to square one, meaning that we had to record business rules as part of use cases, for example. The BPMN specification even explicitly excludes business rules from their scope, so what do you do when using BPM?

Some improvements have arrived since the beginning of UML. At some point (not sure since when) constraints have been added (as a stereotype). Also OCL has emerged as a formal language to capture business rules. You can use OCL to record the business rule in a constraint. I don't know about you, but I still have to meet the first person that speaks OCL, let alone the kind of persons we call customers. So in most cases I expect constraints to be recorded using some natural language.

Now let's asume you are using UML to capture functional requirements. Business rules can be found during any stage, for example while doing use case modeling. When starting to create use cases it perfectly makes sense to record rules as part of that. Use cases have some properties that can be used for recording business rules, being pre-conditions and post-conditions. Pre-conditions must be met before the use case can be executed. A typical example would be "the user must be logged on", but could also be something like "the user must be a manager to view detailed employee information".

Post-conditions can be devided in minimal guarantees and success guarantees. Minimal guarantees indicate what must hold true when none of scenarios of the use case have finished successfully. A success guarantee describes a succesfull execution of the use case. Examples of success guarantees are:
  • The employee information has been recorded successfully
  • A change of the employee salary must have been logged
  • When the customer has boarded 15 times or more on a flight, its frequent flyer status must be set to silver elite.
Then there are so-called invariants, being conditions that always should hold true (before, during and after execution of any use case). Examples would be
  • End date must be on or after begin date
  • There cannot be a non-vegetarian dish in a vegetarian dinner.
Your use case template might not have a property called invariants. But hey, it's your use case, so why not add it?

By now you might wonder how to deal with the problem I pointed out at the beginning, being that you captured the same business rule more than once for different use cases. You might also find yourself recording business rules that relate to each other, or even contradict. Don't worry to much about that in the beginning (using the Unified Process that would be while doing Requirements Modeling). Just record the business rules when and where you find them. You only risk a confused customer when you start record business rules as artifacts on their own.

During some next iteration, you detail the use cases. By that time you might have a class model or will start to create one (using the Unified Process that would be during Requirements Analysis). At this point it makes sense to pull business rules out of the use cases and into constraints. Doing so you are able to remove duplications, and inconsistencies.

If your tool supports publishing use cases together with the artifacts linked to that (like classes and constraints ), you might consider to remove the business rules from the use case to prevent duplication and inconsistencies.

Using JDeveloper you normally add constraints to UML class diagrams and link them to the classes they relate to. But you can also include them in use case diagrams and link them to use cases. Finally, you can link related business rules together, which is convenient when you want to decompose business rules.

Having done all this you are not only able to track what rules apply to what classes but also to what use cases. Handy for example for testing purposes.

Finally, you can include the same contraints in (for example) ADF Business Component diagrams, link them to entity objects, classify them or whatever fancy stuff you like to do. Check out the new version of the Business Rules in ADF BC for ideas about classifying business rules when using BC4J. I will let you know when it get's published.

Got to stop here folks. A long and sunny weekend just knoked at my door, and I intend to open ...