1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.shared.release.transform.jdom2;
20
21 import java.util.Iterator;
22
23 import org.jdom2.Element;
24 import org.jdom2.Namespace;
25 import org.jdom2.Text;
26
27
28
29
30
31
32
33 public final class JDomUtils {
34
35 private JDomUtils() {
36
37 }
38
39
40
41
42
43
44
45
46 public static void rewriteValue(Element element, String value) {
47 Text text = null;
48 if (element.getContent() != null) {
49 for (Iterator<?> it = element.getContent().iterator(); it.hasNext(); ) {
50 Object content = it.next();
51 if ((content instanceof Text) && ((Text) content).getTextTrim().length() > 0) {
52 text = (Text) content;
53 while (it.hasNext()) {
54 content = it.next();
55 if (content instanceof Text) {
56 text.append((Text) content);
57 it.remove();
58 } else {
59 break;
60 }
61 }
62 break;
63 }
64 }
65 }
66 if (text == null) {
67 element.addContent(value);
68 } else {
69 String chars = text.getText();
70 String trimmed = text.getTextTrim();
71 int idx = chars.indexOf(trimmed);
72 String leadingWhitespace = chars.substring(0, idx);
73 String trailingWhitespace = chars.substring(idx + trimmed.length());
74 text.setText(leadingWhitespace + value + trailingWhitespace);
75 }
76 }
77
78
79
80
81
82
83
84
85
86
87 public static Element rewriteElement(String name, String value, Element root, Namespace namespace) {
88 Element tagElement = root.getChild(name, namespace);
89 if (tagElement != null) {
90 if (value != null) {
91 rewriteValue(tagElement, value);
92 } else {
93 int index = root.indexOf(tagElement);
94 root.removeContent(index);
95 for (int i = index - 1; i >= 0; i--) {
96 if (root.getContent(i) instanceof Text) {
97 root.removeContent(i);
98 } else {
99 break;
100 }
101 }
102 }
103 } else {
104 if (value != null) {
105 Element element = new Element(name, namespace);
106 element.setText(value);
107 root.addContent(" ").addContent(element).addContent("\n ");
108 tagElement = element;
109 }
110 }
111 return tagElement;
112 }
113 }