Using multiple EOEditingContexts

The job of an EOEditingContext (EC) in WebObjects is to manage an object graph of EOEnterpriseObjects (EOs). Think of it as a sandbox that your EOs live in. Any changes made to those EOs – attributes changed, relationships created or destroyed, EOs added or deleted – are tracked by the EC and committed to the database by calling its saveChanges() method.

When you create a new WebObjects application you get one EC associated with each Session object. This Session Default Editing Context (SDEC) is obtained by calling defaultEditingContext() on the Session.

The SDEC has one major benefit over the ECs you create yourself: It is automatically locked and unlocked by the frameworks freeing you from this confusing and unwieldily task. For this reason most WebObjects examples/demos/tutorials rely on the SDEC exclusively leaving each user with one global EC for all of their EOs.

Unfortunately, following this example and using only the SDEC in a production application can prove to be highly dangerous.

No one likes a dirty sandbox

I have kids, and a cat, and we live in a cat filled neighbourhood. Cats and kids both really like sandboxes, but for different reasons. I’m sure you can see where this is going. No one likes to play in a dirty sandbox.

The problem with only using the SDEC for your application is this: It is really easy to dirty the sandbox. Because an EC tracks all of the changes made anywhere in its object graph, the potential for unwanted changes getting committed to the database grows with the complexity of your application.

When bad things happen to good object graphs

Let’s say a user lands on an edit page that has a bunch of fields including a WOPopup with an onclick binding that calls some JS to submit the form. They make a change via that popup and then choose to abandon their edit and navigate somewhere else on the site.

Unbeknownst to them, when the form was submitted the EO bound to that WOPopup had it’s values altered and the SDEC faithfully tracked that change. Even though the user didn’t save those changes by calling saveChanges() the SDEC still knows about them and is patiently waiting to commit them when told to.

If the user later chooses to edit another EO, or performs any action that calls saveChanges() on the SDEC that abandoned edit will get committed.

Or, perhaps you have a new object action that creates a new EO and binds it to an edit form. Again, for some reason, the user abandons the form. You now have an empty EO sitting in the SDEC just waiting to get committed at some point in the future. When it occurs, that commit will probably fail, throwing validation errors that will make absolutely no sense to the user, or worse yet it will succeed resulting in unwanted data in your database.

Solutions?

One possible solution to this problem is to tightly manage the contents of your SDEC. This can be done by routinely calling revert() on the SDEC to eliminate unwanted changes. This requires either making your application highly modal or working very hard to trap every possible way the user can abandon any part of the site that could result in EO changes.

Believe me, this can become tired very quickly.

Hrm, any other way?

I thought you’d never ask.

In my opinion, the cleanest way to handle these issues in your application is by using multiple ECs. By creating temporary ECs to wrap any EOs that are being edited, we can eliminate many of the problems mentioned above. If the user chooses to abandon an edit mid stream, the EC (and all of it’s changes) will just disappear when it is garbage collected.

“But you said I’d have to handle icky locking issues.”

You are right, I did. But there is an easy solution. If you use Project Wonder and follow the instructions in this post, then pretty much all of the common cases of EC locking are handled automatically for you.

So it’s as easy as that?

Unfortunately no. There are a few additional things you need to think about.

  • There are peer and nested ECs
  • You cannot relate EOs in different ECs
  • You cannot move uncommitted (new) EOs between ECs

Peer and nested ECs

Usually peer ECs are the same as the SDEC, differing only in the fact that you created them. Because we are using Project Wonder for all of these examples, creating a peer EC is done like this:

EOEditingContext peerEc = ERXEC.newEditingContext();

When saveChanges() is called on peerEc any changes in it’s EOs will be committed to the database.

As their name implies, nested ECs are nested in another EC. They are created like this:

EOEditingContext peerEc = ERXEC.newEditingContext();
EOEditingContext nestedEc = ERXEC.newEditingContext(peerEc);

Unlike the peerEc, calling saveChanges() on the nestedEc does not committed the changes directly to the database. Instead it saves the changes up into it’s parent (peerEC).

Nested ECs are useful if you have a edit step that is dependent on another one. i.e. Creating a new Person EO, and from within that edit form provide the ability to open a new Address form – You wouldn’t want the new Address to be committed to the database until the Person was saved.

You cannot relate EOs in different ECs

As the heading states: YOU CANNOT RELATE EOs IN DIFFERENT ECs. This is going to be the biggest issue you face when working with multiple editing contexts. For instance this code will not work:

