I have a method which does URL decoding on the string 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
throws UnsupportedEncodingException
the first time, then I want to run the same value
against these 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 so I came up with this:
public String decodeValue(String value, Charset charset) {
if (!Strings.isNullOrEmpty(value)) {
try {
value = URLDecoder.decode(value, charset.name());
} catch (UnsupportedEncodingException ex) {
try {
value = value.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
value = value.replaceAll("\\+", "%2B");
value = URLDecoder.decode(value, charset.name());
} catch (UnsupportedEncodingException uex) {
// log error
return null;
}
}
}
return value;
}
I'd like to see if there is any better way to write the above code. As of now, it duplicates the code.