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.jdom.Attribute;
31 import org.jdom.Content;
32 import org.jdom.Document;
33 import org.jdom.Element;
34 import org.jdom.JDOMException;
35 import org.jdom.input.SAXBuilder;
36 import org.jdom.output.Format;
37 import org.jdom.output.XMLOutputter;
38 import org.xml.sax.EntityResolver;
39 import org.xml.sax.InputSource;
40 import org.xml.sax.SAXException;
41
42
43
44
45 public class XmlAppendingTransformer
46 implements ResourceTransformer
47 {
48 public static final String XSI_NS = "http://www.w3.org/2001/XMLSchema-instance";
49
50 boolean ignoreDtd = true;
51
52 String resource;
53
54 Document doc;
55
56 public boolean canTransformResource( String r )
57 {
58 if ( resource != null && resource.equalsIgnoreCase( r ) )
59 {
60 return true;
61 }
62
63 return false;
64 }
65
66 public void processResource( String resource, InputStream is, List relocators )
67 throws IOException
68 {
69 Document r;
70 try
71 {
72 SAXBuilder builder = new SAXBuilder( false );
73 builder.setExpandEntities( false );
74 if ( ignoreDtd )
75 {
76 builder.setEntityResolver( new EntityResolver()
77 {
78 public InputSource resolveEntity( String publicId, String systemId )
79 throws SAXException, IOException
80 {
81 return new InputSource( new StringReader( "" ) );
82 }
83 } );
84 }
85 r = builder.build( is );
86 }
87 catch ( JDOMException e )
88 {
89 throw new RuntimeException( "Error processing resource " + resource + ": " + e.getMessage(), e );
90 }
91
92 if ( doc == null )
93 {
94 doc = r;
95 }
96 else
97 {
98 Element root = r.getRootElement();
99
100 for ( Iterator itr = root.getAttributes().iterator(); itr.hasNext(); )
101 {
102 Attribute a = (Attribute) itr.next();
103 itr.remove();
104
105 Element mergedEl = doc.getRootElement();
106 Attribute mergedAtt = mergedEl.getAttribute( a.getName(), a.getNamespace() );
107 if ( mergedAtt == null )
108 {
109 mergedEl.setAttribute( a );
110 }
111 }
112
113 for ( Iterator itr = root.getChildren().iterator(); itr.hasNext(); )
114 {
115 Content n = (Content) itr.next();
116 itr.remove();
117
118 doc.getRootElement().addContent( n );
119 }
120 }
121 }
122
123 public boolean hasTransformedResource()
124 {
125 return doc != null;
126 }
127
128 public void modifyOutputStream( JarOutputStream jos )
129 throws IOException
130 {
131 jos.putNextEntry( new JarEntry( resource ) );
132
133 new XMLOutputter( Format.getPrettyFormat() ).output( doc, jos );
134
135 doc = null;
136 }
137 }