EOEditingContext sdec = Session().defaultEditingContext();
EOEditingContext myEc = ERXEC.newEditingContext();
EOQualifier qual = Person.EMAIL.eq("moc.bobnull@bob");
Person myPerson = Person.fetchPerson(sdec, qual);

Address newAddress = Address.newAddress(myEc);
newAddress.addToPeopleRelationship(myPerson);
newAddress.editingContext().saveChanges(); //gonna go boom!

To make this work, you are going to need to change the code to something like this:

EOEditingContext sdec = Session().defaultEditingContext();
EOQualifier qual = Person.EMAIL.eq("moc.bobnull@bob");
Person myPerson = Person.fetchPerson(sdec, qual);

EOEditingContext myEc = ERXEC.newEditingContext();
Address newAddress = Address.newAddress(myEc);//* see note
Person localPerson = myPerson.localInstanceIn(myEc);
newAddress.addToPeopleRelationship(localPerson);
newAddress.editingContext().saveChanges();

The myPerson.localInstanceIn(myEc) method is a convenience method in the WOLips Velocity eogeneration templates. It essentially wraps a call to:

EOUtilities.localInstanceOfObject(myEc, myPerson);

You cannot move uncommitted (new) EOs between ECs

The observant of you out there may have noticed that I called localInstance on the Person EO. The EO that we fetched from the DB. Not the new Address EO that we created. The reason I did that is because you cannot move uncommitted EOs between ECs. If you do this:

EOEditingContext ec1 = ERXEC.newEditingContext();
EOEditingContext ec2 = ERXEC.newEditingContext();
Person person = Person.newPerson(ec1);
Person localPerson =
    EOUtilities.localInstanceOfObject(ec, person);

localPerson will be null. And if you replace that EOUtilities call with:

Person localPerson = Person.localInstanceIn(ec2);

The call to localInstanceIn() will throw an Exception.

So, be sure to think about what objects are new and what are pre-existing. Either create your new EOs in the EC that you use to fetch your existing ones, or move your existing ones into the EC you use to create your new ones.

What about nested ECs?

Given a parent EC with a child EC: Saving the parent EC will commit its changes but will not save the changes in its children unless they’ve been saved first. So this code:

EOEditingContext parentEc = ERXEC.newEditingContext();
EOEditingContext childEc = ERXEC.newEditingContext(parentEc);
Person person = Person.newPerson(childEc);
parentEc.saveChanges();

Will not result in a new Person object being saved to the DB. For that to occur, the child EC needs to be saved first:

EOEditingContext parentEc = ERXEC.newEditingContext();
EOEditingContext childEc = ERXEC.newEditingContext(parentEc);
Person person = Person.newPerson(childEc);
childEc.saveChanges(); // move changes into my parent
parentEc.saveChanges();

The same rules that govern EOs in different ECs apply to nested ECs. However with nested ECs, once you’ve saved the child the EO will exist in the parent. You just need to retrieve it:

EOEditingContext parentEc = ERXEC.newEditingContext();
Person person = Person.newPerson(parentEc);

EOEditingContext childEc = ERXEC.newEditingContext(parentEc);
Address address = Address.newAddress(childEc);
childEc.saveChanges(); // move changes into my parent

// Get the address instance in the parent EC.
EOGlobalID gid = childEc.globalIDForObject(address);
address = (Address)parentEc.objectForGlobalID(gid);

person.setAddressRelationship(address);
parentEc.saveChanges();

The End

If you have stuck with me this long, I thank you. This is a fairly long (and perhaps rambling post) but working with multiple EOEditingContexts in WebObjects is an essential skill.

Project Wonder takes a great deal of pain out of working with multiple ECs (by eliminating most of the locking issues) but for the uninitiated, there are still some head scratchers that can crop up and I hope this post helps to illuminate them.

* Hey were does that newAddress() method come from? Well, I usually have a factory method generated by my eogeneration template that looks something like this:

public static Address newAddress(EOEditingContext ec) {
	return (Address)EOUtilities.createAndInsertInstance(ec,
						ENTITY_NAME);
}

Advanced WOComponent API Validation

WebObjects WOComponents are comprised of two files and a bundle. For example a WOComponent named “MyComponent” would have a bundle called MyComponent.wo, a Java file called MyComponent.java, and an API file called MyComponent.api.

Usually the majority of your time is spent editing the content of the .wo bundle and adding logic to the .java file. But when you create a reusable WOComponent it is also important to specify it’s bindings requirements so that the WOLips Component Editor (or WOBuilder if you are so inclined) knows what bindings the component accepts. This is the job of the API file.

WOLips Component Edtior – The API Tab

If you were to create a component named “MyReusableComponent” and in the API tab of the WOLips Component editor you added three bindings the editor window would look something like this:

