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