You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2019/09/19 08:17:21 UTC
[groovy] branch master updated: GROOVY-9254: Split package renaming
second stage (remove violating packages)
This is an automated email from the ASF dual-hosted git repository.
paulk pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/master by this push:
new 0dfbdf9 GROOVY-9254: Split package renaming second stage (remove violating packages)
0dfbdf9 is described below
commit 0dfbdf90a90bdfc6889682124b641f5d0a3253e4
Author: Paul King <pa...@asert.com.au>
AuthorDate: Thu Sep 19 18:17:09 2019 +1000
GROOVY-9254: Split package renaming second stage (remove violating packages)
---
src/main/java/groovy/xml/QName.java | 288 ---
.../main/groovy/groovy/util/FileNameFinder.groovy | 49 -
.../src/main/java/groovy/util/AntBuilder.java | 514 -----
.../src/main/groovy/groovy/util/CliBuilder.groovy | 82 -
.../main/groovy/groovy/util/OptionAccessor.groovy | 38 -
.../src/main/java/groovy/util/GroovyMBean.java | 394 ----
.../codehaus/groovy/runtime/NioGroovyMethods.java | 2023 --------------------
.../org/codehaus/groovy/runtime/WritablePath.java | 216 ---
.../groovy/groovy/lang/GroovyLogTestCase.groovy | 86 -
.../groovy/groovy/util/GroovyShellTestCase.groovy | 83 -
.../groovy/util/JavadocAssertionTestBuilder.groovy | 144 --
.../groovy/util/JavadocAssertionTestSuite.groovy | 123 --
.../main/groovy/groovy/util/StringTestUtil.groovy | 33 -
.../java/groovy/transform/NotYetImplemented.java | 47 -
.../src/main/java/groovy/util/AllTestSuite.java | 147 --
.../src/main/java/groovy/util/GroovyAssert.java | 146 --
.../src/main/java/groovy/util/GroovyTestCase.java | 281 ---
.../src/main/java/groovy/util/GroovyTestSuite.java | 99 -
.../codehaus/groovy/runtime/ScriptTestAdapter.java | 58 -
.../src/main/java/groovy/util/XmlNodePrinter.java | 446 -----
.../src/main/java/groovy/util/XmlParser.java | 505 -----
.../src/main/java/groovy/util/XmlSlurper.java | 467 -----
.../src/main/java/groovy/util/XmlUtil.java | 78 -
.../java/groovy/util/slurpersupport/Attribute.java | 143 --
.../groovy/util/slurpersupport/Attributes.java | 140 --
.../util/slurpersupport/FilteredAttributes.java | 59 -
.../util/slurpersupport/FilteredNodeChildren.java | 65 -
.../groovy/util/slurpersupport/GPathResult.java | 711 -------
.../util/slurpersupport/NamespaceAwareHashMap.java | 79 -
.../groovy/util/slurpersupport/NoChildren.java | 167 --
.../main/java/groovy/util/slurpersupport/Node.java | 339 ----
.../java/groovy/util/slurpersupport/NodeChild.java | 160 --
.../groovy/util/slurpersupport/NodeChildren.java | 235 ---
.../groovy/util/slurpersupport/NodeIterator.java | 60 -
.../groovy/util/slurpersupport/NodeParents.java | 56 -
.../util/slurpersupport/ReplacementNode.java | 47 -
.../java/groovy/util/slurpersupport/package.html | 28 -
.../codehaus/groovy/runtime/XmlGroovyMethods.java | 75 -
.../org/codehaus/groovy/tools/xml/DomToGroovy.java | 405 ----
39 files changed, 9116 deletions(-)
diff --git a/src/main/java/groovy/xml/QName.java b/src/main/java/groovy/xml/QName.java
deleted file mode 100644
index 0c37f42..0000000
--- a/src/main/java/groovy/xml/QName.java
+++ /dev/null
@@ -1,288 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.xml;
-
-import java.io.Serializable;
-
-/**
- * <code>QName</code> class represents the value of a qualified name
- * as specified in <a href="http://www.w3.org/TR/xmlschema-2/#QName">XML
- * Schema Part2: Datatypes specification</a>.
- * <p>
- * The value of a QName contains a <b>namespaceURI</b>, a <b>localPart</b> and a <b>prefix</b>.
- * The localPart provides the local part of the qualified name. The
- * namespaceURI is a URI reference identifying the namespace.
- */
-@Deprecated
-public class QName implements Serializable {
- private static final long serialVersionUID = -9029109610006696081L;
-
- /** comment/shared empty string */
- private static final String EMPTY_STRING = "";
-
- /** Field namespaceURI */
- private String namespaceURI;
-
- /** Field localPart */
- private String localPart;
-
- /** Field prefix */
- private String prefix;
-
- /**
- * Constructor for the QName.
- *
- * @param localPart Local part of the QName
- */
- public QName(String localPart) {
- this(EMPTY_STRING, localPart, EMPTY_STRING);
- }
-
- /**
- * Constructor for the QName.
- *
- * @param namespaceURI Namespace URI for the QName
- * @param localPart Local part of the QName.
- */
- public QName(String namespaceURI, String localPart) {
- this(namespaceURI, localPart, EMPTY_STRING);
- }
-
- /**
- * Constructor for the QName.
- *
- * @param namespaceURI Namespace URI for the QName
- * @param localPart Local part of the QName.
- * @param prefix Prefix of the QName.
- */
- public QName(String namespaceURI, String localPart, String prefix) {
- this.namespaceURI = (namespaceURI == null)
- ? EMPTY_STRING
- : namespaceURI;
- if (localPart == null) {
- throw new IllegalArgumentException("invalid QName local part");
- } else {
- this.localPart = localPart;
- }
-
- if (prefix == null) {
- throw new IllegalArgumentException("invalid QName prefix");
- } else {
- this.prefix = prefix;
- }
- }
-
- /**
- * Gets the Namespace URI for this QName
- *
- * @return Namespace URI
- */
- public String getNamespaceURI() {
- return namespaceURI;
- }
-
- /**
- * Gets the Local part for this QName
- *
- * @return Local part
- */
- public String getLocalPart() {
- return localPart;
- }
-
- /**
- * Gets the Prefix for this QName
- *
- * @return Prefix
- */
- public String getPrefix() {
- return prefix;
- }
-
- /**
- * Returns the fully qualified name of this QName
- *
- * @return a string representation of the QName
- */
- public String getQualifiedName() {
- return ((prefix.equals(EMPTY_STRING))
- ? localPart
- : prefix + ':' + localPart);
- }
-
- /**
- * Returns a string representation of this QName
- *
- * @return a string representation of the QName
- */
- public String toString() {
- return ((namespaceURI.equals(EMPTY_STRING))
- ? localPart
- : '{' + namespaceURI + '}' + localPart);
- }
-
- /**
- * Tests this QName for equality with another object.
- * <p>
- * If the given object is not a QName or String equivalent or is null then this method
- * returns <tt>false</tt>.
- * <p>
- * For two QNames to be considered equal requires that both
- * localPart and namespaceURI must be equal. This method uses
- * <code>String.equals</code> to check equality of localPart
- * and namespaceURI. Any class that extends QName is required
- * to satisfy this equality contract.
- *
- * If the supplied object is a String, then it is split in two on the last colon
- * and the first half is compared against the prefix || namespaceURI
- * and the second half is compared against the localPart
- *
- * i.e. assert new QName("namespace","localPart").equals("namespace:localPart")
- *
- * Intended Usage: for gpath accessors, e.g. root.'urn:mynamespace:node'
- *
- * Warning: this equivalence is not commutative,
- * i.e. qname.equals(string) may be true/false but string.equals(qname) is always false
- *
- * <p>
- * This method satisfies the general contract of the <code>Object.equals</code> method.
- *
- * @param o the reference object with which to compare
- *
- * @return <code>true</code> if the given object is identical to this
- * QName: <code>false</code> otherwise.
- */
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null) return false;
- if (o instanceof QName) {
- final QName qName = (QName) o;
- if (!namespaceURI.equals(qName.namespaceURI)) return false;
- return localPart.equals(qName.localPart);
-
- } else if (o instanceof String) {
- final String string = (String)o;
- if (string.length() == 0) return false;
- int lastColonIndex = string.lastIndexOf(":");
- if (lastColonIndex < 0 || lastColonIndex == string.length() - 1) return false;
- final String stringPrefix = string.substring(0,lastColonIndex);
- final String stringLocalPart = string.substring(lastColonIndex + 1);
- if (stringPrefix.equals(prefix) || stringPrefix.equals(namespaceURI)) {
- return localPart.equals(stringLocalPart);
- }
- return false;
- }
- return false;
- }
-
- /**
- * Tests if this QName matches another object.
- * <p>
- * If the given object is not a QName or String equivalent or is null then this method
- * returns <tt>false</tt>.
- * <p>
- * For two QNames to be considered matching requires that both
- * localPart and namespaceURI must be equal or one of them is a wildcard.
- *
- * If the supplied object is a String, then it is split in two on the last colon
- * and the first half is matched against the prefix || namespaceURI
- * and the second half is matched against the localPart
- *
- * @param o the reference object with which to compare
- *
- * @return <code>true</code> if the given object matches
- * this QName: <code>false</code> otherwise.
- */
- public boolean matches(Object o) {
- if (this == o) return true;
- if (o == null) return false;
- if (o instanceof QName) {
- final QName qName = (QName) o;
- if (!namespaceURI.equals(qName.namespaceURI) && !namespaceURI.equals("*") && !qName.namespaceURI.equals("*")) return false;
- return localPart.equals(qName.localPart) || localPart.equals("*") || qName.localPart.equals("*");
- } else if (o instanceof String) {
- final String string = (String)o;
- if (string.length() == 0) return false;
- // try matching against 'prefix:localname'
- int lastColonIndex = string.lastIndexOf(":");
- if (lastColonIndex < 0 && prefix.length() == 0) return string.equals(localPart);
- if (lastColonIndex < 0 || lastColonIndex == string.length() - 1) return false;
- final String stringPrefix = string.substring(0,lastColonIndex);
- final String stringLocalPart = string.substring(lastColonIndex + 1);
- if (stringPrefix.equals(prefix) || stringPrefix.equals(namespaceURI) || stringPrefix.equals("*")) {
- return localPart.equals(stringLocalPart) || stringLocalPart.equals("*");
- }
- }
- return false;
- }
-
- /**
- * Returns a QName holding the value of the specified String.
- * <p>
- * The string must be in the form returned by the QName.toString()
- * method, i.e. "{namespaceURI}localPart", with the "{namespaceURI}"
- * part being optional.
- * <p>
- * This method doesn't do a full validation of the resulting QName.
- * In particular, it doesn't check that the resulting namespace URI
- * is a legal URI (per RFC 2396 and RFC 2732), nor that the resulting
- * local part is a legal NCName per the XML Namespaces specification.
- *
- * @param s the string to be parsed
- * @throws java.lang.IllegalArgumentException If the specified String cannot be parsed as a QName
- * @return QName corresponding to the given String
- */
- public static QName valueOf(String s) {
-
- if ((s == null) || s.equals("")) {
- throw new IllegalArgumentException("invalid QName literal");
- }
-
- if (s.charAt(0) == '{') {
- int i = s.indexOf('}');
-
- if (i == -1) {
- throw new IllegalArgumentException("invalid QName literal");
- }
-
- if (i == s.length() - 1) {
- throw new IllegalArgumentException("invalid QName literal");
- } else {
- return new QName(s.substring(1, i), s.substring(i + 1));
- }
- } else {
- return new QName(s);
- }
- }
-
- /**
- * Returns a hash code value for this QName object. The hash code
- * is based on both the localPart and namespaceURI parts of the
- * QName. This method satisfies the general contract of the
- * <code>Object.hashCode</code> method.
- *
- * @return a hash code value for this Qname object
- */
- public int hashCode() {
- int result;
- result = namespaceURI.hashCode();
- result = 29 * result + localPart.hashCode();
- return result;
- }
-}
\ No newline at end of file
diff --git a/subprojects/groovy-ant/src/main/groovy/groovy/util/FileNameFinder.groovy b/subprojects/groovy-ant/src/main/groovy/groovy/util/FileNameFinder.groovy
deleted file mode 100644
index c751d30..0000000
--- a/subprojects/groovy-ant/src/main/groovy/groovy/util/FileNameFinder.groovy
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util
-
-import groovy.ant.AntBuilder
-
-/**
- * Find files according to a base directory and an includes and excludes pattern.
- * The include and exclude patterns conform to Ant's fileset pattern conventions.
- */
-@Deprecated
-class FileNameFinder implements IFileNameFinder {
-
- List<String> getFileNames(String basedir, String pattern) {
- getFileNames(dir: basedir, includes: pattern)
- }
-
- List<String> getFileNames(String basedir, String pattern, String excludesPattern) {
- getFileNames(dir: basedir, includes: pattern, excludes: excludesPattern)
- }
-
- List<String> getFileNames(Map args) {
- def ant = new AntBuilder()
- def scanner = ant.fileScanner {
- fileset(args)
- }
- List<String> files = []
- for (File f in scanner) {
- files << f.absolutePath
- }
- files
- }
-}
diff --git a/subprojects/groovy-ant/src/main/java/groovy/util/AntBuilder.java b/subprojects/groovy-ant/src/main/java/groovy/util/AntBuilder.java
deleted file mode 100644
index 988140d..0000000
--- a/subprojects/groovy-ant/src/main/java/groovy/util/AntBuilder.java
+++ /dev/null
@@ -1,514 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util;
-
-import groovy.xml.QName;
-import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.BuildLogger;
-import org.apache.tools.ant.DemuxInputStream;
-import org.apache.tools.ant.DemuxOutputStream;
-import org.apache.tools.ant.Location;
-import org.apache.tools.ant.NoBannerLogger;
-import org.apache.tools.ant.Project;
-import org.apache.tools.ant.ProjectHelper;
-import org.apache.tools.ant.RuntimeConfigurable;
-import org.apache.tools.ant.Target;
-import org.apache.tools.ant.Task;
-import org.apache.tools.ant.UnknownElement;
-import org.apache.tools.ant.dispatch.DispatchUtils;
-import org.apache.tools.ant.helper.AntXMLContext;
-import org.apache.tools.ant.helper.ProjectHelper2;
-import org.codehaus.groovy.ant.FileScanner;
-import org.codehaus.groovy.reflection.ReflectionUtils;
-import org.codehaus.groovy.runtime.DefaultGroovyMethodsSupport;
-import org.xml.sax.Attributes;
-import org.xml.sax.Locator;
-import org.xml.sax.SAXParseException;
-import org.xml.sax.helpers.AttributesImpl;
-
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.lang.reflect.Method;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Vector;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Allows <a href="http://ant.apache.org/manual/coretasklist.html">Ant tasks</a> to
- * be used with a Groovy builder-style markup. Requires that {{ant.jar}} is on your classpath which will
- * happen automatically if you are using the Groovy distribution but will be up
- * to you to organize if you are embedding Groovy. If you wish to use the
- * <a href="http://ant.apache.org/manual/install#optionalTasks">optional tasks</a>
- * you will need to add one or more additional jars from the ant distribution to
- * your classpath - see the <a href="http://ant.apache.org/manual/install.html#librarydependencies">library
- * dependencies</a> for more details.
- */
-@Deprecated
-public class AntBuilder extends BuilderSupport {
-
- private final Logger log = Logger.getLogger(getClass().getName());
- private final Project project;
- private final AntXMLContext antXmlContext;
- private final ProjectHelper2.ElementHandler antElementHandler = new ProjectHelper2.ElementHandler();
- private final ProjectHelper2.TargetHandler antTargetHandler = new ProjectHelper2.TargetHandler();
- private final Target collectorTarget;
- private final Target implicitTarget;
- private Target definingTarget;
- private Object lastCompletedNode;
- // true when inside a task so special ant.target handling occurs just at top level
- boolean insideTask;
-
- private boolean saveStreams = true;
- private static Integer streamCount = 0;
- private static InputStream savedIn;
- private static PrintStream savedErr;
- private static PrintStream savedOut;
- private static DemuxInputStream demuxInputStream;
- private static DemuxOutputStream demuxOutputStream;
- private static DemuxOutputStream demuxErrorStream;
- private static InputStream savedProjectInputStream;
-
- public AntBuilder() {
- this(createProject());
- }
-
- public AntBuilder(final Project project) {
- this(project, new Target());
- }
-
- public AntBuilder(final Project project, final Target owningTarget) {
- this.project = project;
-
- /*
- * GROOVY-4524: The following is not needed anymore as an ant Project already by default has inputhandler
- * set to DefaultInputHandler. And if it is again set here, it mistakenly overrides the custom input handler
- * if set using -inputhandler switch.
- */
- //this.project.setInputHandler(new DefaultInputHandler());
-
- collectorTarget = owningTarget;
- antXmlContext = new AntXMLContext(project);
- collectorTarget.setProject(project);
- antXmlContext.setCurrentTarget(collectorTarget);
- antXmlContext.setLocator(new AntBuilderLocator());
- antXmlContext.setCurrentTargets(new HashMap<String, Target>());
-
- implicitTarget = new Target();
- implicitTarget.setProject(project);
- implicitTarget.setName("");
- antXmlContext.setImplicitTarget(implicitTarget);
-
- // FileScanner is a Groovy utility
- project.addDataTypeDefinition("fileScanner", FileScanner.class);
- }
-
- public AntBuilder(final Task parentTask) {
- this(parentTask.getProject(), parentTask.getOwningTarget());
-
- // define "owning" task as wrapper to avoid having tasks added to the target
- // but it needs to be an UnknownElement and no access is available from
- // task to its original UnknownElement
- final UnknownElement ue = new UnknownElement(parentTask.getTaskName());
- ue.setProject(parentTask.getProject());
- ue.setTaskType(parentTask.getTaskType());
- ue.setTaskName(parentTask.getTaskName());
- ue.setLocation(parentTask.getLocation());
- ue.setOwningTarget(parentTask.getOwningTarget());
- ue.setRuntimeConfigurableWrapper(parentTask.getRuntimeConfigurableWrapper());
- parentTask.getRuntimeConfigurableWrapper().setProxy(ue);
- antXmlContext.pushWrapper(parentTask.getRuntimeConfigurableWrapper());
- }
-
- /**
- * #
- * Gets the Ant project in which the tasks are executed
- *
- * @return the project
- */
- public Project getProject() {
- return project;
- }
-
- /**
- * Gets the xml context of Ant used while creating tasks
- *
- * @return the Ant xml context
- */
- public AntXMLContext getAntXmlContext() {
- return antXmlContext;
- }
-
- /**
- * Whether stdin, stdout, stderr streams are saved.
- *
- * @return true if we are saving streams
- * @see #setSaveStreams(boolean)
- */
- public boolean isSaveStreams() {
- return saveStreams;
- }
-
- /**
- * Indicates that we save stdin, stdout, stderr and replace them
- * while AntBuilder is executing tasks with
- * streams that funnel the normal streams into Ant's logs.
- *
- * @param saveStreams set to false to disable this behavior
- */
- public void setSaveStreams(boolean saveStreams) {
- this.saveStreams = saveStreams;
- }
-
- /**
- * @return Factory method to create new Project instances
- */
- protected static Project createProject() {
- final Project project = new Project();
-
- final ProjectHelper helper = ProjectHelper.getProjectHelper();
- project.addReference(ProjectHelper.PROJECTHELPER_REFERENCE, helper);
- helper.getImportStack().addElement("AntBuilder"); // import checks that stack is not empty
-
- final BuildLogger logger = new NoBannerLogger();
-
- logger.setMessageOutputLevel(org.apache.tools.ant.Project.MSG_INFO);
- logger.setOutputPrintStream(System.out);
- logger.setErrorPrintStream(System.err);
-
- project.addBuildListener(logger);
-
- project.init();
- project.getBaseDir();
- return project;
- }
-
- protected void setParent(Object parent, Object child) {
- }
-
- /**
- * We don't want to return the node as created in {@link #createNode(Object, Map, Object)}
- * but the one made ready by {@link #nodeCompleted(Object, Object)}
- *
- * @see groovy.util.BuilderSupport#doInvokeMethod(java.lang.String, java.lang.Object, java.lang.Object)
- */
- protected Object doInvokeMethod(String methodName, Object name, Object args) {
- super.doInvokeMethod(methodName, name, args);
-
-
- // return the completed node
- return lastCompletedNode;
- }
-
- /**
- * Determines, when the ANT Task that is represented by the "node" should perform.
- * Node must be an ANT Task or no "perform" is called.
- * If node is an ANT Task, it performs right after complete construction.
- * If node is nested in a TaskContainer, calling "perform" is delegated to that
- * TaskContainer.
- *
- * @param parent note: null when node is root
- * @param node the node that now has all its children applied
- */
- protected void nodeCompleted(final Object parent, final Object node) {
- if (parent == null) insideTask = false;
- antElementHandler.onEndElement(null, null, antXmlContext);
-
- lastCompletedNode = node;
- if (parent != null && !(parent instanceof Target)) {
- log.finest("parent is not null: no perform on nodeCompleted");
- return; // parent will care about when children perform
- }
- if (definingTarget != null && definingTarget == parent && node instanceof Task) return; // inside defineTarget
- if (definingTarget == node) {
- definingTarget = null;
- }
-
- // as in Target.execute()
- if (node instanceof Task) {
- Task task = (Task) node;
- final String taskName = task.getTaskName();
-
- if ("antcall".equals(taskName) && parent == null) {
- throw new BuildException("antcall not supported within AntBuilder, consider using 'ant.project.executeTarget('targetName')' instead.");
- }
-
- if (saveStreams) {
- // save original streams
- synchronized (AntBuilder.class) {
- int currentStreamCount = streamCount++;
- if (currentStreamCount == 0) {
- // we are first, save the streams
- savedProjectInputStream = project.getDefaultInputStream();
- savedIn = System.in;
- savedErr = System.err;
- savedOut = System.out;
-
- if (!(savedIn instanceof DemuxInputStream)) {
- project.setDefaultInputStream(savedIn);
- demuxInputStream = new DemuxInputStream(project);
- System.setIn(demuxInputStream);
- }
- demuxOutputStream = new DemuxOutputStream(project, false);
- System.setOut(new PrintStream(demuxOutputStream));
- demuxErrorStream = new DemuxOutputStream(project, true);
- System.setErr(new PrintStream(demuxErrorStream));
- }
- }
- }
-
- try {
- lastCompletedNode = performTask(task);
- } finally {
- if (saveStreams) {
- synchronized (AntBuilder.class) {
- int currentStreamCount = --streamCount;
- if (currentStreamCount == 0) {
- // last to leave, turn out the lights: restore original streams
- project.setDefaultInputStream(savedProjectInputStream);
- System.setOut(savedOut);
- System.setErr(savedErr);
- if (demuxInputStream != null) {
- System.setIn(savedIn);
- DefaultGroovyMethodsSupport.closeQuietly(demuxInputStream);
- demuxInputStream = null;
- }
- DefaultGroovyMethodsSupport.closeQuietly(demuxOutputStream);
- DefaultGroovyMethodsSupport.closeQuietly(demuxErrorStream);
- demuxOutputStream = null;
- demuxErrorStream = null;
- }
- }
- }
- }
-
- // restore dummy collector target
- if ("import".equals(taskName)) {
- antXmlContext.setCurrentTarget(collectorTarget);
- }
- } else if (node instanceof Target) {
- // restore dummy collector target
- antXmlContext.setCurrentTarget(collectorTarget);
- } else {
- final RuntimeConfigurable r = (RuntimeConfigurable) node;
- r.maybeConfigure(project);
- }
- }
-
- // Copied from org.apache.tools.ant.Task, since we need to get a real thing before it gets nulled in DispatchUtils.execute
-
- private Object performTask(Task task) {
-
- Throwable reason = null;
- try {
- // Have to call fireTestStared/fireTestFinished via reflection as they unfortunately have protected access in Project
- final Method fireTaskStarted = Project.class.getDeclaredMethod("fireTaskStarted", Task.class);
- ReflectionUtils.trySetAccessible(fireTaskStarted);
- fireTaskStarted.invoke(project, task);
-
- Object realThing;
- realThing = task;
- task.maybeConfigure();
- if (task instanceof UnknownElement) {
- realThing = ((UnknownElement) task).getRealThing();
- }
-
- DispatchUtils.execute(task);
-
- return realThing != null ? realThing : task;
- }
- catch (BuildException ex) {
- if (ex.getLocation() == Location.UNKNOWN_LOCATION) {
- ex.setLocation(task.getLocation());
- }
- reason = ex;
- throw ex;
- }
- catch (Exception ex) {
- reason = ex;
- BuildException be = new BuildException(ex);
- be.setLocation(task.getLocation());
- throw be;
- }
- catch (Error ex) {
- reason = ex;
- throw ex;
- }
- finally {
- try {
- final Method fireTaskFinished = Project.class.getDeclaredMethod("fireTaskFinished", Task.class, Throwable.class);
- ReflectionUtils.trySetAccessible(fireTaskFinished);
- fireTaskFinished.invoke(project, task, reason);
- }
- catch (Exception e) {
- BuildException be = new BuildException(e);
- be.setLocation(task.getLocation());
- throw be;
- }
- }
- }
-
- protected Object createNode(Object tagName) {
- return createNode(tagName, Collections.EMPTY_MAP);
- }
-
- protected Object createNode(Object name, Object value) {
- Object task = createNode(name);
- setText(task, value.toString());
- return task;
- }
-
- protected Object createNode(Object name, Map attributes, Object value) {
- Object task = createNode(name, attributes);
- setText(task, value.toString());
- return task;
- }
-
- /**
- * Builds an {@link Attributes} from a {@link Map}
- *
- * @param attributes the attributes to wrap
- * @return the wrapped attributes
- */
- protected static Attributes buildAttributes(final Map attributes) {
- final AttributesImpl attr = new AttributesImpl();
- for (Object o : attributes.entrySet()) {
- final Map.Entry entry = (Map.Entry) o;
- final String attributeName = (String) entry.getKey();
- final String attributeValue = String.valueOf(entry.getValue());
- attr.addAttribute(null, attributeName, attributeName, "CDATA", attributeValue);
- }
- return attr;
- }
-
- protected Object createNode(final Object name, final Map attributes) {
-
- final Attributes attrs = buildAttributes(attributes);
- String tagName = name.toString();
- String ns = "";
-
- if (name instanceof QName) {
- QName q = (QName) name;
- tagName = q.getLocalPart();
- ns = q.getNamespaceURI();
- }
-
- // import can be used only as top level element
- if ("import".equals(name)) {
- antXmlContext.setCurrentTarget(implicitTarget);
- } else if ("target".equals(name) && !insideTask) {
- return onStartTarget(attrs, tagName, ns);
- } else if ("defineTarget".equals(name) && !insideTask) {
- return onDefineTarget(attrs, "target", ns);
- }
-
- try {
- antElementHandler.onStartElement(ns, tagName, tagName, attrs, antXmlContext);
- }
- catch (final SAXParseException e) {
- log.log(Level.SEVERE, "Caught: " + e, e);
- }
-
- insideTask = true;
- final RuntimeConfigurable wrapper = antXmlContext.getWrapperStack().lastElement();
- return wrapper.getProxy();
- }
-
- private Target onDefineTarget(final Attributes attrs, String tagName, String ns) {
- final Target target = new Target();
- target.setProject(project);
- target.setLocation(new Location(antXmlContext.getLocator()));
- try {
- antTargetHandler.onStartElement(ns, tagName, tagName, attrs, antXmlContext);
- final Target newTarget = getProject().getTargets().get(attrs.getValue("name"));
- antXmlContext.setCurrentTarget(newTarget);
- definingTarget = newTarget;
- return newTarget;
- }
- catch (final SAXParseException e) {
- log.log(Level.SEVERE, "Caught: " + e, e);
- }
- return null;
- }
-
- private Target onStartTarget(final Attributes attrs, String tagName, String ns) {
- final Target target = new Target();
- target.setProject(project);
- target.setLocation(new Location(antXmlContext.getLocator()));
- try {
- antTargetHandler.onStartElement(ns, tagName, tagName, attrs, antXmlContext);
- final Target newTarget = getProject().getTargets().get(attrs.getValue("name"));
-
- // execute dependencies (if any)
- final Vector<Target> targets = new Vector<Target>();
- for (final Enumeration<String> deps = newTarget.getDependencies(); deps.hasMoreElements();) {
- final String targetName = deps.nextElement();
- targets.add(project.getTargets().get(targetName));
- }
- getProject().executeSortedTargets(targets);
-
- antXmlContext.setCurrentTarget(newTarget);
- return newTarget;
- }
- catch (final SAXParseException e) {
- log.log(Level.SEVERE, "Caught: " + e, e);
- }
- return null;
- }
-
- protected void setText(Object task, String text) {
- final char[] characters = text.toCharArray();
- try {
- antElementHandler.characters(characters, 0, characters.length, antXmlContext);
- }
- catch (final SAXParseException e) {
- log.log(Level.WARNING, "SetText failed: " + task + ". Reason: " + e, e);
- }
- }
-
- public Project getAntProject() {
- return project;
- }
-}
-
-/**
- * Would be nice to retrieve location information (from AST?).
- * In a first time, without info
- */
-@Deprecated
-class AntBuilderLocator implements Locator {
- public int getColumnNumber() {
- return 0;
- }
-
- public int getLineNumber() {
- return 0;
- }
-
- public String getPublicId() {
- return "";
- }
-
- public String getSystemId() {
- return "";
- }
-}
diff --git a/subprojects/groovy-cli-commons/src/main/groovy/groovy/util/CliBuilder.groovy b/subprojects/groovy-cli-commons/src/main/groovy/groovy/util/CliBuilder.groovy
deleted file mode 100644
index c50fca2..0000000
--- a/subprojects/groovy-cli-commons/src/main/groovy/groovy/util/CliBuilder.groovy
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util
-
-import org.apache.commons.cli.CommandLineParser
-import org.apache.commons.cli.HelpFormatter
-
-/**
- * @deprecated use {@code groovy.cli.picocli.CliBuilder} or {@link groovy.cli.commons.CliBuilder} instead.
- */
-@Deprecated
-class CliBuilder {
- private @Delegate
- groovy.cli.commons.CliBuilder delegate = new groovy.cli.commons.CliBuilder()
-
- // explicit delegate to convert return type to expected legacy package
- OptionAccessor parse(args) {
- def result = delegate.parse(args)
- return result == null ? null : new OptionAccessor(delegate: result)
- }
-
- // explicit delegate since groovyObject methods ignored by @Delegate
- def invokeMethod(String name, Object args) {
- delegate.invokeMethod(name, args)
- }
-
- // delegated versions of the methods below are available but we want
- // IDE warnings to encourage people not to use these methods in particular
- // over and above the warning they should have at the class level
-
- /**
- * @deprecated This may not be available in future groovy.util.CliBuilder versions.
- * Use groovy.cli.commons.CliBuilder if you need this feature.
- */
- @Deprecated
- void setParser(CommandLineParser parser) {
- delegate.setParser(parser)
- }
-
- /**
- * @deprecated This may not be available in future groovy.util.CliBuilder versions.
- * Use groovy.cli.commons.CliBuilder if you need this feature.
- */
- @Deprecated
- CommandLineParser getParser() {
- delegate.getParser()
- }
-
- /**
- * @deprecated This may not be available in future groovy.util.CliBuilder versions.
- * Use groovy.cli.commons.CliBuilder if you need this feature.
- */
- @Deprecated
- void setFormatter(HelpFormatter formatter) {
- delegate.setFormatter(formatter)
- }
-
- /**
- * @deprecated This may not be available in future groovy.util.CliBuilder versions.
- * Use groovy.cli.commons.CliBuilder if you need this feature.
- */
- @Deprecated
- HelpFormatter getFormatter() {
- delegate.getFormatter()
- }
-}
diff --git a/subprojects/groovy-cli-commons/src/main/groovy/groovy/util/OptionAccessor.groovy b/subprojects/groovy-cli-commons/src/main/groovy/groovy/util/OptionAccessor.groovy
deleted file mode 100644
index 935cf10..0000000
--- a/subprojects/groovy-cli-commons/src/main/groovy/groovy/util/OptionAccessor.groovy
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util
-
-/**
- * @deprecated use {@code groovy.cli.picocli.OptionAccessor} or {@link groovy.cli.commons.OptionAccessor}
- */
-@Deprecated
-class OptionAccessor {
- @Delegate
- groovy.cli.commons.OptionAccessor delegate
-
- // explicit delegate since groovyObject methods ignored by @Delegate
- def getProperty(String name) {
- delegate.getProperty(name)
- }
-
- // explicit delegate since groovyObject methods ignored by @Delegate
- def invokeMethod(String name, Object args) {
- delegate.invokeMethod(name, args)
- }
-}
diff --git a/subprojects/groovy-jmx/src/main/java/groovy/util/GroovyMBean.java b/subprojects/groovy-jmx/src/main/java/groovy/util/GroovyMBean.java
deleted file mode 100644
index 0cb4bdc..0000000
--- a/subprojects/groovy-jmx/src/main/java/groovy/util/GroovyMBean.java
+++ /dev/null
@@ -1,394 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util;
-
-import groovy.lang.GroovyObjectSupport;
-import groovy.lang.GroovyRuntimeException;
-
-import javax.management.Attribute;
-import javax.management.JMException;
-import javax.management.MBeanAttributeInfo;
-import javax.management.MBeanException;
-import javax.management.MBeanInfo;
-import javax.management.MBeanOperationInfo;
-import javax.management.MBeanParameterInfo;
-import javax.management.MBeanServerConnection;
-import javax.management.ObjectName;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * A GroovyObject facade for an underlying MBean which acts like a normal
- * groovy object but which is actually implemented via
- * an underlying JMX MBean.
- * Properties and normal method invocations
- * delegate to the MBeanServer to the actual MBean.
- *
- * @deprecated Use {@link groovy.jmx.GroovyMBean}
- */
-@Deprecated
-public class GroovyMBean extends GroovyObjectSupport {
- private final MBeanServerConnection server;
- private final ObjectName name;
- private MBeanInfo beanInfo;
- private final boolean ignoreErrors;
- private final Map<String, String[]> operations = new HashMap<String, String[]>();
-
- public GroovyMBean(MBeanServerConnection server, String objectName) throws JMException, IOException {
- this(server, objectName, false);
- }
-
- public GroovyMBean(MBeanServerConnection server, String objectName, boolean ignoreErrors) throws JMException, IOException {
- this(server, new ObjectName(objectName), ignoreErrors);
- }
-
- public GroovyMBean(MBeanServerConnection server, ObjectName name) throws JMException, IOException {
- this(server, name, false);
- }
-
- public GroovyMBean(MBeanServerConnection server, ObjectName name, boolean ignoreErrors) throws JMException, IOException {
- this.server = server;
- this.name = name;
- this.ignoreErrors = ignoreErrors;
- this.beanInfo = server.getMBeanInfo(name);
-
- MBeanOperationInfo[] operationInfos = beanInfo.getOperations();
- for (MBeanOperationInfo info : operationInfos) {
- String signature[] = createSignature(info);
- // Construct a simplistic key to support overloaded operations on the MBean.
- String operationKey = createOperationKey(info.getName(), signature.length);
- operations.put(operationKey, signature);
- }
- }
-
- public MBeanServerConnection server() {
- return server;
- }
-
- public ObjectName name() {
- return name;
- }
-
- public MBeanInfo info() {
- return beanInfo;
- }
-
- public Object getProperty(String property) {
- try {
- return server.getAttribute(name, property);
- }
- catch (MBeanException e) {
- throwExceptionWithTarget("Could not access property: " + property + ". Reason: ", e);
- }
- catch (Exception e) {
- if (!ignoreErrors)
- throwException("Could not access property: " + property + ". Reason: ", e);
- }
- return null;
- }
-
- public void setProperty(String property, Object value) {
- try {
- server.setAttribute(name, new Attribute(property, value));
- }
- catch (MBeanException e) {
- throwExceptionWithTarget("Could not set property: " + property + ". Reason: ", e);
- }
- catch (Exception e) {
- throwException("Could not set property: " + property + ". Reason: ", e);
- }
- }
-
- public Object invokeMethod(String method, Object arguments) {
- Object[] argArray;
- if (arguments instanceof Object[]) {
- argArray = (Object[]) arguments;
- } else {
- argArray = new Object[]{arguments};
- }
- // Locate the specific method based on the name and number of parameters
- String operationKey = createOperationKey(method, argArray.length);
- String[] signature = operations.get(operationKey);
-
- if (signature != null) {
- try {
- return server.invoke(name, method, argArray, signature);
- }
- catch (MBeanException e) {
- throwExceptionWithTarget("Could not invoke method: " + method + ". Reason: ", e);
- }
- catch (Exception e) {
- throwException("Could not invoke method: " + method + ". Reason: ", e);
- }
- return null;
- } else {
- return super.invokeMethod(method, arguments);
- }
- }
-
- protected String[] createSignature(MBeanOperationInfo info) {
- MBeanParameterInfo[] params = info.getSignature();
- String[] answer = new String[params.length];
- for (int i = 0; i < params.length; i++) {
- answer[i] = params[i].getType();
- }
- return answer;
- }
-
- /**
- * Construct a simple key based on the method name and the number of parameters
- *
- * @param operation - the mbean operation name
- * @param params - the number of parameters the operation supports
- * @return simple unique identifier for a method
- */
- protected String createOperationKey(String operation, int params) {
- // This could be changed to support some hash of the parameter types, etc.
- // but should distinguish between reordered params while allowing normal
- // type coercions to be honored
- return operation + "_" + params;
- }
-
- /**
- * List of the names of each of the attributes on the MBean
- *
- * @return list of attribute names
- */
- public Collection<String> listAttributeNames() {
- List<String> list = new ArrayList<String>();
- try {
- MBeanAttributeInfo[] attrs = beanInfo.getAttributes();
- for (MBeanAttributeInfo attr : attrs) {
- list.add(attr.getName());
- }
- } catch (Exception e) {
- throwException("Could not list attribute names. Reason: ", e);
- }
- return list;
- }
-
- /**
- * The values of each of the attributes on the MBean
- *
- * @return list of values of each attribute
- */
- public List<String> listAttributeValues() {
- List<String> list = new ArrayList<String>();
- Collection<String> names = listAttributeNames();
- for (String name : names) {
- try {
- Object val = this.getProperty(name);
- if (val != null) {
- list.add(name + " : " + val.toString());
- }
- } catch (Exception e) {
- throwException("Could not list attribute values. Reason: ", e);
- }
- }
- return list;
- }
-
- /**
- * List of string representations of all of the attributes on the MBean.
- *
- * @return list of descriptions of each attribute on the mbean
- */
- public Collection<String> listAttributeDescriptions() {
- List<String> list = new ArrayList<String>();
- try {
- MBeanAttributeInfo[] attrs = beanInfo.getAttributes();
- for (MBeanAttributeInfo attr : attrs) {
- list.add(describeAttribute(attr));
- }
- } catch (Exception e) {
- throwException("Could not list attribute descriptions. Reason: ", e);
- }
- return list;
- }
-
- /**
- * Description of the specified attribute name.
- *
- * @param attr - the attribute
- * @return String the description
- */
- protected String describeAttribute(MBeanAttributeInfo attr) {
- StringBuilder buf = new StringBuilder();
- buf.append("(");
- if (attr.isReadable()) {
- buf.append("r");
- }
- if (attr.isWritable()) {
- buf.append("w");
- }
- buf.append(") ")
- .append(attr.getType())
- .append(" ")
- .append(attr.getName());
- return buf.toString();
- }
-
- /**
- * Description of the specified attribute name.
- *
- * @param attributeName - stringified name of the attribute
- * @return the description
- */
- public String describeAttribute(String attributeName) {
- String ret = "Attribute not found";
- try {
- MBeanAttributeInfo[] attributes = beanInfo.getAttributes();
- for (MBeanAttributeInfo attribute : attributes) {
- if (attribute.getName().equals(attributeName)) {
- return describeAttribute(attribute);
- }
- }
- } catch (Exception e) {
- throwException("Could not describe attribute '" + attributeName + "'. Reason: ", e);
- }
- return ret;
- }
-
- /**
- * Names of all the operations available on the MBean.
- *
- * @return all the operations on the MBean
- */
- public Collection<String> listOperationNames() {
- List<String> list = new ArrayList<String>();
- try {
- MBeanOperationInfo[] operations = beanInfo.getOperations();
- for (MBeanOperationInfo operation : operations) {
- list.add(operation.getName());
- }
- } catch (Exception e) {
- throwException("Could not list operation names. Reason: ", e);
- }
- return list;
- }
-
- /**
- * Description of all of the operations available on the MBean.
- *
- * @return full description of each operation on the MBean
- */
- public Collection<String> listOperationDescriptions() {
- List<String> list = new ArrayList<String>();
- try {
- MBeanOperationInfo[] operations = beanInfo.getOperations();
- for (MBeanOperationInfo operation : operations) {
- list.add(describeOperation(operation));
- }
- } catch (Exception e) {
- throwException("Could not list operation descriptions. Reason: ", e);
- }
- return list;
- }
-
- /**
- * Get the description of the specified operation. This returns a Collection since
- * operations can be overloaded and one operationName can have multiple forms.
- *
- * @param operationName the name of the operation to describe
- * @return Collection of operation description
- */
- public List<String> describeOperation(String operationName) {
- List<String> list = new ArrayList<String>();
- try {
- MBeanOperationInfo[] operations = beanInfo.getOperations();
- for (MBeanOperationInfo operation : operations) {
- if (operation.getName().equals(operationName)) {
- list.add(describeOperation(operation));
- }
- }
- } catch (Exception e) {
- throwException("Could not describe operations matching name '" + operationName + "'. Reason: ", e);
- }
- return list;
- }
-
- /**
- * Description of the operation.
- *
- * @param operation the operation to describe
- * @return pretty-printed description
- */
- protected String describeOperation(MBeanOperationInfo operation) {
- StringBuilder buf = new StringBuilder();
- buf.append(operation.getReturnType())
- .append(" ")
- .append(operation.getName())
- .append("(");
-
- MBeanParameterInfo[] params = operation.getSignature();
- for (int j = 0; j < params.length; j++) {
- MBeanParameterInfo param = params[j];
- if (j != 0) {
- buf.append(", ");
- }
- buf.append(param.getType())
- .append(" ")
- .append(param.getName());
- }
- buf.append(")");
- return buf.toString();
- }
-
- /**
- * Return an end user readable representation of the underlying MBean
- *
- * @return the user readable description
- */
- public String toString() {
- StringBuilder buf = new StringBuilder();
- buf.append("MBean Name:")
- .append("\n ")
- .append(name.getCanonicalName())
- .append("\n ");
- if (!listAttributeDescriptions().isEmpty()) {
- buf.append("\nAttributes:");
- for (String attrDesc : listAttributeDescriptions()) {
- buf.append("\n ").append(attrDesc);
- }
- }
- if (!listOperationDescriptions().isEmpty()) {
- buf.append("\nOperations:");
- for (String attrDesc : listOperationDescriptions()) {
- buf.append("\n ").append(attrDesc);
- }
- }
- return buf.toString();
- }
-
- private void throwException(String m, Exception e) {
- if (!ignoreErrors) {
- throw new GroovyRuntimeException(m + e, e);
- }
- }
-
- private void throwExceptionWithTarget(String m, MBeanException e) {
- if (!ignoreErrors) {
- throw new GroovyRuntimeException(m + e, e.getTargetException());
- }
- }
-}
diff --git a/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java b/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java
deleted file mode 100644
index 52e7b45..0000000
--- a/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java
+++ /dev/null
@@ -1,2023 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.codehaus.groovy.runtime;
-
-import groovy.io.FileType;
-import groovy.io.FileVisitResult;
-import groovy.io.GroovyPrintWriter;
-import groovy.lang.Closure;
-import groovy.lang.MetaClass;
-import groovy.lang.Writable;
-import groovy.transform.stc.ClosureParams;
-import groovy.transform.stc.FromString;
-import groovy.transform.stc.PickFirstResolver;
-import groovy.transform.stc.SimpleType;
-import org.codehaus.groovy.runtime.callsite.BooleanReturningMethodInvoker;
-import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.Closeable;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.io.Reader;
-import java.io.Writer;
-import java.net.URI;
-import java.nio.charset.Charset;
-import java.nio.file.DirectoryStream;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-import static java.nio.file.StandardOpenOption.APPEND;
-import static java.nio.file.StandardOpenOption.CREATE;
-import static org.codehaus.groovy.runtime.DefaultGroovyMethods.get;
-
-/**
- * This class defines new groovy methods for Readers, Writers, InputStreams and
- * OutputStreams which appear on normal JDK classes inside the Groovy environment.
- * Static methods are used with the first parameter being the destination class,
- * i.e. <code>public static T eachLine(InputStream self, Closure c)</code>
- * provides a <code>eachLine(Closure c)</code> method for <code>InputStream</code>.
- * <p/>
- * NOTE: While this class contains many 'public' static methods, it is
- * primarily regarded as an internal class (its internal package name
- * suggests this also). We value backwards compatibility of these
- * methods when used within Groovy but value less backwards compatibility
- * at the Java method call level. I.e. future versions of Groovy may
- * remove or move a method call in this file but would normally
- * aim to keep the method available from within Groovy.
- */
-@Deprecated
-public class NioGroovyMethods extends DefaultGroovyMethodsSupport {
-
- /**
- * Provide the standard Groovy <code>size()</code> method for <code>Path</code>.
- *
- * @param self a {@code Path} object
- * @return the file's size (length)
- * @since 2.3.0
- */
- @Deprecated
- public static long size(Path self) throws IOException {
- return Files.size(self);
- }
-
- /**
- * Create an object output stream for this path.
- *
- * @param self a {@code Path} object
- * @return an object output stream
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static ObjectOutputStream newObjectOutputStream(Path self) throws IOException {
- return new ObjectOutputStream(Files.newOutputStream(self));
- }
-
- /**
- * Create a new ObjectOutputStream for this path and then pass it to the
- * closure. This method ensures the stream is closed after the closure
- * returns.
- *
- * @param self a Path
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @see IOGroovyMethods#withStream(java.io.OutputStream, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withObjectOutputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.ObjectOutputStream") Closure<T> closure) throws IOException {
- return IOGroovyMethods.withStream(newObjectOutputStream(self), closure);
- }
-
- /**
- * Create an object input stream for this file.
- *
- * @param self a {@code Path} object
- * @return an object input stream
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static ObjectInputStream newObjectInputStream(Path self) throws IOException {
- return new ObjectInputStream(Files.newInputStream(self));
- }
-
- /**
- * Create an object input stream for this path using the given class loader.
- *
- * @param self a {@code Path} object
- * @param classLoader the class loader to use when loading the class
- * @return an object input stream
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static ObjectInputStream newObjectInputStream(Path self, final ClassLoader classLoader) throws IOException {
- return IOGroovyMethods.newObjectInputStream(Files.newInputStream(self), classLoader);
- }
-
- /**
- * Iterates through the given file object by object.
- *
- * @param self a {@code Path} object
- * @param closure a closure
- * @throws java.io.IOException if an IOException occurs.
- * @throws ClassNotFoundException if the class is not found.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#eachObject(java.io.ObjectInputStream, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static void eachObject(Path self, Closure closure) throws IOException, ClassNotFoundException {
- IOGroovyMethods.eachObject(newObjectInputStream(self), closure);
- }
-
- /**
- * Create a new ObjectInputStream for this file and pass it to the closure.
- * This method ensures the stream is closed after the closure returns.
- *
- * @param path a Path
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.InputStream, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withObjectInputStream(Path path, @ClosureParams(value = SimpleType.class, options = "java.io.ObjectInputStream") Closure<T> closure) throws IOException {
- return IOGroovyMethods.withStream(newObjectInputStream(path), closure);
- }
-
- /**
- * Create a new ObjectInputStream for this file associated with the given class loader and pass it to the closure.
- * This method ensures the stream is closed after the closure returns.
- *
- * @param self a Path
- * @param classLoader the class loader to use when loading the class
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.InputStream, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withObjectInputStream(Path self, ClassLoader classLoader, @ClosureParams(value = SimpleType.class, options = "java.io.ObjectInputStream") Closure<T> closure) throws IOException {
- return IOGroovyMethods.withStream(newObjectInputStream(self, classLoader), closure);
- }
-
- /**
- * Iterates through this path line by line. Each line is passed to the
- * given 1 or 2 arg closure. The file is read using a reader which
- * is closed before this method returns.
- *
- * @param self a Path
- * @param closure a closure (arg 1 is line, optional arg 2 is line number starting at line 1)
- * @return the last value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @see #eachLine(Path, int, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T eachLine(Path self, @ClosureParams(value = FromString.class, options = {"String", "String,Integer"}) Closure<T> closure) throws IOException {
- return eachLine(self, 1, closure);
- }
-
- /**
- * Iterates through this file line by line. Each line is passed to the
- * given 1 or 2 arg closure. The file is read using a reader which
- * is closed before this method returns.
- *
- * @param self a Path
- * @param charset opens the file with a specified charset
- * @param closure a closure (arg 1 is line, optional arg 2 is line number starting at line 1)
- * @return the last value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @see #eachLine(Path, String, int, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T eachLine(Path self, String charset, @ClosureParams(value = FromString.class, options = {"String", "String,Integer"}) Closure<T> closure) throws IOException {
- return eachLine(self, charset, 1, closure);
- }
-
- /**
- * Iterates through this file line by line. Each line is passed
- * to the given 1 or 2 arg closure. The file is read using a reader
- * which is closed before this method returns.
- *
- * @param self a Path
- * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0)
- * @param closure a closure (arg 1 is line, optional arg 2 is line number)
- * @return the last value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#eachLine(java.io.Reader, int, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T eachLine(Path self, int firstLine, @ClosureParams(value = FromString.class, options = {"String", "String,Integer"}) Closure<T> closure) throws IOException {
- return IOGroovyMethods.eachLine(newReader(self), firstLine, closure);
- }
-
- /**
- * Iterates through this file line by line. Each line is passed
- * to the given 1 or 2 arg closure. The file is read using a reader
- * which is closed before this method returns.
- *
- * @param self a Path
- * @param charset opens the file with a specified charset
- * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0)
- * @param closure a closure (arg 1 is line, optional arg 2 is line number)
- * @return the last value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#eachLine(java.io.Reader, int, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T eachLine(Path self, String charset, int firstLine, @ClosureParams(value = FromString.class, options = {"String", "String,Integer"}) Closure<T> closure) throws IOException {
- return IOGroovyMethods.eachLine(newReader(self, charset), firstLine, closure);
- }
-
- /**
- * Iterates through this file line by line, splitting each line using
- * the given regex separator. For each line, the given closure is called with
- * a single parameter being the list of strings computed by splitting the line
- * around matches of the given regular expression.
- * Finally the resources used for processing the file are closed.
- *
- * @param self a Path
- * @param regex the delimiting regular expression
- * @param closure a closure
- * @return the last value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#splitEachLine(java.io.Reader, String, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T splitEachLine(Path self, String regex, @ClosureParams(value = FromString.class, options = {"List<String>", "String[]"}, conflictResolutionStrategy = PickFirstResolver.class) Closure<T> closure) throws IOException {
- return IOGroovyMethods.splitEachLine(newReader(self), regex, closure);
- }
-
- /**
- * Iterates through this file line by line, splitting each line using
- * the given separator Pattern. For each line, the given closure is called with
- * a single parameter being the list of strings computed by splitting the line
- * around matches of the given regular expression Pattern.
- * Finally the resources used for processing the file are closed.
- *
- * @param self a Path
- * @param pattern the regular expression Pattern for the delimiter
- * @param closure a closure
- * @return the last value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T splitEachLine(Path self, Pattern pattern, @ClosureParams(value = FromString.class, options = {"List<String>", "String[]"}, conflictResolutionStrategy = PickFirstResolver.class) Closure<T> closure) throws IOException {
- return IOGroovyMethods.splitEachLine(newReader(self), pattern, closure);
- }
-
- /**
- * Iterates through this file line by line, splitting each line using
- * the given regex separator. For each line, the given closure is called with
- * a single parameter being the list of strings computed by splitting the line
- * around matches of the given regular expression.
- * Finally the resources used for processing the file are closed.
- *
- * @param self a Path
- * @param regex the delimiting regular expression
- * @param charset opens the file with a specified charset
- * @param closure a closure
- * @return the last value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#splitEachLine(java.io.Reader, String, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T splitEachLine(Path self, String regex, String charset, @ClosureParams(value = FromString.class, options = {"List<String>", "String[]"}, conflictResolutionStrategy = PickFirstResolver.class) Closure<T> closure) throws IOException {
- return IOGroovyMethods.splitEachLine(newReader(self, charset), regex, closure);
- }
-
- /**
- * Iterates through this file line by line, splitting each line using
- * the given regex separator Pattern. For each line, the given closure is called with
- * a single parameter being the list of strings computed by splitting the line
- * around matches of the given regular expression.
- * Finally the resources used for processing the file are closed.
- *
- * @param self a Path
- * @param pattern the regular expression Pattern for the delimiter
- * @param charset opens the file with a specified charset
- * @param closure a closure
- * @return the last value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T splitEachLine(Path self, Pattern pattern, String charset, @ClosureParams(value = FromString.class, options = {"List<String>", "String[]"}, conflictResolutionStrategy = PickFirstResolver.class) Closure<T> closure) throws IOException {
- return IOGroovyMethods.splitEachLine(newReader(self, charset), pattern, closure);
- }
-
- /**
- * Reads the file into a list of Strings, with one item for each line.
- *
- * @param self a Path
- * @return a List of lines
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#readLines(java.io.Reader)
- * @since 2.3.0
- */
- @Deprecated
- public static List<String> readLines(Path self) throws IOException {
- return IOGroovyMethods.readLines(newReader(self));
- }
-
- /**
- * Reads the file into a list of Strings, with one item for each line.
- *
- * @param self a Path
- * @param charset opens the file with a specified charset
- * @return a List of lines
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#readLines(java.io.Reader)
- * @since 2.3.0
- */
- @Deprecated
- public static List<String> readLines(Path self, String charset) throws IOException {
- return IOGroovyMethods.readLines(newReader(self, charset));
- }
-
- /**
- * Read the content of the Path using the specified encoding and return it
- * as a String.
- *
- * @param self the file whose content we want to read
- * @param charset the charset used to read the content of the file
- * @return a String containing the content of the file
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static String getText(Path self, String charset) throws IOException {
- return IOGroovyMethods.getText(newReader(self, charset));
- }
-
- /**
- * Read the content of the Path and returns it as a String.
- *
- * @param self the file whose content we want to read
- * @return a String containing the content of the file
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static String getText(Path self) throws IOException {
- return IOGroovyMethods.getText(newReader(self));
- }
-
- /**
- * Read the content of the Path and returns it as a byte[].
- *
- * @param self the file whose content we want to read
- * @return a String containing the content of the file
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static byte[] getBytes(Path self) throws IOException {
- return IOGroovyMethods.getBytes(Files.newInputStream(self));
- }
-
- /**
- * Write the bytes from the byte array to the Path.
- *
- * @param self the file to write to
- * @param bytes the byte[] to write to the file
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static void setBytes(Path self, byte[] bytes) throws IOException {
- IOGroovyMethods.setBytes(Files.newOutputStream(self), bytes);
- }
-
- /**
- * Write the text to the Path without writing a BOM .
- *
- * @param self a Path
- * @param text the text to write to the Path
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static void write(Path self, String text) throws IOException {
- write(self, text, false);
- }
-
- /**
- * Write the text to the Path. If the default charset is
- * "UTF-16BE" or "UTF-16LE" (or an equivalent alias) and
- * <code>writeBom</code> is <code>true</code>, the requisite byte order
- * mark is written to the file before the text.
- *
- * @param self a Path
- * @param text the text to write to the Path
- * @param writeBom whether to write the BOM
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.5.0
- */
- @Deprecated
- public static void write(Path self, String text, boolean writeBom) throws IOException {
- write(self, text, Charset.defaultCharset().name(), writeBom);
- }
-
- /**
- * Synonym for write(text) allowing file.text = 'foo'.
- *
- * @param self a Path
- * @param text the text to write to the Path
- * @throws java.io.IOException if an IOException occurs.
- * @see #write(Path, String)
- * @since 2.3.0
- */
- @Deprecated
- public static void setText(Path self, String text) throws IOException {
- write(self, text);
- }
-
- /**
- * Synonym for write(text, charset) allowing:
- * <pre>
- * myFile.setText('some text', charset)
- * </pre>
- * or with some help from <code>ExpandoMetaClass</code>, you could do something like:
- * <pre>
- * myFile.metaClass.setText = { String s {@code ->} delegate.setText(s, 'UTF-8') }
- * myfile.text = 'some text'
- * </pre>
- *
- * @param self A Path
- * @param charset The charset used when writing to the file
- * @param text The text to write to the Path
- * @throws java.io.IOException if an IOException occurs.
- * @see #write(Path, String, String)
- * @since 2.3.0
- */
- @Deprecated
- public static void setText(Path self, String text, String charset) throws IOException {
- write(self, text, charset);
- }
-
- /**
- * Write the text to the Path.
- *
- * @param self a Path
- * @param text the text to write to the Path
- * @return the original file
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static Path leftShift(Path self, Object text) throws IOException {
- append(self, text);
- return self;
- }
-
- /**
- * Write bytes to a Path.
- *
- * @param self a Path
- * @param bytes the byte array to append to the end of the Path
- * @return the original file
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static Path leftShift(Path self, byte[] bytes) throws IOException {
- append(self, bytes);
- return self;
- }
-
- /**
- * Append binary data to the file. See {@link #append(Path, java.io.InputStream)}
- *
- * @param path a Path
- * @param data an InputStream of data to write to the file
- * @return the file
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static Path leftShift(Path path, InputStream data) throws IOException {
- append(path, data);
- return path;
- }
-
- /**
- * Write the text to the Path without writing a BOM, using the specified encoding.
- *
- * @param self a Path
- * @param text the text to write to the Path
- * @param charset the charset used
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static void write(Path self, String text, String charset) throws IOException {
- write(self, text, charset, false);
- }
-
- /**
- * Write the text to the Path, using the specified encoding. If the given
- * charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias) and
- * <code>writeBom</code> is <code>true</code>, the requisite byte order
- * mark is written to the file before the text.
- *
- * @param self a Path
- * @param text the text to write to the Path
- * @param charset the charset used
- * @param writeBom whether to write a BOM
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.5.0
- */
- @Deprecated
- public static void write(Path self, String text, String charset, boolean writeBom) throws IOException {
- Writer writer = null;
- try {
- OutputStream out = Files.newOutputStream(self);
- if (writeBom) {
- writeUTF16BomIfRequired(out, charset);
- }
- writer = new OutputStreamWriter(out, Charset.forName(charset));
- writer.write(text);
- writer.flush();
-
- Writer temp = writer;
- writer = null;
- temp.close();
- } finally {
- closeWithWarning(writer);
- }
- }
-
- /**
- * Append the text at the end of the Path without writing a BOM.
- *
- * @param self a Path
- * @param text the text to append at the end of the Path
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static void append(Path self, Object text) throws IOException {
- append(self, text, Charset.defaultCharset().name(), false);
- }
-
- /**
- * Append the text supplied by the Writer at the end of the File without
- * writing a BOM.
- *
- * @param file a Path
- * @param reader the Reader supplying the text to append at the end of the File
- * @throws IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static void append(Path file, Reader reader) throws IOException {
- append(file, reader, Charset.defaultCharset().name());
- }
-
- /**
- * Append the text supplied by the Writer at the end of the File without writing a BOM.
- *
- * @param file a File
- * @param writer the Writer supplying the text to append at the end of the File
- * @throws IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static void append(Path file, Writer writer) throws IOException {
- append(file, writer, Charset.defaultCharset().name());
- }
-
- /**
- * Append bytes to the end of a Path. It <strong>will not</strong> be
- * interpreted as text.
- *
- * @param self a Path
- * @param bytes the byte array to append to the end of the Path
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static void append(Path self, byte[] bytes) throws IOException {
- OutputStream stream = null;
- try {
- stream = Files.newOutputStream(self, CREATE, APPEND);
- stream.write(bytes, 0, bytes.length);
- stream.flush();
-
- OutputStream temp = stream;
- stream = null;
- temp.close();
- } finally {
- closeWithWarning(stream);
- }
- }
-
- /**
- * Append binary data to the file. It <strong>will not</strong> be
- * interpreted as text.
- *
- * @param self a Path
- * @param stream stream to read data from.
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static void append(Path self, InputStream stream) throws IOException {
- OutputStream out = Files.newOutputStream(self, CREATE, APPEND);
- try {
- IOGroovyMethods.leftShift(out, stream);
- } finally {
- closeWithWarning(out);
- }
- }
-
- /**
- * Append the text at the end of the Path. If the default charset is
- * "UTF-16BE" or "UTF-16LE" (or an equivalent alias) and
- * <code>writeBom</code> is <code>true</code>, the requisite byte order
- * mark is written to the file before the text.
- *
- * @param self a Path
- * @param text the text to append at the end of the Path
- * @param writeBom whether to write the BOM
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.5.0
- */
- @Deprecated
- public static void append(Path self, Object text, boolean writeBom) throws IOException {
- append(self, text, Charset.defaultCharset().name(), writeBom);
- }
-
- /**
- * Append the text at the end of the Path without writing a BOM, using a specified
- * encoding.
- *
- * @param self a Path
- * @param text the text to append at the end of the Path
- * @param charset the charset used
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static void append(Path self, Object text, String charset) throws IOException {
- append(self, text, charset, false);
- }
-
- /**
- * Append the text at the end of the Path, using a specified encoding. If
- * the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias),
- * <code>writeBom</code> is <code>true</code>, and the file doesn't already
- * exist, the requisite byte order mark is written to the file before the
- * text is appended.
- *
- * @param self a Path
- * @param text the text to append at the end of the Path
- * @param charset the charset used
- * @param writeBom whether to write the BOM
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.5.0
- */
- @Deprecated
- public static void append(Path self, Object text, String charset, boolean writeBom) throws IOException {
- Writer writer = null;
- try {
- Charset resolvedCharset = Charset.forName(charset);
- boolean shouldWriteBom = writeBom && !self.toFile().exists();
- OutputStream out = Files.newOutputStream(self, CREATE, APPEND);
- if (shouldWriteBom) {
- writeUTF16BomIfRequired(out, resolvedCharset);
- }
- writer = new OutputStreamWriter(out, resolvedCharset);
- InvokerHelper.write(writer, text);
- writer.flush();
-
- Writer temp = writer;
- writer = null;
- temp.close();
- } finally {
- closeWithWarning(writer);
- }
- }
-
- /**
- * Append the text supplied by the Writer at the end of the File, using a specified encoding.
- * If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias),
- * <code>writeBom</code> is <code>true</code>, and the file doesn't already
- * exist, the requisite byte order mark is written to the file before the
- * text is appended.
- *
- * @param file a File
- * @param writer the Writer supplying the text to append at the end of the File
- * @param writeBom whether to write the BOM
- * @throws IOException if an IOException occurs.
- * @since 2.5.0
- */
- @Deprecated
- public static void append(Path file, Writer writer, boolean writeBom) throws IOException {
- append(file, writer, Charset.defaultCharset().name(), writeBom);
- }
-
- /**
- * Append the text supplied by the Writer at the end of the File without writing a BOM,
- * using a specified encoding.
- *
- * @param file a File
- * @param writer the Writer supplying the text to append at the end of the File
- * @param charset the charset used
- * @throws IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static void append(Path file, Writer writer, String charset) throws IOException {
- appendBuffered(file, writer, charset, false);
- }
-
- /**
- * Append the text supplied by the Writer at the end of the File, using a specified encoding.
- * If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias),
- * <code>writeBom</code> is <code>true</code>, and the file doesn't already
- * exist, the requisite byte order mark is written to the file before the
- * text is appended.
- *
- * @param file a File
- * @param writer the Writer supplying the text to append at the end of the File
- * @param charset the charset used
- * @param writeBom whether to write the BOM
- * @throws IOException if an IOException occurs.
- * @since 2.5.0
- */
- @Deprecated
- public static void append(Path file, Writer writer, String charset, boolean writeBom) throws IOException {
- appendBuffered(file, writer, charset, writeBom);
- }
-
- /**
- * Append the text supplied by the Reader at the end of the File, using a specified encoding.
- * If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias),
- * <code>writeBom</code> is <code>true</code>, and the file doesn't already
- * exist, the requisite byte order mark is written to the file before the
- * text is appended.
- *
- * @param file a File
- * @param reader the Reader supplying the text to append at the end of the File
- * @param writeBom whether to write the BOM
- * @throws IOException if an IOException occurs.
- * @since 2.5.0
- */
- @Deprecated
- public static void append(Path file, Reader reader, boolean writeBom) throws IOException {
- appendBuffered(file, reader, Charset.defaultCharset().name(), writeBom);
- }
-
- /**
- * Append the text supplied by the Reader at the end of the File without writing
- * a BOM, using a specified encoding.
- *
- * @param file a File
- * @param reader the Reader supplying the text to append at the end of the File
- * @param charset the charset used
- * @throws IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static void append(Path file, Reader reader, String charset) throws IOException {
- append(file, reader, charset, false);
- }
-
- /**
- * Append the text supplied by the Reader at the end of the File, using a specified encoding.
- * If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias),
- * <code>writeBom</code> is <code>true</code>, and the file doesn't already
- * exist, the requisite byte order mark is written to the file before the
- * text is appended.
- *
- * @param file a File
- * @param reader the Reader supplying the text to append at the end of the File
- * @param charset the charset used
- * @param writeBom whether to write the BOM
- * @throws IOException if an IOException occurs.
- * @since 2.5.0
- */
- @Deprecated
- public static void append(Path file, Reader reader, String charset, boolean writeBom) throws IOException {
- appendBuffered(file, reader, charset, writeBom);
- }
-
- private static void appendBuffered(Path file, Object text, String charset, boolean writeBom) throws IOException {
- BufferedWriter writer = null;
- try {
- boolean shouldWriteBom = writeBom && !file.toFile().exists();
- writer = newWriter(file, charset, true);
- if (shouldWriteBom) {
- writeUTF16BomIfRequired(writer, charset);
- }
- InvokerHelper.write(writer, text);
- writer.flush();
-
- Writer temp = writer;
- writer = null;
- temp.close();
- } finally {
- closeWithWarning(writer);
- }
- }
-
- /**
- * This method is used to throw useful exceptions when the eachFile* and eachDir closure methods
- * are used incorrectly.
- *
- * @param self The directory to check
- * @throws java.io.FileNotFoundException if the given directory does not exist
- * @throws IllegalArgumentException if the provided Path object does not represent a directory
- * @since 2.3.0
- */
- private static void checkDir(Path self) throws FileNotFoundException, IllegalArgumentException {
- if (!Files.exists(self))
- throw new FileNotFoundException(self.toAbsolutePath().toString());
- if (!Files.isDirectory(self))
- throw new IllegalArgumentException("The provided Path object is not a directory: " + self.toAbsolutePath());
- }
-
- /**
- * Invokes the closure for each 'child' file in this 'parent' folder/directory.
- * Both regular files and subfolders/subdirectories can be processed depending
- * on the fileType enum value.
- *
- * @param self a Path (that happens to be a folder/directory)
- * @param fileType if normal files or directories or both should be processed
- * @param closure the closure to invoke
- * @throws java.io.FileNotFoundException if the given directory does not exist
- * @throws IllegalArgumentException if the provided Path object does not represent a directory
- * @since 2.3.0
- */
- @Deprecated
- public static void eachFile(final Path self, final FileType fileType, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException {
- //throws FileNotFoundException, IllegalArgumentException {
- checkDir(self);
-
- // TODO GroovyDoc doesn't parse this file as our java.g doesn't handle this JDK7 syntax
- try (DirectoryStream<Path> stream = Files.newDirectoryStream(self)) {
- for (Path path : stream) {
- if (fileType == FileType.ANY ||
- (fileType != FileType.FILES && Files.isDirectory(path)) ||
- (fileType != FileType.DIRECTORIES && Files.isRegularFile(path))) {
- closure.call(path);
- }
- }
- }
- }
-
- /**
- * Invokes the closure for each 'child' file in this 'parent' folder/directory.
- * Both regular files and subfolders/subdirectories are processed.
- *
- * @param self a Path (that happens to be a folder/directory)
- * @param closure a closure (the parameter is the Path for the 'child' file)
- * @throws java.io.FileNotFoundException if the given directory does not exist
- * @throws IllegalArgumentException if the provided Path object does not represent a directory
- * @see #eachFile(Path, groovy.io.FileType, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static void eachFile(final Path self, final Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException {
- eachFile(self, FileType.ANY, closure);
- }
-
- /**
- * Invokes the closure for each subdirectory in this directory,
- * ignoring regular files.
- *
- * @param self a Path (that happens to be a folder/directory)
- * @param closure a closure (the parameter is the Path for the subdirectory file)
- * @throws java.io.FileNotFoundException if the given directory does not exist
- * @throws IllegalArgumentException if the provided Path object does not represent a directory
- * @see #eachFile(Path, groovy.io.FileType, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static void eachDir(Path self, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException {
- eachFile(self, FileType.DIRECTORIES, closure);
- }
-
- /**
- * Processes each descendant file in this directory and any sub-directories.
- * Processing consists of potentially calling <code>closure</code> passing it the current
- * file (which may be a normal file or subdirectory) and then if a subdirectory was encountered,
- * recursively processing the subdirectory. Whether the closure is called is determined by whether
- * the file was a normal file or subdirectory and the value of fileType.
- *
- * @param self a Path (that happens to be a folder/directory)
- * @param fileType if normal files or directories or both should be processed
- * @param closure the closure to invoke on each file
- * @throws java.io.FileNotFoundException if the given directory does not exist
- * @throws IllegalArgumentException if the provided Path object does not represent a directory
- * @since 2.3.0
- */
- @Deprecated
- public static void eachFileRecurse(final Path self, final FileType fileType, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException {
- // throws FileNotFoundException, IllegalArgumentException {
- checkDir(self);
- try (DirectoryStream<Path> stream = Files.newDirectoryStream(self)) {
- for (Path path : stream) {
- if (Files.isDirectory(path)) {
- if (fileType != FileType.FILES) closure.call(path);
- eachFileRecurse(path, fileType, closure);
- } else if (fileType != FileType.DIRECTORIES) {
- closure.call(path);
- }
- }
- }
- }
-
- /**
- * Processes each descendant file in this directory and any sub-directories.
- * Processing consists of potentially calling <code>closure</code> passing it the current
- * file (which may be a normal file or subdirectory) and then if a subdirectory was encountered,
- * recursively processing the subdirectory.
- * <p>
- * The traversal can be adapted by providing various options in the <code>options</code> Map according
- * to the following keys:<dl>
- * <dt>type</dt><dd>A {@link groovy.io.FileType} enum to determine if normal files or directories or both are processed</dd>
- * <dt>preDir</dt><dd>A {@link groovy.lang.Closure} run before each directory is processed and optionally returning a {@link groovy.io.FileVisitResult} value
- * which can be used to control subsequent processing.</dd>
- * <dt>preRoot</dt><dd>A boolean indicating that the 'preDir' closure should be applied at the root level</dd>
- * <dt>postDir</dt><dd>A {@link groovy.lang.Closure} run after each directory is processed and optionally returning a {@link groovy.io.FileVisitResult} value
- * which can be used to control subsequent processing.</dd>
- * <dt>postRoot</dt><dd>A boolean indicating that the 'postDir' closure should be applied at the root level</dd>
- * <dt>visitRoot</dt><dd>A boolean indicating that the given closure should be applied for the root dir
- * (not applicable if the 'type' is set to {@link groovy.io.FileType#FILES})</dd>
- * <dt>maxDepth</dt><dd>The maximum number of directory levels when recursing
- * (default is -1 which means infinite, set to 0 for no recursion)</dd>
- * <dt>filter</dt><dd>A filter to perform on traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method). If set,
- * only files/dirs which match are candidates for visiting.</dd>
- * <dt>nameFilter</dt><dd>A filter to perform on the name of traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method). If set,
- * only files/dirs which match are candidates for visiting. (Must not be set if 'filter' is set)</dd>
- * <dt>excludeFilter</dt><dd>A filter to perform on traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method).
- * If set, any candidates which match won't be visited.</dd>
- * <dt>excludeNameFilter</dt><dd>A filter to perform on the names of traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method).
- * If set, any candidates which match won't be visited. (Must not be set if 'excludeFilter' is set)</dd>
- * <dt>sort</dt><dd>A {@link groovy.lang.Closure} which if set causes the files and subdirectories for each directory to be processed in sorted order.
- * Note that even when processing only files, the order of visited subdirectories will be affected by this parameter.</dd>
- * </dl>
- * This example prints out file counts and size aggregates for groovy source files within a directory tree:
- * <pre>
- * def totalSize = 0
- * def count = 0
- * def sortByTypeThenName = { a, b {@code ->}
- * a.isFile() != b.isFile() ? a.isFile() {@code <=>} b.isFile() : a.name {@code <=>} b.name
- * }
- * rootDir.traverse(
- * type : FILES,
- * nameFilter : ~/.*\.groovy/,
- * preDir : { if (it.name == '.svn') return SKIP_SUBTREE },
- * postDir : { println "Found $count files in $it.name totalling $totalSize bytes"
- * totalSize = 0; count = 0 },
- * postRoot : true
- * sort : sortByTypeThenName
- * ) {it {@code ->} totalSize += it.size(); count++ }
- * </pre>
- *
- * @param self a Path (that happens to be a folder/directory)
- * @param options a Map of options to alter the traversal behavior
- * @param closure the Closure to invoke on each file/directory and optionally returning a {@link groovy.io.FileVisitResult} value
- * which can be used to control subsequent processing
- * @throws java.io.FileNotFoundException if the given directory does not exist
- * @throws IllegalArgumentException if the provided Path object does not represent a directory or illegal filter combinations are supplied
- * @see DefaultGroovyMethods#sort(java.util.Collection, groovy.lang.Closure)
- * @see groovy.io.FileVisitResult
- * @see groovy.io.FileType
- * @since 2.3.0
- */
- @Deprecated
- public static void traverse(final Path self, final Map<String, Object> options, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure)
- throws IOException {
- // throws FileNotFoundException, IllegalArgumentException {
- Number maxDepthNumber = DefaultGroovyMethods.asType(options.remove("maxDepth"), Number.class);
- int maxDepth = maxDepthNumber == null ? -1 : maxDepthNumber.intValue();
- Boolean visitRoot = DefaultGroovyMethods.asType(get(options, "visitRoot", false), Boolean.class);
- Boolean preRoot = DefaultGroovyMethods.asType(get(options, "preRoot", false), Boolean.class);
- Boolean postRoot = DefaultGroovyMethods.asType(get(options, "postRoot", false), Boolean.class);
- final Closure pre = (Closure) options.get("preDir");
- final Closure post = (Closure) options.get("postDir");
- final FileType type = (FileType) options.get("type");
- final Object filter = options.get("filter");
- final Object nameFilter = options.get("nameFilter");
- final Object excludeFilter = options.get("excludeFilter");
- final Object excludeNameFilter = options.get("excludeNameFilter");
- Object preResult = null;
- if (preRoot && pre != null) {
- preResult = pre.call(self);
- }
- if (preResult == FileVisitResult.TERMINATE ||
- preResult == FileVisitResult.SKIP_SUBTREE) return;
-
- FileVisitResult terminated = traverse(self, options, closure, maxDepth);
-
- if (type != FileType.FILES && visitRoot) {
- if (closure != null && notFiltered(self, filter, nameFilter, excludeFilter, excludeNameFilter)) {
- Object closureResult = closure.call(self);
- if (closureResult == FileVisitResult.TERMINATE) return;
- }
- }
-
- if (postRoot && post != null && terminated != FileVisitResult.TERMINATE) post.call(self);
- }
-
- private static boolean notFiltered(Path path, Object filter, Object nameFilter, Object excludeFilter, Object excludeNameFilter) {
- if (filter == null && nameFilter == null && excludeFilter == null && excludeNameFilter == null) return true;
- if (filter != null && nameFilter != null)
- throw new IllegalArgumentException("Can't set both 'filter' and 'nameFilter'");
- if (excludeFilter != null && excludeNameFilter != null)
- throw new IllegalArgumentException("Can't set both 'excludeFilter' and 'excludeNameFilter'");
- Object filterToUse = null;
- Object filterParam = null;
- if (filter != null) {
- filterToUse = filter;
- filterParam = path;
- } else if (nameFilter != null) {
- filterToUse = nameFilter;
- filterParam = path.getFileName().toString();
- }
- Object excludeFilterToUse = null;
- Object excludeParam = null;
- if (excludeFilter != null) {
- excludeFilterToUse = excludeFilter;
- excludeParam = path;
- } else if (excludeNameFilter != null) {
- excludeFilterToUse = excludeNameFilter;
- excludeParam = path.getFileName().toString();
- }
- final MetaClass filterMC = filterToUse == null ? null : InvokerHelper.getMetaClass(filterToUse);
- final MetaClass excludeMC = excludeFilterToUse == null ? null : InvokerHelper.getMetaClass(excludeFilterToUse);
- boolean included = filterToUse == null || DefaultTypeTransformation.castToBoolean(filterMC.invokeMethod(filterToUse, "isCase", filterParam));
- boolean excluded = excludeFilterToUse != null && DefaultTypeTransformation.castToBoolean(excludeMC.invokeMethod(excludeFilterToUse, "isCase", excludeParam));
- return included && !excluded;
- }
-
- /**
- * Processes each descendant file in this directory and any sub-directories.
- * Convenience method for {@link #traverse(Path, java.util.Map, groovy.lang.Closure)} when
- * no options to alter the traversal behavior are required.
- *
- * @param self a Path (that happens to be a folder/directory)
- * @param closure the Closure to invoke on each file/directory and optionally returning a {@link groovy.io.FileVisitResult} value
- * which can be used to control subsequent processing
- * @throws java.io.FileNotFoundException if the given directory does not exist
- * @throws IllegalArgumentException if the provided Path object does not represent a directory
- * @see #traverse(Path, java.util.Map, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static void traverse(final Path self, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure)
- throws IOException {
- traverse(self, new HashMap<String, Object>(), closure);
- }
-
- /**
- * Invokes the closure specified with key 'visit' in the options Map
- * for each descendant file in this directory tree. Convenience method
- * for {@link #traverse(Path, java.util.Map, groovy.lang.Closure)} allowing the 'visit' closure
- * to be included in the options Map rather than as a parameter.
- *
- * @param self a Path (that happens to be a folder/directory)
- * @param options a Map of options to alter the traversal behavior
- * @throws java.io.FileNotFoundException if the given directory does not exist
- * @throws IllegalArgumentException if the provided Path object does not represent a directory or illegal filter combinations are supplied
- * @see #traverse(Path, java.util.Map, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static void traverse(final Path self, final Map<String, Object> options)
- throws IOException {
- final Closure visit = (Closure) options.remove("visit");
- traverse(self, options, visit);
- }
-
- private static FileVisitResult traverse(final Path self, final Map<String, Object> options, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure, final int maxDepth)
- throws IOException {
- checkDir(self);
- final Closure pre = (Closure) options.get("preDir");
- final Closure post = (Closure) options.get("postDir");
- final FileType type = (FileType) options.get("type");
- final Object filter = options.get("filter");
- final Object nameFilter = options.get("nameFilter");
- final Object excludeFilter = options.get("excludeFilter");
- final Object excludeNameFilter = options.get("excludeNameFilter");
- final Closure sort = (Closure) options.get("sort");
-
- try (DirectoryStream<Path> stream = Files.newDirectoryStream(self)) {
- final Iterator<Path> itr = stream.iterator();
- List<Path> files = new LinkedList<Path>();
- while (itr.hasNext()) {
- files.add(itr.next());
- }
-
- if (sort != null) files = DefaultGroovyMethods.sort((Iterable<Path>) files, sort);
-
- for (Path path : files) {
- if (Files.isDirectory(path)) {
- if (type != FileType.FILES) {
- if (closure != null && notFiltered(path, filter, nameFilter, excludeFilter, excludeNameFilter)) {
- Object closureResult = closure.call(path);
- if (closureResult == FileVisitResult.SKIP_SIBLINGS) break;
- if (closureResult == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE;
- }
- }
- if (maxDepth != 0) {
- Object preResult = null;
- if (pre != null) {
- preResult = pre.call(path);
- }
- if (preResult == FileVisitResult.SKIP_SIBLINGS) break;
- if (preResult == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE;
- if (preResult != FileVisitResult.SKIP_SUBTREE) {
- FileVisitResult terminated = traverse(path, options, closure, maxDepth - 1);
- if (terminated == FileVisitResult.TERMINATE) return terminated;
- }
- Object postResult = null;
- if (post != null) {
- postResult = post.call(path);
- }
- if (postResult == FileVisitResult.SKIP_SIBLINGS) break;
- if (postResult == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE;
- }
- } else if (type != FileType.DIRECTORIES) {
- if (closure != null && notFiltered(path, filter, nameFilter, excludeFilter, excludeNameFilter)) {
- Object closureResult = closure.call(path);
- if (closureResult == FileVisitResult.SKIP_SIBLINGS) break;
- if (closureResult == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE;
- }
- }
- }
-
- return FileVisitResult.CONTINUE;
- }
- }
-
- /**
- * Processes each descendant file in this directory and any sub-directories.
- * Processing consists of calling <code>closure</code> passing it the current
- * file (which may be a normal file or subdirectory) and then if a subdirectory was encountered,
- * recursively processing the subdirectory.
- *
- * @param self a Path (that happens to be a folder/directory)
- * @param closure a Closure
- * @throws java.io.FileNotFoundException if the given directory does not exist
- * @throws IllegalArgumentException if the provided Path object does not represent a directory
- * @see #eachFileRecurse(Path, groovy.io.FileType, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static void eachFileRecurse(Path self, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException {
- eachFileRecurse(self, FileType.ANY, closure);
- }
-
- /**
- * Recursively processes each descendant subdirectory in this directory.
- * Processing consists of calling <code>closure</code> passing it the current
- * subdirectory and then recursively processing that subdirectory.
- * Regular files are ignored during traversal.
- *
- * @param self a Path (that happens to be a folder/directory)
- * @param closure a closure
- * @throws java.io.FileNotFoundException if the given directory does not exist
- * @throws IllegalArgumentException if the provided Path object does not represent a directory
- * @see #eachFileRecurse(Path, groovy.io.FileType, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static void eachDirRecurse(final Path self, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException { //throws FileNotFoundException, IllegalArgumentException {
- eachFileRecurse(self, FileType.DIRECTORIES, closure);
- }
-
- /**
- * Invokes the closure for each file whose name (file.name) matches the given nameFilter in the given directory
- * - calling the {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#isCase(Object, Object)} method to determine if a match occurs. This method can be used
- * with different kinds of filters like regular expressions, classes, ranges etc.
- * Both regular files and subdirectories may be candidates for matching depending
- * on the value of fileType.
- * <pre>
- * // collect names of files in baseDir matching supplied regex pattern
- * import static groovy.io.FileType.*
- * def names = []
- * baseDir.eachFileMatch FILES, ~/foo\d\.txt/, { names {@code <<} it.name }
- * assert names == ['foo1.txt', 'foo2.txt']
- *
- * // remove all *.bak files in baseDir
- * baseDir.eachFileMatch FILES, ~/.*\.bak/, { Path bak {@code ->} bak.delete() }
- *
- * // print out files > 4K in size from baseDir
- * baseDir.eachFileMatch FILES, { new Path(baseDir, it).size() {@code >} 4096 }, { println "$it.name ${it.size()}" }
- * </pre>
- *
- * @param self a Path (that happens to be a folder/directory)
- * @param fileType whether normal files or directories or both should be processed
- * @param nameFilter the filter to perform on the name of the file/directory (using the {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#isCase(Object, Object)} method)
- * @param closure the closure to invoke
- * @throws java.io.FileNotFoundException if the given directory does not exist
- * @throws IllegalArgumentException if the provided Path object does not represent a directory
- * @since 2.3.0
- */
- @Deprecated
- public static void eachFileMatch(final Path self, final FileType fileType, final Object nameFilter, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException {
- // throws FileNotFoundException, IllegalArgumentException {
- checkDir(self);
- try (DirectoryStream<Path> stream = Files.newDirectoryStream(self)) {
- Iterator<Path> itr = stream.iterator();
- BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase");
- while (itr.hasNext()) {
- Path currentPath = itr.next();
- if ((fileType != FileType.FILES && Files.isDirectory(currentPath)) ||
- (fileType != FileType.DIRECTORIES && Files.isRegularFile(currentPath))) {
- if (bmi.invoke(nameFilter, currentPath.getFileName().toString()))
- closure.call(currentPath);
- }
- }
- }
- }
-
- /**
- * Invokes the closure for each file whose name (file.name) matches the given nameFilter in the given directory
- * - calling the {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#isCase(Object, Object)} method to determine if a match occurs. This method can be used
- * with different kinds of filters like regular expressions, classes, ranges etc.
- * Both regular files and subdirectories are matched.
- *
- * @param self a Path (that happens to be a folder/directory)
- * @param nameFilter the nameFilter to perform on the name of the file (using the {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#isCase(Object, Object)} method)
- * @param closure the closure to invoke
- * @throws java.io.FileNotFoundException if the given directory does not exist
- * @throws IllegalArgumentException if the provided Path object does not represent a directory
- * @see #eachFileMatch(Path, groovy.io.FileType, Object, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static void eachFileMatch(final Path self, final Object nameFilter, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException {
- // throws FileNotFoundException, IllegalArgumentException {
- eachFileMatch(self, FileType.ANY, nameFilter, closure);
- }
-
- /**
- * Invokes the closure for each subdirectory whose name (dir.name) matches the given nameFilter in the given directory
- * - calling the {@link DefaultGroovyMethods#isCase(java.lang.Object, java.lang.Object)} method to determine if a match occurs. This method can be used
- * with different kinds of filters like regular expressions, classes, ranges etc.
- * Only subdirectories are matched; regular files are ignored.
- *
- * @param self a Path (that happens to be a folder/directory)
- * @param nameFilter the nameFilter to perform on the name of the directory (using the {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#isCase(Object, Object)} method)
- * @param closure the closure to invoke
- * @throws java.io.FileNotFoundException if the given directory does not exist
- * @throws IllegalArgumentException if the provided Path object does not represent a directory
- * @see #eachFileMatch(Path, groovy.io.FileType, Object, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static void eachDirMatch(final Path self, final Object nameFilter, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException {
- eachFileMatch(self, FileType.DIRECTORIES, nameFilter, closure);
- }
-
- /**
- * Deletes a directory with all contained files and subdirectories.
- * <p>The method returns
- * <ul>
- * <li>true, when deletion was successful</li>
- * <li>true, when it is called for a non existing directory</li>
- * <li>false, when it is called for a file which isn't a directory</li>
- * <li>false, when directory couldn't be deleted</li>
- * </ul>
- * </p>
- *
- * @param self a Path
- * @return true if the file doesn't exist or deletion was successful
- * @since 2.3.0
- */
- @Deprecated
- public static boolean deleteDir(final Path self) {
- if (!Files.exists(self))
- return true;
-
- if (!Files.isDirectory(self))
- return false;
-
- // delete contained files
- try (DirectoryStream<Path> stream = Files.newDirectoryStream(self)) {
- for (Path path : stream) {
- if (Files.isDirectory(path)) {
- if (!deleteDir(path)) {
- return false;
- }
- } else {
- Files.delete(path);
- }
- }
-
- // now delete directory itself
- Files.delete(self);
- return true;
- } catch (IOException e) {
- return false;
- }
- }
-
- /**
- * Renames a file.
- *
- * @param self a Path
- * @param newPathName The new pathname for the named file
- * @return <code>true</code> if and only if the renaming succeeded;
- * <code>false</code> otherwise
- * @since 2.3.0
- */
- @Deprecated
- public static boolean renameTo(final Path self, String newPathName) {
- try {
- Files.move(self, Paths.get(newPathName));
- return true;
- } catch (IOException e) {
- return false;
- }
- }
-
- /**
- * Renames a file.
- *
- * @param self a Path
- * @param newPathName The new target path specified as a URI object
- * @return <code>true</code> if and only if the renaming succeeded;
- * <code>false</code> otherwise
- * @since 2.3.0
- */
- @Deprecated
- public static boolean renameTo(final Path self, URI newPathName) {
- try {
- Files.move(self, Paths.get(newPathName));
- return true;
- } catch (IOException e) {
- return false;
- }
- }
-
- /**
- * Converts this Path to a {@link groovy.lang.Writable}.
- *
- * @param self a Path
- * @return a Path which wraps the input file and which implements Writable
- * @since 2.3.0
- */
- @Deprecated
- public static Path asWritable(Path self) {
- return new WritablePath(self);
- }
-
- /**
- * Converts this Path to a {@link groovy.lang.Writable} or delegates to default
- * {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#asType(Object, Class)}.
- *
- * @param path a Path
- * @param c the desired class
- * @return the converted object
- * @since 2.3.0
- */
- @SuppressWarnings("unchecked")
- @Deprecated
- public static <T> T asType(Path path, Class<T> c) {
- if (c == Writable.class) {
- return (T) asWritable(path);
- }
- return DefaultGroovyMethods.asType((Object) path, c);
- }
-
- /**
- * Allows a file to return a Writable implementation that can output itself
- * to a Writer stream.
- *
- * @param self a Path
- * @param encoding the encoding to be used when reading the file's contents
- * @return Path which wraps the input file and which implements Writable
- * @since 2.3.0
- */
- @Deprecated
- public static Path asWritable(Path self, String encoding) {
- return new WritablePath(self, encoding);
- }
-
- /**
- * Create a buffered reader for this file.
- *
- * @param self a Path
- * @return a BufferedReader
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static BufferedReader newReader(Path self) throws IOException {
- return Files.newBufferedReader(self, Charset.defaultCharset());
- }
-
- /**
- * Create a buffered reader for this file, using the specified
- * charset as the encoding.
- *
- * @param self a Path
- * @param charset the charset for this Path
- * @return a BufferedReader
- * @throws java.io.FileNotFoundException if the Path was not found
- * @throws java.io.UnsupportedEncodingException if the encoding specified is not supported
- * @since 2.3.0
- */
- @Deprecated
- public static BufferedReader newReader(Path self, String charset) throws IOException {
- return Files.newBufferedReader(self, Charset.forName(charset));
- }
-
- /**
- * Create a new BufferedReader for this file and then
- * passes it into the closure, ensuring the reader is closed after the
- * closure returns.
- *
- * @param self a file object
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withReader(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.Reader") Closure<T> closure) throws IOException {
- return IOGroovyMethods.withReader(newReader(self), closure);
- }
-
- /**
- * Create a new BufferedReader for this file using the specified charset and then
- * passes it into the closure, ensuring the reader is closed after the
- * closure returns. The writer will use the given charset encoding,
- * but will not write a BOM.
- *
- * @param self a file object
- * @param charset the charset for this input stream
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withReader(Path self, String charset, @ClosureParams(value = SimpleType.class, options = "java.io.Reader") Closure<T> closure) throws IOException {
- return IOGroovyMethods.withReader(newReader(self, charset), closure);
- }
-
- /**
- * Create a buffered output stream for this file.
- *
- * @param self a file object
- * @return the created OutputStream
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static BufferedOutputStream newOutputStream(Path self) throws IOException {
- return new BufferedOutputStream(Files.newOutputStream(self));
- }
-
- /**
- * Creates a new data output stream for this file.
- *
- * @param self a file object
- * @return the created DataOutputStream
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static DataOutputStream newDataOutputStream(Path self) throws IOException {
- return new DataOutputStream(Files.newOutputStream(self));
- }
-
- /**
- * Creates a new OutputStream for this file and passes it into the closure.
- * This method ensures the stream is closed after the closure returns.
- *
- * @param self a Path
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.OutputStream, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- @SuppressWarnings("unchecked")
- public static Object withOutputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.OutputStream") Closure closure) throws IOException {
- return IOGroovyMethods.withStream(newOutputStream(self), closure);
- }
-
- /**
- * Create a new InputStream for this file and passes it into the closure.
- * This method ensures the stream is closed after the closure returns.
- *
- * @param self a Path
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.InputStream, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- @SuppressWarnings("unchecked")
- public static Object withInputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.InputStream") Closure closure) throws IOException {
- return IOGroovyMethods.withStream(newInputStream(self), closure);
- }
-
- /**
- * Create a new DataOutputStream for this file and passes it into the closure.
- * This method ensures the stream is closed after the closure returns.
- *
- * @param self a Path
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.OutputStream, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withDataOutputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.DataOutputStream") Closure<T> closure) throws IOException {
- return IOGroovyMethods.withStream(newDataOutputStream(self), closure);
- }
-
- /**
- * Create a new DataInputStream for this file and passes it into the closure.
- * This method ensures the stream is closed after the closure returns.
- *
- * @param self a Path
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.InputStream, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withDataInputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.DataInputStream") Closure<T> closure) throws IOException {
- return IOGroovyMethods.withStream(newDataInputStream(self), closure);
- }
-
- /**
- * Create a buffered writer for this file.
- *
- * @param self a Path
- * @return a BufferedWriter
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static BufferedWriter newWriter(Path self) throws IOException {
- return Files.newBufferedWriter(self, Charset.defaultCharset());
- }
-
- /**
- * Creates a buffered writer for this file, optionally appending to the
- * existing file content.
- *
- * @param self a Path
- * @param append true if data should be appended to the file
- * @return a BufferedWriter
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static BufferedWriter newWriter(Path self, boolean append) throws IOException {
- if (append) {
- return Files.newBufferedWriter(self, Charset.defaultCharset(), CREATE, APPEND);
- }
- return Files.newBufferedWriter(self, Charset.defaultCharset());
- }
-
- /**
- * Helper method to create a buffered writer for a file without writing a BOM.
- *
- * @param self a Path
- * @param charset the name of the encoding used to write in this file
- * @param append true if in append mode
- * @return a BufferedWriter
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static BufferedWriter newWriter(Path self, String charset, boolean append) throws IOException {
- return newWriter(self, charset, append, false);
- }
-
- /**
- * Helper method to create a buffered writer for a file. If the given
- * charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias), the
- * requisite byte order mark is written to the stream before the writer
- * is returned.
- *
- * @param self a Path
- * @param charset the name of the encoding used to write in this file
- * @param append true if in append mode
- * @param writeBom whether to write a BOM
- * @return a BufferedWriter
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.5.0
- */
- @Deprecated
- public static BufferedWriter newWriter(Path self, String charset, boolean append, boolean writeBom) throws IOException {
- boolean shouldWriteBom = writeBom && !self.toFile().exists();
- if (append) {
- BufferedWriter writer = Files.newBufferedWriter(self, Charset.forName(charset), CREATE, APPEND);
- if (shouldWriteBom) {
- writeUTF16BomIfRequired(writer, charset);
- }
- return writer;
- } else {
- OutputStream out = Files.newOutputStream(self);
- if (shouldWriteBom) {
- writeUTF16BomIfRequired(out, charset);
- }
- return new BufferedWriter(new OutputStreamWriter(out, Charset.forName(charset)));
- }
- }
-
- /**
- * Creates a buffered writer for this file without writing a BOM, writing data using the given
- * encoding.
- *
- * @param self a Path
- * @param charset the name of the encoding used to write in this file
- * @return a BufferedWriter
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static BufferedWriter newWriter(Path self, String charset) throws IOException {
- return newWriter(self, charset, false);
- }
-
- /**
- * Creates a new BufferedWriter for this file, passes it to the closure, and
- * ensures the stream is flushed and closed after the closure returns.
- * The writer will not write a BOM.
- *
- * @param self a Path
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withWriter(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException {
- return withWriter(self, Charset.defaultCharset().name(), closure);
- }
-
- /**
- * Creates a new BufferedWriter for this file, passes it to the closure, and
- * ensures the stream is flushed and closed after the closure returns.
- * The writer will use the given charset encoding, but will not write a BOM.
- *
- * @param self a Path
- * @param charset the charset used
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withWriter(Path self, String charset, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException {
- return withWriter(self, charset, false, closure);
- }
-
- /**
- * Creates a new BufferedWriter for this file, passes it to the closure, and
- * ensures the stream is flushed and closed after the closure returns.
- * The writer will use the given charset encoding. If the given charset is
- * "UTF-16BE" or "UTF-16LE" (or an equivalent alias), <code>writeBom</code>
- * is <code>true</code>, and the file doesn't already exist, the requisite
- * byte order mark is written to the stream when the writer is created.
- *
- * @param self a Path
- * @param charset the charset used
- * @param writeBom whether to write the BOM
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.5.0
- */
- @Deprecated
- public static <T> T withWriter(Path self, String charset, boolean writeBom, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException {
- return IOGroovyMethods.withWriter(newWriter(self, charset, false, writeBom), closure);
- }
-
- /**
- * Create a new BufferedWriter which will append to this
- * file. The writer is passed to the closure and will be closed before
- * this method returns. The writer will use the given charset encoding,
- * but will not write a BOM.
- *
- * @param self a Path
- * @param charset the charset used
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withWriterAppend(Path self, String charset, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException {
- return withWriterAppend(self, charset, false, closure);
- }
-
- /**
- * Create a new BufferedWriter which will append to this
- * file. The writer is passed to the closure and will be closed before
- * this method returns. The writer will use the given charset encoding.
- * If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias),
- * <code>writeBom</code> is <code>true</code>, and the file doesn't already exist,
- * the requisite byte order mark is written to the stream when the writer is created.
- *
- * @param self a Path
- * @param charset the charset used
- * @param writeBom whether to write the BOM
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.5.0
- */
- @Deprecated
- public static <T> T withWriterAppend(Path self, String charset, boolean writeBom, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException {
- return IOGroovyMethods.withWriter(newWriter(self, charset, true, writeBom), closure);
- }
-
- /**
- * Create a new BufferedWriter for this file in append mode. The writer
- * is passed to the closure and is closed after the closure returns.
- * The writer will not write a BOM.
- *
- * @param self a Path
- * @param closure a closure
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withWriterAppend(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException {
- return withWriterAppend(self, Charset.defaultCharset().name(), closure);
- }
-
- /**
- * Create a new PrintWriter for this file.
- *
- * @param self a Path
- * @return the created PrintWriter
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static PrintWriter newPrintWriter(Path self) throws IOException {
- return new GroovyPrintWriter(newWriter(self));
- }
-
- /**
- * Create a new PrintWriter for this file, using specified
- * charset.
- *
- * @param self a Path
- * @param charset the charset
- * @return a PrintWriter
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static PrintWriter newPrintWriter(Path self, String charset) throws IOException {
- return new GroovyPrintWriter(newWriter(self, charset));
- }
-
- /**
- * Create a new PrintWriter for this file which is then
- * passed it into the given closure. This method ensures its the writer
- * is closed after the closure returns.
- *
- * @param self a Path
- * @param closure the closure to invoke with the PrintWriter
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withPrintWriter(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.PrintWriter") Closure<T> closure) throws IOException {
- return IOGroovyMethods.withWriter(newPrintWriter(self), closure);
- }
-
- /**
- * Create a new PrintWriter with a specified charset for
- * this file. The writer is passed to the closure, and will be closed
- * before this method returns.
- *
- * @param self a Path
- * @param charset the charset
- * @param closure the closure to invoke with the PrintWriter
- * @return the value returned by the closure
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withPrintWriter(Path self, String charset, @ClosureParams(value = SimpleType.class, options = "java.io.PrintWriter") Closure<T> closure) throws IOException {
- return IOGroovyMethods.withWriter(newPrintWriter(self, charset), closure);
- }
-
- /**
- * Creates a buffered input stream for this file.
- *
- * @param self a Path
- * @return a BufferedInputStream of the file
- * @throws java.io.FileNotFoundException if the file is not found.
- * @since 2.3.0
- */
- @Deprecated
- public static BufferedInputStream newInputStream(Path self) throws IOException { // throws FileNotFoundException {
- return new BufferedInputStream(Files.newInputStream(self));
- }
-
- /**
- * Create a data input stream for this file
- *
- * @param self a Path
- * @return a DataInputStream of the file
- * @throws java.io.FileNotFoundException if the file is not found.
- * @since 2.3.0
- */
- @Deprecated
- public static DataInputStream newDataInputStream(Path self) throws IOException { // throws FileNotFoundException {
- return new DataInputStream(Files.newInputStream(self));
- }
-
- /**
- * Traverse through each byte of this Path
- *
- * @param self a Path
- * @param closure a closure
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#eachByte(java.io.InputStream, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static void eachByte(Path self, @ClosureParams(value = SimpleType.class, options = "byte") Closure closure) throws IOException {
- BufferedInputStream is = newInputStream(self);
- IOGroovyMethods.eachByte(is, closure);
- }
-
- /**
- * Traverse through the bytes of this Path, bufferLen bytes at a time.
- *
- * @param self a Path
- * @param bufferLen the length of the buffer to use.
- * @param closure a 2 parameter closure which is passed the byte[] and a number of bytes successfully read.
- * @throws java.io.IOException if an IOException occurs.
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#eachByte(java.io.InputStream, int, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static void eachByte(Path self, int bufferLen, @ClosureParams(value = FromString.class, options = "byte[],Integer") Closure closure) throws IOException {
- BufferedInputStream is = newInputStream(self);
- IOGroovyMethods.eachByte(is, bufferLen, closure);
- }
-
- /**
- * Filters the lines of a Path and creates a Writable in return to
- * stream the filtered lines.
- *
- * @param self a Path
- * @param closure a closure which returns a boolean indicating to filter
- * the line or not
- * @return a Writable closure
- * @throws java.io.IOException if <code>self</code> is not readable
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#filterLine(java.io.Reader, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static Writable filterLine(Path self, @ClosureParams(value = SimpleType.class, options = "java.lang.String") Closure closure) throws IOException {
- return IOGroovyMethods.filterLine(newReader(self), closure);
- }
-
- /**
- * Filters the lines of a Path and creates a Writable in return to
- * stream the filtered lines.
- *
- * @param self a Path
- * @param charset opens the file with a specified charset
- * @param closure a closure which returns a boolean indicating to filter
- * the line or not
- * @return a Writable closure
- * @throws java.io.IOException if an IOException occurs
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#filterLine(java.io.Reader, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static Writable filterLine(Path self, String charset, @ClosureParams(value = SimpleType.class, options = "java.lang.String") Closure closure) throws IOException {
- return IOGroovyMethods.filterLine(newReader(self, charset), closure);
- }
-
- /**
- * Filter the lines from this Path, and write them to the given writer based
- * on the given closure predicate.
- *
- * @param self a Path
- * @param writer a writer destination to write filtered lines to
- * @param closure a closure which takes each line as a parameter and returns
- * <code>true</code> if the line should be written to this writer.
- * @throws java.io.IOException if <code>self</code> is not readable
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static void filterLine(Path self, Writer writer, @ClosureParams(value = SimpleType.class, options = "java.lang.String") Closure closure) throws IOException {
- IOGroovyMethods.filterLine(newReader(self), writer, closure);
- }
-
- /**
- * Filter the lines from this Path, and write them to the given writer based
- * on the given closure predicate.
- *
- * @param self a Path
- * @param writer a writer destination to write filtered lines to
- * @param charset opens the file with a specified charset
- * @param closure a closure which takes each line as a parameter and returns
- * <code>true</code> if the line should be written to this writer.
- * @throws java.io.IOException if an IO error occurs
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static void filterLine(Path self, Writer writer, String charset, @ClosureParams(value = SimpleType.class, options = "java.lang.String") Closure closure) throws IOException {
- IOGroovyMethods.filterLine(newReader(self, charset), writer, closure);
- }
-
- /**
- * Reads the content of the file into a byte array.
- *
- * @param self a Path
- * @return a byte array with the contents of the file.
- * @throws java.io.IOException if an IOException occurs.
- * @since 2.3.0
- */
- @Deprecated
- public static byte[] readBytes(Path self) throws IOException {
- return Files.readAllBytes(self);
- }
-
- /**
- * #deprecated use the variant in IOGroovyMethods
- *
- * @see org.codehaus.groovy.runtime.IOGroovyMethods#withCloseable(java.io.Closeable, groovy.lang.Closure)
- * @since 2.3.0
- */
- @Deprecated
- public static <T> T withCloseable(Closeable self, @ClosureParams(value = SimpleType.class, options = "java.io.Closeable") Closure<T> action) throws IOException {
- return IOGroovyMethods.withCloseable(self, action);
- }
-
-}
diff --git a/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/WritablePath.java b/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/WritablePath.java
deleted file mode 100644
index 56d5e59..0000000
--- a/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/WritablePath.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.codehaus.groovy.runtime;
-
-import groovy.lang.Writable;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.io.Writer;
-import java.net.URI;
-import java.nio.charset.Charset;
-import java.nio.file.FileSystem;
-import java.nio.file.Files;
-import java.nio.file.LinkOption;
-import java.nio.file.Path;
-import java.nio.file.WatchEvent;
-import java.nio.file.WatchKey;
-import java.nio.file.WatchService;
-import java.util.Iterator;
-
-/**
- * A Writable Path.
- */
-@Deprecated
-public class WritablePath implements Path, Writable {
-
- private final String encoding;
- private final Path delegate;
-
- public WritablePath(final Path delegate) {
- this(delegate, null);
- }
-
- public WritablePath(final Path delegate, final String encoding) {
- this.encoding = encoding;
- this.delegate = delegate;
- }
-
- public Writer writeTo(final Writer out) throws IOException {
-
- try (Reader reader = (this.encoding == null)
- ? new InputStreamReader(Files.newInputStream(this))
- : new InputStreamReader(Files.newInputStream(this), Charset.forName(this.encoding))) {
- int c = reader.read();
-
- while (c != -1) {
- out.write(c);
- c = reader.read();
- }
- }
- return out;
- }
-
- @Override
- public FileSystem getFileSystem() {
- return delegate.getFileSystem();
- }
-
- @Override
- public boolean isAbsolute() {
- return delegate.isAbsolute();
- }
-
- @Override
- public Path getRoot() {
- return delegate.getRoot();
- }
-
- @Override
- public Path getFileName() {
- return delegate.getFileName();
- }
-
- @Override
- public Path getParent() {
- return delegate.getParent();
- }
-
- @Override
- public int getNameCount() {
- return delegate.getNameCount();
- }
-
- @Override
- public Path getName(int index) {
- return delegate.getName(index);
- }
-
- @Override
- public Path subpath(int beginIndex, int endIndex) {
- return delegate.subpath(beginIndex, endIndex);
- }
-
- @Override
- public boolean startsWith(Path other) {
- return delegate.startsWith(other);
- }
-
- @Override
- public boolean startsWith(String other) {
- return delegate.startsWith(other);
- }
-
- @Override
- public boolean endsWith(Path other) {
- return delegate.endsWith(other);
- }
-
- @Override
- public boolean endsWith(String other) {
- return delegate.endsWith(other);
- }
-
- @Override
- public Path normalize() {
- return delegate.normalize();
- }
-
- @Override
- public Path resolve(Path other) {
- return delegate.resolve(other);
- }
-
- @Override
- public Path resolve(String other) {
- return delegate.resolve(other);
- }
-
- @Override
- public Path resolveSibling(Path other) {
- return delegate.resolveSibling(other);
- }
-
- @Override
- public Path resolveSibling(String other) {
- return delegate.resolveSibling(other);
- }
-
- @Override
- public Path relativize(Path other) {
- return delegate.relativize(other);
- }
-
- @Override
- public URI toUri() {
- return delegate.toUri();
- }
-
- @Override
- public Path toAbsolutePath() {
- return delegate.toAbsolutePath();
- }
-
- @Override
- public Path toRealPath(LinkOption... options) throws IOException {
- return delegate.toRealPath(options);
- }
-
- @Override
- public File toFile() {
- return delegate.toFile();
- }
-
- @Override
- public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers) throws IOException {
- return delegate.register(watcher, events, modifiers);
- }
-
- @Override
- public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) throws IOException {
- return delegate.register(watcher, events);
- }
-
- @Override
- public Iterator<Path> iterator() {
- return delegate.iterator();
- }
-
- @Override
- public int compareTo(Path other) {
- return delegate.compareTo(other);
- }
-
- @Override
- public boolean equals(Object other) {
- return delegate.equals(other);
- }
-
- @Override
- public int hashCode() {
- return delegate.hashCode();
- }
-
- @Override
- public String toString() {
- return delegate.toString();
- }
-}
diff --git a/subprojects/groovy-test/src/main/groovy/groovy/lang/GroovyLogTestCase.groovy b/subprojects/groovy-test/src/main/groovy/groovy/lang/GroovyLogTestCase.groovy
deleted file mode 100644
index c96808d..0000000
--- a/subprojects/groovy-test/src/main/groovy/groovy/lang/GroovyLogTestCase.groovy
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.lang
-
-import java.util.logging.Handler
-import java.util.logging.Level
-import java.util.logging.Logger
-import java.util.logging.SimpleFormatter
-import java.util.logging.StreamHandler
-
-/**
- * Helper class to spoof log entries as produced by calling arbitrary code.
- * This allows non-intrusive testing of dependent objects without
- * explicitly using Mock objects as long as those dependent objects
- * do some proper logging.
- * As a measure of last resort, it can be used on MetaClass to spoof
- * it's log entries on 'invokeMethod'.
- *
- * @see GroovyLogTestCaseTest
- */
-@Deprecated
-class GroovyLogTestCase extends GroovyTestCase {
-
- /**
- * Execute the given Closure with the according level for the Logger that
- * is qualified by the qualifier and return the log output as a String.
- * Qualifiers are usually package or class names.
- * Existing log level and handlers are restored after execution.
- */
- static String stringLog(Level level, String qualifier, Closure yield) {
- // store old values
- Logger logger = Logger.getLogger(qualifier)
- def usesParentHandlers = logger.useParentHandlers
- // set new values
- logger.useParentHandlers = false
- def out = new ByteArrayOutputStream(1024)
- Handler stringHandler = new StreamHandler(out, new SimpleFormatter())
- stringHandler.level = Level.ALL
- logger.addHandler(stringHandler) // any old handlers remain
-
- withLevel(level, qualifier, yield)
-
- // restore old values
- logger.level = Level.OFF // temporarily, to avoid logging the 3 stmts below
- stringHandler.flush()
- out.close()
- logger.removeHandler(stringHandler)
- logger.useParentHandlers = usesParentHandlers
- return out.toString()
- }
-
- /**
- * Execute the given Closure with the according level for the Logger that
- * is qualified by the qualifier. Qualifiers are usually package or class names.
- * The log level is restored after execution.
- */
- static def withLevel(Level level, String qualifier, Closure yield) {
- // store old values
- Logger logger = Logger.getLogger(qualifier)
- def loglevel = logger.level
- // set new values
- if (!logger.isLoggable(level)) logger.level = level // use min value
-
- def result = yield()
-
- // restore old values
- logger.level = loglevel
- return result
- }
-}
\ No newline at end of file
diff --git a/subprojects/groovy-test/src/main/groovy/groovy/util/GroovyShellTestCase.groovy b/subprojects/groovy-test/src/main/groovy/groovy/util/GroovyShellTestCase.groovy
deleted file mode 100644
index c313763..0000000
--- a/subprojects/groovy-test/src/main/groovy/groovy/util/GroovyShellTestCase.groovy
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util
-
-/**
- * Groovy test case, which recreates internal GroovyShell in each setUp()
- */
-
-@Deprecated
-class GroovyShellTestCase extends GroovyTestCase {
-
- @Delegate protected GroovyShell shell
-
- protected void setUp() {
- super.setUp()
- shell = createNewShell()
- }
-
- protected void tearDown() {
- shell = null
- super.tearDown()
- }
-
- /**
- * Create new shell instance.
- * Overwrite it to customize
- */
- protected GroovyShell createNewShell() {
- return new GroovyShell()
- }
-
- /**
- * Executes closure with given binding
- */
- protected def withBinding (Map map, Closure closure) {
- Binding binding = shell.context
- Map bmap = binding.variables
- try {
- Map vars = new HashMap(bmap)
- bmap.putAll map
-
- return closure.call()
- }
- finally {
- bmap.clear()
- bmap.putAll vars
- }
- }
-
- /**
- * Evaluates script with given binding
- */
- protected def withBinding (Map map, String script) {
- Binding binding = shell.context
- Map bmap = binding.variables
- try {
- Map vars = new HashMap(bmap)
- bmap.putAll map
-
- return evaluate(script)
- }
- finally {
- bmap.clear()
- bmap.putAll vars
- }
- }
-}
\ No newline at end of file
diff --git a/subprojects/groovy-test/src/main/groovy/groovy/util/JavadocAssertionTestBuilder.groovy b/subprojects/groovy-test/src/main/groovy/groovy/util/JavadocAssertionTestBuilder.groovy
deleted file mode 100644
index df83633..0000000
--- a/subprojects/groovy-test/src/main/groovy/groovy/util/JavadocAssertionTestBuilder.groovy
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util
-
-import java.util.regex.Pattern
-
-/**
- * <code>JavadocAssertionTestBuilder</code> will dynamically create a test cases from Groovy assertions placed within
- * the Javadoc comments of a source file. Assertions should be placed within an html tag with a <code>class="groovyTestCase"</code>
- * attribute assignment. Example:
- * <pre><pre class="groovyTestCase"> assert "example".size() == 7 </pre></pre>
- * When extracting the code for the test, single-line snippets of code without braces within a {{@code @code} ...}
- * tag will have the javadoc {@code code} tag stripped. Similarly, html entities are converted back when extracting
- * code, so {@code <} and {@code >} will be converted to {@code <} and {@code >}.
- */
-@Deprecated
-class JavadocAssertionTestBuilder {
- // TODO write tests for this classes functionality
- private static final Pattern javadocPattern =
- Pattern.compile( /(?ims)\/\*\*.*?\*\// )
- private static final Pattern assertionPattern =
- Pattern.compile( /(?ims)<([a-z]+)\s+class\s*=\s*['"]groovyTestCase['"]\s*>.*?<\s*\/\s*\1>/ )
-
- Class buildTest(String filename, String code) {
- Class test = null
-
- List assertionTags = getAssertionTags(code)
- if (assertionTags) {
- String testName = getTestName(filename)
-
- Map lineNumberToAssertions = getLineNumberToAssertionsMap(code, assertionTags)
- List testMethods = getTestMethods(lineNumberToAssertions, filename)
- String testCode = getTestCode(testName, testMethods)
-
- test = createClass(testCode)
- }
-
- return test
- }
-
- private List getAssertionTags(String code) {
- List assertions = new ArrayList()
-
- code.eachMatch(javadocPattern) { javadoc ->
- assertions.addAll(javadoc.findAll(assertionPattern))
- }
-
- return assertions
- }
-
- private String getTestName(String filename) {
- String filenameWithoutPath = new File(filename).name
- String testName = filenameWithoutPath.substring(0, filenameWithoutPath.lastIndexOf(".")) +
- "JavadocAssertionTest"
-
- return testName
- }
-
- private Map getLineNumberToAssertionsMap(String code, List assertionTags) {
- Map lineNumberToAssertions = [:] as LinkedHashMap
-
- int codeIndex = 0
- assertionTags.each { tag ->
- codeIndex = code.indexOf(tag, codeIndex)
- int lineNumber = code.substring(0, codeIndex).findAll("(?m)^").size()
- codeIndex += tag.size()
-
- String assertion = getAssertion(tag)
-
- lineNumberToAssertions.get(lineNumber, []) << assertion
- }
-
- return lineNumberToAssertions
- }
-
- private String getAssertion(String tag) {
- String tagInner = tag.substring(tag.indexOf(">")+1, tag.lastIndexOf("<"))
- String htmlAssertion = tagInner.replaceAll("(?m)^\\s*\\*", "")
- String assertion = htmlAssertion
- // TODO improve on this
- [nbsp:' ', gt:'>', lt:'<', quot:'"', apos:"'", at:'@', '#64':'@', ndash:'-', amp:'&'].each { key, value ->
- assertion = assertion.replaceAll("(?i)&$key;", value)
- }
- assertion = assertion.replaceAll(/(?i)\{@code ([^}]*)\}/, '$1')
-
- return assertion
- }
-
- private List getTestMethods(Map lineNumberToAssertions, String filename) {
- List testMethods = lineNumberToAssertions.collect { lineNumber, assertions ->
- Character differentiator = 'a'
- assertions.collect { assertion ->
- String suffix = (assertions.size() > 1 ? "$lineNumber$differentiator" : lineNumber)
- differentiator++
- getTestMethodCodeForAssertion(suffix, assertion, basename(filename))
- }
- }.flatten()
-
- return testMethods
- }
-
- private String basename(String fullPath) {
- def path = new File(fullPath)
- def fullName = path.name
- fullName.substring(0, fullName.lastIndexOf("."))
- }
-
- private String getTestMethodCodeForAssertion(String suffix, String assertion, String basename) {
- return """
- public void testAssertionFrom${basename}Line$suffix() {
- byte[] bytes = [ ${(assertion.getBytes("UTF-8") as List).join(", ")} ] as byte[]
- Eval.me(new String(bytes, "UTF-8"))
- }
- """
- }
-
- private String getTestCode(String testName, List testMethods) {
- return """
- class $testName extends junit.framework.TestCase {
- """+testMethods.join("\r\n")+"""
- }
- """
- }
-
- private Class createClass(String testCode) {
- return new GroovyClassLoader().parseClass(testCode)
- }
-}
diff --git a/subprojects/groovy-test/src/main/groovy/groovy/util/JavadocAssertionTestSuite.groovy b/subprojects/groovy-test/src/main/groovy/groovy/util/JavadocAssertionTestSuite.groovy
deleted file mode 100644
index 5e813e7..0000000
--- a/subprojects/groovy-test/src/main/groovy/groovy/util/JavadocAssertionTestSuite.groovy
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util
-
-import junit.framework.Test
-import junit.framework.TestSuite
-import junit.textui.TestRunner
-
-/**
- * <code>JavadocAssertionTestSuite</code> will dynamically create test cases from Groovy assertions placed within
- * Javadoc comments. Assertions should be placed within an html tag with a <code>class="groovyTestCase"</code>
- * attribute assignment. Example:
- * <pre><pre class="groovyTestCase"> assert "example".size() == 7 </pre></pre>
- *
- * Source files will be read from the directory specified by the <code>javadocAssertion.src.dir</code>
- * system property, including all files matching <code>javadocAssertion.src.pattern</code> and
- * excluding files matching the <code>javadocAssertion.src.excludesPattern</code>.
- *
- * By default all <code>.java</code> and <code>.groovy</code> source files from <code>./src</code> will
- * be scanned for assertions.
- *
- * You can also run this class as an application from the command line (assumes Groovy, JUnit and Ant
- * are on the classpath). As an example:
- * <p>
- * <code>
- * java groovy.util.JavadocAssertionTestSuite src/main
- * </code>
- *
- * <b>Note: this class requires the Ant module at runtime.</b>
- */
-@Deprecated
-class JavadocAssertionTestSuite extends TestSuite {
- /** The System Property to set as base directory for collection of Classes.
- * The pattern will be used as an Ant fileset include basedir.
- * Key is "javadocAssertion.src.dir".
- * Defaults to the <code>./src</code> directory
- */
- public static final String SYSPROP_SRC_DIR = "javadocAssertion.src.dir";
-
- /** The System Property to set as the filename pattern for collection of Classes.
- * The pattern will be used as Regular Expression pattern applied with the find
- * operator against each candidate file.path.
- * Key is "javadocAssertion.src.pattern".
- * Defaults to including all <code>.java</code> and <code>.groovy</code> files.
- */
- public static final String SYSPROP_SRC_PATTERN = "javadocAssertion.src.pattern";
-
- /** The System Property to set as a filename excludes pattern for collection of Classes.
- * When non-empty, the pattern will be used as Regular Expression pattern applied with the
- * find operator against each candidate file.path.
- * Key is "javadocAssertion.src.excludesPattern".
- * Default value is "".
- */
- public static final String SYSPROP_SRC_EXCLUDES_PATTERN = "javadocAssertion.src.excludesPattern";
-
- private static final JavadocAssertionTestBuilder testBuilder = new JavadocAssertionTestBuilder()
- private static final IFileNameFinder finder = Class.forName('groovy.ant.FileNameFinder',true,this.classLoader).newInstance()
-
- static Test suite() {
- String basedir = System.getProperty(SYSPROP_SRC_DIR, "./src/")
- return suite(basedir)
- }
-
- static Test suite(String basedir) {
- String includePattern = System.getProperty(SYSPROP_SRC_PATTERN, "**/*.java,**/*.groovy")
- return suite(basedir, includePattern)
- }
-
- static Test suite(String basedir, String includePattern) {
- String excludePattern = System.getProperty(SYSPROP_SRC_EXCLUDES_PATTERN, "")
- return suite(basedir, includePattern, excludePattern)
- }
-
- static Test suite(String basedir, String includePattern, String excludePattern) {
- assert new File(basedir).exists()
-
- TestSuite suite = new JavadocAssertionTestSuite()
-
- Collection filenames = finder.getFileNames([dir:basedir, includes:includePattern, excludes:excludePattern])
- filenames.each { filename ->
- String code = new File(filename).text
- Class test = testBuilder.buildTest(filename, code)
- if (test != null) {
- suite.addTestSuite(test)
- }
- }
-
- return suite
- }
-
- static void main(String[] args) {
- switch(args.length) {
- case 3:
- TestRunner.run(suite(args[0], args[1], args[2]))
- break
- case 2:
- TestRunner.run(suite(args[0], args[1]))
- break
- case 1:
- TestRunner.run(suite(args[0]))
- break
- default:
- TestRunner.run(suite())
- }
- }
-
-}
diff --git a/subprojects/groovy-test/src/main/groovy/groovy/util/StringTestUtil.groovy b/subprojects/groovy-test/src/main/groovy/groovy/util/StringTestUtil.groovy
deleted file mode 100644
index a49ac12..0000000
--- a/subprojects/groovy-test/src/main/groovy/groovy/util/StringTestUtil.groovy
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util
-
-import org.junit.Assert
-
-@Deprecated
-class StringTestUtil {
- static void assertMultilineStringsEqual(String a, String b) {
- def aLines = a.trim().replaceAll('\r','').split('\n')
- def bLines = b.trim().replaceAll('\r','').split('\n')
- assert aLines.size() == bLines.size()
- for (i in 0..<aLines.size()) {
- Assert.assertEquals(aLines[i].trim(), bLines[i].trim())
- }
- }
-}
diff --git a/subprojects/groovy-test/src/main/java/groovy/transform/NotYetImplemented.java b/subprojects/groovy-test/src/main/java/groovy/transform/NotYetImplemented.java
deleted file mode 100644
index 0f9ddf3..0000000
--- a/subprojects/groovy-test/src/main/java/groovy/transform/NotYetImplemented.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.transform;
-
-import org.codehaus.groovy.transform.GroovyASTTransformationClass;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Method annotation used to invert test case results. If a JUnit 3/4 test case method is
- * annotated with {@code @NotYetImplemented} the test will fail if no test failure occurs and it will pass
- * if a test failure occurs.
- * <p>
- * This is helpful for tests that don't currently work but should work one day,
- * when the tested functionality has been implemented.
- * <p>
- * The idea for this AST transformation originated in {@link groovy.test.GroovyTestCase#notYetImplemented()}.
- *
- * @since 2.0.0
- * @deprecated use {@link groovy.test.NotYetImplemented}
- */
-@Deprecated
-@java.lang.annotation.Documented
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.METHOD})
-@GroovyASTTransformationClass("org.apache.groovy.test.transform.NotYetImplementedASTTransformation")
-public @interface NotYetImplemented {
-}
diff --git a/subprojects/groovy-test/src/main/java/groovy/util/AllTestSuite.java b/subprojects/groovy-test/src/main/java/groovy/util/AllTestSuite.java
deleted file mode 100644
index afd62d0..0000000
--- a/subprojects/groovy-test/src/main/java/groovy/util/AllTestSuite.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util;
-
-import groovy.lang.GroovyClassLoader;
-import groovy.lang.Script;
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-import org.codehaus.groovy.control.CompilationFailedException;
-import org.apache.groovy.test.ScriptTestAdapter;
-
-import java.io.File;
-import java.io.IOException;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.List;
-import java.util.logging.Logger;
-
-/**
- * AllTestSuite can be used in extension of GroovyTestSuite to execute TestCases written in Groovy
- * from inside a Java IDE.
- * AllTestSuite collects all files below a given directory that comply to a given pattern.
- * From these files, a TestSuite is constructed that can be run via an IDE graphical Test runner.
- * The files are assumed to be Groovy source files and be either a TestCase or a Script that can
- * be wrapped transparently into a TestCase.
- * The directory and the pattern can be set via System properties (see this classes' constants for details.)
- * <p>
- * When setting the log level of this class to FINEST, all file loading will be logged.
- * <p>
- * See also groovy.util.AllTestSuiteTest.groovy
- */
-@Deprecated
-public class AllTestSuite extends TestSuite {
-
- /**
- * The System Property to set as base directory for collection of Test Cases.
- * The pattern will be used as an Ant fileset include basedir.
- * Key is "groovy.test.dir".
- * Default value is "./test/".
- */
- public static final String SYSPROP_TEST_DIR = "groovy.test.dir";
-
- /**
- * The System Property to set as the filename pattern for collection of Test Cases.
- * The pattern will be used as Regular Expression pattern applied with the find
- * operator against each candidate file.path.
- * Key is "groovy.test.pattern".
- * Default value is "Test.groovy".
- */
- public static final String SYSPROP_TEST_PATTERN = "groovy.test.pattern";
-
- /**
- * The System Property to set as a filename excludes pattern for collection of Test Cases.
- * When non-empty, the pattern will be used as Regular Expression pattern applied with the
- * find operator against each candidate file.path.
- * Key is "groovy.test.excludesPattern".
- * Default value is "".
- */
- public static final String SYSPROP_TEST_EXCLUDES_PATTERN = "groovy.test.excludesPattern";
-
- private static final Logger LOG = Logger.getLogger(AllTestSuite.class.getName());
- private static final ClassLoader JAVA_LOADER = AllTestSuite.class.getClassLoader();
- private static final GroovyClassLoader GROOVY_LOADER =
- AccessController.doPrivileged(
- new PrivilegedAction<GroovyClassLoader>() {
- @Override
- public GroovyClassLoader run() {
- return new GroovyClassLoader(JAVA_LOADER);
- }
- }
- );
-
- private static final String[] EMPTY_ARGS = new String[]{};
- private static IFileNameFinder finder = null;
-
- static { // this is only needed since the Groovy Build compiles *.groovy files after *.java files
- try {
- // TODO: dk: make FileNameFinder injectable
- finder = (IFileNameFinder) Class.forName("groovy.ant.FileNameFinder").getDeclaredConstructor().newInstance();
- } catch (Exception e) {
- throw new RuntimeException("Cannot find and instantiate class FileNameFinder", e);
- }
- }
-
- public static Test suite() {
- String basedir = System.getProperty(SYSPROP_TEST_DIR, "./test/");
- String pattern = System.getProperty(SYSPROP_TEST_PATTERN, "**/*Test.groovy");
- String excludesPattern = System.getProperty(SYSPROP_TEST_EXCLUDES_PATTERN, "");
- return suite(basedir, pattern, excludesPattern);
- }
-
- public static Test suite(String basedir, String pattern) {
- return suite(basedir, pattern, "");
- }
-
- public static Test suite(String basedir, String pattern, String excludesPattern) {
- AllTestSuite suite = new AllTestSuite();
- List<String> filenames = excludesPattern.length() > 0
- ? finder.getFileNames(basedir, pattern, excludesPattern)
- : finder.getFileNames(basedir, pattern);
- for (String filename : filenames) {
- LOG.finest("trying to load " + filename);
- try {
- suite.loadTest(filename);
- } catch (CompilationFailedException cfe) {
- cfe.printStackTrace();
- throw new RuntimeException("CompilationFailedException when loading " + filename, cfe);
- } catch (IOException ioe) {
- throw new RuntimeException("IOException when loading " + filename, ioe);
- }
- }
- return suite;
- }
-
- @SuppressWarnings("unchecked")
- protected void loadTest(String filename) throws CompilationFailedException, IOException {
- Class type = compile(filename);
- if (TestCase.class.isAssignableFrom(type)) {
- addTestSuite((Class<? extends TestCase>)type);
- } else if (Script.class.isAssignableFrom(type)) {
- addTest(new ScriptTestAdapter(type, EMPTY_ARGS));
- } else {
- throw new RuntimeException("Don't know how to treat " + filename + " as a JUnit test");
- }
- }
-
- protected Class compile(String filename) throws CompilationFailedException, IOException {
- return GROOVY_LOADER.parseClass(new File(filename));
- }
-}
diff --git a/subprojects/groovy-test/src/main/java/groovy/util/GroovyAssert.java b/subprojects/groovy-test/src/main/java/groovy/util/GroovyAssert.java
deleted file mode 100644
index f36f227..0000000
--- a/subprojects/groovy-test/src/main/java/groovy/util/GroovyAssert.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util;
-
-import groovy.lang.Closure;
-import groovy.lang.GroovyRuntimeException;
-import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-/**
- * @deprecated Use the {@link groovy.test.GroovyAssert} class instead
- */
-@Deprecated
-public class GroovyAssert {
- private static final int MAX_NESTED_EXCEPTIONS = 10;
-
- /**
- * Asserts that the given code closure fails when it is evaluated
- *
- * @param code the code expected to throw the exception
- * @return the message of the thrown Throwable
- */
- public static Throwable shouldFail(Closure code) {
- boolean failed = false;
- Throwable th = null;
- try {
- code.call();
- } catch (GroovyRuntimeException gre) {
- failed = true;
- th = ScriptBytecodeAdapter.unwrap(gre);
- } catch (Throwable e) {
- failed = true;
- th = e;
- }
- assertTrue("Closure " + code + " should have failed", failed);
- return th;
- }
-
- /**
- * Asserts that the given code closure fails when it is evaluated
- * and that a particular exception is thrown.
- *
- * @param clazz the class of the expected exception
- * @param code the closure that should fail
- * @return the message of the expected Throwable
- */
- public static Throwable shouldFail(Class clazz, Closure code) {
- Throwable th = null;
- try {
- code.call();
- } catch (GroovyRuntimeException gre) {
- th = ScriptBytecodeAdapter.unwrap(gre);
- } catch (Throwable e) {
- th = e;
- }
-
- if (th == null) {
- fail("Closure " + code + " should have failed with an exception of type " + clazz.getName());
- } else if (!clazz.isInstance(th)) {
- fail("Closure " + code + " should have failed with an exception of type " + clazz.getName() + ", instead got Exception " + th);
- }
- return th;
- }
-
- /**
- * Asserts that the given code closure fails when it is evaluated
- * and that a particular exception can be attributed to the cause.
- * The expected exception class is compared recursively with any nested
- * exceptions using getCause() until either a match is found or no more
- * nested exceptions exist.
- * <p>
- * If a match is found the error message associated with the matching
- * exception is returned. If no match was found the method will fail.
- *
- * @param clazz the class of the expected exception
- * @param code the closure that should fail
- * @return the message of the expected Throwable
- */
- public static Throwable shouldFailWithCause(Class clazz, Closure code) {
- Throwable th = null;
- Throwable orig = null;
- int level = 0;
- try {
- code.call();
- } catch (GroovyRuntimeException gre) {
- orig = ScriptBytecodeAdapter.unwrap(gre);
- th = orig.getCause();
- } catch (Throwable e) {
- orig = e;
- th = orig.getCause();
- }
-
- while (th != null && !clazz.isInstance(th) && th != th.getCause() && level < MAX_NESTED_EXCEPTIONS) {
- th = th.getCause();
- level++;
- }
-
- if (orig == null) {
- fail("Closure " + code + " should have failed with an exception caused by type " + clazz.getName());
- } else if (th == null || !clazz.isInstance(th)) {
- fail("Closure " + code + " should have failed with an exception caused by type " + clazz.getName() + ", instead found these Exceptions:\n" + buildExceptionList(orig));
- }
- return th;
- }
-
- private static String buildExceptionList(Throwable th) {
- StringBuilder sb = new StringBuilder();
- int level = 0;
- while (th != null) {
- if (level > 1) {
- for (int i = 0; i < level - 1; i++) sb.append(" ");
- }
- if (level > 0) sb.append("-> ");
- if (level > MAX_NESTED_EXCEPTIONS) {
- sb.append("...");
- break;
- }
- sb.append(th.getClass().getName()).append(": ").append(th.getMessage()).append("\n");
- if (th == th.getCause()) {
- break;
- }
- th = th.getCause();
- level++;
- }
- return sb.toString();
- }
-
-}
diff --git a/subprojects/groovy-test/src/main/java/groovy/util/GroovyTestCase.java b/subprojects/groovy-test/src/main/java/groovy/util/GroovyTestCase.java
deleted file mode 100644
index 76dc45e..0000000
--- a/subprojects/groovy-test/src/main/java/groovy/util/GroovyTestCase.java
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util;
-
-import groovy.lang.Closure;
-import groovy.test.GroovyAssert;
-import junit.framework.TestCase;
-import org.codehaus.groovy.runtime.InvokerHelper;
-import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
-
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.logging.Logger;
-
-/**
- * A JUnit 3 {@link junit.framework.TestCase} base class in Groovy.
- *
- * In case JUnit 4 is used, see {@link groovy.test.GroovyAssert}.
- *
- * @see groovy.test.GroovyAssert
- */
-@Deprecated
-public class GroovyTestCase extends TestCase {
-
- protected static Logger log = Logger.getLogger(GroovyTestCase.class.getName());
-
- private static final AtomicInteger scriptFileNameCounter = new AtomicInteger(0);
-
- public static final String TEST_SCRIPT_NAME_PREFIX = "TestScript";
-
- private boolean useAgileDoxNaming = false;
-
- /**
- * Overload the getName() method to make the test cases look more like AgileDox
- * (thanks to Joe Walnes for this tip!)
- */
- public String getName() {
- if (useAgileDoxNaming) {
- return super.getName().substring(4).replaceAll("([A-Z])", " $1").toLowerCase();
- } else {
- return super.getName();
- }
- }
-
- public String getMethodName() {
- return super.getName();
- }
-
- /**
- * Asserts that the arrays are equivalent and contain the same values
- *
- * @param expected
- * @param value
- */
- protected void assertArrayEquals(Object[] expected, Object[] value) {
- String message =
- "expected array: " + InvokerHelper.toString(expected) + " value array: " + InvokerHelper.toString(value);
- assertNotNull(message + ": expected should not be null", expected);
- assertNotNull(message + ": value should not be null", value);
- assertEquals(message, expected.length, value.length);
- for (int i = 0, size = expected.length; i < size; i++) {
- assertEquals("value[" + i + "] when " + message, expected[i], value[i]);
- }
- }
-
- /**
- * Asserts that the array of characters has a given length
- *
- * @param length expected length
- * @param array the array
- */
- protected void assertLength(int length, char[] array) {
- assertEquals(length, array.length);
- }
-
- /**
- * Asserts that the array of ints has a given length
- *
- * @param length expected length
- * @param array the array
- */
- protected void assertLength(int length, int[] array) {
- assertEquals(length, array.length);
- }
-
- /**
- * Asserts that the array of objects has a given length
- *
- * @param length expected length
- * @param array the array
- */
- protected void assertLength(int length, Object[] array) {
- assertEquals(length, array.length);
- }
-
- /**
- * Asserts that the array of characters contains a given char
- *
- * @param expected expected character to be found
- * @param array the array
- */
- protected void assertContains(char expected, char[] array) {
- for (int i = 0; i < array.length; ++i) {
- if (array[i] == expected) {
- return;
- }
- }
-
- StringBuilder message = new StringBuilder();
-
- message.append(expected).append(" not in {");
-
- for (int i = 0; i < array.length; ++i) {
- message.append("'").append(array[i]).append("'");
-
- if (i < (array.length - 1)) {
- message.append(", ");
- }
- }
-
- message.append(" }");
-
- fail(message.toString());
- }
-
- /**
- * Asserts that the array of ints contains a given int
- *
- * @param expected expected int
- * @param array the array
- */
- protected void assertContains(int expected, int[] array) {
- for (int anInt : array) {
- if (anInt == expected) {
- return;
- }
- }
-
- StringBuilder message = new StringBuilder();
-
- message.append(expected).append(" not in {");
-
- for (int i = 0; i < array.length; ++i) {
- message.append("'").append(array[i]).append("'");
-
- if (i < (array.length - 1)) {
- message.append(", ");
- }
- }
-
- message.append(" }");
-
- fail(message.toString());
- }
-
- /**
- * Asserts that the value of toString() on the given object matches the
- * given text string
- *
- * @param value the object to be output to the console
- * @param expected the expected String representation
- */
- protected void assertToString(Object value, String expected) {
- Object console = InvokerHelper.invokeMethod(value, "toString", null);
- assertEquals("toString() on value: " + value, expected, console);
- }
-
- /**
- * Asserts that the value of inspect() on the given object matches the
- * given text string
- *
- * @param value the object to be output to the console
- * @param expected the expected String representation
- */
- protected void assertInspect(Object value, String expected) {
- Object console = InvokerHelper.invokeMethod(value, "inspect", null);
- assertEquals("inspect() on value: " + value, expected, console);
- }
-
- /**
- * see {@link groovy.test.GroovyAssert#assertScript(String)}
- */
- protected void assertScript(final String script) throws Exception {
- GroovyAssert.assertScript(script);
- }
-
- protected String getTestClassName() {
- return TEST_SCRIPT_NAME_PREFIX + getMethodName() + (scriptFileNameCounter.getAndIncrement()) + ".groovy";
- }
-
- /**
- * see {@link groovy.test.GroovyAssert#shouldFail(groovy.lang.Closure)}
- */
- protected String shouldFail(Closure code) {
- return GroovyAssert.shouldFail(code).getMessage();
- }
-
- /**
- * see {@link groovy.test.GroovyAssert#shouldFail(Class, groovy.lang.Closure)}
- */
- protected String shouldFail(Class clazz, Closure code) {
- return GroovyAssert.shouldFail(clazz, code).getMessage();
- }
-
- /**
- * see {@link groovy.test.GroovyAssert#shouldFailWithCause(Class, groovy.lang.Closure)}
- */
- protected String shouldFailWithCause(Class clazz, Closure code) {
- return GroovyAssert.shouldFailWithCause(clazz, code).getMessage();
- }
-
- /**
- * see {@link groovy.test.GroovyAssert#shouldFail(Class, String)}
- */
- protected String shouldFail(Class clazz, String script) {
- return GroovyAssert.shouldFail(clazz, script).getMessage();
- }
-
- /**
- * see {@link groovy.test.GroovyAssert#shouldFail(String)}
- */
- protected String shouldFail(String script) {
- return GroovyAssert.shouldFail(script).getMessage();
- }
-
- /**
- * Returns a copy of a string in which all EOLs are \n.
- */
- protected String fixEOLs(String value) {
- return value.replaceAll("(\\r\\n?)|\n", "\n");
- }
-
- /**
- * see {@link groovy.test.GroovyAssert#notYetImplemented(java.lang.Object)}
- */
- public static boolean notYetImplemented(Object caller) {
- return GroovyAssert.notYetImplemented(caller);
- }
-
- /**
- * Convenience method for subclasses of GroovyTestCase, identical to
- * <pre> GroovyTestCase.notYetImplemented(this); </pre>.
- *
- * @return <code>false</code> when not itself already in the call stack
- * @see #notYetImplemented(java.lang.Object)
- */
- public boolean notYetImplemented() {
- return notYetImplemented(this);
- }
-
- public static void assertEquals(String message, Object expected, Object actual) {
- if (expected == null && actual == null)
- return;
- if (expected != null && DefaultTypeTransformation.compareEqual(expected, actual))
- return;
- TestCase.assertEquals(message, expected, actual);
- }
-
- public static void assertEquals(Object expected, Object actual) {
- assertEquals(null, expected, actual);
- }
-
- public static void assertEquals(String expected, String actual) {
- assertEquals(null, expected, actual);
- }
-}
diff --git a/subprojects/groovy-test/src/main/java/groovy/util/GroovyTestSuite.java b/subprojects/groovy-test/src/main/java/groovy/util/GroovyTestSuite.java
deleted file mode 100644
index f8ce24e..0000000
--- a/subprojects/groovy-test/src/main/java/groovy/util/GroovyTestSuite.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util;
-
-import groovy.lang.GroovyClassLoader;
-import groovy.lang.Script;
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-import org.apache.groovy.test.ScriptTestAdapter;
-
-import java.io.File;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-
-/**
- * A TestSuite which will run a Groovy unit test case inside any Java IDE
- * either as a unit test case or as an application.
- * <p>
- * You can specify the GroovyUnitTest to run by running this class as an application
- * and specifying the script to run on the command line.
- * <code>
- * java groovy.util.GroovyTestSuite src/test/Foo.groovy
- * </code>
- * Or to run the test suite as a unit test suite in an IDE you can use
- * the 'test' system property to define the test script to run.
- * e.g. pass this into the JVM when the unit test plugin runs...
- * <code>
- * -Dtest=src/test/Foo.groovy
- * </code>
- */
-@Deprecated
-public class GroovyTestSuite extends TestSuite {
-
- protected static String file = null;
-
- protected final GroovyClassLoader loader =
- AccessController.doPrivileged(
- new PrivilegedAction<GroovyClassLoader>() {
- @Override
- public GroovyClassLoader run() {
- return new GroovyClassLoader(GroovyTestSuite.class.getClassLoader());
- }
- }
- );
-
- public static void main(String[] args) {
- if (args.length > 0) {
- file = args[0];
- }
- TestRunner.run(suite());
- }
-
- public static Test suite() {
- GroovyTestSuite suite = new GroovyTestSuite();
- try {
- suite.loadTestSuite();
- } catch (Exception e) {
- throw new RuntimeException("Could not create the test suite: " + e, e);
- }
- return suite;
- }
-
- public void loadTestSuite() throws Exception {
- String fileName = System.getProperty("test", file);
- if (fileName == null) {
- throw new RuntimeException("No filename given in the 'test' system property so cannot run a Groovy unit test");
- }
- System.out.println("Compiling: " + fileName);
- Class type = compile(fileName);
- String[] args = {};
- if (!Test.class.isAssignableFrom(type) && Script.class.isAssignableFrom(type)) {
- // let's treat the script as a Test
- addTest(new ScriptTestAdapter(type, args));
- } else {
- addTestSuite(type);
- }
- }
-
- public Class compile(String fileName) throws Exception {
- return loader.parseClass(new File(fileName));
- }
-}
diff --git a/subprojects/groovy-test/src/main/java/org/codehaus/groovy/runtime/ScriptTestAdapter.java b/subprojects/groovy-test/src/main/java/org/codehaus/groovy/runtime/ScriptTestAdapter.java
deleted file mode 100644
index b82b49a..0000000
--- a/subprojects/groovy-test/src/main/java/org/codehaus/groovy/runtime/ScriptTestAdapter.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.codehaus.groovy.runtime;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-
-/**
- * An adapter to make any Groovy Script class an instance of a JUnit Test
- *
- * @deprecated use {@link org.apache.groovy.test.ScriptTestAdapter}
- */
-@Deprecated
-public class ScriptTestAdapter implements Test {
- private Class scriptClass;
- private String[] arguments;
-
- public ScriptTestAdapter(Class scriptClass, String[] arguments) {
- this.scriptClass = scriptClass;
- this.arguments = arguments;
- }
-
- public int countTestCases() {
- return 1;
- }
-
- public void run(TestResult result) {
- try {
- result.startTest(this);
-
- // let's run the script
- InvokerHelper.runScript(scriptClass, arguments);
- result.endTest(this);
- } catch (Exception e) {
- result.addError(this, e);
- }
- }
-
- public String toString() {
- return "TestCase for script: " + scriptClass.getName();
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/XmlNodePrinter.java b/subprojects/groovy-xml/src/main/java/groovy/util/XmlNodePrinter.java
deleted file mode 100644
index 261b9c9..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/XmlNodePrinter.java
+++ /dev/null
@@ -1,446 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util;
-
-import groovy.xml.QName;
-import org.codehaus.groovy.runtime.InvokerHelper;
-
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Prints a <code>groovy.util.Node</code> (as used with <code>XmlParser</code>) including all children in XML format.
- * Typical usage:
- * <pre>
- * def xml = '<html><head><title>Title</title></head><body><h1>Header</h1></body></html>'
- * def root = new XmlParser().parseText(xml)
- * new XmlNodePrinter(preserveWhitespace:true).print(root.body[0])
- * </pre>
- * which when run produces this on stdout (or use your own <code>PrintWriter</code> to direct elsewhere):
- * <pre>
- * <body>
- * <h1>Header</h1>
- * </body>
- * </pre>
- *
- * @see groovy.util.NodePrinter
- * @see groovy.xml.XmlUtil#serialize(Node)
- * @deprecated use {@link groovy.xml.XmlNodePrinter}
- */
-@Deprecated
-public class XmlNodePrinter {
-
- protected final IndentPrinter out;
- private String quote;
- private boolean namespaceAware = true;
- private boolean preserveWhitespace = false;
- private boolean expandEmptyElements = false;
-
- public XmlNodePrinter(PrintWriter out) {
- this(out, " ");
- }
-
- public XmlNodePrinter(PrintWriter out, String indent) {
- this(out, indent, "\"");
- }
-
- public XmlNodePrinter(PrintWriter out, String indent, String quote) {
- this(new IndentPrinter(out, indent), quote);
- }
-
- public XmlNodePrinter(IndentPrinter out) {
- this(out, "\"");
- }
-
- public XmlNodePrinter(IndentPrinter out, String quote) {
- if (out == null) {
- throw new IllegalArgumentException("Argument 'IndentPrinter out' must not be null!");
- }
- this.out = out;
- this.quote = quote;
- }
-
- public XmlNodePrinter() {
- this(new PrintWriter(new OutputStreamWriter(System.out)));
- }
-
- public void print(Node node) {
- print(node, new NamespaceContext());
- }
-
- /**
- * Check if namespace handling is enabled.
- * Defaults to <code>true</code>.
- *
- * @return true if namespace handling is enabled
- */
- public boolean isNamespaceAware() {
- return namespaceAware;
- }
-
- /**
- * Enable and/or disable namespace handling.
- *
- * @param namespaceAware the new desired value
- */
- public void setNamespaceAware(boolean namespaceAware) {
- this.namespaceAware = namespaceAware;
- }
-
- /**
- * Check if whitespace preservation is enabled.
- * Defaults to <code>false</code>.
- *
- * @return true if whitespaces are honoured when printing simple text nodes
- */
- public boolean isPreserveWhitespace() {
- return preserveWhitespace;
- }
-
- /**
- * Enable and/or disable preservation of whitespace.
- *
- * @param preserveWhitespace the new desired value
- */
- public void setPreserveWhitespace(boolean preserveWhitespace) {
- this.preserveWhitespace = preserveWhitespace;
- }
-
- /**
- * Get Quote to use when printing attributes.
- *
- * @return the quote character
- */
- public String getQuote() {
- return quote;
- }
-
- /**
- * Set Quote to use when printing attributes.
- *
- * @param quote the quote character
- */
- public void setQuote(String quote) {
- this.quote = quote;
- }
-
- /**
- * Whether empty elements are expanded from <tagName/> to <tagName></tagName>.
- *
- * @return <code>true</code>, if empty elements will be represented by an opening tag
- * followed immediately by a closing tag.
- */
- public boolean isExpandEmptyElements() {
- return expandEmptyElements;
- }
-
- /**
- * Whether empty elements are expanded from <tagName/> to <tagName></tagName>.
- *
- * @param expandEmptyElements if <code>true</code>, empty
- * elements will be represented by an opening tag
- * followed immediately by a closing tag.
- * Defaults to <code>false</code>.
- */
- public void setExpandEmptyElements(boolean expandEmptyElements) {
- this.expandEmptyElements = expandEmptyElements;
- }
-
- protected void print(Node node, NamespaceContext ctx) {
- /*
- * Handle empty elements like '<br/>', '<img/> or '<hr noshade="noshade"/>.
- */
- if (isEmptyElement(node)) {
- printLineBegin();
- out.print("<");
- out.print(getName(node));
- if (ctx != null) {
- printNamespace(node, ctx);
- }
- printNameAttributes(node.attributes(), ctx);
- if (expandEmptyElements) {
- out.print("></");
- out.print(getName(node));
- out.print(">");
- } else {
- out.print("/>");
- }
- printLineEnd();
- out.flush();
- return;
- }
-
- /*
- * Hook for extra processing, e.g. GSP tag element!
- */
- if (printSpecialNode(node)) {
- out.flush();
- return;
- }
-
- /*
- * Handle normal element like <html> ... </html>.
- */
- Object value = node.value();
- if (value instanceof List) {
- printName(node, ctx, true, isListOfSimple((List) value));
- printList((List) value, ctx);
- printName(node, ctx, false, isListOfSimple((List) value));
- out.flush();
- return;
- }
-
- // treat as simple type - probably a String
- printName(node, ctx, true, preserveWhitespace);
- printSimpleItemWithIndent(value);
- printName(node, ctx, false, preserveWhitespace);
- out.flush();
- }
-
- private boolean isListOfSimple(List value) {
- for (Object p : value) {
- if (p instanceof Node) return false;
- }
- return preserveWhitespace;
- }
-
- protected void printLineBegin() {
- out.printIndent();
- }
-
- protected void printLineEnd() {
- printLineEnd(null);
- }
-
- protected void printLineEnd(String comment) {
- if (comment != null) {
- out.print(" <!-- ");
- out.print(comment);
- out.print(" -->");
- }
- out.println();
- out.flush();
- }
-
- protected void printList(List list, NamespaceContext ctx) {
- out.incrementIndent();
- for (Object value : list) {
- NamespaceContext context = new NamespaceContext(ctx);
- /*
- * If the current value is a node, recurse into that node.
- */
- if (value instanceof Node) {
- print((Node) value, context);
- continue;
- }
- printSimpleItem(value);
- }
- out.decrementIndent();
- }
-
- protected void printSimpleItem(Object value) {
- if (!preserveWhitespace) printLineBegin();
- printEscaped(InvokerHelper.toString(value), false);
- if (!preserveWhitespace) printLineEnd();
- }
-
- protected void printName(Node node, NamespaceContext ctx, boolean begin, boolean preserve) {
- if (node == null) {
- throw new NullPointerException("Node must not be null.");
- }
- Object name = node.name();
- if (name == null) {
- throw new NullPointerException("Name must not be null.");
- }
- if (!preserve || begin) printLineBegin();
- out.print("<");
- if (!begin) {
- out.print("/");
- }
- out.print(getName(node));
- if (ctx != null) {
- printNamespace(node, ctx);
- }
- if (begin) {
- printNameAttributes(node.attributes(), ctx);
- }
- out.print(">");
- if (!preserve || !begin) printLineEnd();
- }
-
- protected boolean printSpecialNode(Node node) {
- return false;
- }
-
- protected void printNamespace(Object object, NamespaceContext ctx) {
- if (namespaceAware) {
- if (object instanceof Node) {
- printNamespace(((Node) object).name(), ctx);
- } else if (object instanceof QName) {
- QName qname = (QName) object;
- String namespaceUri = qname.getNamespaceURI();
- if (namespaceUri != null) {
- String prefix = qname.getPrefix();
- if (!ctx.isPrefixRegistered(prefix, namespaceUri)) {
- ctx.registerNamespacePrefix(prefix, namespaceUri);
- out.print(" ");
- out.print("xmlns");
- if (prefix.length() > 0) {
- out.print(":");
- out.print(prefix);
- }
- out.print("=" + quote);
- out.print(namespaceUri);
- out.print(quote);
- }
- }
- }
- }
- }
-
- protected void printNameAttributes(Map attributes, NamespaceContext ctx) {
- if (attributes == null || attributes.isEmpty()) {
- return;
- }
- for (Object p : attributes.entrySet()) {
- Map.Entry entry = (Map.Entry) p;
- out.print(" ");
- out.print(getName(entry.getKey()));
- out.print("=");
- Object value = entry.getValue();
- out.print(quote);
- if (value instanceof String) {
- printEscaped((String) value, true);
- } else {
- printEscaped(InvokerHelper.toString(value), true);
- }
- out.print(quote);
- printNamespace(entry.getKey(), ctx);
- }
- }
-
- private static boolean isEmptyElement(Node node) {
- if (node == null) {
- throw new IllegalArgumentException("Node must not be null!");
- }
- if (!node.children().isEmpty()) {
- return false;
- }
- return node.text().length() == 0;
- }
-
- private String getName(Object object) {
- if (object instanceof String) {
- return (String) object;
- } else if (object instanceof QName) {
- QName qname = (QName) object;
- if (!namespaceAware) {
- return qname.getLocalPart();
- }
- return qname.getQualifiedName();
- } else if (object instanceof Node) {
- Object name = ((Node) object).name();
- return getName(name);
- }
- return object.toString();
- }
-
- private void printSimpleItemWithIndent(Object value) {
- if (!preserveWhitespace) out.incrementIndent();
- printSimpleItem(value);
- if (!preserveWhitespace) out.decrementIndent();
- }
-
- // For ' and " we only escape if needed. As far as XML is concerned,
- // we could always escape if we wanted to.
- private void printEscaped(String s, boolean isAttributeValue) {
- for (int i = 0; i < s.length(); i++) {
- char c = s.charAt(i);
- switch (c) {
- case '<':
- out.print("<");
- break;
- case '>':
- out.print(">");
- break;
- case '&':
- out.print("&");
- break;
- case '\'':
- if (isAttributeValue && quote.equals("'"))
- out.print("'");
- else
- out.print(c);
- break;
- case '"':
- if (isAttributeValue && quote.equals("\""))
- out.print(""");
- else
- out.print(c);
- break;
- case '\n':
- if (isAttributeValue)
- out.print(" ");
- else
- out.print(c);
- break;
- case '\r':
- if (isAttributeValue)
- out.print(" ");
- else
- out.print(c);
- break;
- default:
- out.print(c);
- }
- }
- }
-
- @Deprecated
- protected static class NamespaceContext {
- private final Map<String, String> namespaceMap;
-
- public NamespaceContext() {
- namespaceMap = new HashMap<String, String>();
- }
-
- public NamespaceContext(NamespaceContext context) {
- this();
- namespaceMap.putAll(context.namespaceMap);
- }
-
- public boolean isPrefixRegistered(String prefix, String uri) {
- return namespaceMap.containsKey(prefix) && namespaceMap.get(prefix).equals(uri);
- }
-
- public void registerNamespacePrefix(String prefix, String uri) {
- if (!isPrefixRegistered(prefix, uri)) {
- namespaceMap.put(prefix, uri);
- }
- }
-
- public String getNamespace(String prefix) {
- Object uri = namespaceMap.get(prefix);
- return (uri == null) ? null : uri.toString();
- }
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/XmlParser.java b/subprojects/groovy-xml/src/main/java/groovy/util/XmlParser.java
deleted file mode 100644
index ce28050..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/XmlParser.java
+++ /dev/null
@@ -1,505 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util;
-
-import groovy.xml.FactorySupport;
-import groovy.xml.QName;
-import org.xml.sax.Attributes;
-import org.xml.sax.ContentHandler;
-import org.xml.sax.DTDHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.Locator;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.XMLReader;
-
-import javax.xml.XMLConstants;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Reader;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * A helper class for parsing XML into a tree of Node instances for a
- * simple way of processing XML. This parser does not preserve the XML
- * InfoSet - if that's what you need try using W3C DOM, dom4j, JDOM, XOM etc.
- * This parser ignores comments and processing instructions and converts
- * the XML into a Node for each element in the XML with attributes
- * and child Nodes and Strings. This simple model is sufficient for
- * most simple use cases of processing XML.
- * <p>
- * Example usage:
- * <pre class="groovyTestCase">
- * def xml = '<root><one a1="uno!"/><two>Some text!</two></root>'
- * def rootNode = new XmlParser().parseText(xml)
- * assert rootNode.name() == 'root'
- * assert rootNode.one[0].@a1 == 'uno!'
- * assert rootNode.two.text() == 'Some text!'
- * rootNode.children().each { assert it.name() in ['one','two'] }
- * </pre>
- *
- * @deprecated use {@link groovy.xml.XmlParser}
- */
-@Deprecated
-public class XmlParser implements ContentHandler {
-
- private StringBuilder bodyText = new StringBuilder();
- private final List<Node> stack = new ArrayList<Node>();
- private Locator locator;
- private final XMLReader reader;
- private Node parent;
-
- private boolean trimWhitespace = false;
- private boolean keepIgnorableWhitespace = false;
- private boolean namespaceAware;
-
- /**
- * Creates a non-validating and namespace-aware <code>XmlParser</code> which does not allow DOCTYPE declarations in documents.
- *
- * @throws ParserConfigurationException if no parser which satisfies the requested configuration can be created.
- * @throws SAXException for SAX errors.
- */
- public XmlParser() throws ParserConfigurationException, SAXException {
- this(false, true);
- }
-
- /**
- * Creates a <code>XmlParser</code> which does not allow DOCTYPE declarations in documents.
- *
- * @param validating <code>true</code> if the parser should validate documents as they are parsed; false otherwise.
- * @param namespaceAware <code>true</code> if the parser should provide support for XML namespaces; <code>false</code> otherwise.
- * @throws ParserConfigurationException if no parser which satisfies the requested configuration can be created.
- * @throws SAXException for SAX errors.
- */
- public XmlParser(boolean validating, boolean namespaceAware) throws ParserConfigurationException, SAXException {
- this(validating, namespaceAware, false);
- }
-
- /**
- * Creates a <code>XmlParser</code>.
- *
- * @param validating <code>true</code> if the parser should validate documents as they are parsed; false otherwise.
- * @param namespaceAware <code>true</code> if the parser should provide support for XML namespaces; <code>false</code> otherwise.
- * @param allowDocTypeDeclaration <code>true</code> if the parser should provide support for DOCTYPE declarations; <code>false</code> otherwise.
- * @throws ParserConfigurationException if no parser which satisfies the requested configuration can be created.
- * @throws SAXException for SAX errors.
- */
- public XmlParser(boolean validating, boolean namespaceAware, boolean allowDocTypeDeclaration) throws ParserConfigurationException, SAXException {
- SAXParserFactory factory = FactorySupport.createSaxParserFactory();
- factory.setNamespaceAware(namespaceAware);
- this.namespaceAware = namespaceAware;
- factory.setValidating(validating);
- setQuietly(factory, XMLConstants.FEATURE_SECURE_PROCESSING, true);
- setQuietly(factory, "http://apache.org/xml/features/disallow-doctype-decl", !allowDocTypeDeclaration);
- reader = factory.newSAXParser().getXMLReader();
- }
-
- public XmlParser(XMLReader reader) {
- this.reader = reader;
- }
-
- public XmlParser(SAXParser parser) throws SAXException {
- reader = parser.getXMLReader();
- }
-
- private static void setQuietly(SAXParserFactory factory, String feature, boolean value) {
- try {
- factory.setFeature(feature, value);
- }
- catch (ParserConfigurationException | SAXNotSupportedException | SAXNotRecognizedException ignored) { }
- }
-
- /**
- * Returns the current trim whitespace setting.
- *
- * @return true if whitespace will be trimmed
- */
- public boolean isTrimWhitespace() {
- return trimWhitespace;
- }
-
- /**
- * Sets the trim whitespace setting value.
- *
- * @param trimWhitespace the desired setting value
- */
- public void setTrimWhitespace(boolean trimWhitespace) {
- this.trimWhitespace = trimWhitespace;
- }
-
- /**
- * Returns the current keep ignorable whitespace setting.
- *
- * @return true if ignorable whitespace will be kept (default false)
- */
- public boolean isKeepIgnorableWhitespace() {
- return keepIgnorableWhitespace;
- }
-
- /**
- * Sets the keep ignorable whitespace setting value.
- *
- * @param keepIgnorableWhitespace the desired new value
- */
- public void setKeepIgnorableWhitespace(boolean keepIgnorableWhitespace) {
- this.keepIgnorableWhitespace = keepIgnorableWhitespace;
- }
-
- /**
- * Parses the content of the given file as XML turning it into a tree
- * of Nodes.
- *
- * @param file the File containing the XML to be parsed
- * @return the root node of the parsed tree of Nodes
- * @throws SAXException Any SAX exception, possibly
- * wrapping another exception.
- * @throws IOException An IO exception from the parser,
- * possibly from a byte stream or character stream
- * supplied by the application.
- */
- public Node parse(File file) throws IOException, SAXException {
- InputSource input = new InputSource(new FileInputStream(file));
- input.setSystemId("file://" + file.getAbsolutePath());
- getXMLReader().parse(input);
- return parent;
-
- }
-
- /**
- * Parse the content of the specified input source into a tree of Nodes.
- *
- * @param input the InputSource for the XML to parse
- * @return the root node of the parsed tree of Nodes
- * @throws SAXException Any SAX exception, possibly
- * wrapping another exception.
- * @throws IOException An IO exception from the parser,
- * possibly from a byte stream or character stream
- * supplied by the application.
- */
- public Node parse(InputSource input) throws IOException, SAXException {
- getXMLReader().parse(input);
- return parent;
- }
-
- /**
- * Parse the content of the specified input stream into a tree of Nodes.
- * <p>
- * Note that using this method will not provide the parser with any URI
- * for which to find DTDs etc
- *
- * @param input an InputStream containing the XML to be parsed
- * @return the root node of the parsed tree of Nodes
- * @throws SAXException Any SAX exception, possibly
- * wrapping another exception.
- * @throws IOException An IO exception from the parser,
- * possibly from a byte stream or character stream
- * supplied by the application.
- */
- public Node parse(InputStream input) throws IOException, SAXException {
- InputSource is = new InputSource(input);
- getXMLReader().parse(is);
- return parent;
- }
-
- /**
- * Parse the content of the specified reader into a tree of Nodes.
- * <p>
- * Note that using this method will not provide the parser with any URI
- * for which to find DTDs etc
- *
- * @param in a Reader to read the XML to be parsed
- * @return the root node of the parsed tree of Nodes
- * @throws SAXException Any SAX exception, possibly
- * wrapping another exception.
- * @throws IOException An IO exception from the parser,
- * possibly from a byte stream or character stream
- * supplied by the application.
- */
- public Node parse(Reader in) throws IOException, SAXException {
- InputSource is = new InputSource(in);
- getXMLReader().parse(is);
- return parent;
- }
-
- /**
- * Parse the content of the specified URI into a tree of Nodes.
- *
- * @param uri a String containing a uri pointing to the XML to be parsed
- * @return the root node of the parsed tree of Nodes
- * @throws SAXException Any SAX exception, possibly
- * wrapping another exception.
- * @throws IOException An IO exception from the parser,
- * possibly from a byte stream or character stream
- * supplied by the application.
- */
- public Node parse(String uri) throws IOException, SAXException {
- InputSource is = new InputSource(uri);
- getXMLReader().parse(is);
- return parent;
- }
-
- /**
- * A helper method to parse the given text as XML.
- *
- * @param text the XML text to parse
- * @return the root node of the parsed tree of Nodes
- * @throws SAXException Any SAX exception, possibly
- * wrapping another exception.
- * @throws IOException An IO exception from the parser,
- * possibly from a byte stream or character stream
- * supplied by the application.
- */
- public Node parseText(String text) throws IOException, SAXException {
- return parse(new StringReader(text));
- }
-
- /**
- * Determine if namespace handling is enabled.
- *
- * @return true if namespace handling is enabled
- */
- public boolean isNamespaceAware() {
- return namespaceAware;
- }
-
- /**
- * Enable and/or disable namespace handling.
- *
- * @param namespaceAware the new desired value
- */
- public void setNamespaceAware(boolean namespaceAware) {
- this.namespaceAware = namespaceAware;
- }
-
- // Delegated XMLReader methods
- //------------------------------------------------------------------------
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#getDTDHandler()
- */
- public DTDHandler getDTDHandler() {
- return this.reader.getDTDHandler();
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#getEntityResolver()
- */
- public EntityResolver getEntityResolver() {
- return this.reader.getEntityResolver();
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#getErrorHandler()
- */
- public ErrorHandler getErrorHandler() {
- return this.reader.getErrorHandler();
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#getFeature(java.lang.String)
- */
- public boolean getFeature(final String uri) throws SAXNotRecognizedException, SAXNotSupportedException {
- return this.reader.getFeature(uri);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#getProperty(java.lang.String)
- */
- public Object getProperty(final String uri) throws SAXNotRecognizedException, SAXNotSupportedException {
- return this.reader.getProperty(uri);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#setDTDHandler(org.xml.sax.DTDHandler)
- */
- public void setDTDHandler(final DTDHandler dtdHandler) {
- this.reader.setDTDHandler(dtdHandler);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#setEntityResolver(org.xml.sax.EntityResolver)
- */
- public void setEntityResolver(final EntityResolver entityResolver) {
- this.reader.setEntityResolver(entityResolver);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#setErrorHandler(org.xml.sax.ErrorHandler)
- */
- public void setErrorHandler(final ErrorHandler errorHandler) {
- this.reader.setErrorHandler(errorHandler);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean)
- */
- public void setFeature(final String uri, final boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {
- this.reader.setFeature(uri, value);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#setProperty(java.lang.String, java.lang.Object)
- */
- public void setProperty(final String uri, final Object value) throws SAXNotRecognizedException, SAXNotSupportedException {
- reader.setProperty(uri, value);
- }
-
- // ContentHandler interface
- //-------------------------------------------------------------------------
- public void startDocument() throws SAXException {
- parent = null;
- }
-
- public void endDocument() throws SAXException {
- stack.clear();
- }
-
- public void startElement(String namespaceURI, String localName, String qName, Attributes list)
- throws SAXException {
- addTextToNode();
-
- Object nodeName = getElementName(namespaceURI, localName, qName);
-
- int size = list.getLength();
- Map<Object, String> attributes = new LinkedHashMap<Object, String>(size);
- for (int i = 0; i < size; i++) {
- Object attributeName = getElementName(list.getURI(i), list.getLocalName(i), list.getQName(i));
- String value = list.getValue(i);
- attributes.put(attributeName, value);
- }
- parent = createNode(parent, nodeName, attributes);
- stack.add(parent);
- }
-
- public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
- addTextToNode();
-
- if (!stack.isEmpty()) {
- stack.remove(stack.size() - 1);
- if (!stack.isEmpty()) {
- parent = stack.get(stack.size() - 1);
- }
- }
- }
-
- public void characters(char buffer[], int start, int length) throws SAXException {
- bodyText.append(buffer, start, length);
- }
-
- public void startPrefixMapping(String prefix, String namespaceURI) throws SAXException {
- }
-
- public void endPrefixMapping(String prefix) throws SAXException {
- }
-
- public void ignorableWhitespace(char buffer[], int start, int len) throws SAXException {
- if (keepIgnorableWhitespace) characters(buffer, start, len);
- }
-
- public void processingInstruction(String target, String data) throws SAXException {
- }
-
- public Locator getDocumentLocator() {
- return locator;
- }
-
- public void setDocumentLocator(Locator locator) {
- this.locator = locator;
- }
-
- public void skippedEntity(String name) throws SAXException {
- }
-
- // Implementation methods
- //-------------------------------------------------------------------------
- protected XMLReader getXMLReader() {
- reader.setContentHandler(this);
- return reader;
- }
-
- protected void addTextToNode() {
- if (parent == null) {
- // TODO store this on root node? reset bodyText?
- return;
- }
- String text = bodyText.toString();
- if (!trimWhitespace && keepIgnorableWhitespace) {
- parent.children().add(text);
- } else if (!trimWhitespace && text.trim().length() > 0) {
- parent.children().add(text);
- } else if (text.trim().length() > 0) {
- parent.children().add(text.trim());
- }
- bodyText = new StringBuilder();
- }
-
- /**
- * Creates a new node with the given parent, name, and attributes. The
- * default implementation returns an instance of
- * <code>groovy.util.Node</code>.
- *
- * @param parent the parent node, or null if the node being created is the
- * root node
- * @param name an Object representing the name of the node (typically
- * an instance of {@link QName})
- * @param attributes a Map of attribute names to attribute values
- * @return a new Node instance representing the current node
- */
- protected Node createNode(Node parent, Object name, Map attributes) {
- return new Node(parent, name, attributes);
- }
-
- /**
- * Return a name given the namespaceURI, localName and qName.
- *
- * @param namespaceURI the namespace URI
- * @param localName the local name
- * @param qName the qualified name
- * @return the newly created representation of the name
- */
- protected Object getElementName(String namespaceURI, String localName, String qName) {
- String name = localName;
- String prefix = "";
- if ((name == null) || (name.length() < 1)) {
- name = qName;
- }
- if (namespaceURI == null || namespaceURI.length() <= 0) {
- return name;
- }
- if (qName != null && qName.length() > 0 && namespaceAware) {
- int index = qName.lastIndexOf(":");
- if (index > 0) {
- prefix = qName.substring(0, index);
- }
- }
- return new QName(namespaceURI, name, prefix);
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/XmlSlurper.java b/subprojects/groovy-xml/src/main/java/groovy/util/XmlSlurper.java
deleted file mode 100644
index 90e6bb3..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/XmlSlurper.java
+++ /dev/null
@@ -1,467 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util;
-
-import groovy.util.slurpersupport.GPathResult;
-import groovy.util.slurpersupport.NamespaceAwareHashMap;
-import groovy.util.slurpersupport.Node;
-import groovy.util.slurpersupport.NodeChild;
-import groovy.xml.FactorySupport;
-import groovy.xml.QName;
-import org.xml.sax.Attributes;
-import org.xml.sax.DTDHandler;
-import org.xml.sax.EntityResolver;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.DefaultHandler;
-
-import javax.xml.XMLConstants;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Reader;
-import java.io.StringReader;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Stack;
-
-/**
- * Parse XML into a document tree that may be traversed similar to XPath
- * expressions. For example:
- * <pre class="groovyTestCase">
- * def rootNode = new XmlSlurper().parseText(
- * '<root><one a1="uno!"/><two>Some text!</two></root>' )
- *
- * assert rootNode.name() == 'root'
- * assert rootNode.one[0].@a1 == 'uno!'
- * assert rootNode.two.text() == 'Some text!'
- * rootNode.children().each { assert it.name() in ['one','two'] }
- * </pre>
- * <p>
- * Note that in some cases, a 'selector' expression may not resolve to a
- * single node. For example:
- * <pre class="groovyTestCase">
- * def rootNode = new XmlSlurper().parseText(
- * '''<root>
- * <a>one!</a>
- * <a>two!</a>
- * </root>''' )
- *
- * assert rootNode.a.size() == 2
- * rootNode.a.each { assert it.text() in ['one!','two!'] }
- * </pre>
- *
- * @see GPathResult
- * @deprecated use {@link groovy.xml.XmlSlurper}
- */
-@Deprecated
-public class XmlSlurper extends DefaultHandler {
- private final XMLReader reader;
- private Node currentNode = null;
- private final Stack<Node> stack = new Stack<Node>();
- private final StringBuilder charBuffer = new StringBuilder();
- private final Map<String, String> namespaceTagHints = new HashMap<String, String>();
- private boolean keepIgnorableWhitespace = false;
- private boolean namespaceAware = false;
-
- /**
- * Creates a non-validating and namespace-aware <code>XmlSlurper</code> which does not allow DOCTYPE declarations in documents.
- *
- * @throws ParserConfigurationException if no parser which satisfies the requested configuration can be created.
- * @throws SAXException for SAX errors.
- */
- public XmlSlurper() throws ParserConfigurationException, SAXException {
- this(false, true);
- }
-
- /**
- * Creates a <code>XmlSlurper</code> which does not allow DOCTYPE declarations in documents.
- *
- * @param validating <code>true</code> if the parser should validate documents as they are parsed; false otherwise.
- * @param namespaceAware <code>true</code> if the parser should provide support for XML namespaces; <code>false</code> otherwise.
- *
- * @throws ParserConfigurationException if no parser which satisfies the requested configuration can be created.
- * @throws SAXException for SAX errors.
- */
- public XmlSlurper(final boolean validating, final boolean namespaceAware) throws ParserConfigurationException, SAXException {
- this(validating, namespaceAware, false);
- }
-
- /**
- * Creates a <code>XmlSlurper</code>.
- *
- * @param validating <code>true</code> if the parser should validate documents as they are parsed; false otherwise.
- * @param namespaceAware <code>true</code> if the parser should provide support for XML namespaces; <code>false</code> otherwise.
- * @param allowDocTypeDeclaration <code>true</code> if the parser should provide support for DOCTYPE declarations; <code>false</code> otherwise.
- *
- * @throws ParserConfigurationException if no parser which satisfies the requested configuration can be created.
- * @throws SAXException for SAX errors.
- */
- public XmlSlurper(final boolean validating, final boolean namespaceAware, boolean allowDocTypeDeclaration) throws ParserConfigurationException, SAXException {
- SAXParserFactory factory = FactorySupport.createSaxParserFactory();
- factory.setNamespaceAware(namespaceAware);
- this.namespaceAware = namespaceAware;
- factory.setValidating(validating);
- setQuietly(factory, XMLConstants.FEATURE_SECURE_PROCESSING, true);
- setQuietly(factory, "http://apache.org/xml/features/disallow-doctype-decl", !allowDocTypeDeclaration);
- reader = factory.newSAXParser().getXMLReader();
- }
-
- public XmlSlurper(final XMLReader reader) {
- this.reader = reader;
- }
-
- public XmlSlurper(final SAXParser parser) throws SAXException {
- this(parser.getXMLReader());
- }
-
- private static void setQuietly(SAXParserFactory factory, String feature, boolean value) {
- try {
- factory.setFeature(feature, value);
- }
- catch (ParserConfigurationException | SAXNotSupportedException | SAXNotRecognizedException ignored) { }
- }
-
- /**
- * @deprecated use setKeepIgnorableWhitespace
- * @param keepWhitespace If true then whitespace before elements is kept.
- * The default is to discard the whitespace.
- */
- @Deprecated
- public void setKeepWhitespace(boolean keepWhitespace) {
- setKeepIgnorableWhitespace(keepWhitespace);
- }
-
- /**
- * @param keepIgnorableWhitespace If true then ignorable whitespace (i.e. whitespace before elements) is kept.
- * The default is to discard the whitespace.
- */
- public void setKeepIgnorableWhitespace(boolean keepIgnorableWhitespace) {
- this.keepIgnorableWhitespace = keepIgnorableWhitespace;
- }
-
- /**
- * @return true if ignorable whitespace is kept
- */
- public boolean isKeepIgnorableWhitespace() {
- return keepIgnorableWhitespace;
- }
-
- /**
- * @return The GPathResult instance created by consuming a stream of SAX events
- * Note if one of the parse methods has been called then this returns null
- * Note if this is called more than once all calls after the first will return null
- */
- public GPathResult getDocument() {
- try {
- // xml namespace is always defined
- if (namespaceAware) {
- namespaceTagHints.put("xml", "http://www.w3.org/XML/1998/namespace");
- }
- return new NodeChild(currentNode, null, namespaceTagHints);
- } finally {
- currentNode = null;
- }
- }
-
- /**
- * Parse the content of the specified input source into a GPathResult object
- *
- * @param input the InputSource to parse
- * @return An object which supports GPath expressions
- * @throws SAXException Any SAX exception, possibly wrapping another exception.
- * @throws IOException An IO exception from the parser, possibly from a byte stream
- * or character stream supplied by the application.
- */
- public GPathResult parse(final InputSource input) throws IOException, SAXException {
- reader.setContentHandler(this);
- reader.parse(input);
- return getDocument();
- }
-
- /**
- * Parses the content of the given file as XML turning it into a GPathResult object
- *
- * @param file the File to parse
- * @return An object which supports GPath expressions
- * @throws SAXException Any SAX exception, possibly wrapping another exception.
- * @throws IOException An IO exception from the parser, possibly from a byte stream
- * or character stream supplied by the application.
- */
- public GPathResult parse(final File file) throws IOException, SAXException {
- final FileInputStream fis = new FileInputStream(file);
- final InputSource input = new InputSource(fis);
- input.setSystemId("file://" + file.getAbsolutePath());
- try {
- return parse(input);
- } finally {
- fis.close();
- }
- }
-
- /**
- * Parse the content of the specified input stream into an GPathResult Object.
- * Note that using this method will not provide the parser with any URI
- * for which to find DTDs etc. It is up to you to close the InputStream
- * after parsing is complete (if required).
- *
- * @param input the InputStream to parse
- * @return An object which supports GPath expressions
- * @throws SAXException Any SAX exception, possibly wrapping another exception.
- * @throws IOException An IO exception from the parser, possibly from a byte stream
- * or character stream supplied by the application.
- */
- public GPathResult parse(final InputStream input) throws IOException, SAXException {
- return parse(new InputSource(input));
- }
-
- /**
- * Parse the content of the specified reader into a GPathResult Object.
- * Note that using this method will not provide the parser with any URI
- * for which to find DTDs etc. It is up to you to close the Reader
- * after parsing is complete (if required).
- *
- * @param in the Reader to parse
- * @return An object which supports GPath expressions
- * @throws SAXException Any SAX exception, possibly wrapping another exception.
- * @throws IOException An IO exception from the parser, possibly from a byte stream
- * or character stream supplied by the application.
- */
- public GPathResult parse(final Reader in) throws IOException, SAXException {
- return parse(new InputSource(in));
- }
-
- /**
- * Parse the content of the specified URI into a GPathResult Object
- *
- * @param uri a String containing the URI to parse
- * @return An object which supports GPath expressions
- * @throws SAXException Any SAX exception, possibly wrapping another exception.
- * @throws IOException An IO exception from the parser, possibly from a byte stream
- * or character stream supplied by the application.
- */
- public GPathResult parse(final String uri) throws IOException, SAXException {
- return parse(new InputSource(uri));
- }
-
- /**
- * A helper method to parse the given text as XML
- *
- * @param text a String containing XML to parse
- * @return An object which supports GPath expressions
- * @throws SAXException Any SAX exception, possibly wrapping another exception.
- * @throws IOException An IO exception from the parser, possibly from a byte stream
- * or character stream supplied by the application.
- */
- public GPathResult parseText(final String text) throws IOException, SAXException {
- return parse(new StringReader(text));
- }
-
- // Delegated XMLReader methods
- //------------------------------------------------------------------------
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#getDTDHandler()
- */
- public DTDHandler getDTDHandler() {
- return reader.getDTDHandler();
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#getEntityResolver()
- */
- public EntityResolver getEntityResolver() {
- return reader.getEntityResolver();
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#getErrorHandler()
- */
- public ErrorHandler getErrorHandler() {
- return reader.getErrorHandler();
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#getFeature(java.lang.String)
- */
- public boolean getFeature(final String uri) throws SAXNotRecognizedException, SAXNotSupportedException {
- return reader.getFeature(uri);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#getProperty(java.lang.String)
- */
- public Object getProperty(final String uri) throws SAXNotRecognizedException, SAXNotSupportedException {
- return reader.getProperty(uri);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#setDTDHandler(org.xml.sax.DTDHandler)
- */
- public void setDTDHandler(final DTDHandler dtdHandler) {
- reader.setDTDHandler(dtdHandler);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#setEntityResolver(org.xml.sax.EntityResolver)
- */
- public void setEntityResolver(final EntityResolver entityResolver) {
- reader.setEntityResolver(entityResolver);
- }
-
- /**
- * Resolves entities against using the supplied URL as the base for relative URLs
- *
- * @param base The URL used to resolve relative URLs
- */
- public void setEntityBaseUrl(final URL base) {
- reader.setEntityResolver(new EntityResolver() {
- public InputSource resolveEntity(final String publicId, final String systemId) throws IOException {
- return new InputSource(new URL(base, systemId).openStream());
- }
- });
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#setErrorHandler(org.xml.sax.ErrorHandler)
- */
- public void setErrorHandler(final ErrorHandler errorHandler) {
- reader.setErrorHandler(errorHandler);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean)
- */
- public void setFeature(final String uri, final boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {
- reader.setFeature(uri, value);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.XMLReader#setProperty(java.lang.String, java.lang.Object)
- */
- public void setProperty(final String uri, final Object value) throws SAXNotRecognizedException, SAXNotSupportedException {
- reader.setProperty(uri, value);
- }
-
- // ContentHandler interface
- //-------------------------------------------------------------------------
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#startDocument()
- */
- public void startDocument() throws SAXException {
- currentNode = null;
- charBuffer.setLength(0);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.helpers.DefaultHandler#startPrefixMapping(java.lang.String, java.lang.String)
- */
- public void startPrefixMapping(final String tag, final String uri) throws SAXException {
- if (namespaceAware) namespaceTagHints.put(tag, uri);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
- */
- public void startElement(final String namespaceURI, final String localName, final String qName, final Attributes atts) throws SAXException {
- addCdata();
-
- final Map<String, String> attributes = new NamespaceAwareHashMap();
- final Map<String, String> attributeNamespaces = new HashMap<String, String>();
-
- for (int i = atts.getLength() - 1; i != -1; i--) {
- if (atts.getURI(i).length() == 0) {
- attributes.put(atts.getQName(i), atts.getValue(i));
- } else {
- String key = new QName(atts.getURI(i), atts.getLocalName(i)).toString();
- attributes.put(key, atts.getValue(i));
- attributeNamespaces.put(key, atts.getURI(i));
- }
- }
-
- final Node newElement;
-
- if (namespaceURI.length() == 0) {
- newElement = new Node(currentNode, qName, attributes, attributeNamespaces, namespaceURI);
- } else {
- newElement = new Node(currentNode, localName, attributes, attributeNamespaces, namespaceURI);
- }
-
- if (currentNode != null) {
- currentNode.addChild(newElement);
- }
-
- stack.push(currentNode);
- currentNode = newElement;
- }
-
- public void ignorableWhitespace(char buffer[], int start, int len) throws SAXException {
- if (keepIgnorableWhitespace) characters(buffer, start, len);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#characters(char[], int, int)
- */
- public void characters(final char[] ch, final int start, final int length) throws SAXException {
- charBuffer.append(ch, start, length);
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
- */
- public void endElement(final String namespaceURI, final String localName, final String qName) throws SAXException {
- addCdata();
- Node oldCurrentNode = stack.pop();
- if (oldCurrentNode != null) {
- currentNode = oldCurrentNode;
- }
- }
-
- /* (non-Javadoc)
- * @see org.xml.sax.ContentHandler#endDocument()
- */
- public void endDocument() throws SAXException {
- }
-
- private void addCdata() {
- if (charBuffer.length() != 0) {
- //
- // This element is preceded by CDATA if keepIgnorableWhitespace is false (the default setting) and
- // it's not whitespace add it to the body
- // Note that, according to the XML spec, we should preserve the CDATA if it's all whitespace
- // but for the sort of work I'm doing ignoring the whitespace is preferable
- //
- final String cdata = charBuffer.toString();
- charBuffer.setLength(0);
- if (keepIgnorableWhitespace || cdata.trim().length() != 0) {
- currentNode.addChild(cdata);
- }
- }
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/XmlUtil.java b/subprojects/groovy-xml/src/main/java/groovy/util/XmlUtil.java
deleted file mode 100644
index 0443ca0..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/XmlUtil.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util;
-
-import groovy.lang.Writable;
-import groovy.util.slurpersupport.GPathResult;
-import org.codehaus.groovy.runtime.InvokerHelper;
-
-import java.io.OutputStream;
-import java.io.Writer;
-
-/**
- * Used for pretty printing XML content and other XML related utilities.
- */
-@Deprecated
-public class XmlUtil {
- /**
- * Return a pretty version of the GPathResult.
- *
- * @param node a GPathResult to serialize to a String
- * @return the pretty String representation of the GPathResult
- */
- @Deprecated
- public static String serialize(GPathResult node) {
- return groovy.xml.XmlUtil.serialize(asString(node));
- }
-
- /**
- * Write a pretty version of the GPathResult to the OutputStream.
- *
- * @param node a GPathResult to serialize
- * @param os the OutputStream to write to
- */
- @Deprecated
- public static void serialize(GPathResult node, OutputStream os) {
- groovy.xml.XmlUtil.serialize(asString(node), os);
- }
-
- /**
- * Write a pretty version of the GPathResult to the Writer.
- *
- * @param node a GPathResult to serialize
- * @param w the Writer to write to
- */
- @Deprecated
- public static void serialize(GPathResult node, Writer w) {
- groovy.xml.XmlUtil.serialize(asString(node), w);
- }
-
- private static String asString(GPathResult node) {
- // little bit of hackery to avoid Groovy dependency in this file
- try {
- Object builder = Class.forName("groovy.xml.StreamingMarkupBuilder").getDeclaredConstructor().newInstance();
- InvokerHelper.setProperty(builder, "encoding", "UTF-8");
- Writable w = (Writable) InvokerHelper.invokeMethod(builder, "bindNode", node);
- return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + w.toString();
- } catch (Exception e) {
- return "Couldn't convert node to string because: " + e.getMessage();
- }
- }
-
-}
\ No newline at end of file
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/Attribute.java b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/Attribute.java
deleted file mode 100644
index d8a3e20..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/Attribute.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util.slurpersupport;
-
-import groovy.lang.Closure;
-import groovy.lang.GroovyObject;
-import groovy.lang.GroovyRuntimeException;
-import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Iterator;
-import java.util.Map;
-
-/**
- * Lazy evaluated representation of a node attribute.
- */
-@Deprecated
-public class Attribute extends GPathResult {
- private final String value;
-
- /**
- * @param name of the attribute
- * @param value of the attribute
- * @param parent the GPathResult prior to the application of the expression creating this GPathResult
- * @param namespacePrefix the namespace prefix if any
- * @param namespaceTagHints the known tag to namespace mappings
- */
- public Attribute(final String name, final String value, final GPathResult parent, final String namespacePrefix, final Map<String, String> namespaceTagHints) {
- super(parent, name, namespacePrefix, namespaceTagHints);
- this.value = value;
- }
-
- public String name() {
- // this name contains @name we need to return name
- return this.name.substring(1);
- }
-
- /**
- * Returns the size of this Attribute, which is always <code>1</code>.
- * @return <code>1</code>
- */
- public int size() {
- return 1;
- }
-
- /**
- * Returns the value of this Attribute.
- * @return the value of this Attribute
- */
- public String text() {
- return this.value;
- }
-
- /**
- * Returns the URI of the namespace of this Attribute.
- * @return the namespace of this Attribute
- */
- public String namespaceURI() {
- if (namespacePrefix == null || namespacePrefix.isEmpty()) return "";
- String uri = namespaceTagHints.get(namespacePrefix);
- return uri == null ? "" : uri;
- }
-
- /**
- * Throws a <code>GroovyRuntimeException</code>, because this method is not implemented yet.
- */
- public GPathResult parents() {
- // TODO Auto-generated method stub
- throw new GroovyRuntimeException("parents() not implemented yet");
- }
-
- /**
- * Throws a <code>GroovyRuntimeException</code>, because an attribute can have no children.
- */
- public Iterator childNodes() {
- throw new GroovyRuntimeException("can't call childNodes() in the attribute " + this.name);
- }
-
- public Iterator iterator() {
- return nodeIterator();
- }
-
- public GPathResult find(final Closure closure) {
- if (DefaultTypeTransformation.castToBoolean(closure.call(new Object[]{this}))) {
- return this;
- } else {
- return new NoChildren(this, "", this.namespaceTagHints);
- }
- }
-
- public GPathResult findAll(final Closure closure) {
- return find(closure);
- }
-
- public Iterator nodeIterator() {
- return createIterator(this);
- }
-
- public Writer writeTo(final Writer out) throws IOException {
- out.write(this.value);
- return out;
- }
-
- public void build(final GroovyObject builder) {
- builder.getProperty("mkp");
- builder.invokeMethod("yield", new Object[]{this.value});
- }
-
- /**
- * NOP, because an attribute does not have any Node to replace.
- */
- protected void replaceNode(final Closure newValue) {
- }
-
- /**
- * NOP, because an attribute does not have a Body.
- */
- protected void replaceBody(final Object newValue) {
- }
-
- /**
- * NOP, because an node can not be appended to an attribute.
- */
- protected void appendNode(final Object newValue) {
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/Attributes.java b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/Attributes.java
deleted file mode 100644
index 8664dff..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/Attributes.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util.slurpersupport;
-
-import groovy.lang.Closure;
-import groovy.lang.GroovyObject;
-import groovy.lang.GroovyRuntimeException;
-import groovy.xml.QName;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Lazy evaluated representation of a node's attributes.
- */
-@Deprecated
-public class Attributes extends NodeChildren {
- final String attributeName;
-
- /**
- * @param parent the GPathResult prior to the application of the expression creating this GPathResult
- * @param name if the GPathResult corresponds to something with a name, e.g. a node
- * @param namespacePrefix the namespace prefix if any
- * @param namespaceTagHints the known tag to namespace mappings
- */
- public Attributes(final GPathResult parent, final String name, final String namespacePrefix, final Map<String, String> namespaceTagHints) {
- super(parent, name, namespacePrefix, namespaceTagHints);
- this.attributeName = this.name.substring(1);
- }
-
- /**
- * @param parent the GPathResult prior to the application of the expression creating this GPathResult
- * @param name if the GPathResult corresponds to something with a name, e.g. a node
- * @param namespaceTagHints the known tag to namespace mappings
- */
- public Attributes(final GPathResult parent, final String name, final Map<String, String> namespaceTagHints) {
- this(parent, name, "*", namespaceTagHints);
- }
-
- public String name() {
- // this name contains @name we need to return name
- return this.name.substring(1);
- }
-
- /**
- * Throws a <code>GroovyRuntimeException</code>, because attributes can have no children.
- */
- public Iterator childNodes() {
- throw new GroovyRuntimeException("Can't get the child nodes on a GPath expression selecting attributes: ...." + this.parent.name() + "." + name() + ".childNodes()");
- }
-
- public Iterator iterator() {
- return new NodeIterator(nodeIterator()) {
- protected Object getNextNode(final Iterator iter) {
- while (iter.hasNext()) {
- final Object next = iter.next();
- if (next instanceof Attribute) {
- return next;
- } else {
- String attributeKey = Attributes.this.attributeName;
- if (Attributes.this.namespacePrefix != null &&
- !"*".equals(Attributes.this.namespacePrefix) &&
- Attributes.this.namespacePrefix.length() > 0) {
- attributeKey = new QName(Attributes.this.lookupNamespace(Attributes.this.namespacePrefix), Attributes.this.attributeName).toString();
- }
- final String value = (String) ((Node) next).attributes().get(attributeKey);
- if (value != null) {
- return new Attribute(Attributes.this.name,
- value,
- new NodeChild((Node) next, Attributes.this.parent.parent, "", Attributes.this.namespaceTagHints),
- (Attributes.this.namespacePrefix == null || "*".equals(Attributes.this.namespacePrefix)) ? "" : Attributes.this.namespacePrefix,
- Attributes.this.namespaceTagHints);
- }
- }
- }
- return null;
- }
- };
- }
-
- public Iterator nodeIterator() {
- return this.parent.nodeIterator();
- }
-
- public GPathResult parents() {
- return super.parents();
- }
-
- public String text() {
- final StringBuilder sb = new StringBuilder();
- final Iterator iter = iterator();
- while (iter.hasNext()) {
- sb.append(iter.next());
- }
- return sb.toString();
- }
-
- public List list() {
- final Iterator iter = iterator();
- final List result = new ArrayList();
- while (iter.hasNext()) {
- result.add(iter.next());
- }
- return result;
- }
-
- public GPathResult findAll(final Closure closure) {
- return new FilteredAttributes(this, closure, this.namespaceTagHints);
- }
-
- public Writer writeTo(final Writer out) throws IOException {
- out.write(text());
- return out;
- }
-
- public void build(final GroovyObject builder) {
- builder.getProperty("mkp");
- builder.invokeMethod("yield", new Object[]{text()});
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/FilteredAttributes.java b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/FilteredAttributes.java
deleted file mode 100644
index 56fbb1a..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/FilteredAttributes.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util.slurpersupport;
-
-import groovy.lang.Closure;
-import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
-
-import java.util.Iterator;
-import java.util.Map;
-
-/**
- * Lazy evaluated representation of a node's attributes filtered by a Closure.
- */
-@Deprecated
-public class FilteredAttributes extends Attributes {
- private final Closure closure;
-
- /**
- * @param parent the GPathResult prior to the application of the expression creating this GPathResult
- * @param closure the Closure to use to filter the attributes
- * @param namespaceTagHints the known tag to namespace mappings
- */
- public FilteredAttributes(final GPathResult parent, final Closure closure, final Map<String, String> namespaceTagHints) {
- super(parent, parent.name, namespaceTagHints);
- this.closure = closure;
- }
-
- public Iterator nodeIterator() {
- return new NodeIterator(this.parent.iterator())
- {
- protected Object getNextNode(final Iterator iter) {
- while (iter.hasNext()) {
- final Object node = iter.next();
- if (DefaultTypeTransformation.castToBoolean(FilteredAttributes.this.closure.call(new Object[]{node}))) {
- return node;
- }
- }
- return null;
- }
- };
- }
-
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/FilteredNodeChildren.java b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/FilteredNodeChildren.java
deleted file mode 100644
index 0459427..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/FilteredNodeChildren.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util.slurpersupport;
-
-import groovy.lang.Closure;
-import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
-
-import java.util.Iterator;
-import java.util.Map;
-
-/**
- * Lazy evaluated representation of child nodes filtered by a Closure.
- */
-@Deprecated
-public class FilteredNodeChildren extends NodeChildren {
- private final Closure closure;
-
- /**
- * @param parent the GPathResult prior to the application of the expression creating this GPathResult
- * @param closure the Closure to use to filter the nodes
- * @param namespaceTagHints the known tag to namespace mappings
- */
- public FilteredNodeChildren(final GPathResult parent, final Closure closure, final Map<String, String> namespaceTagHints) {
- super(parent, parent.name, namespaceTagHints);
- this.closure = closure;
- }
-
- public GPathResult pop() {
- return this.parent.parent;
- }
-
- public Iterator nodeIterator() {
- return new NodeIterator(this.parent.nodeIterator()) {
- protected Object getNextNode(final Iterator iter) {
- while (iter.hasNext()) {
- final Object node = iter.next();
- if (closureYieldsTrueForNode(new NodeChild((Node) node, FilteredNodeChildren.this.parent, FilteredNodeChildren.this.namespaceTagHints))) {
- return node;
- }
- }
- return null;
- }
- };
- }
-
- private boolean closureYieldsTrueForNode(Object childNode) {
- return DefaultTypeTransformation.castToBoolean(FilteredNodeChildren.this.closure.call(new Object[]{childNode}));
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/GPathResult.java b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/GPathResult.java
deleted file mode 100644
index e4f8438..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/GPathResult.java
+++ /dev/null
@@ -1,711 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util.slurpersupport;
-
-import groovy.lang.Buildable;
-import groovy.lang.Closure;
-import groovy.lang.DelegatingMetaClass;
-import groovy.lang.GString;
-import groovy.lang.GroovyObject;
-import groovy.lang.GroovyObjectSupport;
-import groovy.lang.IntRange;
-import groovy.lang.MetaClass;
-import groovy.lang.Writable;
-import org.codehaus.groovy.runtime.DefaultGroovyMethods;
-import org.codehaus.groovy.runtime.ResourceGroovyMethods;
-import org.codehaus.groovy.runtime.StringGroovyMethods;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Stack;
-
-/**
- * Base class for representing lazy evaluated GPath expressions.
- */
-@Deprecated
-public abstract class GPathResult extends GroovyObjectSupport implements Writable, Buildable, Iterable {
- protected final GPathResult parent;
- protected final String name;
- protected final String namespacePrefix;
- protected final Map namespaceMap = new HashMap();
- protected final Map<String, String> namespaceTagHints;
-
- /**
- * Creates a new GPathResult named <code>name</code> with the parent <code>parent</code>,
- * the namespacePrefix <code>namespacePrefix</code> and the namespaceTagHints specified in
- * the <code>namespaceTagHints</code> Map.
- *
- * @param parent the GPathResult prior to the application of the expression creating this GPathResult
- * @param name if the GPathResult corresponds to something with a name, e.g. a node
- * @param namespacePrefix the namespace prefix if any
- * @param namespaceTagHints the known tag to namespace mappings
- */
- public GPathResult(final GPathResult parent, final String name, final String namespacePrefix, final Map<String, String> namespaceTagHints) {
- if (parent == null) {
- // we are the top of the tree
- this.parent = this;
- this.namespaceMap.put("xml", "http://www.w3.org/XML/1998/namespace"); // The XML namespace is always defined
- } else {
- this.parent = parent;
- this.namespaceMap.putAll(parent.namespaceMap);
- }
- this.name = name;
- this.namespacePrefix = namespacePrefix;
- this.namespaceTagHints = namespaceTagHints;
-
- setMetaClass(getMetaClass()); // wrap the standard MetaClass with the delegate
- }
-
- /**
- * Replaces the MetaClass of this GPathResult.
- *
- * @param metaClass the new MetaClass
- */
- @Override
- public void setMetaClass(final MetaClass metaClass) {
- final MetaClass newMetaClass = new DelegatingMetaClass(metaClass) {
- @Override
- public Object getAttribute(final Object object, final String attribute) {
- return GPathResult.this.getProperty("@" + attribute);
- }
-
- @Override
- public void setAttribute(final Object object, final String attribute, final Object newValue) {
- GPathResult.this.setProperty("@" + attribute, newValue);
- }
- };
- super.setMetaClass(newMetaClass);
- }
-
- /**
- * Returns the specified Property of this GPathResult.
- * <p>
- * Realizes the follow shortcuts:
- * <ul>
- * <li><code>'..'</code> for <code>parent()</code>
- * <li><code>'*'</code> for <code>children()</code>
- * <li><code>'**'</code> for <code>depthFirst()</code>
- * <li><code>'@'</code> for attribute access
- * </ul>
- * @param property the Property to fetch
- */
- public Object getProperty(final String property) {
- if ("..".equals(property)) {
- return parent();
- } else if ("*".equals(property)) {
- return children();
- } else if ("**".equals(property)) {
- return depthFirst();
- } else if (property.startsWith("@")) {
- if (property.contains(":") && !this.namespaceTagHints.isEmpty()) {
- final int i = property.indexOf(":");
- return new Attributes(this, "@" + property.substring(i + 1), property.substring(1, i), this.namespaceTagHints);
- } else {
- return new Attributes(this, property, this.namespaceTagHints);
- }
- } else {
- if (property.contains(":") && !this.namespaceTagHints.isEmpty()) {
- final int i = property.indexOf(":");
- return new NodeChildren(this, property.substring(i + 1), property.substring(0, i), this.namespaceTagHints);
- } else {
- return new NodeChildren(this, property, this.namespaceTagHints);
- }
- }
- }
-
- /**
- * Replaces the specified property of this GPathResult with a new value.
- *
- * @param property the property of this GPathResult to replace
- * @param newValue the new value of the property
- */
- public void setProperty(final String property, final Object newValue) {
- if (property.startsWith("@")) {
- if (newValue instanceof String || newValue instanceof GString) {
- final Iterator iter = iterator();
-
- while (iter.hasNext()) {
- final NodeChild child = (NodeChild) iter.next();
-
- child.attributes().put(property.substring(1), newValue);
- }
- }
- } else {
- final GPathResult result = new NodeChildren(this, property, this.namespaceTagHints);
-
- if (newValue instanceof Map) {
- for (Object o : ((Map) newValue).entrySet()) {
- final Map.Entry entry = (Map.Entry) o;
- result.setProperty("@" + entry.getKey(), entry.getValue());
- }
- } else {
- if (newValue instanceof Closure) {
- result.replaceNode((Closure) newValue);
- } else {
- result.replaceBody(newValue);
- }
- }
- }
- }
-
- /**
- * Overloads the left shift operator to provide an easy way to
- * lazily append Objects to this GPathResult.
- *
- * @param newValue the Object to append
- * @return <code>this</code>
- */
- public Object leftShift(final Object newValue) {
- appendNode(newValue);
- return this;
- }
-
- /**
- * Lazily adds the specified Object to this GPathResult.
- *
- * @param newValue the Object to add
- * @return <code>this</code>
- */
- public Object plus(final Object newValue) {
- this.replaceNode(new Closure(this) {
- public void doCall(Object[] args) {
- final GroovyObject delegate = (GroovyObject) getDelegate();
- delegate.getProperty("mkp");
- delegate.invokeMethod("yield", args);
- delegate.getProperty("mkp");
- delegate.invokeMethod("yield", new Object[]{newValue});
- }
- });
-
- return this;
- }
-
- protected abstract void replaceNode(Closure newValue);
-
- protected abstract void replaceBody(Object newValue);
-
- protected abstract void appendNode(Object newValue);
-
- /**
- * Returns the name of this GPathResult.
- *
- * @return the name of this GPathResult
- */
- public String name() {
- return this.name;
- }
-
- /**
- * Returns the parent of this GPathResult. If this GPathResult has no parent the GPathResult itself is returned.
- * This is no navigation in the XML tree. It is backtracking on the GPath expression chain.
- * It is the behavior of parent() prior to 2.2.0.
- * Backtracking on '..' actually goes down one level in the tree again.
- * find() and findAll() are popped along with the level they have been applied to.
- *
- * @return the parent or <code>this</code>
- */
- public GPathResult pop() {
- return this.parent;
- }
-
- /**
- * Returns as GPathResult with the parent nodes of the current GPathResult
- *
- * @return the parents GPathResult or <code>this</code> for the root
- */
- public GPathResult parent() {
- return new NodeParents(this, this.namespaceTagHints);
- }
-
- /**
- * Returns the children of this GPathResult as a GPathResult object.
- *
- * @return the children of this GPathResult
- */
- public GPathResult children() {
- return new NodeChildren(this, this.namespaceTagHints);
- }
-
- /**
- * Returns the namespace mapped to the specified prefix.
- *
- * @param prefix the prefix lookup
- * @return the namespace of the prefix
- */
- public String lookupNamespace(final String prefix) {
- Object namespace = namespaceMap.get(prefix);
- if (namespace != null) {
- return namespace.toString();
- }
- return this.namespaceTagHints.isEmpty() ? prefix : this.namespaceTagHints.get(prefix);
- }
-
- /**
- * Returns the text of this GPathResult.
- *
- * @return the GPathResult, converted to a <code>String</code>
- */
- public String toString() {
- return text();
- }
-
- /**
- * Converts the text of this GPathResult to a Integer object.
- *
- * @return the GPathResult, converted to a <code>Integer</code>
- */
- public Integer toInteger() {
- if(textIsEmptyOrNull()){
- return null;
- }
- return StringGroovyMethods.toInteger((CharSequence)text());
- }
-
- /**
- * Converts the text of this GPathResult to a Long object.
- *
- * @return the GPathResult, converted to a <code>Long</code>
- */
- public Long toLong() {
- if(textIsEmptyOrNull()){
- return null;
- }
- return StringGroovyMethods.toLong((CharSequence)text());
- }
-
- /**
- * Converts the text of this GPathResult to a Float object.
- *
- * @return the GPathResult, converted to a <code>Float</code>
- */
- public Float toFloat() {
- if(textIsEmptyOrNull()){
- return null;
- }
- return StringGroovyMethods.toFloat((CharSequence)text());
- }
-
- /**
- * Converts the text of this GPathResult to a Double object.
- *
- * @return the GPathResult, converted to a <code>Double</code>
- */
- public Double toDouble() {
- if(textIsEmptyOrNull()){
- return null;
- }
- return StringGroovyMethods.toDouble((CharSequence)text());
- }
-
- /**
- * Converts the text of this GPathResult to a BigDecimal object.
- *
- * @return the GPathResult, converted to a <code>BigDecimal</code>
- */
- public BigDecimal toBigDecimal() {
- if(textIsEmptyOrNull()){
- return null;
- }
- return StringGroovyMethods.toBigDecimal((CharSequence)text());
- }
-
- /**
- * Converts the text of this GPathResult to a BigInteger object.
- *
- * @return the GPathResult, converted to a <code>BigInteger</code>
- */
- public BigInteger toBigInteger() {
- if(textIsEmptyOrNull()){
- return null;
- }
- return StringGroovyMethods.toBigInteger((CharSequence)text());
- }
-
- private boolean textIsEmptyOrNull() {
- String t = text();
- return null == t || 0 == t.length();
- }
-
- /**
- * Converts the text of this GPathResult to a URL object.
- *
- * @return the GPathResult, converted to a <code>URL</code>
- */
- public URL toURL() throws MalformedURLException {
- return ResourceGroovyMethods.toURL((CharSequence)text());
- }
-
- /**
- * Converts the text of this GPathResult to a URI object.
- *
- * @return the GPathResult, converted to a <code>URI</code>
- */
- public URI toURI() throws URISyntaxException {
- return ResourceGroovyMethods.toURI((CharSequence)text());
- }
-
- /**
- * Converts the text of this GPathResult to a Boolean object.
- *
- * @return the GPathResult, converted to a <code>Boolean</code>
- */
- public Boolean toBoolean() {
- return StringGroovyMethods.toBoolean(text());
- }
-
- /**
- * Adds the specified map of prefix to namespace mappings to this GPathResult.
- * Already existing prefixes are overwritten.
- *
- * @param newNamespaceMapping the mappings to add
- * @return <code>this</code>
- */
- public GPathResult declareNamespace(final Map newNamespaceMapping) {
- this.namespaceMap.putAll(newNamespaceMapping);
- return this;
- }
-
- @Override
- public int hashCode() {
- return text().hashCode();
- }
-
- @Override
- public boolean equals(Object obj) {
- if (null == obj) {
- return false;
- }
-
- return text().equals(obj.toString());
- }
-
- /**
- * Supports the subscript operator for a GPathResult.
- * <pre class="groovyTestCase">
- * import groovy.util.slurpersupport.*
- * def text = """
- * <characterList>
- * <character/>
- * <character>
- * <name>Gromit</name>
- * </character>
- * </characterList>"""
- *
- * GPathResult characterList = new XmlSlurper().parseText(text)
- *
- * assert characterList.character[1].name == 'Gromit'
- * </pre>
- * @param index an index
- * @return the value at the given index
- */
- public Object getAt(final int index) {
- if (index < 0) {
- // calculate whole list in this case
- // recommend avoiding -ve's as this is obviously not as efficient
- List list = list();
- int adjustedIndex = index + list.size();
- if (adjustedIndex >= 0 && adjustedIndex < list.size())
- return list.get(adjustedIndex);
- } else {
- final Iterator iter = iterator();
- int count = 0;
-
- while (iter.hasNext()) {
- if (count++ == index) {
- return iter.next();
- } else {
- iter.next();
- }
- }
- }
-
- return new NoChildren(this, this.name, this.namespaceTagHints);
- }
-
- /**
- * Supports the range subscript operator for a GPathResult.
- * <pre class="groovyTestCase">
- * import groovy.util.slurpersupport.*
- * def text = """
- * <characterList>
- * <character>Wallace</character>
- * <character>Gromit</character>
- * <character>Shaun</character>
- * </characterList>"""
- *
- * GPathResult characterList = new XmlSlurper().parseText(text)
- *
- * assert characterList.character[1..2].join(',') == 'Gromit,Shaun'
- * </pre>
- * @param range a Range indicating the items to get
- * @return a new list based on range borders
- */
- public Object getAt(final IntRange range) {
- return DefaultGroovyMethods.getAt(list(), range);
- }
-
- /**
- * A helper method to allow GPathResults to work with subscript operators
- * @param index an index
- * @param newValue the value to put at the given index
- */
- public void putAt(final int index, final Object newValue) {
- final GPathResult result = (GPathResult)getAt(index);
- if (newValue instanceof Closure) {
- result.replaceNode((Closure)newValue);
- } else {
- result.replaceBody(newValue);
- }
- }
-
- /**
- * Provides an Iterator over all the nodes of this GPathResult using a depth-first traversal.
- *
- * @return the <code>Iterator</code> of (depth-first) ordered GPathResults
- */
- public Iterator depthFirst() {
- return new Iterator() {
- private final List list = new LinkedList();
- private final Stack stack = new Stack();
- private Iterator iter = iterator();
- private GPathResult next = getNextByDepth();
-
- public boolean hasNext() {
- return this.next != null;
- }
-
- public Object next() {
- try {
- return this.next;
- } finally {
- this.next = getNextByDepth();
- }
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- private GPathResult getNextByDepth() {
- while (this.iter.hasNext()) {
- final GPathResult node = (GPathResult) this.iter.next();
- this.list.add(node);
- this.stack.push(this.iter);
- this.iter = node.children().iterator();
- }
-
- if (this.list.isEmpty()) {
- return null;
- } else {
- GPathResult result = (GPathResult) this.list.get(0);
- this.list.remove(0);
- this.iter = (Iterator) this.stack.pop();
- return result;
- }
- }
- };
- }
-
- /**
- * Provides an Iterator over all the nodes of this GPathResult using a breadth-first traversal.
- *
- * @return the <code>Iterator</code> of (breadth-first) ordered GPathResults
- */
- public Iterator breadthFirst() {
- return new Iterator() {
- private final List list = new LinkedList();
- private Iterator iter = iterator();
- private GPathResult next = getNextByBreadth();
-
- public boolean hasNext() {
- return this.next != null;
- }
-
- public Object next() {
- try {
- return this.next;
- } finally {
- this.next = getNextByBreadth();
- }
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- private GPathResult getNextByBreadth() {
- List children = new ArrayList();
- while (this.iter.hasNext() || !children.isEmpty()) {
- if (this.iter.hasNext()) {
- final GPathResult node = (GPathResult) this.iter.next();
- this.list.add(node);
- this.list.add(this.iter);
- children.add(node.children());
- } else {
- List nextLevel = new ArrayList();
- for (Object child : children) {
- GPathResult next = (GPathResult) child;
- Iterator iterator = next.iterator();
- while (iterator.hasNext()) {
- nextLevel.add(iterator.next());
- }
- }
- this.iter = nextLevel.iterator();
- children = new ArrayList();
- }
- }
- if (this.list.isEmpty()) {
- return null;
- } else {
- GPathResult result = (GPathResult) this.list.get(0);
- this.list.remove(0);
- this.iter = (Iterator) this.list.get(0);
- this.list.remove(0);
- return result;
- }
- }
- };
- }
-
- /**
- * Creates a list of objects representing this GPathResult.
- *
- * @return a list representing of this GPathResult
- */
- public List list() {
- final Iterator iter = nodeIterator();
- final List result = new LinkedList();
- while (iter.hasNext()) {
- result.add(new NodeChild((Node) iter.next(), this.parent, this.namespacePrefix, this.namespaceTagHints));
- }
- return result;
- }
-
- /**
- * Returns true if the GPathResult is empty, i.e. if, and only if, <code>size()</code> is 0.
- *
- * @return true if the GPathResult is empty
- */
- public boolean isEmpty() {
- return size() == 0;
- }
-
- /**
- * Creates a Closure representing the body of this GPathResult.
- *
- * @return the body of this GPathResult, converted to a <code>Closure</code>
- */
- public Closure getBody() {
- return new Closure(this.parent,this) {
- public void doCall(Object[] args) {
- final GroovyObject delegate = (GroovyObject)getDelegate();
- final GPathResult thisObject = (GPathResult)getThisObject();
-
- Node node = (Node)thisObject.getAt(0);
- List children = node.children();
-
- for (Object child : children) {
- delegate.getProperty("mkp");
- if (child instanceof Node) {
- delegate.invokeMethod("yield", new Object[]{new NodeChild((Node) child, thisObject, "*", null)});
- } else {
- delegate.invokeMethod("yield", new Object[]{child});
- }
- }
- }
- };
- }
-
- /**
- * Returns the size of this GPathResult.
- * @return the size of this GPathResult
- */
- public abstract int size();
-
- /**
- * Returns the text of this GPathResult as a <code>String</code>.
- * @return the text of this GPathResult
- */
- public abstract String text();
-
- /**
- * Returns the parents of this GPathResult as a <code>GPathResult</code>.
- * Warning: The subclasses of this package do not implement this method yet.
- * @return the parents of this GPathResult
- */
- public abstract GPathResult parents();
-
- /**
- * Returns an iterator over the child nodes of this GPathResult.
- * @return an iterator over the child nodes of this GPathResult
- */
- public abstract Iterator childNodes();
-
- public abstract Iterator iterator();
-
- /**
- * Returns the first child of this GPathResult matching the condition(s)
- * specified in the passed closure.
- * @param closure a closure to filters the children of this GPathResult
- * @return the first child matching the closure
- */
- public abstract GPathResult find(Closure closure);
-
- /**
- * Returns the children of this GPathResult matching the condition(s)
- * specified in the passed closure.
- * @param closure a closure to filters the children of this GPathResult
- * @return the children matching the closure
- */
- public abstract GPathResult findAll(Closure closure);
-
- public abstract Iterator nodeIterator();
-
- protected Iterator createIterator(final Object obj) {
- return new Iterator() {
- private boolean hasNext = true;
-
- public boolean hasNext() {
- return this.hasNext;
- }
-
- public Object next() {
- try {
- return (this.hasNext) ? obj : null;
- } finally {
- this.hasNext = false;
- }
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
- };
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NamespaceAwareHashMap.java b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NamespaceAwareHashMap.java
deleted file mode 100644
index 7199765..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NamespaceAwareHashMap.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util.slurpersupport;
-
-import groovy.xml.QName;
-
-import java.util.HashMap;
-import java.util.Map;
-
-@Deprecated
-public class NamespaceAwareHashMap extends HashMap<String, String> {
- public void setNamespaceTagHints(Map namespaceTagHints) {
- this.namespaceTagHints = namespaceTagHints;
- }
-
- private Map namespaceTagHints = null;
-
- public Map getNamespaceTagHints() {
- return namespaceTagHints;
- }
-
- @Override
- public String get(Object key) {
- key = adjustForNamespaceIfNeeded(key);
- return super.get(key);
- }
-
- @Override
- public String remove(Object key) {
- key = adjustForNamespaceIfNeeded(key).toString();
- return super.remove(key);
- }
-
- @Override
- public boolean containsKey(Object key) {
- key = adjustForNamespaceIfNeeded(key).toString();
- return super.containsKey(key);
- }
-
- @Override
- public String put(String key, String value) {
- key = adjustForNamespaceIfNeeded(key).toString();
- return super.put(key, value);
- }
-
- @Override
- public void putAll(Map<? extends String, ? extends String> m) {
- for (Object o : m.entrySet())
- if (o instanceof Map.Entry) {
- Map.Entry<String, String> e = (Map.Entry) o;
- put(e.getKey(), e.getValue());
- }
- }
-
- private Object adjustForNamespaceIfNeeded(Object key) {
- String keyString = key.toString();
- if (keyString.contains("{") || namespaceTagHints == null || namespaceTagHints.isEmpty() || !keyString.contains(":")) {
- return key;
- }
- final int i = keyString.indexOf(":");
- return new QName(namespaceTagHints.get(keyString.substring(0, i)).toString(), keyString.substring(i + 1)).toString();
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NoChildren.java b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NoChildren.java
deleted file mode 100644
index 8f6de18..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NoChildren.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util.slurpersupport;
-
-import groovy.lang.Closure;
-import groovy.lang.GroovyObject;
-import groovy.lang.GroovyRuntimeException;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Iterator;
-import java.util.Map;
-
-/**
- * Lazy evaluated representation of a GPath expression returning no children.
- *
- * As this class represents a GPath expression with no results, all methods
- * are either NOPs or return an empty result.
- */
-@Deprecated
-public class NoChildren extends GPathResult {
-
- /**
- * @param parent the GPathResult prior to the application of the expression creating this GPathResult
- * @param name if the GPathResult corresponds to something with a name, e.g. a node
- * @param namespaceTagHints the known tag to namespace mappings
- */
- public NoChildren(final GPathResult parent, final String name, final Map<String, String> namespaceTagHints) {
- super(parent, name, "*", namespaceTagHints);
- }
-
- /**
- * Returns <code>0</code>.
- * @return <code>0</code>
- */
- public int size() {
- return 0;
- }
-
- /**
- * Returns an empty <code>String</code>.
- * @return an empty <code>String</code>
- */
- public String text() {
- return "";
- }
-
- /**
- * Throws a <code>GroovyRuntimeException</code>, because it is not implemented yet.
- */
- public GPathResult parents() {
- // TODO Auto-generated method stub
- throw new GroovyRuntimeException("parents() not implemented yet");
- }
-
- /**
- * Returns an empty <code>Iterator</code>.
- * @return an empty <code>Iterator</code>
- */
- public Iterator childNodes() {
- return iterator();
- }
-
- /**
- * Returns an empty <code>Iterator</code>.
- * @return an empty <code>Iterator</code>
- */
- public Iterator iterator() {
- return new Iterator() {
- public boolean hasNext() {
- return false;
- }
-
- public Object next() {
- return null;
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
- };
- }
-
- /**
- * Returns <code>this</code>.
- * @return <code>this</code>
- */
- public GPathResult find(final Closure closure) {
- return this;
- }
-
- /**
- * Returns <code>this</code>.
- * @return <code>this</code>
- */
- public GPathResult findAll(final Closure closure) {
- return this;
- }
-
- /**
- * Returns an empty iterator.
- * @return an empty iterator
- */
- public Iterator nodeIterator() {
- return iterator();
- }
-
- /**
- * Does not write any output, just returns the writer.
- *
- * @return the <code>Writer</code> which was passed in
- */
- public Writer writeTo(final Writer out) throws IOException {
- return out;
- }
-
- /**
- * NOP
- */
- public void build(final GroovyObject builder) {
- }
-
- /**
- * NOP
- */
- protected void replaceNode(final Closure newValue) {
- // No elements match GPath expression - do nothing
- }
-
- /**
- * NOP
- */
- protected void replaceBody(final Object newValue) {
- // No elements match GPath expression - do nothing
- }
-
- /**
- * NOP
- */
- protected void appendNode(final Object newValue) {
- // TODO consider creating an element for this
- }
-
- /**
- * Returns <code>false</code>.
- * @return <code>false</code>
- */
- public boolean asBoolean() {
- return false;
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/Node.java b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/Node.java
deleted file mode 100644
index 596d3bb..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/Node.java
+++ /dev/null
@@ -1,339 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util.slurpersupport;
-
-import groovy.lang.Buildable;
-import groovy.lang.Closure;
-import groovy.lang.GroovyObject;
-import groovy.lang.Writable;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Stack;
-
-/**
- * Represents a node.
- */
-@Deprecated
-public class Node implements Writable {
- private final String name;
- private final Map attributes;
- private final Map attributeNamespaces;
- private final String namespaceURI;
- private final List children = new LinkedList();
- private final Stack replacementNodeStack = new Stack();
- private final Node parent;
-
- /**
- * @param parent the parent node
- * @param name the name for the node
- * @param attributes the attributes for the node
- * @param attributeNamespaces the namespace mappings for attributes
- * @param namespaceURI the namespace URI if any
- */
- public Node(final Node parent, final String name, final Map attributes, final Map attributeNamespaces, final String namespaceURI) {
- this.name = name;
- this.attributes = attributes;
- this.attributeNamespaces = attributeNamespaces;
- this.namespaceURI = namespaceURI;
- this.parent = parent;
- }
-
- /**
- * Returns the name of this Node.
- * @return the name of this Node
- */
- public String name() {
- return this.name;
- }
-
- /**
- * Returns the parent of this Node.
- * @return the parent of this Node
- */
- public Node parent() {
- return this.parent;
- }
-
- /**
- * Returns the URI of the namespace of this Node.
- * @return the namespace of this Node
- */
- public String namespaceURI() {
- return this.namespaceURI;
- }
-
- /**
- * Returns a map of the attributes of this Node.
- * @return a map of the attributes of this Node
- */
- public Map attributes() {
- return this.attributes;
- }
-
- /**
- * Returns a list of the children of this Node.
- * @return a list of the children of this Node
- */
- public List children() {
- return this.children;
- }
-
- /**
- * Adds an object as a new child to this Node.
- * @param child the object to add as a child
- */
- public void addChild(final Object child) {
- this.children.add(child);
- }
-
- public void replaceNode(final Closure replacementClosure, final GPathResult result) {
- this.replacementNodeStack.push(new ReplacementNode() {
- public void build(final GroovyObject builder, final Map namespaceMap, final Map<String, String> namespaceTagHints) {
- final Closure c = (Closure) replacementClosure.clone();
- Node.this.replacementNodeStack.pop(); // disable the replacement whilst the closure is being executed
- c.setDelegate(builder);
- c.call(new Object[]{result});
- Node.this.replacementNodeStack.push(this);
- }
- });
- }
-
- /**
- * Replaces the current body of this Node with the passed object.
- * @param newValue the new body
- */
- protected void replaceBody(final Object newValue) {
- this.children.clear();
- this.children.add(newValue);
- }
-
- protected void appendNode(final Object newValue, final GPathResult result) {
- if (newValue instanceof Closure) {
- this.children.add(new ReplacementNode() {
- public void build(final GroovyObject builder, final Map namespaceMap, final Map<String, String> namespaceTagHints) {
- final Closure c = (Closure) ((Closure) newValue).clone();
- c.setDelegate(builder);
- c.call(new Object[]{result});
- }
- });
- } else {
- this.children.add(newValue);
- }
- }
-
- /**
- * Returns a string containing the text of the children of this Node.
- * @return a string containing the text of the children of this Node
- */
- public String text() {
- final StringBuilder sb = new StringBuilder();
- for (Object child : this.children) {
- if (child instanceof Node) {
- sb.append(((Node) child).text());
- } else {
- sb.append(child);
- }
- }
- return sb.toString();
- }
-
- /**
- * Returns the list of any direct String nodes of this node.
- *
- * @return the list of String values from this node
- * @since 2.3.0
- */
- public List<String> localText() {
- final List<String> result = new ArrayList<String>();
- for (Object child : this.children) {
- if (!(child instanceof Node)) {
- result.add(child.toString());
- }
- }
- return result;
- }
-
- /**
- * Returns an iterator over the child nodes of this Node.
- * @return an iterator over the child nodes of this Node
- */
- public Iterator childNodes() {
- return new Iterator() {
- private final Iterator iter = Node.this.children.iterator();
- private Object nextElementNodes = getNextElementNodes();
-
- public boolean hasNext() {
- return this.nextElementNodes != null;
- }
-
- public Object next() {
- try {
- return this.nextElementNodes;
- } finally {
- this.nextElementNodes = getNextElementNodes();
- }
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- private Object getNextElementNodes() {
- while (iter.hasNext()) {
- final Object node = iter.next();
- if (node instanceof Node) {
- return node;
- }
- }
- return null;
- }
- };
- }
-
- public Writer writeTo(final Writer out) throws IOException {
- if (this.replacementNodeStack.empty()) {
- for (Object child : this.children) {
- if (child instanceof Writable) {
- ((Writable) child).writeTo(out);
- } else {
- out.write(child.toString());
- }
- }
- return out;
- } else {
- return ((Writable) this.replacementNodeStack.peek()).writeTo(out);
- }
- }
-
- public void build(final GroovyObject builder, final Map namespaceMap, final Map<String, String> namespaceTagHints) {
- if (this.replacementNodeStack.empty()) {
- final Closure rest = new Closure(null) {
- public Object doCall(final Object o) {
- buildChildren(builder, namespaceMap, namespaceTagHints);
- return null;
- }
- };
-
- if (this.namespaceURI.length() == 0 && this.attributeNamespaces.isEmpty()) {
- builder.invokeMethod(this.name, new Object[]{this.attributes, rest});
- } else {
- final List newTags = new LinkedList();
- builder.getProperty("mkp");
- final List namespaces = (List) builder.invokeMethod("getNamespaces", new Object[]{});
-
- final Map current = (Map) namespaces.get(0);
- final Map pending = (Map) namespaces.get(1);
-
- if (this.attributeNamespaces.isEmpty()) {
- builder.getProperty(getTagFor(this.namespaceURI, current, pending, namespaceMap, namespaceTagHints, newTags, builder));
- builder.invokeMethod(this.name, new Object[]{this.attributes, rest});
- } else {
- final Map attributesWithNamespaces = new HashMap(this.attributes);
- for (Object key : this.attributes.keySet()) {
- final Object attributeNamespaceURI = this.attributeNamespaces.get(key);
- if (attributeNamespaceURI != null) {
- attributesWithNamespaces.put(getTagFor(attributeNamespaceURI, current, pending, namespaceMap, namespaceTagHints, newTags, builder) +
- "$" + key, attributesWithNamespaces.remove(key));
- }
- }
- builder.getProperty(getTagFor(this.namespaceURI, current, pending, namespaceMap, namespaceTagHints, newTags, builder));
- builder.invokeMethod(this.name, new Object[]{attributesWithNamespaces, rest});
- }
-
- // remove the new tags we had to define for this element
- if (!newTags.isEmpty()) {
- final Iterator iter = newTags.iterator();
- do {
- pending.remove(iter.next());
- } while (iter.hasNext());
- }
- }
- } else {
- ((ReplacementNode) this.replacementNodeStack.peek()).build(builder, namespaceMap, namespaceTagHints);
- }
- }
-
- private static String getTagFor(final Object namespaceURI, final Map current,
- final Map pending, final Map local, final Map tagHints,
- final List newTags, final GroovyObject builder) {
- String tag = findNamespaceTag(pending, namespaceURI); // look in the namespaces whose declaration has already been emitted
- if (tag == null) {
- tag = findNamespaceTag(current, namespaceURI); // look in the namespaces who will be declared at the next element
-
- if (tag == null) {
- // we have to declare the namespace - choose a tag
- tag = findNamespaceTag(local, namespaceURI); // If the namespace has been declared in the GPath expression use that tag
-
- if (tag == null || tag.length() == 0) {
- tag = findNamespaceTag(tagHints, namespaceURI); // If the namespace has been used in the parse document use that tag
- }
-
- if (tag == null || tag.length() == 0) { // otherwise make up a new tag and check it has not been used before
- int suffix = 0;
- do {
- final String possibleTag = "tag" + suffix++;
-
- if (!pending.containsKey(possibleTag) && !current.containsKey(possibleTag) && !local.containsKey(possibleTag)) {
- tag = possibleTag;
- }
- } while (tag == null);
- }
-
- final Map newNamespace = new HashMap();
- newNamespace.put(tag, namespaceURI);
- builder.getProperty("mkp");
- builder.invokeMethod("declareNamespace", new Object[]{newNamespace});
- newTags.add(tag);
- }
- }
- return tag;
- }
-
- private static String findNamespaceTag(final Map tagMap, final Object namespaceURI) {
- if (tagMap.containsValue(namespaceURI)) {
- for (Object o : tagMap.entrySet()) {
- final Map.Entry entry = (Map.Entry) o;
- if (namespaceURI.equals(entry.getValue())) {
- return (String) entry.getKey();
- }
- }
- }
- return null;
- }
-
- private void buildChildren(final GroovyObject builder, final Map namespaceMap, final Map<String, String> namespaceTagHints) {
- for (Object child : this.children) {
- if (child instanceof Node) {
- ((Node) child).build(builder, namespaceMap, namespaceTagHints);
- } else if (child instanceof Buildable) {
- ((Buildable) child).build(builder);
- } else {
- builder.getProperty("mkp");
- builder.invokeMethod("yield", new Object[]{child});
- }
- }
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NodeChild.java b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NodeChild.java
deleted file mode 100644
index 9d97d0e..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NodeChild.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util.slurpersupport;
-
-import groovy.lang.Closure;
-import groovy.lang.GroovyObject;
-import groovy.lang.GroovyRuntimeException;
-import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Lazy evaluated representation of a child node.
- */
-@Deprecated
-public class NodeChild extends GPathResult {
- private final Node node;
-
- /**
- * @param node a node
- * @param parent the GPathResult prior to the application of the expression creating this GPathResult
- * @param namespacePrefix the namespace prefix if any
- * @param namespaceTagHints the known tag to namespace mappings
- */
- public NodeChild(final Node node, final GPathResult parent, final String namespacePrefix, final Map<String, String> namespaceTagHints) {
- super(parent, node.name(), namespacePrefix, namespaceTagHints);
- this.node = node;
- ((NamespaceAwareHashMap)this.node.attributes()).setNamespaceTagHints(namespaceTagHints);
- }
-
- /**
- * @param node a node
- * @param parent the GPathResult prior to the application of the expression creating this GPathResult
- * @param namespaceTagHints the known tag to namespace mappings
- */
- public NodeChild(final Node node, final GPathResult parent, final Map<String, String> namespaceTagHints) {
- this(node, parent, "*", namespaceTagHints);
- }
-
- public GPathResult parent() {
- if (node.parent() != null)
- return new NodeChild(node.parent(), this, namespaceTagHints);
- else
- return this;
- }
-
- public int size() {
- return 1;
- }
-
- public String text() {
- return this.node.text();
- }
-
- /**
- * Returns the list of any direct String nodes of this NodeChild.
- *
- * @return the list of String values from this node
- * @since 2.3.0
- */
- public List<String> localText() {
- return this.node.localText();
- }
-
- /**
- * Returns the URI of the namespace of this NodeChild.
- * @return the namespace of this NodeChild
- */
- public String namespaceURI() {
- return this.node.namespaceURI();
- }
-
- /**
- * Throws a <code>GroovyRuntimeException</code>, because this method is not implemented yet.
- */
- public GPathResult parents() {
- // TODO Auto-generated method stub
- throw new GroovyRuntimeException("parents() not implemented yet");
- }
-
- public Iterator iterator() {
- return createIterator(this);
- }
-
- public Iterator nodeIterator() {
- return createIterator(this.node);
- }
-
- public Object getAt(final int index) {
- if (index == 0) {
- return node;
- } else {
- throw new ArrayIndexOutOfBoundsException(index);
- }
- }
-
- /**
- * Returns a map containing all attributes of the Node of this NodeChild.
- * @return a map containing all attributes
- */
- public Map attributes() {
- return this.node.attributes();
- }
-
- public Iterator childNodes() {
- return this.node.childNodes();
- }
-
- public GPathResult find(final Closure closure) {
- if (DefaultTypeTransformation.castToBoolean(closure.call(new Object[]{this.node}))) {
- return this;
- } else {
- return new NoChildren(this, "", this.namespaceTagHints);
- }
- }
-
- public GPathResult findAll(final Closure closure) {
- return find(closure);
- }
-
- public void build(final GroovyObject builder) {
- this.node.build(builder, this.namespaceMap, this.namespaceTagHints);
- }
-
- public Writer writeTo(final Writer out) throws IOException {
- return this.node.writeTo(out);
- }
-
- protected void replaceNode(final Closure newValue) {
- this.node.replaceNode(newValue, this);
- }
-
- protected void replaceBody(final Object newValue) {
- this.node.replaceBody(newValue);
- }
-
- protected void appendNode(final Object newValue) {
- this.node.appendNode(newValue, this);
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NodeChildren.java b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NodeChildren.java
deleted file mode 100644
index 8f1532c..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NodeChildren.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util.slurpersupport;
-
-import groovy.lang.Buildable;
-import groovy.lang.Closure;
-import groovy.lang.GroovyObject;
-import groovy.lang.GroovyRuntimeException;
-import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Iterator;
-import java.util.Map;
-
-/**
- * Lazy evaluated representation of child nodes.
- */
-@Deprecated
-public class NodeChildren extends GPathResult {
- private int size = -1;
-
- /**
- * @param parent the GPathResult prior to the application of the expression creating this GPathResult
- * @param name if the GPathResult corresponds to something with a name, e.g. a node
- * @param namespacePrefix the namespace prefix if any
- * @param namespaceTagHints the known tag to namespace mappings
- */
- public NodeChildren(final GPathResult parent, final String name, final String namespacePrefix, final Map<String, String> namespaceTagHints) {
- super(parent, name, namespacePrefix, namespaceTagHints);
- }
-
- /**
- * @param parent the GPathResult prior to the application of the expression creating this GPathResult
- * @param name if the GPathResult corresponds to something with a name, e.g. a node
- * @param namespaceTagHints the known tag to namespace mappings
- */
- public NodeChildren(final GPathResult parent, final String name, final Map<String, String> namespaceTagHints) {
- this(parent, name, "*", namespaceTagHints);
- }
-
- /**
- * @param parent the GPathResult prior to the application of the expression creating this GPathResult
- * @param namespaceTagHints the known tag to namespace mappings
- */
- public NodeChildren(final GPathResult parent, final Map<String, String> namespaceTagHints) {
- this(parent, "*", namespaceTagHints);
- }
-
- public Iterator childNodes() {
- return new Iterator() {
- private final Iterator iter = nodeIterator();
- private Iterator childIter = nextChildIter();
-
- public boolean hasNext() {
- return childIter != null;
- }
-
- public Object next() {
- while (childIter != null) {
- try {
- if (childIter.hasNext()) {
- return childIter.next();
- }
- } finally {
- if (!childIter.hasNext()) {
- childIter = nextChildIter();
- }
- }
- }
- return null;
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- private Iterator nextChildIter() {
- while (iter.hasNext()) {
- final Node node = (Node)iter.next();
- final Iterator result = node.childNodes();
- if (result.hasNext()) return result;
- }
- return null;
- }
- };
- }
-
- public Iterator iterator() {
- return new Iterator() {
- final Iterator iter = nodeIterator();
-
- public boolean hasNext() {
- return iter.hasNext();
- }
-
- public Object next() {
- return new NodeChild((Node) iter.next(), pop(), namespaceTagHints);
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
- };
- }
-
- public Iterator nodeIterator() {
- if ("*".equals(name)) {
- return parent.childNodes();
- } else {
- return new NodeIterator(parent.childNodes()) {
- protected Object getNextNode(Iterator iter) {
- while (iter.hasNext()) {
- final Node node = (Node) iter.next();
- if (name.equals(node.name())) {
- if ("*".equals(namespacePrefix) ||
- ("".equals(namespacePrefix) && "".equals(node.namespaceURI())) ||
- node.namespaceURI().equals(namespaceMap.get(namespacePrefix))) {
- return node;
- }
- }
- }
- return null;
- }
- };
- }
- }
-
- /**
- * Throws a <code>GroovyRuntimeException</code>, because it is not implemented yet.
- */
- public GPathResult parents() {
- // TODO Auto-generated method stub
- throw new GroovyRuntimeException("parents() not implemented yet");
- }
-
- public synchronized int size() {
- if (this.size == -1) {
- final Iterator iter = iterator();
- this.size = 0;
- while (iter.hasNext()) {
- iter.next();
- this.size++;
- }
- }
- return this.size;
- }
-
- public String text() {
- final StringBuilder buf = new StringBuilder();
- final Iterator iter = nodeIterator();
- while (iter.hasNext()) {
- buf.append(((Node) iter.next()).text());
- }
- return buf.toString();
- }
-
- public GPathResult find(final Closure closure) {
- final Iterator iter = iterator();
- while (iter.hasNext()) {
- final Object node = iter.next();
- if (DefaultTypeTransformation.castToBoolean(closure.call(new Object[]{node}))) {
- return (GPathResult) node;
- }
- }
- return new NoChildren(this, this.name, namespaceTagHints);
- }
-
- public GPathResult findAll(final Closure closure) {
- return new FilteredNodeChildren(this, closure, namespaceTagHints);
- }
-
- public void build(final GroovyObject builder) {
- final Iterator iter = nodeIterator();
- while (iter.hasNext()) {
- final Object next = iter.next();
- if (next instanceof Buildable) {
- ((Buildable) next).build(builder);
- } else {
- ((Node) next).build(builder, namespaceMap, namespaceTagHints);
- }
- }
- }
-
- /* (non-Javadoc)
- * @see groovy.lang.Writable#writeTo(java.io.Writer)
- */
- public Writer writeTo(final Writer out) throws IOException {
- final Iterator iter = nodeIterator();
- while (iter.hasNext()) {
- ((Node) iter.next()).writeTo(out);
- }
- return out;
- }
-
- protected void replaceNode(final Closure newValue) {
- final Iterator iter = iterator();
- while (iter.hasNext()) {
- final NodeChild result = (NodeChild) iter.next();
- result.replaceNode(newValue);
- }
- }
-
- protected void replaceBody(final Object newValue) {
- final Iterator iter = iterator();
- while (iter.hasNext()) {
- final NodeChild result = (NodeChild) iter.next();
- result.replaceBody(newValue);
- }
- }
-
- protected void appendNode(final Object newValue) {
- final Iterator iter = iterator();
- while (iter.hasNext()) {
- final NodeChild result = (NodeChild) iter.next();
- result.appendNode(newValue);
- }
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NodeIterator.java b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NodeIterator.java
deleted file mode 100644
index 0f092d7..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NodeIterator.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util.slurpersupport;
-
-import java.util.Iterator;
-
-/**
- * Helper class for iterating through nodes.
- */
-@Deprecated
-public abstract class NodeIterator implements Iterator {
- private static final Object DELAYED_INIT = new Object();
- private final Iterator iter;
- private Object nextNode;
-
- public NodeIterator(final Iterator iter) {
- this.iter = iter;
- this.nextNode = DELAYED_INIT;
- }
-
- private void initNextNode(){
- if (nextNode==DELAYED_INIT) nextNode = getNextNode(iter);
- }
-
- public boolean hasNext() {
- initNextNode();
- return this.nextNode != null;
- }
-
- public Object next() {
- initNextNode();
- try {
- return this.nextNode;
- } finally {
- this.nextNode = getNextNode(this.iter);
- }
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- protected abstract Object getNextNode(final Iterator iter);
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NodeParents.java b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NodeParents.java
deleted file mode 100644
index dcf7913..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/NodeParents.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util.slurpersupport;
-
-import java.util.Iterator;
-import java.util.Map;
-
-/**
-* Lazy evaluated representation of parent nodes without duplicates
-*/
-@Deprecated
-public class NodeParents extends NodeChildren {
-
- /**
- * @param parent the GPathResult prior to the application of the expression creating this GPathResult
- * @param namespaceTagHints the known tag to namespace mappings
- */
- public NodeParents(final GPathResult parent, final Map<String, String> namespaceTagHints) {
- super(parent, parent.parent.name, namespaceTagHints);
- }
-
- public Iterator nodeIterator() {
- return new NodeIterator(this.parent.nodeIterator()) {
-
- private Node prev = null;
-
- protected Object getNextNode(final Iterator iter) {
- while (iter.hasNext()) {
- final Node node = ((Node)iter.next()).parent();
- if (node != null && node != prev) {
- prev = node;
- return node;
- }
- }
- return null;
- }
- };
- }
-
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/ReplacementNode.java b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/ReplacementNode.java
deleted file mode 100644
index 39654f7..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/ReplacementNode.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.util.slurpersupport;
-
-import groovy.lang.Buildable;
-import groovy.lang.GroovyObject;
-import groovy.lang.Writable;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Map;
-
-/**
- * Helper base class used for lazy updates.
- */
-@Deprecated
-public abstract class ReplacementNode implements Buildable, Writable {
- public abstract void build(GroovyObject builder, Map namespaceMap, Map<String, String> namespaceTagHints);
-
- public void build(final GroovyObject builder) {
- build(builder, null, null);
- }
-
- /**
- * NOP
- * @return the Writer that was passed
- */
- public Writer writeTo(final Writer out) throws IOException {
- return out;
- }
-}
diff --git a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/package.html b/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/package.html
deleted file mode 100644
index a47137e..0000000
--- a/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/package.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
--->
-<html>
- <head>
- <title>package groovy.util.slurpersupport.*</title>
- </head>
- <body>
- <p>Helper classes for XmlSlurper.</p>
- </body>
-</html>
diff --git a/subprojects/groovy-xml/src/main/java/org/codehaus/groovy/runtime/XmlGroovyMethods.java b/subprojects/groovy-xml/src/main/java/org/codehaus/groovy/runtime/XmlGroovyMethods.java
deleted file mode 100644
index 3d899da..0000000
--- a/subprojects/groovy-xml/src/main/java/org/codehaus/groovy/runtime/XmlGroovyMethods.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.codehaus.groovy.runtime;
-
-import groovy.xml.XmlUtil;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.util.Iterator;
-
-/**
- * This class defines all the new XML-related groovy methods which enhance
- * the normal JDK XML classes when inside the Groovy environment.
- * Static methods are used with the first parameter the destination class.
- */
-@Deprecated
-public class XmlGroovyMethods {
-
- /**
- * Makes NodeList iterable by returning a read-only Iterator which traverses
- * over each Node.
- *
- * @param nodeList a NodeList
- * @return an Iterator for a NodeList
- * @since 1.0
- */
- @Deprecated
- public static Iterator<Node> iterator(final NodeList nodeList) {
- return new Iterator<Node>() {
- private int current /* = 0 */;
-
- public boolean hasNext() {
- return current < nodeList.getLength();
- }
-
- public Node next() {
- return nodeList.item(current++);
- }
-
- public void remove() {
- throw new UnsupportedOperationException("Cannot remove() from a NodeList iterator");
- }
- };
- }
-
- /**
- * Transforms the element to its text equivalent.
- * (The resulting string does not contain a xml declaration. Use {@code XmlUtil.serialize(element)} if you need the declaration.)
- *
- * @param element the element to serialize
- * @return the string representation of the element
- * @since 2.1
- */
- @Deprecated
- public static String serialize(Element element) {
- return XmlUtil.serialize(element).replaceFirst("<\\?xml version=\"1.0\".*\\?>", "");
- }
-}
\ No newline at end of file
diff --git a/subprojects/groovy-xml/src/main/java/org/codehaus/groovy/tools/xml/DomToGroovy.java b/subprojects/groovy-xml/src/main/java/org/codehaus/groovy/tools/xml/DomToGroovy.java
deleted file mode 100644
index 46eaeb6..0000000
--- a/subprojects/groovy-xml/src/main/java/org/codehaus/groovy/tools/xml/DomToGroovy.java
+++ /dev/null
@@ -1,405 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.codehaus.groovy.tools.xml;
-
-import groovy.util.IndentPrinter;
-import org.codehaus.groovy.syntax.Types;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Comment;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.ProcessingInstruction;
-import org.w3c.dom.Text;
-import org.xml.sax.InputSource;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintWriter;
-import java.io.Reader;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * A SAX handler for turning XML into Groovy scripts
- */
-@Deprecated
-public class DomToGroovy {
-
- protected IndentPrinter out;
- protected boolean inMixed = false;
- protected String qt = "'";
- protected Collection<String> keywords = Types.getKeywords();
-
- public DomToGroovy(PrintWriter out) {
- this(new IndentPrinter(out));
- }
-
- // TODO allow string quoting delimiter to be specified, e.g. ' vs "
- public DomToGroovy(IndentPrinter out) {
- this.out = out;
- }
-
- public void print(Document document) {
- printChildren(document, new HashMap());
- }
-
- public static void main(String[] args) {
- if (args.length < 1) {
- System.out.println("Usage: DomToGroovy infilename [outfilename]");
- System.exit(1);
- }
- Document document = null;
- try {
- document = parse(args[0]);
- } catch (Exception e) {
- System.out.println("Unable to parse input file '" + args[0] + "': " + e.getMessage());
- System.exit(1);
- }
- PrintWriter writer = null;
- if (args.length < 2) {
- writer = new PrintWriter(System.out);
- } else {
- try {
- writer = new PrintWriter(new FileWriter(new File(args[1])));
- } catch (IOException e) {
- System.out.println("Unable to create output file '" + args[1] + "': " + e.getMessage());
- System.exit(1);
- }
- }
- DomToGroovy converter = new DomToGroovy(writer);
- converter.out.incrementIndent();
- writer.println("#!/bin/groovy");
- writer.println();
- writer.println("// generated from " + args[0]);
- writer.println("System.out << new groovy.xml.StreamingMarkupBuilder().bind {");
- converter.print(document);
- writer.println("}");
- writer.close();
- }
-
- // Implementation methods
- //-------------------------------------------------------------------------
-
- protected static Document parse(final String fileName) throws Exception {
- return parse(new File(fileName));
- }
-
- public static Document parse(final File file) throws Exception {
- return parse(new BufferedReader(new FileReader(file)));
- }
-
- public static Document parse(final Reader input) throws Exception {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setNamespaceAware(true);
- DocumentBuilder builder = factory.newDocumentBuilder();
- return builder.parse(new InputSource(input));
- }
-
- public static Document parse(final InputStream input) throws Exception {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setNamespaceAware(true);
- DocumentBuilder builder = factory.newDocumentBuilder();
- return builder.parse(new InputSource(input));
- }
-
- protected void print(Node node, Map namespaces, boolean endWithComma) {
- switch (node.getNodeType()) {
- case Node.ELEMENT_NODE :
- printElement((Element) node, namespaces, endWithComma);
- break;
- case Node.PROCESSING_INSTRUCTION_NODE :
- printPI((ProcessingInstruction) node, endWithComma);
- break;
- case Node.TEXT_NODE :
- printText((Text) node, endWithComma);
- break;
- case Node.COMMENT_NODE :
- printComment((Comment) node, endWithComma);
- break;
- }
- }
-
- protected void printElement(Element element, Map namespaces, boolean endWithComma) {
- namespaces = defineNamespaces(element, namespaces);
-
- element.normalize();
- printIndent();
-
- String prefix = element.getPrefix();
- boolean hasPrefix = prefix != null && prefix.length() > 0;
- String localName = getLocalName(element);
- boolean isKeyword = checkEscaping(localName);
- if (isKeyword || hasPrefix) print(qt);
- if (hasPrefix) {
- print(prefix);
- print(".");
- }
- print(localName);
- if (isKeyword || hasPrefix) print(qt);
- print("(");
-
- boolean hasAttributes = printAttributes(element);
-
- NodeList list = element.getChildNodes();
- int length = list.getLength();
- if (length == 0) {
- printEnd(")", endWithComma);
- } else {
- Node node = list.item(0);
- if (length == 1 && node instanceof Text) {
- Text textNode = (Text) node;
- String text = getTextNodeData(textNode);
- if (hasAttributes) print(", ");
- printQuoted(text);
- printEnd(")", endWithComma);
- } else if (mixedContent(list)) {
- println(") {");
- out.incrementIndent();
- boolean oldInMixed = inMixed;
- inMixed = true;
- for (node = element.getFirstChild(); node != null; node = node.getNextSibling()) {
- print(node, namespaces, false);
- }
- inMixed = oldInMixed;
- out.decrementIndent();
- printIndent();
- printEnd("}", endWithComma);
- } else {
- println(") {");
- out.incrementIndent();
- printChildren(element, namespaces);
- out.decrementIndent();
- printIndent();
- printEnd("}", endWithComma);
- }
- }
- }
-
- protected void printQuoted(String text) {
- if (text.contains("\n")) {
- print("'''");
- print(text);
- print("'''");
- } else {
- print(qt);
- print(escapeQuote(text));
- print(qt);
- }
- }
-
- protected void printPI(ProcessingInstruction instruction, boolean endWithComma) {
- printIndent();
- print("mkp.pi(" + qt);
- print(instruction.getTarget());
- print(qt + ", " + qt);
- print(instruction.getData());
- printEnd(qt + ");", endWithComma);
- }
-
- protected void printComment(Comment comment, boolean endWithComma) {
- String text = comment.getData().trim();
- if (text.length() >0) {
- printIndent();
- print("/* ");
- print(text);
- printEnd(" */", endWithComma);
- }
- }
-
- protected void printText(Text node, boolean endWithComma) {
- String text = getTextNodeData(node);
- if (text.length() > 0) {
- printIndent();
- if (inMixed) print("mkp.yield ");
- printQuoted(text);
- printEnd("", endWithComma);
- }
- }
-
- protected String escapeQuote(String text) {
- return text.replaceAll("\\\\", "\\\\\\\\").replaceAll(qt, "\\\\" + qt);
- }
-
- protected Map defineNamespaces(Element element, Map namespaces) {
- Map answer = null;
- String prefix = element.getPrefix();
- if (prefix != null && prefix.length() > 0 && !namespaces.containsKey(prefix)) {
- answer = new HashMap(namespaces);
- defineNamespace(answer, prefix, element.getNamespaceURI());
- }
- NamedNodeMap attributes = element.getAttributes();
- int length = attributes.getLength();
- for (int i = 0; i < length; i++) {
- Attr attribute = (Attr) attributes.item(i);
- prefix = attribute.getPrefix();
- if (prefix != null && prefix.length() > 0 && !namespaces.containsKey(prefix)) {
- if (answer == null) {
- answer = new HashMap(namespaces);
- }
- defineNamespace(answer, prefix, attribute.getNamespaceURI());
- }
- }
- return (answer != null) ? answer : namespaces;
- }
-
- protected void defineNamespace(Map namespaces, String prefix, String uri) {
- namespaces.put(prefix, uri);
- if (!prefix.equals("xmlns") && !prefix.equals("xml")) {
- printIndent();
- print("mkp.declareNamespace(");
- print(prefix);
- print(":" + qt);
- print(uri);
- println(qt + ")");
- }
- }
-
- protected boolean printAttributes(Element element) {
- boolean hasAttribute = false;
- NamedNodeMap attributes = element.getAttributes();
- int length = attributes.getLength();
- if (length > 0) {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < length; i++) {
- printAttributeWithPrefix((Attr) attributes.item(i), buffer);
- }
- for (int i = 0; i < length; i++) {
- hasAttribute = printAttributeWithoutPrefix((Attr) attributes.item(i), hasAttribute);
- }
- if (buffer.length() > 0) {
- if (hasAttribute) {
- print(", ");
- }
- print(buffer.toString());
- hasAttribute = true;
- }
- }
- return hasAttribute;
- }
-
- protected void printAttributeWithPrefix(Attr attribute, StringBuffer buffer) {
- String prefix = attribute.getPrefix();
- if (prefix != null && prefix.length() > 0 && !prefix.equals("xmlns")) {
- if (buffer.length() > 0) {
- buffer.append(", ");
- }
- buffer.append(qt);
- buffer.append(prefix);
- buffer.append(":");
- buffer.append(getLocalName(attribute));
- buffer.append(qt).append(":").append(qt);
- buffer.append(escapeQuote(getAttributeValue(attribute)));
- buffer.append(qt);
- }
- }
-
- protected String getAttributeValue(Attr attribute) {
- return attribute.getValue();
- }
-
- protected boolean printAttributeWithoutPrefix(Attr attribute, boolean hasAttribute) {
- String prefix = attribute.getPrefix();
- if (prefix == null || prefix.length() == 0) {
- if (!hasAttribute) {
- hasAttribute = true;
- } else {
- print(", ");
- }
- String localName = getLocalName(attribute);
- boolean needsEscaping = checkEscaping(localName);
- if (needsEscaping) print(qt);
- print(localName);
- if (needsEscaping) print(qt);
- print(":");
- printQuoted(getAttributeValue(attribute));
- }
- return hasAttribute;
- }
-
- protected boolean checkEscaping(String localName) {
- return keywords.contains(localName) || localName.contains("-") || localName.contains(":") || localName.contains(".");
- }
-
- protected String getTextNodeData(Text node) {
- return node.getData().trim();
- }
-
- protected boolean mixedContent(NodeList list) {
- boolean hasText = false;
- boolean hasElement = false;
- for (int i = 0, size = list.getLength(); i < size; i++) {
- Node node = list.item(i);
- if (node instanceof Element) {
- hasElement = true;
- } else if (node instanceof Text) {
- String text = getTextNodeData((Text) node);
- if (text.length() > 0) {
- hasText = true;
- }
- }
- if (hasText && hasElement) break;
- }
- return hasText && hasElement;
- }
-
- protected void printChildren(Node parent, Map namespaces) {
- for (Node node = parent.getFirstChild(); node != null; node = node.getNextSibling()) {
- print(node, namespaces, false);
- }
- }
-
- protected String getLocalName(Node node) {
- String answer = node.getLocalName();
- if (answer == null) {
- answer = node.getNodeName();
- }
- return answer.trim();
- }
-
- protected void printEnd(String text, boolean endWithComma) {
- if (endWithComma) {
- print(text);
- println(",");
- } else {
- println(text);
- }
- }
-
- protected void println(String text) {
- out.println(text);
- }
-
- protected void print(String text) {
- out.print(text);
- }
-
- protected void printIndent() {
- out.printIndent();
- }
-}