api_window_1.png

Now if you were to open the MyReusableComponent.api file in a text editor instead of the API editor you’d find a chunk of xml that looked like this:

< ?xml version="1.0" encoding="UTF-8" standalone="yes"?>

Back in the API editor if you selected the first binding and checked the “Required” checkbox you’d see the API change to this:

< ?xml version="1.0" encoding="UTF-8" standalone="yes"?>

    

    

The additional xml defines a validation message that will be triggered if it’s contents evaluate to true. In this case: if “myBinding1” is not bound.

Unfortunately, this is about as far as the validation rules currently go in the WOLips Component Editor. If you need validation that is any more complicated than “Required” or “Will Set” you are on your own…

On Your Own

Lets say our reusable component has an “action” and “href” binding. Either action or href needs to be bound but not both. Let’s start with the API xml that the Component Editor gives us:

< ?xml version="1.0" encoding="UTF-8" standalone="yes"?>

I told the Component Editor to mark the “action” binding as being required to get the boilerplate validation message. Now lets extend the API to handle the “href” binding.

The validation message block supports <and> and <or> tags, so lets try with that:

&lt; ?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;

    

    

If we test this by embedding our component in a page we’ll see that it works for one potential case. We get a validation warning if we neglect to bind “action” or “href”, however it fails to flag us if we bind both. So lets extend the validation rule to handle that case:

&lt; ?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;

      

      

Not Done Yet

Alternately we could use the “count” directive and write our validation like this:

&lt; ?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;

      

      

Now We’re Done

The easiest way to learn the different options available for the API validation rules is to browse some existing examples – ERExtensions from Project Wonder or WO’s JavaWOExtensions are two good places to start. Simply open the Framework/Resources folder and browse through the various component API files you find there.

Connection Dictionary Twiddling – Part 2

I wrote about using Project Wonder’s ERXConfigurationManager to ‘twiddle’ your model connection dictionary settings here.

I only listed the global properties, but there are per model properties as well. Unfortunately the JDBC settings are not very well documented. So, to google index my brain, here are my notes: Most of the heavy lifting is done by the fixJDBCDictionary method in ERXModelGroup – you can read the source if you want to know all the values – here is a (MySQL) example with the most common ones:

  • MyModelName.URL=jdbc:mysql://localhost/my_dbname?capitalize…etc
  • MyModelName.DBUser=db_user
  • MyModelName.DBPassword=db_password
  • MyModelName.DBDriver=com.mysql.jdbc.Driver

New Screencast

WO/ProjectWonder/WOLips – Part 2

I just completed part 2 of the WO/Wonder/WOLips series. This episode introduces:

  • Reusable components
  • Importing files into your project
  • DirectActions
  • Modeling relationships
  • Updating a db schema with Migrations

It should be in available in WebObjects Podcasts on iTunes, from the WOCommunity site, or direct from my .mac account here.

Resources

Source of the completed project.

As always, comments and suggestions welcome.

Screencasts

I’ve been playing with the very cool ScreenFlow from vara software this week… Did I mention that it was very cool?

Anyway, I put together a couple of introductory screencasts on using WebObjects and WOLips. They can both be found in the WebObjects Podcasts on iTMS or from the WOCommunity site.

HelloWorld

The first is a short HelloWorld tutorial that introduces:

  • Launching Eclipse/WOLips for the first time
  • Creating a new WebObjects project
  • Project folder structure
  • Running the application
  • Modifying the application run settings
  • Editing components

Direct link from my .mac account here.

WO/ProjectWonder/WOLips

The second is a more advanced WO/Wonder/WOLips tutorial that introduces:

  • Database setup using Wonder’s Migrations (NOTE: I use WO 5.3 on Leopard – Migrations are broken in WO 5.4)
  • Inline bindings
  • WOLips’ Add Action, and Add Key dialogs
  • EOGeneration using the Wonder Velocity Template
  • ERXKey and chainable qualifiers

Direct link from my .mac account here.

Resources

Login form mockup.

Source of the completed project.

Notes:

The response from the WO lists has been very positive, so thank you everyone.

Lachlan Deck asked:

Probably helpful to explain why you’re making the ivars public (i.e., in the absence of getter/setters)

My general thoughts on this are:

If –

  • The ivars are only used by the component’s bindings (ie WORepetition item bindings)
  • Are used by bindings and are set in only one action or method in the component
  • Are never exposed by the api

Then I usually feel OK accessing them directly. If I need to expose the variable via the components API or I need to set the ivars value multiple places in the component then I will make the ivar private and wrap it with accessors.

Comments and suggestions welcome.