From 7f1b1b09aa0e7c6a2c31e047ea37589d13013378 Mon Sep 17 00:00:00 2001 From: Gabriel Belingueres Date: Tue, 4 Dec 2018 11:23:49 -0300 Subject: [PATCH] Solved infinite loop in MXParser when parsing a malformed Processing Instruction. --- .travis.yml | 5 +- pom.xml | 11 +- .../codehaus/plexus/util/AbstractScanner.java | 32 +-- .../plexus/util/DirectoryScanner.java | 125 +++++------ .../org/codehaus/plexus/util/FileUtils.java | 153 ++++++------- .../util/LineOrientedInterpolatingReader.java | 8 +- .../codehaus/plexus/util/MatchPattern.java | 6 +- .../codehaus/plexus/util/MatchPatterns.java | 6 +- .../java/org/codehaus/plexus/util/Os.java | 4 +- .../org/codehaus/plexus/util/PathTool.java | 30 +-- .../codehaus/plexus/util/SelectorUtils.java | 27 +-- .../plexus/util/StringInputStream.java | 2 +- .../org/codehaus/plexus/util/StringUtils.java | 8 +- .../org/codehaus/plexus/util/SweeperPool.java | 9 +- .../org/codehaus/plexus/util/TypeFormat.java | 2 - .../codehaus/plexus/util/WriterFactory.java | 1 - .../plexus/util/cli/CommandLineUtils.java | 2 - .../codehaus/plexus/util/cli/Commandline.java | 76 +++---- .../codehaus/plexus/util/cli/shell/Shell.java | 2 - .../org/codehaus/plexus/util/dag/DAG.java | 4 +- .../org/codehaus/plexus/util/dag/Vertex.java | 6 +- .../plexus/util/introspection/ClassMap.java | 12 +- .../ReflectionValueExtractor.java | 14 +- .../codehaus/plexus/util/xml/XmlReader.java | 49 ++-- .../org/codehaus/plexus/util/xml/Xpp3Dom.java | 90 ++++++-- .../plexus/util/xml/Xpp3DomBuilder.java | 46 +++- .../plexus/util/xml/Xpp3DomUtils.java | 62 ++++-- .../plexus/util/xml/pull/MXParser.java | 25 ++- .../plexus/util/xml/pull/XmlPullParser.java | 42 ++-- .../plexus/util/xml/pull/XmlSerializer.java | 2 +- .../plexus/util/CollectionUtilsTest.java | 12 +- .../plexus/util/DirectoryScannerTest.java | 86 ++++++- .../plexus/util/DirectoryWalkerTest.java | 8 +- .../plexus/util/FileBasedTestCase.java | 4 +- .../codehaus/plexus/util/FileUtilsTest.java | 99 +++++++-- .../org/codehaus/plexus/util/IOUtilTest.java | 36 ++- .../util/InterpolationFilterReaderTest.java | 16 +- .../LineOrientedInterpolatingReaderTest.java | 33 +-- .../plexus/util/MatchPatternTest.java | 8 +- .../plexus/util/MatchPatternsTest.java | 9 +- .../java/org/codehaus/plexus/util/OsTest.java | 10 +- .../codehaus/plexus/util/PathToolTest.java | 10 +- .../org/codehaus/plexus/util/PerfTest.java | 8 +- .../plexus/util/ReflectionUtilsTest.java | 16 +- .../plexus/util/SelectorUtilsTest.java | 15 +- .../codehaus/plexus/util/StringUtilsTest.java | 28 ++- .../codehaus/plexus/util/SweeperPoolTest.java | 47 ++-- .../plexus/util/cli/CommandLineUtilsTest.java | 13 +- .../plexus/util/cli/CommandlineTest.java | 209 ++++++++---------- .../plexus/util/cli/DefaultConsumerTest.java | 25 +-- .../util/cli/EnhancedStringTokenizerTest.java | 29 +-- .../plexus/util/cli/StreamPumperTest.java | 32 +-- .../util/cli/shell/BourneShellTest.java | 19 +- .../util/dag/CycleDetectedExceptionTest.java | 6 +- .../plexus/util/dag/CycleDetectorTest.java | 10 +- .../org/codehaus/plexus/util/dag/DAGTest.java | 9 +- .../util/dag/TopologicalSorterTest.java | 6 +- .../codehaus/plexus/util/dag/VertexTest.java | 6 +- .../ReflectionValueExtractorTest.java | 96 ++++---- .../plexus/util/reflection/ReflectorTest.java | 14 +- .../util/xml/PrettyPrintXMLWriterTest.java | 44 ++-- .../plexus/util/xml/XmlStreamWriterTest.java | 17 +- .../codehaus/plexus/util/xml/XmlUtilTest.java | 25 +-- .../plexus/util/xml/XmlWriterUtilTest.java | 37 +++- .../plexus/util/xml/Xpp3DomBuilderTest.java | 61 ++++- .../codehaus/plexus/util/xml/Xpp3DomTest.java | 82 ++++++- .../plexus/util/xml/Xpp3DomUtilsTest.java | 43 +++- .../plexus/util/xml/Xpp3DomWriterTest.java | 7 +- .../plexus/util/xml/pull/MXParserTest.java | 148 ++++++++++++- 69 files changed, 1414 insertions(+), 830 deletions(-) diff --git a/.travis.yml b/.travis.yml index 13f6528e..dc7432dd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,10 @@ language: java jdk: - openjdk7 - - oraclejdk8 + - openjdk8 + - openjdk9 + - openjdk10 + - openjdk11 # No need for preliminary install step. install: true diff --git a/pom.xml b/pom.xml index 4f7a4979..b4be05fb 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,7 @@ limitations under the License. plexus-utils - 3.1.1-SNAPSHOT + 3.2.0-SNAPSHOT Plexus Common Utilities A collection of various utility classes to ease working with strings, files, command lines, XML and @@ -63,6 +63,15 @@ limitations under the License. + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.0.0 + + + org.apache.maven.plugins diff --git a/src/main/java/org/codehaus/plexus/util/AbstractScanner.java b/src/main/java/org/codehaus/plexus/util/AbstractScanner.java index 1aaef2f9..02486288 100644 --- a/src/main/java/org/codehaus/plexus/util/AbstractScanner.java +++ b/src/main/java/org/codehaus/plexus/util/AbstractScanner.java @@ -130,10 +130,10 @@ public void setCaseSensitive( boolean isCaseSensitive ) } /** - * Tests whether or not a given path matches the start of a given pattern up to the first "**". - *

- * This is not a general purpose test and should only be used if you can live with false positives. For example, - * pattern=**\a and str=b will yield true. + *

Tests whether or not a given path matches the start of a given pattern up to the first "**".

+ * + *

This is not a general purpose test and should only be used if you can live with false positives. For example, + * pattern=**\a and str=b will yield true.

