Search in sources :

Example 6 with Resource

use of com.android.tools.lint.checks.ResourceUsageModel.Resource in project bazel by bazelbuild.

the class ResourceUsageAnalyzer method createStubIds.

/**
   * Write stub values for IDs to values.xml to match those available in public.xml.
   */
private void createStubIds(File values, Map<File, String> rewritten, File publicXml) throws IOException, ParserConfigurationException, SAXException {
    if (values.exists()) {
        String xml = rewritten.get(values);
        if (xml == null) {
            xml = Files.toString(values, UTF_8);
        }
        List<String> stubbed = Lists.newArrayList();
        Document document = XmlUtils.parseDocument(xml, true);
        Element root = document.getDocumentElement();
        for (Resource resource : model.getResources()) {
            boolean inPublicXml = resource.declarations != null && resource.declarations.contains(publicXml);
            NodeList existing = null;
            try {
                XPathExpression expr = XPathFactory.newInstance().newXPath().compile(String.format("//item[@type=\"id\"][@name=\"%s\"]", resource.name));
                existing = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
            } catch (XPathException e) {
            // Failed to retrieve any existing declarations for resource.
            }
            if (resource.type == ResourceType.ID && inPublicXml && (existing == null || existing.getLength() == 0)) {
                Element item = document.createElement(TAG_ITEM);
                item.setAttribute(ATTR_TYPE, resource.type.getName());
                item.setAttribute(ATTR_NAME, resource.name);
                root.appendChild(item);
                stubbed.add(resource.getUrl());
            }
        }
        logger.fine("Created " + stubbed.size() + " stub IDs for:\n  " + Joiner.on(", ").join(stubbed));
        String formatted = XmlPrettyPrinter.prettyPrint(document, xml.endsWith("\n"));
        rewritten.put(values, formatted);
    }
}
Also used : XPathExpression(javax.xml.xpath.XPathExpression) XPathException(javax.xml.xpath.XPathException) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Resource(com.android.tools.lint.checks.ResourceUsageModel.Resource) Document(org.w3c.dom.Document)

Aggregations

Resource (com.android.tools.lint.checks.ResourceUsageModel.Resource)6 ResourceType (com.android.resources.ResourceType)4 Document (org.w3c.dom.Document)3 Element (org.w3c.dom.Element)3 NodeList (org.w3c.dom.NodeList)3 File (java.io.File)2 Node (org.w3c.dom.Node)2 ResourceFolderType (com.android.resources.ResourceFolderType)1 Function (com.google.common.base.Function)1 ArrayList (java.util.ArrayList)1 Pattern (java.util.regex.Pattern)1 PatternSyntaxException (java.util.regex.PatternSyntaxException)1 XPathException (javax.xml.xpath.XPathException)1 XPathExpression (javax.xml.xpath.XPathExpression)1