001package ball.util.ant.taskdefs;
002/*-
003 * ##########################################################################
004 * Utilities
005 * $Id: XPathEvaluateTask.html 5431 2020-02-12 19:03:17Z ball $
006 * $HeadURL: svn+ssh://svn.hcf.dev/var/spool/scm/repository.svn/hcf-dev/blog/2019-07-08-fivethirtyeight-best-scrabble-string/src/main/resources/javadoc/src-html/ball/util/ant/taskdefs/XPathEvaluateTask.html $
007 * %%
008 * Copyright (C) 2008 - 2020 Allen D. Ball
009 * %%
010 * Licensed under the Apache License, Version 2.0 (the "License");
011 * you may not use this file except in compliance with the License.
012 * You may obtain a copy of the License at
013 *
014 *      http://www.apache.org/licenses/LICENSE-2.0
015 *
016 * Unless required by applicable law or agreed to in writing, software
017 * distributed under the License is distributed on an "AS IS" BASIS,
018 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
019 * See the License for the specific language governing permissions and
020 * limitations under the License.
021 * ##########################################################################
022 */
023import ball.activation.ReaderWriterDataSource;
024import java.io.File;
025import java.io.OutputStream;
026import javax.xml.parsers.DocumentBuilderFactory;
027import javax.xml.transform.Transformer;
028import javax.xml.transform.TransformerFactory;
029import javax.xml.transform.dom.DOMSource;
030import javax.xml.transform.stream.StreamResult;
031import javax.xml.xpath.XPath;
032import javax.xml.xpath.XPathExpression;
033import javax.xml.xpath.XPathFactory;
034import lombok.Getter;
035import lombok.NoArgsConstructor;
036import lombok.Setter;
037import lombok.ToString;
038import lombok.experimental.Accessors;
039import org.apache.tools.ant.BuildException;
040import org.apache.tools.ant.Task;
041import org.apache.tools.ant.util.ClasspathUtils;
042import org.w3c.dom.Document;
043import org.w3c.dom.NodeList;
044
045import static javax.xml.transform.OutputKeys.INDENT;
046import static javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION;
047import static javax.xml.xpath.XPathConstants.NODESET;
048
049/**
050 * {@link.uri http://ant.apache.org/ Ant} {@link Task} to test {@link XPath}
051 * expressions.
052 *
053 * {@ant.task}
054 *
055 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
056 * @version $Revision: 5431 $
057 */
058@AntTask("xpath-evaluate")
059@NoArgsConstructor @ToString
060public class XPathEvaluateTask extends Task
061                               implements AnnotatedAntTask,
062                                          ClasspathDelegateAntTask,
063                                          ConfigurableAntTask {
064    private static final String NO = "no";
065    private static final String YES = "yes";
066
067    private static final String INDENT_AMOUNT =
068        "{http://xml.apache.org/xslt}indent-amount";
069
070    @Getter @Setter @Accessors(chain = true, fluent = true)
071    private ClasspathUtils.Delegate delegate = null;
072    @NotNull @Getter @Setter
073    private File file = null;
074    @NotNull @Getter @Setter
075    private String expression = null;
076
077    @Override
078    public void init() throws BuildException {
079        super.init();
080        ClasspathDelegateAntTask.super.init();
081        ConfigurableAntTask.super.init();
082    }
083
084    @Override
085    public void execute() throws BuildException {
086        super.execute();
087        AnnotatedAntTask.super.execute();
088
089        log(String.valueOf(getFile()));
090        log(getExpression());
091
092        try {
093            Document document =
094                DocumentBuilderFactory.newInstance()
095                .newDocumentBuilder()
096                .parse(getFile());
097            XPath xpath = XPathFactory.newInstance().newXPath();
098            XPathExpression expression = xpath.compile(getExpression());
099            NodeList set = (NodeList) expression.evaluate(document, NODESET);
100            Transformer transformer =
101                TransformerFactory.newInstance().newTransformer();
102
103            transformer.setOutputProperty(OMIT_XML_DECLARATION, YES);
104            transformer.setOutputProperty(INDENT, YES);
105            transformer.setOutputProperty(INDENT_AMOUNT, String.valueOf(2));
106
107            for (int i = 0; i < set.getLength(); i += 1) {
108                ReaderWriterDataSource ds =
109                    new ReaderWriterDataSource(null, null);
110
111                try (OutputStream out = ds.getOutputStream()) {
112                    transformer.transform(new DOMSource(set.item(i)),
113                                          new StreamResult(out));
114                }
115
116                log();
117                log(ds.getBufferedReader().lines());
118            }
119        } catch (BuildException exception) {
120            throw exception;
121        } catch (RuntimeException exception) {
122            throw exception;
123        } catch (Exception exception) {
124            throw new BuildException(exception);
125        }
126    }
127}