• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2009 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.ant;
18 
19 import com.android.sdklib.xml.AndroidXPathFactory;
20 
21 import org.apache.tools.ant.BuildException;
22 import org.apache.tools.ant.Task;
23 import org.apache.tools.ant.types.Path;
24 import org.xml.sax.InputSource;
25 
26 import java.io.FileInputStream;
27 import java.io.FileNotFoundException;
28 
29 import javax.xml.xpath.XPath;
30 import javax.xml.xpath.XPathExpressionException;
31 
32 /**
33  * Android specific XPath task.
34  * The goal is to get the result of an XPath expression on Android XML files. The android namespace
35  * (http://schemas.android.com/apk/res/android) must be associated to the "android" prefix.
36  */
37 public class XPathTask extends Task {
38 
39     private Path mManifestFile;
40     private String mProperty;
41     private String mExpression;
42 
setInput(Path manifestFile)43     public void setInput(Path manifestFile) {
44         mManifestFile = manifestFile;
45     }
46 
setOutput(String property)47     public void setOutput(String property) {
48         mProperty = property;
49     }
50 
setExpression(String expression)51     public void setExpression(String expression) {
52         mExpression = expression;
53     }
54 
55     @Override
execute()56     public void execute() throws BuildException {
57         try {
58             if (mManifestFile == null || mManifestFile.list().length == 0) {
59                 throw new BuildException("input attribute is missing!");
60             }
61 
62             if (mProperty == null) {
63                 throw new BuildException("output attribute is missing!");
64             }
65 
66             if (mExpression == null) {
67                 throw new BuildException("expression attribute is missing!");
68             }
69 
70             XPath xpath = AndroidXPathFactory.newXPath();
71 
72             String file = mManifestFile.list()[0];
73             String result = xpath.evaluate(mExpression, new InputSource(new FileInputStream(file)));
74 
75             getProject().setProperty(mProperty, result);
76         } catch (XPathExpressionException e) {
77             throw new BuildException(e);
78         } catch (FileNotFoundException e) {
79             throw new BuildException(e);
80         }
81     }
82 }
83