1 package com.atlassian.plugins.codegen.util;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.util.List;
7
8 import com.atlassian.fugue.Option;
9 import com.atlassian.plugins.codegen.modules.PluginModuleLocation;
10
11 import org.dom4j.Document;
12 import org.dom4j.DocumentException;
13 import org.dom4j.Element;
14 import org.dom4j.io.SAXReader;
15
16 import static com.atlassian.fugue.Option.none;
17 import static com.atlassian.fugue.Option.some;
18
19
20
21
22 public class PluginXmlHelper
23 {
24 private final File xmlFile;
25 private final Document document;
26 private final PluginModuleLocation location;
27
28 public PluginXmlHelper(PluginModuleLocation location) throws IOException, DocumentException
29 {
30 this(location, "atlassian-plugin.xml");
31 }
32
33 public PluginXmlHelper(PluginModuleLocation location, String fileName) throws IOException, DocumentException
34 {
35 this.location = location;
36 this.xmlFile = new File(location.getResourcesDir(), fileName);
37
38 final SAXReader reader = new SAXReader();
39 reader.setMergeAdjacentText(true);
40 reader.setStripWhitespaceText(false);
41 this.document = reader.read(new FileInputStream(xmlFile));
42 }
43
44 public Document getDocument()
45 {
46 return document;
47 }
48
49 public File getXmlFile()
50 {
51 return xmlFile;
52 }
53
54 public String getPluginKey()
55 {
56 String key = document.getRootElement().attributeValue("key");
57 if (key == null)
58 {
59 throw new IllegalStateException("atlassian-plugin element does not have required attribute: key");
60 }
61 return key.replace("${project.groupId}", location.getGroupId()).replace("${project.artifactId}", location.getArtifactId());
62 }
63
64 public String getDefaultI18nName()
65 {
66 return "i18n";
67 }
68
69 @SuppressWarnings("unchecked")
70 public String getDefaultI18nLocation()
71 {
72 List<Element> i18nElements = (List<Element>) document.selectNodes("//resource[@type='i18n']");
73 if (!i18nElements.isEmpty())
74 {
75 return i18nElements.get(0).attributeValue("location");
76 }
77 return getPluginKey();
78 }
79
80 @SuppressWarnings("unchecked")
81 public static Option<Element> findElementByTypeAndAttribute(Element parent, String type, String attributeName, String attributeValue)
82 {
83 for (Element e : (List<Element>) parent.elements(type))
84 {
85 if (attributeValue.equals(e.attributeValue(attributeName)))
86 {
87 return some(e);
88 }
89 }
90 return none();
91 }
92 }