1 15 package org.apache.tapestry.form.translator; 16 17 import java.text.MessageFormat ; 18 import java.util.Locale ; 19 20 import org.apache.hivemind.HiveMind; 21 import org.apache.tapestry.IForm; 22 import org.apache.tapestry.IMarkupWriter; 23 import org.apache.tapestry.IRequestCycle; 24 import org.apache.tapestry.form.AbstractFormComponentContributor; 25 import org.apache.tapestry.form.FormComponentContributorContext; 26 import org.apache.tapestry.form.IFormComponent; 27 import org.apache.tapestry.valid.ValidationStrings; 28 import org.apache.tapestry.valid.ValidatorException; 29 30 37 public abstract class AbstractTranslator extends AbstractFormComponentContributor implements 38 Translator 39 { 40 private boolean _trim; 41 42 private String _message; 43 44 public AbstractTranslator() 45 { 46 } 47 48 public AbstractTranslator(String initializer) 50 { 51 super(initializer); 52 } 53 54 58 public String format(IFormComponent field, Object object) 59 { 60 return (object != null) ? formatObject(field, object) : ""; 61 } 62 63 67 public Object parse(IFormComponent field, String text) throws ValidatorException 68 { 69 String value = _trim ? text.trim() : text; 70 71 return HiveMind.isBlank(value) ? getEmpty() : parseText(field, value); 72 } 73 74 protected abstract String formatObject(IFormComponent field, Object object); 75 76 protected abstract Object parseText(IFormComponent field, String text) 77 throws ValidatorException; 78 79 protected Object getEmpty() 80 { 81 return null; 82 } 83 84 protected String buildMessage(IFormComponent field, String key) 85 { 86 Locale locale = field.getPage().getLocale(); 87 88 String pattern = (_message == null) ? ValidationStrings.getMessagePattern(key, locale) 89 : _message; 90 91 String name = field.getDisplayName(); 92 93 return MessageFormat.format(pattern, getMessageParameters(locale, name)); 94 } 95 96 protected Object [] getMessageParameters(Locale locale, String label) 97 { 98 return new Object [] 99 { label }; 100 } 101 102 106 public void renderContribution(IMarkupWriter writer, IRequestCycle cycle, FormComponentContributorContext context, IFormComponent field) 107 { 108 super.renderContribution(writer, cycle, context, field); 109 110 if (_trim) 111 { 112 IForm form = field.getForm(); 113 114 addSubmitHandler(form, "trim(document." + form.getName() + "." + field.getName() + ")"); 115 } 116 } 117 118 public boolean isTrim() 119 { 120 return _trim; 121 } 122 123 public void setTrim(boolean trim) 124 { 125 _trim = trim; 126 } 127 128 public String getMessage() 129 { 130 return _message; 131 } 132 133 public void setMessage(String message) 134 { 135 _message = message; 136 } 137 } 138 | Popular Tags |