001 /*
002 @license.text@
003 */
004 package biz.hammurapi.ant;
005
006 import java.io.File;
007 import java.io.FileInputStream;
008 import java.io.IOException;
009 import java.util.ArrayList;
010 import java.util.Collection;
011 import java.util.Iterator;
012
013 import javax.xml.parsers.ParserConfigurationException;
014 import javax.xml.transform.TransformerException;
015
016 import org.apache.tools.ant.BuildException;
017 import org.apache.tools.ant.DirectoryScanner;
018 import org.apache.tools.ant.Task;
019 import org.apache.tools.ant.types.FileSet;
020 import org.apache.xpath.XPathAPI;
021 import org.w3c.dom.Document;
022 import org.xml.sax.SAXException;
023
024 import biz.hammurapi.xml.dom.DOMUtils;
025
026 /**
027 * This task applies a stylesheet to XML files. Output file name is calculated from XPath expression.
028 * @author Pavel Vlasov
029 * @revision $Revision$
030 */
031 public class StyleTask extends Task {
032
033 private File outputDir;
034
035 private String fileName;
036
037 private Collection fileSets = new ArrayList();
038
039 private File style;
040
041 /**
042 * Output directory.
043 * @param outputDir
044 */
045 public void setOutputDir(File outputDir) {
046 this.outputDir = outputDir;
047 }
048
049 /**
050 * XPath expression for file name. Use / for file separator.
051 * @param fileName
052 */
053 public void setFileName(String fileName) {
054 this.fileName = fileName;
055 }
056
057 public void addFileSet(FileSet fileSet) {
058 fileSets.add(fileSet);
059 }
060
061 public void setStyle(File style) {
062 this.style = style;
063 }
064
065 public void execute() throws BuildException {
066 try {
067 Iterator it=fileSets.iterator();
068 while (it.hasNext()) {
069 FileSet fs=(FileSet) it.next();
070 DirectoryScanner ds = fs.getDirectoryScanner(getProject());
071 String[] files=ds.getIncludedFiles();
072 for (int i=0; i<files.length; i++) {
073 File in = new File(ds.getBasedir(), files[i]);
074 Document doc = DOMUtils.parse(in);
075
076 String fn = XPathAPI.eval(doc.getDocumentElement(), fileName).toString().replace('/', File.separatorChar);
077 File out = new File(outputDir, fn);
078
079 File parentDir = out.getParentFile();
080 if (!parentDir.exists()) {
081 if (!parentDir.mkdirs()) {
082 throw new BuildException("Could not create directory: "+parentDir.getAbsolutePath());
083 }
084 }
085
086 DOMUtils.style(doc, out, new FileInputStream(style), null);
087 }
088 }
089 } catch (IOException e) {
090 throw new BuildException(e);
091 } catch (SAXException e) {
092 throw new BuildException(e);
093 } catch (ParserConfigurationException e) {
094 throw new BuildException(e);
095 } catch (TransformerException e) {
096 throw new BuildException(e);
097 }
098 }
099
100 }