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 17package com.android.ant; 18 19import com.android.xml.AndroidXPathFactory; 20 21import org.apache.tools.ant.BuildException; 22import org.apache.tools.ant.Task; 23import org.apache.tools.ant.types.Path; 24import org.xml.sax.InputSource; 25 26import java.io.FileInputStream; 27import java.io.FileNotFoundException; 28 29import javax.xml.xpath.XPath; 30import 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 */ 37public class XPathTask extends Task { 38 39 private Path mManifestFile; 40 private String mProperty; 41 private String mExpression; 42 private String mDefault; 43 44 public void setInput(Path manifestFile) { 45 mManifestFile = manifestFile; 46 } 47 48 public void setOutput(String property) { 49 mProperty = property; 50 } 51 52 public void setExpression(String expression) { 53 mExpression = expression; 54 } 55 56 public void setDefault(String defaultValue) { 57 mDefault = defaultValue; 58 } 59 60 @Override 61 public void execute() throws BuildException { 62 try { 63 if (mManifestFile == null || mManifestFile.list().length == 0) { 64 throw new BuildException("input attribute is missing!"); 65 } 66 67 if (mProperty == null) { 68 throw new BuildException("output attribute is missing!"); 69 } 70 71 if (mExpression == null) { 72 throw new BuildException("expression attribute is missing!"); 73 } 74 75 XPath xpath = AndroidXPathFactory.newXPath(); 76 77 String file = mManifestFile.list()[0]; 78 String result = xpath.evaluate(mExpression, new InputSource(new FileInputStream(file))); 79 if (result.length() == 0 && mDefault != null) { 80 result = mDefault; 81 } 82 83 getProject().setProperty(mProperty, result); 84 } catch (XPathExpressionException e) { 85 throw new BuildException(e); 86 } catch (FileNotFoundException e) { 87 throw new BuildException(e); 88 } 89 } 90} 91