001/** 002 * 003 * Copyright 2014-2021 Florian Schmaus 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.jivesoftware.smack.util; 018 019import java.io.IOException; 020import java.io.Writer; 021import java.util.ArrayList; 022import java.util.Collection; 023import java.util.Date; 024import java.util.List; 025 026import org.jivesoftware.smack.packet.Element; 027import org.jivesoftware.smack.packet.ExtensionElement; 028import org.jivesoftware.smack.packet.FullyQualifiedElement; 029import org.jivesoftware.smack.packet.NamedElement; 030import org.jivesoftware.smack.packet.XmlEnvironment; 031 032import org.jxmpp.util.XmppDateTime; 033 034public class XmlStringBuilder implements Appendable, CharSequence, Element { 035 public static final String RIGHT_ANGLE_BRACKET = Character.toString('>'); 036 037 private final LazyStringBuilder sb; 038 039 private final XmlEnvironment effectiveXmlEnvironment; 040 041 public XmlStringBuilder() { 042 sb = new LazyStringBuilder(); 043 effectiveXmlEnvironment = null; 044 } 045 046 public XmlStringBuilder(ExtensionElement pe) { 047 this(pe, null); 048 } 049 050 public XmlStringBuilder(NamedElement e) { 051 this(); 052 halfOpenElement(e.getElementName()); 053 } 054 055 public XmlStringBuilder(FullyQualifiedElement element, XmlEnvironment enclosingXmlEnvironment) { 056 this(element.getElementName(), element.getNamespace(), element.getLanguage(), enclosingXmlEnvironment); 057 } 058 059 public XmlStringBuilder(String elementName, String xmlNs, String xmlLang, XmlEnvironment enclosingXmlEnvironment) { 060 sb = new LazyStringBuilder(); 061 halfOpenElement(elementName); 062 063 if (enclosingXmlEnvironment == null) { 064 xmlnsAttribute(xmlNs); 065 xmllangAttribute(xmlLang); 066 } else { 067 if (!enclosingXmlEnvironment.effectiveNamespaceEquals(xmlNs)) { 068 xmlnsAttribute(xmlNs); 069 } 070 if (!enclosingXmlEnvironment.effectiveLanguageEquals(xmlLang)) { 071 xmllangAttribute(xmlLang); 072 } 073 } 074 075 effectiveXmlEnvironment = XmlEnvironment.builder() 076 .withNamespace(xmlNs) 077 .withLanguage(xmlLang) 078 .withNext(enclosingXmlEnvironment) 079 .build(); 080 } 081 082 public XmlEnvironment getXmlEnvironment() { 083 return effectiveXmlEnvironment; 084 } 085 086 public XmlStringBuilder escapedElement(String name, String escapedContent) { 087 assert escapedContent != null; 088 openElement(name); 089 append(escapedContent); 090 closeElement(name); 091 return this; 092 } 093 094 /** 095 * Add a new element to this builder. 096 * 097 * @param name TODO javadoc me please 098 * @param content TODO javadoc me please 099 * @return the XmlStringBuilder 100 */ 101 public XmlStringBuilder element(String name, String content) { 102 if (content.isEmpty()) { 103 return emptyElement(name); 104 } 105 openElement(name); 106 escape(content); 107 closeElement(name); 108 return this; 109 } 110 111 /** 112 * Add a new element to this builder, with the {@link java.util.Date} instance as its content, 113 * which will get formatted with {@link XmppDateTime#formatXEP0082Date(Date)}. 114 * 115 * @param name element name 116 * @param content content of element 117 * @return this XmlStringBuilder 118 */ 119 public XmlStringBuilder element(String name, Date content) { 120 assert content != null; 121 return element(name, XmppDateTime.formatXEP0082Date(content)); 122 } 123 124 /** 125 * Add a new element to this builder. 126 * 127 * @param name TODO javadoc me please 128 * @param content TODO javadoc me please 129 * @return the XmlStringBuilder 130 */ 131 public XmlStringBuilder element(String name, CharSequence content) { 132 return element(name, content.toString()); 133 } 134 135 public XmlStringBuilder element(String name, Enum<?> content) { 136 assert content != null; 137 element(name, content.toString()); 138 return this; 139 } 140 141 /** 142 * Deprecated. 143 * 144 * @param element deprecated. 145 * @return deprecated. 146 * @deprecated use {@link #append(Element)} instead. 147 */ 148 @Deprecated 149 // TODO: Remove in Smack 4.5. 150 public XmlStringBuilder element(Element element) { 151 assert element != null; 152 return append(element.toXML()); 153 } 154 155 public XmlStringBuilder optElement(String name, String content) { 156 if (content != null) { 157 element(name, content); 158 } 159 return this; 160 } 161 162 /** 163 * Add a new element to this builder, with the {@link java.util.Date} instance as its content, 164 * which will get formatted with {@link XmppDateTime#formatXEP0082Date(Date)} 165 * if {@link java.util.Date} instance is not <code>null</code>. 166 * 167 * @param name element name 168 * @param content content of element 169 * @return this XmlStringBuilder 170 */ 171 public XmlStringBuilder optElement(String name, Date content) { 172 if (content != null) { 173 element(name, content); 174 } 175 return this; 176 } 177 178 public XmlStringBuilder optElement(String name, CharSequence content) { 179 if (content != null) { 180 element(name, content.toString()); 181 } 182 return this; 183 } 184 185 public XmlStringBuilder optElement(Element element) { 186 if (element != null) { 187 append(element); 188 } 189 return this; 190 } 191 192 public XmlStringBuilder optElement(String name, Enum<?> content) { 193 if (content != null) { 194 element(name, content); 195 } 196 return this; 197 } 198 199 public XmlStringBuilder optElement(String name, Object object) { 200 if (object != null) { 201 element(name, object.toString()); 202 } 203 return this; 204 } 205 206 public XmlStringBuilder optIntElement(String name, int value) { 207 if (value >= 0) { 208 element(name, String.valueOf(value)); 209 } 210 return this; 211 } 212 213 public XmlStringBuilder halfOpenElement(String name) { 214 assert StringUtils.isNotEmpty(name); 215 sb.append('<').append(name); 216 return this; 217 } 218 219 public XmlStringBuilder halfOpenElement(NamedElement namedElement) { 220 return halfOpenElement(namedElement.getElementName()); 221 } 222 223 public XmlStringBuilder openElement(String name) { 224 halfOpenElement(name).rightAngleBracket(); 225 return this; 226 } 227 228 public XmlStringBuilder closeElement(String name) { 229 sb.append("</").append(name); 230 rightAngleBracket(); 231 return this; 232 } 233 234 public XmlStringBuilder closeElement(NamedElement e) { 235 closeElement(e.getElementName()); 236 return this; 237 } 238 239 public XmlStringBuilder closeEmptyElement() { 240 sb.append("/>"); 241 return this; 242 } 243 244 /** 245 * Add a right angle bracket '>'. 246 * 247 * @return a reference to this object. 248 */ 249 public XmlStringBuilder rightAngleBracket() { 250 sb.append(RIGHT_ANGLE_BRACKET); 251 return this; 252 } 253 254 /** 255 * Does nothing if value is null. 256 * 257 * @param name TODO javadoc me please 258 * @param value TODO javadoc me please 259 * @return the XmlStringBuilder 260 */ 261 public XmlStringBuilder attribute(String name, String value) { 262 assert value != null; 263 sb.append(' ').append(name).append("='"); 264 escapeAttributeValue(value); 265 sb.append('\''); 266 return this; 267 } 268 269 public XmlStringBuilder attribute(String name, boolean bool) { 270 return attribute(name, Boolean.toString(bool)); 271 } 272 273 /** 274 * Add a new attribute to this builder, with the {@link java.util.Date} instance as its value, 275 * which will get formatted with {@link XmppDateTime#formatXEP0082Date(Date)}. 276 * 277 * @param name name of attribute 278 * @param value value of attribute 279 * @return this XmlStringBuilder 280 */ 281 public XmlStringBuilder attribute(String name, Date value) { 282 assert value != null; 283 return attribute(name, XmppDateTime.formatXEP0082Date(value)); 284 } 285 286 public XmlStringBuilder attribute(String name, CharSequence value) { 287 return attribute(name, value.toString()); 288 } 289 290 public XmlStringBuilder attribute(String name, Enum<?> value) { 291 assert value != null; 292 attribute(name, value.toString()); 293 return this; 294 } 295 296 public <E extends Enum<?>> XmlStringBuilder attribute(String name, E value, E implicitDefault) { 297 if (value == null || value == implicitDefault) { 298 return this; 299 } 300 301 attribute(name, value.toString()); 302 return this; 303 } 304 305 public XmlStringBuilder attribute(String name, int value) { 306 assert name != null; 307 return attribute(name, String.valueOf(value)); 308 } 309 310 public XmlStringBuilder attribute(String name, long value) { 311 assert name != null; 312 return attribute(name, String.valueOf(value)); 313 } 314 315 public XmlStringBuilder optAttribute(String name, String value) { 316 if (value != null) { 317 attribute(name, value); 318 } 319 return this; 320 } 321 322 public XmlStringBuilder optAttribute(String name, Long value) { 323 if (value != null) { 324 attribute(name, value); 325 } 326 return this; 327 } 328 329 /** 330 * Add a new attribute to this builder, with the {@link java.util.Date} instance as its value, 331 * which will get formatted with {@link XmppDateTime#formatXEP0082Date(Date)} 332 * if {@link java.util.Date} instance is not <code>null</code>. 333 * 334 * @param name attribute name 335 * @param value value of this attribute 336 * @return this XmlStringBuilder 337 */ 338 public XmlStringBuilder optAttribute(String name, Date value) { 339 if (value != null) { 340 attribute(name, value); 341 } 342 return this; 343 } 344 345 public XmlStringBuilder optAttribute(String name, CharSequence value) { 346 if (value != null) { 347 attribute(name, value.toString()); 348 } 349 return this; 350 } 351 352 public XmlStringBuilder optAttribute(String name, Enum<?> value) { 353 if (value != null) { 354 attribute(name, value.toString()); 355 } 356 return this; 357 } 358 359 public XmlStringBuilder optAttribute(String name, Number number) { 360 if (number != null) { 361 attribute(name, number.toString()); 362 } 363 return this; 364 } 365 366 /** 367 * Same as {@link #optAttribute(String, CharSequence)}, but with a different method name. This method can be used if 368 * the provided attribute value argument type causes ambiguity in method overloading. For example if the type is a 369 * subclass of Number and CharSequence. 370 * 371 * @param name the name of the attribute. 372 * @param value the value of the attribute. 373 * @return a reference to this object. 374 * @since 4.5 375 */ 376 public XmlStringBuilder optAttributeCs(String name, CharSequence value) { 377 return optAttribute(name, value); 378 } 379 380 /** 381 * Add the given attribute if {@code value => 0}. 382 * 383 * @param name TODO javadoc me please 384 * @param value TODO javadoc me please 385 * @return a reference to this object 386 */ 387 public XmlStringBuilder optIntAttribute(String name, int value) { 388 if (value >= 0) { 389 attribute(name, Integer.toString(value)); 390 } 391 return this; 392 } 393 394 /** 395 * If the provided Integer argument is not null, then add a new XML attribute with the given name and the Integer as 396 * value. 397 * 398 * @param name the XML attribute name. 399 * @param value the optional integer to use as the attribute's value. 400 * @return a reference to this object. 401 * @since 4.4.1 402 */ 403 public XmlStringBuilder optIntAttribute(String name, Integer value) { 404 if (value != null) { 405 attribute(name, value.toString()); 406 } 407 return this; 408 } 409 410 /** 411 * Add the given attribute if value not null and {@code value => 0}. 412 * 413 * @param name TODO javadoc me please 414 * @param value TODO javadoc me please 415 * @return a reference to this object 416 */ 417 public XmlStringBuilder optLongAttribute(String name, Long value) { 418 if (value != null && value >= 0) { 419 attribute(name, Long.toString(value)); 420 } 421 return this; 422 } 423 424 public XmlStringBuilder optBooleanAttribute(String name, boolean bool) { 425 if (bool) { 426 sb.append(' ').append(name).append("='true'"); 427 } 428 return this; 429 } 430 431 public XmlStringBuilder optBooleanAttributeDefaultTrue(String name, boolean bool) { 432 if (!bool) { 433 sb.append(' ').append(name).append("='false'"); 434 } 435 return this; 436 } 437 438 private static final class XmlNsAttribute implements CharSequence { 439 private final String value; 440 private final String xmlFragment; 441 442 private XmlNsAttribute(String value) { 443 this.value = StringUtils.requireNotNullNorEmpty(value, "Value must not be null"); 444 this.xmlFragment = " xmlns='" + value + '\''; 445 } 446 447 @Override 448 public String toString() { 449 return xmlFragment; 450 } 451 452 @Override 453 public int length() { 454 return xmlFragment.length(); 455 } 456 457 @Override 458 public char charAt(int index) { 459 return xmlFragment.charAt(index); 460 } 461 462 @Override 463 public CharSequence subSequence(int start, int end) { 464 return xmlFragment.subSequence(start, end); 465 } 466 } 467 468 public XmlStringBuilder xmlnsAttribute(String value) { 469 if (value == null || (effectiveXmlEnvironment != null 470 && effectiveXmlEnvironment.effectiveNamespaceEquals(value))) { 471 return this; 472 } 473 XmlNsAttribute xmlNsAttribute = new XmlNsAttribute(value); 474 append(xmlNsAttribute); 475 return this; 476 } 477 478 public XmlStringBuilder xmllangAttribute(String value) { 479 // TODO: This should probably be attribute(), not optAttribute(). 480 optAttribute("xml:lang", value); 481 return this; 482 } 483 484 public XmlStringBuilder optXmlLangAttribute(String lang) { 485 if (!StringUtils.isNullOrEmpty(lang)) { 486 xmllangAttribute(lang); 487 } 488 return this; 489 } 490 491 public XmlStringBuilder text(CharSequence text) { 492 assert text != null; 493 CharSequence escapedText = StringUtils.escapeForXmlText(text); 494 sb.append(escapedText); 495 return this; 496 } 497 498 public XmlStringBuilder escape(String text) { 499 assert text != null; 500 sb.append(StringUtils.escapeForXml(text)); 501 return this; 502 } 503 504 public XmlStringBuilder escapeAttributeValue(String value) { 505 assert value != null; 506 sb.append(StringUtils.escapeForXmlAttributeApos(value)); 507 return this; 508 } 509 510 public XmlStringBuilder optEscape(CharSequence text) { 511 if (text == null) { 512 return this; 513 } 514 return escape(text); 515 } 516 517 public XmlStringBuilder escape(CharSequence text) { 518 return escape(text.toString()); 519 } 520 521 protected XmlStringBuilder prelude(FullyQualifiedElement pe) { 522 return prelude(pe.getElementName(), pe.getNamespace()); 523 } 524 525 protected XmlStringBuilder prelude(String elementName, String namespace) { 526 halfOpenElement(elementName); 527 xmlnsAttribute(namespace); 528 return this; 529 } 530 531 public XmlStringBuilder optAppend(Element element) { 532 if (element != null) { 533 append(element.toXML(effectiveXmlEnvironment)); 534 } 535 return this; 536 } 537 538 public XmlStringBuilder optAppend(Collection<? extends Element> elements) { 539 if (elements != null) { 540 append(elements); 541 } 542 return this; 543 } 544 545 public XmlStringBuilder optTextChild(CharSequence sqc, NamedElement parentElement) { 546 if (sqc == null) { 547 return closeEmptyElement(); 548 } 549 rightAngleBracket(); 550 escape(sqc); 551 closeElement(parentElement); 552 return this; 553 } 554 555 public XmlStringBuilder append(XmlStringBuilder xsb) { 556 assert xsb != null; 557 sb.append(xsb.sb); 558 return this; 559 } 560 561 public XmlStringBuilder append(Element element) { 562 return append(element.toXML(effectiveXmlEnvironment)); 563 } 564 565 public XmlStringBuilder append(Collection<? extends Element> elements) { 566 for (Element element : elements) { 567 append(element); 568 } 569 return this; 570 } 571 572 public XmlStringBuilder emptyElement(Enum<?> element) { 573 // Use Enum.toString() instead Enum.name() here, since some enums override toString() in order to replace 574 // underscores ('_') with dash ('-') for example (name() is declared final in Enum). 575 return emptyElement(element.toString()); 576 } 577 578 public XmlStringBuilder emptyElement(String element) { 579 halfOpenElement(element); 580 return closeEmptyElement(); 581 } 582 583 public XmlStringBuilder condEmptyElement(boolean condition, String element) { 584 if (condition) { 585 emptyElement(element); 586 } 587 return this; 588 } 589 590 public XmlStringBuilder condAttribute(boolean condition, String name, String value) { 591 if (condition) { 592 attribute(name, value); 593 } 594 return this; 595 } 596 597 @Override 598 public XmlStringBuilder append(CharSequence csq) { 599 assert csq != null; 600 sb.append(csq); 601 return this; 602 } 603 604 @Override 605 public XmlStringBuilder append(CharSequence csq, int start, int end) { 606 assert csq != null; 607 sb.append(csq, start, end); 608 return this; 609 } 610 611 @Override 612 public XmlStringBuilder append(char c) { 613 sb.append(c); 614 return this; 615 } 616 617 @Override 618 public int length() { 619 return sb.length(); 620 } 621 622 @Override 623 public char charAt(int index) { 624 return sb.charAt(index); 625 } 626 627 @Override 628 public CharSequence subSequence(int start, int end) { 629 return sb.subSequence(start, end); 630 } 631 632 @Override 633 public String toString() { 634 return sb.toString(); 635 } 636 637 @Override 638 public boolean equals(Object other) { 639 if (!(other instanceof CharSequence)) { 640 return false; 641 } 642 CharSequence otherCharSequenceBuilder = (CharSequence) other; 643 return toString().equals(otherCharSequenceBuilder.toString()); 644 } 645 646 @Override 647 public int hashCode() { 648 return toString().hashCode(); 649 } 650 651 private static final class WrappedIoException extends RuntimeException { 652 653 private static final long serialVersionUID = 1L; 654 655 private final IOException wrappedIoException; 656 657 private WrappedIoException(IOException wrappedIoException) { 658 this.wrappedIoException = wrappedIoException; 659 } 660 } 661 662 /** 663 * Write the contents of this <code>XmlStringBuilder</code> to a {@link Writer}. This will write 664 * the single parts one-by-one, avoiding allocation of a big continuous memory block holding the 665 * XmlStringBuilder contents. 666 * 667 * @param writer TODO javadoc me please 668 * @param enclosingXmlEnvironment the enclosing XML environment. 669 * @throws IOException if an I/O error occurred. 670 */ 671 public void write(Writer writer, XmlEnvironment enclosingXmlEnvironment) throws IOException { 672 try { 673 appendXmlTo(csq -> { 674 try { 675 writer.append(csq); 676 } catch (IOException e) { 677 throw new WrappedIoException(e); 678 } 679 }, enclosingXmlEnvironment); 680 } catch (WrappedIoException e) { 681 throw e.wrappedIoException; 682 } 683 } 684 685 public List<CharSequence> toList(XmlEnvironment enclosingXmlEnvironment) { 686 List<CharSequence> res = new ArrayList<>(sb.getAsList().size()); 687 688 appendXmlTo(csq -> res.add(csq), enclosingXmlEnvironment); 689 690 return res; 691 } 692 693 @Override 694 public StringBuilder toXML(XmlEnvironment enclosingXmlEnvironment) { 695 // This is only the potential length, since the actual length depends on the given XmlEnvironment. 696 int potentialLength = length(); 697 StringBuilder res = new StringBuilder(potentialLength); 698 699 appendXmlTo(csq -> res.append(csq), enclosingXmlEnvironment); 700 701 return res; 702 } 703 704 private void appendXmlTo(Consumer<CharSequence> charSequenceSink, XmlEnvironment enclosingXmlEnvironment) { 705 for (CharSequence csq : sb.getAsList()) { 706 if (csq instanceof XmlStringBuilder) { 707 ((XmlStringBuilder) csq).appendXmlTo(charSequenceSink, enclosingXmlEnvironment); 708 } 709 else if (csq instanceof XmlNsAttribute) { 710 XmlNsAttribute xmlNsAttribute = (XmlNsAttribute) csq; 711 if (!xmlNsAttribute.value.equals(enclosingXmlEnvironment.getEffectiveNamespace())) { 712 charSequenceSink.accept(xmlNsAttribute); 713 enclosingXmlEnvironment = new XmlEnvironment(xmlNsAttribute.value); 714 } 715 } 716 else { 717 charSequenceSink.accept(csq); 718 } 719 } 720 } 721}