1 package org.apache.maven.plugins.shade.resource;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.StringReader;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.jar.JarEntry;
28 import java.util.jar.JarOutputStream;
29
30 import org.apache.maven.plugins.shade.relocation.Relocator;
31 import org.jdom2.Attribute;
32 import org.jdom2.Content;
33 import org.jdom2.Document;
34 import org.jdom2.Element;
35 import org.jdom2.JDOMException;
36 import org.jdom2.input.SAXBuilder;
37 import org.jdom2.output.Format;
38 import org.jdom2.output.XMLOutputter;
39 import org.xml.sax.EntityResolver;
40 import org.xml.sax.InputSource;
41 import org.xml.sax.SAXException;
42
43
44
45
46 public class XmlAppendingTransformer
47 extends AbstractCompatibilityTransformer
48 {
49 public static final String XSI_NS = "http://www.w3.org/2001/XMLSchema-instance";
50
51 boolean ignoreDtd = true;
52
53 String resource;
54
55 Document doc;
56
57 private long time = Long.MIN_VALUE;
58
59 public boolean canTransformResource( String r )
60 {
61 return resource != null && resource.equalsIgnoreCase( r );
62 }
63
64 public void processResource( String resource, InputStream is, List<Relocator> relocators, long time )
65 throws IOException
66 {
67 Document r;
68 try
69 {
70 SAXBuilder builder = new SAXBuilder( false );
71 builder.setExpandEntities( false );
72 if ( ignoreDtd )
73 {
74 builder.setEntityResolver( new EntityResolver()
75 {
76 public InputSource resolveEntity( String publicId, String systemId )
77 throws SAXException, IOException
78 {
79 return new InputSource( new StringReader( "" ) );
80 }
81 } );
82 }
83 r = builder.build( is );
84 }
85 catch ( JDOMException e )
86 {
87 throw new RuntimeException( "Error processing resource " + resource + ": " + e.getMessage(), e );
88 }
89
90 if ( doc == null )
91 {
92 doc = r;
93 }
94 else
95 {
96 Element root = r.getRootElement();
97
98 for ( Iterator<Attribute> itr = root.getAttributes().iterator(); itr.hasNext(); )
99 {
100 Attribute a = itr.next();
101 itr.remove();
102
103 Element mergedEl = doc.getRootElement();
104 Attribute mergedAtt = mergedEl.getAttribute( a.getName(), a.getNamespace() );
105 if ( mergedAtt == null )
106 {
107 mergedEl.setAttribute( a );
108 }
109 }
110
111 for ( Iterator<Element> itr = root.getChildren().iterator(); itr.hasNext(); )
112 {
113 Content n = itr.next();
114 itr.remove();
115
116 doc.getRootElement().addContent( n );
117 }
118 }
119
120 if ( time > this.time )
121 {
122 this.time = time;
123 }
124 }
125
126 public boolean hasTransformedResource()
127 {
128 return doc != null;
129 }
130
131 public void modifyOutputStream( JarOutputStream jos )
132 throws IOException
133 {
134 JarEntry jarEntry = new JarEntry( resource );
135 jarEntry.setTime( time );
136 jos.putNextEntry( jarEntry );
137
138 new XMLOutputter( Format.getPrettyFormat() ).output( doc, jos );
139
140 doc = null;
141 }
142 }