1
2
3
4
5
6
7
8
9
10
11
12
13
14 package net.sf.maven.plugins.eclipseformat;
15
16 import java.io.File;
17 import java.io.FileInputStream;
18 import java.io.InputStream;
19 import java.util.Properties;
20
21 import javax.xml.parsers.SAXParser;
22 import javax.xml.parsers.SAXParserFactory;
23
24 import org.apache.maven.plugin.MojoExecutionException;
25 import org.apache.maven.plugin.logging.Log;
26
27 import org.codehaus.plexus.util.IOUtil;
28 import org.codehaus.plexus.util.StringUtils;
29
30 import org.xml.sax.Attributes;
31 import org.xml.sax.helpers.DefaultHandler;
32
33
34
35
36
37
38 class ConfigReader extends DefaultHandler {
39
40 private static final String SETTING_NODE_NAME = "setting";
41 private static final String ID_ATTR_NAME = "id";
42 private static final String VALUE_ATTR_NAME = "value";
43 private final Properties properties;
44 private final Log log;
45 private final String defaultConfig;
46 private final String alternativeConfig;
47 private final boolean failOnError;
48
49
50
51
52
53
54
55
56
57
58
59
60
61 public ConfigReader(final Log log, final String defaultConfig, final String alternativeConfig,
62 final boolean failOnError) {
63 super();
64 this.properties = new Properties();
65 this.log = log;
66 this.defaultConfig = defaultConfig;
67 this.alternativeConfig = alternativeConfig;
68 this.failOnError = failOnError;
69 }
70
71
72
73
74 public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) {
75 if (SETTING_NODE_NAME.equals(qName)) {
76 String key = attributes.getValue(ID_ATTR_NAME);
77
78 if (StringUtils.isNotBlank(key)) {
79 String value = attributes.getValue(VALUE_ATTR_NAME);
80
81 if (StringUtils.isNotBlank(value)) {
82 properties.put(key.trim(), value);
83 }
84 }
85 }
86 }
87
88
89
90
91
92
93
94
95 public Properties getProperties() throws MojoExecutionException {
96 synchronized (properties) {
97
98 InputStream inputStream = null;
99
100 try {
101
102
103 if (StringUtils.isNotBlank(alternativeConfig)) {
104 File configFile = new File(alternativeConfig);
105 if (configFile.exists()) {
106 inputStream = new FileInputStream(configFile);
107 } else {
108 inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(
109 alternativeConfig);
110 }
111 }
112
113
114 if (inputStream == null) {
115 inputStream = getClass().getResourceAsStream(defaultConfig);
116 }
117
118 try {
119 SAXParser sparser = SAXParserFactory.newInstance().newSAXParser();
120 sparser.parse(inputStream, this);
121 } finally {
122 IOUtil.close(inputStream);
123 }
124
125 } catch (Exception e) {
126 log.error("Error reading XML config", e);
127 if (failOnError) {
128 throw new MojoExecutionException("Error reading XML config", e);
129 }
130 }
131 }
132
133 return properties;
134 }
135 }