|
| 1 | +package com.abstractdog.dependency.analyzer.eclipse.project.classpath; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +import javax.xml.parsers.DocumentBuilder; |
| 8 | +import javax.xml.parsers.DocumentBuilderFactory; |
| 9 | +import javax.xml.parsers.ParserConfigurationException; |
| 10 | +import javax.xml.xpath.XPathConstants; |
| 11 | +import javax.xml.xpath.XPathExpression; |
| 12 | +import javax.xml.xpath.XPathExpressionException; |
| 13 | +import javax.xml.xpath.XPathFactory; |
| 14 | + |
| 15 | +import org.w3c.dom.Document; |
| 16 | +import org.w3c.dom.Node; |
| 17 | +import org.w3c.dom.NodeList; |
| 18 | + |
| 19 | +public class ClassPathParser { |
| 20 | + private static XPathExpression entryXPath; |
| 21 | + private static DocumentBuilder documentBuilder; |
| 22 | + |
| 23 | + private List<ClassPathEntry> classPathEntries; |
| 24 | + |
| 25 | + static { |
| 26 | + try { |
| 27 | + entryXPath = XPathFactory.newInstance().newXPath() |
| 28 | + .compile("/classpath/classpathentry"); |
| 29 | + } catch (XPathExpressionException e) { |
| 30 | + throw new RuntimeException(e); |
| 31 | + } |
| 32 | + |
| 33 | + try { |
| 34 | + documentBuilder = DocumentBuilderFactory.newInstance() |
| 35 | + .newDocumentBuilder(); |
| 36 | + } catch (ParserConfigurationException e) { |
| 37 | + throw new RuntimeException(e); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + private File classPathFile; |
| 42 | + |
| 43 | + public ClassPathParser(File classPathFile) { |
| 44 | + this.classPathFile = classPathFile; |
| 45 | + } |
| 46 | + |
| 47 | + public List<ClassPathEntry> getClassPathEntries() throws Exception { |
| 48 | + if (classPathEntries != null) { |
| 49 | + return classPathEntries; |
| 50 | + } |
| 51 | + |
| 52 | + classPathEntries = new ArrayList<ClassPathEntry>(); |
| 53 | + |
| 54 | + Document doc = documentBuilder.parse(classPathFile); |
| 55 | + NodeList nodeList = (NodeList) entryXPath.evaluate(doc, |
| 56 | + XPathConstants.NODESET); |
| 57 | + |
| 58 | + for (int i = 0; i < nodeList.getLength(); i++) { |
| 59 | + Node node = nodeList.item(i); |
| 60 | + |
| 61 | + ClassPathEntry entry = new ClassPathEntry.Builder(getAttributeValue(node, "kind")) |
| 62 | + .path(getAttributeValue(node, "path")) |
| 63 | + .output(getAttributeValue(node, "output")) |
| 64 | + .excluding(getAttributeValue(node, "excluding")) |
| 65 | + .build(); |
| 66 | + |
| 67 | + classPathEntries.add(entry); |
| 68 | + } |
| 69 | + |
| 70 | + return classPathEntries; |
| 71 | + } |
| 72 | + |
| 73 | + private String getAttributeValue(Node node, String name) { |
| 74 | + return node.getAttributes().getNamedItem(name) == null ? null : node |
| 75 | + .getAttributes().getNamedItem(name).getNodeValue(); |
| 76 | + } |
| 77 | +} |
0 commit comments