Wednesday, December 16, 2009

Making The User Datastore More Robust

On the front page, I want to expand the data model for the template. I want to be able to display a nice "Welcome back, Jay" sort of message, incorporating the member's name.

This means I have to get the user's name from the RPX results. While I'm at it, I want to make the User records more robust...for example, let's say that I have a hundred people sign up on the site, and later decide I want to start pulling their middle name from the RPX results.

The way the code is written now, I only pull from RPX results when the user first signs in to the site. I want to change that so that on future sign ins, if I discover that the datastore is missing user information I want, I fill that in from the RPX results.

The RPX results has a field called DisplayName that supposedly contains a version of the user's name suitable for display. I want to add that to my user record. I already have a field called Name in the User object, but so far I haven't set it. Here's how I'll set it from within RPXResults.java.

(By the way, I'm going to stop formatting the code for indentation manually in HTML. It's been too much of a pain, and shouldn't affect your ability to understand the code.)


String identifier = info.getElementsByTagName("identifier").item(0).getTextContent();
String name = info.getElementsByTagName("displayName").item(0).getTextContent();

PersistenceManager pm = PMF.get().getPersistenceManager();

Query query = pm.newQuery("select from project.server.User where identifier == identifierParam");
query.declareParameters("String identifierParam");

try
{
List results = (List) query.execute(identifier);
User user = null;

if (results.size() == 0)
{
user = new User ();
user.setIdentifier(identifier);
user.setName(name);
pm.makePersistent(user);
}
else
{
boolean changed = false;

user = results.get(0);

if (user.getName () == null)
{
user.setName (name);
changed = true;
}

if (changed)
pm.makePersistent(user);
}

HttpSession session = req.getSession();
session.setAttribute("userid", user.getId());
}
finally
{
query.closeAll();
pm.close();
}


Note how I set the name when the User already exists, but there's nothing in the name field. That allows me to add new RPX fields that I'm interested in later, and have existing Users pick up those fields.

No comments:

Post a Comment