You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

XMLReader.java 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. package org.apache.archiva.xml;
  2. /*
  3. * Licensed to the Apache Software Foundation (ASF) under one
  4. * or more contributor license agreements. See the NOTICE file
  5. * distributed with this work for additional information
  6. * regarding copyright ownership. The ASF licenses this file
  7. * to you under the Apache License, Version 2.0 (the
  8. * "License"); you may not use this file except in compliance
  9. * with the License. You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing,
  14. * software distributed under the License is distributed on an
  15. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. * KIND, either express or implied. See the License for the
  17. * specific language governing permissions and limitations
  18. * under the License.
  19. */
  20. import org.apache.commons.lang.StringUtils;
  21. import org.dom4j.Attribute;
  22. import org.dom4j.Document;
  23. import org.dom4j.DocumentException;
  24. import org.dom4j.Element;
  25. import org.dom4j.Namespace;
  26. import org.dom4j.Node;
  27. import org.dom4j.QName;
  28. import org.dom4j.XPath;
  29. import org.dom4j.io.SAXReader;
  30. import java.io.IOException;
  31. import java.io.InputStream;
  32. import java.io.InputStreamReader;
  33. import java.net.MalformedURLException;
  34. import java.net.URL;
  35. import java.nio.charset.Charset;
  36. import java.nio.file.Files;
  37. import java.nio.file.Path;
  38. import java.util.ArrayList;
  39. import java.util.HashMap;
  40. import java.util.Iterator;
  41. import java.util.List;
  42. import java.util.Map;
  43. /**
  44. * XMLReader - a set of common xml utility methods for reading content out of an xml file.
  45. */
  46. public class XMLReader
  47. {
  48. private URL xmlUrl;
  49. private String documentType;
  50. private Document document;
  51. private Map<String, String> namespaceMap = new HashMap<>();
  52. public XMLReader( String type, Path file )
  53. throws XMLException
  54. {
  55. if ( !Files.exists(file) )
  56. {
  57. throw new XMLException( "file does not exist: " + file.toAbsolutePath() );
  58. }
  59. if ( !Files.isRegularFile(file) )
  60. {
  61. throw new XMLException( "path is not a file: " + file.toAbsolutePath() );
  62. }
  63. if ( !Files.isReadable(file) )
  64. {
  65. throw new XMLException( "Cannot read xml file due to permissions: " + file.toAbsolutePath() );
  66. }
  67. try
  68. {
  69. init( type, file.toUri().toURL() );
  70. }
  71. catch ( MalformedURLException e )
  72. {
  73. throw new XMLException( "Unable to translate file " + file + " to URL: " + e.getMessage(), e );
  74. }
  75. }
  76. public XMLReader( String type, URL url )
  77. throws XMLException
  78. {
  79. init( type, url );
  80. }
  81. private void init( String type, URL url )
  82. throws XMLException
  83. {
  84. this.documentType = type;
  85. this.xmlUrl = url;
  86. SAXReader reader = new SAXReader();
  87. try (InputStream in = url.openStream())
  88. {
  89. InputStreamReader inReader = new InputStreamReader( in, Charset.forName( "UTF-8" ) );
  90. LatinEntityResolutionReader latinReader = new LatinEntityResolutionReader( inReader );
  91. this.document = reader.read( latinReader );
  92. }
  93. catch ( DocumentException e )
  94. {
  95. throw new XMLException( "Unable to parse " + documentType + " xml " + xmlUrl + ": " + e.getMessage(), e );
  96. }
  97. catch ( IOException e )
  98. {
  99. throw new XMLException( "Unable to open stream to " + url + ": " + e.getMessage(), e );
  100. }
  101. Element root = this.document.getRootElement();
  102. if ( root == null )
  103. {
  104. throw new XMLException( "Invalid " + documentType + " xml: root element is null." );
  105. }
  106. if ( !StringUtils.equals( root.getName(), documentType ) )
  107. {
  108. throw new XMLException(
  109. "Invalid " + documentType + " xml: Unexpected root element <" + root.getName() + ">, expected <"
  110. + documentType + ">" );
  111. }
  112. }
  113. public String getDefaultNamespaceURI()
  114. {
  115. Namespace namespace = this.document.getRootElement().getNamespace();
  116. return namespace.getURI();
  117. }
  118. public void addNamespaceMapping( String elementName, String uri )
  119. {
  120. this.namespaceMap.put( elementName, uri );
  121. }
  122. public Element getElement( String xpathExpr )
  123. throws XMLException
  124. {
  125. XPath xpath = createXPath( xpathExpr );
  126. Object evaluated = xpath.selectSingleNode( document );
  127. if ( evaluated == null )
  128. {
  129. return null;
  130. }
  131. if ( evaluated instanceof Element )
  132. {
  133. return (Element) evaluated;
  134. }
  135. else
  136. {
  137. // Unknown evaluated type.
  138. throw new XMLException( ".getElement( Expr: " + xpathExpr + " ) resulted in non-Element type -> ("
  139. + evaluated.getClass().getName() + ") " + evaluated );
  140. }
  141. }
  142. private XPath createXPath( String xpathExpr )
  143. {
  144. XPath xpath = document.createXPath( xpathExpr );
  145. if ( !this.namespaceMap.isEmpty() )
  146. {
  147. xpath.setNamespaceURIs( this.namespaceMap );
  148. }
  149. return xpath;
  150. }
  151. public boolean hasElement( String xpathExpr )
  152. throws XMLException
  153. {
  154. XPath xpath = createXPath( xpathExpr );
  155. Object evaluated = xpath.selectSingleNode( document );
  156. if ( evaluated == null )
  157. {
  158. return false;
  159. }
  160. return true;
  161. }
  162. /**
  163. * Remove namespaces from entire document.
  164. */
  165. public void removeNamespaces()
  166. {
  167. removeNamespaces( this.document.getRootElement() );
  168. }
  169. /**
  170. * Remove namespaces from element recursively.
  171. */
  172. @SuppressWarnings("unchecked")
  173. public void removeNamespaces( Element elem )
  174. {
  175. elem.setQName( QName.get( elem.getName(), Namespace.NO_NAMESPACE, elem.getQualifiedName() ) );
  176. Node n;
  177. Iterator<Node> it = elem.elementIterator();
  178. while ( it.hasNext() )
  179. {
  180. n = it.next();
  181. switch ( n.getNodeType() )
  182. {
  183. case Node.ATTRIBUTE_NODE:
  184. ( (Attribute) n ).setNamespace( Namespace.NO_NAMESPACE );
  185. break;
  186. case Node.ELEMENT_NODE:
  187. removeNamespaces( (Element) n );
  188. break;
  189. }
  190. }
  191. }
  192. public String getElementText( Node context, String xpathExpr )
  193. throws XMLException
  194. {
  195. XPath xpath = createXPath( xpathExpr );
  196. Object evaluated = xpath.selectSingleNode( context );
  197. if ( evaluated == null )
  198. {
  199. return null;
  200. }
  201. if ( evaluated instanceof Element )
  202. {
  203. Element evalElem = (Element) evaluated;
  204. return evalElem.getTextTrim();
  205. }
  206. else
  207. {
  208. // Unknown evaluated type.
  209. throw new XMLException( ".getElementText( Node, Expr: " + xpathExpr + " ) resulted in non-Element type -> ("
  210. + evaluated.getClass().getName() + ") " + evaluated );
  211. }
  212. }
  213. public String getElementText( String xpathExpr )
  214. throws XMLException
  215. {
  216. XPath xpath = createXPath( xpathExpr );
  217. Object evaluated = xpath.selectSingleNode( document );
  218. if ( evaluated == null )
  219. {
  220. return null;
  221. }
  222. if ( evaluated instanceof Element )
  223. {
  224. Element evalElem = (Element) evaluated;
  225. return evalElem.getTextTrim();
  226. }
  227. else
  228. {
  229. // Unknown evaluated type.
  230. throw new XMLException( ".getElementText( Expr: " + xpathExpr + " ) resulted in non-Element type -> ("
  231. + evaluated.getClass().getName() + ") " + evaluated );
  232. }
  233. }
  234. @SuppressWarnings("unchecked")
  235. public List<Element> getElementList( String xpathExpr )
  236. throws XMLException
  237. {
  238. XPath xpath = createXPath( xpathExpr );
  239. Object evaluated = xpath.evaluate( document );
  240. if ( evaluated == null )
  241. {
  242. return null;
  243. }
  244. /* The xpath.evaluate(Context) method can return:
  245. * 1) A Collection or List of dom4j Nodes.
  246. * 2) A single dom4j Node.
  247. */
  248. if ( evaluated instanceof List )
  249. {
  250. return (List<Element>) evaluated;
  251. }
  252. else if ( evaluated instanceof Node )
  253. {
  254. List<Element> ret = new ArrayList<>();
  255. ret.add( (Element) evaluated );
  256. return ret;
  257. }
  258. else
  259. {
  260. // Unknown evaluated type.
  261. throw new XMLException( ".getElementList( Expr: " + xpathExpr + " ) resulted in non-List type -> ("
  262. + evaluated.getClass().getName() + ") " + evaluated );
  263. }
  264. }
  265. public List<String> getElementListText( String xpathExpr )
  266. throws XMLException
  267. {
  268. List<Element> elemList = getElementList( xpathExpr );
  269. if ( elemList == null )
  270. {
  271. return null;
  272. }
  273. List<String> ret = new ArrayList<>();
  274. for ( Iterator<Element> iter = elemList.iterator(); iter.hasNext(); )
  275. {
  276. Element listelem = iter.next();
  277. ret.add( listelem.getTextTrim() );
  278. }
  279. return ret;
  280. }
  281. }