I think you should reconsider your design and use individual keys for the several "aliases" - or probably even better: No aliases at all and just one key per replacement. The problem is that the keys in those properties files are not supposed to contain spaces -- parantheses or not -- so the files are not parsed correctly. If you print the keys, you will see that they are truncated at the first space, e.g. (inv_start_date|invoice start date)
becomes (inv_start_date|invoice
.
Of course, this also means that, even if you split those "aliases" into separate keys, you can not have keys like invoice start date
, as it still contains spaces and will not be parsed correctly.
You could just put those replacements into a regualr Map
in your Java source code:
static Map<String, String> replacements = new HashMap<>();
static {
replacements.put("inv_date", "INVOICE DATE");
replacements.put("(BaseRate|Rate|tk_rate)", "LINE ITEM UNIT COST");
// ... more stuff ...
}
Or parse the file manually, splitting the strings at =
and putting them into a Map
.
And since keys like (BaseRate|Rate|tk_rate)
are in fact valid regular expressions, you can just use replaceAll
to replace them in all their variants. If they are not contained in the string, replaceAll
will just do nothing, so the contains
check is not really necessary.
public static String toUserFriendlyErrorMessage(String message) {
for (String key : replacements.keySet()) {
message = message.replaceAll(key, replacements.get(key));
}
return message;
}
Example output:
Line 3 : Could not parse INVOICE DATE value
Line : 1 LINE ITEM UNIT COST is a required field
Or, if you want to use some "Java 8 magic", you could use reduce
, but personally, I think the loop is more readable.
return replacements.keySet().stream()
.reduce(message, (s, k) -> s.replaceAll(k, replacements.get(k)))
.toString();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…