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 implements ResourceTransformer
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 public boolean canTransformResource( String r )
58 {
59 if ( resource != null && resource.equalsIgnoreCase( r ) )
60 {
61 return true;
62 }
63
64 return false;
65 }
66
67 public void processResource( String resource, InputStream is, List<Relocator> relocators )
68 throws IOException
69 {
70 Document r;
71 try
72 {
73 SAXBuilder builder = new SAXBuilder( false );
74 builder.setExpandEntities( false );
75 if ( ignoreDtd )
76 {
77 builder.setEntityResolver( new EntityResolver()
78 {
79 public InputSource resolveEntity( String publicId, String systemId )
80 throws SAXException, IOException
81 {
82 return new InputSource( new StringReader( "" ) );
83 }
84 } );
85 }
86 r = builder.build( is );
87 }
88 catch ( JDOMException e )
89 {
90 throw new RuntimeException( "Error processing resource " + resource + ": " + e.getMessage(), e );
91 }
92
93 if ( doc == null )
94 {
95 doc = r;
96 }
97 else
98 {
99 Element root = r.getRootElement();
100
101 for ( Iterator<Attribute> itr = root.getAttributes().iterator(); itr.hasNext(); )
102 {
103 Attribute a = itr.next();
104 itr.remove();
105
106 Element mergedEl = doc.getRootElement();
107 Attribute mergedAtt = mergedEl.getAttribute( a.getName(), a.getNamespace() );
108 if ( mergedAtt == null )
109 {
110 mergedEl.setAttribute( a );
111 }
112 }
113
114 for ( Iterator<Element> itr = root.getChildren().iterator(); itr.hasNext(); )
115 {
116 Content n = itr.next();
117 itr.remove();
118
119 doc.getRootElement().addContent( n );
120 }
121 }
122 }
123
124 public boolean hasTransformedResource()
125 {
126 return doc != null;
127 }
128
129 public void modifyOutputStream( JarOutputStream jos )
130 throws IOException
131 {
132 jos.putNextEntry( new JarEntry( resource ) );
133
134 new XMLOutputter( Format.getPrettyFormat() ).output( doc, jos );
135
136 doc = null;
137 }
138 }