1 package org.codehaus.plexus.metadata.merge;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 import java.io.File;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.OutputStreamWriter;
28 import java.io.Writer;
29 import java.util.List;
30
31 import org.codehaus.plexus.util.IOUtil;
32 import org.jdom2.Document;
33 import org.jdom2.JDOMException;
34 import org.jdom2.input.SAXBuilder;
35 import org.jdom2.input.sax.XMLReaderSAX2Factory;
36 import org.jdom2.output.XMLOutputter;
37
38
39
40
41
42
43 public abstract class AbstractMerger implements Merger {
44
45
46
47
48 public void writeMergedDocument(Document mergedDocument, File file) throws IOException {
49 if (!file.getParentFile().exists()) {
50 file.getParentFile().mkdirs();
51 }
52
53 XMLOutputter out = new XMLOutputter();
54 Writer fw = null;
55 try {
56 fw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
57 out.output(mergedDocument, fw);
58 } finally {
59 IOUtil.close(fw);
60 }
61 }
62
63 public void mergeDescriptors(File outputDescriptor, List<File> descriptors) throws IOException {
64 SAXBuilder builder = new SAXBuilder(new XMLReaderSAX2Factory(false, Driver.class.getName()));
65
66 Document finalDoc = null;
67
68 for (File f : descriptors) {
69 try {
70 Document doc = builder.build(f);
71
72 if (finalDoc != null) {
73
74 finalDoc = merge(doc, finalDoc);
75 } else {
76 finalDoc = doc;
77 }
78 } catch (JDOMException e) {
79 throw new IOException("Invalid input descriptor for merge: " + f + " --> " + e.getMessage());
80 } catch (MergeException e) {
81 throw new IOException("Error merging descriptor: " + f + " --> " + e.getMessage());
82 }
83 }
84
85 if (finalDoc != null) {
86 try {
87 writeMergedDocument(finalDoc, outputDescriptor);
88 } catch (IOException e) {
89 throw new IOException("Error writing merged descriptor: " + outputDescriptor);
90 }
91 }
92 }
93 }