I was adapting the code at http://displaytag.svn.sourceforge.net/viewvc/displaytag/trunk/displaytag/src/main/java/org/displaytag/localization/I18nWebworkAdapter.java?revision=1173&view=markup that gets the i18n resource from the key in Displaytag (see code below).
I was wondering if this is the cleanest approach (I dislike the iterator there). The only alternative I see, however, is getting the Action from the ActionInvocation (ActionContext.getContext().getActionInvocation().getAction()) and relying on a cast to ActionSupport to get the resource (which implements TextProvider). This doesn’t seem very safe, though (action may not extend actionsupport).
Do you have any other suggestions?
/**
* @see I18nResourceProvider#getResource(String, String, Tag, PageContext)
*/
public String getResource(String resourceKey, String defaultValue, Tag tag, PageContext pageContext)
{
// if resourceKey isn't defined either, use defaultValue
String key = (resourceKey != null) ? resourceKey : defaultValue;
String message = null;
OgnlValueStack stack = TagUtils.getStack(pageContext);
Iterator iterator = stack.getRoot().iterator();
while (iterator.hasNext())
{
Object o = iterator.next();
if (o instanceof TextProvider)
{
TextProvider tp = (TextProvider) o;
message = tp.getText(key, null, null);
break;
}
}
// if user explicitely added a titleKey we guess this is an error
if (message == null && resourceKey != null)
{
log.debug(Messages.getString("Localization.missingkey", resourceKey)); //$NON-NLS-1$
message = UNDEFINED_KEY + resourceKey + UNDEFINED_KEY;
}
return message;
}
The best way would be to do it the same way the text tag does (check the implementation), or the rest of the tags do: by searching the stack.
Also, you probably don’t mean to explicitly cast to
ActionSupport, you’d likely want to check if it’s castable to aTextProvider, which is what you’re actually interested in.I’m not sure what your issue with the iterator is–that’s how it should be done, since your goal is to walk the stack and try with the top-most
TextProvider. You may not want to stop with the top-most, depends on your needs/goals.