-
Notifications
You must be signed in to change notification settings - Fork 99
/
MavenUtils.java
317 lines (263 loc) · 12.8 KB
/
MavenUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.kafkaconnector.maven.utils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Stream;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import freemarker.cache.URLTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.camel.tooling.util.PackageHelper;
import org.apache.camel.tooling.util.srcgen.JavaClass;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import static org.apache.camel.maven.packaging.AbstractGeneratorMojo.updateResource;
public final class MavenUtils {
private MavenUtils() {
}
public static void addExclusionsToDependency(Document pom, String targetDependency, Set<String> colonSeparatedDependeciesToExclude, String generatedSectionStartMarker, String generatedSectionStopMarker) throws XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
Node dependency = ((NodeList) xpath.compile("/project/dependencies/dependency[artifactId/text() = '" + targetDependency + "']").evaluate(pom, XPathConstants.NODESET)).item(0);
Element exclusions = pom.createElement("exclusions");
dependency.appendChild(pom.createComment(generatedSectionStartMarker));
dependency.appendChild(exclusions);
dependency.appendChild(pom.createComment(generatedSectionStopMarker));
for (String dep : colonSeparatedDependeciesToExclude) {
String[] tokens = dep.split("\\:");
String groupIdStr = tokens[0];
String artifactIdStr = tokens[1];
Element exclusion = pom.createElement("exclusion");
Element groupId = pom.createElement("groupId");
groupId.setTextContent(groupIdStr);
exclusion.appendChild(groupId);
Element artifactId = pom.createElement("artifactId");
artifactId.setTextContent(artifactIdStr);
exclusion.appendChild(artifactId);
exclusions.appendChild(exclusion);
}
}
public static String removeGeneratedSections(String pom, String generatedSectionStartMarker, String generatedSectionStopMarker, int maxNumberOfOccurrences) {
if (maxNumberOfOccurrences > 0 && pom.contains(generatedSectionStartMarker)) {
int start = pom.indexOf(generatedSectionStartMarker);
int end = pom.indexOf(generatedSectionStopMarker);
if (end <= start) {
throw new IllegalArgumentException("Generated sections inside the xml document are not well-formed");
}
String newPom = pom.substring(0, start) + pom.substring(end + generatedSectionStopMarker.length());
return removeGeneratedSections(newPom, generatedSectionStartMarker, generatedSectionStopMarker, maxNumberOfOccurrences - 1);
}
return pom;
}
public static void writeFileIfChanged(String newContent, File file, Log log) throws IOException {
boolean write = true;
file = file.getCanonicalFile();
if (file.exists()) {
try (FileReader fr = new FileReader(file)) {
String oldContent = IOUtils.toString(fr);
if (!newContent.equals(oldContent)) {
log.debug("Writing new file " + file.getAbsolutePath());
} else {
log.debug("File " + file.getAbsolutePath() + " has been left unchanged");
write = false;
}
}
} else {
// Create the structure
File parent = file.getParentFile();
parent.mkdirs();
}
if (write) {
try (FileWriter fw = new FileWriter(file)) {
IOUtils.write(newContent, fw);
}
}
}
public static void writeXmlFormatted(Document pom, File destination, Log log) throws Exception {
XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//text()[normalize-space(.) = '']");
NodeList emptyNodes = (NodeList) xpath.evaluate(pom, XPathConstants.NODESET);
// Remove empty text nodes
for (int i = 0; i < emptyNodes.getLength(); i++) {
Node emptyNode = emptyNodes.item(i);
emptyNode.getParentNode().removeChild(emptyNode);
}
pom.setXmlStandalone(true);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(pom);
String content;
try (StringWriter out = new StringWriter()) {
StreamResult result = new StreamResult(out);
transformer.transform(source, result);
content = out.toString();
}
// Fix header formatting problem
content = content.replaceFirst("-->", "-->\n").replaceFirst("\\?><!--", "\\?>\n<!--");
writeFileIfChanged(content, destination, log);
}
public static void addDependencies(Document pom, Set<String> deps, String generatedSectionStartMarker, String generatedSectionStopMarker) throws XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
Node dependencies = ((NodeList) xpath.compile("/project/dependencies").evaluate(pom, XPathConstants.NODESET)).item(0);
if (!deps.isEmpty()) {
dependencies.appendChild(pom.createComment(generatedSectionStartMarker));
for (String dep : deps) {
Element dependency = pom.createElement("dependency");
dependencies.appendChild(dependency);
String[] comps = dep.split("\\:");
String groupIdStr = comps[0];
String artifactIdStr = comps[1];
String versionStr = comps.length > 2 && !comps[2].isEmpty() ? comps[2] : null;
String scopeStr = comps.length > 3 ? comps[3] : null;
Element groupId = pom.createElement("groupId");
groupId.setTextContent(groupIdStr);
dependency.appendChild(groupId);
Element artifactId = pom.createElement("artifactId");
artifactId.setTextContent(artifactIdStr);
dependency.appendChild(artifactId);
if (versionStr != null) {
Element version = pom.createElement("version");
version.setTextContent(versionStr);
dependency.appendChild(version);
}
if (scopeStr != null) {
Element scope = pom.createElement("scope");
scope.setTextContent(scopeStr);
dependency.appendChild(scope);
}
}
dependencies.appendChild(pom.createComment(generatedSectionStopMarker));
}
}
public static <T> Stream<T> concat(Stream<T> s1, Stream<T> s2, Stream<T> s3) {
return Stream.concat(s1, Stream.concat(s2, s3));
}
public static Document createCrateXmlDocumentFromTemplate(Template template, Map<String, String> props) throws IOException, TemplateException, ParserConfigurationException, SAXException {
StringWriter sw = new StringWriter();
template.process(props, sw);
String xml = sw.toString();
ByteArrayInputStream bin = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return builder.parse(bin);
}
public static Template getTemplate(File templateFile) throws IOException {
Configuration cfg = new Configuration(Configuration.getVersion());
cfg.setTemplateLoader(new URLTemplateLoader() {
@Override
protected URL getURL(String name) {
try {
return new URL(name);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
});
cfg.setDefaultEncoding("UTF-8");
cfg.setLocalizedLookup(false);
Template template = cfg.getTemplate(templateFile.toURI().toURL().toExternalForm());
return template;
}
public static Set<String> csvToSet(String csv) {
if (csv == null || csv.trim().length() == 0) {
return new TreeSet<>();
}
Set<String> set = new TreeSet<>();
for (String s : csv.split(",")) {
set.add(s.trim());
}
return set;
}
public static void writeSourceIfChanged(JavaClass source, String fileName, boolean innerClassesLast, File baseDir, File javaFileHeader) throws MojoFailureException {
writeSourceIfChanged(source.printClass(innerClassesLast), fileName, baseDir, javaFileHeader);
}
public static void writeSourceIfChanged(String source, String fileName, File baseDir, File javaFileHeader) throws MojoFailureException {
File target = new File(new File(baseDir, "src/main/java"), fileName);
if (target.exists()) {
try {
if (!FileUtils.readFileToString(target).contains("@Generated")) {
// Do not write class if a class already exists and has no @Generated annotation
return;
}
} catch (IOException ioe) {
throw new MojoFailureException("IO error trying to read whether " + target.toString() + " contains @Generated annotation", ioe);
}
}
deleteFile(baseDir, target);
try {
String header;
try (InputStream is = new FileInputStream(javaFileHeader)) {
header = PackageHelper.loadText(is);
}
String code = header + source;
updateResource(null, target.toPath(), code);
} catch (Exception e) {
throw new MojoFailureException("IOError with file " + target, e);
}
}
public static void deleteFile(File baseDir, File targetFile) {
String relativePath = baseDir.toPath().relativize(targetFile.toPath()).toString();
File mainArtifactFile = new File(baseDir, relativePath);
if (mainArtifactFile.exists()) {
try {
Files.delete(mainArtifactFile.toPath());
} catch (IOException e) {
throw new IllegalStateException("Cannot delete file " + mainArtifactFile, e);
}
}
}
public static String sanitizeMavenArtifactId(String toBesanitizedArtifactId) {
return toBesanitizedArtifactId != null ? toBesanitizedArtifactId.toLowerCase().replaceAll("[^A-Za-z0-9]", "-") : null;
}
}