1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.betwixt.strategy;
19
20 import org.apache.commons.betwixt.ElementDescriptor;
21 import org.apache.commons.betwixt.XMLUtils;
22
23 /***
24 * <p>Basic implementation for {@link MixedContentEncodingStrategy}
25 * supports variations of most common use case.
26 * </p>
27 * <p>This supports subclasses that choose to encode body content
28 * either as a <code>CDATA</code> section or by escaping the characters.
29 * Implementations should override {@link #encodeAsCDATA}
30 * with an appropriate decision algorithm.
31 * </p>
32 * @author <a href='http://jakarta.apache.org/'>Apache Commons Team</a>
33 * @since 0.5
34 */
35 public abstract class BaseMixedContentEncodingStrategy
36 extends MixedContentEncodingStrategy {
37
38 /***
39 * Escapes a sequence of body content.
40 * @param bodyContent the content whose character data should be escaped,
41 * not null
42 * @return the escaped character data, not null
43 */
44 protected String escapeCharacters(String bodyContent) {
45 return XMLUtils.escapeBodyValue(bodyContent);
46 }
47
48 /***
49 * Wraps the given content into a CDATA section.
50 * @param bodyContent the content to be encoded into a CDATA
51 * section
52 * @return the content wrapped inside a CDATA section, not null
53 */
54 protected String encodeInCDATA(String bodyContent) {
55 StringBuffer buffer = new StringBuffer(bodyContent);
56 buffer.ensureCapacity(12);
57 XMLUtils.escapeCDATAContent(buffer);
58 return buffer.insert(0, "<![CDATA[").append("]]>").toString();
59 }
60
61 /***
62 * Encodes the given body content by either escaping the character data
63 * or by encoding within a <code>CDATA</code> section.
64 * The algorithm used to decide whether a particular element's mixed
65 * should be escaped is delegated to the concrete subclass through
66 * {@link #encodeAsCDATA}
67 * @see org.apache.commons.betwixt.strategy.MixedContentEncodingStrategy#encode(java.lang.String, org.apache.commons.betwixt.ElementDescriptor)
68 */
69 public String encode(String bodyContent, ElementDescriptor element) {
70 if (encodeAsCDATA(element)) {
71 return encodeInCDATA(bodyContent);
72 }
73
74 return escapeCharacters(bodyContent);
75 }
76
77 /***
78 * <p>Should the element described by the given
79 * <code>ElementDescriptor</code> be encoded as a <code>CDATA</code>
80 * section?
81 * </p>
82 * <p><strong>Usage:</strong> subclasses should provide a strategy
83 * to determine whether an element should be encoded using a
84 * <code>CDATA</code> section.
85 * </p>
86 *
87 * @param element <code>ElementDescriptor</code>, not null
88 * @return true if the element should be encoded
89 * as a <code>CDATA</code> section
90 */
91 protected abstract boolean encodeAsCDATA(ElementDescriptor element);
92
93 }