01: package org.andromda.cartridges.jsf.validator;
02:
03: import java.text.MessageFormat;
04:
05: import java.util.Locale;
06: import java.util.MissingResourceException;
07:
08: import javax.faces.context.FacesContext;
09:
10: import org.andromda.cartridges.jsf.Messages;
11: import org.apache.commons.validator.Arg;
12: import org.apache.commons.validator.Field;
13: import org.apache.commons.validator.ValidatorAction;
14:
15: /**
16: * Retrieves and formats the validation messages.
17: *
18: * @author Chad Brandon
19: */
20: public class ValidatorMessages {
21: /**
22: * Gets the <code>message</code> based on the <code<action</code>
23: * message and the <code>field</code>'s arg objects.
24: *
25: * @param action Validator action
26: * @param args any message arguments to be substituted.
27: * @param context the faces context
28: */
29: public static String getMessage(final ValidatorAction action,
30: final String[] args, final FacesContext context) {
31: final Locale locale = context.getViewRoot().getLocale();
32: String message = null;
33: final String messageKey = action.getMsg();
34: if (message == null) {
35: try {
36: message = Messages.get(messageKey, args);
37: } catch (final MissingResourceException exception) {
38: message = messageKey;
39: }
40: }
41: message = new MessageFormat(message, locale).format(args);
42: return message;
43: }
44:
45: /**
46: * Gets the message given the action, field and faces context.
47: *
48: * @param action the validator action instance.
49: * @param field the field.
50: * @param context the faces context.
51: * @return the message
52: */
53: public static String getMessage(final ValidatorAction action,
54: final Field field, final FacesContext context) {
55: return getMessage(action, getArgs(action.getName(), field),
56: context);
57: }
58:
59: /**
60: * Gets the message arguments based on the given
61: * validator <code>action</code> and <code>cield</code>.
62: * @param action action name
63: * @param field the validator field
64: */
65: public static String[] getArgs(final String action,
66: final Field field) {
67: final Arg[] args = field.getArgs(action);
68: final String[] argMessages = new String[args.length];
69: for (int ctr = 0; ctr < args.length; ctr++) {
70: final Arg arg = args[ctr];
71: if (arg != null) {
72: if (arg.isResource()) {
73: argMessages[ctr] = Messages.get(arg.getKey(), null);
74: } else {
75: argMessages[ctr] = arg.getKey();
76: }
77: }
78: }
79: return argMessages;
80: }
81: }
|