1 16 17 package org.springframework.validation; 18 19 import java.io.Serializable ; 20 import java.util.ArrayList ; 21 import java.util.Iterator ; 22 import java.util.List ; 23 24 import org.springframework.util.StringUtils; 25 26 79 public class DefaultMessageCodesResolver implements MessageCodesResolver, Serializable { 80 81 84 public static final String CODE_SEPARATOR = "."; 85 86 87 private String prefix = ""; 88 89 90 95 public void setPrefix(String prefix) { 96 this.prefix = (prefix != null ? prefix : ""); 97 } 98 99 103 protected String getPrefix() { 104 return this.prefix; 105 } 106 107 108 public String [] resolveMessageCodes(String errorCode, String objectName) { 109 return new String [] { 110 postProcessMessageCode(errorCode + CODE_SEPARATOR + objectName), 111 postProcessMessageCode(errorCode)}; 112 } 113 114 123 public String [] resolveMessageCodes(String errorCode, String objectName, String field, Class fieldType) { 124 List codeList = new ArrayList (); 125 List fieldList = new ArrayList (); 126 buildFieldList(field, fieldList); 127 for (Iterator it = fieldList.iterator(); it.hasNext();) { 128 String fieldInList = (String ) it.next(); 129 codeList.add(postProcessMessageCode(errorCode + CODE_SEPARATOR + objectName + CODE_SEPARATOR + fieldInList)); 130 } 131 int dotIndex = field.lastIndexOf('.'); 132 if (dotIndex != -1) { 133 buildFieldList(field.substring(dotIndex + 1), fieldList); 134 } 135 for (Iterator it = fieldList.iterator(); it.hasNext();) { 136 String fieldInList = (String ) it.next(); 137 codeList.add(postProcessMessageCode(errorCode + CODE_SEPARATOR + fieldInList)); 138 } 139 if (fieldType != null) { 140 codeList.add(postProcessMessageCode(errorCode + CODE_SEPARATOR + fieldType.getName())); 141 } 142 codeList.add(postProcessMessageCode(errorCode)); 143 return StringUtils.toStringArray(codeList); 144 } 145 146 150 protected void buildFieldList(String field, List fieldList) { 151 fieldList.add(field); 152 String plainField = field; 153 int keyIndex = plainField.lastIndexOf('['); 154 while (keyIndex != -1) { 155 int endKeyIndex = plainField.indexOf(']', keyIndex); 156 if (endKeyIndex != -1) { 157 plainField = plainField.substring(0, keyIndex) + plainField.substring(endKeyIndex + 1); 158 fieldList.add(plainField); 159 keyIndex = plainField.lastIndexOf('['); 160 } 161 else { 162 keyIndex = -1; 163 } 164 } 165 } 166 167 174 protected String postProcessMessageCode(String code) { 175 return getPrefix() + code; 176 } 177 178 } 179 | Popular Tags |