I have a below method which does URL decoding on the value passed along with using charset.
public String decodeValue(String value, Charset charset) {
if (!Strings.isNullOrEmpty(value)) {
try {
value = URLDecoder.decode(value, charset.name());
} catch (UnsupportedEncodingException ex) {
// log error
return null;
}
}
return value;
}
Now if URLDecoder.decode line throws UnsupportedEncodingException first time then I want to run same value against below three lines:
value = value.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
value = value.replaceAll("\\+", "%2B");
value = URLDecoder.decode(value, charset.name());
And if then again URLDecoder.decode line throws exception second time, then I will log the error but only second time and return null value otherwise return the value which is decoded.
What is the best and elegant way to do this?
The easiest way is to make a private version of your function signature which includes an extra flag.
Then, just pass
truethe first time andfalsein the recursive call. Inside the function, only execute the next three lines iftrueis passed.The public version can pass
true.