2 * Copyright (C) 2009 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.ant;
19 import com.android.sdklib.xml.AndroidXPathFactory;
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;
26 import java.io.FileInputStream;
27 import java.io.FileNotFoundException;
29 import javax.xml.xpath.XPath;
30 import javax.xml.xpath.XPathExpressionException;
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.
37 public class XPathTask extends Task {
39 private Path mManifestFile;
40 private String mProperty;
41 private String mExpression;
42 private String mDefault;
44 public void setInput(Path manifestFile) {
45 mManifestFile = manifestFile;
48 public void setOutput(String property) {
52 public void setExpression(String expression) {
53 mExpression = expression;
56 public void setDefault(String defaultValue) {
57 mDefault = defaultValue;
61 public void execute() throws BuildException {
63 if (mManifestFile == null || mManifestFile.list().length == 0) {
64 throw new BuildException("input attribute is missing!");
67 if (mProperty == null) {
68 throw new BuildException("output attribute is missing!");
71 if (mExpression == null) {
72 throw new BuildException("expression attribute is missing!");
75 XPath xpath = AndroidXPathFactory.newXPath();
77 String file = mManifestFile.list()[0];
78 String result = xpath.evaluate(mExpression, new InputSource(new FileInputStream(file)));
79 if (result.length() == 0 && mDefault != null) {
83 getProject().setProperty(mProperty, result);
84 } catch (XPathExpressionException e) {
85 throw new BuildException(e);
86 } catch (FileNotFoundException e) {
87 throw new BuildException(e);