001 /* 002 @license.text@ 003 */ 004 package biz.hammurapi.ant; 005 006 import java.io.File; 007 008 import javax.xml.parsers.DocumentBuilder; 009 import javax.xml.parsers.DocumentBuilderFactory; 010 011 import org.apache.tools.ant.BuildException; 012 import org.apache.tools.ant.Project; 013 import org.apache.tools.ant.Task; 014 import org.w3c.dom.Element; 015 016 /** 017 * Base class for elements, which need to read xml files. 018 * @author Pavel Vlasov 019 * @version $Revision: 1.2 $ 020 */ 021 public class XmlSourceEntry extends Task { 022 023 /** Holds value of property failOnError. */ 024 private boolean failOnError = true; 025 026 /** 027 * Fail build if unable to read source. Default is true. 028 * @ant.non-required 029 */ 030 public void setFailOnError(boolean failOnError) { 031 this.failOnError = failOnError; 032 } 033 034 /** Getter for property failOnError. 035 * @return Value of property failOnError. 036 */ 037 public boolean isFailOnError() { 038 return this.failOnError; 039 } 040 041 /** 042 * URL to read rules from. 043 * @ant.non-required Yes, unless file is set. 044 */ 045 public void setURL(String url) { 046 this.url = url; 047 } 048 049 /** Getter for property URL. 050 * @return Value of property URL. 051 */ 052 public String getURL() { 053 return this.url; 054 } 055 056 /** 057 * File to read rules from. 058 * @ant.required Yes, unless URL is set. 059 */ 060 public void setFile(File file) { 061 this.file=file; 062 } 063 064 /** Getter for property file. 065 * @return Value of property file. 066 */ 067 public File getFile() { 068 return this.file; 069 } 070 071 /** Holds value of property URL. */ 072 private String url; 073 /** Holds value of property file. */ 074 private File file; 075 076 public Element getDocumentElement() { 077 if (file!=null && url!=null) { 078 throw new BuildException("file and url are mutually exclusive"); 079 } 080 081 try { 082 DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); 083 if (file!=null) { 084 if (failOnError && !(file.exists() && file.isFile())) { 085 throw new BuildException(file.getAbsolutePath()+" does not exist or is not a file"); 086 } 087 088 if (getProject()!=null) { 089 log("Parsing "+file.getAbsolutePath(), Project.MSG_VERBOSE); 090 } 091 return builder.parse(file).getDocumentElement(); 092 } else if (url!=null) { 093 if (getProject()!=null) { 094 log("Parsing URL "+url, Project.MSG_VERBOSE); 095 } 096 java.net.URL theURL=new java.net.URL(url); 097 return builder.parse(theURL.openStream()).getDocumentElement(); 098 } else { 099 throw new BuildException("file or url must be set"); 100 } 101 } catch (Exception e) { 102 if (failOnError) { 103 throw new BuildException("Cannot load xml document", e); 104 } 105 106 return null; 107 } 108 } 109 }