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.NamedElement;
028import org.jivesoftware.smack.packet.XmlElement;
029import org.jivesoftware.smack.packet.XmlEnvironment;
030
031import org.jxmpp.util.XmppDateTime;
032
033public class XmlStringBuilder implements Appendable, CharSequence, Element {
034    public static final String RIGHT_ANGLE_BRACKET = Character.toString('>');
035
036    private final LazyStringBuilder sb;
037
038    private final XmlEnvironment effectiveXmlEnvironment;
039
040    public XmlStringBuilder() {
041        sb = new LazyStringBuilder();
042        effectiveXmlEnvironment = null;
043    }
044
045    public XmlStringBuilder(XmlElement pe) {
046        this(pe, null);
047    }
048
049    public XmlStringBuilder(NamedElement e) {
050        this();
051        halfOpenElement(e.getElementName());
052    }
053
054    public XmlStringBuilder(XmlElement element, XmlEnvironment enclosingXmlEnvironment) {
055        this(element.getElementName(), element.getNamespace(), element.getLanguage(), enclosingXmlEnvironment);
056    }
057
058    public XmlStringBuilder(String elementName, String xmlNs, String xmlLang, XmlEnvironment enclosingXmlEnvironment) {
059        sb = new LazyStringBuilder();
060        halfOpenElement(elementName);
061
062        if (enclosingXmlEnvironment == null) {
063            xmlnsAttribute(xmlNs);
064            xmllangAttribute(xmlLang);
065        } else {
066            if (!enclosingXmlEnvironment.effectiveNamespaceEquals(xmlNs)) {
067                xmlnsAttribute(xmlNs);
068            }
069            if (!enclosingXmlEnvironment.effectiveLanguageEquals(xmlLang)) {
070                xmllangAttribute(xmlLang);
071            }
072        }
073
074        effectiveXmlEnvironment = XmlEnvironment.builder()
075                .withNamespace(xmlNs)
076                .withLanguage(xmlLang)
077                .withNext(enclosingXmlEnvironment)
078                .build();
079    }
080
081    public XmlEnvironment getXmlEnvironment() {
082        return effectiveXmlEnvironment;
083    }
084
085    public XmlStringBuilder escapedElement(String name, String escapedContent) {
086        assert escapedContent != null;
087        openElement(name);
088        append(escapedContent);
089        closeElement(name);
090        return this;
091    }
092
093    /**
094     * Add a new element to this builder.
095     *
096     * @param name TODO javadoc me please
097     * @param content TODO javadoc me please
098     * @return the XmlStringBuilder
099     */
100    public XmlStringBuilder element(String name, String content) {
101        if (content.isEmpty()) {
102            return emptyElement(name);
103        }
104        openElement(name);
105        escape(content);
106        closeElement(name);
107        return this;
108    }
109
110    /**
111     * Add a new element to this builder, with the {@link java.util.Date} instance as its content,
112     * which will get formatted with {@link XmppDateTime#formatXEP0082Date(Date)}.
113     *
114     * @param name element name
115     * @param content content of element
116     * @return this XmlStringBuilder
117     */
118    public XmlStringBuilder element(String name, Date content) {
119        assert content != null;
120        return element(name, XmppDateTime.formatXEP0082Date(content));
121    }
122
123   /**
124    * Add a new element to this builder.
125    *
126    * @param name TODO javadoc me please
127    * @param content TODO javadoc me please
128    * @return the XmlStringBuilder
129    */
130   public XmlStringBuilder element(String name, CharSequence content) {
131       return element(name, content.toString());
132   }
133
134    public XmlStringBuilder element(String name, Enum<?> content) {
135        assert content != null;
136        element(name, content.toString());
137        return this;
138    }
139
140    /**
141     * Deprecated.
142     *
143     * @param element deprecated.
144     * @return deprecated.
145     * @deprecated use {@link #append(Element)} instead.
146     */
147    @Deprecated
148    // TODO: Remove in Smack 4.5.
149    public XmlStringBuilder element(Element element) {
150        assert element != null;
151        return append(element.toXML());
152    }
153
154    public XmlStringBuilder optElement(String name, String content) {
155        if (content != null) {
156            element(name, content);
157        }
158        return this;
159    }
160
161    /**
162     * Add a new element to this builder, with the {@link java.util.Date} instance as its content,
163     * which will get formatted with {@link XmppDateTime#formatXEP0082Date(Date)}
164     * if {@link java.util.Date} instance is not <code>null</code>.
165     *
166     * @param name element name
167     * @param content content of element
168     * @return this XmlStringBuilder
169     */
170    public XmlStringBuilder optElement(String name, Date content) {
171        if (content != null) {
172            element(name, content);
173        }
174        return this;
175    }
176
177    public XmlStringBuilder optElement(String name, CharSequence content) {
178        if (content != null) {
179            element(name, content.toString());
180        }
181        return this;
182    }
183
184    public XmlStringBuilder optElement(Element element) {
185        if (element != null) {
186            append(element);
187        }
188        return this;
189    }
190
191    public XmlStringBuilder optElement(String name, Enum<?> content) {
192        if (content != null) {
193            element(name, content);
194        }
195        return this;
196    }
197
198    public XmlStringBuilder optElement(String name, Object object) {
199        if (object != null) {
200            element(name, object.toString());
201        }
202        return this;
203    }
204
205    public XmlStringBuilder optIntElement(String name, int value) {
206        if (value >= 0) {
207            element(name, String.valueOf(value));
208        }
209        return this;
210    }
211
212    public XmlStringBuilder halfOpenElement(String name) {
213        assert StringUtils.isNotEmpty(name);
214        sb.append('<').append(name);
215        return this;
216    }
217
218    public XmlStringBuilder halfOpenElement(NamedElement namedElement) {
219        return halfOpenElement(namedElement.getElementName());
220    }
221
222    public XmlStringBuilder openElement(String name) {
223        halfOpenElement(name).rightAngleBracket();
224        return this;
225    }
226
227    public XmlStringBuilder closeElement(String name) {
228        sb.append("</").append(name);
229        rightAngleBracket();
230        return this;
231    }
232
233    public XmlStringBuilder closeElement(NamedElement e) {
234        closeElement(e.getElementName());
235        return this;
236    }
237
238    public XmlStringBuilder closeEmptyElement() {
239        sb.append("/>");
240        return this;
241    }
242
243    /**
244     * Add a right angle bracket '&gt;'.
245     *
246     * @return a reference to this object.
247     */
248    public XmlStringBuilder rightAngleBracket() {
249        sb.append(RIGHT_ANGLE_BRACKET);
250        return this;
251    }
252
253    /**
254     * Does nothing if value is null.
255     *
256     * @param name TODO javadoc me please
257     * @param value TODO javadoc me please
258     * @return the XmlStringBuilder
259     */
260    public XmlStringBuilder attribute(String name, String value) {
261        assert value != null;
262        sb.append(' ').append(name).append("='");
263        escapeAttributeValue(value);
264        sb.append('\'');
265        return this;
266    }
267
268    public XmlStringBuilder attribute(String name, boolean bool) {
269        return attribute(name, Boolean.toString(bool));
270    }
271
272    /**
273     * Add a new attribute to this builder, with the {@link java.util.Date} instance as its value,
274     * which will get formatted with {@link XmppDateTime#formatXEP0082Date(Date)}.
275     *
276     * @param name name of attribute
277     * @param value value of attribute
278     * @return this XmlStringBuilder
279     */
280    public XmlStringBuilder attribute(String name, Date value) {
281        assert value != null;
282        return attribute(name, XmppDateTime.formatXEP0082Date(value));
283    }
284
285    public XmlStringBuilder attribute(String name, CharSequence value) {
286        return attribute(name, value.toString());
287    }
288
289    public XmlStringBuilder attribute(String name, Enum<?> value) {
290        assert value != null;
291        // TODO: Should use toString() instead of name().
292        attribute(name, value.name());
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(XmlElement 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}