1 package com.xtremelabs.robolectric.res; 2 3 import org.w3c.dom.Document; 4 5 import javax.xml.parsers.DocumentBuilder; 6 import javax.xml.parsers.DocumentBuilderFactory; 7 import java.io.File; 8 import java.io.FileFilter; 9 10 public class DocumentLoader { 11 private final XmlLoader[] xmlLoaders; 12 private final DocumentBuilderFactory documentBuilderFactory; 13 private FileFilter xmlFileFilter = new FileFilter() { 14 @Override public boolean accept(File file) { 15 return file.getName().endsWith(".xml"); 16 } 17 }; 18 19 public DocumentLoader(XmlLoader... xmlLoaders) { 20 this.xmlLoaders = xmlLoaders; 21 22 documentBuilderFactory = DocumentBuilderFactory.newInstance(); 23 documentBuilderFactory.setNamespaceAware(true); 24 documentBuilderFactory.setIgnoringComments(true); 25 documentBuilderFactory.setIgnoringElementContentWhitespace(true); 26 } 27 28 public void loadResourceXmlDirs(File... resourceXmlDirs) throws Exception { 29 loadResourceXmlDirs(false, resourceXmlDirs); 30 } 31 32 public void loadResourceXmlDirs(boolean isSystem, File... resourceXmlDirs) throws Exception { 33 for (File resourceXmlDir : resourceXmlDirs) { 34 loadResourceXmlDir(resourceXmlDir, isSystem); 35 } 36 } 37 38 public void loadResourceXmlDir(File resourceXmlDir) throws Exception { 39 loadResourceXmlDir(resourceXmlDir, false); 40 } 41 42 public void loadSystemResourceXmlDir(File resourceXmlDir) throws Exception { 43 loadResourceXmlDir(resourceXmlDir, true); 44 } 45 46 private void loadResourceXmlDir(File resourceXmlDir, boolean isSystem) throws Exception { 47 if (!resourceXmlDir.exists()) { 48 throw new RuntimeException("no such directory " + resourceXmlDir); 49 } 50 51 for (File file : resourceXmlDir.listFiles(xmlFileFilter)) { 52 loadResourceXmlFile(file, isSystem); 53 } 54 } 55 56 private void loadResourceXmlFile(File file, boolean isSystem) throws Exception { 57 for (XmlLoader xmlLoader : xmlLoaders) { 58 xmlLoader.processResourceXml(file, parse(file), isSystem); 59 } 60 } 61 62 private Document parse(File xmlFile) throws Exception { 63 DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); 64 return documentBuilder.parse(xmlFile); 65 } 66 67 } 68