* * @param pattern The pattern to match against. Must not be null. * @param str The path to match, as a String. Must not be null. @@ -145,10 +145,10 @@ protected static boolean matchPatternStart( String pattern, String str ) } /** - * Tests whether or not a given path matches the start of a given pattern up to the first "**". - *

- * This is not a general purpose test and should only be used if you can live with false positives. For example, - * pattern=**\a and str=b will yield true. + *

Tests whether or not a given path matches the start of a given pattern up to the first "**".

+ * + *

This is not a general purpose test and should only be used if you can live with false positives. For example, + * pattern=**\a and str=b will yield true.

* * @param pattern The pattern to match against. Must not be null. * @param str The path to match, as a String. Must not be null. @@ -215,10 +215,10 @@ protected static boolean match( String pattern, String str, boolean isCaseSensit } /** - * Sets the list of include patterns to use. All '/' and '\' characters are replaced by - * File.separatorChar, so the separator used need not match File.separatorChar. - *

- * When a pattern ends with a '/' or '\', "**" is appended. + *

Sets the list of include patterns to use. All '/' and '\' characters are replaced by + * File.separatorChar, so the separator used need not match File.separatorChar.

+ * + *

When a pattern ends with a '/' or '\', "**" is appended.

* * @param includes A list of include patterns. May be null, indicating that all files should be * included. If a non-null list is given, all elements must be non-null. @@ -244,10 +244,10 @@ public void setIncludes( String[] includes ) } /** - * Sets the list of exclude patterns to use. All '/' and '\' characters are replaced by - * File.separatorChar, so the separator used need not match File.separatorChar. - *

- * When a pattern ends with a '/' or '\', "**" is appended. + *

Sets the list of exclude patterns to use. All '/' and '\' characters are replaced by + * File.separatorChar, so the separator used need not match File.separatorChar.

+ * + *

When a pattern ends with a '/' or '\', "**" is appended.

* * @param excludes A list of exclude patterns. May be null, indicating that no files should be * excluded. If a non-null list is given, all elements must be non-null. diff --git a/src/main/java/org/codehaus/plexus/util/DirectoryScanner.java b/src/main/java/org/codehaus/plexus/util/DirectoryScanner.java index 6f982572..ea3e4b65 100644 --- a/src/main/java/org/codehaus/plexus/util/DirectoryScanner.java +++ b/src/main/java/org/codehaus/plexus/util/DirectoryScanner.java @@ -60,56 +60,52 @@ import java.util.Vector; /** - * Class for scanning a directory for files/directories which match certain criteria. - *

- * These criteria consist of selectors and patterns which have been specified. With the selectors you can select which + *

Class for scanning a directory for files/directories which match certain criteria.

+ * + *

These criteria consist of selectors and patterns which have been specified. With the selectors you can select which * files you want to have included. Files which are not selected are excluded. With patterns you can include or exclude - * files based on their filename. - *

- * The idea is simple. A given directory is recursively scanned for all files and directories. Each file/directory is + * files based on their filename.

+ * + *

The idea is simple. A given directory is recursively scanned for all files and directories. Each file/directory is * matched against a set of selectors, including special support for matching against filenames with include and and * exclude patterns. Only files/directories which match at least one pattern of the include pattern list or other file * selector, and don't match any pattern of the exclude pattern list or fail to match against a required selector will - * be placed in the list of files/directories found. - *

- * When no list of include patterns is supplied, "**" will be used, which means that everything will be matched. When no + * be placed in the list of files/directories found.

+ * + *

When no list of include patterns is supplied, "**" will be used, which means that everything will be matched. When no * list of exclude patterns is supplied, an empty list is used, such that nothing will be excluded. When no selectors - * are supplied, none are applied. - *

- * The filename pattern matching is done as follows: The name to be matched is split up in path segments. A path segment + * are supplied, none are applied.

+ * + *

The filename pattern matching is done as follows: The name to be matched is split up in path segments. A path segment * is the name of a directory or file, which is bounded by File.separator ('/' under UNIX, '\' under * Windows). For example, "abc/def/ghi/xyz.java" is split up in the segments "abc", "def","ghi" and "xyz.java". The same - * is done for the pattern against which should be matched. - *

- * The segments of the name and the pattern are then matched against each other. When '**' is used for a path segment in - * the pattern, it matches zero or more path segments of the name. - *

- * There is a special case regarding the use of File.separators at the beginning of the pattern and the + * is done for the pattern against which should be matched.

+ * + *

The segments of the name and the pattern are then matched against each other. When '**' is used for a path segment in + * the pattern, it matches zero or more path segments of the name.

+ * + *

There is a special case regarding the use of File.separators at the beginning of the pattern and the * string to match:
* When a pattern starts with a File.separator, the string to match must also start with a * File.separator. When a pattern does not start with a File.separator, the string to match - * may not start with a File.separator. When one of these rules is not obeyed, the string will not match. - *

- * When a name path segment is matched against a pattern path segment, the following special characters can be used:
+ * may not start with a File.separator. When one of these rules is not obeyed, the string will not match.

+ * + *

When a name path segment is matched against a pattern path segment, the following special characters can be used:
* '*' matches zero or more characters
- * '?' matches one character. - *

+ * '?' matches one character.

+ * * Examples: - *

- * "**\*.class" matches all .class files/dirs in a directory tree. - *

- * "test\a??.java" matches all files/dirs which start with an 'a', then two more characters and then ".java", in a - * directory called test. - *

- * "**" matches everything in a directory tree. - *

- * "**\test\**\XYZ*" matches all files/dirs which start with "XYZ" and where there is a parent directory called test - * (e.g. "abc\test\def\ghi\XYZ123"). - *

- * Case sensitivity may be turned off if necessary. By default, it is turned on. - *

- * Example of usage: + *

    + *
  • "**\*.class" matches all .class files/dirs in a directory tree.
  • + *
  • "test\a??.java" matches all files/dirs which start with an 'a', then two more characters and then ".java", in a + * directory called test.
  • + *
  • "**" matches everything in a directory tree.
  • + *
  • "**\test\**\XYZ*" matches all files/dirs which start with "XYZ" and where there is a parent directory called test + * (e.g. "abc\test\def\ghi\XYZ123").
  • + *
* + *

Case sensitivity may be turned off if necessary. By default, it is turned on.

+ * Example of usage: *
  * String[] includes = { "**\\*.class" };
  * String[] excludes = { "modules\\*\\**" };
@@ -121,14 +117,14 @@
  *
  * System.out.println( "FILES:" );
  * String[] files = ds.getIncludedFiles();
- * for ( int i = 0; i < files.length; i++ )
+ * for ( int i = 0; i < files.length; i++ )
  * {
  *     System.out.println( files[i] );
  * }
  * 
* - * This will scan a directory called test for .class files, but excludes all files in all proper subdirectories of a - * directory called "modules" + *

This will scan a directory called test for .class files, but excludes all files in all proper subdirectories of a + * directory called "modules"

* * @author Arnout J. Kuiper ajkuiper@wxs.nl * @author Magesh Umasankar @@ -324,11 +320,11 @@ public void scan() } /** - * Top level invocation for a slow scan. A slow scan builds up a full list of excluded/included files/directories, + *

Top level invocation for a slow scan. A slow scan builds up a full list of excluded/included files/directories, * whereas a fast scan will only have full results for included files, as it ignores directories which can't - * possibly hold any included files/directories. - *

- * Returns immediately if a slow scan has already been completed. + * possibly hold any included files/directories.

+ * + *

Returns immediately if a slow scan has already been completed.

*/ protected void slowScan() { @@ -586,14 +582,10 @@ public String[] getExcludedFiles() } /** - *

- * Returns the names of the files which were selected out and therefore not ultimately included. - *

- *

- *

- * The names are relative to the base directory. This involves performing a slow scan if one has not already been - * completed. - *

+ *

Returns the names of the files which were selected out and therefore not ultimately included.

+ * + *

The names are relative to the base directory. This involves performing a slow scan if one has not already been + * completed.

* * @return the names of the files which were deselected. * @see #slowScan @@ -653,14 +645,10 @@ public String[] getExcludedDirectories() } /** - *

- * Returns the names of the directories which were selected out and therefore not ultimately included. - *

- *

- *

- * The names are relative to the base directory. This involves performing a slow scan if one has not already been - * completed. - *

+ *

Returns the names of the directories which were selected out and therefore not ultimately included.

+ * + *

The names are relative to the base directory. This involves performing a slow scan if one has not already been + * completed.

* * @return the names of the directories which were deselected. * @see #slowScan @@ -674,10 +662,9 @@ public String[] getDeselectedDirectories() } /** - * Checks whether a given file is a symbolic link. - *

- *

- * It doesn't really test for symbolic links but whether the canonical and absolute paths of the file are identical + *

Checks whether a given file is a symbolic link.

+ * + *

It doesn't really test for symbolic links but whether the canonical and absolute paths of the file are identical * - this may lead to false positives on some platforms. *

* @@ -700,12 +687,10 @@ public boolean isSymbolicLink( File parent, String name ) } /** - * Checks whether the parent of this file is a symbolic link. - *

- *

- * For java versions prior to 7 It doesn't really test for symbolic links but whether the canonical and absolute - * paths of the file are identical - this may lead to false positives on some platforms. - *

+ *

Checks whether the parent of this file is a symbolic link.

+ * + *

For java versions prior to 7 It doesn't really test for symbolic links but whether the canonical and absolute + * paths of the file are identical - this may lead to false positives on some platforms.

* * @param parent the parent directory of the file to test * @param name the name of the file to test. diff --git a/src/main/java/org/codehaus/plexus/util/FileUtils.java b/src/main/java/org/codehaus/plexus/util/FileUtils.java index 8d93c9cc..a784bf54 100644 --- a/src/main/java/org/codehaus/plexus/util/FileUtils.java +++ b/src/main/java/org/codehaus/plexus/util/FileUtils.java @@ -81,12 +81,11 @@ import java.util.Random; /** - * This class provides basic facilities for manipulating files and file paths. - *

+ *

This class provides basic facilities for manipulating files and file paths.

+ * *

Path-related methods

- *

- *

- * Methods exist to retrieve the components of a typical file path. For example + * + *

Methods exist to retrieve the components of a typical file path. For example * /www/hosted/mysite/index.html, can be broken into: *

    *
  • /www/hosted/mysite/ -- retrievable through {@link #getPath}
  • @@ -94,21 +93,19 @@ *
  • /www/hosted/mysite/index -- retrievable through {@link #removeExtension}
  • *
  • html -- retrievable through {@link #getExtension}
  • *
- * There are also methods to {@link #catPath concatenate two paths}, {@link #resolveFile resolve a path relative to a - * File} and {@link #normalize} a path. - *

- *

+ *

There are also methods to {@link #catPath concatenate two paths}, {@link #resolveFile resolve a path relative to a + * File} and {@link #normalize} a path.

+ *

File-related methods

- *

- * There are methods to create a {@link #toFile File from a URL}, copy a {@link #copyFileToDirectory File to a + * + *

There are methods to create a {@link #toFile File from a URL}, copy a {@link #copyFileToDirectory File to a * directory}, copy a {@link #copyFile File to another File}, copy a {@link #copyURLToFile URL's contents to a File}, as - * well as methods to {@link #deleteDirectory(File) delete} and {@link #cleanDirectory(File) clean} a directory. - *

- *

- * Common {@link java.io.File} manipulation routines. - *

- * Taken from the commons-utils repo. Also code from Alexandria's FileUtils. And from Avalon Excalibur's IO. And from - * Ant. + * well as methods to {@link #deleteDirectory(File) delete} and {@link #cleanDirectory(File) clean} a directory.

+ * + *

Common {@link java.io.File} manipulation routines.

+ * + *

Taken from the commons-utils repo. Also code from Alexandria's FileUtils. And from Avalon Excalibur's IO. And from + * Ant.

* * @author Kevin A. Burton * @author Scott Sanders @@ -601,11 +598,11 @@ public static File getFile( String fileName ) } /** - * Given a directory and an array of extensions return an array of compliant files. - *

- * TODO Should an ignore list be passed in? TODO Should a recurse flag be passed in? - *

- * The given extensions should be like "java" and not like ".java" + *

Given a directory and an array of extensions return an array of compliant files.

+ * + *

TODO Should an ignore list be passed in? TODO Should a recurse flag be passed in?

+ * + *

The given extensions should be like "java" and not like ".java"

* * @param directory The path of the directory. * @param extensions an array of expected extensions. @@ -828,9 +825,9 @@ public static URL[] toURLs( final File[] files ) * Remove extension from filename. ie * *
-     * foo.txt    --> foo
-     * a\b\c.jpg --> a\b\c
-     * a\b\c     --> a\b\c
+     * foo.txt    --> foo
+     * a\b\c.jpg  --> a\b\c
+     * a\b\c      --> a\b\c
      * 
* * @param filename the path of the file @@ -853,9 +850,9 @@ public static String removeExtension( final String filename ) * Get extension from filename. ie * *
-     * foo.txt    --> "txt"
-     * a\b\c.jpg --> "jpg"
-     * a\b\c     --> ""
+     * foo.txt    --> "txt"
+     * a\b\c.jpg  --> "jpg"
+     * a\b\c      --> ""
      * 
* * @param filename the path of the file @@ -870,8 +867,8 @@ public static String getExtension( final String filename ) * Remove path from filename. Equivalent to the unix command basename ie. * *
-     * a/b/c.txt --> c.txt
-     * a.txt     --> a.txt
+     * a/b/c.txt --> c.txt
+     * a.txt     --> a.txt
      * 
* * @param filepath the path of the file @@ -886,8 +883,8 @@ public static String removePath( final String filepath ) * Remove path from filename. ie. * *
-     * a/b/c.txt --> c.txt
-     * a.txt     --> a.txt
+     * a/b/c.txt --> c.txt
+     * a.txt     --> a.txt
      * 
* * @param filepath the path of the file @@ -910,8 +907,8 @@ public static String removePath( final String filepath, final char fileSeparator * Get path from filename. Roughly equivalent to the unix command dirname. ie. * *
-     * a/b/c.txt --> a/b
-     * a.txt     --> ""
+     * a/b/c.txt --> a/b
+     * a.txt     --> ""
      * 
* * @param filepath the filepath @@ -926,8 +923,8 @@ public static String getPath( final String filepath ) * Get path from filename. ie. * *
-     * a/b/c.txt --> a/b
-     * a.txt     --> ""
+     * a/b/c.txt --> a/b
+     * a.txt     --> ""
      * 
* * @param filepath the filepath @@ -1259,13 +1256,13 @@ private static void mkdirsFor( File destination ) * root. Eg: * *
-     * /foo//               -->     /foo/
-     * /foo/./              -->     /foo/
-     * /foo/../bar          -->     /bar
-     * /foo/../bar/         -->     /bar/
-     * /foo/../bar/../baz   -->     /baz
-     * //foo//./bar         -->     /foo/bar
-     * /../                 -->     null
+     * /foo//               -->     /foo/
+     * /foo/./              -->     /foo/
+     * /foo/../bar          -->     /bar
+     * /foo/../bar/         -->     /bar/
+     * /foo/../bar/../baz   -->     /baz
+     * //foo//./bar         -->     /foo/bar
+     * /../                 -->     null
      * 
* * @param path the path to normalize @@ -1317,14 +1314,15 @@ public static String normalize( final String path ) } /** - * Will concatenate 2 paths. Paths with .. will be properly handled. - *

- * Eg.,
- * /a/b/c + d = /a/b/d
- * /a/b/c + ../d = /a/d
- *

- *

- * Thieved from Tomcat sources... + *

Will concatenate 2 paths. Paths with .. will be properly handled.

+ * + * Eg., + *
+     * /a/b/c + d = /a/b/d
+     * /a/b/c + ../d = /a/d
+     * 
+ + *

Thieved from Tomcat sources...

* * @param lookupPath a path * @param path the path to concatenate @@ -2019,8 +2017,8 @@ public static void copyDirectory( File sourceDirectory, File destinationDirector } /** - * Copies a entire directory layout : no files will be copied only directories - *

+ *

Copies a entire directory layout : no files will be copied only directories

+ * * Note: *
    *
  • It will include empty directories. @@ -2095,8 +2093,8 @@ public static void copyDirectoryLayout( File sourceDirectory, File destinationDi } /** - * Copies a entire directory structure. - *

    + *

    Copies a entire directory structure.

    + * * Note: *
      *
    • It will include empty directories. @@ -2114,8 +2112,8 @@ public static void copyDirectoryStructure( File sourceDirectory, File destinatio } /** - * Copies an entire directory structure but only source files with timestamp later than the destinations'. - *

      + *

      Copies an entire directory structure but only source files with timestamp later than the destinations'.

      + * * Note: *
        *
      • It will include empty directories. @@ -2205,12 +2203,10 @@ else if ( file.isDirectory() ) } /** - * Renames a file, even if that involves crossing file system boundaries. - *

        - *

        - * This will remove to (if it exists), ensure that to's parent directory exists and move - * from, which involves deleting from as well. - *

        + *

        Renames a file, even if that involves crossing file system boundaries.

        + * + *

        This will remove to (if it exists), ensure that to's parent directory exists and move + * from, which involves deleting from as well.

        * * @param from the file to move * @param to the new file name @@ -2242,22 +2238,17 @@ public static void rename( File from, File to ) } /** - * Create a temporary file in a given directory. - *

        - *

        - * The file denoted by the returned abstract pathname did not exist before this method was invoked, any subsequent - * invocation of this method will yield a different file name. - *

        - *

        - * The filename is prefixNNNNNsuffix where NNNN is a random number - *

        - *

        - * This method is different to {@link File#createTempFile(String, String, File)} of JDK 1.2 as it doesn't create the - * file itself. It uses the location pointed to by java.io.tmpdir when the parentDir attribute is null. - *

        - *

        - * To delete automatically the file created by this method, use the {@link File#deleteOnExit()} method. - *

        + *

        Create a temporary file in a given directory.

        + * + *

        The file denoted by the returned abstract pathname did not exist before this method was invoked, any subsequent + * invocation of this method will yield a different file name.

        + * + *

        The filename is prefixNNNNNsuffix where NNNN is a random number

        + * + *

        This method is different to {@link File#createTempFile(String, String, File)} of JDK 1.2 as it doesn't create the + * file itself. It uses the location pointed to by java.io.tmpdir when the parentDir attribute is null.

        + * + *

        To delete automatically the file created by this method, use the {@link File#deleteOnExit()} method.

        * * @param prefix prefix before the random number * @param suffix file extension; include the '.' @@ -2418,7 +2409,7 @@ public static List loadFile( File file ) /** * For Windows OS, check if the file name contains any of the following characters: - * ":", "*", "?", "\"", "<", ">", "|" + * ":", "*", "?", "\"", "<", ">", "|" * * @param f not null file * @return false if the file path contains any of forbidden Windows characters, true if diff --git a/src/main/java/org/codehaus/plexus/util/LineOrientedInterpolatingReader.java b/src/main/java/org/codehaus/plexus/util/LineOrientedInterpolatingReader.java index 4af790c4..afdc7bcd 100644 --- a/src/main/java/org/codehaus/plexus/util/LineOrientedInterpolatingReader.java +++ b/src/main/java/org/codehaus/plexus/util/LineOrientedInterpolatingReader.java @@ -44,15 +44,13 @@ *
      • if the enclosed string is not found in the keyword Map, then no substitution is made; the token text is * passed through unaltered.
      • *
      - *

      - * A token in the incoming character stream may be escaped by prepending an "escape sequence" which is + * + *

      A token in the incoming character stream may be escaped by prepending an "escape sequence" which is * specified to the constructor. An escaped token is passed through as written, with the escape sequence removed. This - * allows things which would look like tokens to be read literally rather than interpolated. - *

      + * allows things which would look like tokens to be read literally rather than interpolated.

      * * @author jdcasey Created on Feb 3, 2005 * @see InterpolationFilterReader - * @see org.codehaus.plexus.interpolation */ public class LineOrientedInterpolatingReader extends FilterReader diff --git a/src/main/java/org/codehaus/plexus/util/MatchPattern.java b/src/main/java/org/codehaus/plexus/util/MatchPattern.java index ede49b74..4bcc6522 100644 --- a/src/main/java/org/codehaus/plexus/util/MatchPattern.java +++ b/src/main/java/org/codehaus/plexus/util/MatchPattern.java @@ -22,9 +22,9 @@ import java.util.StringTokenizer; /** - * Describes a match target for SelectorUtils. - *

      - * Significantly more efficient than using strings, since re-evaluation and re-tokenizing is avoided. + *

      Describes a match target for SelectorUtils.

      + * + *

      Significantly more efficient than using strings, since re-evaluation and re-tokenizing is avoided.

      * * @author Kristian Rosenvold */ diff --git a/src/main/java/org/codehaus/plexus/util/MatchPatterns.java b/src/main/java/org/codehaus/plexus/util/MatchPatterns.java index 3dffd545..f871f8e1 100644 --- a/src/main/java/org/codehaus/plexus/util/MatchPatterns.java +++ b/src/main/java/org/codehaus/plexus/util/MatchPatterns.java @@ -19,9 +19,9 @@ private MatchPatterns( MatchPattern[] patterns ) } /** - * Checks these MatchPatterns against a specified string. - *

      - * Uses far less string tokenization than any of the alternatives. + *

      Checks these MatchPatterns against a specified string.

      + * + *

      Uses far less string tokenization than any of the alternatives.

      * * @param name The name to look for * @param isCaseSensitive If the comparison is case sensitive diff --git a/src/main/java/org/codehaus/plexus/util/Os.java b/src/main/java/org/codehaus/plexus/util/Os.java index 19be09cc..fce9f5d7 100644 --- a/src/main/java/org/codehaus/plexus/util/Os.java +++ b/src/main/java/org/codehaus/plexus/util/Os.java @@ -156,8 +156,8 @@ private static Set setValidFamilies() /** * Sets the desired OS family type * - * @param f The OS family type desired
      - * Possible values:
      + * @param f The OS family type desired
      + * Possible values: *
        *
      • dos
      • *
      • mac
      • diff --git a/src/main/java/org/codehaus/plexus/util/PathTool.java b/src/main/java/org/codehaus/plexus/util/PathTool.java index d9b1ec13..a64556c7 100644 --- a/src/main/java/org/codehaus/plexus/util/PathTool.java +++ b/src/main/java/org/codehaus/plexus/util/PathTool.java @@ -30,13 +30,13 @@ public class PathTool { /** - * Determines the relative path of a filename from a base directory. This method is useful in building relative + *

        Determines the relative path of a filename from a base directory. This method is useful in building relative * links within pages of a web site. It provides similar functionality to Anakia's $relativePath * context variable. The arguments to this method may contain either forward or backward slashes as file separators. * The relative path returned is formed using forward slashes as it is expected this path is to be used as a link in - * a web page (again mimicking Anakia's behavior). - *

        - * This method is thread-safe.
        + * a web page (again mimicking Anakia's behavior).

        + * + *

        This method is thread-safe.

        * *
              * PathTool.getRelativePath( null, null )                                   = ""
        @@ -85,13 +85,13 @@ public static final String getRelativePath( String basedir, String filename )
             }
         
             /**
        -     * Determines the relative path of a filename. This method is useful in building relative links within pages of a
        +     * 

        Determines the relative path of a filename. This method is useful in building relative links within pages of a * web site. It provides similar functionality to Anakia's $relativePath context variable. The argument * to this method may contain either forward or backward slashes as file separators. The relative path returned is * formed using forward slashes as it is expected this path is to be used as a link in a web page (again mimicking - * Anakia's behavior). - *

        - * This method is thread-safe. + * Anakia's behavior).

        + * + *

        This method is thread-safe.

        * * @param filename The filename to be parsed. * @return The relative path of the filename. This value is not terminated with a forward slash. A zero-length @@ -123,11 +123,11 @@ public static final String getRelativePath( String filename ) } /** - * Determines the directory component of a filename. This is useful within DVSL templates when used in conjunction + *

        Determines the directory component of a filename. This is useful within DVSL templates when used in conjunction * with the DVSL's $context.getAppValue("infilename") to get the current directory that is currently - * being processed. - *

        - * This method is thread-safe.
        + * being processed.

        + * + *

        This method is thread-safe.

        * *
              * PathTool.getDirectoryComponent( null )                                   = ""
        @@ -159,7 +159,7 @@ public static final String getDirectoryComponent( String filename )
             }
         
             /**
        -     * Calculates the appropriate link given the preferred link and the relativePath of the document. 
        + * Calculates the appropriate link given the preferred link and the relativePath of the document. * *
              * PathTool.calculateLink( "/index.html", "../.." )                                        = "../../index.html"
        @@ -227,7 +227,7 @@ public static final String calculateLink( String link, String relativePath )
             }
         
             /**
        -     * This method can calculate the relative path between two paths on a web site. 
        + * This method can calculate the relative path between two paths on a web site. * *
              * PathTool.getRelativeWebPath( null, null )                                          = ""
        @@ -261,7 +261,7 @@ public static final String getRelativeWebPath( final String oldPath, final Strin
             }
         
             /**
        -     * This method can calculate the relative path between two paths on a file system. 
        + * This method can calculate the relative path between two paths on a file system. * *
              * PathTool.getRelativeFilePath( null, null )                                   = ""
        diff --git a/src/main/java/org/codehaus/plexus/util/SelectorUtils.java b/src/main/java/org/codehaus/plexus/util/SelectorUtils.java
        index e4055642..950524ab 100644
        --- a/src/main/java/org/codehaus/plexus/util/SelectorUtils.java
        +++ b/src/main/java/org/codehaus/plexus/util/SelectorUtils.java
        @@ -60,14 +60,11 @@
         import java.util.StringTokenizer;
         
         /**
        - * 

        - * This is a utility class used by selectors and DirectoryScanner. The functionality more properly belongs just to + *

        This is a utility class used by selectors and DirectoryScanner. The functionality more properly belongs just to * selectors, but unfortunately DirectoryScanner exposed these as protected methods. Thus we have to support any - * subclasses of DirectoryScanner that may access these methods. - *

        - *

        - * This is a Singleton. - *

        + * subclasses of DirectoryScanner that may access these methods.

        + * + *

        This is a Singleton.

        * * @author Arnout J. Kuiper ajkuiper@wxs.nl * @author Magesh Umasankar @@ -104,10 +101,10 @@ public static SelectorUtils getInstance() } /** - * Tests whether or not a given path matches the start of a given pattern up to the first "**". - *

        - * This is not a general purpose test and should only be used if you can live with false positives. For example, - * pattern=**\a and str=b will yield true. + *

        Tests whether or not a given path matches the start of a given pattern up to the first "**".

        + * + *

        This is not a general purpose test and should only be used if you can live with false positives. For example, + * pattern=**\a and str=b will yield true.

        * * @param pattern The pattern to match against. Must not be null. * @param str The path to match, as a String. Must not be null. @@ -119,10 +116,10 @@ public static boolean matchPatternStart( String pattern, String str ) } /** - * Tests whether or not a given path matches the start of a given pattern up to the first "**". - *

        - * This is not a general purpose test and should only be used if you can live with false positives. For example, - * pattern=**\a and str=b will yield true. + *

        Tests whether or not a given path matches the start of a given pattern up to the first "**".

        + * + *

        This is not a general purpose test and should only be used if you can live with false positives. For example, + * pattern=**\a and str=b will yield true.

        * * @param pattern The pattern to match against. Must not be null. * @param str The path to match, as a String. Must not be null. diff --git a/src/main/java/org/codehaus/plexus/util/StringInputStream.java b/src/main/java/org/codehaus/plexus/util/StringInputStream.java index 7f32c351..84400070 100644 --- a/src/main/java/org/codehaus/plexus/util/StringInputStream.java +++ b/src/main/java/org/codehaus/plexus/util/StringInputStream.java @@ -62,7 +62,7 @@ /** * Wraps a String as an InputStream. Note that data will be lost for characters not in ISO Latin 1, as a simple - * char->byte mapping is assumed. + * char->byte mapping is assumed. * * @author Magesh Umasankar * @deprecated As of version 1.5.2 this class should no longer be used because it does not properly handle character diff --git a/src/main/java/org/codehaus/plexus/util/StringUtils.java b/src/main/java/org/codehaus/plexus/util/StringUtils.java index a4ad172e..4092c401 100644 --- a/src/main/java/org/codehaus/plexus/util/StringUtils.java +++ b/src/main/java/org/codehaus/plexus/util/StringUtils.java @@ -157,7 +157,7 @@ public static String deleteWhitespace( String str ) /** *

        - * Checks if a String is non null and is not empty (length > 0). + * Checks if a String is non null and is not empty (length > 0). *

        * * @param str the String to check @@ -1263,7 +1263,7 @@ else if ( ch < 32 ) * @param str String to repeat * @param repeat number of times to repeat str * @return String with repeated String - * @throws NegativeArraySizeException if repeat < 0 + * @throws NegativeArraySizeException if repeat < 0 * @throws NullPointerException if str is null */ public static String repeat( String str, int repeat ) @@ -2199,7 +2199,7 @@ public static String abbreviate( String s, int offset, int maxWidth ) * Compare two strings, and return the portion where they differ. (More precisely, return the remainder of the * second string, starting from where it's different from the first.) *

        - * E.g. strdiff("i am a machine", "i am a robot") -> "robot" + * E.g. strdiff("i am a machine", "i am a robot") -> "robot" * * @return the portion of s2 where it differs from s1; returns the empty string ("") if they are equal **/ @@ -2216,7 +2216,7 @@ public static String difference( String s1, String s2 ) /** * Compare two strings, and return the index at which the strings begin to differ. *

        - * E.g. strdiff("i am a machine", "i am a robot") -> 7 + * E.g. strdiff("i am a machine", "i am a robot") -> 7 *

        * * @return the index where s2 and s1 begin to differ; -1 if they are equal diff --git a/src/main/java/org/codehaus/plexus/util/SweeperPool.java b/src/main/java/org/codehaus/plexus/util/SweeperPool.java index fb5e72b5..0aeca99f 100644 --- a/src/main/java/org/codehaus/plexus/util/SweeperPool.java +++ b/src/main/java/org/codehaus/plexus/util/SweeperPool.java @@ -53,22 +53,19 @@ public class SweeperPool // private Vector used; /** - *

        * There are a number of settings to control how the pool operates. *

          *
        • minSize - this is the size the pool is trimmed to
        • *
        • triggerSize - this determines if the pool is trimmed when the sweeper runs. If the pool size is - * greater or equal than this value then the pool is trimmed to minSize. + * greater or equal than this value then the pool is trimmed to minSize.
        • *
        • maxSize - if the pool has reached this size, any objects added are immediately disposed. If the * pool is this size when the sweeper runs, then the pool is also trimmed to minSize irrespective of * the triggerSize.
        • *
        • sweepInterval - how often the sweeper runs. Is actually the time since the sweeper last finished * a pass. 0 if the sweeper should not run.
        • *
        - *

        - *

        - * Any value less than 0 is automatically converted to 0 - *

        + + *

        Any value less than 0 is automatically converted to 0

        */ public SweeperPool( int maxSize, int minSize, int intialCapacity, int sweepInterval, int triggerSize ) { diff --git a/src/main/java/org/codehaus/plexus/util/TypeFormat.java b/src/main/java/org/codehaus/plexus/util/TypeFormat.java index e464da6e..f950003b 100644 --- a/src/main/java/org/codehaus/plexus/util/TypeFormat.java +++ b/src/main/java/org/codehaus/plexus/util/TypeFormat.java @@ -14,7 +14,6 @@ * Methods from this utility class do not create temporary objects and are typically faster than standard library * methods (e.g {@link #parseDouble} is up to 15x faster than Double.parseDouble). *

        - *

        * For class instances, formatting is typically performed using specialized java.text.Format * (Locale sensitive) and/or using conventional methods (class sensitive). For example: * @@ -27,7 +26,6 @@ * } * } *

        - *

        *

        * This class is public domain (not copyrighted). *

        diff --git a/src/main/java/org/codehaus/plexus/util/WriterFactory.java b/src/main/java/org/codehaus/plexus/util/WriterFactory.java index fe818835..229f1082 100644 --- a/src/main/java/org/codehaus/plexus/util/WriterFactory.java +++ b/src/main/java/org/codehaus/plexus/util/WriterFactory.java @@ -127,7 +127,6 @@ public static XmlStreamWriter newXmlWriter( File file ) * * @param out not null output stream. * @return a writer instance for the output stream using the default platform charset. - * @throws IOException if any. * @see Charset#defaultCharset() */ public static Writer newPlatformWriter( OutputStream out ) diff --git a/src/main/java/org/codehaus/plexus/util/cli/CommandLineUtils.java b/src/main/java/org/codehaus/plexus/util/cli/CommandLineUtils.java index 0c965975..43c5c817 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/CommandLineUtils.java +++ b/src/main/java/org/codehaus/plexus/util/cli/CommandLineUtils.java @@ -97,7 +97,6 @@ public static int executeCommandLine( Commandline cl, InputStream systemIn, Stre * @param timeoutInSeconds Positive integer to specify timeout, zero and negative integers for no timeout. * @return A return value, see {@link Process#exitValue()} * @throws CommandLineException or CommandLineTimeOutException if time out occurs - * @noinspection ThrowableResultOfMethodCallIgnored */ public static int executeCommandLine( Commandline cl, InputStream systemIn, StreamConsumer systemOut, StreamConsumer systemErr, int timeoutInSeconds ) @@ -120,7 +119,6 @@ public static int executeCommandLine( Commandline cl, InputStream systemIn, Stre * must be called on this to be sure the forked process has terminated, no guarantees is made about any * internal state before after the completion of the call statements * @throws CommandLineException or CommandLineTimeOutException if time out occurs - * @noinspection ThrowableResultOfMethodCallIgnored */ public static CommandLineCallable executeCommandLineAsCallable( final Commandline cl, final InputStream systemIn, final StreamConsumer systemOut, diff --git a/src/main/java/org/codehaus/plexus/util/cli/Commandline.java b/src/main/java/org/codehaus/plexus/util/cli/Commandline.java index 58ddfe35..2affbb03 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/Commandline.java +++ b/src/main/java/org/codehaus/plexus/util/cli/Commandline.java @@ -67,21 +67,17 @@ import java.io.File; import java.io.IOException; import java.util.Collections; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import java.util.Vector; /** - *

        - * Commandline objects help handling command lines specifying processes to execute. - *

        - *

        - * The class can be used to define a command line as nested elements or as a helper to define a command line by an - * application. - *

        - *

        + *

        Commandline objects help handling command lines specifying processes to execute.

        + * + *

        The class can be used to define a command line as nested elements or as a helper to define a command line by an + * application.

        + * * * <someelement>
        *   <acommandline executable="/executable/to/run">
        @@ -91,11 +87,9 @@ *   </acommandline>
        * </someelement>
        *
        - *

        - *

        - * The element someelement must provide a method createAcommandline which returns an instance - * of this class. - *

        + * + *

        The element someelement must provide a method createAcommandline which returns an instance + * of this class.

        * * @author thomas.haas@softwired-inc.com * @author Stefan Bodewig @@ -241,11 +235,9 @@ public class Marker } /** - * Return the number of arguments that preceded this marker. - *

        - *

        - * The name of the executable - if set - is counted as the very first argument. - *

        + *

        Return the number of arguments that preceded this marker.

        + * + *

        The name of the executable - if set - is counted as the very first argument.

        */ public int getPosition() { @@ -288,12 +280,10 @@ private void setDefaultShell() } /** - * Creates an argument object. - *

        - *

        - * Each commandline object has at most one instance of the argument class. This method calls - * this.createArgument(false). - *

        + *

        Creates an argument object.

        + * + *

        Each commandline object has at most one instance of the argument class. This method calls + * this.createArgument(false).

        * * @return the argument object. * @see #createArgument(boolean) @@ -305,11 +295,9 @@ public Argument createArgument() } /** - * Creates an argument object and adds it to our list of args. - *

        - *

        - * Each commandline object has at most one instance of the argument class. - *

        + *

        Creates an argument object and adds it to our list of args.

        + * + *

        Each commandline object has at most one instance of the argument class.

        * * @param insertAtStart if true, the argument is inserted at the beginning of the list of args, otherwise it is * appended. @@ -330,12 +318,10 @@ public Argument createArgument( boolean insertAtStart ) } /** - * Creates an argument object. - *

        - *

        - * Each commandline object has at most one instance of the argument class. This method calls - * this.createArgument(false). - *

        + *

        Creates an argument object.

        + * + *

        Each commandline object has at most one instance of the argument class. This method calls + * this.createArgument(false).

        * * @return the argument object. * @see #createArgument(boolean) @@ -346,11 +332,9 @@ public Arg createArg() } /** - * Creates an argument object and adds it to our list of args. - *

        - *

        - * Each commandline object has at most one instance of the argument class. - *

        + *

        Creates an argument object and adds it to our list of args.

        + * + *

        Each commandline object has at most one instance of the argument class.

        * * @param insertAtStart if true, the argument is inserted at the beginning of the list of args, otherwise it is * appended. @@ -372,7 +356,6 @@ public Arg createArg( boolean insertAtStart ) /** * Adds an argument object to our list of args. * - * @return the argument object. * @see #addArg(Arg,boolean) */ public void addArg( Arg argument ) @@ -495,7 +478,7 @@ public String[] getEnvironmentVariables() } /** - * Returns the executable and all defined arguments.
        + * Returns the executable and all defined arguments.
        * For Windows Family, {@link Commandline#getShellCommandline()} is returned */ public String[] getCommandline() @@ -594,10 +577,9 @@ public void clearArgs() } /** - * Return a marker. - *

        - *

        - * This marker can be used to locate a position on the commandline - to insert something for example - when all + *

        Return a marker.

        + * + *

        This marker can be used to locate a position on the commandline - to insert something for example - when all * parameters have been set. *

        */ diff --git a/src/main/java/org/codehaus/plexus/util/cli/shell/Shell.java b/src/main/java/org/codehaus/plexus/util/cli/shell/Shell.java index 4a2451e5..75b5f80e 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/shell/Shell.java +++ b/src/main/java/org/codehaus/plexus/util/cli/shell/Shell.java @@ -24,13 +24,11 @@ import java.util.List; /** - *

        * Class that abstracts the Shell functionality, with subclasses for shells that behave particularly, like *

          *
        • command.com
        • *
        • cmd.exe
        • *
        - *

        * * @author Carlos Sanchez * @since 1.2 diff --git a/src/main/java/org/codehaus/plexus/util/dag/DAG.java b/src/main/java/org/codehaus/plexus/util/dag/DAG.java index 7a3f4a5b..19fe67c8 100644 --- a/src/main/java/org/codehaus/plexus/util/dag/DAG.java +++ b/src/main/java/org/codehaus/plexus/util/dag/DAG.java @@ -28,7 +28,7 @@ * * @author Michal Maczka * @version $Id$ - * @todo this class should be renamed from DAG to Dag + * TODO this class should be renamed from DAG to Dag */ public class DAG implements Cloneable, Serializable @@ -223,7 +223,7 @@ public Object clone() /** * Indicates if there is at least one edge leading to or from vertex of given label * - * @return true if this vertex is connected with other vertex,false otherwise + * @return true if this vertex is connected with other vertex,false otherwise */ public boolean isConnected( final String label ) { diff --git a/src/main/java/org/codehaus/plexus/util/dag/Vertex.java b/src/main/java/org/codehaus/plexus/util/dag/Vertex.java index aa177c97..9e5260df 100644 --- a/src/main/java/org/codehaus/plexus/util/dag/Vertex.java +++ b/src/main/java/org/codehaus/plexus/util/dag/Vertex.java @@ -139,7 +139,7 @@ public List getParentLabels() /** * Indicates if given vertex has no child * - * @return true if this vertex has no child, false otherwise + * @return true if this vertex has no child, false otherwise */ public boolean isLeaf() { @@ -149,7 +149,7 @@ public boolean isLeaf() /** * Indicates if given vertex has no parent * - * @return true if this vertex has no parent, false otherwise + * @return true if this vertex has no parent, false otherwise */ public boolean isRoot() { @@ -159,7 +159,7 @@ public boolean isRoot() /** * Indicates if there is at least one edee leading to or from given vertex * - * @return true if this vertex is connected with other vertex,false otherwise + * @return true if this vertex is connected with other vertex,false otherwise */ public boolean isConnected() { diff --git a/src/main/java/org/codehaus/plexus/util/introspection/ClassMap.java b/src/main/java/org/codehaus/plexus/util/introspection/ClassMap.java index efd22208..387dc68a 100644 --- a/src/main/java/org/codehaus/plexus/util/introspection/ClassMap.java +++ b/src/main/java/org/codehaus/plexus/util/introspection/ClassMap.java @@ -72,12 +72,12 @@ Class getCachedClass() } /** - * Find a Method using the methodKey provided. - *

        - * Look in the methodMap for an entry. If found, it'll either be a CACHE_MISS, in which case we simply give up, or - * it'll be a Method, in which case, we return it. - *

        - * If nothing is found, then we must actually go and introspect the method from the MethodMap. + *

        Find a Method using the methodKey provided.

        + * + *

        Look in the methodMap for an entry. If found, it'll either be a CACHE_MISS, in which case we simply give up, or + * it'll be a Method, in which case, we return it.

        + * + *

        If nothing is found, then we must actually go and introspect the method from the MethodMap.

        */ public Method findMethod( String name, Object[] params ) throws MethodMap.AmbiguousException diff --git a/src/main/java/org/codehaus/plexus/util/introspection/ReflectionValueExtractor.java b/src/main/java/org/codehaus/plexus/util/introspection/ReflectionValueExtractor.java index 8e03f14d..e4603f3d 100644 --- a/src/main/java/org/codehaus/plexus/util/introspection/ReflectionValueExtractor.java +++ b/src/main/java/org/codehaus/plexus/util/introspection/ReflectionValueExtractor.java @@ -141,16 +141,15 @@ private ReflectionValueExtractor() } /** - *

        - * The implementation supports indexed, nested and mapped properties. - *

        + *

        The implementation supports indexed, nested and mapped properties.

        + * *
          *
        • nested properties should be defined by a dot, i.e. "user.address.street"
        • *
        • indexed properties (java.util.List or array instance) should be contains (\\w+)\\[(\\d+)\\] * pattern, i.e. "user.addresses[1].street"
        • *
        • mapped properties should be contains (\\w+)\\((.+)\\) pattern, i.e. * "user.addresses(myAddress).street"
        • - *
            + *
          * * @param expression not null expression * @param root not null object @@ -164,16 +163,15 @@ public static Object evaluate( String expression, Object root ) } /** - *

          - * The implementation supports indexed, nested and mapped properties. - *

          + *

          The implementation supports indexed, nested and mapped properties.

          + * *
            *
          • nested properties should be defined by a dot, i.e. "user.address.street"
          • *
          • indexed properties (java.util.List or array instance) should be contains (\\w+)\\[(\\d+)\\] * pattern, i.e. "user.addresses[1].street"
          • *
          • mapped properties should be contains (\\w+)\\((.+)\\) pattern, i.e. * "user.addresses(myAddress).street"
          • - *
              + *
            * * @param expression not null expression * @param root not null object diff --git a/src/main/java/org/codehaus/plexus/util/xml/XmlReader.java b/src/main/java/org/codehaus/plexus/util/xml/XmlReader.java index 734d47c7..2cd639e7 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/XmlReader.java +++ b/src/main/java/org/codehaus/plexus/util/xml/XmlReader.java @@ -34,23 +34,22 @@ import java.text.MessageFormat; /** - * Character stream that handles (or at least attempts to) all the necessary Voodo to figure out the charset encoding of - * the XML document within the stream. - *

            - * IMPORTANT: This class is not related in any way to the org.xml.sax.XMLReader. This one IS a character stream. - *

            - * All this has to be done without consuming characters from the stream, if not the XML parser will not recognized the + *

            Character stream that handles (or at least attempts to) all the necessary Voodo to figure out the charset encoding of + * the XML document within the stream.

            + * + *

            IMPORTANT: This class is not related in any way to the org.xml.sax.XMLReader. This one IS a character stream.

            + * + *

            All this has to be done without consuming characters from the stream, if not the XML parser will not recognized the * document as a valid XML. This is not 100% true, but it's close enough (UTF-8 BOM is not handled by all parsers right - * now, XmlReader handles it and things work in all parsers). - *

            - * The XmlReader class handles the charset encoding of XML documents in Files, raw streams and HTTP streams by offering - * a wide set of constructors. - *

            - * By default the charset encoding detection is lenient, the constructor with the lenient flag can be used for an script + * now, XmlReader handles it and things work in all parsers).

            + * + *

            The XmlReader class handles the charset encoding of XML documents in Files, raw streams and HTTP streams by offering + * a wide set of constructors.

            + * + *

            By default the charset encoding detection is lenient, the constructor with the lenient flag can be used for an script * (following HTTP MIME and XML specifications). All this is nicely explained by Mark Pilgrim in his blog, * Determining the character encoding of a - * feed. - *

            + * feed.

            * * @author Alejandro Abdelnur * @version revision 1.17 taken on 26/06/2007 from Rome (see @@ -84,13 +83,12 @@ public class XmlReader private String _defaultEncoding; /** - * Sets the default encoding to use if none is set in HTTP content-type, XML prolog and the rules based on - * content-type are not adequate. - *

            - * If it is set to NULL the content-type based rules are used. - *

            - * By default it is NULL. - *

            + *

            Sets the default encoding to use if none is set in HTTP content-type, XML prolog and the rules based on + * content-type are not adequate.

            + * + *

            If it is set to NULL the content-type based rules are used.

            + * + *

            By default it is NULL.

            * * @param encoding charset encoding to default to. */ @@ -100,11 +98,10 @@ public static void setDefaultEncoding( String encoding ) } /** - * Returns the default encoding to use if none is set in HTTP content-type, XML prolog and the rules based on - * content-type are not adequate. - *

            - * If it is NULL the content-type based rules are used. - *

            + *

            Returns the default encoding to use if none is set in HTTP content-type, XML prolog and the rules based on + * content-type are not adequate.

            + * + *

            If it is NULL the content-type based rules are used.

            * * @return the default encoding to use. */ diff --git a/src/main/java/org/codehaus/plexus/util/xml/Xpp3Dom.java b/src/main/java/org/codehaus/plexus/util/xml/Xpp3Dom.java index 3467ab4c..e10498f1 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/Xpp3Dom.java +++ b/src/main/java/org/codehaus/plexus/util/xml/Xpp3Dom.java @@ -48,6 +48,11 @@ public class Xpp3Dom protected Xpp3Dom parent; + /** + * @since 3.2.0 + */ + protected Object inputLocation; + private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final Xpp3Dom[] EMPTY_DOM_ARRAY = new Xpp3Dom[0]; @@ -86,6 +91,15 @@ public Xpp3Dom( String name ) childMap = new HashMap(); } + /** + * @since 3.2.0 + */ + public Xpp3Dom( String name, Object inputLocation ) + { + this( name ); + this.inputLocation = inputLocation; + } + /** * Copy constructor. */ @@ -100,6 +114,7 @@ public Xpp3Dom( Xpp3Dom src ) public Xpp3Dom( Xpp3Dom src, String name ) { this.name = name; + this.inputLocation = src.inputLocation; int childCount = src.getChildCount(); @@ -278,6 +293,26 @@ public void setParent( Xpp3Dom parent ) this.parent = parent; } + // ---------------------------------------------------------------------- + // Input location handling + // ---------------------------------------------------------------------- + + /** + * @since 3.2.0 + */ + public Object getInputLocation() + { + return inputLocation; + } + + /** + * @since 3.2.0 + */ + public void setInputLocation( Object inputLocation ) + { + this.inputLocation = inputLocation; + } + // ---------------------------------------------------------------------- // Helpers // ---------------------------------------------------------------------- @@ -296,23 +331,41 @@ public void writeToSerializer( String namespace, XmlSerializer serializer ) } /** - * Merges one DOM into another, given a specific algorithm and possible override points for that algorithm. The - * algorithm is as follows: 1. if the recessive DOM is null, there is nothing to do...return. 2. Determine whether - * the dominant node will suppress the recessive one (flag=mergeSelf). A. retrieve the 'combine.self' attribute on - * the dominant node, and try to match against 'override'... if it matches 'override', then set mergeSelf == - * false...the dominant node suppresses the recessive one completely. B. otherwise, use the default value for - * mergeSelf, which is true...this is the same as specifying 'combine.self' == 'merge' as an attribute of the - * dominant root node. 3. If mergeSelf == true A. if the dominant root node's value is empty, set it to the - * recessive root node's value B. For each attribute in the recessive root node which is not set in the dominant - * root node, set it. C. Determine whether children from the recessive DOM will be merged or appended to the - * dominant DOM as siblings (flag=mergeChildren). i. if childMergeOverride is set (non-null), use that value - * (true/false) ii. retrieve the 'combine.children' attribute on the dominant node, and try to match against - * 'append'...if it matches 'append', then set mergeChildren == false...the recessive children will be appended as - * siblings of the dominant children. iii. otherwise, use the default value for mergeChildren, which is true...this - * is the same as specifying 'combine.children' == 'merge' as an attribute on the dominant root node. D. Iterate - * through the recessive children, and: i. if mergeChildren == true and there is a corresponding dominant child - * (matched by element name), merge the two. ii. otherwise, add the recessive child as a new child on the dominant - * root node. + * Merges one DOM into another, given a specific algorithm and possible override points for that algorithm.

            + * The algorithm is as follows: + *

              + *
            1. if the recessive DOM is null, there is nothing to do... return.
            2. + *
            3. Determine whether the dominant node will suppress the recessive one (flag=mergeSelf). + *
                + *
              1. retrieve the 'combine.self' attribute on the dominant node, and try to match against 'override'... + * if it matches 'override', then set mergeSelf == false...the dominant node suppresses the recessive one + * completely.
              2. + *
              3. otherwise, use the default value for mergeSelf, which is true...this is the same as specifying + * 'combine.self' == 'merge' as an attribute of the dominant root node.
              4. + *
            4. + *
            5. If mergeSelf == true + *
                + *
              1. if the dominant root node's value is empty, set it to the recessive root node's value
              2. + *
              3. For each attribute in the recessive root node which is not set in the dominant root node, set it.
              4. + *
              5. Determine whether children from the recessive DOM will be merged or appended to the dominant DOM as + * siblings (flag=mergeChildren). + *
                  + *
                1. if childMergeOverride is set (non-null), use that value (true/false)
                2. + *
                3. retrieve the 'combine.children' attribute on the dominant node, and try to match against + * 'append'...
                4. + *
                5. if it matches 'append', then set mergeChildren == false...the recessive children will be appended as + * siblings of the dominant children.
                6. + *
                7. otherwise, use the default value for mergeChildren, which is true...this is the same as specifying + * 'combine.children' == 'merge' as an attribute on the dominant root node.
                8. + *
              6. + *
              7. Iterate through the recessive children, and: + *
                  + *
                1. if mergeChildren == true and there is a corresponding dominant child (matched by element name), + * merge the two.
                2. + *
                3. otherwise, add the recessive child as a new child on the dominant root node.
                4. + *
              8. + *
            6. + *
            */ private static void mergeIntoXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive, Boolean childMergeOverride ) { @@ -333,9 +386,10 @@ private static void mergeIntoXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive, Boole if ( mergeSelf ) { - if ( isEmpty( dominant.getValue() ) ) + if ( isEmpty( dominant.getValue() ) && !isEmpty( recessive.getValue() ) ) { dominant.setValue( recessive.getValue() ); + dominant.setInputLocation( recessive.getInputLocation() ); } String[] recessiveAttrs = recessive.getAttributeNames(); diff --git a/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomBuilder.java b/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomBuilder.java index 3f8ce989..ffe108d5 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomBuilder.java +++ b/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomBuilder.java @@ -37,7 +37,16 @@ public class Xpp3DomBuilder public static Xpp3Dom build( Reader reader ) throws XmlPullParserException, IOException { - return build( reader, DEFAULT_TRIM ); + return build( reader, null ); + } + + /** + * @since 3.2.0 + */ + public static Xpp3Dom build( Reader reader, InputLocationBuilder locationBuilder ) + throws XmlPullParserException, IOException + { + return build( reader, DEFAULT_TRIM, locationBuilder ); } public static Xpp3Dom build( InputStream is, String encoding ) @@ -68,13 +77,22 @@ public static Xpp3Dom build( InputStream is, String encoding, boolean trim ) public static Xpp3Dom build( Reader reader, boolean trim ) throws XmlPullParserException, IOException + { + return build( reader, trim, null ); + } + + /** + * @since 3.2.0 + */ + public static Xpp3Dom build( Reader reader, boolean trim, InputLocationBuilder locationBuilder ) + throws XmlPullParserException, IOException { try { final XmlPullParser parser = new MXParser(); parser.setInput( reader ); - final Xpp3Dom xpp3Dom = build( parser, trim ); + final Xpp3Dom xpp3Dom = build( parser, trim, locationBuilder ); reader.close(); reader = null; @@ -94,6 +112,15 @@ public static Xpp3Dom build( XmlPullParser parser ) public static Xpp3Dom build( XmlPullParser parser, boolean trim ) throws XmlPullParserException, IOException + { + return build( parser, trim, null ); + } + + /** + * @since 3.2.0 + */ + public static Xpp3Dom build( XmlPullParser parser, boolean trim, InputLocationBuilder locationBuilder ) + throws XmlPullParserException, IOException { List elements = new ArrayList(); @@ -113,6 +140,11 @@ public static Xpp3Dom build( XmlPullParser parser, boolean trim ) Xpp3Dom childConfiguration = new Xpp3Dom( rawName ); + if ( locationBuilder != null ) + { + childConfiguration.setInputLocation( locationBuilder.toInputLocation( parser ) ); + } + int depth = elements.size(); if ( depth > 0 ) @@ -194,4 +226,14 @@ else if ( eventType == XmlPullParser.END_TAG ) throw new IllegalStateException( "End of document found before returning to 0 depth" ); } + + /** + * Input location builder interface, to be implemented to choose how to store data. + * + * @since 3.2.0 + */ + public static interface InputLocationBuilder + { + Object toInputLocation( XmlPullParser parser ); + } } diff --git a/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomUtils.java b/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomUtils.java index f3d5d488..70d00143 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomUtils.java +++ b/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomUtils.java @@ -19,6 +19,10 @@ import org.codehaus.plexus.util.xml.pull.XmlSerializer; import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; /** @author Jason van Zyl */ public class Xpp3DomUtils @@ -71,24 +75,43 @@ public void writeToSerializer( String namespace, XmlSerializer serializer, Xpp3D } /** - * Merges one DOM into another, given a specific algorithm and possible override points for that algorithm. The - * algorithm is as follows: 1. if the recessive DOM is null, there is nothing to do...return. 2. Determine whether - * the dominant node will suppress the recessive one (flag=mergeSelf). A. retrieve the 'combine.self' attribute on - * the dominant node, and try to match against 'override'... if it matches 'override', then set mergeSelf == - * false...the dominant node suppresses the recessive one completely. B. otherwise, use the default value for - * mergeSelf, which is true...this is the same as specifying 'combine.self' == 'merge' as an attribute of the - * dominant root node. 3. If mergeSelf == true A. if the dominant root node's value is empty, set it to the - * recessive root node's value B. For each attribute in the recessive root node which is not set in the dominant - * root node, set it. C. Determine whether children from the recessive DOM will be merged or appended to the - * dominant DOM as siblings (flag=mergeChildren). i. if childMergeOverride is set (non-null), use that value - * (true/false) ii. retrieve the 'combine.children' attribute on the dominant node, and try to match against - * 'append'...if it matches 'append', then set mergeChildren == false...the recessive children will be appended as - * siblings of the dominant children. iii. otherwise, use the default value for mergeChildren, which is true...this - * is the same as specifying 'combine.children' == 'merge' as an attribute on the dominant root node. D. Iterate - * through the recessive children, and: i. if 'combine.id' is set and there is a corresponding dominant child - * (matched by value of 'combine.id'), merge the two. ii. if mergeChildren == true and there is a corresponding - * dominant child (matched by element name), merge the two. iii. otherwise, add the recessive child as a new child - * on the dominant root node. + * Merges one DOM into another, given a specific algorithm and possible override points for that algorithm.

            + * The algorithm is as follows: + *

              + *
            1. if the recessive DOM is null, there is nothing to do... return.
            2. + *
            3. Determine whether the dominant node will suppress the recessive one (flag=mergeSelf). + *
                + *
              1. retrieve the 'combine.self' attribute on the dominant node, and try to match against 'override'... + * if it matches 'override', then set mergeSelf == false...the dominant node suppresses the recessive one + * completely.
              2. + *
              3. otherwise, use the default value for mergeSelf, which is true...this is the same as specifying + * 'combine.self' == 'merge' as an attribute of the dominant root node.
              4. + *
            4. + *
            5. If mergeSelf == true + *
                + *
              1. if the dominant root node's value is empty, set it to the recessive root node's value
              2. + *
              3. For each attribute in the recessive root node which is not set in the dominant root node, set it.
              4. + *
              5. Determine whether children from the recessive DOM will be merged or appended to the dominant DOM as + * siblings (flag=mergeChildren). + *
                  + *
                1. if childMergeOverride is set (non-null), use that value (true/false)
                2. + *
                3. retrieve the 'combine.children' attribute on the dominant node, and try to match against + * 'append'...
                4. + *
                5. if it matches 'append', then set mergeChildren == false...the recessive children will be appended as + * siblings of the dominant children.
                6. + *
                7. otherwise, use the default value for mergeChildren, which is true...this is the same as specifying + * 'combine.children' == 'merge' as an attribute on the dominant root node.
                8. + *
              6. + *
              7. Iterate through the recessive children, and: + *
                  + *
                1. if 'combine.id' is set and there is a corresponding dominant child (matched by value of 'combine.id'), + * merge the two.
                2. + *
                3. if mergeChildren == true and there is a corresponding dominant child (matched by element name), + * merge the two.
                4. + *
                5. otherwise, add the recessive child as a new child on the dominant root node.
                6. + *
              8. + *
            6. + *
            */ private static void mergeIntoXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive, Boolean childMergeOverride ) { @@ -109,9 +132,10 @@ private static void mergeIntoXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive, Boole if ( mergeSelf ) { - if ( isEmpty( dominant.getValue() ) ) + if ( isEmpty( dominant.getValue() ) && !isEmpty( recessive.getValue() ) ) { dominant.setValue( recessive.getValue() ); + dominant.setInputLocation( recessive.getInputLocation() ); } String[] recessiveAttrs = recessive.getAttributeNames(); diff --git a/src/main/java/org/codehaus/plexus/util/xml/pull/MXParser.java b/src/main/java/org/codehaus/plexus/util/xml/pull/MXParser.java index 9a14003e..cede3545 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/pull/MXParser.java +++ b/src/main/java/org/codehaus/plexus/util/xml/pull/MXParser.java @@ -582,7 +582,9 @@ else if ( FEATURE_XML_ROUNDTRIP.equals( name ) ) } } - /** Unknown properties are always returned as false */ + /** + * Unknown properties are always returned as false + */ public boolean getFeature( String name ) { if ( name == null ) @@ -3012,6 +3014,7 @@ protected boolean parsePI() try { + boolean seenPITarget = false; boolean seenQ = false; char ch = more(); if ( isS( ch ) ) @@ -3026,6 +3029,11 @@ protected boolean parsePI() if ( ch == '?' ) { + if ( !seenPITarget ) + { + throw new XmlPullParserException( "processing instruction PITarget name not found", this, + null ); + } seenQ = true; } else if ( ch == '>' ) @@ -3034,7 +3042,18 @@ else if ( ch == '>' ) { break; // found end sequence!!!! } - seenQ = false; + + if ( !seenPITarget ) + { + throw new XmlPullParserException( "processing instruction PITarget name not found", this, + null ); + } + else + { + // seenPITarget && !seenQ + throw new XmlPullParserException( "processing instruction started on line " + curLine + + " and column " + curColumn + " was not closed", this, null ); + } } else { @@ -3073,6 +3092,7 @@ else if ( ch == '>' ) } } } + seenQ = false; } if ( normalizeIgnorableWS ) @@ -3122,6 +3142,7 @@ else if ( ch == '\n' ) normalizedCR = false; } } + seenPITarget = true; ch = more(); } } diff --git a/src/main/java/org/codehaus/plexus/util/xml/pull/XmlPullParser.java b/src/main/java/org/codehaus/plexus/util/xml/pull/XmlPullParser.java index a34bd38e..7c2e139f 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/pull/XmlPullParser.java +++ b/src/main/java/org/codehaus/plexus/util/xml/pull/XmlPullParser.java @@ -66,8 +66,8 @@ * import java.io.StringReader; * * import org.xmlpull.v1.XmlPullParser; - * import org.xmlpull.v1.XmlPullParserException.html; - * import org.xmlpull.v1.XmlPullParserFactory; + * import org.xmlpull.v1.XmlPullParserException; + * import org.xmlpull.v1.XmlPullParserFactory; * * public class SimpleXmlPullApp * { @@ -79,7 +79,7 @@ * factory.setNamespaceAware(true); * XmlPullParser xpp = factory.newPullParser(); * - * xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) ); + * xpp.setInput( new StringReader ( "<foo%gt;Hello World!</foo>" ) ); * int eventType = xpp.getEventType(); * while (eventType != xpp.END_DOCUMENT) { * if(eventType == xpp.START_DOCUMENT) { @@ -87,11 +87,11 @@ * } else if(eventType == xpp.END_DOCUMENT) { * System.out.println("End document"); * } else if(eventType == xpp.START_TAG) { - * System.out.println("Start tag "+xpp.getName()); + * System.out.println("Start tag "+xpp.getName()); * } else if(eventType == xpp.END_TAG) { * System.out.println("End tag "+xpp.getName()); * } else if(eventType == xpp.TEXT) { - * System.out.println("Text "+xpp.getText()); + * System.out.println("Text "+xpp.getText()); * } * eventType = xpp.next(); * } @@ -107,7 +107,7 @@ * Text Hello World! * End tag foo *
        - *

        + * * For more details on API usage, please refer to the quick Introduction available at * http://www.xmlpull.org * @@ -140,7 +140,7 @@ public interface XmlPullParser /** * Signalize that parser is at the very beginning of the document and nothing was read yet. This event type can only - * be observed by calling getEvent() before the first call to next(), nextToken, or nextTag()). + * be observed by calling getEvent() before the first call to next(), nextToken, or nextTag()). * * @see #next * @see #nextToken @@ -457,7 +457,7 @@ void defineEntityReplacementText( String entityName, String replacementText ) * XmlPullParser pp = ... * int nsStart = pp.getNamespaceCount(pp.getDepth()-1); * int nsEnd = pp.getNamespaceCount(pp.getDepth()); - * for (int i = nsStart; i < nsEnd; i++) { + * for (int i = nsStart; i > nsEnd; i++) { * String prefix = pp.getNamespacePrefix(i); * String ns = pp.getNamespaceUri(i); * // ... @@ -501,7 +501,7 @@ String getNamespaceUri( int pos ) * This method is a convenience method for * *

        -     * for ( int i = getNamespaceCount( getDepth() ) - 1; i >= 0; i-- )
        +     * for ( int i = getNamespaceCount( getDepth() ) - 1; i >= 0; i-- )
              * {
              *     if ( getNamespacePrefix( i ).equals( prefix ) )
              *     {
        @@ -531,7 +531,7 @@ String getNamespaceUri( int pos )
              *
              * 
              * <!-- outside -->     0
        -     * <root>                  1
        +     * <root>                  1
              *   sometext                 1
              *     <foobar>         2
              *     </foobar>        2
        @@ -763,8 +763,8 @@ int getEventType()
              * exception mus be thrown if entity reference can not be expanded). If element content is empty (content is "")
              * then no TEXT event will be reported.
              * 

        - * NOTE: empty element (such as <tag/>) will be reported with two separate events: START_TAG, END_TAG - it - * must be so to preserve parsing equivalency of empty element to <tag></tag>. (see isEmptyElementTag ()) + * NOTE: empty element (such as <tag/>) will be reported with two separate events: START_TAG, END_TAG - it + * must be so to preserve parsing equivalency of empty element to <tag></tag>. (see isEmptyElementTag ()) * * @see #isEmptyElementTag * @see #START_TAG @@ -795,9 +795,9 @@ int next() *

        END_DOCUMENT *
        null *
        START_TAG - *
        null unless FEATURE_XML_ROUNDTRIP enabled and then returns XML tag, ex: <tag attr='val'> + *
        null unless FEATURE_XML_ROUNDTRIP enabled and then returns XML tag, ex: <tag attr='val'> *
        END_TAG - *
        null unless FEATURE_XML_ROUNDTRIP id enabled and then returns XML tag, ex: </tag> + *
        null unless FEATURE_XML_ROUNDTRIP id enabled and then returns XML tag, ex: </tag> *
        TEXT *
        return element content.
        * Note: that element content may be delivered in multiple consecutive TEXT events. @@ -807,13 +807,13 @@ int next() * optional.
        * Note: that element content may be delivered in multiple consecutive IGNORABLE_WHITESPACE events. *
        CDSECT - *
        return text inside CDATA (ex. 'fo<o' from <!CDATA[fo<o]]>) + *
        return text inside CDATA (ex. 'fo<o' from <!CDATA[fo<o]]>) *
        PROCESSING_INSTRUCTION - *
        if FEATURE_XML_ROUNDTRIP is true return exact PI content ex: 'pi foo' from <?pi foo?> otherwise it may be - * exact PI content or concatenation of PI target, space and data so for example for <?target data?> string + *
        if FEATURE_XML_ROUNDTRIP is true return exact PI content ex: 'pi foo' from <?pi foo?> otherwise it may be + * exact PI content or concatenation of PI target, space and data so for example for <?target data?> string * "target data" may be returned if FEATURE_XML_ROUNDTRIP is false. *
        COMMENT - *
        return comment content ex. 'foo bar' from <!--foo bar--> + *
        return comment content ex. 'foo bar' from <!--foo bar--> *
        ENTITY_REF *
        getText() MUST return entity replacement text if PROCESS_DOCDECL is false otherwise getText() MAY return * null, additionally getTextCharacters() MUST return entity name (for example 'entity_name' for &entity_name;). @@ -831,14 +831,14 @@ int next() * *
              * " titlepage SYSTEM "http://www.foo.bar/dtds/typo.dtd"
        -     * [<!ENTITY % active.links "INCLUDE">]"
        +     * [<!ENTITY % active.links "INCLUDE">]"
              * 
        *

        * for input document that contained: * *

              * <!DOCTYPE titlepage SYSTEM "http://www.foo.bar/dtds/typo.dtd"
        -     * [<!ENTITY % active.links "INCLUDE">]>
        +     * [<!ENTITY % active.links "INCLUDE">]>
              * 
        * * otherwise if FEATURE_XML_ROUNDTRIP is false and PROCESS_DOCDECL is true then what is returned is undefined (it @@ -904,7 +904,7 @@ void require( int type, String namespace, String name ) * p.requireEvent(p.START_TAG, "", "tag"); * String content = p.nextText(); * p.requireEvent(p.END_TAG, "", "tag"); - *
        + *
        * * This function together with nextTag make it very easy to parse XML that has no mixed content. *

        diff --git a/src/main/java/org/codehaus/plexus/util/xml/pull/XmlSerializer.java b/src/main/java/org/codehaus/plexus/util/xml/pull/XmlSerializer.java index 48e923a0..d7668d74 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/pull/XmlSerializer.java +++ b/src/main/java/org/codehaus/plexus/util/xml/pull/XmlSerializer.java @@ -68,7 +68,7 @@ void setProperty( String name, Object value ) /** * Look up the value of a property. The property name is any fully-qualified URI. I *

        - * NOTE: unknown properties are always returned as null + * NOTE: unknown properties are always returned as null * * @param name The name of property to be retrieved. * @return The value of named property. diff --git a/src/test/java/org/codehaus/plexus/util/CollectionUtilsTest.java b/src/test/java/org/codehaus/plexus/util/CollectionUtilsTest.java index 8071251d..225c1bb0 100644 --- a/src/test/java/org/codehaus/plexus/util/CollectionUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/CollectionUtilsTest.java @@ -16,17 +16,21 @@ * limitations under the License. */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; -import junit.framework.TestCase; +import org.junit.Test; public class CollectionUtilsTest - extends TestCase { + @Test public void testMergeMaps() { Map dominantMap = new HashMap(); @@ -63,6 +67,7 @@ public void testMergeMaps() } @SuppressWarnings( "unchecked" ) + @Test public void testMergeMapArray() { // Test empty array of Maps @@ -114,6 +119,7 @@ public void testMergeMapArray() assertEquals( "ccc", result5.get( "c" ) ); } + @Test public void testMavenPropertiesLoading() { // Mimic MavenSession properties loading. Properties listed @@ -170,6 +176,7 @@ public void testMavenPropertiesLoading() assertEquals( mavenRepoRemote, (String) result.get( "maven.repo.remote" ) ); } + @Test public void testIteratorToListWithAPopulatedList() { List original = new ArrayList(); @@ -189,6 +196,7 @@ public void testIteratorToListWithAPopulatedList() assertEquals( "tre", copy.get( 2 ) ); } + @Test public void testIteratorToListWithAEmptyList() { List original = new ArrayList(); diff --git a/src/test/java/org/codehaus/plexus/util/DirectoryScannerTest.java b/src/test/java/org/codehaus/plexus/util/DirectoryScannerTest.java index 5726c2fe..9d3500ee 100644 --- a/src/test/java/org/codehaus/plexus/util/DirectoryScannerTest.java +++ b/src/test/java/org/codehaus/plexus/util/DirectoryScannerTest.java @@ -16,15 +16,27 @@ * limitations under the License. */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.junit.Assume.assumeTrue; + import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestName; + /** * Base class for testcases doing tests with files. * @@ -33,8 +45,12 @@ public class DirectoryScannerTest extends FileBasedTestCase { + @Rule + public TestName name = new TestName(); + private static String testDir = getTestDirectory().getPath(); + @Test public void testCrossPlatformIncludesString() throws IOException, URISyntaxException { @@ -59,6 +75,7 @@ public void testCrossPlatformIncludesString() assertEquals( 1, files.length ); } + @Test public void testCrossPlatformExcludesString() throws IOException, URISyntaxException { @@ -109,7 +126,49 @@ private void createTestFiles() this.createFile( new File( testDir + "/scanner4.dat" ), 0 ); this.createFile( new File( testDir + "/scanner5.dat" ), 0 ); } + + /** + * Check if 'src/test/resources/symlinks/src/sym*' test files (start with 'sym') exist and are symlinks.
        + * On some OS (like Windows 10), the 'git clone' requires to be executed with admin permissions and the + * 'core.symlinks=true' git option. + * + * @return true If files here and symlinks, false otherwise + */ + private boolean checkTestFilesSymlinks() + { + File symlinksDirectory = new File( "src/test/resources/symlinks/src" ); + try + { + List symlinks = + FileUtils.getFileAndDirectoryNames( symlinksDirectory, "sym*", null, true, true, true, true ); + if ( symlinks.isEmpty() ) + { + throw new IOException( "Symlinks files/directories are not present" ); + } + for ( String symLink : symlinks ) + { + if ( !Files.isSymbolicLink( Paths.get( symLink ) ) ) + { + throw new IOException( String.format( "Path is not a symlink: %s", symLink ) ); + } + } + return true; + } + catch ( IOException e ) + { + System.err.println( String.format( "The unit test '%s.%s' will be skipped, reason: %s", + this.getClass().getSimpleName(), name.getMethodName(), + e.getMessage() ) ); + System.out.println( String.format( "This test requires symlinks files in '%s' directory.", + symlinksDirectory.getPath() ) ); + System.out.println( "On some OS (like Windows 10), files are present only if the clone/checkout is done" + + " in administrator mode, and correct (symlinks and not flat file/directory)" + + " if symlinks option are used (for git: git clone -c core.symlinks=true [url])" ); + return false; + } + } + @Test public void testGeneral() throws IOException { @@ -127,6 +186,7 @@ public void testGeneral() } + @Test public void testIncludesExcludesWithWhiteSpaces() throws IOException { @@ -144,8 +204,11 @@ public void testIncludesExcludesWithWhiteSpaces() assertTrue( "5 not found.", fileNames.contains( new File( "scanner5.dat" ) ) ); } + @Test public void testFollowSymlinksFalse() { + assumeTrue( checkTestFilesSymlinks() ); + DirectoryScanner ds = new DirectoryScanner(); ds.setBasedir( new File( "src/test/resources/symlinks/src/" ) ); ds.setFollowSymlinks( false ); @@ -175,8 +238,11 @@ private void assertAlwaysIncluded( List included ) assertTrue( included.contains( "symLinkToFileOnTheOutside" ) ); } + @Test public void testFollowSymlinks() { + assumeTrue( checkTestFilesSymlinks() ); + DirectoryScanner ds = new DirectoryScanner(); ds.setBasedir( new File( "src/test/resources/symlinks/src/" ) ); ds.setFollowSymlinks( true ); @@ -211,6 +277,7 @@ private void createTestDirectories() + File.separator + "file1.dat" ), 0 ); } + @Test public void testDirectoriesWithHyphens() throws IOException { @@ -229,6 +296,7 @@ public void testDirectoriesWithHyphens() assertEquals( "Wrong number of results.", 3, files.length ); } + @Test public void testAntExcludesOverrideIncludes() throws IOException { @@ -263,6 +331,7 @@ public void testAntExcludesOverrideIncludes() assertInclusionsAndExclusions( ds.getIncludedFiles(), excludedPaths, includedPaths ); } + @Test public void testAntExcludesOverrideIncludesWithExplicitAntPrefix() throws IOException { @@ -298,6 +367,7 @@ public void testAntExcludesOverrideIncludesWithExplicitAntPrefix() assertInclusionsAndExclusions( ds.getIncludedFiles(), excludedPaths, includedPaths ); } + @Test public void testRegexIncludeWithExcludedPrefixDirs() throws IOException { @@ -328,6 +398,7 @@ public void testRegexIncludeWithExcludedPrefixDirs() assertInclusionsAndExclusions( ds.getIncludedFiles(), excludedPaths, includedPaths ); } + @Test public void testRegexExcludeWithNegativeLookahead() throws IOException { @@ -366,6 +437,7 @@ public void testRegexExcludeWithNegativeLookahead() assertInclusionsAndExclusions( ds.getIncludedFiles(), excludedPaths, includedPaths ); } + @Test public void testRegexWithSlashInsideCharacterClass() throws IOException { @@ -405,14 +477,11 @@ public void testRegexWithSlashInsideCharacterClass() assertInclusionsAndExclusions( ds.getIncludedFiles(), excludedPaths, includedPaths ); } + @Test public void testIsSymbolicLink() throws IOException { - // TODO: Uncomment when PR #25 merged - // if ( !checkTestFilesSymlinks() ) - // { - // return; - // } + assumeTrue( checkTestFilesSymlinks() ); final File directory = new File( "src/test/resources/symlinks/src" ); DirectoryScanner ds = new DirectoryScanner(); @@ -422,14 +491,11 @@ public void testIsSymbolicLink() assertFalse( ds.isSymbolicLink( directory, "aRegularDir" ) ); } + @Test public void testIsParentSymbolicLink() throws IOException { - // TODO: Uncomment when PR #25 merged - // if ( !checkTestFilesSymlinks() ) - // { - // return; - // } + assumeTrue( checkTestFilesSymlinks() ); final File directory = new File( "src/test/resources/symlinks/src" ); DirectoryScanner ds = new DirectoryScanner(); diff --git a/src/test/java/org/codehaus/plexus/util/DirectoryWalkerTest.java b/src/test/java/org/codehaus/plexus/util/DirectoryWalkerTest.java index d71ea89f..5ccdb9bc 100644 --- a/src/test/java/org/codehaus/plexus/util/DirectoryWalkerTest.java +++ b/src/test/java/org/codehaus/plexus/util/DirectoryWalkerTest.java @@ -16,13 +16,17 @@ * limitations under the License. */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import java.io.File; -import junit.framework.TestCase; +import org.junit.Test; public class DirectoryWalkerTest - extends TestCase { + @Test public void testDirectoryWalk() { DirectoryWalker walker = new DirectoryWalker(); diff --git a/src/test/java/org/codehaus/plexus/util/FileBasedTestCase.java b/src/test/java/org/codehaus/plexus/util/FileBasedTestCase.java index 9adc79a7..1be701d8 100644 --- a/src/test/java/org/codehaus/plexus/util/FileBasedTestCase.java +++ b/src/test/java/org/codehaus/plexus/util/FileBasedTestCase.java @@ -16,6 +16,8 @@ * limitations under the License. */ +import static org.junit.Assert.assertTrue; + import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -30,7 +32,6 @@ import java.util.Arrays; import junit.framework.AssertionFailedError; -import junit.framework.TestCase; /** * Base class for testcases doing tests with files. @@ -38,7 +39,6 @@ * @author Jeremias Maerki */ public abstract class FileBasedTestCase - extends TestCase { private static File testDir; diff --git a/src/test/java/org/codehaus/plexus/util/FileUtilsTest.java b/src/test/java/org/codehaus/plexus/util/FileUtilsTest.java index 51087306..f29dd418 100644 --- a/src/test/java/org/codehaus/plexus/util/FileUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/FileUtilsTest.java @@ -16,6 +16,13 @@ * limitations under the License. */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; @@ -29,6 +36,11 @@ import java.net.URL; import java.util.Properties; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestName; + /** * This is used to test FileUtils for correctness. * @@ -40,6 +52,9 @@ public final class FileUtilsTest extends FileBasedTestCase { + @Rule + public TestName name = new TestName(); + // Test data /** @@ -65,10 +80,8 @@ public FileUtilsTest() testFile2Size = (int) testFile2.length(); } - /** - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() + @Before + public void setUp() throws Exception { getTestDirectory().mkdirs(); @@ -82,6 +95,7 @@ protected void setUp() // byteCountToDisplaySize + @Test public void testByteCountToDisplaySize() { assertEquals( FileUtils.byteCountToDisplaySize( 0 ), "0 bytes" ); @@ -92,6 +106,7 @@ public void testByteCountToDisplaySize() // waitFor + @Test public void testWaitFor() { FileUtils.waitFor( "", -1 ); @@ -99,6 +114,7 @@ public void testWaitFor() FileUtils.waitFor( "", 2 ); } + @Test public void testToFile() throws Exception { @@ -108,6 +124,7 @@ public void testToFile() assertEquals( "name #%20?{}[]<>.txt", file.getName() ); } + @Test public void testToFileBadProtocol() throws Exception { @@ -116,6 +133,7 @@ public void testToFileBadProtocol() assertNull( file ); } + @Test public void testToFileNull() throws Exception { @@ -124,6 +142,7 @@ public void testToFileNull() } // Hacked to sanity by Trygve + @Test public void testToURLs() throws Exception { @@ -140,6 +159,7 @@ public void testToURLs() } } + @Test public void testGetFilesFromExtension() { // TODO I'm not sure what is supposed to happen here @@ -160,6 +180,7 @@ public void testGetFilesFromExtension() // mkdir + @Test public void testMkdir() { final File dir = new File( getTestDirectory(), "testdir" ); @@ -184,11 +205,12 @@ public void testMkdir() // contentEquals + @Test public void testContentEquals() throws Exception { // Non-existent files - final File file = new File( getTestDirectory(), getName() ); + final File file = new File( getTestDirectory(), name.getMethodName() ); assertTrue( FileUtils.contentEquals( file, file ) ); // TODO Should comparing 2 directories throw an Exception instead of returning false? @@ -196,11 +218,11 @@ public void testContentEquals() assertTrue( !FileUtils.contentEquals( getTestDirectory(), getTestDirectory() ) ); // Different files - final File objFile1 = new File( getTestDirectory(), getName() + ".object" ); + final File objFile1 = new File( getTestDirectory(), name.getMethodName() + ".object" ); objFile1.deleteOnExit(); FileUtils.copyURLToFile( getClass().getResource( "/java/lang/Object.class" ), objFile1 ); - final File objFile2 = new File( getTestDirectory(), getName() + ".collection" ); + final File objFile2 = new File( getTestDirectory(), name.getMethodName() + ".collection" ); objFile2.deleteOnExit(); FileUtils.copyURLToFile( getClass().getResource( "/java/util/Collection.class" ), objFile2 ); @@ -213,27 +235,32 @@ public void testContentEquals() // removePath + @Test public void testRemovePath() { - final String fileName = FileUtils.removePath( new File( getTestDirectory(), getName() ).getAbsolutePath() ); - assertEquals( getName(), fileName ); + final String fileName = + FileUtils.removePath( new File( getTestDirectory(), name.getMethodName() ).getAbsolutePath() ); + assertEquals( name.getMethodName(), fileName ); } // getPath + @Test public void testGetPath() { - final String fileName = FileUtils.getPath( new File( getTestDirectory(), getName() ).getAbsolutePath() ); + final String fileName = + FileUtils.getPath( new File( getTestDirectory(), name.getMethodName() ).getAbsolutePath() ); assertEquals( getTestDirectory().getAbsolutePath(), fileName ); } // copyURLToFile + @Test public void testCopyURLToFile() throws Exception { // Creates file - final File file = new File( getTestDirectory(), getName() ); + final File file = new File( getTestDirectory(), name.getMethodName() ); file.deleteOnExit(); // Loads resource @@ -255,6 +282,7 @@ public void testCopyURLToFile() // catPath + @Test public void testCatPath() { // TODO StringIndexOutOfBoundsException thrown if file doesn't contain slash. @@ -267,6 +295,7 @@ public void testCatPath() // forceMkdir + @Test public void testForceMkdir() throws Exception { @@ -274,7 +303,7 @@ public void testForceMkdir() FileUtils.forceMkdir( getTestDirectory() ); // Creates test file - final File testFile = new File( getTestDirectory(), getName() ); + final File testFile = new File( getTestDirectory(), name.getMethodName() ); testFile.deleteOnExit(); testFile.createNewFile(); assertTrue( "Test file does not exist.", testFile.exists() ); @@ -313,10 +342,11 @@ public void testForceMkdir() // sizeOfDirectory + @Test public void testSizeOfDirectory() throws Exception { - final File file = new File( getTestDirectory(), getName() ); + final File file = new File( getTestDirectory(), name.getMethodName() ); // Non-existent file try @@ -358,6 +388,7 @@ public void XtestIsFileNewer() } // copyFile + @Test public void testCopyFile1() throws Exception { @@ -367,6 +398,7 @@ public void testCopyFile1() assertTrue( "Check Full copy", destination.length() == testFile1Size ); } + @Test public void testCopyFile2() throws Exception { @@ -381,6 +413,7 @@ public void testCopyFile2() * * @throws Exception */ + @Test public void testCopyFile3() throws Exception { @@ -397,6 +430,7 @@ public void testCopyFile3() // copyFileIfModified + @Test public void testCopyIfModifiedWhenSourceIsNewer() throws Exception { @@ -419,6 +453,7 @@ public void testCopyIfModifiedWhenSourceIsNewer() FileUtils.copyFileIfModified( source, destination ) ); } + @Test public void testCopyIfModifiedWhenSourceIsOlder() throws Exception { @@ -439,6 +474,7 @@ public void testCopyIfModifiedWhenSourceIsOlder() assertFalse( "Source file should not have been copied.", FileUtils.copyFileIfModified( source, destination ) ); } + @Test public void testCopyIfModifiedWhenSourceHasZeroDate() throws Exception { @@ -458,6 +494,7 @@ public void testCopyIfModifiedWhenSourceHasZeroDate() // forceDelete + @Test public void testForceDeleteAFile1() throws Exception { @@ -468,6 +505,7 @@ public void testForceDeleteAFile1() assertTrue( "Check No Exist", !destination.exists() ); } + @Test public void testForceDeleteAFile2() throws Exception { @@ -480,6 +518,7 @@ public void testForceDeleteAFile2() // copyFileToDirectory + @Test public void testCopyFile1ToDir() throws Exception { @@ -494,6 +533,7 @@ public void testCopyFile1ToDir() assertTrue( "Check Full copy", destination.length() == testFile1Size ); } + @Test public void testCopyFile2ToDir() throws Exception { @@ -510,6 +550,7 @@ public void testCopyFile2ToDir() // copyFileToDirectoryIfModified + @Test public void testCopyFile1ToDirIfModified() throws Exception { @@ -535,6 +576,7 @@ public void testCopyFile1ToDirIfModified() assertTrue( "Timestamp was changed", timestamp == target.lastModified() ); } + @Test public void testCopyFile2ToDirIfModified() throws Exception { @@ -562,6 +604,7 @@ public void testCopyFile2ToDirIfModified() // forceDelete + @Test public void testForceDeleteDir() throws Exception { @@ -571,6 +614,7 @@ public void testForceDeleteDir() // resolveFile + @Test public void testResolveFileDotDot() throws Exception { @@ -578,6 +622,7 @@ public void testResolveFileDotDot() assertEquals( "Check .. operator", file, getTestDirectory().getParentFile() ); } + @Test public void testResolveFileDot() throws Exception { @@ -587,6 +632,7 @@ public void testResolveFileDot() // normalize + @Test public void testNormalize() throws Exception { @@ -625,6 +671,7 @@ private String replaceAll( String text, String lookFor, String replaceWith ) * Test the FileUtils implementation. */ // Used to exist as IOTestCase class + @Test public void testFileUtils() throws Exception { @@ -662,6 +709,7 @@ public void testFileUtils() } + @Test public void testGetExtension() { final String[][] tests = @@ -675,6 +723,7 @@ public void testGetExtension() } } + @Test public void testGetExtensionWithPaths() { // Since the utilities are based on the separator for the platform @@ -694,6 +743,7 @@ public void testGetExtensionWithPaths() } } + @Test public void testRemoveExtension() { final String[][] tests = { { "filename.ext", "filename" }, { "first.second.third.ext", "first.second.third" }, @@ -707,6 +757,7 @@ public void testRemoveExtension() } /* TODO: Reenable this test */ + @Test public void testRemoveExtensionWithPaths() { // Since the utilities are based on the separator for the platform @@ -731,6 +782,7 @@ public void testRemoveExtensionWithPaths() } } + @Test public void testCopyDirectoryStructureWithAEmptyDirectoryStructure() throws Exception { @@ -747,6 +799,7 @@ public void testCopyDirectoryStructureWithAEmptyDirectoryStructure() FileUtils.copyDirectoryStructure( from, to ); } + @Test public void testCopyDirectoryStructureWithAPopulatedStructure() throws Exception { @@ -806,6 +859,7 @@ public void testCopyDirectoryStructureWithAPopulatedStructure() checkFile( f2_1, new File( to, "2/2_1/2_1.txt" ) ); } + @Test public void testCopyDirectoryStructureIfModified() throws Exception { @@ -885,6 +939,7 @@ public void testCopyDirectoryStructureIfModified() } + @Test public void testCopyDirectoryStructureToSelf() throws Exception { @@ -926,6 +981,7 @@ public void testCopyDirectoryStructureToSelf() } } + @Test public void testFilteredFileCopy() throws Exception { @@ -957,6 +1013,7 @@ public Reader getReader( Reader reader ) compareFile.delete(); } + @Test public void testFilteredWithoutFilterAndOlderFile() throws Exception { @@ -986,6 +1043,7 @@ public void testFilteredWithoutFilterAndOlderFile() } + @Test public void testFilteredWithoutFilterAndOlderFileAndOverwrite() throws Exception { @@ -1015,6 +1073,7 @@ public void testFilteredWithoutFilterAndOlderFileAndOverwrite() } + @Test public void testFileRead() throws IOException { @@ -1043,6 +1102,7 @@ public void testFileRead() testFile.delete(); } + @Test public void testFileReadWithEncoding() throws IOException { @@ -1067,6 +1127,7 @@ public void testFileReadWithEncoding() testFile.delete(); } + @Test public void testFileAppend() throws IOException { @@ -1091,6 +1152,7 @@ public void testFileAppend() testFile.delete(); } + @Test public void testFileAppendWithEncoding() throws IOException { @@ -1116,6 +1178,7 @@ public void testFileAppendWithEncoding() testFile.delete(); } + @Test public void testFileWrite() throws IOException { @@ -1128,6 +1191,7 @@ public void testFileWrite() testFile.delete(); } + @Test public void testFileWriteWithEncoding() throws IOException { @@ -1149,6 +1213,7 @@ public void testFileWriteWithEncoding() * @see Sun bug id=6182812 * @see Sun bug id=6481955 */ + @Test public void testDeleteLongPathOnWindows() throws Exception { @@ -1186,6 +1251,7 @@ public void testDeleteLongPathOnWindows() } // Test for bug PLXUTILS-10 + @Test public void testCopyFileOnSameFile() throws IOException { @@ -1202,6 +1268,7 @@ public void testCopyFileOnSameFile() assertTrue( theFile.length() > 0 ); } + @Test public void testExtensions() throws Exception { @@ -1221,6 +1288,7 @@ public void testExtensions() } } + @Test public void testIsValidWindowsFileName() throws Exception { @@ -1246,6 +1314,7 @@ public void testIsValidWindowsFileName() } } + @Test public void testDeleteDirectoryWithValidFileSymlink() throws Exception { @@ -1267,6 +1336,7 @@ public void testDeleteDirectoryWithValidFileSymlink() assertTrue( "Failed to delete test directory", !getTestDirectory().exists() ); } + @Test public void testDeleteDirectoryWithValidDirSymlink() throws Exception { @@ -1288,6 +1358,7 @@ public void testDeleteDirectoryWithValidDirSymlink() assertTrue( "Failed to delete test directory", !getTestDirectory().exists() ); } + @Test public void testDeleteDirectoryWithDanglingSymlink() throws Exception { @@ -1308,6 +1379,7 @@ public void testDeleteDirectoryWithDanglingSymlink() assertTrue( "Failed to delete test directory", !getTestDirectory().exists() ); } + @Test public void testcopyDirectoryLayoutWithExcludesIncludes() throws Exception { @@ -1349,6 +1421,7 @@ public void testcopyDirectoryLayoutWithExcludesIncludes() * * @throws Exception if any */ + @Test public void testCreateTempFile() throws Exception { diff --git a/src/test/java/org/codehaus/plexus/util/IOUtilTest.java b/src/test/java/org/codehaus/plexus/util/IOUtilTest.java index e6ec723a..c99384c1 100644 --- a/src/test/java/org/codehaus/plexus/util/IOUtilTest.java +++ b/src/test/java/org/codehaus/plexus/util/IOUtilTest.java @@ -16,6 +16,10 @@ * limitations under the License. */ +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; @@ -31,8 +35,8 @@ import java.io.Writer; import java.util.Arrays; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; /** * This is used to test IOUtil for correctness. The following checks are performed: @@ -48,7 +52,6 @@ * @author Jeff Turner */ public final class IOUtilTest - extends TestCase { /* * Note: this is not particularly beautiful code. A better way to check for flush and close status would be to @@ -62,6 +65,7 @@ public final class IOUtilTest private File testFile; + @Before public void setUp() { try @@ -88,11 +92,6 @@ public void tearDown() testDirectory.delete(); } - public IOUtilTest( String name ) - { - super( name ); - } - private void createFile( File file, long size ) throws IOException { @@ -156,6 +155,7 @@ private void assertEqualContent( byte[] b0, File file ) is.close(); } + @Test public void testInputStreamToOutputStream() throws Exception { @@ -174,6 +174,7 @@ public void testInputStreamToOutputStream() deleteFile( destination ); } + @Test public void testInputStreamToWriter() throws Exception { @@ -193,6 +194,7 @@ public void testInputStreamToWriter() deleteFile( destination ); } + @Test public void testInputStreamToString() throws Exception { @@ -204,6 +206,7 @@ public void testInputStreamToString() fin.close(); } + @Test public void testReaderToOutputStream() throws Exception { @@ -225,6 +228,7 @@ public void testReaderToOutputStream() deleteFile( destination ); } + @Test public void testReaderToWriter() throws Exception { @@ -241,6 +245,7 @@ public void testReaderToWriter() deleteFile( destination ); } + @Test public void testReaderToString() throws Exception { @@ -251,6 +256,7 @@ public void testReaderToString() fin.close(); } + @Test public void testStringToOutputStream() throws Exception { @@ -274,6 +280,7 @@ public void testStringToOutputStream() deleteFile( destination ); } + @Test public void testStringToWriter() throws Exception { @@ -293,6 +300,7 @@ public void testStringToWriter() deleteFile( destination ); } + @Test public void testInputStreamToByteArray() throws Exception { @@ -305,6 +313,7 @@ public void testInputStreamToByteArray() fin.close(); } + @Test public void testStringToByteArray() throws Exception { @@ -318,6 +327,7 @@ public void testStringToByteArray() fin.close(); } + @Test public void testByteArrayToWriter() throws Exception { @@ -336,6 +346,7 @@ public void testByteArrayToWriter() deleteFile( destination ); } + @Test public void testByteArrayToString() throws Exception { @@ -347,6 +358,7 @@ public void testByteArrayToString() fin.close(); } + @Test public void testByteArrayToOutputStream() throws Exception { @@ -372,6 +384,7 @@ public void testByteArrayToOutputStream() // Test closeXXX() // ---------------------------------------------------------------------- + @Test public void testCloseInputStream() throws Exception { @@ -384,6 +397,7 @@ public void testCloseInputStream() assertTrue( inputStream.closed ); } + @Test public void testCloseOutputStream() throws Exception { @@ -396,6 +410,7 @@ public void testCloseOutputStream() assertTrue( outputStream.closed ); } + @Test public void testCloseReader() throws Exception { @@ -408,6 +423,7 @@ public void testCloseReader() assertTrue( reader.closed ); } + @Test public void testCloseWriter() throws Exception { @@ -522,7 +538,7 @@ private void checkWrite( OutputStream output ) } catch ( Throwable t ) { - throw new AssertionFailedError( "The copy() method closed the stream " + "when it shouldn't have. " + throw new Exception( "The copy() method closed the stream " + "when it shouldn't have. " + t.getMessage() ); } } @@ -536,7 +552,7 @@ private void checkWrite( Writer output ) } catch ( Throwable t ) { - throw new AssertionFailedError( "The copy() method closed the stream " + "when it shouldn't have. " + throw new Exception( "The copy() method closed the stream " + "when it shouldn't have. " + t.getMessage() ); } } diff --git a/src/test/java/org/codehaus/plexus/util/InterpolationFilterReaderTest.java b/src/test/java/org/codehaus/plexus/util/InterpolationFilterReaderTest.java index 26803960..f68eb400 100644 --- a/src/test/java/org/codehaus/plexus/util/InterpolationFilterReaderTest.java +++ b/src/test/java/org/codehaus/plexus/util/InterpolationFilterReaderTest.java @@ -16,19 +16,21 @@ * limitations under the License. */ +import static org.junit.Assert.assertEquals; + import java.io.StringReader; import java.util.HashMap; import java.util.Map; -import junit.framework.TestCase; +import org.junit.Test; public class InterpolationFilterReaderTest - extends TestCase { /* * Added and commented by jdcasey@03-Feb-2005 because it is a bug in the InterpolationFilterReader. * kenneyw@15-04-2005 fixed the bug. */ + @Test public void testShouldNotInterpolateExpressionAtEndOfDataWithInvalidEndToken() throws Exception { @@ -43,6 +45,7 @@ public void testShouldNotInterpolateExpressionAtEndOfDataWithInvalidEndToken() /* * kenneyw@14-04-2005 Added test to check above fix. */ + @Test public void testShouldNotInterpolateExpressionWithMissingEndToken() throws Exception { @@ -54,6 +57,7 @@ public void testShouldNotInterpolateExpressionWithMissingEndToken() assertEquals( "This is a ${test, really", interpolate( testStr, m ) ); } + @Test public void testShouldNotInterpolateWithMalformedStartToken() throws Exception { @@ -65,6 +69,7 @@ public void testShouldNotInterpolateWithMalformedStartToken() assertEquals( "This is a $!test} again", interpolate( foo, m ) ); } + @Test public void testShouldNotInterpolateWithMalformedEndToken() throws Exception { @@ -76,6 +81,7 @@ public void testShouldNotInterpolateWithMalformedEndToken() assertEquals( "This is a ${test!} again", interpolate( foo, m, "${", "$}" ) ); } + @Test public void testInterpolationWithMulticharDelimiters() throws Exception { @@ -87,6 +93,7 @@ public void testInterpolationWithMulticharDelimiters() assertEquals( "This is a testValue again", interpolate( foo, m, "${", "$}" ) ); } + @Test public void testDefaultInterpolationWithNonInterpolatedValueAtEnd() throws Exception { @@ -99,6 +106,7 @@ public void testDefaultInterpolationWithNonInterpolatedValueAtEnd() assertEquals( "jason is an asshole. ${not.interpolated}", interpolate( foo, m ) ); } + @Test public void testDefaultInterpolationWithInterpolatedValueAtEnd() throws Exception { @@ -111,6 +119,7 @@ public void testDefaultInterpolationWithInterpolatedValueAtEnd() assertEquals( "jason is an asshole", interpolate( foo, m ) ); } + @Test public void testInterpolationWithSpecifiedBoundaryTokens() throws Exception { @@ -123,6 +132,7 @@ public void testInterpolationWithSpecifiedBoundaryTokens() assertEquals( "jason is an asshole. @not.interpolated@ baby @foo@. @bar@", interpolate( foo, m, "@", "@" ) ); } + @Test public void testInterpolationWithSpecifiedBoundaryTokensWithNonInterpolatedValueAtEnd() throws Exception { @@ -135,6 +145,7 @@ public void testInterpolationWithSpecifiedBoundaryTokensWithNonInterpolatedValue assertEquals( "jason is an @foobarred@", interpolate( foo, m, "@", "@" ) ); } + @Test public void testInterpolationWithSpecifiedBoundaryTokensWithInterpolatedValueAtEnd() throws Exception { @@ -147,6 +158,7 @@ public void testInterpolationWithSpecifiedBoundaryTokensWithInterpolatedValueAtE assertEquals( "jason is an asshole", interpolate( foo, m, "@", "@" ) ); } + @Test public void testInterpolationWithSpecifiedBoundaryTokensAndAdditionalTokenCharacter() throws Exception { diff --git a/src/test/java/org/codehaus/plexus/util/LineOrientedInterpolatingReaderTest.java b/src/test/java/org/codehaus/plexus/util/LineOrientedInterpolatingReaderTest.java index a29afe1f..346f1e88 100644 --- a/src/test/java/org/codehaus/plexus/util/LineOrientedInterpolatingReaderTest.java +++ b/src/test/java/org/codehaus/plexus/util/LineOrientedInterpolatingReaderTest.java @@ -16,6 +16,8 @@ * limitations under the License. */ +import static org.junit.Assert.assertEquals; + import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; @@ -24,39 +26,18 @@ import java.util.HashMap; import java.util.Map; -import junit.framework.TestCase; +import org.junit.Test; /** * Generated by JUnitDoclet, a tool provided by ObjectFab GmbH under LGPL. Please see www.junitdoclet.org, www.gnu.org * and www.objectfab.de for informations about the tool, the licence and the authors. */ public class LineOrientedInterpolatingReaderTest - extends TestCase { - public LineOrientedInterpolatingReaderTest( String name ) - { - super( name ); - } - - /** - * The JUnit setup method - */ - protected void setUp() - throws Exception - { - } - - /** - * The teardown method for JUnit - */ - protected void tearDown() - throws Exception - { - } - /* * Added and commented by jdcasey@03-Feb-2005 because it is a bug in the InterpolationFilterReader. */ + @Test public void testShouldInterpolateExpressionAtEndOfDataWithInvalidEndToken() throws IOException { @@ -71,6 +52,7 @@ public void testShouldInterpolateExpressionAtEndOfDataWithInvalidEndToken() assertEquals( "This is a ${test", result ); } + @Test public void testDefaultInterpolationWithNonInterpolatedValueAtEnd() throws Exception { @@ -95,6 +77,7 @@ private Map getStandardMap() return m; } + @Test public void testDefaultInterpolationWithEscapedExpression() throws Exception { @@ -111,6 +94,7 @@ public void testDefaultInterpolationWithEscapedExpression() assertEquals( "jason is an asshole. ${noun} value", bar ); } + @Test public void testDefaultInterpolationWithInterpolatedValueAtEnd() throws Exception { @@ -127,6 +111,7 @@ public void testDefaultInterpolationWithInterpolatedValueAtEnd() assertEquals( "jason is an asshole", bar ); } + @Test public void testInterpolationWithSpecifiedBoundaryTokens() throws Exception { @@ -144,6 +129,7 @@ public void testInterpolationWithSpecifiedBoundaryTokens() assertEquals( "jason is an asshole. @not.interpolated@ baby @foo@. @bar@", bar ); } + @Test public void testInterpolationWithSpecifiedBoundaryTokensWithNonInterpolatedValueAtEnd() throws Exception { @@ -161,6 +147,7 @@ public void testInterpolationWithSpecifiedBoundaryTokensWithNonInterpolatedValue assertEquals( "jason is an @foobarred@", bar ); } + @Test public void testInterpolationWithSpecifiedBoundaryTokensWithInterpolatedValueAtEnd() throws Exception { diff --git a/src/test/java/org/codehaus/plexus/util/MatchPatternTest.java b/src/test/java/org/codehaus/plexus/util/MatchPatternTest.java index bb3de466..38deb81e 100644 --- a/src/test/java/org/codehaus/plexus/util/MatchPatternTest.java +++ b/src/test/java/org/codehaus/plexus/util/MatchPatternTest.java @@ -1,4 +1,5 @@ package org.codehaus.plexus.util; + /* * Copyright The Codehaus Foundation. * @@ -15,19 +16,20 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; /** * @author Kristian Rosenvold */ public class MatchPatternTest - extends TestCase { + @Test public void testMatchPath() throws Exception { MatchPattern mp = MatchPattern.fromString( "ABC*" ); assertTrue( mp.matchPath( "ABCD", true ) ); - } } diff --git a/src/test/java/org/codehaus/plexus/util/MatchPatternsTest.java b/src/test/java/org/codehaus/plexus/util/MatchPatternsTest.java index b75b5b54..d4e51566 100644 --- a/src/test/java/org/codehaus/plexus/util/MatchPatternsTest.java +++ b/src/test/java/org/codehaus/plexus/util/MatchPatternsTest.java @@ -1,4 +1,5 @@ package org.codehaus.plexus.util; + /* * Copyright The Codehaus Foundation. * @@ -15,11 +16,14 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; public class MatchPatternsTest - extends TestCase { + @Test public void testMatches() throws Exception { @@ -27,6 +31,5 @@ public void testMatches() assertTrue( from.matches( "ABCDE", true ) ); assertTrue( from.matches( "CDEF", true ) ); assertFalse( from.matches( "XYZ", true ) ); - } } diff --git a/src/test/java/org/codehaus/plexus/util/OsTest.java b/src/test/java/org/codehaus/plexus/util/OsTest.java index 6a706b25..363df35b 100644 --- a/src/test/java/org/codehaus/plexus/util/OsTest.java +++ b/src/test/java/org/codehaus/plexus/util/OsTest.java @@ -16,21 +16,26 @@ * limitations under the License. */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import java.util.Iterator; -import junit.framework.TestCase; +import org.junit.Test; /** * Test Case for Os */ public class OsTest - extends TestCase { + @Test public void testUndefinedFamily() { assertFalse( Os.isFamily( "bogus family" ) ); } + @Test public void testOs() { Iterator iter = Os.getValidFamilies().iterator(); @@ -74,6 +79,7 @@ public void testOs() assertFalse( Os.isOs( currentFamily, Os.OS_NAME, Os.OS_ARCH, "myversion" ) ); } + @Test public void testValidList() { assertTrue( Os.isValidFamily( "dos" ) ); diff --git a/src/test/java/org/codehaus/plexus/util/PathToolTest.java b/src/test/java/org/codehaus/plexus/util/PathToolTest.java index 8367c7e8..e7f01ba8 100644 --- a/src/test/java/org/codehaus/plexus/util/PathToolTest.java +++ b/src/test/java/org/codehaus/plexus/util/PathToolTest.java @@ -16,18 +16,20 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; /** * @author Vincent Siveton * @version $Id$ */ public class PathToolTest - extends TestCase { /** * @throws Exception */ + @Test public void testGetRelativePath() throws Exception { @@ -42,6 +44,7 @@ public void testGetRelativePath() /** * @throws Exception */ + @Test public void testGetDirectoryComponent() throws Exception { @@ -54,6 +57,7 @@ public void testGetDirectoryComponent() /** * @throws Exception */ + @Test public void testCalculateLink() throws Exception { @@ -71,6 +75,7 @@ public void testCalculateLink() /** * @throws Exception */ + @Test public void testGetRelativeWebPath() throws Exception { @@ -88,6 +93,7 @@ public void testGetRelativeWebPath() /** * @throws Exception */ + @Test public void testGetRelativeFilePath() throws Exception { diff --git a/src/test/java/org/codehaus/plexus/util/PerfTest.java b/src/test/java/org/codehaus/plexus/util/PerfTest.java index 1a219175..a443fd95 100644 --- a/src/test/java/org/codehaus/plexus/util/PerfTest.java +++ b/src/test/java/org/codehaus/plexus/util/PerfTest.java @@ -1,7 +1,5 @@ package org.codehaus.plexus.util; -import junit.framework.TestCase; - /* * Copyright 2011 The Codehaus Foundation. * @@ -18,14 +16,15 @@ * limitations under the License. */ +import org.junit.Test; + public class PerfTest - extends TestCase { - String src = "012345578901234556789012345678901234456789012345678901234567890"; private final int oops = 100; + @Test public void testSubString() { StringBuilder res = new StringBuilder(); @@ -41,6 +40,7 @@ public void testSubString() System.out.println( "i = " + i ); } + @Test public void testResDir() { StringBuilder res = new StringBuilder(); diff --git a/src/test/java/org/codehaus/plexus/util/ReflectionUtilsTest.java b/src/test/java/org/codehaus/plexus/util/ReflectionUtilsTest.java index fe812a62..767c72e8 100644 --- a/src/test/java/org/codehaus/plexus/util/ReflectionUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/ReflectionUtilsTest.java @@ -16,9 +16,12 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; import java.util.Map; + +import org.junit.Test; + import java.util.HashMap; /** @@ -29,22 +32,17 @@ * @see org.codehaus.plexus.util.ReflectionUtils */ public final class ReflectionUtilsTest - extends TestCase { public ReflectionUtilsTestClass testClass = new ReflectionUtilsTestClass(); - protected void setUp() - throws Exception - { - - } - + @Test public void testSimpleVariableAccess() throws IllegalAccessException { assertEquals( "woohoo", (String) ReflectionUtils.getValueIncludingSuperclasses( "myString", testClass ) ); } + @Test public void testComplexVariableAccess() throws IllegalAccessException { @@ -57,6 +55,7 @@ public void testComplexVariableAccess() } + @Test public void testSuperClassVariableAccess() throws IllegalAccessException { @@ -64,6 +63,7 @@ public void testSuperClassVariableAccess() (String) ReflectionUtils.getValueIncludingSuperclasses( "mySuperString", testClass ) ); } + @Test public void testSettingVariableValue() throws IllegalAccessException { diff --git a/src/test/java/org/codehaus/plexus/util/SelectorUtilsTest.java b/src/test/java/org/codehaus/plexus/util/SelectorUtilsTest.java index f007d324..194c45b4 100644 --- a/src/test/java/org/codehaus/plexus/util/SelectorUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/SelectorUtilsTest.java @@ -1,9 +1,5 @@ package org.codehaus.plexus.util; -import java.io.File; - -import junit.framework.TestCase; - /* * Copyright The Codehaus Foundation. * @@ -20,9 +16,16 @@ * limitations under the License. */ +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; + +import org.junit.Test; + public class SelectorUtilsTest - extends TestCase { + @Test public void testMatchPath_DefaultFileSeparator() { String separator = File.separator; @@ -38,6 +41,7 @@ public void testMatchPath_DefaultFileSeparator() assertTrue( SelectorUtils.matchPath( "*" + separator + "a.txt", "b" + separator + "a.txt" ) ); } + @Test public void testMatchPath_UnixFileSeparator() { String separator = "/"; @@ -55,6 +59,7 @@ public void testMatchPath_UnixFileSeparator() assertTrue( SelectorUtils.matchPath( "*" + separator + "a.txt", "b" + separator + "a.txt", separator, false ) ); } + @Test public void testMatchPath_WindowsFileSeparator() { String separator = "\\"; diff --git a/src/test/java/org/codehaus/plexus/util/StringUtilsTest.java b/src/test/java/org/codehaus/plexus/util/StringUtilsTest.java index 732acf5c..42f1a75b 100644 --- a/src/test/java/org/codehaus/plexus/util/StringUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/StringUtilsTest.java @@ -16,10 +16,14 @@ * limitations under the License. */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import java.util.Arrays; import java.util.Locale; -import junit.framework.TestCase; +import org.junit.Test; /** * Test string utils. @@ -28,9 +32,9 @@ * @version $Id$ */ public class StringUtilsTest - extends TestCase { + @Test public void testIsEmpty() { assertEquals( true, StringUtils.isEmpty( null ) ); @@ -40,6 +44,7 @@ public void testIsEmpty() assertEquals( false, StringUtils.isEmpty( " foo " ) ); } + @Test public void testIsNotEmpty() { assertEquals( false, StringUtils.isNotEmpty( null ) ); @@ -49,6 +54,7 @@ public void testIsNotEmpty() assertEquals( true, StringUtils.isNotEmpty( " foo " ) ); } + @Test public void testIsBlank() { assertEquals( true, StringUtils.isBlank( null ) ); @@ -58,6 +64,7 @@ public void testIsBlank() assertEquals( false, StringUtils.isBlank( " foo " ) ); } + @Test public void testIsNotBlank() { assertEquals( false, StringUtils.isNotBlank( null ) ); @@ -67,12 +74,14 @@ public void testIsNotBlank() assertEquals( true, StringUtils.isNotBlank( " foo " ) ); } + @Test public void testCapitalizeFirstLetter() { assertEquals( "Id", StringUtils.capitalizeFirstLetter( "id" ) ); assertEquals( "Id", StringUtils.capitalizeFirstLetter( "Id" ) ); } + @Test public void testCapitalizeFirstLetterTurkish() { Locale l = Locale.getDefault(); @@ -82,12 +91,14 @@ public void testCapitalizeFirstLetterTurkish() Locale.setDefault( l ); } + @Test public void testLowerCaseFirstLetter() { assertEquals( "id", StringUtils.lowercaseFirstLetter( "id" ) ); assertEquals( "id", StringUtils.lowercaseFirstLetter( "Id" ) ); } + @Test public void testLowerCaseFirstLetterTurkish() { Locale l = Locale.getDefault(); @@ -97,12 +108,14 @@ public void testLowerCaseFirstLetterTurkish() Locale.setDefault( l ); } + @Test public void testRemoveAndHump() { assertEquals( "Id", StringUtils.removeAndHump( "id", "-" ) ); assertEquals( "SomeId", StringUtils.removeAndHump( "some-id", "-" ) ); } + @Test public void testRemoveAndHumpTurkish() { Locale l = Locale.getDefault(); @@ -112,6 +125,7 @@ public void testRemoveAndHumpTurkish() Locale.setDefault( l ); } + @Test public void testQuote_EscapeEmbeddedSingleQuotes() { String src = "This \'is a\' test"; @@ -123,6 +137,7 @@ public void testQuote_EscapeEmbeddedSingleQuotes() assertEquals( check, result ); } + @Test public void testQuote_EscapeEmbeddedSingleQuotesWithPattern() { String src = "This \'is a\' test"; @@ -134,6 +149,7 @@ public void testQuote_EscapeEmbeddedSingleQuotesWithPattern() assertEquals( check, result ); } + @Test public void testQuote_EscapeEmbeddedDoubleQuotesAndSpaces() { String src = "This \"is a\" test"; @@ -145,6 +161,7 @@ public void testQuote_EscapeEmbeddedDoubleQuotesAndSpaces() assertEquals( check, result ); } + @Test public void testQuote_DontQuoteIfUnneeded() { String src = "ThisIsATest"; @@ -155,6 +172,7 @@ public void testQuote_DontQuoteIfUnneeded() assertEquals( src, result ); } + @Test public void testQuote_WrapWithSingleQuotes() { String src = "This is a test"; @@ -166,6 +184,7 @@ public void testQuote_WrapWithSingleQuotes() assertEquals( check, result ); } + @Test public void testQuote_PreserveExistingQuotes() { String src = "\'This is a test\'"; @@ -176,6 +195,7 @@ public void testQuote_PreserveExistingQuotes() assertEquals( src, result ); } + @Test public void testQuote_WrapExistingQuotesWhenForceIsTrue() { String src = "\'This is a test\'"; @@ -187,6 +207,7 @@ public void testQuote_WrapExistingQuotesWhenForceIsTrue() assertEquals( check, result ); } + @Test public void testQuote_ShortVersion_SingleQuotesPreserved() { String src = "\'This is a test\'"; @@ -196,6 +217,7 @@ public void testQuote_ShortVersion_SingleQuotesPreserved() assertEquals( src, result ); } + @Test public void testSplit() { String[] tokens; @@ -225,6 +247,7 @@ public void testSplit() assertEquals( Arrays.asList( new String[] { "this", "is", "a", "test", "really" } ), Arrays.asList( tokens ) ); } + @Test public void testRemoveDuplicateWhitespace() throws Exception { @@ -239,6 +262,7 @@ public void testRemoveDuplicateWhitespace() } + @Test public void testUnifyLineSeparators() throws Exception { diff --git a/src/test/java/org/codehaus/plexus/util/SweeperPoolTest.java b/src/test/java/org/codehaus/plexus/util/SweeperPoolTest.java index 68e2884d..9dd1a41f 100644 --- a/src/test/java/org/codehaus/plexus/util/SweeperPoolTest.java +++ b/src/test/java/org/codehaus/plexus/util/SweeperPoolTest.java @@ -16,10 +16,19 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.util.Vector; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + /** * Created on 21/06/2003 * @@ -27,7 +36,6 @@ * @version $Revision$ */ public class SweeperPoolTest - extends TestCase { /** The pool under test */ TestObjectPool pool; @@ -45,27 +53,10 @@ public class SweeperPoolTest Object o6; - /** - * Constructor - */ - public SweeperPoolTest() - { - super(); - } - - /** - * Constructor - * - * @param arg0 - */ - public SweeperPoolTest( String arg0 ) - { - super( arg0 ); - } - /** * Test the pool limits it's size, and disposes unneeded objects correctly */ + @Test public void testMaxSize() { int sweepInterval = 0; @@ -98,6 +89,7 @@ public void testMaxSize() } + @Test public void testSweepAndTrim1() { // test trigger @@ -129,32 +121,25 @@ public void testSweepAndTrim1() } - /** - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() + @Before + public void setUp() throws Exception { - o1 = new Object(); o2 = new Object(); o3 = new Object(); o4 = new Object(); o5 = new Object(); o6 = new Object(); - super.setUp(); } - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() + @After + public void tearDown() throws Exception { pool.dispose(); assertTrue( pool.isDisposed() ); pool = null; - super.tearDown(); } diff --git a/src/test/java/org/codehaus/plexus/util/cli/CommandLineUtilsTest.java b/src/test/java/org/codehaus/plexus/util/cli/CommandLineUtilsTest.java index 6e333870..ae4b3e19 100644 --- a/src/test/java/org/codehaus/plexus/util/cli/CommandLineUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/cli/CommandLineUtilsTest.java @@ -16,18 +16,22 @@ * limitations under the License. */ -import junit.framework.TestCase; -import org.codehaus.plexus.util.Os; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; import java.util.Arrays; import java.util.Locale; import java.util.Properties; +import org.codehaus.plexus.util.Os; +import org.junit.Test; + @SuppressWarnings( { "JavaDoc", "deprecation" } ) public class CommandLineUtilsTest - extends TestCase { + @Test public void testQuoteArguments() { try @@ -59,6 +63,7 @@ public void testQuoteArguments() /** * Tests that case-insensitive environment variables are normalized to upper case. */ + @Test public void testGetSystemEnvVarsCaseInsensitive() throws Exception { @@ -73,6 +78,7 @@ public void testGetSystemEnvVarsCaseInsensitive() /** * Tests that environment variables on Windows are normalized to upper case. Does nothing on Unix platforms. */ + @Test public void testGetSystemEnvVarsWindows() throws Exception { @@ -91,6 +97,7 @@ public void testGetSystemEnvVarsWindows() /** * Tests the splitting of a command line into distinct arguments. */ + @Test public void testTranslateCommandline() throws Exception { diff --git a/src/test/java/org/codehaus/plexus/util/cli/CommandlineTest.java b/src/test/java/org/codehaus/plexus/util/cli/CommandlineTest.java index 841219af..28ec8297 100644 --- a/src/test/java/org/codehaus/plexus/util/cli/CommandlineTest.java +++ b/src/test/java/org/codehaus/plexus/util/cli/CommandlineTest.java @@ -16,36 +16,32 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; + import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.Os; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.cli.shell.BourneShell; import org.codehaus.plexus.util.cli.shell.CmdShell; import org.codehaus.plexus.util.cli.shell.Shell; - -import java.io.*; +import org.junit.Before; +import org.junit.Test; public class CommandlineTest - extends TestCase { private String baseDir; - /** - * @param testName - */ - public CommandlineTest( final String testName ) - { - super( testName ); - } - - /* - * @see TestCase#setUp() - */ + @Before public void setUp() throws Exception { - super.setUp(); baseDir = System.getProperty( "basedir" ); if ( baseDir == null ) @@ -54,143 +50,104 @@ public void setUp() } } + @Test public void testCommandlineWithoutCommandInConstructor() { - try - { - Commandline cmd = new Commandline( new Shell() ); - cmd.setWorkingDirectory( baseDir ); - cmd.createArgument().setValue( "cd" ); - cmd.createArgument().setValue( "." ); + Commandline cmd = new Commandline( new Shell() ); + cmd.setWorkingDirectory( baseDir ); + cmd.createArgument().setValue( "cd" ); + cmd.createArgument().setValue( "." ); - // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. - assertEquals( "cd .", cmd.toString() ); - } - catch ( Exception e ) - { - fail( e.getMessage() ); - } + // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. + assertEquals( "cd .", cmd.toString() ); } + @Test public void testCommandlineWithCommandInConstructor() { - try - { - Commandline cmd = new Commandline( "cd .", new Shell() ); - cmd.setWorkingDirectory( baseDir ); + Commandline cmd = new Commandline( "cd .", new Shell() ); + cmd.setWorkingDirectory( baseDir ); - // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. - assertEquals( "cd .", cmd.toString() ); - } - catch ( Exception e ) - { - fail( e.getMessage() ); - } + // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. + assertEquals( "cd .", cmd.toString() ); } + @Test public void testExecuteBinaryOnPath() + throws Exception { - try - { - // Maven startup script on PATH is required for this test - Commandline cmd = new Commandline(); - cmd.setWorkingDirectory( baseDir ); - cmd.setExecutable( "mvn" ); - assertEquals( "mvn", cmd.getShell().getOriginalExecutable() ); - cmd.createArg().setValue( "-version" ); - Process process = cmd.execute(); - String out = IOUtil.toString( process.getInputStream() ); - assertTrue( out.contains( "Apache Maven" ) ); - assertTrue( out.contains( "Maven home:" ) ); - assertTrue( out.contains( "Java version:" ) ); - } - catch ( Exception e ) - { - fail( "Maven startup script seems not on the PATH: " + e.getMessage() ); - } + // Maven startup script on PATH is required for this test + Commandline cmd = new Commandline(); + cmd.setWorkingDirectory( baseDir ); + cmd.setExecutable( "mvn" ); + assertEquals( "mvn", cmd.getShell().getOriginalExecutable() ); + cmd.createArg().setValue( "-version" ); + Process process = cmd.execute(); + String out = IOUtil.toString( process.getInputStream() ); + assertTrue( out.contains( "Apache Maven" ) ); + assertTrue( out.contains( "Maven home:" ) ); + assertTrue( out.contains( "Java version:" ) ); } + @Test public void testExecute() + throws Exception { - try - { - // allow it to detect the proper shell here. - Commandline cmd = new Commandline(); - cmd.setWorkingDirectory( baseDir ); - cmd.setExecutable( "echo" ); - assertEquals( "echo", cmd.getShell().getOriginalExecutable() ); - cmd.createArgument().setValue( "Hello" ); + // allow it to detect the proper shell here. + Commandline cmd = new Commandline(); + cmd.setWorkingDirectory( baseDir ); + cmd.setExecutable( "echo" ); + assertEquals( "echo", cmd.getShell().getOriginalExecutable() ); + cmd.createArgument().setValue( "Hello" ); - Process process = cmd.execute(); - assertEquals( "Hello", IOUtil.toString( process.getInputStream() ).trim() ); - } - catch ( Exception e ) - { - fail( e.getMessage() ); - } + Process process = cmd.execute(); + assertEquals( "Hello", IOUtil.toString( process.getInputStream() ).trim() ); } + @Test public void testSetLine() { - try - { - Commandline cmd = new Commandline( new Shell() ); - cmd.setWorkingDirectory( baseDir ); - cmd.setExecutable( "echo" ); - cmd.createArgument().setLine( null ); - cmd.createArgument().setLine( "Hello" ); - - // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. - assertEquals( "echo Hello", cmd.toString() ); - } - catch ( Exception e ) - { - fail( e.getMessage() ); - } + Commandline cmd = new Commandline( new Shell() ); + cmd.setWorkingDirectory( baseDir ); + cmd.setExecutable( "echo" ); + cmd.createArgument().setLine( null ); + cmd.createArgument().setLine( "Hello" ); + + // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. + assertEquals( "echo Hello", cmd.toString() ); } + @Test public void testCreateCommandInReverseOrder() { - try - { - Commandline cmd = new Commandline( new Shell() ); - cmd.setWorkingDirectory( baseDir ); - cmd.createArgument().setValue( "." ); - cmd.createArgument( true ).setValue( "cd" ); + Commandline cmd = new Commandline( new Shell() ); + cmd.setWorkingDirectory( baseDir ); + cmd.createArgument().setValue( "." ); + cmd.createArgument( true ).setValue( "cd" ); - // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. - assertEquals( "cd .", cmd.toString() ); - } - catch ( Exception e ) - { - fail( e.getMessage() ); - } + // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. + assertEquals( "cd .", cmd.toString() ); } + @Test public void testSetFile() { - try + Commandline cmd = new Commandline( new Shell() ); + cmd.setWorkingDirectory( baseDir ); + cmd.createArgument().setValue( "more" ); + File f = new File( "test.txt" ); + cmd.createArgument().setFile( f ); + String fileName = f.getAbsolutePath(); + if ( fileName.contains( " " ) ) { - Commandline cmd = new Commandline( new Shell() ); - cmd.setWorkingDirectory( baseDir ); - cmd.createArgument().setValue( "more" ); - File f = new File( "test.txt" ); - cmd.createArgument().setFile( f ); - String fileName = f.getAbsolutePath(); - if ( fileName.contains( " " ) ) - { - fileName = "\"" + fileName + "\""; - } - - // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. - assertEquals( "more " + fileName, cmd.toString() ); - } - catch ( Exception e ) - { - fail( e.getMessage() ); + fileName = "\"" + fileName + "\""; } + + // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. + assertEquals( "more " + fileName, cmd.toString() ); } + @Test public void testGetShellCommandLineWindows() throws Exception { @@ -209,6 +166,7 @@ public void testGetShellCommandLineWindows() assertEquals( expectedShellCmd, shellCommandline[3] ); } + @Test public void testGetShellCommandLineWindowsWithSeveralQuotes() throws Exception { @@ -233,6 +191,7 @@ public void testGetShellCommandLineWindowsWithSeveralQuotes() * * @throws Exception */ + @Test public void testGetShellCommandLineBash() throws Exception { @@ -259,6 +218,7 @@ public void testGetShellCommandLineBash() * * @throws Exception */ + @Test public void testGetShellCommandLineBash_WithWorkingDirectory() throws Exception { @@ -288,6 +248,7 @@ public void testGetShellCommandLineBash_WithWorkingDirectory() * * @throws Exception */ + @Test public void testGetShellCommandLineBash_WithSingleQuotedArg() throws Exception { @@ -309,6 +270,7 @@ public void testGetShellCommandLineBash_WithSingleQuotedArg() assertEquals( expectedShellCmd, shellCommandline[2] ); } + @Test public void testGetShellCommandLineNonWindows() throws Exception { @@ -332,6 +294,7 @@ public void testGetShellCommandLineNonWindows() } } + @Test public void testEnvironment() throws Exception { @@ -340,6 +303,7 @@ public void testEnvironment() assertEquals( "name=value", cmd.getEnvironmentVariables()[0] ); } + @Test public void testEnvironmentWitOverrideSystemEnvironment() throws Exception { @@ -364,6 +328,7 @@ public void testEnvironmentWitOverrideSystemEnvironment() * * @throws Exception */ + @Test public void testQuotedPathWithSingleApostrophe() throws Exception { @@ -379,6 +344,7 @@ public void testQuotedPathWithSingleApostrophe() * * @throws Exception */ + @Test public void testPathWithShellExpansionStrings() throws Exception { @@ -391,6 +357,7 @@ public void testPathWithShellExpansionStrings() * * @throws Exception */ + @Test public void testQuotedPathWithQuotationMark() throws Exception { @@ -413,6 +380,7 @@ public void testQuotedPathWithQuotationMark() * * @throws Exception */ + @Test public void testQuotedPathWithQuotationMarkAndApostrophe() throws Exception { @@ -434,6 +402,7 @@ public void testQuotedPathWithQuotationMarkAndApostrophe() * * @throws Exception */ + @Test public void testOnlyQuotedPath() throws Exception { @@ -464,6 +433,7 @@ public void testOnlyQuotedPath() createAndCallScript( dir, javaBinStr + " -version" ); } + @Test public void testDollarSignInArgumentPath() throws Exception { @@ -498,6 +468,7 @@ public void testDollarSignInArgumentPath() executeCommandLine( cmd ); } + @Test public void testTimeOutException() throws Exception { diff --git a/src/test/java/org/codehaus/plexus/util/cli/DefaultConsumerTest.java b/src/test/java/org/codehaus/plexus/util/cli/DefaultConsumerTest.java index 50766092..4c8d9931 100644 --- a/src/test/java/org/codehaus/plexus/util/cli/DefaultConsumerTest.java +++ b/src/test/java/org/codehaus/plexus/util/cli/DefaultConsumerTest.java @@ -16,32 +16,13 @@ * limitations under the License. */ -import java.io.IOException; - -import junit.framework.TestCase; +import org.junit.Test; public class DefaultConsumerTest - extends TestCase { - /** - * @param testName - */ - public DefaultConsumerTest( String testName ) - { - super( testName ); - } - - /* - * @see TestCase#setUp() - */ - public void setUp() - throws Exception - { - super.setUp(); - } - + @Test public void testConsumeLine() - throws IOException + throws Exception { DefaultConsumer cons = new DefaultConsumer(); cons.consumeLine( "Test DefaultConsumer consumeLine" ); diff --git a/src/test/java/org/codehaus/plexus/util/cli/EnhancedStringTokenizerTest.java b/src/test/java/org/codehaus/plexus/util/cli/EnhancedStringTokenizerTest.java index 3c4f6396..c9ce9ebd 100644 --- a/src/test/java/org/codehaus/plexus/util/cli/EnhancedStringTokenizerTest.java +++ b/src/test/java/org/codehaus/plexus/util/cli/EnhancedStringTokenizerTest.java @@ -16,28 +16,14 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; public class EnhancedStringTokenizerTest - extends TestCase { - /** - * @param testName - */ - public EnhancedStringTokenizerTest( final String testName ) - { - super( testName ); - } - - /* - * @see TestCase#setUp() - */ - public void setUp() - throws Exception - { - super.setUp(); - } - + @Test public void test1() { EnhancedStringTokenizer est = new EnhancedStringTokenizer( "this is a test string" ); @@ -50,6 +36,7 @@ public void test1() assertEquals( "this is a test string ", sb.toString() ); } + @Test public void test2() { EnhancedStringTokenizer est = new EnhancedStringTokenizer( "1,,,3,,4", "," ); @@ -61,6 +48,7 @@ public void test2() assertEquals( "Token 6", "4", est.nextToken() ); } + @Test public void test3() { EnhancedStringTokenizer est = new EnhancedStringTokenizer( "1,,,3,,4", ",", true ); @@ -77,6 +65,7 @@ public void test3() assertEquals( "Token 11", "4", est.nextToken() ); } + @Test public void testMultipleDelim() { EnhancedStringTokenizer est = new EnhancedStringTokenizer( "1 2|3|4", " |", true ); @@ -90,6 +79,7 @@ public void testMultipleDelim() assertEquals( "est.hasMoreTokens()", false, est.hasMoreTokens() ); } + @Test public void testEmptyString() { EnhancedStringTokenizer est = new EnhancedStringTokenizer( "" ); @@ -104,6 +94,7 @@ public void testEmptyString() } } + @Test public void testSimpleString() { EnhancedStringTokenizer est = new EnhancedStringTokenizer( "a " ); diff --git a/src/test/java/org/codehaus/plexus/util/cli/StreamPumperTest.java b/src/test/java/org/codehaus/plexus/util/cli/StreamPumperTest.java index a682c215..a00e156c 100644 --- a/src/test/java/org/codehaus/plexus/util/cli/StreamPumperTest.java +++ b/src/test/java/org/codehaus/plexus/util/cli/StreamPumperTest.java @@ -52,7 +52,9 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -62,32 +64,16 @@ import java.util.ArrayList; import java.util.List; +import org.junit.Test; + /** * @author Paul Julius */ public class StreamPumperTest - extends TestCase { - private String lineSeparator; - - /** - * @param testName - */ - public StreamPumperTest( String testName ) - { - super( testName ); - } - - /* - * @see TestCase#setUp() - */ - public void setUp() - throws Exception - { - super.setUp(); - lineSeparator = System.getProperty( "line.separator" ); - } + private String lineSeparator = System.lineSeparator(); + @Test public void testPumping() { String line1 = "line1"; @@ -104,6 +90,7 @@ public void testPumping() assertTrue( consumer.wasLineConsumed( line2, 1000 ) ); } + @Test public void testPumpingWithPrintWriter() { String inputString = "This a test string"; @@ -118,6 +105,7 @@ public void testPumpingWithPrintWriter() pumper.close(); } + @Test public void testPumperReadsInputStreamUntilEndEvenIfConsumerFails() { // the number of bytes generated should surely exceed the read buffer used by the pumper @@ -233,6 +221,7 @@ public void consumeLine( String line ) } } + @Test public void testEnabled() { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( "AB\nCE\nEF".getBytes() ); @@ -242,6 +231,7 @@ public void testEnabled() assertEquals( 3, streamConsumer.lines.size() ); } + @Test public void testDisabled() { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( "AB\nCE\nEF".getBytes() ); diff --git a/src/test/java/org/codehaus/plexus/util/cli/shell/BourneShellTest.java b/src/test/java/org/codehaus/plexus/util/cli/shell/BourneShellTest.java index 3a147cf3..95b70b5b 100644 --- a/src/test/java/org/codehaus/plexus/util/cli/shell/BourneShellTest.java +++ b/src/test/java/org/codehaus/plexus/util/cli/shell/BourneShellTest.java @@ -1,5 +1,6 @@ package org.codehaus.plexus.util.cli.shell; + /* * Copyright The Codehaus Foundation. * @@ -16,15 +17,17 @@ * limitations under the License. */ -import junit.framework.TestCase; -import org.codehaus.plexus.util.StringUtils; -import org.codehaus.plexus.util.cli.Commandline; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; +import org.codehaus.plexus.util.StringUtils; +import org.codehaus.plexus.util.cli.Commandline; +import org.junit.Test; + public class BourneShellTest - extends TestCase { protected Shell newShell() @@ -32,6 +35,7 @@ protected Shell newShell() return new BourneShell(); } + @Test public void testQuoteWorkingDirectoryAndExecutable() { Shell sh = newShell(); @@ -44,6 +48,7 @@ public void testQuoteWorkingDirectoryAndExecutable() assertEquals( "/bin/sh -c cd '/usr/local/bin' && 'chmod'", executable ); } + @Test public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes() { Shell sh = newShell(); @@ -56,6 +61,7 @@ public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes() assertEquals( "/bin/sh -c cd '/usr/local/'\"'\"'something else'\"'\"'' && 'chmod'", executable ); } + @Test public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep() { Shell sh = newShell(); @@ -68,6 +74,7 @@ public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_Backsl assertEquals( "/bin/sh -c cd '\\usr\\local\\\'\"'\"'something else'\"'\"'' && 'chmod'", executable ); } + @Test public void testPreserveSingleQuotesOnArgument() { Shell sh = newShell(); @@ -84,6 +91,7 @@ public void testPreserveSingleQuotesOnArgument() assertTrue( cli.endsWith( "''\"'\"'some arg with spaces'\"'\"''" ) ); } + @Test public void testAddSingleQuotesOnArgumentWithSpaces() { Shell sh = newShell(); @@ -100,6 +108,7 @@ public void testAddSingleQuotesOnArgumentWithSpaces() assertTrue( cli.endsWith( "\'" + args[0] + "\'" ) ); } + @Test public void testEscapeSingleQuotesOnArgument() { Shell sh = newShell(); @@ -117,6 +126,7 @@ public void testEscapeSingleQuotesOnArgument() shellCommandLine.get( shellCommandLine.size() - 1 ) ); } + @Test public void testArgumentsWithsemicolon() { @@ -173,6 +183,7 @@ public void testArgumentsWithsemicolon() assertEquals( "\"--password ;password\"", lines[3] ); } + @Test public void testBourneShellQuotingCharacters() throws Exception { diff --git a/src/test/java/org/codehaus/plexus/util/dag/CycleDetectedExceptionTest.java b/src/test/java/org/codehaus/plexus/util/dag/CycleDetectedExceptionTest.java index b18fe806..4d0c9ad9 100644 --- a/src/test/java/org/codehaus/plexus/util/dag/CycleDetectedExceptionTest.java +++ b/src/test/java/org/codehaus/plexus/util/dag/CycleDetectedExceptionTest.java @@ -16,18 +16,20 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; +import org.junit.Test; + /** * @author Jason van Zyl * @version $Id$ */ public class CycleDetectedExceptionTest - extends TestCase { + @Test public void testException() { final List cycle = new ArrayList(); diff --git a/src/test/java/org/codehaus/plexus/util/dag/CycleDetectorTest.java b/src/test/java/org/codehaus/plexus/util/dag/CycleDetectorTest.java index 9173ebba..df52fe0e 100644 --- a/src/test/java/org/codehaus/plexus/util/dag/CycleDetectorTest.java +++ b/src/test/java/org/codehaus/plexus/util/dag/CycleDetectorTest.java @@ -16,18 +16,24 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.util.List; +import org.junit.Test; + /** * @author Michal Maczka * @version $Id$ */ public class CycleDetectorTest - extends TestCase { + @Test public void testCycyleDetection() { // No cycle diff --git a/src/test/java/org/codehaus/plexus/util/dag/DAGTest.java b/src/test/java/org/codehaus/plexus/util/dag/DAGTest.java index 0b5f1538..0ff1269c 100644 --- a/src/test/java/org/codehaus/plexus/util/dag/DAGTest.java +++ b/src/test/java/org/codehaus/plexus/util/dag/DAGTest.java @@ -16,19 +16,23 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Set; +import org.junit.Test; + /** * @author Michal Maczka * @version $Id$ */ public class DAGTest - extends TestCase { + @Test public void testDAG() throws CycleDetectedException { @@ -131,6 +135,7 @@ public void testDAG() assertTrue( d.getParentLabels().contains( "c" ) ); } + @Test public void testGetPredecessors() throws CycleDetectedException { diff --git a/src/test/java/org/codehaus/plexus/util/dag/TopologicalSorterTest.java b/src/test/java/org/codehaus/plexus/util/dag/TopologicalSorterTest.java index fded5ee2..67afbbeb 100644 --- a/src/test/java/org/codehaus/plexus/util/dag/TopologicalSorterTest.java +++ b/src/test/java/org/codehaus/plexus/util/dag/TopologicalSorterTest.java @@ -16,18 +16,20 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; +import org.junit.Test; + /** * @author Michal Maczka * @version $Id$ */ public class TopologicalSorterTest - extends TestCase { + @Test public void testDfs() throws CycleDetectedException { diff --git a/src/test/java/org/codehaus/plexus/util/dag/VertexTest.java b/src/test/java/org/codehaus/plexus/util/dag/VertexTest.java index b7c135dc..0044795b 100644 --- a/src/test/java/org/codehaus/plexus/util/dag/VertexTest.java +++ b/src/test/java/org/codehaus/plexus/util/dag/VertexTest.java @@ -16,15 +16,17 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; /** * @author Michal Maczka * @version $Id$ */ public class VertexTest - extends TestCase { + @Test public void testVertex() { diff --git a/src/test/java/org/codehaus/plexus/util/introspection/ReflectionValueExtractorTest.java b/src/test/java/org/codehaus/plexus/util/introspection/ReflectionValueExtractorTest.java index 9c34bd38..39b3f9fa 100644 --- a/src/test/java/org/codehaus/plexus/util/introspection/ReflectionValueExtractorTest.java +++ b/src/test/java/org/codehaus/plexus/util/introspection/ReflectionValueExtractorTest.java @@ -1,5 +1,6 @@ package org.codehaus.plexus.util.introspection; + /* * Copyright The Codehaus Foundation. * @@ -16,30 +17,32 @@ * limitations under the License. */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; -import junit.framework.Assert; -import junit.framework.TestCase; import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +import org.junit.Before; +import org.junit.Test; /** * @author Jason van Zyl * @version $Id$ */ public class ReflectionValueExtractorTest - extends TestCase { private Project project; - protected void setUp() + @Before + public void setUp() throws Exception { - super.setUp(); - Dependency dependency1 = new Dependency(); dependency1.setArtifactId( "dep1" ); Dependency dependency2 = new Dependency(); @@ -63,6 +66,7 @@ protected void setUp() project.addArtifact( new Artifact( "g2", "a2", "v2", "e2", "c2" ) ); } + @Test public void testValueExtraction() throws Exception { @@ -92,9 +96,9 @@ public void testValueExtraction() List dependencies = (List) ReflectionValueExtractor.evaluate( "project.dependencies", project ); - Assert.assertNotNull( dependencies ); + assertNotNull( dependencies ); - Assert.assertEquals( 2, dependencies.size() ); + assertEquals( 2, dependencies.size() ); // ---------------------------------------------------------------------- // Dependencies - using index notation @@ -103,38 +107,38 @@ public void testValueExtraction() // List Dependency dependency = (Dependency) ReflectionValueExtractor.evaluate( "project.dependencies[0]", project ); - Assert.assertNotNull( dependency ); + assertNotNull( dependency ); - Assert.assertTrue( "dep1".equals( dependency.getArtifactId() ) ); + assertTrue( "dep1".equals( dependency.getArtifactId() ) ); String artifactId = (String) ReflectionValueExtractor.evaluate( "project.dependencies[1].artifactId", project ); - Assert.assertTrue( "dep2".equals( artifactId ) ); + assertTrue( "dep2".equals( artifactId ) ); // Array dependency = (Dependency) ReflectionValueExtractor.evaluate( "project.dependenciesAsArray[0]", project ); - Assert.assertNotNull( dependency ); + assertNotNull( dependency ); - Assert.assertTrue( "dep1".equals( dependency.getArtifactId() ) ); + assertTrue( "dep1".equals( dependency.getArtifactId() ) ); artifactId = (String) ReflectionValueExtractor.evaluate( "project.dependenciesAsArray[1].artifactId", project ); - Assert.assertTrue( "dep2".equals( artifactId ) ); + assertTrue( "dep2".equals( artifactId ) ); // Map dependency = (Dependency) ReflectionValueExtractor.evaluate( "project.dependenciesAsMap(dep1)", project ); - Assert.assertNotNull( dependency ); + assertNotNull( dependency ); - Assert.assertTrue( "dep1".equals( dependency.getArtifactId() ) ); + assertTrue( "dep1".equals( dependency.getArtifactId() ) ); artifactId = (String) ReflectionValueExtractor.evaluate( "project.dependenciesAsMap(dep2).artifactId", project ); - Assert.assertTrue( "dep2".equals( artifactId ) ); + assertTrue( "dep2".equals( artifactId ) ); // ---------------------------------------------------------------------- // Build @@ -142,26 +146,29 @@ public void testValueExtraction() Build build = (Build) ReflectionValueExtractor.evaluate( "project.build", project ); - Assert.assertNotNull( build ); + assertNotNull( build ); } + @Test public void testValueExtractorWithAInvalidExpression() throws Exception { - Assert.assertNull( ReflectionValueExtractor.evaluate( "project.foo", project ) ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "project.dependencies[10]", project ) ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "project.dependencies[0].foo", project ) ); + assertNull( ReflectionValueExtractor.evaluate( "project.foo", project ) ); + assertNull( ReflectionValueExtractor.evaluate( "project.dependencies[10]", project ) ); + assertNull( ReflectionValueExtractor.evaluate( "project.dependencies[0].foo", project ) ); } + @Test public void testMappedDottedKey() throws Exception { Map map = new HashMap(); map.put( "a.b", "a.b-value" ); - Assert.assertEquals( "a.b-value", ReflectionValueExtractor.evaluate( "h.value(a.b)", new ValueHolder( map ) ) ); + assertEquals( "a.b-value", ReflectionValueExtractor.evaluate( "h.value(a.b)", new ValueHolder( map ) ) ); } + @Test public void testIndexedMapped() throws Exception { @@ -170,9 +177,10 @@ public void testIndexedMapped() List list = new ArrayList(); list.add( map ); - Assert.assertEquals( "a-value", ReflectionValueExtractor.evaluate( "h.value[0](a)", new ValueHolder( list ) ) ); + assertEquals( "a-value", ReflectionValueExtractor.evaluate( "h.value[0](a)", new ValueHolder( list ) ) ); } + @Test public void testMappedIndexed() throws Exception { @@ -180,31 +188,35 @@ public void testMappedIndexed() list.add( "a-value" ); Map map = new HashMap(); map.put( "a", list ); - Assert.assertEquals( "a-value", ReflectionValueExtractor.evaluate( "h.value(a)[0]", new ValueHolder( map ) ) ); + assertEquals( "a-value", ReflectionValueExtractor.evaluate( "h.value(a)[0]", new ValueHolder( map ) ) ); } + @Test public void testMappedMissingDot() throws Exception { Map map = new HashMap(); map.put( "a", new ValueHolder( "a-value" ) ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "h.value(a)value", new ValueHolder( map ) ) ); + assertNull( ReflectionValueExtractor.evaluate( "h.value(a)value", new ValueHolder( map ) ) ); } + @Test public void testIndexedMissingDot() throws Exception { List list = new ArrayList(); list.add( new ValueHolder( "a-value" ) ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "h.value[0]value", new ValueHolder( list ) ) ); + assertNull( ReflectionValueExtractor.evaluate( "h.value[0]value", new ValueHolder( list ) ) ); } + @Test public void testDotDot() throws Exception { - Assert.assertNull( ReflectionValueExtractor.evaluate( "h..value", new ValueHolder( "value" ) ) ); + assertNull( ReflectionValueExtractor.evaluate( "h..value", new ValueHolder( "value" ) ) ); } + @Test public void testBadIndexedSyntax() throws Exception { @@ -212,14 +224,15 @@ public void testBadIndexedSyntax() list.add( "a-value" ); Object value = new ValueHolder( list ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "h.value[", value ) ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "h.value[]", value ) ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "h.value[a]", value ) ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "h.value[0", value ) ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "h.value[0)", value ) ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "h.value[-1]", value ) ); + assertNull( ReflectionValueExtractor.evaluate( "h.value[", value ) ); + assertNull( ReflectionValueExtractor.evaluate( "h.value[]", value ) ); + assertNull( ReflectionValueExtractor.evaluate( "h.value[a]", value ) ); + assertNull( ReflectionValueExtractor.evaluate( "h.value[0", value ) ); + assertNull( ReflectionValueExtractor.evaluate( "h.value[0)", value ) ); + assertNull( ReflectionValueExtractor.evaluate( "h.value[-1]", value ) ); } + @Test public void testBadMappedSyntax() throws Exception { @@ -227,12 +240,13 @@ public void testBadMappedSyntax() map.put( "a", "a-value" ); Object value = new ValueHolder( map ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "h.value(", value ) ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "h.value()", value ) ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "h.value(a", value ) ); - Assert.assertNull( ReflectionValueExtractor.evaluate( "h.value(a]", value ) ); + assertNull( ReflectionValueExtractor.evaluate( "h.value(", value ) ); + assertNull( ReflectionValueExtractor.evaluate( "h.value()", value ) ); + assertNull( ReflectionValueExtractor.evaluate( "h.value(a", value ) ); + assertNull( ReflectionValueExtractor.evaluate( "h.value(a]", value ) ); } + @Test public void testIllegalIndexedType() throws Exception { @@ -246,6 +260,7 @@ public void testIllegalIndexedType() } } + @Test public void testIllegalMappedType() throws Exception { @@ -259,12 +274,14 @@ public void testIllegalMappedType() } } + @Test public void testTrimRootToken() throws Exception { - Assert.assertNull( ReflectionValueExtractor.evaluate( "project", project, true ) ); + assertNull( ReflectionValueExtractor.evaluate( "project", project, true ) ); } + @Test public void testArtifactMap() throws Exception { @@ -526,6 +543,7 @@ public Object getValue() } } + @Test public void testRootPropertyRegression() throws Exception { diff --git a/src/test/java/org/codehaus/plexus/util/reflection/ReflectorTest.java b/src/test/java/org/codehaus/plexus/util/reflection/ReflectorTest.java index 841800a4..c8f1c4aa 100644 --- a/src/test/java/org/codehaus/plexus/util/reflection/ReflectorTest.java +++ b/src/test/java/org/codehaus/plexus/util/reflection/ReflectorTest.java @@ -16,24 +16,25 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; /** * @author Jörg Schaible * @version $Id$ */ public class ReflectorTest - extends TestCase { private Project project; private Reflector reflector; - protected void setUp() + @Before + public void setUp() throws Exception { - super.setUp(); - project = new Project(); project.setModelVersion( "1.0.0" ); project.setVersion( "42" ); @@ -41,18 +42,21 @@ protected void setUp() reflector = new Reflector(); } + @Test public void testObjectPropertyFromName() throws Exception { assertEquals( "1.0.0", reflector.getObjectProperty( project, "modelVersion" ) ); } + @Test public void testObjectPropertyFromBean() throws Exception { assertEquals( "Foo", reflector.getObjectProperty( project, "name" ) ); } + @Test public void testObjectPropertyFromField() throws Exception { diff --git a/src/test/java/org/codehaus/plexus/util/xml/PrettyPrintXMLWriterTest.java b/src/test/java/org/codehaus/plexus/util/xml/PrettyPrintXMLWriterTest.java index 23f37894..128d004f 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/PrettyPrintXMLWriterTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/PrettyPrintXMLWriterTest.java @@ -16,6 +16,10 @@ * limitations under the License. */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -26,8 +30,9 @@ import javax.swing.text.html.HTML.Tag; import org.codehaus.plexus.util.StringUtils; - -import junit.framework.TestCase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; /** * Test of {@link PrettyPrintXMLWriter} @@ -37,27 +42,20 @@ * @version $Id$ */ public class PrettyPrintXMLWriterTest - extends TestCase { StringWriter w; PrettyPrintXMLWriter writer; - /** {@inheritDoc} */ - protected void setUp() - throws Exception + @Before + public void setUp() { - super.setUp(); - initWriter(); } - /** {@inheritDoc} */ - protected void tearDown() - throws Exception + @After + public void tearDown() { - super.tearDown(); - writer = null; w = null; } @@ -68,6 +66,7 @@ private void initWriter() writer = new PrettyPrintXMLWriter( w ); } + @Test public void testDefaultPrettyPrintXMLWriter() { writer.startElement( Tag.HTML.toString() ); @@ -81,6 +80,7 @@ public void testDefaultPrettyPrintXMLWriter() assertEquals( expectedResult( PrettyPrintXMLWriter.LS ), w.toString() ); } + @Test public void testPrettyPrintXMLWriterWithGivenLineSeparator() { writer.setLineSeparator( "\n" ); @@ -96,6 +96,7 @@ public void testPrettyPrintXMLWriterWithGivenLineSeparator() assertEquals( expectedResult( "\n" ), w.toString() ); } + @Test public void testPrettyPrintXMLWriterWithGivenLineIndenter() { writer.setLineIndenter( " " ); @@ -111,6 +112,7 @@ public void testPrettyPrintXMLWriterWithGivenLineIndenter() assertEquals( expectedResult( " ", PrettyPrintXMLWriter.LS ), w.toString() ); } + @Test public void testEscapeXmlAttribute() { // Windows @@ -134,6 +136,7 @@ public void testEscapeXmlAttribute() assertEquals( "
        ", w.toString() ); } + @Test public void testendElementAlreadyClosed() { try @@ -151,19 +154,14 @@ public void testendElementAlreadyClosed() } /** - * Issue #51: https://github.com/codehaus-plexus/plexus-utils/issues/51 - * - * Purpose: test if concatenation string optimization bug is present. - * - * Target environment: Java 7 (u79 and u80 verified) running on Windows. - * - * Detection strategy: Tries to build a big XML file (~750MB size) and with - * many nested tags to force the JVM to trigger the concatenation string - * optimization bug that throws a NoSuchElementException when calling - * endElement() method. + * Issue #51: https://github.com/codehaus-plexus/plexus-utils/issues/51 Purpose: test if concatenation string + * optimization bug is present. Target environment: Java 7 (u79 and u80 verified) running on Windows. Detection + * strategy: Tries to build a big XML file (~750MB size) and with many nested tags to force the JVM to trigger the + * concatenation string optimization bug that throws a NoSuchElementException when calling endElement() method. * * @throws IOException if an I/O error occurs */ + @Test public void testIssue51DetectJava7ConcatenationBug() throws IOException { diff --git a/src/test/java/org/codehaus/plexus/util/xml/XmlStreamWriterTest.java b/src/test/java/org/codehaus/plexus/util/xml/XmlStreamWriterTest.java index f6ba1f90..f87ab7d3 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/XmlStreamWriterTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/XmlStreamWriterTest.java @@ -1,5 +1,7 @@ package org.codehaus.plexus.util.xml; +import static org.junit.Assert.assertEquals; + /* * Copyright The Codehaus Foundation. * @@ -19,10 +21,9 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; -import junit.framework.TestCase; +import org.junit.Test; public class XmlStreamWriterTest - extends TestCase { /** french */ private static final String TEXT_LATIN1 = "eacute: \u00E9"; @@ -71,6 +72,7 @@ private static void checkXmlWriter( String text, String encoding ) checkXmlContent( xml, effectiveEncoding ); } + @Test public void testNoXmlHeader() throws IOException { @@ -78,6 +80,7 @@ public void testNoXmlHeader() checkXmlContent( xml, "UTF-8" ); } + @Test public void testEmpty() throws IOException { @@ -91,60 +94,70 @@ public void testEmpty() writer.close(); } + @Test public void testDefaultEncoding() throws IOException { checkXmlWriter( TEXT_UNICODE, null ); } + @Test public void testUTF8Encoding() throws IOException { checkXmlWriter( TEXT_UNICODE, "UTF-8" ); } + @Test public void testUTF16Encoding() throws IOException { checkXmlWriter( TEXT_UNICODE, "UTF-16" ); } + @Test public void testUTF16BEEncoding() throws IOException { checkXmlWriter( TEXT_UNICODE, "UTF-16BE" ); } + @Test public void testUTF16LEEncoding() throws IOException { checkXmlWriter( TEXT_UNICODE, "UTF-16LE" ); } + @Test public void testLatin1Encoding() throws IOException { checkXmlWriter( TEXT_LATIN1, "ISO-8859-1" ); } + @Test public void testLatin7Encoding() throws IOException { checkXmlWriter( TEXT_LATIN7, "ISO-8859-7" ); } + @Test public void testLatin15Encoding() throws IOException { checkXmlWriter( TEXT_LATIN15, "ISO-8859-15" ); } + @Test public void testEUC_JPEncoding() throws IOException { checkXmlWriter( TEXT_EUC_JP, "EUC-JP" ); } + @Test public void testEBCDICEncoding() throws IOException { diff --git a/src/test/java/org/codehaus/plexus/util/xml/XmlUtilTest.java b/src/test/java/org/codehaus/plexus/util/xml/XmlUtilTest.java index eac61719..25ee91ae 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/XmlUtilTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/XmlUtilTest.java @@ -16,6 +16,9 @@ * limitations under the License. */ +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -26,12 +29,11 @@ import java.io.StringWriter; import java.io.Writer; -import junit.framework.TestCase; - import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.WriterFactory; +import org.junit.Test; /** * Test the {@link XmlUtil} class. @@ -40,7 +42,6 @@ * @version $Id$ */ public class XmlUtilTest - extends TestCase { private String basedir; @@ -65,20 +66,7 @@ private File getTestOutputFile( String relPath ) return file; } - /** {@inheritDoc} */ - protected void setUp() - throws Exception - { - super.setUp(); - } - - /** {@inheritDoc} */ - protected void tearDown() - throws Exception - { - super.tearDown(); - } - + @Test public void testPrettyFormatInputStreamOutputStream() throws Exception { @@ -104,6 +92,7 @@ public void testPrettyFormatInputStreamOutputStream() } } + @Test public void testPrettyFormatReaderWriter() throws Exception { @@ -130,6 +119,7 @@ public void testPrettyFormatReaderWriter() } } + @Test public void testPrettyFormatString() throws Exception { @@ -160,6 +150,7 @@ public void testPrettyFormatString() assertTrue( countEOL < StringUtils.countMatches( writer.toString(), XmlUtil.DEFAULT_LINE_SEPARATOR ) ); } + @Test public void testPrettyFormatReaderWriter2() throws Exception { diff --git a/src/test/java/org/codehaus/plexus/util/xml/XmlWriterUtilTest.java b/src/test/java/org/codehaus/plexus/util/xml/XmlWriterUtilTest.java index bb29b157..6c4fe638 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/XmlWriterUtilTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/XmlWriterUtilTest.java @@ -16,21 +16,24 @@ * limitations under the License. */ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.Writer; -import junit.framework.TestCase; - import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.WriterFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; /** * @author Vincent Siveton * @version $Id$ */ public class XmlWriterUtilTest - extends TestCase { private OutputStream output; @@ -38,23 +41,19 @@ public class XmlWriterUtilTest private XMLWriter xmlWriter; - /** {@inheritDoc} */ - protected void setUp() + @Before + public void setUp() throws Exception { - super.setUp(); - output = new ByteArrayOutputStream(); writer = WriterFactory.newXmlWriter( output ); xmlWriter = new PrettyPrintXMLWriter( writer ); } - /** {@inheritDoc} */ - protected void tearDown() + @After + public void tearDown() throws Exception { - super.tearDown(); - xmlWriter = null; writer = null; output = null; @@ -66,6 +65,7 @@ protected void tearDown() * * @throws Exception if any */ + @Test public void testWriteLineBreakXMLWriter() throws Exception { @@ -80,6 +80,7 @@ public void testWriteLineBreakXMLWriter() * * @throws Exception if any */ + @Test public void testWriteLineBreakXMLWriterInt() throws Exception { @@ -94,6 +95,7 @@ public void testWriteLineBreakXMLWriterInt() * * @throws Exception if any */ + @Test public void testWriteLineBreakXMLWriterIntInt() throws Exception { @@ -111,6 +113,7 @@ public void testWriteLineBreakXMLWriterIntInt() * * @throws Exception if any */ + @Test public void testWriteLineBreakXMLWriterIntIntInt() throws Exception { @@ -126,6 +129,7 @@ public void testWriteLineBreakXMLWriterIntIntInt() * * @throws Exception if any */ + @Test public void testWriteCommentLineBreakXMLWriter() throws Exception { @@ -143,6 +147,7 @@ public void testWriteCommentLineBreakXMLWriter() * * @throws Exception if any */ + @Test public void testWriteCommentLineBreakXMLWriterInt() throws Exception { @@ -164,6 +169,7 @@ public void testWriteCommentLineBreakXMLWriterInt() * * @throws Exception if any */ + @Test public void testWriteCommentXMLWriterString() throws Exception { @@ -204,6 +210,7 @@ public void testWriteCommentXMLWriterString() * * @throws Exception if any */ + @Test public void testWriteCommentXMLWriterStringInt() throws Exception { @@ -239,6 +246,7 @@ public void testWriteCommentXMLWriterStringInt() * * @throws Exception if any */ + @Test public void testWriteCommentXMLWriterStringIntInt() throws Exception { @@ -274,6 +282,7 @@ public void testWriteCommentXMLWriterStringIntInt() * * @throws Exception if any */ + @Test public void testWriteCommentXMLWriterStringIntIntInt() throws Exception { @@ -305,6 +314,7 @@ public void testWriteCommentXMLWriterStringIntIntInt() * * @throws Exception if any */ + @Test public void testWriteCommentTextXMLWriterStringInt() throws Exception { @@ -347,6 +357,7 @@ public void testWriteCommentTextXMLWriterStringInt() * * @throws Exception if any */ + @Test public void testWriteCommentTextXMLWriterStringIntInt() throws Exception { @@ -372,6 +383,7 @@ public void testWriteCommentTextXMLWriterStringIntInt() * * @throws Exception if any */ + @Test public void testWriteCommentTextXMLWriterStringIntIntInt() throws Exception { @@ -397,6 +409,7 @@ public void testWriteCommentTextXMLWriterStringIntIntInt() * * @throws Exception if any */ + @Test public void testWriteCommentNull() throws Exception { @@ -413,6 +426,7 @@ public void testWriteCommentNull() * * @throws Exception if any */ + @Test public void testWriteCommentShort() throws Exception { @@ -429,6 +443,7 @@ public void testWriteCommentShort() * * @throws Exception if any */ + @Test public void testWriteCommentLong() throws Exception { diff --git a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomBuilderTest.java b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomBuilderTest.java index 76b0ec5d..0c8e5a17 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomBuilderTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomBuilderTest.java @@ -16,15 +16,19 @@ * limitations under the License. */ -import junit.framework.TestCase; -import org.codehaus.plexus.util.xml.pull.MXParser; -import org.codehaus.plexus.util.xml.pull.XmlPullParser; -import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; +import org.codehaus.plexus.util.xml.pull.MXParser; +import org.codehaus.plexus.util.xml.pull.XmlPullParser; +import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +import org.junit.Test; + /** * Test the Xpp3DomBuilder. * @@ -32,11 +36,10 @@ * @version $Id$ */ public class Xpp3DomBuilderTest - extends TestCase { + private static final String LS = System.lineSeparator(); - private static final String LS = System.getProperty( "line.separator" ); - + @Test public void testBuildFromReader() throws Exception { @@ -49,6 +52,7 @@ public void testBuildFromReader() assertEquals( "check DOMs match", expectedDom, dom ); } + @Test public void testBuildTrimming() throws Exception { @@ -63,6 +67,7 @@ public void testBuildTrimming() assertEquals( "test with trimming off", " element1\n ", dom.getChild( "el1" ).getValue() ); } + @Test public void testBuildFromXpp3Dom() throws Exception { @@ -120,6 +125,7 @@ else if ( "root".equals( rawName ) ) /** * Test we get an error from the parser, and don't hit the IllegalStateException. */ + @Test public void testUnclosedXml() { String domString = "" + createDomString(); @@ -139,6 +145,7 @@ public void testUnclosedXml() } } + @Test public void testEscapingInContent() throws IOException, XmlPullParserException { @@ -153,6 +160,7 @@ public void testEscapingInContent() assertEquals( "Compare stringified DOMs", getExpectedString(), w.toString() ); } + @Test public void testEscapingInAttributes() throws IOException, XmlPullParserException { @@ -167,6 +175,35 @@ public void testEscapingInAttributes() assertEquals( "Compare stringified DOMs", newString, s ); } + @Test + public void testInputLocationTracking() + throws IOException, XmlPullParserException + { + Xpp3DomBuilder.InputLocationBuilder ilb = new Xpp3DomBuilder.InputLocationBuilder() { + public Object toInputLocation( XmlPullParser parser ) + { + return parser.getLineNumber(); // store only line number as a simple Integer + } + + }; + Xpp3Dom dom = Xpp3DomBuilder.build( new StringReader( createDomString() ), true, ilb ); + Xpp3Dom expectedDom = createExpectedDom(); + assertEquals( "root input location", expectedDom.getInputLocation(), dom.getInputLocation() ); + for( int i = 0; i < dom.getChildCount(); i++ ) + { + Xpp3Dom elt = dom.getChild( i ); + Xpp3Dom expectedElt = expectedDom.getChild( i ); + assertEquals( elt.getName() + " input location", expectedElt.getInputLocation(), elt.getInputLocation() ); + + if ( "el2".equals( elt.getName() ) ) + { + Xpp3Dom el3 = elt.getChild( 0 ); + Xpp3Dom expectedEl3 = expectedElt.getChild( 0 ); + assertEquals( el3.getName() + " input location", expectedEl3.getInputLocation(), el3.getInputLocation() ); + } + } + } + private static String getAttributeEncodedString() { StringBuilder domString = new StringBuilder(); @@ -229,23 +266,33 @@ private static String createDomString() private static Xpp3Dom createExpectedDom() { + int line = 1; Xpp3Dom expectedDom = new Xpp3Dom( "root" ); + expectedDom.setInputLocation( line ); Xpp3Dom el1 = new Xpp3Dom( "el1" ); + el1.setInputLocation( ++line ); el1.setValue( "element1" ); expectedDom.addChild( el1 ); + ++line; // newline trimmed in Xpp3Dom but not in source Xpp3Dom el2 = new Xpp3Dom( "el2" ); + el2.setInputLocation( ++line ); el2.setAttribute( "att2", "attribute2\nnextline" ); expectedDom.addChild( el2 ); Xpp3Dom el3 = new Xpp3Dom( "el3" ); + el3.setInputLocation( ++line ); el3.setAttribute( "att3", "attribute3" ); el3.setValue( "element3" ); el2.addChild( el3 ); + ++line; Xpp3Dom el4 = new Xpp3Dom( "el4" ); + el4.setInputLocation( ++line ); el4.setValue( "" ); expectedDom.addChild( el4 ); Xpp3Dom el5 = new Xpp3Dom( "el5" ); + el5.setInputLocation( ++line ); expectedDom.addChild( el5 ); Xpp3Dom el6 = new Xpp3Dom( "el6" ); + el6.setInputLocation( ++line ); el6.setAttribute( "xml:space", "preserve" ); el6.setValue( " do not trim " ); expectedDom.addChild( el6 ); diff --git a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomTest.java b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomTest.java index 4c94a203..04444f31 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomTest.java @@ -16,34 +16,44 @@ * limitations under the License. */ -import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; -import junit.framework.TestCase; +import org.codehaus.plexus.util.xml.pull.XmlPullParser; +import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +import org.junit.Test; public class Xpp3DomTest - extends TestCase { - + @Test public void testShouldPerformAppendAtFirstSubElementLevel() { // create the dominant DOM Xpp3Dom t1 = new Xpp3Dom( "top" ); t1.setAttribute( Xpp3Dom.CHILDREN_COMBINATION_MODE_ATTRIBUTE, Xpp3Dom.CHILDREN_COMBINATION_APPEND ); + t1.setInputLocation( "t1top" ); Xpp3Dom t1s1 = new Xpp3Dom( "topsub1" ); t1s1.setValue( "t1s1Value" ); + t1s1.setInputLocation( "t1s1" ); t1.addChild( t1s1 ); // create the recessive DOM Xpp3Dom t2 = new Xpp3Dom( "top" ); + t2.setInputLocation( "t2top" ); Xpp3Dom t2s1 = new Xpp3Dom( "topsub1" ); t2s1.setValue( "t2s1Value" ); + t2s1.setInputLocation( "t2s1" ); t2.addChild( t2s1 ); @@ -51,24 +61,35 @@ public void testShouldPerformAppendAtFirstSubElementLevel() Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( t1, t2 ); assertEquals( 2, result.getChildren( "topsub1" ).length ); + assertEquals( "t2s1Value", result.getChildren( "topsub1" )[0].getValue() ); + assertEquals( "t1s1Value", result.getChildren( "topsub1" )[1].getValue() ); + + assertEquals( "t1top", result.getInputLocation() ); + assertEquals( "t2s1", result.getChildren( "topsub1" )[0].getInputLocation() ); + assertEquals( "t1s1", result.getChildren( "topsub1" )[1].getInputLocation() ); } + @Test public void testShouldOverrideAppendAndDeepMerge() { // create the dominant DOM Xpp3Dom t1 = new Xpp3Dom( "top" ); t1.setAttribute( Xpp3Dom.CHILDREN_COMBINATION_MODE_ATTRIBUTE, Xpp3Dom.CHILDREN_COMBINATION_APPEND ); + t1.setInputLocation( "t1top" ); Xpp3Dom t1s1 = new Xpp3Dom( "topsub1" ); t1s1.setValue( "t1s1Value" ); + t1s1.setInputLocation( "t1s1" ); t1.addChild( t1s1 ); // create the recessive DOM Xpp3Dom t2 = new Xpp3Dom( "top" ); + t2.setInputLocation( "t2top" ); Xpp3Dom t2s1 = new Xpp3Dom( "topsub1" ); t2s1.setValue( "t2s1Value" ); + t2s1.setInputLocation( "t2s1" ); t2.addChild( t2s1 ); @@ -76,13 +97,19 @@ public void testShouldOverrideAppendAndDeepMerge() Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( t1, t2, Boolean.TRUE ); assertEquals( 1, result.getChildren( "topsub1" ).length ); + assertEquals( "t1s1Value", result.getChildren( "topsub1" )[0].getValue() ); + + assertEquals( "t1top", result.getInputLocation() ); + assertEquals( "t1s1", result.getChildren( "topsub1" )[0].getInputLocation() ); } + @Test public void testShouldPerformSelfOverrideAtTopLevel() { // create the dominant DOM Xpp3Dom t1 = new Xpp3Dom( "top" ); t1.setAttribute( "attr", "value" ); + t1.setInputLocation( "t1top" ); t1.setAttribute( Xpp3Dom.SELF_COMBINATION_MODE_ATTRIBUTE, Xpp3Dom.SELF_COMBINATION_OVERRIDE ); @@ -90,24 +117,29 @@ public void testShouldPerformSelfOverrideAtTopLevel() Xpp3Dom t2 = new Xpp3Dom( "top" ); t2.setAttribute( "attr2", "value2" ); t2.setValue( "t2Value" ); + t2.setInputLocation( "t2top" ); // merge and check results. Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( t1, t2 ); assertEquals( 2, result.getAttributeNames().length ); assertNull( result.getValue() ); + assertEquals( "t1top", result.getInputLocation() ); } + @Test public void testShouldMergeValuesAtTopLevelByDefault() { // create the dominant DOM Xpp3Dom t1 = new Xpp3Dom( "top" ); t1.setAttribute( "attr", "value" ); + t1.setInputLocation( "t1top" ); // create the recessive DOM Xpp3Dom t2 = new Xpp3Dom( "top" ); t2.setAttribute( "attr2", "value2" ); t2.setValue( "t2Value" ); + t2.setInputLocation( "t2top" ); // merge and check results. Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( t1, t2 ); @@ -116,8 +148,10 @@ public void testShouldMergeValuesAtTopLevelByDefault() assertEquals( 2, result.getAttributeNames().length ); assertEquals( result.getValue(), t2.getValue() ); + assertEquals( "t2top", result.getInputLocation() ); } + @Test public void testShouldMergeValuesAtTopLevel() { // create the dominant DOM @@ -138,6 +172,7 @@ public void testShouldMergeValuesAtTopLevel() assertEquals( result.getValue(), t2.getValue() ); } + @Test public void testNullAttributeNameOrValue() { Xpp3Dom t1 = new Xpp3Dom( "top" ); @@ -161,6 +196,7 @@ public void testNullAttributeNameOrValue() t1.toString(); } + @Test public void testEquals() { Xpp3Dom dom = new Xpp3Dom( "top" ); @@ -170,6 +206,7 @@ public void testEquals() assertFalse( dom.equals( new Xpp3Dom( (String) null ) ) ); } + @Test public void testEqualsIsNullSafe() throws XmlPullParserException, IOException { @@ -196,14 +233,17 @@ public void testEqualsIsNullSafe() } } + @Test public void testShouldOverwritePluginConfigurationSubItemsByDefault() throws XmlPullParserException, IOException { String parentConfigStr = "onetwo"; - Xpp3Dom parentConfig = Xpp3DomBuilder.build( new StringReader( parentConfigStr ) ); + Xpp3Dom parentConfig = + Xpp3DomBuilder.build( new StringReader( parentConfigStr ), new FixedInputLocationBuilder( "parent" ) ); String childConfigStr = "three"; - Xpp3Dom childConfig = Xpp3DomBuilder.build( new StringReader( childConfigStr ) ); + Xpp3Dom childConfig = + Xpp3DomBuilder.build( new StringReader( childConfigStr ), new FixedInputLocationBuilder( "child" ) ); Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( childConfig, parentConfig ); Xpp3Dom items = result.getChild( "items" ); @@ -212,17 +252,21 @@ public void testShouldOverwritePluginConfigurationSubItemsByDefault() Xpp3Dom item = items.getChild( 0 ); assertEquals( "three", item.getValue() ); + assertEquals( "child", item.getInputLocation() ); } + @Test public void testShouldMergePluginConfigurationSubItemsWithMergeAttributeSet() throws XmlPullParserException, IOException { String parentConfigStr = "onetwo"; - Xpp3Dom parentConfig = Xpp3DomBuilder.build( new StringReader( parentConfigStr ) ); + Xpp3Dom parentConfig = + Xpp3DomBuilder.build( new StringReader( parentConfigStr ), new FixedInputLocationBuilder( "parent" ) ); String childConfigStr = "three"; - Xpp3Dom childConfig = Xpp3DomBuilder.build( new StringReader( childConfigStr ) ); + Xpp3Dom childConfig = + Xpp3DomBuilder.build( new StringReader( childConfigStr ), new FixedInputLocationBuilder( "child" ) ); Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( childConfig, parentConfig ); Xpp3Dom items = result.getChild( "items" ); @@ -232,10 +276,14 @@ public void testShouldMergePluginConfigurationSubItemsWithMergeAttributeSet() Xpp3Dom[] item = items.getChildren(); assertEquals( "one", item[0].getValue() ); + assertEquals( "parent", item[0].getInputLocation() ); assertEquals( "two", item[1].getValue() ); + assertEquals( "parent", item[1].getInputLocation() ); assertEquals( "three", item[2].getValue() ); + assertEquals( "child", item[2].getInputLocation() ); } + @Test public void testShouldNotChangeUponMergeWithItselfWhenFirstOrLastSubItemIsEmpty() throws Exception { @@ -253,6 +301,7 @@ public void testShouldNotChangeUponMergeWithItselfWhenFirstOrLastSubItemIsEmpty( assertEquals( null, items.getChild( 2 ).getValue() ); } + @Test public void testShouldCopyRecessiveChildrenNotPresentInTarget() throws Exception { @@ -270,6 +319,7 @@ public void testShouldCopyRecessiveChildrenNotPresentInTarget() assertNotSame( result.getChild( "bar" ), recessiveConfig.getChild( "bar" ) ); } + @Test public void testDupeChildren() throws IOException, XmlPullParserException { @@ -278,4 +328,20 @@ public void testDupeChildren() assertNotNull( dom ); assertEquals( "y", dom.getChild( "foo" ).getValue() ); } + + private static class FixedInputLocationBuilder + implements Xpp3DomBuilder.InputLocationBuilder + { + private final Object location; + + public FixedInputLocationBuilder( Object location ) + { + this.location = location; + } + + public Object toInputLocation( XmlPullParser parser ) + { + return location; + } + } } diff --git a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomUtilsTest.java b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomUtilsTest.java index 5be4fa85..f4d0eb04 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomUtilsTest.java @@ -16,14 +16,16 @@ * limitations under the License. */ +import static org.junit.Assert.assertEquals; + import java.io.StringReader; -import junit.framework.TestCase; +import org.codehaus.plexus.util.xml.pull.XmlPullParser; +import org.junit.Test; public class Xpp3DomUtilsTest - extends TestCase { - + @Test public void testCombineId() throws Exception { @@ -33,17 +35,44 @@ public void testCombineId() String rhs = "" + "RHS-ONLYRHS" + "TOOVERWRITERHS" + ""; - Xpp3Dom leftDom = Xpp3DomBuilder.build( new StringReader( lhs ) ); - Xpp3Dom rightDom = Xpp3DomBuilder.build( new StringReader( rhs ) ); + Xpp3Dom leftDom = Xpp3DomBuilder.build( new StringReader( lhs ), new FixedInputLocationBuilder( "left" ) ); + Xpp3Dom rightDom = Xpp3DomBuilder.build( new StringReader( rhs ), new FixedInputLocationBuilder( "right" ) ); Xpp3Dom mergeResult = Xpp3DomUtils.mergeXpp3Dom( leftDom, rightDom, true ); assertEquals( 3, mergeResult.getChildren( "property" ).length ); - assertEquals( "LHS-ONLY", mergeResult.getChildren( "property" )[0].getChild( "name" ).getValue() ); - assertEquals( "LHS", mergeResult.getChildren( "property" )[0].getChild( "value" ).getValue() ); + Xpp3Dom p0 = mergeResult.getChildren( "property" )[0]; + assertEquals( "LHS-ONLY", p0.getChild( "name" ).getValue() ); + assertEquals( "left", p0.getChild( "name" ).getInputLocation() ); + assertEquals( "LHS", p0.getChild( "value" ).getValue() ); + assertEquals( "left", p0.getChild( "value" ).getInputLocation() ); + + Xpp3Dom p1 = mergeResult.getChildren( "property" )[1]; assertEquals( "TOOVERWRITE", mergeResult.getChildren( "property" )[1].getChild( "name" ).getValue() ); + assertEquals( "left", p1.getChild( "name" ).getInputLocation() ); assertEquals( "LHS", mergeResult.getChildren( "property" )[1].getChild( "value" ).getValue() ); + assertEquals( "left", p1.getChild( "value" ).getInputLocation() ); + + Xpp3Dom p2 = mergeResult.getChildren( "property" )[2]; assertEquals( "RHS-ONLY", mergeResult.getChildren( "property" )[2].getChild( "name" ).getValue() ); + assertEquals( "right", p2.getChild( "name" ).getInputLocation() ); assertEquals( "RHS", mergeResult.getChildren( "property" )[2].getChild( "value" ).getValue() ); + assertEquals( "right", p2.getChild( "value" ).getInputLocation() ); + } + + private static class FixedInputLocationBuilder + implements Xpp3DomBuilder.InputLocationBuilder + { + private final Object location; + + public FixedInputLocationBuilder( Object location ) + { + this.location = location; + } + + public Object toInputLocation( XmlPullParser parser ) + { + return location; + } } } diff --git a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomWriterTest.java b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomWriterTest.java index 81ea5951..c218e4c7 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomWriterTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomWriterTest.java @@ -16,18 +16,20 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; import java.io.StringWriter; +import org.junit.Test; + /** * @author Edwin Punzalan */ public class Xpp3DomWriterTest - extends TestCase { private static final String LS = System.getProperty( "line.separator" ); + @Test public void testWriter() { StringWriter writer = new StringWriter(); @@ -37,6 +39,7 @@ public void testWriter() assertEquals( "Check if output matches", createExpectedXML( true ), writer.toString() ); } + @Test public void testWriterNoEscape() { StringWriter writer = new StringWriter(); diff --git a/src/test/java/org/codehaus/plexus/util/xml/pull/MXParserTest.java b/src/test/java/org/codehaus/plexus/util/xml/pull/MXParserTest.java index 5df8a972..ee6203b1 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/pull/MXParserTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/pull/MXParserTest.java @@ -16,18 +16,22 @@ * limitations under the License. */ -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.IOException; import java.io.StringReader; +import org.junit.Test; + /** * @author Trygve Laugstøl * @version $Id$ */ public class MXParserTest - extends TestCase { + @Test public void testHexadecimalEntities() throws Exception { @@ -48,6 +52,7 @@ public void testHexadecimalEntities() assertEquals( XmlPullParser.END_TAG, parser.next() ); } + @Test public void testDecimalEntities() throws Exception { @@ -68,6 +73,7 @@ public void testDecimalEntities() assertEquals( XmlPullParser.END_TAG, parser.next() ); } + @Test public void testPredefinedEntities() throws Exception { @@ -88,6 +94,7 @@ public void testPredefinedEntities() assertEquals( XmlPullParser.END_TAG, parser.next() ); } + @Test public void testEntityReplacementMap() throws XmlPullParserException, IOException { @@ -103,6 +110,7 @@ public void testEntityReplacementMap() assertEquals( XmlPullParser.END_TAG, parser.next() ); } + @Test public void testCustomEntities() throws Exception { @@ -127,6 +135,7 @@ public void testCustomEntities() assertEquals( XmlPullParser.END_TAG, parser.next() ); } + @Test public void testUnicodeEntities() throws Exception { @@ -149,6 +158,7 @@ public void testUnicodeEntities() assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); } + @Test public void testProcessingInstruction() throws Exception { @@ -163,6 +173,7 @@ public void testProcessingInstruction() assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); } + @Test public void testSubsequentProcessingInstructionShort() throws Exception { @@ -184,6 +195,7 @@ public void testSubsequentProcessingInstructionShort() assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); } + @Test public void testSubsequentProcessingInstructionMoreThan8k() throws Exception { @@ -225,4 +237,136 @@ public void testSubsequentProcessingInstructionMoreThan8k() assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken() ); assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); } + + public void testMalformedProcessingInstructionAfterTag() + throws Exception + { + MXParser parser = new MXParser(); + + String input = ""; + + parser.setInput( new StringReader( input ) ); + + try + { + assertEquals( XmlPullParser.START_TAG, parser.next() ); + + assertEquals( XmlPullParser.END_TAG, parser.next() ); + + assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.next() ); + + fail( "Should fail since it has an invalid Processing Instruction" ); + } + catch ( XmlPullParserException ex ) + { + assertTrue( ex.getMessage().contains( "processing instruction PITarget name not found" ) ); + } + } + + public void testMalformedProcessingInstructionBeforeTag() + throws Exception + { + MXParser parser = new MXParser(); + + String input = ""; + + parser.setInput( new StringReader( input ) ); + + try + { + assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.next() ); + + assertEquals( XmlPullParser.START_TAG, parser.next() ); + + assertEquals( XmlPullParser.END_TAG, parser.next() ); + + fail( "Should fail since it has invalid PI" ); + } + catch ( XmlPullParserException ex ) + { + assertTrue( ex.getMessage().contains( "processing instruction PITarget name not found" ) ); + } + } + + public void testMalformedProcessingInstructionSpaceBeforeName() + throws Exception + { + MXParser parser = new MXParser(); + + StringBuilder sb = new StringBuilder(); + sb.append( "" ); + sb.append( "" ); + + parser.setInput( new StringReader( sb.toString() ) ); + + try + { + assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.next() ); + + assertEquals( XmlPullParser.START_TAG, parser.next() ); + + assertEquals( XmlPullParser.END_TAG, parser.next() ); + + fail( "Should fail since it has invalid PI" ); + } + catch ( XmlPullParserException ex ) + { + assertTrue( ex.getMessage().contains( "processing instruction PITarget must be exactly after " ); + sb.append( "" ); + + parser.setInput( new StringReader( sb.toString() ) ); + + try + { + assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.next() ); + + assertEquals( XmlPullParser.START_TAG, parser.next() ); + + assertEquals( XmlPullParser.END_TAG, parser.next() ); + + fail( "Should fail since it has invalid PI" ); + } + catch ( XmlPullParserException ex ) + { + assertTrue( ex.getMessage().contains( "processing instruction started on line 1 and column 2 was not closed" ) ); + } + } + + public void testSubsequentMalformedProcessingInstructionNoClosingQuestionMark() + throws Exception + { + MXParser parser = new MXParser(); + + StringBuilder sb = new StringBuilder(); + sb.append( "" ); + sb.append( "" ); + + parser.setInput( new StringReader( sb.toString() ) ); + + try + { + assertEquals( XmlPullParser.START_TAG, parser.next() ); + + assertEquals( XmlPullParser.END_TAG, parser.next() ); + + assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.next() ); + + fail( "Should fail since it has invalid PI" ); + } + catch ( XmlPullParserException ex ) + { + assertTrue( ex.getMessage().contains( "processing instruction started on line 1 and column 13 was not closed" ) ); + } + } + }