1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.project;
20
21 import java.io.BufferedInputStream;
22 import java.io.File;
23 import java.io.FileInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.jar.JarFile;
29 import java.util.zip.ZipEntry;
30 import org.apache.maven.api.xml.Dom;
31 import org.apache.maven.internal.xml.Xpp3DomBuilder;
32 import org.codehaus.plexus.util.ReaderFactory;
33 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
34
35
36
37
38
39
40 public class ExtensionDescriptorBuilder {
41
42
43
44
45 public String getExtensionDescriptorLocation() {
46 return "META-INF/maven/extension.xml";
47 }
48
49
50
51
52
53
54
55
56 public ExtensionDescriptor build(File extensionJar) throws IOException {
57 ExtensionDescriptor extensionDescriptor = null;
58
59 if (extensionJar.isFile()) {
60 try (JarFile pluginJar = new JarFile(extensionJar, false)) {
61 ZipEntry pluginDescriptorEntry = pluginJar.getEntry(getExtensionDescriptorLocation());
62
63 if (pluginDescriptorEntry != null) {
64 try (InputStream is = pluginJar.getInputStream(pluginDescriptorEntry)) {
65 extensionDescriptor = build(is);
66 }
67 }
68 }
69 } else {
70 File pluginXml = new File(extensionJar, getExtensionDescriptorLocation());
71
72 if (pluginXml.canRead()) {
73 try (InputStream is = new BufferedInputStream(new FileInputStream(pluginXml))) {
74 extensionDescriptor = build(is);
75 }
76 }
77 }
78
79 return extensionDescriptor;
80 }
81
82
83
84
85 public ExtensionDescriptor build(InputStream is) throws IOException {
86 ExtensionDescriptor extensionDescriptor = new ExtensionDescriptor();
87
88 Dom dom;
89 try {
90 dom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(is));
91 } catch (XmlPullParserException e) {
92 throw new IOException(e.getMessage(), e);
93 }
94
95 if (!"extension".equals(dom.getName())) {
96 throw new IOException("Unexpected root element \"" + dom.getName() + "\", expected \"extension\"");
97 }
98
99 extensionDescriptor.setExportedPackages(parseStrings(dom.getChild("exportedPackages")));
100
101 extensionDescriptor.setExportedArtifacts(parseStrings(dom.getChild("exportedArtifacts")));
102
103 return extensionDescriptor;
104 }
105
106 private List<String> parseStrings(Dom dom) {
107 List<String> strings = null;
108
109 if (dom != null) {
110 strings = new ArrayList<>();
111
112 for (Dom child : dom.getChildren()) {
113 String string = child.getValue();
114 if (string != null) {
115 string = string.trim();
116 if (string.length() > 0) {
117 strings.add(string);
118 }
119 }
120 }
121 }
122
123 return strings;
124 }
125 }