1 package com.atlassian.plugins.codegen.util;
2
3 import java.io.*;
4
5 import org.apache.commons.lang.Validate;
6 import org.dom4j.*;
7 import org.dom4j.io.OutputFormat;
8 import org.dom4j.io.SAXReader;
9 import org.dom4j.io.XMLWriter;
10
11
12
13
14 public class PluginXmlHelper
15 {
16
17 private final File pluginXml;
18 private final Document document;
19
20 public PluginXmlHelper(File pluginXml) throws Exception
21 {
22 Validate.notNull(pluginXml);
23 Validate.isTrue(pluginXml.exists());
24
25 this.pluginXml = pluginXml;
26
27 InputStream is = new FileInputStream(pluginXml);
28 this.document = createDocument(is);
29 }
30
31 public void addModuleAsLastChild(String fragment) throws Exception
32 {
33 try
34 {
35 Document fragDoc = DocumentHelper.parseText(fragment);
36 Element pluginRoot = document.getRootElement();
37 pluginRoot.add(fragDoc.getRootElement());
38 } catch (DocumentException e)
39 {
40 throw new Exception("Could not parse module XML fragment", e);
41 }
42 }
43
44 public void addI18nResource(String name) throws Exception
45 {
46 String xpath = "//resource[@type='i18n' and @location='" + name + "']";
47 Node resourceNode = document.selectSingleNode(xpath);
48
49 if (null == resourceNode)
50 {
51 Element pluginRoot = document.getRootElement();
52 Document fragDoc = DocumentHelper.parseText("<resource type=\"i18n\" name=\"i18n\" location=\"" + name + "\" />");
53 pluginRoot.add(fragDoc.getRootElement());
54 }
55 }
56
57 public void addPluginInfoParam(String name, String value) throws Exception
58 {
59 Element pluginInfo = (Element) document.selectSingleNode("//plugin-info");
60 if (pluginInfo == null)
61 {
62 pluginInfo = document.addElement("plugin-info");
63 }
64 pluginInfo.addElement("param").addAttribute("name", name).setText(value);
65 }
66
67 public String getPluginXmlAsString()
68 {
69 return document.asXML();
70 }
71
72 protected Document getDocument()
73 {
74 return document;
75 }
76
77 protected Document createDocument(final InputStream source) throws Exception
78 {
79 final SAXReader reader = new SAXReader();
80 reader.setMergeAdjacentText(true);
81 reader.setStripWhitespaceText(false);
82 try
83 {
84 return reader.read(source);
85 } catch (final DocumentException e)
86 {
87 throw new Exception("Cannot parse XML plugin descriptor", e);
88 }
89 }
90
91 public void savePluginXml() throws IOException
92 {
93 OutputFormat format = OutputFormat.createPrettyPrint();
94 XMLWriter writer = new XMLWriter(new FileWriter(pluginXml), format);
95
96 writer.write(document);
97 writer.close();
98 }
99 }