@@ -206,8 +206,14 @@ public Message build() {
206206 }
207207
208208 // check if content is encapsulated in <messageML/> node
209- boolean isAlreadyWrapped = this .content .startsWith ("<messageML" ) && this .content .endsWith ("</messageML>" );
210- if (!isAlreadyWrapped ) {
209+ String trimmedContent = this .content .trim ();
210+ boolean hasStartTag = trimmedContent .startsWith ("<messageML" );
211+ boolean hasEndTag = trimmedContent .endsWith ("</messageML>" );
212+ if (hasStartTag != hasEndTag ) {
213+ throw new MessageCreationException (
214+ "Malformed <messageML> tag. Missing " + (hasStartTag ? "closing" : "opening" ) + " tag" );
215+ }
216+ if (!hasStartTag ) {
211217 log .trace ("Processing content to prefix with <messageML> and suffix with </messageML>" );
212218 if (Boolean .TRUE .equals (this .beta )) {
213219 this .content = "<messageML beta=\" true\" >" + this .content + "</messageML>" ;
@@ -219,6 +225,9 @@ public Message build() {
219225 throw new MessageCreationException (
220226 "Cannot set beta=true when content is already wrapped with <messageML> without the beta attribute. "
221227 + "Either remove the wrapper or include beta=\" true\" in your messageML tag." );
228+ } else {
229+ // content is already wrapped, but we can trim if needed
230+ this .content = trimmedContent ;
222231 }
223232
224233 // check done below because it will rejected by the agent otherwise
@@ -229,4 +238,15 @@ public Message build() {
229238 return new Message (this );
230239 }
231240 }
241+
242+ private boolean isAlreadyWrapped (String content ) {
243+ boolean hasStart = content .startsWith ("<messageML>" );
244+ boolean hasEnd = content .endsWith ("</messageML>" );
245+
246+ if (hasStart != hasEnd ) {
247+ throw new IllegalStateException ("Malformed MessageML: missing " + (hasStart ? "closing" : "opening" ) + " tag." );
248+ }
249+
250+ return hasStart ; // Since they are equal, if hasStart is true, both are true.
251+ }
232252}
0 commit comments