this on is biting me for days now. I am writing a Confluence plugin that offers a macro with a body. I have not figured out a suitable way in my Java class to check for an empty body.
It seems that Confluence creates default content if the body is submitted empty by the user. It looks like a p-tag with a blank. I tried the following code in my Java class:
body = body.trim();
if (!body.equals("<p> </p>") && !body.equals("<p> </p>") && !body.equals(" ") && !body.equals(" ")) {
// Body not empty. Do something with it here
...
}
So far, the code always enters that if-statement, so my check for an empty body is not correct.
I played around some and came up with this solution (not perfect probably but it works):
import org.apache.commons.codec.binary.Hex;
...
body = body.trim();
String hexBody = Hex.encodeHexString(body.getBytes());
if (!hexBody.equals("3c703ea03c2f703e")) {
// This is a user body. Do something with it...
}
“3c703ea03c2f703e” is the hexadecimal representation of an empty body as passed by Confluence into the handler class.
My only thought was to get Confluence to render the body as wiki markup – there’s a method for that somewhere – then trim the resulting string to see if its a zero length string. Again, not cool.
If we go mental, you can always parse XML or even better (less mental i guess) to pattern match it. I somewhere have had the same problem solved but I don’t have access to comp atm. Will post at first chance
Update: Can’t find exact code, tried to recreate though on 5.8.8 instance:
@Override
public String execute(Map<String, String> params, String body, ConversionContext conversionContext)
throws MacroExecutionException {
logger.debug(body); //this gives for me <p>?</p>
Pattern pattern=Pattern.compile("^<p>.{1}</p>$");
Matcher m=pattern.matcher(body);
if(m.matches())
logger.debug("gotcha by pattern");
......
}