diff --git a/pom.xml b/pom.xml index 87470bae..3fd99a42 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -30,14 +28,13 @@ limitations under the License. Plexus Common Utilities A collection of various utility classes to ease working with strings, files, command lines, XML and - more. - + more. scm:git:git@github.com:codehaus-plexus/plexus-utils.git scm:git:git@github.com:codehaus-plexus/plexus-utils.git - http://github.com/codehaus-plexus/plexus-utils plexus-utils-3.5.0 + http://github.com/codehaus-plexus/plexus-utils github @@ -110,15 +107,17 @@ limitations under the License. org.apache.maven.plugins maven-scm-publish-plugin - ${project.reporting.outputDirectory} + ${project.reporting.outputDirectory} + scm-publish - site-deploy + publish-scm + site-deploy @@ -178,8 +177,8 @@ limitations under the License. 9 ${project.basedir}/src/main/java9 - - true + + true @@ -208,8 +207,8 @@ limitations under the License. 10 ${project.basedir}/src/main/java10 - - true + + true @@ -219,35 +218,35 @@ limitations under the License. - jdk11+ - - [11,) - - - - - - maven-compiler-plugin - - - compile-java-11 - - compile - - - 11 - - ${project.basedir}/src/main/java11 + jdk11+ + + [11,) + + + + + + maven-compiler-plugin + + + compile-java-11 + + compile + + + 11 + + ${project.basedir}/src/main/java11 true - - - - - - - - + + + + + + + + plexus-release diff --git a/src/main/java/org/codehaus/plexus/util/AbstractScanner.java b/src/main/java/org/codehaus/plexus/util/AbstractScanner.java index 16d64ef9..a10f43c7 100644 --- a/src/main/java/org/codehaus/plexus/util/AbstractScanner.java +++ b/src/main/java/org/codehaus/plexus/util/AbstractScanner.java @@ -24,9 +24,7 @@ /** * Scan a directory tree for files, with specified inclusions and exclusions. */ -public abstract class AbstractScanner - implements Scanner -{ +public abstract class AbstractScanner implements Scanner { /** * Patterns which should be excluded by default, like SCM files *
    @@ -54,16 +52,24 @@ public abstract class AbstractScanner */ public static final String[] DEFAULTEXCLUDES = { // Miscellaneous typical temporary files - "**/*~", "**/#*#", "**/.#*", "**/%*%", "**/._*", + "**/*~", + "**/#*#", + "**/.#*", + "**/%*%", + "**/._*", // CVS - "**/CVS", "**/CVS/**", "**/.cvsignore", + "**/CVS", + "**/CVS/**", + "**/.cvsignore", // RCS - "**/RCS", "**/RCS/**", + "**/RCS", + "**/RCS/**", // SCCS - "**/SCCS", "**/SCCS/**", + "**/SCCS", + "**/SCCS/**", // Visual SourceSafe "**/vssver.scc", @@ -72,13 +78,16 @@ public abstract class AbstractScanner "**/project.pj", // Subversion - "**/.svn", "**/.svn/**", + "**/.svn", + "**/.svn/**", // Arch - "**/.arch-ids", "**/.arch-ids/**", + "**/.arch-ids", + "**/.arch-ids/**", // Bazaar - "**/.bzr", "**/.bzr/**", + "**/.bzr", + "**/.bzr/**", // SurroundSCM "**/.MySCMServerInfo", @@ -87,19 +96,31 @@ public abstract class AbstractScanner "**/.DS_Store", // Serena Dimensions Version 10 - "**/.metadata", "**/.metadata/**", + "**/.metadata", + "**/.metadata/**", // Mercurial - "**/.hg", "**/.hg/**", + "**/.hg", + "**/.hg/**", // git - "**/.git", "**/.git/**", + "**/.git", + "**/.git/**", // BitKeeper - "**/BitKeeper", "**/BitKeeper/**", "**/ChangeSet", "**/ChangeSet/**", + "**/BitKeeper", + "**/BitKeeper/**", + "**/ChangeSet", + "**/ChangeSet/**", // darcs - "**/_darcs", "**/_darcs/**", "**/.darcsrepo", "**/.darcsrepo/**", "**/-darcs-backup*", "**/.darcs-temp-mail" }; + "**/_darcs", + "**/_darcs/**", + "**/.darcsrepo", + "**/.darcsrepo/**", + "**/-darcs-backup*", + "**/.darcs-temp-mail" + }; /** * The patterns for the files to be included. @@ -130,8 +151,7 @@ public abstract class AbstractScanner * * @param isCaseSensitive whether or not the file system should be regarded as a case sensitive one */ - public void setCaseSensitive( boolean isCaseSensitive ) - { + public void setCaseSensitive(boolean isCaseSensitive) { this.isCaseSensitive = isCaseSensitive; } @@ -145,9 +165,8 @@ public void setCaseSensitive( boolean isCaseSensitive ) * @param str The path to match, as a String. Must not be null. * @return whether or not a given path matches the start of a given pattern up to the first "**". */ - protected static boolean matchPatternStart( String pattern, String str ) - { - return SelectorUtils.matchPatternStart( pattern, str ); + protected static boolean matchPatternStart(String pattern, String str) { + return SelectorUtils.matchPatternStart(pattern, str); } /** @@ -161,9 +180,8 @@ protected static boolean matchPatternStart( String pattern, String str ) * @param isCaseSensitive Whether or not matching should be performed case sensitively. * @return whether or not a given path matches the start of a given pattern up to the first "**". */ - protected static boolean matchPatternStart( String pattern, String str, boolean isCaseSensitive ) - { - return SelectorUtils.matchPatternStart( pattern, str, isCaseSensitive ); + protected static boolean matchPatternStart(String pattern, String str, boolean isCaseSensitive) { + return SelectorUtils.matchPatternStart(pattern, str, isCaseSensitive); } /** @@ -173,9 +191,8 @@ protected static boolean matchPatternStart( String pattern, String str, boolean * @param str The path to match, as a String. Must not be null. * @return true if the pattern matches against the string, or false otherwise. */ - protected static boolean matchPath( String pattern, String str ) - { - return SelectorUtils.matchPath( pattern, str ); + protected static boolean matchPath(String pattern, String str) { + return SelectorUtils.matchPath(pattern, str); } /** @@ -186,9 +203,8 @@ protected static boolean matchPath( String pattern, String str ) * @param isCaseSensitive Whether or not matching should be performed case sensitively. * @return true if the pattern matches against the string, or false otherwise. */ - protected static boolean matchPath( String pattern, String str, boolean isCaseSensitive ) - { - return SelectorUtils.matchPath( pattern, str, isCaseSensitive ); + protected static boolean matchPath(String pattern, String str, boolean isCaseSensitive) { + return SelectorUtils.matchPath(pattern, str, isCaseSensitive); } /** @@ -200,9 +216,8 @@ protected static boolean matchPath( String pattern, String str, boolean isCaseSe * @param str The string which must be matched against the pattern. Must not be null. * @return true if the string matches against the pattern, or false otherwise. */ - public static boolean match( String pattern, String str ) - { - return SelectorUtils.match( pattern, str ); + public static boolean match(String pattern, String str) { + return SelectorUtils.match(pattern, str); } /** @@ -215,9 +230,8 @@ public static boolean match( String pattern, String str ) * @param isCaseSensitive Whether or not matching should be performed case sensitively. * @return true if the string matches against the pattern, or false otherwise. */ - protected static boolean match( String pattern, String str, boolean isCaseSensitive ) - { - return SelectorUtils.match( pattern, str, isCaseSensitive ); + protected static boolean match(String pattern, String str, boolean isCaseSensitive) { + return SelectorUtils.match(pattern, str, isCaseSensitive); } /** @@ -230,23 +244,17 @@ protected static boolean match( String pattern, String str, boolean isCaseSensit * included. If a non-null list is given, all elements must be non-null. */ @Override - public void setIncludes( String[] includes ) - { - if ( includes == null ) - { + public void setIncludes(String[] includes) { + if (includes == null) { this.includes = null; - } - else - { - final List list = new ArrayList( includes.length ); - for ( String include : includes ) - { - if ( include != null ) - { - list.add( normalizePattern( include ) ); + } else { + final List list = new ArrayList(includes.length); + for (String include : includes) { + if (include != null) { + list.add(normalizePattern(include)); } } - this.includes = list.toArray( new String[0] ); + this.includes = list.toArray(new String[0]); } } @@ -260,23 +268,17 @@ public void setIncludes( String[] includes ) * excluded. If a non-null list is given, all elements must be non-null. */ @Override - public void setExcludes( String[] excludes ) - { - if ( excludes == null ) - { + public void setExcludes(String[] excludes) { + if (excludes == null) { this.excludes = null; - } - else - { - final List list = new ArrayList( excludes.length ); - for ( String exclude : excludes ) - { - if ( exclude != null ) - { - list.add( normalizePattern( exclude ) ); + } else { + final List list = new ArrayList(excludes.length); + for (String exclude : excludes) { + if (exclude != null) { + list.add(normalizePattern(exclude)); } } - this.excludes = list.toArray( new String[0] ); + this.excludes = list.toArray(new String[0]); } } @@ -286,27 +288,19 @@ public void setExcludes( String[] excludes ) * @param pattern The pattern to normalize, must not be null. * @return The normalized pattern, never null. */ - private String normalizePattern( String pattern ) - { + private String normalizePattern(String pattern) { pattern = pattern.trim(); - if ( pattern.startsWith( SelectorUtils.REGEX_HANDLER_PREFIX ) ) - { - if ( File.separatorChar == '\\' ) - { - pattern = StringUtils.replace( pattern, "/", "\\\\" ); + if (pattern.startsWith(SelectorUtils.REGEX_HANDLER_PREFIX)) { + if (File.separatorChar == '\\') { + pattern = StringUtils.replace(pattern, "/", "\\\\"); + } else { + pattern = StringUtils.replace(pattern, "\\\\", "/"); } - else - { - pattern = StringUtils.replace( pattern, "\\\\", "/" ); - } - } - else - { - pattern = pattern.replace( File.separatorChar == '/' ? '\\' : '/', File.separatorChar ); + } else { + pattern = pattern.replace(File.separatorChar == '/' ? '\\' : '/', File.separatorChar); - if ( pattern.endsWith( File.separator ) ) - { + if (pattern.endsWith(File.separator)) { pattern += "**"; } } @@ -321,19 +315,16 @@ private String normalizePattern( String pattern ) * @return true when the name matches against at least one include pattern, or false * otherwise. */ - protected boolean isIncluded( String name ) - { - return includesPatterns.matches( name, isCaseSensitive ); + protected boolean isIncluded(String name) { + return includesPatterns.matches(name, isCaseSensitive); } - protected boolean isIncluded( String name, String[] tokenizedName ) - { - return includesPatterns.matches( name, tokenizedName, isCaseSensitive ); + protected boolean isIncluded(String name, String[] tokenizedName) { + return includesPatterns.matches(name, tokenizedName, isCaseSensitive); } - protected boolean isIncluded( String name, char[][] tokenizedName ) - { - return includesPatterns.matches( name, tokenizedName, isCaseSensitive ); + protected boolean isIncluded(String name, char[][] tokenizedName) { + return includesPatterns.matches(name, tokenizedName, isCaseSensitive); } /** @@ -343,9 +334,8 @@ protected boolean isIncluded( String name, char[][] tokenizedName ) * @return true when the name matches against the start of at least one include pattern, or * false otherwise. */ - protected boolean couldHoldIncluded( String name ) - { - return includesPatterns.matchesPatternStart( name, isCaseSensitive ); + protected boolean couldHoldIncluded(String name) { + return includesPatterns.matchesPatternStart(name, isCaseSensitive); } /** @@ -355,64 +345,53 @@ protected boolean couldHoldIncluded( String name ) * @return true when the name matches against at least one exclude pattern, or false * otherwise. */ - protected boolean isExcluded( String name ) - { - return excludesPatterns.matches( name, isCaseSensitive ); + protected boolean isExcluded(String name) { + return excludesPatterns.matches(name, isCaseSensitive); } - protected boolean isExcluded( String name, String[] tokenizedName ) - { - return excludesPatterns.matches( name, tokenizedName, isCaseSensitive ); + protected boolean isExcluded(String name, String[] tokenizedName) { + return excludesPatterns.matches(name, tokenizedName, isCaseSensitive); } - protected boolean isExcluded( String name, char[][] tokenizedName ) - { - return excludesPatterns.matches( name, tokenizedName, isCaseSensitive ); + protected boolean isExcluded(String name, char[][] tokenizedName) { + return excludesPatterns.matches(name, tokenizedName, isCaseSensitive); } /** * Adds default exclusions to the current exclusions set. */ @Override - public void addDefaultExcludes() - { + public void addDefaultExcludes() { int excludesLength = excludes == null ? 0 : excludes.length; String[] newExcludes; newExcludes = new String[excludesLength + DEFAULTEXCLUDES.length]; - if ( excludesLength > 0 ) - { - System.arraycopy( excludes, 0, newExcludes, 0, excludesLength ); + if (excludesLength > 0) { + System.arraycopy(excludes, 0, newExcludes, 0, excludesLength); } - for ( int i = 0; i < DEFAULTEXCLUDES.length; i++ ) - { - newExcludes[i + excludesLength] = DEFAULTEXCLUDES[i].replace( '/', File.separatorChar ); + for (int i = 0; i < DEFAULTEXCLUDES.length; i++) { + newExcludes[i + excludesLength] = DEFAULTEXCLUDES[i].replace('/', File.separatorChar); } excludes = newExcludes; } - protected void setupDefaultFilters() - { - if ( includes == null ) - { + protected void setupDefaultFilters() { + if (includes == null) { // No includes supplied, so set it to 'matches all' includes = new String[1]; includes[0] = "**"; } - if ( excludes == null ) - { + if (excludes == null) { excludes = new String[0]; } } - protected void setupMatchPatterns() - { - includesPatterns = MatchPatterns.from( includes ); - excludesPatterns = MatchPatterns.from( excludes ); + protected void setupMatchPatterns() { + includesPatterns = MatchPatterns.from(includes); + excludesPatterns = MatchPatterns.from(excludes); } @Override - public void setFilenameComparator( Comparator filenameComparator ) - { + public void setFilenameComparator(Comparator filenameComparator) { this.filenameComparator = filenameComparator; } } diff --git a/src/main/java/org/codehaus/plexus/util/Base64.java b/src/main/java/org/codehaus/plexus/util/Base64.java index 120feb8f..e574a287 100644 --- a/src/main/java/org/codehaus/plexus/util/Base64.java +++ b/src/main/java/org/codehaus/plexus/util/Base64.java @@ -28,8 +28,7 @@ * @since 1.0-dev * */ -public class Base64 -{ +public class Base64 { // // Source Id: Base64.java 161350 2005-04-14 20:39:46Z ggregory @@ -121,41 +120,33 @@ public class Base64 private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH]; // Populating the lookup and character arrays - static - { - for ( int i = 0; i < BASELENGTH; i++ ) - { + static { + for (int i = 0; i < BASELENGTH; i++) { base64Alphabet[i] = (byte) -1; } - for ( int i = 'Z'; i >= 'A'; i-- ) - { - base64Alphabet[i] = (byte) ( i - 'A' ); + for (int i = 'Z'; i >= 'A'; i--) { + base64Alphabet[i] = (byte) (i - 'A'); } - for ( int i = 'z'; i >= 'a'; i-- ) - { - base64Alphabet[i] = (byte) ( i - 'a' + 26 ); + for (int i = 'z'; i >= 'a'; i--) { + base64Alphabet[i] = (byte) (i - 'a' + 26); } - for ( int i = '9'; i >= '0'; i-- ) - { - base64Alphabet[i] = (byte) ( i - '0' + 52 ); + for (int i = '9'; i >= '0'; i--) { + base64Alphabet[i] = (byte) (i - '0' + 52); } base64Alphabet['+'] = 62; base64Alphabet['/'] = 63; - for ( int i = 0; i <= 25; i++ ) - { - lookUpBase64Alphabet[i] = (byte) ( 'A' + i ); + for (int i = 0; i <= 25; i++) { + lookUpBase64Alphabet[i] = (byte) ('A' + i); } - for ( int i = 26, j = 0; i <= 51; i++, j++ ) - { - lookUpBase64Alphabet[i] = (byte) ( 'a' + j ); + for (int i = 26, j = 0; i <= 51; i++, j++) { + lookUpBase64Alphabet[i] = (byte) ('a' + j); } - for ( int i = 52, j = 0; i <= 61; i++, j++ ) - { - lookUpBase64Alphabet[i] = (byte) ( '0' + j ); + for (int i = 52, j = 0; i <= 61; i++, j++) { + lookUpBase64Alphabet[i] = (byte) ('0' + j); } lookUpBase64Alphabet[62] = (byte) '+'; @@ -168,18 +159,12 @@ public class Base64 * @param octect The value to test * @return true if the value is defined in the the base 64 alphabet, false otherwise. */ - private static boolean isBase64( byte octect ) - { - if ( octect == PAD ) - { + private static boolean isBase64(byte octect) { + if (octect == PAD) { return true; - } - else if ( octect < 0 || base64Alphabet[octect] == -1 ) - { + } else if (octect < 0 || base64Alphabet[octect] == -1) { return false; - } - else - { + } else { return true; } } @@ -191,22 +176,18 @@ else if ( octect < 0 || base64Alphabet[octect] == -1 ) * @return true if all bytes are valid characters in the Base64 alphabet or if the byte array is empty; * false, otherwise */ - public static boolean isArrayByteBase64( byte[] arrayOctect ) - { + public static boolean isArrayByteBase64(byte[] arrayOctect) { - arrayOctect = discardWhitespace( arrayOctect ); + arrayOctect = discardWhitespace(arrayOctect); int length = arrayOctect.length; - if ( length == 0 ) - { + if (length == 0) { // shouldn't a 0 length array be valid base64 data? // return false; return true; } - for ( byte anArrayOctect : arrayOctect ) - { - if ( !isBase64( anArrayOctect ) ) - { + for (byte anArrayOctect : arrayOctect) { + if (!isBase64(anArrayOctect)) { return false; } } @@ -219,9 +200,8 @@ public static boolean isArrayByteBase64( byte[] arrayOctect ) * @param binaryData binary data to encode * @return Base64 characters */ - public static byte[] encodeBase64( byte[] binaryData ) - { - return encodeBase64( binaryData, false ); + public static byte[] encodeBase64(byte[] binaryData) { + return encodeBase64(binaryData, false); } /** @@ -230,9 +210,8 @@ public static byte[] encodeBase64( byte[] binaryData ) * @param binaryData binary data to encode * @return Base64 characters chunked in 76 character blocks */ - public static byte[] encodeBase64Chunked( byte[] binaryData ) - { - return encodeBase64( binaryData, true ); + public static byte[] encodeBase64Chunked(byte[] binaryData) { + return encodeBase64(binaryData, true); } /** @@ -241,9 +220,8 @@ public static byte[] encodeBase64Chunked( byte[] binaryData ) * @param pArray A byte array containing Base64 character data * @return a byte array containing binary data */ - public byte[] decode( byte[] pArray ) - { - return decodeBase64( pArray ); + public byte[] decode(byte[] pArray) { + return decodeBase64(pArray); } /** @@ -253,8 +231,7 @@ public byte[] decode( byte[] pArray ) * @param isChunked if true this encoder will chunk the base64 output into 76 character blocks * @return Base64-encoded data. */ - public static byte[] encodeBase64( byte[] binaryData, boolean isChunked ) - { + public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; @@ -262,13 +239,10 @@ public static byte[] encodeBase64( byte[] binaryData, boolean isChunked ) int encodedDataLength = 0; int nbrChunks = 0; - if ( fewerThan24bits != 0 ) - { + if (fewerThan24bits != 0) { // data not divisible by 24 bit - encodedDataLength = ( numberTriplets + 1 ) * 4; - } - else - { + encodedDataLength = (numberTriplets + 1) * 4; + } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } @@ -276,10 +250,9 @@ public static byte[] encodeBase64( byte[] binaryData, boolean isChunked ) // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) - if ( isChunked ) - { + if (isChunked) { - nbrChunks = ( CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil( (float) encodedDataLength / CHUNK_SIZE ) ); + nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } @@ -294,8 +267,7 @@ public static byte[] encodeBase64( byte[] binaryData, boolean isChunked ) int chunksSoFar = 0; // log.debug("number of triplets = " + numberTriplets); - for ( i = 0; i < numberTriplets; i++ ) - { + for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; @@ -303,33 +275,30 @@ public static byte[] encodeBase64( byte[] binaryData, boolean isChunked ) // log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); - l = (byte) ( b2 & 0x0f ); - k = (byte) ( b1 & 0x03 ); + l = (byte) (b2 & 0x0f); + k = (byte) (b1 & 0x03); - byte val1 = ( ( b1 & SIGN ) == 0 ) ? (byte) ( b1 >> 2 ) : (byte) ( ( b1 ) >> 2 ^ 0xc0 ); - byte val2 = ( ( b2 & SIGN ) == 0 ) ? (byte) ( b2 >> 4 ) : (byte) ( ( b2 ) >> 4 ^ 0xf0 ); - byte val3 = ( ( b3 & SIGN ) == 0 ) ? (byte) ( b3 >> 6 ) : (byte) ( ( b3 ) >> 6 ^ 0xfc ); + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); + byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; // log.debug( "val2 = " + val2 ); // log.debug( "k4 = " + (k<<4) ); // log.debug( "vak = " + (val2 | (k<<4)) ); - encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | ( k << 4 )]; - encodedData[encodedIndex + 2] = lookUpBase64Alphabet[( l << 2 ) | val3]; + encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. - if ( isChunked ) - { + if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 - if ( encodedIndex == nextSeparatorIndex ) - { - System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length ); + if (encodedIndex == nextSeparatorIndex) { + System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; - nextSeparatorIndex = - ( CHUNK_SIZE * ( chunksSoFar + 1 ) ) + ( chunksSoFar * CHUNK_SEPARATOR.length ); + nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } @@ -338,42 +307,41 @@ public static byte[] encodeBase64( byte[] binaryData, boolean isChunked ) // form integral number of 6-bit groups dataIndex = i * 3; - if ( fewerThan24bits == EIGHTBIT ) - { + if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; - k = (byte) ( b1 & 0x03 ); + k = (byte) (b1 & 0x03); // log.debug("b1=" + b1); // log.debug("b1<<2 = " + (b1>>2) ); - byte val1 = ( ( b1 & SIGN ) == 0 ) ? (byte) ( b1 >> 2 ) : (byte) ( ( b1 ) >> 2 ^ 0xc0 ); + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; - } - else if ( fewerThan24bits == SIXTEENBIT ) - { + } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; - l = (byte) ( b2 & 0x0f ); - k = (byte) ( b1 & 0x03 ); + l = (byte) (b2 & 0x0f); + k = (byte) (b1 & 0x03); - byte val1 = ( ( b1 & SIGN ) == 0 ) ? (byte) ( b1 >> 2 ) : (byte) ( ( b1 ) >> 2 ^ 0xc0 ); - byte val2 = ( ( b2 & SIGN ) == 0 ) ? (byte) ( b2 >> 4 ) : (byte) ( ( b2 ) >> 4 ^ 0xf0 ); + byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; - encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | ( k << 4 )]; + encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } - if ( isChunked ) - { + if (isChunked) { // we also add a separator to the end of the final chunk. - if ( chunksSoFar < nbrChunks ) - { - System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, - CHUNK_SEPARATOR.length ); + if (chunksSoFar < nbrChunks) { + System.arraycopy( + CHUNK_SEPARATOR, + 0, + encodedData, + encodedDataLength - CHUNK_SEPARATOR.length, + CHUNK_SEPARATOR.length); } } @@ -386,14 +354,12 @@ else if ( fewerThan24bits == SIXTEENBIT ) * @param base64Data Byte array containing Base64 data * @return Array containing decoded data. */ - public static byte[] decodeBase64( byte[] base64Data ) - { + public static byte[] decodeBase64(byte[] base64Data) { // RFC 2045 requires that we discard ALL non-Base64 characters - base64Data = discardNonBase64( base64Data ); + base64Data = discardNonBase64(base64Data); // handle the edge case, so we don't have to worry about it later - if ( base64Data.length == 0 ) - { + if (base64Data.length == 0) { return new byte[0]; } @@ -409,18 +375,15 @@ public static byte[] decodeBase64( byte[] base64Data ) // this sizes the output array properly - rlw int lastData = base64Data.length; // ignore the '=' padding - while ( base64Data[lastData - 1] == PAD ) - { - if ( --lastData == 0 ) - { + while (base64Data[lastData - 1] == PAD) { + if (--lastData == 0) { return new byte[0]; } } decodedData = new byte[lastData - numberQuadruple]; } - for ( int i = 0; i < numberQuadruple; i++ ) - { + for (int i = 0; i < numberQuadruple; i++) { dataIndex = i * 4; marker0 = base64Data[dataIndex + 2]; marker1 = base64Data[dataIndex + 3]; @@ -428,28 +391,23 @@ public static byte[] decodeBase64( byte[] base64Data ) b1 = base64Alphabet[base64Data[dataIndex]]; b2 = base64Alphabet[base64Data[dataIndex + 1]]; - if ( marker0 != PAD && marker1 != PAD ) - { + if (marker0 != PAD && marker1 != PAD) { // No PAD e.g 3cQl b3 = base64Alphabet[marker0]; b4 = base64Alphabet[marker1]; - decodedData[encodedIndex] = (byte) ( b1 << 2 | b2 >> 4 ); - decodedData[encodedIndex + 1] = (byte) ( ( ( b2 & 0xf ) << 4 ) | ( ( b3 >> 2 ) & 0xf ) ); - decodedData[encodedIndex + 2] = (byte) ( b3 << 6 | b4 ); - } - else if ( marker0 == PAD ) - { + decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); + decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4); + } else if (marker0 == PAD) { // Two PAD e.g. 3c[Pad][Pad] - decodedData[encodedIndex] = (byte) ( b1 << 2 | b2 >> 4 ); - } - else if ( marker1 == PAD ) - { + decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); + } else if (marker1 == PAD) { // One PAD e.g. 3cQ[Pad] b3 = base64Alphabet[marker0]; - decodedData[encodedIndex] = (byte) ( b1 << 2 | b2 >> 4 ); - decodedData[encodedIndex + 1] = (byte) ( ( ( b2 & 0xf ) << 4 ) | ( ( b3 >> 2 ) & 0xf ) ); + decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); + decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); } encodedIndex += 3; } @@ -462,15 +420,12 @@ else if ( marker1 == PAD ) * @param data The base-64 encoded data to discard the whitespace from. * @return The data, less whitespace (see RFC 2045). */ - static byte[] discardWhitespace( byte[] data ) - { + static byte[] discardWhitespace(byte[] data) { byte groomedData[] = new byte[data.length]; int bytesCopied = 0; - for ( byte aData : data ) - { - switch ( aData ) - { + for (byte aData : data) { + switch (aData) { case (byte) ' ': case (byte) '\n': case (byte) '\r': @@ -483,7 +438,7 @@ static byte[] discardWhitespace( byte[] data ) byte packedData[] = new byte[bytesCopied]; - System.arraycopy( groomedData, 0, packedData, 0, bytesCopied ); + System.arraycopy(groomedData, 0, packedData, 0, bytesCopied); return packedData; } @@ -495,22 +450,19 @@ static byte[] discardWhitespace( byte[] data ) * @param data The base-64 encoded data to groom * @return The data, less non-base64 characters (see RFC 2045). */ - static byte[] discardNonBase64( byte[] data ) - { + static byte[] discardNonBase64(byte[] data) { byte groomedData[] = new byte[data.length]; int bytesCopied = 0; - for ( byte aData : data ) - { - if ( isBase64( aData ) ) - { + for (byte aData : data) { + if (isBase64(aData)) { groomedData[bytesCopied++] = aData; } } byte packedData[] = new byte[bytesCopied]; - System.arraycopy( groomedData, 0, packedData, 0, bytesCopied ); + System.arraycopy(groomedData, 0, packedData, 0, bytesCopied); return packedData; } @@ -521,9 +473,7 @@ static byte[] discardNonBase64( byte[] data ) * @param pArray a byte array containing binary data * @return A byte array containing only Base64 character data */ - public byte[] encode( byte[] pArray ) - { - return encodeBase64( pArray, false ); + public byte[] encode(byte[] pArray) { + return encodeBase64(pArray, false); } - } diff --git a/src/main/java/org/codehaus/plexus/util/BaseFileUtils.java b/src/main/java/org/codehaus/plexus/util/BaseFileUtils.java index 0a3803d5..beb5e16d 100644 --- a/src/main/java/org/codehaus/plexus/util/BaseFileUtils.java +++ b/src/main/java/org/codehaus/plexus/util/BaseFileUtils.java @@ -4,22 +4,18 @@ import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; -import java.nio.file.StandardOpenOption; /** * Implementation specific to Java SE 8 version. */ -abstract class BaseFileUtils -{ - static String fileRead( Path path, String encoding ) throws IOException - { - byte[] bytes = Files.readAllBytes( path ); - return encoding != null ? new String( bytes, encoding ) : new String( bytes ); +abstract class BaseFileUtils { + static String fileRead(Path path, String encoding) throws IOException { + byte[] bytes = Files.readAllBytes(path); + return encoding != null ? new String(bytes, encoding) : new String(bytes); } - static void fileWrite( Path path, String encoding, String data, OpenOption... openOptions ) throws IOException - { - byte[] bytes = encoding != null ? data.getBytes( encoding ) : data.getBytes(); - Files.write( path, bytes, openOptions ); + static void fileWrite(Path path, String encoding, String data, OpenOption... openOptions) throws IOException { + byte[] bytes = encoding != null ? data.getBytes(encoding) : data.getBytes(); + Files.write(path, bytes, openOptions); } } diff --git a/src/main/java/org/codehaus/plexus/util/BaseIOUtil.java b/src/main/java/org/codehaus/plexus/util/BaseIOUtil.java index ac2ade02..ab391c87 100644 --- a/src/main/java/org/codehaus/plexus/util/BaseIOUtil.java +++ b/src/main/java/org/codehaus/plexus/util/BaseIOUtil.java @@ -9,19 +9,14 @@ /** * Implementation specific to Java SE 8 version. */ -abstract class BaseIOUtil -{ +abstract class BaseIOUtil { private static final int DEFAULT_BUFFER_SIZE = 1024 * 16; - static void copy( final InputStream input, final OutputStream output ) - throws IOException - { - IOUtil.copy( input, output, DEFAULT_BUFFER_SIZE ); + static void copy(final InputStream input, final OutputStream output) throws IOException { + IOUtil.copy(input, output, DEFAULT_BUFFER_SIZE); } - static void copy( final Reader input, final Writer output ) - throws IOException - { - IOUtil.copy( input, output, DEFAULT_BUFFER_SIZE ); + static void copy(final Reader input, final Writer output) throws IOException { + IOUtil.copy(input, output, DEFAULT_BUFFER_SIZE); } } diff --git a/src/main/java/org/codehaus/plexus/util/CachedMap.java b/src/main/java/org/codehaus/plexus/util/CachedMap.java index c77d2180..6c78dce0 100644 --- a/src/main/java/org/codehaus/plexus/util/CachedMap.java +++ b/src/main/java/org/codehaus/plexus/util/CachedMap.java @@ -38,13 +38,11 @@ *

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

    - * + * * @author Jean-Marie Dautelle * @version 5.3, October 30, 2003 */ -public final class CachedMap - implements Map -{ +public final class CachedMap implements Map { /** * Holds the FastMap backing this collection (null if generic backing map). @@ -80,9 +78,8 @@ public final class CachedMap * Creates a cached map backed by a {@link FastMap}. The default cache size and map capacity is set to * 256 entries. */ - public CachedMap() - { - this( 256, new FastMap() ); + public CachedMap() { + this(256, new FastMap()); } /** @@ -91,9 +88,8 @@ public CachedMap() * @param cacheSize the cache size, the actual cache size is the first power of 2 greater or equal to * cacheSize. This is also the initial capacity of the backing map. */ - public CachedMap( int cacheSize ) - { - this( cacheSize, new FastMap( cacheSize ) ); + public CachedMap(int cacheSize) { + this(cacheSize, new FastMap(cacheSize)); } /** @@ -105,13 +101,11 @@ public CachedMap( int cacheSize ) * cacheSize. * @param backingMap the backing map to be "wrapped" in a cached map. */ - public CachedMap( int cacheSize, Map backingMap ) - { + public CachedMap(int cacheSize, Map backingMap) { // Find a power of 2 >= minimalCache int actualCacheSize = 1; - while ( actualCacheSize < cacheSize ) - { + while (actualCacheSize < cacheSize) { actualCacheSize <<= 1; } @@ -121,20 +115,16 @@ public CachedMap( int cacheSize, Map backingMap ) _mask = actualCacheSize - 1; // Sets backing map references. - if ( backingMap instanceof FastMap ) - { + if (backingMap instanceof FastMap) { _backingFastMap = (FastMap) backingMap; _backingMap = _backingFastMap; _keysMap = null; - } - else - { + } else { _backingFastMap = null; _backingMap = backingMap; - _keysMap = new FastMap( backingMap.size() ); - for ( Object key : backingMap.keySet() ) - { - _keysMap.put( key, key ); + _keysMap = new FastMap(backingMap.size()); + for (Object key : backingMap.keySet()) { + _keysMap.put(key, key); } } } @@ -144,8 +134,7 @@ public CachedMap( int cacheSize, Map backingMap ) * * @return the cache size (power of 2). */ - public int getCacheSize() - { + public int getCacheSize() { return _keys.length; } @@ -155,28 +144,23 @@ public int getCacheSize() * @return the backing map. * @see #flush */ - public Map getBackingMap() - { - return ( _backingFastMap != null ) ? _backingFastMap : _backingMap; + public Map getBackingMap() { + return (_backingFastMap != null) ? _backingFastMap : _backingMap; } /** * Flushes the key/value pairs being cached. This method should be called if the backing map is externally modified. */ - public void flush() - { - for ( int i = 0; i < _keys.length; i++ ) - { + public void flush() { + for (int i = 0; i < _keys.length; i++) { _keys[i] = null; _values[i] = null; } - if ( _keysMap != null ) - { + if (_keysMap != null) { // Re-populates keys from backing map. - for ( Object key : _backingMap.keySet() ) - { - _keysMap.put( key, key ); + for (Object key : _backingMap.keySet()) { + _keysMap.put(key, key); } } } @@ -192,41 +176,30 @@ public void flush() * @throws NullPointerException if the key is null. */ @Override - public Object get( Object key ) - { + public Object get(Object key) { int index = key.hashCode() & _mask; - return key.equals( _keys[index] ) ? _values[index] : getCacheMissed( key, index ); + return key.equals(_keys[index]) ? _values[index] : getCacheMissed(key, index); } - private Object getCacheMissed( Object key, int index ) - { - if ( _backingFastMap != null ) - { - Map.Entry entry = _backingFastMap.getEntry( key ); - if ( entry != null ) - { + private Object getCacheMissed(Object key, int index) { + if (_backingFastMap != null) { + Map.Entry entry = _backingFastMap.getEntry(key); + if (entry != null) { _keys[index] = entry.getKey(); Object value = entry.getValue(); _values[index] = value; return value; - } - else - { + } else { return null; } - } - else - { // Generic backing map. - Object mapKey = _keysMap.get( key ); - if ( mapKey != null ) - { + } else { // Generic backing map. + Object mapKey = _keysMap.get(key); + if (mapKey != null) { _keys[index] = mapKey; - Object value = _backingMap.get( key ); + Object value = _backingMap.get(key); _values[index] = value; return value; - } - else - { + } else { return null; } } @@ -245,21 +218,17 @@ private Object getCacheMissed( Object key, int index ) * @throws NullPointerException if the key is null. */ @Override - public Object put( Object key, Object value ) - { + public Object put(Object key, Object value) { // Updates the cache. int index = key.hashCode() & _mask; - if ( key.equals( _keys[index] ) ) - { + if (key.equals(_keys[index])) { _values[index] = value; - } - else if ( _keysMap != null ) - { // Possibly a new key. - _keysMap.put( key, key ); + } else if (_keysMap != null) { // Possibly a new key. + _keysMap.put(key, key); } // Updates the backing map. - return _backingMap.put( key, value ); + return _backingMap.put(key, value); } /** @@ -272,21 +241,18 @@ else if ( _keysMap != null ) * @throws UnsupportedOperationException if the remove method is not supported by the backing map. */ @Override - public Object remove( Object key ) - { + public Object remove(Object key) { // Removes from cache. int index = key.hashCode() & _mask; - if ( key.equals( _keys[index] ) ) - { + if (key.equals(_keys[index])) { _keys[index] = null; } // Removes from key map. - if ( _keysMap != null ) - { - _keysMap.remove( key ); + if (_keysMap != null) { + _keysMap.remove(key); } // Removes from backing map. - return _backingMap.remove( key ); + return _backingMap.remove(key); } /** @@ -296,17 +262,13 @@ public Object remove( Object key ) * @return true if this map contains a mapping for the specified key; false otherwise. */ @Override - public boolean containsKey( Object key ) - { + public boolean containsKey(Object key) { // Checks the cache. int index = key.hashCode() & _mask; - if ( key.equals( _keys[index] ) ) - { + if (key.equals(_keys[index])) { return true; - } - else - { // Checks the backing map. - return _backingMap.containsKey( key ); + } else { // Checks the backing map. + return _backingMap.containsKey(key); } } @@ -317,8 +279,7 @@ public boolean containsKey( Object key ) * @return the number of key-value mappings in this map. */ @Override - public int size() - { + public int size() { return _backingMap.size(); } @@ -328,8 +289,7 @@ public int size() * @return true if this map contains no key-value mappings. */ @Override - public boolean isEmpty() - { + public boolean isEmpty() { return _backingMap.isEmpty(); } @@ -343,9 +303,8 @@ public boolean isEmpty() * null values. */ @Override - public boolean containsValue( Object value ) - { - return _backingMap.containsValue( value ); + public boolean containsValue(Object value) { + return _backingMap.containsValue(value); } /** @@ -362,9 +321,8 @@ public boolean containsValue( Object value ) * null keys or values, and the specified map contains null keys or values. */ @Override - public void putAll( Map map ) - { - _backingMap.putAll( map ); + public void putAll(Map map) { + _backingMap.putAll(map); flush(); } @@ -374,8 +332,7 @@ public void putAll( Map map ) * @throws UnsupportedOperationException if clear is not supported by the backing map. */ @Override - public void clear() - { + public void clear() { _backingMap.clear(); flush(); } @@ -386,9 +343,8 @@ public void clear() * @return an unmodifiable view of the keys contained in this map. */ @Override - public Set keySet() - { - return Collections.unmodifiableSet( _backingMap.keySet() ); + public Set keySet() { + return Collections.unmodifiableSet(_backingMap.keySet()); } /** @@ -397,9 +353,8 @@ public Set keySet() * @return an unmodifiable view of the values contained in this map. */ @Override - public Collection values() - { - return Collections.unmodifiableCollection( _backingMap.values() ); + public Collection values() { + return Collections.unmodifiableCollection(_backingMap.values()); } /** @@ -409,9 +364,8 @@ public Collection values() * @return an unmodifiable view of the mappings contained in this map. */ @Override - public Set entrySet() - { - return Collections.unmodifiableSet( _backingMap.entrySet() ); + public Set entrySet() { + return Collections.unmodifiableSet(_backingMap.entrySet()); } /** @@ -422,9 +376,8 @@ public Set entrySet() * @return true if the specified object is equal to this map. */ @Override - public boolean equals( Object o ) - { - return _backingMap.equals( o ); + public boolean equals(Object o) { + return _backingMap.equals(o); } /** @@ -433,8 +386,7 @@ public boolean equals( Object o ) * @return the hash code value for this map. */ @Override - public int hashCode() - { + public int hashCode() { return _backingMap.hashCode(); } } diff --git a/src/main/java/org/codehaus/plexus/util/CollectionUtils.java b/src/main/java/org/codehaus/plexus/util/CollectionUtils.java index b16200fd..c966d8ff 100644 --- a/src/main/java/org/codehaus/plexus/util/CollectionUtils.java +++ b/src/main/java/org/codehaus/plexus/util/CollectionUtils.java @@ -30,8 +30,7 @@ * @author olamy * */ -public class CollectionUtils -{ +public class CollectionUtils { // ---------------------------------------------------------------------- // Static methods that can probably be moved to a real util class. // ---------------------------------------------------------------------- @@ -48,21 +47,17 @@ public class CollectionUtils * @param type * @return The result map with combined dominant and recessive values. */ - public static Map mergeMaps( Map dominantMap, Map recessiveMap ) - { + public static Map mergeMaps(Map dominantMap, Map recessiveMap) { - if ( dominantMap == null && recessiveMap == null ) - { + if (dominantMap == null && recessiveMap == null) { return null; } - if ( dominantMap != null && recessiveMap == null ) - { + if (dominantMap != null && recessiveMap == null) { return dominantMap; } - if ( dominantMap == null ) - { + if (dominantMap == null) { return recessiveMap; } @@ -75,17 +70,15 @@ public static Map mergeMaps( Map dominantMap, Map reces // Create the set of keys that will be contributed by the // recessive Map by subtracting the intersection of keys // from the recessive Map's keys. - Collection contributingRecessiveKeys = - CollectionUtils.subtract( recessiveMapKeys, - CollectionUtils.intersection( dominantMapKeys, recessiveMapKeys ) ); + Collection contributingRecessiveKeys = CollectionUtils.subtract( + recessiveMapKeys, CollectionUtils.intersection(dominantMapKeys, recessiveMapKeys)); - result.putAll( dominantMap ); + result.putAll(dominantMap); // Now take the keys we just found and extract the values from // the recessiveMap and put the key:value pairs into the dominantMap. - for ( K key : contributingRecessiveKeys ) - { - result.put( key, recessiveMap.get( key ) ); + for (K key : contributingRecessiveKeys) { + result.put(key, recessiveMap.get(key)); } return result; @@ -100,25 +93,18 @@ public static Map mergeMaps( Map dominantMap, Map reces * @param type * @return Map The result Map produced after the merging process. */ - public static Map mergeMaps( Map[] maps ) - { + public static Map mergeMaps(Map[] maps) { Map result; - if ( maps.length == 0 ) - { + if (maps.length == 0) { result = null; - } - else if ( maps.length == 1 ) - { + } else if (maps.length == 1) { result = maps[0]; - } - else - { - result = mergeMaps( maps[0], maps[1] ); + } else { + result = mergeMaps(maps[0], maps[1]); - for ( int i = 2; i < maps.length; i++ ) - { - result = mergeMaps( result, maps[i] ); + for (int i = 2; i < maps.length; i++) { + result = mergeMaps(result, maps[i]); } } @@ -138,18 +124,15 @@ else if ( maps.length == 1 ) * @see Collection#retainAll * @return The intersection of a and b, never null */ - public static Collection intersection( final Collection a, final Collection b ) - { + public static Collection intersection(final Collection a, final Collection b) { ArrayList list = new ArrayList<>(); - Map mapa = getCardinalityMap( a ); - Map mapb = getCardinalityMap( b ); - Set elts = new HashSet<>( a ); - elts.addAll( b ); - for ( E obj : elts ) - { - for ( int i = 0, m = Math.min( getFreq( obj, mapa ), getFreq( obj, mapb ) ); i < m; i++ ) - { - list.add( obj ); + Map mapa = getCardinalityMap(a); + Map mapb = getCardinalityMap(b); + Set elts = new HashSet<>(a); + elts.addAll(b); + for (E obj : elts) { + for (int i = 0, m = Math.min(getFreq(obj, mapa), getFreq(obj, mapb)); i < m; i++) { + list.add(obj); } } return list; @@ -166,12 +149,10 @@ public static Collection intersection( final Collection a, final Colle * @see Collection#removeAll * @return The result of the subtraction */ - public static Collection subtract( final Collection a, final Collection b ) - { - ArrayList list = new ArrayList<>( a ); - for ( T aB : b ) - { - list.remove( aB ); + public static Collection subtract(final Collection a, final Collection b) { + ArrayList list = new ArrayList<>(a); + for (T aB : b) { + list.remove(aB); } return list; } @@ -180,41 +161,33 @@ public static Collection subtract( final Collection a, final Collectio * Returns a {@link Map} mapping each unique element in the given {@link Collection} to an {@link Integer} * representing the number of occurrences of that element in the {@link Collection}. An entry that maps to * null indicates that the element does not appear in the given {@link Collection}. - * + * * @param col The collection to count cardinalities for * @param the type * @return A map of counts, indexed on each element in the collection */ - public static Map getCardinalityMap( final Collection col ) - { + public static Map getCardinalityMap(final Collection col) { HashMap count = new HashMap<>(); - for ( E obj : col ) - { - Integer c = count.get( obj ); - if ( null == c ) - { - count.put( obj, 1 ); - } - else - { - count.put( obj, c + 1 ); + for (E obj : col) { + Integer c = count.get(obj); + if (null == c) { + count.put(obj, 1); + } else { + count.put(obj, c + 1); } } return count; } - public static List iteratorToList( Iterator it ) - { - if ( it == null ) - { - throw new NullPointerException( "it cannot be null." ); + public static List iteratorToList(Iterator it) { + if (it == null) { + throw new NullPointerException("it cannot be null."); } List list = new ArrayList(); - while ( it.hasNext() ) - { - list.add( it.next() ); + while (it.hasNext()) { + list.add(it.next()); } return list; @@ -224,18 +197,14 @@ public static List iteratorToList( Iterator it ) // // ---------------------------------------------------------------------- - private static int getFreq( final E obj, final Map freqMap ) - { - try - { - Integer o = freqMap.get( obj ); - if ( o != null ) // minimize NullPointerExceptions + private static int getFreq(final E obj, final Map freqMap) { + try { + Integer o = freqMap.get(obj); + if (o != null) // minimize NullPointerExceptions { return o; } - } - catch ( NullPointerException | NoSuchElementException ignore ) - { + } catch (NullPointerException | NoSuchElementException ignore) { } return 0; } diff --git a/src/main/java/org/codehaus/plexus/util/DirectoryScanner.java b/src/main/java/org/codehaus/plexus/util/DirectoryScanner.java index 5db6a903..64fd8994 100644 --- a/src/main/java/org/codehaus/plexus/util/DirectoryScanner.java +++ b/src/main/java/org/codehaus/plexus/util/DirectoryScanner.java @@ -61,39 +61,39 @@ /** *

    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 * 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 * 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 * 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 * 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:
    * '*' matches zero or more characters
    * '?' matches one character.

    - * + * * Examples: *
      *
    • "**\*.class" matches all .class files/dirs in a directory tree.
    • @@ -103,7 +103,7 @@ *
    • "**\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: *
    @@ -122,7 +122,7 @@
      *     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"

    * @@ -131,9 +131,7 @@ * @author Bruce Atherton * @author Antoine Levy-Lambert */ -public class DirectoryScanner - extends AbstractScanner -{ +public class DirectoryScanner extends AbstractScanner { private static final String[] EMPTY_STRING_ARRAY = new String[0]; @@ -199,14 +197,12 @@ public class DirectoryScanner */ protected boolean everythingIncluded = true; - private final char[][] tokenizedEmpty = MatchPattern.tokenizePathToCharArray( "", File.separator ); + private final char[][] tokenizedEmpty = MatchPattern.tokenizePathToCharArray("", File.separator); /** * Sole constructor. */ - public DirectoryScanner() - { - } + public DirectoryScanner() {} /** * Sets the base directory to be scanned. This is the directory which is scanned recursively. All '/' and '\' @@ -215,9 +211,8 @@ public DirectoryScanner() * * @param basedir The base directory to scan. Must not be null. */ - public void setBasedir( String basedir ) - { - setBasedir( new File( basedir.replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ) ) ); + public void setBasedir(String basedir) { + setBasedir(new File(basedir.replace('/', File.separatorChar).replace('\\', File.separatorChar))); } /** @@ -225,8 +220,7 @@ public void setBasedir( String basedir ) * * @param basedir The base directory for scanning. Should not be null. */ - public void setBasedir( File basedir ) - { + public void setBasedir(File basedir) { this.basedir = basedir; } @@ -236,8 +230,7 @@ public void setBasedir( File basedir ) * @return the base directory to be scanned */ @Override - public File getBasedir() - { + public File getBasedir() { return basedir; } @@ -246,8 +239,7 @@ public File getBasedir() * * @param followSymlinks whether or not symbolic links should be followed */ - public void setFollowSymlinks( boolean followSymlinks ) - { + public void setFollowSymlinks(boolean followSymlinks) { this.followSymlinks = followSymlinks; } @@ -256,8 +248,7 @@ public void setFollowSymlinks( boolean followSymlinks ) * * @return true if all files and directories which have been found so far have been included. */ - public boolean isEverythingIncluded() - { + public boolean isEverythingIncluded() { return everythingIncluded; } @@ -269,20 +260,15 @@ public boolean isEverythingIncluded() * exist, or isn't a directory). */ @Override - public void scan() - throws IllegalStateException - { - if ( basedir == null ) - { - throw new IllegalStateException( "No basedir set" ); + public void scan() throws IllegalStateException { + if (basedir == null) { + throw new IllegalStateException("No basedir set"); } - if ( !basedir.exists() ) - { - throw new IllegalStateException( "basedir " + basedir + " does not exist" ); + if (!basedir.exists()) { + throw new IllegalStateException("basedir " + basedir + " does not exist"); } - if ( !basedir.isDirectory() ) - { - throw new IllegalStateException( "basedir " + basedir + " is not a directory" ); + if (!basedir.isDirectory()) { + throw new IllegalStateException("basedir " + basedir + " is not a directory"); } setupDefaultFilters(); @@ -297,62 +283,47 @@ public void scan() dirsExcluded = new ArrayList(); dirsDeselected = new ArrayList(); - if ( isIncluded( "", tokenizedEmpty ) ) - { + if (isIncluded("", tokenizedEmpty)) { - if ( !isExcluded( "", tokenizedEmpty ) ) - { - if ( isSelected( "", basedir ) ) - { - dirsIncluded.add( "" ); + if (!isExcluded("", tokenizedEmpty)) { + if (isSelected("", basedir)) { + dirsIncluded.add(""); + } else { + dirsDeselected.add(""); } - else - { - dirsDeselected.add( "" ); - } - } - else - { - dirsExcluded.add( "" ); + } else { + dirsExcluded.add(""); } + } else { + dirsNotIncluded.add(""); } - else - { - dirsNotIncluded.add( "" ); - } - scandir( basedir, "", true ); + scandir(basedir, "", true); } /** *

    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.

    */ - protected void slowScan() - { - if ( haveSlowResults ) - { + protected void slowScan() { + if (haveSlowResults) { return; } - String[] excl = dirsExcluded.toArray( EMPTY_STRING_ARRAY ); - String[] notIncl = dirsNotIncluded.toArray( EMPTY_STRING_ARRAY ); + String[] excl = dirsExcluded.toArray(EMPTY_STRING_ARRAY); + String[] notIncl = dirsNotIncluded.toArray(EMPTY_STRING_ARRAY); - for ( String anExcl : excl ) - { - if ( !couldHoldIncluded( anExcl ) ) - { - scandir( new File( basedir, anExcl ), anExcl + File.separator, false ); + for (String anExcl : excl) { + if (!couldHoldIncluded(anExcl)) { + scandir(new File(basedir, anExcl), anExcl + File.separator, false); } } - for ( String aNotIncl : notIncl ) - { - if ( !couldHoldIncluded( aNotIncl ) ) - { - scandir( new File( basedir, aNotIncl ), aNotIncl + File.separator, false ); + for (String aNotIncl : notIncl) { + if (!couldHoldIncluded(aNotIncl)) { + scandir(new File(basedir, aNotIncl), aNotIncl + File.separator, false); } } @@ -376,12 +347,10 @@ protected void slowScan() * @see #dirsExcluded * @see #slowScan */ - protected void scandir( File dir, String vpath, boolean fast ) - { + protected void scandir(File dir, String vpath, boolean fast) { String[] newfiles = dir.list(); - if ( newfiles == null ) - { + if (newfiles == null) { /* * two reasons are mentioned in the API docs for File.list (1) dir is not a directory. This is impossible as * we wouldn't get here in this case. (2) an IO error occurred (why doesn't it throw an exception then???) @@ -401,122 +370,85 @@ protected void scandir( File dir, String vpath, boolean fast ) // throw new IOException( "IO error scanning directory " + dir.getAbsolutePath() ); } - if ( !followSymlinks ) - { - try - { - if ( isParentSymbolicLink( dir, null ) ) - { - for ( String newfile : newfiles ) - { + if (!followSymlinks) { + try { + if (isParentSymbolicLink(dir, null)) { + for (String newfile : newfiles) { String name = vpath + newfile; - File file = new File( dir, newfile ); - if ( file.isDirectory() ) - { - dirsExcluded.add( name ); - } - else - { - filesExcluded.add( name ); + File file = new File(dir, newfile); + if (file.isDirectory()) { + dirsExcluded.add(name); + } else { + filesExcluded.add(name); } } return; } - } - catch ( IOException ioe ) - { + } catch (IOException ioe) { String msg = "IOException caught while checking for links!"; // will be caught and redirected to Ant's logging system - System.err.println( msg ); + System.err.println(msg); } } - if ( filenameComparator != null ) - { - Arrays.sort( newfiles, filenameComparator ); + if (filenameComparator != null) { + Arrays.sort(newfiles, filenameComparator); } - for ( String newfile : newfiles ) - { + for (String newfile : newfiles) { String name = vpath + newfile; - char[][] tokenizedName = MatchPattern.tokenizePathToCharArray( name, File.separator ); - File file = new File( dir, newfile ); - if ( file.isDirectory() ) - { - - if ( isIncluded( name, tokenizedName ) ) - { - if ( !isExcluded( name, tokenizedName ) ) - { - if ( isSelected( name, file ) ) - { - dirsIncluded.add( name ); - if ( fast ) - { - scandir( file, name + File.separator, fast ); + char[][] tokenizedName = MatchPattern.tokenizePathToCharArray(name, File.separator); + File file = new File(dir, newfile); + if (file.isDirectory()) { + + if (isIncluded(name, tokenizedName)) { + if (!isExcluded(name, tokenizedName)) { + if (isSelected(name, file)) { + dirsIncluded.add(name); + if (fast) { + scandir(file, name + File.separator, fast); } - } - else - { + } else { everythingIncluded = false; - dirsDeselected.add( name ); - if ( fast && couldHoldIncluded( name ) ) - { - scandir( file, name + File.separator, fast ); + dirsDeselected.add(name); + if (fast && couldHoldIncluded(name)) { + scandir(file, name + File.separator, fast); } } - } - else - { + } else { everythingIncluded = false; - dirsExcluded.add( name ); - if ( fast && couldHoldIncluded( name ) ) - { - scandir( file, name + File.separator, fast ); + dirsExcluded.add(name); + if (fast && couldHoldIncluded(name)) { + scandir(file, name + File.separator, fast); } } - } - else - { + } else { everythingIncluded = false; - dirsNotIncluded.add( name ); - if ( fast && couldHoldIncluded( name ) ) - { - scandir( file, name + File.separator, fast ); + dirsNotIncluded.add(name); + if (fast && couldHoldIncluded(name)) { + scandir(file, name + File.separator, fast); } } - if ( !fast ) - { - scandir( file, name + File.separator, fast ); + if (!fast) { + scandir(file, name + File.separator, fast); } - } - else if ( file.isFile() ) - { - if ( isIncluded( name, tokenizedName ) ) - { - if ( !isExcluded( name, tokenizedName ) ) - { - if ( isSelected( name, file ) ) - { - filesIncluded.add( name ); - } - else - { + } else if (file.isFile()) { + if (isIncluded(name, tokenizedName)) { + if (!isExcluded(name, tokenizedName)) { + if (isSelected(name, file)) { + filesIncluded.add(name); + } else { everythingIncluded = false; - filesDeselected.add( name ); + filesDeselected.add(name); } - } - else - { + } else { everythingIncluded = false; - filesExcluded.add( name ); + filesExcluded.add(name); } - } - else - { + } else { everythingIncluded = false; - filesNotIncluded.add( name ); + filesNotIncluded.add(name); } } } @@ -530,8 +462,7 @@ else if ( file.isFile() ) * @return false when the selectors says that the file should not be selected, true * otherwise. */ - protected boolean isSelected( String name, File file ) - { + protected boolean isSelected(String name, File file) { return true; } @@ -543,9 +474,8 @@ protected boolean isSelected( String name, File file ) * patterns. */ @Override - public String[] getIncludedFiles() - { - return filesIncluded.toArray( EMPTY_STRING_ARRAY ); + public String[] getIncludedFiles() { + return filesIncluded.toArray(EMPTY_STRING_ARRAY); } /** @@ -555,10 +485,9 @@ public String[] getIncludedFiles() * @return the names of the files which matched none of the include patterns. * @see #slowScan */ - public String[] getNotIncludedFiles() - { + public String[] getNotIncludedFiles() { slowScan(); - return filesNotIncluded.toArray( EMPTY_STRING_ARRAY ); + return filesNotIncluded.toArray(EMPTY_STRING_ARRAY); } /** @@ -570,25 +499,23 @@ public String[] getNotIncludedFiles() * exclude patterns. * @see #slowScan */ - public String[] getExcludedFiles() - { + public String[] getExcludedFiles() { slowScan(); - return filesExcluded.toArray( EMPTY_STRING_ARRAY ); + return filesExcluded.toArray(EMPTY_STRING_ARRAY); } /** *

    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 */ - public String[] getDeselectedFiles() - { + public String[] getDeselectedFiles() { slowScan(); - return filesDeselected.toArray( EMPTY_STRING_ARRAY ); + return filesDeselected.toArray(EMPTY_STRING_ARRAY); } /** @@ -599,9 +526,8 @@ public String[] getDeselectedFiles() * patterns. */ @Override - public String[] getIncludedDirectories() - { - return dirsIncluded.toArray( EMPTY_STRING_ARRAY ); + public String[] getIncludedDirectories() { + return dirsIncluded.toArray(EMPTY_STRING_ARRAY); } /** @@ -611,10 +537,9 @@ public String[] getIncludedDirectories() * @return the names of the directories which matched none of the include patterns. * @see #slowScan */ - public String[] getNotIncludedDirectories() - { + public String[] getNotIncludedDirectories() { slowScan(); - return dirsNotIncluded.toArray( EMPTY_STRING_ARRAY ); + return dirsNotIncluded.toArray(EMPTY_STRING_ARRAY); } /** @@ -626,30 +551,28 @@ public String[] getNotIncludedDirectories() * exclude patterns. * @see #slowScan */ - public String[] getExcludedDirectories() - { + public String[] getExcludedDirectories() { slowScan(); - return dirsExcluded.toArray( EMPTY_STRING_ARRAY ); + return dirsExcluded.toArray(EMPTY_STRING_ARRAY); } /** *

    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 */ - public String[] getDeselectedDirectories() - { + public String[] getDeselectedDirectories() { slowScan(); - return dirsDeselected.toArray( EMPTY_STRING_ARRAY ); + return dirsDeselected.toArray(EMPTY_STRING_ARRAY); } /** *

    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. *

    @@ -660,15 +583,13 @@ public String[] getDeselectedDirectories() * @throws java.io.IOException . * @since Ant 1.5 */ - public boolean isSymbolicLink( File parent, String name ) - throws IOException - { - return NioFiles.isSymbolicLink( new File( parent, name ) ); + public boolean isSymbolicLink(File parent, String name) throws IOException { + return NioFiles.isSymbolicLink(new File(parent, 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.

    * @@ -678,9 +599,7 @@ public boolean isSymbolicLink( File parent, String name ) * @throws java.io.IOException . * @since Ant 1.5 */ - public boolean isParentSymbolicLink( File parent, String name ) - throws IOException - { - return NioFiles.isSymbolicLink( parent ); + public boolean isParentSymbolicLink(File parent, String name) throws IOException { + return NioFiles.isSymbolicLink(parent); } } diff --git a/src/main/java/org/codehaus/plexus/util/DirectoryWalkListener.java b/src/main/java/org/codehaus/plexus/util/DirectoryWalkListener.java index 8e1fda24..b6c83ef9 100644 --- a/src/main/java/org/codehaus/plexus/util/DirectoryWalkListener.java +++ b/src/main/java/org/codehaus/plexus/util/DirectoryWalkListener.java @@ -20,18 +20,17 @@ /** * Observes the actions of a {@link DirectoryWalker}. - * + * * * @see DirectoryWalker */ -public interface DirectoryWalkListener -{ +public interface DirectoryWalkListener { /** * The directory walking has begun. * * @param basedir the basedir that walk started in. */ - void directoryWalkStarting( File basedir ); + void directoryWalkStarting(File basedir); /** * The included entry that was encountered. @@ -39,12 +38,12 @@ public interface DirectoryWalkListener * @param percentage rough percentage of the walk completed. (inaccurate) * @param file the file that was included. */ - void directoryWalkStep( int percentage, File file ); + void directoryWalkStep(int percentage, File file); /** * The directory walking has finished. */ void directoryWalkFinished(); - void debug( String message ); + void debug(String message); } diff --git a/src/main/java/org/codehaus/plexus/util/DirectoryWalker.java b/src/main/java/org/codehaus/plexus/util/DirectoryWalker.java index 2ffa4b0a..58142c50 100644 --- a/src/main/java/org/codehaus/plexus/util/DirectoryWalker.java +++ b/src/main/java/org/codehaus/plexus/util/DirectoryWalker.java @@ -24,16 +24,14 @@ /** * DirectoryWalker - * + * * */ -public class DirectoryWalker -{ +public class DirectoryWalker { /** * DirStackEntry is an Item on the {@link DirectoryWalker#dirStack} */ - class DirStackEntry - { + class DirStackEntry { /** * Count of files in the directory. */ @@ -65,8 +63,7 @@ class DirStackEntry * @param d the directory to track * @param length the length of entries in the directory. */ - public DirStackEntry( File d, int length ) - { + public DirStackEntry(File d, int length) { dir = d; count = length; } @@ -76,9 +73,8 @@ public DirStackEntry( File d, int length ) * * @return the value for the next percentage offset. */ - public double getNextPercentageOffset() - { - return percentageOffset + ( index * ( percentageSize / count ) ); + public double getNextPercentageOffset() { + return percentageOffset + (index * (percentageSize / count)); } /** @@ -86,9 +82,8 @@ public double getNextPercentageOffset() * * @return the value for the next percentage size. */ - public double getNextPercentageSize() - { - return ( percentageSize / count ); + public double getNextPercentageSize() { + return (percentageSize / count); } /** @@ -96,19 +91,17 @@ public double getNextPercentageSize() * * @return the percentage right now. */ - public int getPercentage() - { + public int getPercentage() { double percentageWithinDir = (double) index / (double) count; - return (int) Math.floor( percentageOffset + ( percentageWithinDir * percentageSize ) ); + return (int) Math.floor(percentageOffset + (percentageWithinDir * percentageSize)); } @Override - public String toString() - { + public String toString() { return "DirStackEntry[" + "dir=" + dir.getAbsolutePath() + ",count=" + count + ",index=" + index - + ",percentageOffset=" + percentageOffset + ",percentageSize=" + percentageSize + ",percentage()=" - + getPercentage() + ",getNextPercentageOffset()=" + getNextPercentageOffset() - + ",getNextPercentageSize()=" + getNextPercentageSize() + "]"; + + ",percentageOffset=" + percentageOffset + ",percentageSize=" + percentageSize + ",percentage()=" + + getPercentage() + ",getNextPercentageOffset()=" + getNextPercentageOffset() + + ",getNextPercentageSize()=" + getNextPercentageSize() + "]"; } } @@ -128,137 +121,111 @@ public String toString() private boolean debugEnabled = false; - public DirectoryWalker() - { + public DirectoryWalker() { includes = new ArrayList(); excludes = new ArrayList(); listeners = new ArrayList(); } - public void addDirectoryWalkListener( DirectoryWalkListener listener ) - { - listeners.add( listener ); + public void addDirectoryWalkListener(DirectoryWalkListener listener) { + listeners.add(listener); } - public void addExclude( String exclude ) - { - excludes.add( fixPattern( exclude ) ); + public void addExclude(String exclude) { + excludes.add(fixPattern(exclude)); } - public void addInclude( String include ) - { - includes.add( fixPattern( include ) ); + public void addInclude(String include) { + includes.add(fixPattern(include)); } /** * Add's to the Exclude List the default list of SCM excludes. */ - public void addSCMExcludes() - { + public void addSCMExcludes() { String scmexcludes[] = AbstractScanner.DEFAULTEXCLUDES; - for ( String scmexclude : scmexcludes ) - { - addExclude( scmexclude ); + for (String scmexclude : scmexcludes) { + addExclude(scmexclude); } } - private void fireStep( File file ) - { + private void fireStep(File file) { DirStackEntry dsEntry = dirStack.peek(); int percentage = dsEntry.getPercentage(); - for ( Object listener1 : listeners ) - { + for (Object listener1 : listeners) { DirectoryWalkListener listener = (DirectoryWalkListener) listener1; - listener.directoryWalkStep( percentage, file ); + listener.directoryWalkStep(percentage, file); } } - private void fireWalkFinished() - { - for ( DirectoryWalkListener listener1 : listeners ) - { + private void fireWalkFinished() { + for (DirectoryWalkListener listener1 : listeners) { listener1.directoryWalkFinished(); } } - private void fireWalkStarting() - { - for ( DirectoryWalkListener listener1 : listeners ) - { - listener1.directoryWalkStarting( baseDir ); + private void fireWalkStarting() { + for (DirectoryWalkListener listener1 : listeners) { + listener1.directoryWalkStarting(baseDir); } } - private void fireDebugMessage( String message ) - { - for ( DirectoryWalkListener listener1 : listeners ) - { - listener1.debug( message ); + private void fireDebugMessage(String message) { + for (DirectoryWalkListener listener1 : listeners) { + listener1.debug(message); } } - private String fixPattern( String pattern ) - { + private String fixPattern(String pattern) { String cleanPattern = pattern; - if ( File.separatorChar != '/' ) - { - cleanPattern = cleanPattern.replace( '/', File.separatorChar ); + if (File.separatorChar != '/') { + cleanPattern = cleanPattern.replace('/', File.separatorChar); } - if ( File.separatorChar != '\\' ) - { - cleanPattern = cleanPattern.replace( '\\', File.separatorChar ); + if (File.separatorChar != '\\') { + cleanPattern = cleanPattern.replace('\\', File.separatorChar); } return cleanPattern; } - public void setDebugMode( boolean debugEnabled ) - { + public void setDebugMode(boolean debugEnabled) { this.debugEnabled = debugEnabled; } /** * @return Returns the baseDir. */ - public File getBaseDir() - { + public File getBaseDir() { return baseDir; } /** * @return Returns the excludes. */ - public List getExcludes() - { + public List getExcludes() { return excludes; } /** * @return Returns the includes. */ - public List getIncludes() - { + public List getIncludes() { return includes; } - private boolean isExcluded( String name ) - { - return isMatch( excludes, name ); + private boolean isExcluded(String name) { + return isMatch(excludes, name); } - private boolean isIncluded( String name ) - { - return isMatch( includes, name ); + private boolean isIncluded(String name) { + return isMatch(includes, name); } - private boolean isMatch( List patterns, String name ) - { - for ( String pattern1 : patterns ) - { - if ( SelectorUtils.matchPath( pattern1, name, isCaseSensitive ) ) - { + private boolean isMatch(List patterns, String name) { + for (String pattern1 : patterns) { + if (SelectorUtils.matchPath(pattern1, name, isCaseSensitive)) { return true; } } @@ -266,9 +233,8 @@ private boolean isMatch( List patterns, String name ) return false; } - private String relativeToBaseDir( File file ) - { - return file.getAbsolutePath().substring( baseDirOffset + 1 ); + private String relativeToBaseDir(File file) { + return file.getAbsolutePath().substring(baseDirOffset + 1); } /** @@ -276,110 +242,90 @@ private String relativeToBaseDir( File file ) * * @param listener the listener to remove. */ - public void removeDirectoryWalkListener( DirectoryWalkListener listener ) - { - listeners.remove( listener ); + public void removeDirectoryWalkListener(DirectoryWalkListener listener) { + listeners.remove(listener); } /** * Performs a Scan against the provided {@link #setBaseDir(File)} */ - public void scan() - { - if ( baseDir == null ) - { - throw new IllegalStateException( "Scan Failure. BaseDir not specified." ); + public void scan() { + if (baseDir == null) { + throw new IllegalStateException("Scan Failure. BaseDir not specified."); } - if ( !baseDir.exists() ) - { - throw new IllegalStateException( "Scan Failure. BaseDir does not exist." ); + if (!baseDir.exists()) { + throw new IllegalStateException("Scan Failure. BaseDir does not exist."); } - if ( !baseDir.isDirectory() ) - { - throw new IllegalStateException( "Scan Failure. BaseDir is not a directory." ); + if (!baseDir.isDirectory()) { + throw new IllegalStateException("Scan Failure. BaseDir is not a directory."); } - if ( includes.isEmpty() ) - { + if (includes.isEmpty()) { // default to include all. - addInclude( "**" ); + addInclude("**"); } - if ( debugEnabled ) - { + if (debugEnabled) { Iterator it; StringBuilder dbg = new StringBuilder(); - dbg.append( "DirectoryWalker Scan" ); - dbg.append( "\n Base Dir: " ).append( baseDir.getAbsolutePath() ); - dbg.append( "\n Includes: " ); + dbg.append("DirectoryWalker Scan"); + dbg.append("\n Base Dir: ").append(baseDir.getAbsolutePath()); + dbg.append("\n Includes: "); it = includes.iterator(); - while ( it.hasNext() ) - { + while (it.hasNext()) { String include = it.next(); - dbg.append( "\n - \"" ).append( include ).append( "\"" ); + dbg.append("\n - \"").append(include).append("\""); } - dbg.append( "\n Excludes: " ); + dbg.append("\n Excludes: "); it = excludes.iterator(); - while ( it.hasNext() ) - { + while (it.hasNext()) { String exclude = it.next(); - dbg.append( "\n - \"" ).append( exclude ).append( "\"" ); + dbg.append("\n - \"").append(exclude).append("\""); } - fireDebugMessage( dbg.toString() ); + fireDebugMessage(dbg.toString()); } fireWalkStarting(); dirStack = new Stack(); - scanDir( baseDir ); + scanDir(baseDir); fireWalkFinished(); } - private void scanDir( File dir ) - { + private void scanDir(File dir) { File[] files = dir.listFiles(); - if ( files == null ) - { + if (files == null) { return; } - DirectoryWalker.DirStackEntry curStackEntry = new DirectoryWalker.DirStackEntry( dir, files.length ); - if ( dirStack.isEmpty() ) - { + DirectoryWalker.DirStackEntry curStackEntry = new DirectoryWalker.DirStackEntry(dir, files.length); + if (dirStack.isEmpty()) { curStackEntry.percentageOffset = 0; curStackEntry.percentageSize = 100; - } - else - { + } else { DirectoryWalker.DirStackEntry previousStackEntry = dirStack.peek(); curStackEntry.percentageOffset = previousStackEntry.getNextPercentageOffset(); curStackEntry.percentageSize = previousStackEntry.getNextPercentageSize(); } - dirStack.push( curStackEntry ); + dirStack.push(curStackEntry); - for ( int idx = 0; idx < files.length; idx++ ) - { + for (int idx = 0; idx < files.length; idx++) { curStackEntry.index = idx; - String name = relativeToBaseDir( files[idx] ); + String name = relativeToBaseDir(files[idx]); - if ( isExcluded( name ) ) - { - fireDebugMessage( name + " is excluded." ); + if (isExcluded(name)) { + fireDebugMessage(name + " is excluded."); continue; } - if ( files[idx].isDirectory() ) - { - scanDir( files[idx] ); - } - else - { - if ( isIncluded( name ) ) - { - fireStep( files[idx] ); + if (files[idx].isDirectory()) { + scanDir(files[idx]); + } else { + if (isIncluded(name)) { + fireStep(files[idx]); } } } @@ -390,8 +336,7 @@ private void scanDir( File dir ) /** * @param baseDir The baseDir to set. */ - public void setBaseDir( File baseDir ) - { + public void setBaseDir(File baseDir) { this.baseDir = baseDir; baseDirOffset = baseDir.getAbsolutePath().length(); } @@ -399,14 +344,11 @@ public void setBaseDir( File baseDir ) /** * @param entries The excludes to set. */ - public void setExcludes( List entries ) - { + public void setExcludes(List entries) { excludes.clear(); - if ( entries != null ) - { - for ( String entry : entries ) - { - excludes.add( fixPattern( entry ) ); + if (entries != null) { + for (String entry : entries) { + excludes.add(fixPattern(entry)); } } } @@ -414,16 +356,12 @@ public void setExcludes( List entries ) /** * @param entries The includes to set. */ - public void setIncludes( List entries ) - { + public void setIncludes(List entries) { includes.clear(); - if ( entries != null ) - { - for ( String entry : entries ) - { - includes.add( fixPattern( entry ) ); + if (entries != null) { + for (String entry : entries) { + includes.add(fixPattern(entry)); } } } - } diff --git a/src/main/java/org/codehaus/plexus/util/ExceptionUtils.java b/src/main/java/org/codehaus/plexus/util/ExceptionUtils.java index 540dbe98..de4aa5df 100644 --- a/src/main/java/org/codehaus/plexus/util/ExceptionUtils.java +++ b/src/main/java/org/codehaus/plexus/util/ExceptionUtils.java @@ -78,8 +78,7 @@ * @since 1.0 * */ -public class ExceptionUtils -{ +public class ExceptionUtils { /** * Used when printing stack frames to denote the start of a wrapped exception. Package private for accessibility by * test suite. @@ -89,15 +88,21 @@ public class ExceptionUtils /** * The names of methods commonly used to access a wrapped exception. */ - protected static String[] CAUSE_METHOD_NAMES = { "getCause", "getNextException", "getTargetException", - "getException", "getSourceException", "getRootCause", "getCausedByException", "getNested" }; + protected static String[] CAUSE_METHOD_NAMES = { + "getCause", + "getNextException", + "getTargetException", + "getException", + "getSourceException", + "getRootCause", + "getCausedByException", + "getNested" + }; /** * Constructs a new ExceptionUtils. Protected to discourage instantiation. */ - protected ExceptionUtils() - { - } + protected ExceptionUtils() {} /** *

    @@ -106,13 +111,11 @@ protected ExceptionUtils() * * @param methodName the methodName to add to the list, null and empty strings are ignored */ - public static void addCauseMethodName( String methodName ) - { - if ( methodName != null && methodName.length() > 0 ) - { - List list = new ArrayList( Arrays.asList( CAUSE_METHOD_NAMES ) ); - list.add( methodName ); - CAUSE_METHOD_NAMES = list.toArray( new String[0] ); + public static void addCauseMethodName(String methodName) { + if (methodName != null && methodName.length() > 0) { + List list = new ArrayList(Arrays.asList(CAUSE_METHOD_NAMES)); + list.add(methodName); + CAUSE_METHOD_NAMES = list.toArray(new String[0]); } } @@ -147,9 +150,8 @@ public static void addCauseMethodName( String methodName ) * @return The cause of the Throwable. * @throws NullPointerException if the throwable is null */ - public static Throwable getCause( Throwable throwable ) - { - return getCause( throwable, CAUSE_METHOD_NAMES ); + public static Throwable getCause(Throwable throwable) { + return getCause(throwable, CAUSE_METHOD_NAMES); } /** @@ -163,23 +165,18 @@ public static Throwable getCause( Throwable throwable ) * @throws NullPointerException if the method names array is null or contains null * @throws NullPointerException if the throwable is null */ - public static Throwable getCause( Throwable throwable, String[] methodNames ) - { - Throwable cause = getCauseUsingWellKnownTypes( throwable ); - if ( cause == null ) - { - for ( String methodName : methodNames ) - { - cause = getCauseUsingMethodName( throwable, methodName ); - if ( cause != null ) - { + public static Throwable getCause(Throwable throwable, String[] methodNames) { + Throwable cause = getCauseUsingWellKnownTypes(throwable); + if (cause == null) { + for (String methodName : methodNames) { + cause = getCauseUsingMethodName(throwable, methodName); + if (cause != null) { break; } } - if ( cause == null ) - { - cause = getCauseUsingFieldName( throwable, "detail" ); + if (cause == null) { + cause = getCauseUsingFieldName(throwable, "detail"); } } return cause; @@ -194,14 +191,11 @@ public static Throwable getCause( Throwable throwable, String[] methodNames ) * @param throwable the throwable to get the root cause for * @return The root cause of the Throwable. */ - public static Throwable getRootCause( Throwable throwable ) - { - Throwable cause = getCause( throwable ); - if ( cause != null ) - { + public static Throwable getRootCause(Throwable throwable) { + Throwable cause = getCause(throwable); + if (cause != null) { throwable = cause; - while ( ( throwable = getCause( throwable ) ) != null ) - { + while ((throwable = getCause(throwable)) != null) { cause = throwable; } } @@ -217,18 +211,12 @@ public static Throwable getRootCause( Throwable throwable ) * @param throwable the exception to examine * @return The wrapped exception, or null if not found. */ - private static Throwable getCauseUsingWellKnownTypes( Throwable throwable ) - { - if ( throwable instanceof SQLException ) - { - return ( (SQLException) throwable ).getNextException(); - } - else if ( throwable instanceof InvocationTargetException ) - { - return ( (InvocationTargetException) throwable ).getTargetException(); - } - else - { + private static Throwable getCauseUsingWellKnownTypes(Throwable throwable) { + if (throwable instanceof SQLException) { + return ((SQLException) throwable).getNextException(); + } else if (throwable instanceof InvocationTargetException) { + return ((InvocationTargetException) throwable).getTargetException(); + } else { return null; } } @@ -242,34 +230,20 @@ else if ( throwable instanceof InvocationTargetException ) * @param methodName the name of the method to find and invoke * @return The wrapped exception, or null if not found. */ - private static Throwable getCauseUsingMethodName( Throwable throwable, String methodName ) - { + private static Throwable getCauseUsingMethodName(Throwable throwable, String methodName) { Method method = null; - try - { - method = throwable.getClass().getMethod( methodName, null ); - } - catch ( NoSuchMethodException ignored ) - { - } - catch ( SecurityException ignored ) - { - } - - if ( method != null && Throwable.class.isAssignableFrom( method.getReturnType() ) ) - { - try - { - return (Throwable) method.invoke( throwable, new Object[0] ); - } - catch ( IllegalAccessException ignored ) - { - } - catch ( IllegalArgumentException ignored ) - { - } - catch ( InvocationTargetException ignored ) - { + try { + method = throwable.getClass().getMethod(methodName, null); + } catch (NoSuchMethodException ignored) { + } catch (SecurityException ignored) { + } + + if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) { + try { + return (Throwable) method.invoke(throwable, new Object[0]); + } catch (IllegalAccessException ignored) { + } catch (IllegalArgumentException ignored) { + } catch (InvocationTargetException ignored) { } } return null; @@ -284,31 +258,19 @@ private static Throwable getCauseUsingMethodName( Throwable throwable, String me * @param fieldName the name of the attribute to examine * @return The wrapped exception, or null if not found. */ - private static Throwable getCauseUsingFieldName( Throwable throwable, String fieldName ) - { + private static Throwable getCauseUsingFieldName(Throwable throwable, String fieldName) { Field field = null; - try - { - field = throwable.getClass().getField( fieldName ); - } - catch ( NoSuchFieldException ignored ) - { - } - catch ( SecurityException ignored ) - { + try { + field = throwable.getClass().getField(fieldName); + } catch (NoSuchFieldException ignored) { + } catch (SecurityException ignored) { } - if ( field != null && Throwable.class.isAssignableFrom( field.getType() ) ) - { - try - { - return (Throwable) field.get( throwable ); - } - catch ( IllegalAccessException ignored ) - { - } - catch ( IllegalArgumentException ignored ) - { + if (field != null && Throwable.class.isAssignableFrom(field.getType())) { + try { + return (Throwable) field.get(throwable); + } catch (IllegalAccessException ignored) { + } catch (IllegalArgumentException ignored) { } } return null; @@ -322,14 +284,12 @@ private static Throwable getCauseUsingFieldName( Throwable throwable, String fie * @param throwable the exception to inspect * @return The throwable count. */ - public static int getThrowableCount( Throwable throwable ) - { + public static int getThrowableCount(Throwable throwable) { // Count the number of throwables int count = 0; - while ( throwable != null ) - { + while (throwable != null) { count++; - throwable = ExceptionUtils.getCause( throwable ); + throwable = ExceptionUtils.getCause(throwable); } return count; } @@ -342,15 +302,13 @@ public static int getThrowableCount( Throwable throwable ) * @param throwable the exception to inspect * @return The list of Throwable objects. */ - public static Throwable[] getThrowables( Throwable throwable ) - { + public static Throwable[] getThrowables(Throwable throwable) { List list = new ArrayList<>(); - while ( throwable != null ) - { - list.add( throwable ); - throwable = getCause( throwable ); + while (throwable != null) { + list.add(throwable); + throwable = getCause(throwable); } - return list.toArray( new Throwable[0] ); + return list.toArray(new Throwable[0]); } /** @@ -363,9 +321,8 @@ public static Throwable[] getThrowables( Throwable throwable ) * @return index of the stack matching the type * @see #indexOfThrowable(Throwable, Class, int) */ - public static int indexOfThrowable( Throwable throwable, Class type ) - { - return indexOfThrowable( throwable, type, 0 ); + public static int indexOfThrowable(Throwable throwable, Class type) { + return indexOfThrowable(throwable, type, 0); } /** @@ -382,21 +339,16 @@ public static int indexOfThrowable( Throwable throwable, Class type ) * @throws IndexOutOfBoundsException If the fromIndex argument is negative or not less than the count * of Throwables in the chain. */ - public static int indexOfThrowable( Throwable throwable, Class type, int fromIndex ) - { - if ( fromIndex < 0 ) - { - throw new IndexOutOfBoundsException( "Throwable index out of range: " + fromIndex ); + public static int indexOfThrowable(Throwable throwable, Class type, int fromIndex) { + if (fromIndex < 0) { + throw new IndexOutOfBoundsException("Throwable index out of range: " + fromIndex); } - Throwable[] throwables = ExceptionUtils.getThrowables( throwable ); - if ( fromIndex >= throwables.length ) - { - throw new IndexOutOfBoundsException( "Throwable index out of range: " + fromIndex ); + Throwable[] throwables = ExceptionUtils.getThrowables(throwable); + if (fromIndex >= throwables.length) { + throw new IndexOutOfBoundsException("Throwable index out of range: " + fromIndex); } - for ( int i = fromIndex; i < throwables.length; i++ ) - { - if ( throwables[i].getClass().equals( type ) ) - { + for (int i = fromIndex; i < throwables.length; i++) { + if (throwables[i].getClass().equals(type)) { return i; } } @@ -412,12 +364,10 @@ public static int indexOfThrowable( Throwable throwable, Class type, int fromInd * @param t the exception * @param stream the stream */ - public static void printRootCauseStackTrace( Throwable t, PrintStream stream ) - { - String trace[] = getRootCauseStackTrace( t ); - for ( String aTrace : trace ) - { - stream.println( aTrace ); + public static void printRootCauseStackTrace(Throwable t, PrintStream stream) { + String trace[] = getRootCauseStackTrace(t); + for (String aTrace : trace) { + stream.println(aTrace); } stream.flush(); } @@ -426,9 +376,8 @@ public static void printRootCauseStackTrace( Throwable t, PrintStream stream ) * Equivalent to printRootCauseStackTrace(t, System.err) * @param t the exception */ - public static void printRootCauseStackTrace( Throwable t ) - { - printRootCauseStackTrace( t, System.err ); + public static void printRootCauseStackTrace(Throwable t) { + printRootCauseStackTrace(t, System.err); } /** @@ -436,12 +385,10 @@ public static void printRootCauseStackTrace( Throwable t ) * @param t the cause * @param writer the writer */ - public static void printRootCauseStackTrace( Throwable t, PrintWriter writer ) - { - String trace[] = getRootCauseStackTrace( t ); - for ( String aTrace : trace ) - { - writer.println( aTrace ); + public static void printRootCauseStackTrace(Throwable t, PrintWriter writer) { + String trace[] = getRootCauseStackTrace(t); + for (String aTrace : trace) { + writer.println(aTrace); } writer.flush(); } @@ -452,34 +399,27 @@ public static void printRootCauseStackTrace( Throwable t, PrintWriter writer ) * @param t the cause * @return the Stack */ - public static String[] getRootCauseStackTrace( Throwable t ) - { - Throwable[] throwables = getThrowables( t ); + public static String[] getRootCauseStackTrace(Throwable t) { + Throwable[] throwables = getThrowables(t); int count = throwables.length; ArrayList frames = new ArrayList<>(); - List nextTrace = getStackFrameList( throwables[count - 1] ); - for ( int i = count; --i >= 0; ) - { + List nextTrace = getStackFrameList(throwables[count - 1]); + for (int i = count; --i >= 0; ) { List trace = nextTrace; - if ( i != 0 ) - { - nextTrace = getStackFrameList( throwables[i - 1] ); - removeCommonFrames( trace, nextTrace ); + if (i != 0) { + nextTrace = getStackFrameList(throwables[i - 1]); + removeCommonFrames(trace, nextTrace); } - if ( i == ( count - 1 ) ) - { - frames.add( throwables[i].toString() ); + if (i == (count - 1)) { + frames.add(throwables[i].toString()); + } else { + frames.add(WRAPPED_MARKER + throwables[i].toString()); } - else - { - frames.add( WRAPPED_MARKER + throwables[i].toString() ); - } - for ( String aTrace : trace ) - { - frames.add( aTrace ); + for (String aTrace : trace) { + frames.add(aTrace); } } - return frames.toArray( new String[0] ); + return frames.toArray(new String[0]); } /** @@ -488,19 +428,16 @@ public static String[] getRootCauseStackTrace( Throwable t ) * @param causeFrames stack trace of a cause throwable * @param wrapperFrames stack trace of a wrapper throwable */ - private static void removeCommonFrames( List causeFrames, List wrapperFrames ) - { + private static void removeCommonFrames(List causeFrames, List wrapperFrames) { int causeFrameIndex = causeFrames.size() - 1; int wrapperFrameIndex = wrapperFrames.size() - 1; - while ( causeFrameIndex >= 0 && wrapperFrameIndex >= 0 ) - { + while (causeFrameIndex >= 0 && wrapperFrameIndex >= 0) { // Remove the frame from the cause trace if it is the same // as in the wrapper trace - String causeFrame = causeFrames.get( causeFrameIndex ); - String wrapperFrame = wrapperFrames.get( wrapperFrameIndex ); - if ( causeFrame.equals( wrapperFrame ) ) - { - causeFrames.remove( causeFrameIndex ); + String causeFrame = causeFrames.get(causeFrameIndex); + String wrapperFrame = wrapperFrames.get(wrapperFrameIndex); + if (causeFrame.equals(wrapperFrame)) { + causeFrames.remove(causeFrameIndex); } causeFrameIndex--; wrapperFrameIndex--; @@ -513,11 +450,10 @@ private static void removeCommonFrames( List causeFrames, List w * @param t The Throwable. * @return The stack trace as generated by the exception's printStackTrace(PrintWriter) method. */ - public static String getStackTrace( Throwable t ) - { + public static String getStackTrace(Throwable t) { StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter( sw, true ); - t.printStackTrace( pw ); + PrintWriter pw = new PrintWriter(sw, true); + t.printStackTrace(pw); return sw.getBuffer().toString(); } @@ -527,16 +463,13 @@ public static String getStackTrace( Throwable t ) * @param t The Throwable. * @return The nested stack trace, with the root cause first. */ - public static String getFullStackTrace( Throwable t ) - { + public static String getFullStackTrace(Throwable t) { StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter( sw, true ); - Throwable[] ts = getThrowables( t ); - for ( Throwable t1 : ts ) - { - t1.printStackTrace( pw ); - if ( isNestedThrowable( t1 ) ) - { + PrintWriter pw = new PrintWriter(sw, true); + Throwable[] ts = getThrowables(t); + for (Throwable t1 : ts) { + t1.printStackTrace(pw); + if (isNestedThrowable(t1)) { break; } } @@ -549,53 +482,35 @@ public static String getFullStackTrace( Throwable t ) * @param throwable The Throwable. * @return boolean true/false */ - public static boolean isNestedThrowable( Throwable throwable ) - { - if ( throwable == null ) - { + public static boolean isNestedThrowable(Throwable throwable) { + if (throwable == null) { return false; } - if ( throwable instanceof SQLException ) - { + if (throwable instanceof SQLException) { return true; - } - else if ( throwable instanceof InvocationTargetException ) - { + } else if (throwable instanceof InvocationTargetException) { return true; } - for ( String CAUSE_METHOD_NAME : CAUSE_METHOD_NAMES ) - { - try - { - Method method = throwable.getClass().getMethod( CAUSE_METHOD_NAME, null ); - if ( method != null ) - { + for (String CAUSE_METHOD_NAME : CAUSE_METHOD_NAMES) { + try { + Method method = throwable.getClass().getMethod(CAUSE_METHOD_NAME, null); + if (method != null) { return true; } - } - catch ( NoSuchMethodException ignored ) - { - } - catch ( SecurityException ignored ) - { + } catch (NoSuchMethodException ignored) { + } catch (SecurityException ignored) { } } - try - { - Field field = throwable.getClass().getField( "detail" ); - if ( field != null ) - { + try { + Field field = throwable.getClass().getField("detail"); + if (field != null) { return true; } - } - catch ( NoSuchFieldException ignored ) - { - } - catch ( SecurityException ignored ) - { + } catch (NoSuchFieldException ignored) { + } catch (SecurityException ignored) { } return false; @@ -608,24 +523,21 @@ else if ( throwable instanceof InvocationTargetException ) * @param t The Throwable. * @return An array of strings describing each stack frame. */ - public static String[] getStackFrames( Throwable t ) - { - return getStackFrames( getStackTrace( t ) ); + public static String[] getStackFrames(Throwable t) { + return getStackFrames(getStackTrace(t)); } /** * Functionality shared between the getStackFrames(Throwable) methods of this and the classes. */ - static String[] getStackFrames( String stackTrace ) - { - String linebreak = System.getProperty( "line.separator" ); - StringTokenizer frames = new StringTokenizer( stackTrace, linebreak ); + static String[] getStackFrames(String stackTrace) { + String linebreak = System.getProperty("line.separator"); + StringTokenizer frames = new StringTokenizer(stackTrace, linebreak); List list = new LinkedList(); - while ( frames.hasMoreTokens() ) - { - list.add( frames.nextToken() ); + while (frames.hasMoreTokens()) { + list.add(frames.nextToken()); } - return list.toArray( new String[0] ); + return list.toArray(new String[0]); } /** @@ -635,25 +547,20 @@ static String[] getStackFrames( String stackTrace ) * @param t is any throwable * @return List of stack frames */ - static List getStackFrameList( Throwable t ) - { - String stackTrace = getStackTrace( t ); - String linebreak = System.getProperty( "line.separator" ); - StringTokenizer frames = new StringTokenizer( stackTrace, linebreak ); + static List getStackFrameList(Throwable t) { + String stackTrace = getStackTrace(t); + String linebreak = System.getProperty("line.separator"); + StringTokenizer frames = new StringTokenizer(stackTrace, linebreak); List list = new LinkedList(); boolean traceStarted = false; - while ( frames.hasMoreTokens() ) - { + while (frames.hasMoreTokens()) { String token = frames.nextToken(); // Determine if the line starts with at - int at = token.indexOf( "at" ); - if ( at != -1 && token.substring( 0, at ).trim().length() == 0 ) - { + int at = token.indexOf("at"); + if (at != -1 && token.substring(0, at).trim().length() == 0) { traceStarted = true; - list.add( token ); - } - else if ( traceStarted ) - { + list.add(token); + } else if (traceStarted) { break; } } diff --git a/src/main/java/org/codehaus/plexus/util/Expand.java b/src/main/java/org/codehaus/plexus/util/Expand.java index 5b195811..8abcdd95 100644 --- a/src/main/java/org/codehaus/plexus/util/Expand.java +++ b/src/main/java/org/codehaus/plexus/util/Expand.java @@ -73,12 +73,11 @@ * @since Ant 1.1 @ant.task category="packaging" name="unzip" name="unjar" name="unwar" * */ -public class Expand -{ +public class Expand { - private File dest;// req + private File dest; // req - private File source;// req + private File source; // req private boolean overwrite = true; @@ -87,44 +86,37 @@ public class Expand * * @exception Exception Thrown in unrecoverable error. */ - public void execute() - throws Exception - { - expandFile( source, dest ); + public void execute() throws Exception { + expandFile(source, dest); } - protected void expandFile( final File srcF, final File dir ) - throws Exception - { + protected void expandFile(final File srcF, final File dir) throws Exception { // code from WarExpand - try ( ZipInputStream zis = new ZipInputStream( Files.newInputStream( srcF.toPath() ) ) ) - { - for ( ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry() ) - { - extractFile( srcF, dir, zis, ze.getName(), new Date( ze.getTime() ), ze.isDirectory() ); + try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(srcF.toPath()))) { + for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) { + extractFile(srcF, dir, zis, ze.getName(), new Date(ze.getTime()), ze.isDirectory()); } - } - catch ( IOException ioe ) - { - throw new Exception( "Error while expanding " + srcF.getPath(), ioe ); + } catch (IOException ioe) { + throw new Exception("Error while expanding " + srcF.getPath(), ioe); } } - protected void extractFile( File srcF, File dir, InputStream compressedInputStream, String entryName, - Date entryDate, boolean isDirectory ) - throws Exception - { - File f = FileUtils.resolveFile( dir, entryName ); - - if ( !f.getAbsolutePath().startsWith( dir.getAbsolutePath() ) ) - { - throw new IOException( "Entry '" + entryName + "' outside the target directory." ); + protected void extractFile( + File srcF, + File dir, + InputStream compressedInputStream, + String entryName, + Date entryDate, + boolean isDirectory) + throws Exception { + File f = FileUtils.resolveFile(dir, entryName); + + if (!f.getAbsolutePath().startsWith(dir.getAbsolutePath())) { + throw new IOException("Entry '" + entryName + "' outside the target directory."); } - try - { - if ( !overwrite && f.exists() && f.lastModified() >= entryDate.getTime() ) - { + try { + if (!overwrite && f.exists() && f.lastModified() >= entryDate.getTime()) { return; } @@ -132,30 +124,23 @@ protected void extractFile( File srcF, File dir, InputStream compressedInputStre File dirF = f.getParentFile(); dirF.mkdirs(); - if ( isDirectory ) - { + if (isDirectory) { f.mkdirs(); - } - else - { + } else { byte[] buffer = new byte[65536]; - - try ( OutputStream fos = Files.newOutputStream( f.toPath() ) ) - { - for ( int length = compressedInputStream.read( buffer ); - length >= 0; - fos.write( buffer, 0, length ), length = compressedInputStream.read( buffer ) ) + + try (OutputStream fos = Files.newOutputStream(f.toPath())) { + for (int length = compressedInputStream.read(buffer); + length >= 0; + fos.write(buffer, 0, length), length = compressedInputStream.read(buffer)) ; } } - f.setLastModified( entryDate.getTime() ); + f.setLastModified(entryDate.getTime()); + } catch (FileNotFoundException ex) { + throw new Exception("Can't extract file " + srcF.getPath(), ex); } - catch ( FileNotFoundException ex ) - { - throw new Exception( "Can't extract file " + srcF.getPath(), ex ); - } - } /** @@ -163,8 +148,7 @@ protected void extractFile( File srcF, File dir, InputStream compressedInputStre * * @param d Path to the directory. */ - public void setDest( File d ) - { + public void setDest(File d) { this.dest = d; } @@ -173,17 +157,14 @@ public void setDest( File d ) * * @param s Path to zip-file. */ - public void setSrc( File s ) - { + public void setSrc(File s) { this.source = s; } /** * @param b Should we overwrite files in dest, even if they are newer than the corresponding entries in the archive? */ - public void setOverwrite( boolean b ) - { + public void setOverwrite(boolean b) { overwrite = b; } - } diff --git a/src/main/java/org/codehaus/plexus/util/FastMap.java b/src/main/java/org/codehaus/plexus/util/FastMap.java index 9bb9e82f..54076641 100644 --- a/src/main/java/org/codehaus/plexus/util/FastMap.java +++ b/src/main/java/org/codehaus/plexus/util/FastMap.java @@ -49,13 +49,11 @@ *

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

    - * + * * @author Jean-Marie Dautelle * @version 5.3, October 31 2003 */ -public class FastMap - implements Map, Cloneable, Serializable -{ +public class FastMap implements Map, Cloneable, Serializable { /** * Holds the map's hash table. @@ -95,40 +93,37 @@ public class FastMap /** * Creates a {@link FastMap} with a capacity of 256 entries. */ - public FastMap() - { - initialize( 256 ); + public FastMap() { + initialize(256); } /** * Creates a {@link FastMap}, copy of the specified Map. If the specified map is not an instance of * {@link FastMap}, the newly created map has a capacity set to the specified map's size. The copy has the same * order as the original, regardless of the original map's implementation: - * + * *
          *     TreeMap dictionary = ...;
          *     FastMap dictionaryLookup = new FastMap(dictionary);
          * 
    - * + * * @param map the map whose mappings are to be placed in this map. */ - public FastMap( Map map ) - { - int capacity = ( map instanceof FastMap ) ? ( (FastMap) map ).capacity() : map.size(); - initialize( capacity ); - putAll( map ); + public FastMap(Map map) { + int capacity = (map instanceof FastMap) ? ((FastMap) map).capacity() : map.size(); + initialize(capacity); + putAll(map); } /** * Creates a {@link FastMap} with the specified capacity. Unless the capacity is exceeded, operations on this map do * not allocate entries. For optimum performance, the capacity should be of the same order of magnitude or larger * than the expected map's size. - * + * * @param capacity the number of buckets in the hash table; it also defines the number of pre-allocated entries. */ - public FastMap( int capacity ) - { - initialize( capacity ); + public FastMap(int capacity) { + initialize(capacity); } /** @@ -137,8 +132,7 @@ public FastMap( int capacity ) * @return this map's size. */ @Override - public int size() - { + public int size() { return _size; } @@ -148,8 +142,7 @@ public int size() * * @return this map's capacity. */ - public int capacity() - { + public int capacity() { return _capacity; } @@ -159,8 +152,7 @@ public int capacity() * @return true if this map contains no key-value mappings; false otherwise. */ @Override - public boolean isEmpty() - { + public boolean isEmpty() { return _size == 0; } @@ -172,13 +164,10 @@ public boolean isEmpty() * @throws NullPointerException if the key is null. */ @Override - public boolean containsKey( Object key ) - { - EntryImpl entry = _entries[keyHash( key ) & _mask]; - while ( entry != null ) - { - if ( key.equals( entry._key ) ) - { + public boolean containsKey(Object key) { + EntryImpl entry = _entries[keyHash(key) & _mask]; + while (entry != null) { + if (key.equals(entry._key)) { return true; } entry = entry._next; @@ -194,13 +183,10 @@ public boolean containsKey( Object key ) * @throws NullPointerException if the key is null. */ @Override - public boolean containsValue( Object value ) - { + public boolean containsValue(Object value) { EntryImpl entry = _mapFirst; - while ( entry != null ) - { - if ( value.equals( entry._value ) ) - { + while (entry != null) { + if (value.equals(entry._value)) { return true; } entry = entry._after; @@ -217,13 +203,10 @@ public boolean containsValue( Object value ) * @throws NullPointerException if key is null. */ @Override - public V get( Object key ) - { - EntryImpl entry = _entries[keyHash( key ) & _mask]; - while ( entry != null ) - { - if ( key.equals( entry._key ) ) - { + public V get(Object key) { + EntryImpl entry = _entries[keyHash(key) & _mask]; + while (entry != null) { + if (key.equals(entry._key)) { return entry._value; } entry = entry._next; @@ -233,17 +216,14 @@ public V get( Object key ) /** * Returns the entry with the specified key. - * + * * @param key the key whose associated entry is to be returned. * @return the entry for the specified key or null if none. */ - public Map.Entry getEntry( Object key ) - { - EntryImpl entry = _entries[keyHash( key ) & _mask]; - while ( entry != null ) - { - if ( key.equals( entry._key ) ) - { + public Map.Entry getEntry(Object key) { + EntryImpl entry = _entries[keyHash(key) & _mask]; + while (entry != null) { + if (key.equals(entry._key)) { return entry; } entry = entry._next; @@ -263,13 +243,10 @@ public Map.Entry getEntry( Object key ) * @throws NullPointerException if the key is null. */ @Override - public Object put( Object key, Object value ) - { - EntryImpl entry = _entries[keyHash( key ) & _mask]; - while ( entry != null ) - { - if ( key.equals( entry._key ) ) - { + public Object put(Object key, Object value) { + EntryImpl entry = _entries[keyHash(key) & _mask]; + while (entry != null) { + if (key.equals(entry._key)) { Object prevValue = entry._value; entry._value = value; return prevValue; @@ -277,7 +254,7 @@ public Object put( Object key, Object value ) entry = entry._next; } // No previous mapping. - addEntry( key, value ); + addEntry(key, value); return null; } @@ -289,11 +266,9 @@ public Object put( Object key, Object value ) * null keys. */ @Override - public void putAll( Map map ) - { - for ( Entry entry : map.entrySet() ) - { - addEntry( entry.getKey(), entry.getValue() ); + public void putAll(Map map) { + for (Entry entry : map.entrySet()) { + addEntry(entry.getKey(), entry.getValue()); } } @@ -307,15 +282,12 @@ public void putAll( Map map ) * @throws NullPointerException if the key is null. */ @Override - public V remove( Object key ) - { - EntryImpl entry = _entries[keyHash( key ) & _mask]; - while ( entry != null ) - { - if ( key.equals( entry._key ) ) - { + public V remove(Object key) { + EntryImpl entry = _entries[keyHash(key) & _mask]; + while (entry != null) { + if (key.equals(entry._key)) { V prevValue = entry._value; - removeEntry( entry ); + removeEntry(entry); return prevValue; } entry = entry._next; @@ -327,28 +299,22 @@ public V remove( Object key ) * Removes all mappings from this {@link FastMap}. */ @Override - public void clear() - { + public void clear() { // Clears all keys, values and buckets linked lists. - for ( EntryImpl entry = _mapFirst; entry != null; entry = entry._after ) - { + for (EntryImpl entry = _mapFirst; entry != null; entry = entry._after) { entry._key = null; entry._value = null; entry._before = null; entry._next = null; - if ( entry._previous == null ) - { // First in bucket. + if (entry._previous == null) { // First in bucket. _entries[entry._index] = null; - } - else - { + } else { entry._previous = null; } } // Recycles all entries. - if ( _mapLast != null ) - { + if (_mapLast != null) { _mapLast._after = _poolFirst; // Connects to pool. _poolFirst = _mapFirst; _mapFirst = null; @@ -362,24 +328,18 @@ public void clear() * Changes the current capacity of this {@link FastMap}. If the capacity is increased, new entries are allocated and * added to the pool. If the capacity is decreased, entries from the pool are deallocated (and are eventually * garbage collected). The capacity also determined the number of buckets for the hash table. - * + * * @param newCapacity the new capacity of this map. */ - public void setCapacity( int newCapacity ) - { - if ( newCapacity > _capacity ) - { // Capacity increases. - for ( int i = _capacity; i < newCapacity; i++ ) - { + public void setCapacity(int newCapacity) { + if (newCapacity > _capacity) { // Capacity increases. + for (int i = _capacity; i < newCapacity; i++) { EntryImpl entry = new EntryImpl(); entry._after = _poolFirst; _poolFirst = entry; } - } - else if ( newCapacity < _capacity ) - { // Capacity decreases. - for ( int i = newCapacity; ( i < _capacity ) && ( _poolFirst != null ); i++ ) - { + } else if (newCapacity < _capacity) { // Capacity decreases. + for (int i = newCapacity; (i < _capacity) && (_poolFirst != null); i++) { // Disconnects the entry for gc to do its work. EntryImpl entry = _poolFirst; _poolFirst = entry._after; @@ -388,29 +348,25 @@ else if ( newCapacity < _capacity ) } // Find a power of 2 >= capacity int tableLength = 16; - while ( tableLength < newCapacity ) - { + while (tableLength < newCapacity) { tableLength <<= 1; } // Checks if the hash table has to be re-sized. - if ( _entries.length != tableLength ) - { + if (_entries.length != tableLength) { _entries = new EntryImpl[tableLength]; _mask = tableLength - 1; // Repopulates the hash table. EntryImpl entry = _mapFirst; - while ( entry != null ) - { - int index = keyHash( entry._key ) & _mask; + while (entry != null) { + int index = keyHash(entry._key) & _mask; entry._index = index; // Connects to bucket. entry._previous = null; // Resets previous. EntryImpl next = _entries[index]; entry._next = next; - if ( next != null ) - { + if (next != null) { next._previous = entry; } _entries[index] = entry; @@ -427,17 +383,13 @@ else if ( newCapacity < _capacity ) * @return a shallow copy of this map. */ @Override - public Object clone() - { - try - { + public Object clone() { + try { FastMap clone = (FastMap) super.clone(); - clone.initialize( _capacity ); - clone.putAll( this ); + clone.initialize(_capacity); + clone.putAll(this); return clone; - } - catch ( CloneNotSupportedException e ) - { + } catch (CloneNotSupportedException e) { // Should not happen, since we are Cloneable. throw new InternalError(); } @@ -451,35 +403,24 @@ public Object clone() * @return true if the specified object is equal to this map; false otherwise. */ @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; - } - else if ( obj instanceof Map ) - { + } else if (obj instanceof Map) { Map that = (Map) obj; - if ( this.size() == that.size() ) - { + if (this.size() == that.size()) { EntryImpl entry = _mapFirst; - while ( entry != null ) - { - if ( !that.entrySet().contains( entry ) ) - { + while (entry != null) { + if (!that.entrySet().contains(entry)) { return false; } entry = entry._after; } return true; - } - else - { + } else { return false; } - } - else - { + } else { return false; } } @@ -490,12 +431,10 @@ else if ( obj instanceof Map ) * @return the hash code value for this map. */ @Override - public int hashCode() - { + public int hashCode() { int code = 0; EntryImpl entry = _mapFirst; - while ( entry != null ) - { + while (entry != null) { code += entry.hashCode(); entry = entry._after; } @@ -508,8 +447,7 @@ public int hashCode() * @return this.entrySet().toString(); */ @Override - public String toString() - { + public String toString() { return entrySet().toString(); } @@ -523,40 +461,32 @@ public String toString() * @return a collection view of the values contained in this map. */ @Override - public Collection values() - { + public Collection values() { return _values; } private transient Values _values; - private class Values - extends AbstractCollection - { + private class Values extends AbstractCollection { @Override - public Iterator iterator() - { - return new Iterator() - { + public Iterator iterator() { + return new Iterator() { EntryImpl after = _mapFirst; EntryImpl before; @Override - public void remove() - { - removeEntry( before ); + public void remove() { + removeEntry(before); } @Override - public boolean hasNext() - { + public boolean hasNext() { return after != null; } @Override - public Object next() - { + public Object next() { before = after; after = after._after; return before._value; @@ -565,20 +495,17 @@ public Object next() } @Override - public int size() - { + public int size() { return _size; } @Override - public boolean contains( Object o ) - { - return containsValue( o ); + public boolean contains(Object o) { + return containsValue(o); } @Override - public void clear() - { + public void clear() { FastMap.this.clear(); } } @@ -594,40 +521,32 @@ public void clear() * @return a collection view of the mappings contained in this map. */ @Override - public Set entrySet() - { + public Set entrySet() { return _entrySet; } private transient EntrySet _entrySet; - private class EntrySet - extends AbstractSet - { + private class EntrySet extends AbstractSet { @Override - public Iterator iterator() - { - return new Iterator() - { + public Iterator iterator() { + return new Iterator() { EntryImpl after = _mapFirst; EntryImpl before; @Override - public void remove() - { - removeEntry( before ); + public void remove() { + removeEntry(before); } @Override - public boolean hasNext() - { + public boolean hasNext() { return after != null; } @Override - public Object next() - { + public Object next() { before = after; after = after._after; return before; @@ -636,36 +555,28 @@ public Object next() } @Override - public int size() - { + public int size() { return _size; } @Override - public boolean contains( Object obj ) - { // Optimization. - if ( obj instanceof Map.Entry ) - { + public boolean contains(Object obj) { // Optimization. + if (obj instanceof Map.Entry) { Map.Entry entry = (Map.Entry) obj; - Map.Entry mapEntry = getEntry( entry.getKey() ); - return entry.equals( mapEntry ); - } - else - { + Map.Entry mapEntry = getEntry(entry.getKey()); + return entry.equals(mapEntry); + } else { return false; } } @Override - public boolean remove( Object obj ) - { // Optimization. - if ( obj instanceof Map.Entry ) - { + public boolean remove(Object obj) { // Optimization. + if (obj instanceof Map.Entry) { Map.Entry entry = (Map.Entry) obj; - EntryImpl mapEntry = (EntryImpl) getEntry( entry.getKey() ); - if ( ( mapEntry != null ) && ( entry.getValue() ).equals( mapEntry._value ) ) - { - removeEntry( mapEntry ); + EntryImpl mapEntry = (EntryImpl) getEntry(entry.getKey()); + if ((mapEntry != null) && (entry.getValue()).equals(mapEntry._value)) { + removeEntry(mapEntry); return true; } } @@ -683,40 +594,32 @@ public boolean remove( Object obj ) * @return a set view of the keys contained in this map. */ @Override - public Set keySet() - { + public Set keySet() { return _keySet; } private transient KeySet _keySet; - private class KeySet - extends AbstractSet - { + private class KeySet extends AbstractSet { @Override - public Iterator iterator() - { - return new Iterator() - { + public Iterator iterator() { + return new Iterator() { EntryImpl after = _mapFirst; EntryImpl before; @Override - public void remove() - { - removeEntry( before ); + public void remove() { + removeEntry(before); } @Override - public boolean hasNext() - { + public boolean hasNext() { return after != null; } @Override - public Object next() - { + public Object next() { before = after; after = after._after; return before._key; @@ -725,26 +628,22 @@ public Object next() } @Override - public int size() - { + public int size() { return _size; } @Override - public boolean contains( Object obj ) - { // Optimization. - return FastMap.this.containsKey( obj ); + public boolean contains(Object obj) { // Optimization. + return FastMap.this.containsKey(obj); } @Override - public boolean remove( Object obj ) - { // Optimization. - return FastMap.this.remove( obj ) != null; + public boolean remove(Object obj) { // Optimization. + return FastMap.this.remove(obj) != null; } @Override - public void clear() - { // Optimization. + public void clear() { // Optimization. FastMap.this.clear(); } } @@ -753,7 +652,7 @@ public void clear() * This methods is being called when the size of this {@link FastMap} has changed. The default behavior is to double * the map's capacity when the map's size reaches the current map's capacity. Sub-class may override this method to * implement custom resizing policies or to disable automatic resizing. For example: - * + * *
          * Map fixedCapacityMap = new FastMap( 256 )
          * {
    @@ -763,77 +662,66 @@ public void clear()
          *     }
          * };
          * 
    - * + * * @see #setCapacity */ - protected void sizeChanged() - { - if ( size() > capacity() ) - { - setCapacity( capacity() * 2 ); + protected void sizeChanged() { + if (size() > capacity()) { + setCapacity(capacity() * 2); } } /** * Returns the hash code for the specified key. The formula being used is identical to the formula used by * java.util.HashMap (ensures similar behavior for ill-conditioned hashcode keys). - * + * * @param key the key to calculate the hashcode for. * @return the hash code for the specified key. */ - private static int keyHash( Object key ) - { + private static int keyHash(Object key) { // From HashMap.hash(Object) function. int hashCode = key.hashCode(); - hashCode += ~( hashCode << 9 ); - hashCode ^= ( hashCode >>> 14 ); - hashCode += ( hashCode << 4 ); - hashCode ^= ( hashCode >>> 10 ); + hashCode += ~(hashCode << 9); + hashCode ^= (hashCode >>> 14); + hashCode += (hashCode << 4); + hashCode ^= (hashCode >>> 10); return hashCode; } /** * Adds a new entry for the specified key and value. - * + * * @param key the entry's key. * @param value the entry's value. */ - private void addEntry( Object key, Object value ) - { + private void addEntry(Object key, Object value) { EntryImpl entry = _poolFirst; - if ( entry != null ) - { + if (entry != null) { _poolFirst = entry._after; entry._after = null; - } - else - { // Pool empty. + } else { // Pool empty. entry = new EntryImpl(); } // Setup entry parameters. entry._key = key; entry._value = value; - int index = keyHash( key ) & _mask; + int index = keyHash(key) & _mask; entry._index = index; // Connects to bucket. EntryImpl next = _entries[index]; entry._next = next; - if ( next != null ) - { + if (next != null) { next._previous = entry; } _entries[index] = entry; // Connects to collection. - if ( _mapLast != null ) - { + if (_mapLast != null) { entry._before = _mapLast; _mapLast._after = entry; - } - else - { + } else { _mapFirst = entry; } _mapLast = entry; @@ -845,26 +733,21 @@ private void addEntry( Object key, Object value ) /** * Removes the specified entry from the map. - * + * * @param entry the entry to be removed. */ - private void removeEntry( EntryImpl entry ) - { + private void removeEntry(EntryImpl entry) { // Removes from bucket. EntryImpl previous = entry._previous; EntryImpl next = entry._next; - if ( previous != null ) - { + if (previous != null) { previous._next = next; entry._previous = null; - } - else - { // First in bucket. + } else { // First in bucket. _entries[entry._index] = next; } - if ( next != null ) - { + if (next != null) { next._previous = previous; entry._next = null; } // Else do nothing, no last pointer. @@ -872,21 +755,15 @@ private void removeEntry( EntryImpl entry ) // Removes from collection. EntryImpl before = entry._before; EntryImpl after = entry._after; - if ( before != null ) - { + if (before != null) { before._after = after; entry._before = null; - } - else - { // First in collection. + } else { // First in collection. _mapFirst = after; } - if ( after != null ) - { + if (after != null) { after._before = before; - } - else - { // Last in collection. + } else { // Last in collection. _mapLast = before; } @@ -906,15 +783,13 @@ private void removeEntry( EntryImpl entry ) /** * Initializes this instance for the specified capacity. Once initialized, operations on this map should not create * new objects (unless the map's size exceeds the specified capacity). - * + * * @param capacity the initial capacity. */ - private void initialize( int capacity ) - { + private void initialize(int capacity) { // Find a power of 2 >= capacity int tableLength = 16; - while ( tableLength < capacity ) - { + while (tableLength < capacity) { tableLength <<= 1; } // Allocates hash table. @@ -931,8 +806,7 @@ private void initialize( int capacity ) _mapFirst = null; _mapLast = null; // Allocates entries. - for ( int i = 0; i < capacity; i++ ) - { + for (int i = 0; i < capacity; i++) { EntryImpl entry = new EntryImpl(); entry._after = _poolFirst; _poolFirst = entry; @@ -946,17 +820,14 @@ private void initialize( int capacity ) * @throws IOException if an I/O error occurs. * @throws ClassNotFoundException if the class for the object de-serialized is not found. */ - private void readObject( ObjectInputStream stream ) - throws IOException, ClassNotFoundException - { + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { int capacity = stream.readInt(); - initialize( capacity ); + initialize(capacity); int size = stream.readInt(); - for ( int i = 0; i < size; i++ ) - { + for (int i = 0; i < size; i++) { Object key = stream.readObject(); Object value = stream.readObject(); - addEntry( key, value ); + addEntry(key, value); } } @@ -966,32 +837,26 @@ private void readObject( ObjectInputStream stream ) * @param stream the object output stream. * @throws IOException if an I/O error occurs. */ - private void writeObject( ObjectOutputStream stream ) - throws IOException - { - stream.writeInt( _capacity ); - stream.writeInt( _size ); + private void writeObject(ObjectOutputStream stream) throws IOException { + stream.writeInt(_capacity); + stream.writeInt(_size); int count = 0; EntryImpl entry = _mapFirst; - while ( entry != null ) - { - stream.writeObject( entry._key ); - stream.writeObject( entry._value ); + while (entry != null) { + stream.writeObject(entry._key); + stream.writeObject(entry._value); count++; entry = entry._after; } - if ( count != _size ) - { - throw new IOException( "FastMap Corrupted" ); + if (count != _size) { + throw new IOException("FastMap Corrupted"); } } /** * This class represents a {@link FastMap} entry. */ - private static final class EntryImpl - implements Map.Entry - { + private static final class EntryImpl implements Map.Entry { /** * Holds the entry key (null when in pool). @@ -1030,35 +895,32 @@ private static final class EntryImpl /** * Returns the key for this entry. - * + * * @return the entry's key. */ @Override - public K getKey() - { + public K getKey() { return _key; } /** * Returns the value for this entry. - * + * * @return the entry's value. */ @Override - public V getValue() - { + public V getValue() { return _value; } /** * Sets the value for this entry. - * + * * @param value the new value. * @return the previous value. */ @Override - public V setValue( V value ) - { + public V setValue(V value) { V old = _value; _value = value; return old; @@ -1066,45 +928,39 @@ public V setValue( V value ) /** * Indicates if this entry is considered equals to the specified entry. - * + * * @param that the object to test for equality. * @return true if both entry are considered equal; false otherwise. */ @Override - public boolean equals( Object that ) - { - if ( that instanceof Map.Entry ) - { + public boolean equals(Object that) { + if (that instanceof Map.Entry) { Map.Entry entry = (Map.Entry) that; - return ( _key.equals( entry.getKey() ) ) - && ( ( _value != null ) ? _value.equals( entry.getValue() ) : ( entry.getValue() == null ) ); - } - else - { + return (_key.equals(entry.getKey())) + && ((_value != null) ? _value.equals(entry.getValue()) : (entry.getValue() == null)); + } else { return false; } } /** * Returns the hash code for this entry. - * + * * @return this entry's hash code. */ @Override - public int hashCode() - { - return _key.hashCode() ^ ( ( _value != null ) ? _value.hashCode() : 0 ); + public int hashCode() { + return _key.hashCode() ^ ((_value != null) ? _value.hashCode() : 0); } /** * Returns the text representation of this entry. - * + * * @return this entry's textual representation. */ @Override - public String toString() - { + public String toString() { return _key + "=" + _value; } } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/util/FileUtils.java b/src/main/java/org/codehaus/plexus/util/FileUtils.java index e182145e..fceb191e 100644 --- a/src/main/java/org/codehaus/plexus/util/FileUtils.java +++ b/src/main/java/org/codehaus/plexus/util/FileUtils.java @@ -55,9 +55,6 @@ * */ -import org.codehaus.plexus.util.io.InputStreamFacade; -import org.codehaus.plexus.util.io.URLInputStreamFacade; - import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -79,11 +76,14 @@ import java.util.List; import java.util.Random; +import org.codehaus.plexus.util.io.InputStreamFacade; +import org.codehaus.plexus.util.io.URLInputStreamFacade; + /** *

    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 * /www/hosted/mysite/index.html, can be broken into: *

      @@ -94,15 +94,15 @@ *
    *

    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 * 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.

    * @@ -114,8 +114,7 @@ * @author Jeff Turner * */ -public class FileUtils extends BaseFileUtils -{ +public class FileUtils extends BaseFileUtils { /** * The number of bytes in a kilobyte. */ @@ -142,14 +141,13 @@ public class FileUtils extends BaseFileUtils * @see * http://support.microsoft.com/?scid=kb%3Ben-us%3B177506&x=12&y=13 */ - private static final String[] INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME = { ":", "*", "?", "\"", "<", ">", "|" }; + private static final String[] INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME = {":", "*", "?", "\"", "<", ">", "|"}; /** * @return the default excludes pattern * @see DirectoryScanner#DEFAULTEXCLUDES */ - public static String[] getDefaultExcludes() - { + public static String[] getDefaultExcludes() { return DirectoryScanner.DEFAULTEXCLUDES; } @@ -157,9 +155,8 @@ public static String[] getDefaultExcludes() * @return the default excludes pattern as list. * @see #getDefaultExcludes() */ - public static List getDefaultExcludesAsList() - { - return Arrays.asList( getDefaultExcludes() ); + public static List getDefaultExcludesAsList() { + return Arrays.asList(getDefaultExcludes()); } /** @@ -167,9 +164,8 @@ public static List getDefaultExcludesAsList() * @see DirectoryScanner#DEFAULTEXCLUDES * @see StringUtils#join(Object[], String) */ - public static String getDefaultExcludesAsString() - { - return StringUtils.join( DirectoryScanner.DEFAULTEXCLUDES, "," ); + public static String getDefaultExcludesAsString() { + return StringUtils.join(DirectoryScanner.DEFAULTEXCLUDES, ","); } /** @@ -178,25 +174,17 @@ public static String getDefaultExcludesAsString() * @param size The number of bytes. * @return A human-readable display value (includes units). */ - public static String byteCountToDisplaySize( int size ) - { + public static String byteCountToDisplaySize(int size) { String displaySize; - if ( size / ONE_GB > 0 ) - { - displaySize = String.valueOf( size / ONE_GB ) + " GB"; - } - else if ( size / ONE_MB > 0 ) - { - displaySize = String.valueOf( size / ONE_MB ) + " MB"; - } - else if ( size / ONE_KB > 0 ) - { - displaySize = String.valueOf( size / ONE_KB ) + " KB"; - } - else - { - displaySize = String.valueOf( size ) + " bytes"; + if (size / ONE_GB > 0) { + displaySize = String.valueOf(size / ONE_GB) + " GB"; + } else if (size / ONE_MB > 0) { + displaySize = String.valueOf(size / ONE_MB) + " MB"; + } else if (size / ONE_KB > 0) { + displaySize = String.valueOf(size / ONE_KB) + " KB"; + } else { + displaySize = String.valueOf(size) + " bytes"; } return displaySize; @@ -208,10 +196,9 @@ else if ( size / ONE_KB > 0 ) * @param filename the file path * @return The directory portion excluding the ending file separator. */ - public static String dirname( String filename ) - { - int i = filename.lastIndexOf( File.separator ); - return ( i >= 0 ? filename.substring( 0, i ) : "" ); + public static String dirname(String filename) { + int i = filename.lastIndexOf(File.separator); + return (i >= 0 ? filename.substring(0, i) : ""); } /** @@ -220,10 +207,9 @@ public static String dirname( String filename ) * @param filename the file path * @return The filename string with extension. */ - public static String filename( String filename ) - { - int i = filename.lastIndexOf( File.separator ); - return ( i >= 0 ? filename.substring( i + 1 ) : filename ); + public static String filename(String filename) { + int i = filename.lastIndexOf(File.separator); + return (i >= 0 ? filename.substring(i + 1) : filename); } /** @@ -232,9 +218,8 @@ public static String filename( String filename ) * @param filename the file path * @return The filename string without extension. */ - public static String basename( String filename ) - { - return basename( filename, extension( filename ) ); + public static String basename(String filename) { + return basename(filename, extension(filename)); } /** @@ -244,21 +229,15 @@ public static String basename( String filename ) * @param suffix the file suffix * @return the basename of the file */ - public static String basename( String filename, String suffix ) - { - int i = filename.lastIndexOf( File.separator ) + 1; - int lastDot = ( ( suffix != null ) && ( suffix.length() > 0 ) ) ? filename.lastIndexOf( suffix ) : -1; + public static String basename(String filename, String suffix) { + int i = filename.lastIndexOf(File.separator) + 1; + int lastDot = ((suffix != null) && (suffix.length() > 0)) ? filename.lastIndexOf(suffix) : -1; - if ( lastDot >= 0 ) - { - return filename.substring( i, lastDot ); - } - else if ( i > 0 ) - { - return filename.substring( i ); - } - else - { + if (lastDot >= 0) { + return filename.substring(i, lastDot); + } else if (i > 0) { + return filename.substring(i); + } else { return filename; // else returns all (no path and no extension) } } @@ -270,27 +249,21 @@ else if ( i > 0 ) * @param filename the file path * @return the extension of the file */ - public static String extension( String filename ) - { + public static String extension(String filename) { // Ensure the last dot is after the last file separator - int lastSep = filename.lastIndexOf( File.separatorChar ); + int lastSep = filename.lastIndexOf(File.separatorChar); int lastDot; - if ( lastSep < 0 ) - { - lastDot = filename.lastIndexOf( '.' ); - } - else - { - lastDot = filename.substring( lastSep + 1 ).lastIndexOf( '.' ); - if ( lastDot >= 0 ) - { + if (lastSep < 0) { + lastDot = filename.lastIndexOf('.'); + } else { + lastDot = filename.substring(lastSep + 1).lastIndexOf('.'); + if (lastDot >= 0) { lastDot += lastSep + 1; } } - if ( lastDot >= 0 && lastDot > lastSep ) - { - return filename.substring( lastDot + 1 ); + if (lastDot >= 0 && lastDot > lastSep) { + return filename.substring(lastDot + 1); } return ""; @@ -302,9 +275,8 @@ public static String extension( String filename ) * @param fileName the file path. * @return true if file exists. */ - public static boolean fileExists( String fileName ) - { - File file = new File( fileName ); + public static boolean fileExists(String fileName) { + File file = new File(fileName); return file.exists(); } @@ -315,10 +287,8 @@ public static boolean fileExists( String fileName ) * @return the file content using the platform encoding. * @throws IOException if any */ - public static String fileRead( String file ) - throws IOException - { - return fileRead( file, null ); + public static String fileRead(String file) throws IOException { + return fileRead(file, null); } /** @@ -327,10 +297,8 @@ public static String fileRead( String file ) * @return the file content using the specified encoding. * @throws IOException if any */ - public static String fileRead( String file, String encoding ) - throws IOException - { - return fileRead( Paths.get( file ), encoding ); + public static String fileRead(String file, String encoding) throws IOException { + return fileRead(Paths.get(file), encoding); } /** @@ -340,10 +308,8 @@ public static String fileRead( String file, String encoding ) * @return the file content using the platform encoding. * @throws IOException if any */ - public static String fileRead( File file ) - throws IOException - { - return fileRead( file, null ); + public static String fileRead(File file) throws IOException { + return fileRead(file, null); } /** @@ -352,10 +318,8 @@ public static String fileRead( File file ) * @return the file content using the specified encoding. * @throws IOException if any */ - public static String fileRead( File file, String encoding ) - throws IOException - { - return fileRead( file.toPath(), encoding ); + public static String fileRead(File file, String encoding) throws IOException { + return fileRead(file.toPath(), encoding); } /** @@ -368,10 +332,8 @@ public static String fileRead( File file, String encoding ) * @deprecated use {@code java.nio.files.Files.write(filename, data.getBytes(encoding), * StandardOpenOption.APPEND, StandardOpenOption.CREATE)} */ - public static void fileAppend( String fileName, String data ) - throws IOException - { - fileAppend( fileName, null, data ); + public static void fileAppend(String fileName, String data) throws IOException { + fileAppend(fileName, null, data); } /** @@ -384,15 +346,12 @@ public static void fileAppend( String fileName, String data ) * @deprecated use {@code java.nio.files.Files.write(filename, data.getBytes(encoding), * StandardOpenOption.APPEND, StandardOpenOption.CREATE)} */ - public static void fileAppend( String fileName, String encoding, String data ) - throws IOException - { - fileAppend( Paths.get( fileName), encoding, data ); + public static void fileAppend(String fileName, String encoding, String data) throws IOException { + fileAppend(Paths.get(fileName), encoding, data); } - private static void fileAppend( Path path, String encoding, String data ) throws IOException - { - fileWrite( path, encoding, data, StandardOpenOption.APPEND, StandardOpenOption.CREATE ); + private static void fileAppend(Path path, String encoding, String data) throws IOException { + fileWrite(path, encoding, data, StandardOpenOption.APPEND, StandardOpenOption.CREATE); } /** @@ -403,10 +362,8 @@ private static void fileAppend( Path path, String encoding, String data ) throws * @param data The content to write to the file. * @throws IOException if any */ - public static void fileWrite( String fileName, String data ) - throws IOException - { - fileWrite( fileName, null, data ); + public static void fileWrite(String fileName, String data) throws IOException { + fileWrite(fileName, null, data); } /** @@ -417,11 +374,9 @@ public static void fileWrite( String fileName, String data ) * @param data The content to write to the file. * @throws IOException if any */ - public static void fileWrite( String fileName, String encoding, String data ) - throws IOException - { - Path file = ( fileName == null ) ? null : Paths.get( fileName ); - fileWrite( file, encoding, data ); + public static void fileWrite(String fileName, String encoding, String data) throws IOException { + Path file = (fileName == null) ? null : Paths.get(fileName); + fileWrite(file, encoding, data); } /** @@ -433,10 +388,8 @@ public static void fileWrite( String fileName, String encoding, String data ) * @throws IOException if any * @since 2.0.6 */ - public static void fileWrite( File file, String data ) - throws IOException - { - fileWrite( file, null, data ); + public static void fileWrite(File file, String data) throws IOException { + fileWrite(file, null, data); } /** @@ -448,10 +401,8 @@ public static void fileWrite( File file, String data ) * @throws IOException if any * @since 2.0.6 */ - public static void fileWrite( File file, String encoding, String data ) - throws IOException - { - fileWrite( file.toPath(), encoding, data ); + public static void fileWrite(File file, String encoding, String data) throws IOException { + fileWrite(file.toPath(), encoding, data); } /** @@ -459,16 +410,12 @@ public static void fileWrite( File file, String encoding, String data ) * * @param fileName The path of the file to delete. */ - public static void fileDelete( String fileName ) - { - File file = new File( fileName ); - try - { - NioFiles.deleteIfExists( file ); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + public static void fileDelete(String fileName) { + File file = new File(fileName); + try { + NioFiles.deleteIfExists(file); + } catch (IOException e) { + throw new RuntimeException(e); } } @@ -479,9 +426,8 @@ public static void fileDelete( String fileName ) * @param seconds The maximum time in seconds to wait. * @return True if file exists. */ - public static boolean waitFor( String fileName, int seconds ) - { - return waitFor( new File( fileName ), seconds ); + public static boolean waitFor(String fileName, int seconds) { + return waitFor(new File(fileName), seconds); } /** @@ -491,26 +437,19 @@ public static boolean waitFor( String fileName, int seconds ) * @param seconds The maximum time in seconds to wait. * @return True if file exists. */ - public static boolean waitFor( File file, int seconds ) - { + public static boolean waitFor(File file, int seconds) { int timeout = 0; int tick = 0; - while ( !file.exists() ) - { - if ( tick++ >= 10 ) - { + while (!file.exists()) { + if (tick++ >= 10) { tick = 0; - if ( timeout++ > seconds ) - { + if (timeout++ > seconds) { return false; } } - try - { - Thread.sleep( 100 ); - } - catch ( InterruptedException ignore ) - { + try { + Thread.sleep(100); + } catch (InterruptedException ignore) { // nop } } @@ -523,78 +462,67 @@ public static boolean waitFor( File file, int seconds ) * @param fileName The path of the file. * @return A File manager. */ - public static File getFile( String fileName ) - { - return new File( fileName ); + public static File getFile(String fileName) { + return new File(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"

    * * @param directory The path of the directory. * @param extensions an array of expected extensions. * @return An array of files for the wanted extensions. */ - public static String[] getFilesFromExtension( String directory, String[] extensions ) - { + public static String[] getFilesFromExtension(String directory, String[] extensions) { List files = new ArrayList(); - File currentDir = new File( directory ); + File currentDir = new File(directory); String[] unknownFiles = currentDir.list(); - if ( unknownFiles == null ) - { + if (unknownFiles == null) { return new String[0]; } - for ( String unknownFile : unknownFiles ) - { - String currentFileName = directory + System.getProperty( "file.separator" ) + unknownFile; - File currentFile = new File( currentFileName ); + for (String unknownFile : unknownFiles) { + String currentFileName = directory + System.getProperty("file.separator") + unknownFile; + File currentFile = new File(currentFileName); - if ( currentFile.isDirectory() ) - { + if (currentFile.isDirectory()) { // ignore all CVS directories... - if ( currentFile.getName().equals( "CVS" ) ) - { + if (currentFile.getName().equals("CVS")) { continue; } // ok... transverse into this directory and get all the files... then combine // them with the current list. - String[] fetchFiles = getFilesFromExtension( currentFileName, extensions ); - files = blendFilesToVector( files, fetchFiles ); - } - else - { + String[] fetchFiles = getFilesFromExtension(currentFileName, extensions); + files = blendFilesToVector(files, fetchFiles); + } else { // ok... add the file String add = currentFile.getAbsolutePath(); - if ( isValidFile( add, extensions ) ) - { - files.add( add ); + if (isValidFile(add, extensions)) { + files.add(add); } } } // ok... move the Vector into the files list... - return files.toArray( new String[0] ); + return files.toArray(new String[0]); } /** * Private helper method for getFilesFromExtension() */ - private static List blendFilesToVector( List v, String[] files ) - { - for ( String file : files ) - { - v.add( file ); + private static List blendFilesToVector(List v, String[] files) { + for (String file : files) { + v.add(file); } return v; @@ -604,27 +532,22 @@ private static List blendFilesToVector( List v, String[] files ) * Checks to see if a file is of a particular type(s). Note that if the file does not have an extension, an empty * string ("") is matched for. */ - private static boolean isValidFile( String file, String[] extensions ) - { - String extension = extension( file ); - if ( extension == null ) - { + private static boolean isValidFile(String file, String[] extensions) { + String extension = extension(file); + if (extension == null) { extension = ""; } // ok.. now that we have the "extension" go through the current know // excepted extensions and determine if this one is OK. - for ( String extension1 : extensions ) - { - if ( extension1.equals( extension ) ) - { + for (String extension1 : extensions) { + if (extension1.equals(extension)) { return true; } } return false; - } /** @@ -634,19 +557,16 @@ private static boolean isValidFile( String file, String[] extensions ) * @throws IllegalArgumentException if the dir contains illegal Windows characters under Windows OS. * @see #INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME */ - public static void mkdir( String dir ) - { - File file = new File( dir ); + public static void mkdir(String dir) { + File file = new File(dir); - if ( Os.isFamily( Os.FAMILY_WINDOWS ) && !isValidWindowsFileName( file ) ) - { - throw new IllegalArgumentException( "The file (" + dir - + ") cannot contain any of the following characters: \n" - + StringUtils.join( INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME, " " ) ); + if (Os.isFamily(Os.FAMILY_WINDOWS) && !isValidWindowsFileName(file)) { + throw new IllegalArgumentException("The file (" + dir + + ") cannot contain any of the following characters: \n" + + StringUtils.join(INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME, " ")); } - if ( !file.exists() ) - { + if (!file.exists()) { file.mkdirs(); } } @@ -659,31 +579,25 @@ public static void mkdir( String dir ) * @return true if the content of the files are equal or they both don't exist, false otherwise * @throws IOException if any */ - public static boolean contentEquals( final File file1, final File file2 ) - throws IOException - { + public static boolean contentEquals(final File file1, final File file2) throws IOException { final boolean file1Exists = file1.exists(); - if ( file1Exists != file2.exists() ) - { + if (file1Exists != file2.exists()) { return false; } - if ( !file1Exists ) - { + if (!file1Exists) { // two not existing files are equal return true; } - if ( file1.isDirectory() || file2.isDirectory() ) - { + if (file1.isDirectory() || file2.isDirectory()) { // don't want to compare directory contents return false; } - - try ( InputStream input1 = Files.newInputStream( file1.toPath() ); - InputStream input2 = Files.newInputStream( file2.toPath() ) ) - { - return IOUtil.contentEquals( input1, input2 ); + + try (InputStream input1 = Files.newInputStream(file1.toPath()); + InputStream input2 = Files.newInputStream(file2.toPath())) { + return IOUtil.contentEquals(input1, input2); } } @@ -694,25 +608,21 @@ public static boolean contentEquals( final File file1, final File file2 ) * @return The equivalent File object, or null if the URL's protocol is not * file */ - public static File toFile( final URL url ) - { - if ( url == null || !url.getProtocol().equalsIgnoreCase( "file" ) ) - { + public static File toFile(final URL url) { + if (url == null || !url.getProtocol().equalsIgnoreCase("file")) { return null; } - String filename = url.getFile().replace( '/', File.separatorChar ); + String filename = url.getFile().replace('/', File.separatorChar); int pos = -1; - while ( ( pos = filename.indexOf( '%', pos + 1 ) ) >= 0 ) - { - if ( pos + 2 < filename.length() ) - { - String hexStr = filename.substring( pos + 1, pos + 3 ); - char ch = (char) Integer.parseInt( hexStr, 16 ); - filename = filename.substring( 0, pos ) + ch + filename.substring( pos + 3 ); + while ((pos = filename.indexOf('%', pos + 1)) >= 0) { + if (pos + 2 < filename.length()) { + String hexStr = filename.substring(pos + 1, pos + 3); + char ch = (char) Integer.parseInt(hexStr, 16); + filename = filename.substring(0, pos) + ch + filename.substring(pos + 3); } } - return new File( filename ); + return new File(filename); } /** @@ -722,13 +632,10 @@ public static File toFile( final URL url ) * @return the array of URLs * @throws IOException if an error occurs */ - public static URL[] toURLs( final File[] files ) - throws IOException - { + public static URL[] toURLs(final File[] files) throws IOException { final URL[] urls = new URL[files.length]; - for ( int i = 0; i < urls.length; i++ ) - { + for (int i = 0; i < urls.length; i++) { urls[i] = files[i].toURI().toURL(); } @@ -737,7 +644,7 @@ public static URL[] toURLs( final File[] files ) /** * Remove extension from filename. ie - * + * *
          * foo.txt    --> foo
          * a\b\c.jpg  --> a\b\c
    @@ -747,22 +654,20 @@ public static URL[] toURLs( final File[] files )
          * @param filename the path of the file
          * @return the filename minus extension
          */
    -    public static String removeExtension( final String filename )
    -    {
    -        String ext = extension( filename );
    +    public static String removeExtension(final String filename) {
    +        String ext = extension(filename);
     
    -        if ( "".equals( ext ) )
    -        {
    +        if ("".equals(ext)) {
                 return filename;
             }
     
    -        final int index = filename.lastIndexOf( ext ) - 1;
    -        return filename.substring( 0, index );
    +        final int index = filename.lastIndexOf(ext) - 1;
    +        return filename.substring(0, index);
         }
     
         /**
          * Get extension from filename. ie
    -     * 
    +     *
          * 
          * foo.txt    --> "txt"
          * a\b\c.jpg  --> "jpg"
    @@ -772,14 +677,13 @@ public static String removeExtension( final String filename )
          * @param filename the path of the file
          * @return the extension of filename or "" if none
          */
    -    public static String getExtension( final String filename )
    -    {
    -        return extension( filename );
    +    public static String getExtension(final String filename) {
    +        return extension(filename);
         }
     
         /**
          * Remove path from filename. Equivalent to the unix command basename ie.
    -     * 
    +     *
          * 
          * a/b/c.txt --> c.txt
          * a.txt     --> a.txt
    @@ -788,14 +692,13 @@ public static String getExtension( final String filename )
          * @param filepath the path of the file
          * @return the filename minus path
          */
    -    public static String removePath( final String filepath )
    -    {
    -        return removePath( filepath, File.separatorChar );
    +    public static String removePath(final String filepath) {
    +        return removePath(filepath, File.separatorChar);
         }
     
         /**
          * Remove path from filename. ie.
    -     * 
    +     *
          * 
          * a/b/c.txt --> c.txt
          * a.txt     --> a.txt
    @@ -805,21 +708,19 @@ public static String removePath( final String filepath )
          * @param fileSeparatorChar the file separator character like / on Unix platforms.
          * @return the filename minus path
          */
    -    public static String removePath( final String filepath, final char fileSeparatorChar )
    -    {
    -        final int index = filepath.lastIndexOf( fileSeparatorChar );
    +    public static String removePath(final String filepath, final char fileSeparatorChar) {
    +        final int index = filepath.lastIndexOf(fileSeparatorChar);
     
    -        if ( -1 == index )
    -        {
    +        if (-1 == index) {
                 return filepath;
             }
     
    -        return filepath.substring( index + 1 );
    +        return filepath.substring(index + 1);
         }
     
         /**
          * Get path from filename. Roughly equivalent to the unix command dirname. ie.
    -     * 
    +     *
          * 
          * a/b/c.txt --> a/b
          * a.txt     --> ""
    @@ -828,14 +729,13 @@ public static String removePath( final String filepath, final char fileSeparator
          * @param filepath the filepath
          * @return the filename minus path
          */
    -    public static String getPath( final String filepath )
    -    {
    -        return getPath( filepath, File.separatorChar );
    +    public static String getPath(final String filepath) {
    +        return getPath(filepath, File.separatorChar);
         }
     
         /**
          * Get path from filename. ie.
    -     * 
    +     *
          * 
          * a/b/c.txt --> a/b
          * a.txt     --> ""
    @@ -845,15 +745,13 @@ public static String getPath( final String filepath )
          * @param fileSeparatorChar the file separator character like / on Unix platforms.
          * @return the filename minus path
          */
    -    public static String getPath( final String filepath, final char fileSeparatorChar )
    -    {
    -        final int index = filepath.lastIndexOf( fileSeparatorChar );
    -        if ( -1 == index )
    -        {
    +    public static String getPath(final String filepath, final char fileSeparatorChar) {
    +        final int index = filepath.lastIndexOf(fileSeparatorChar);
    +        if (-1 == index) {
                 return "";
             }
     
    -        return filepath.substring( 0, index );
    +        return filepath.substring(0, index);
         }
     
         /**
    @@ -868,10 +766,8 @@ public static String getPath( final String filepath, final char fileSeparatorCha
          * @throws IOException if source does not exist, the file in destinationDirectory cannot
          *             be written to, or an IO error occurs during copying.
          */
    -    public static void copyFileToDirectory( final String source, final String destinationDirectory )
    -        throws IOException
    -    {
    -        copyFileToDirectory( new File( source ), new File( destinationDirectory ) );
    +    public static void copyFileToDirectory(final String source, final String destinationDirectory) throws IOException {
    +        copyFileToDirectory(new File(source), new File(destinationDirectory));
         }
     
         /**
    @@ -886,10 +782,9 @@ public static void copyFileToDirectory( final String source, final String destin
          * @throws IOException if source does not exist, the file in destinationDirectory cannot
          *             be written to, or an IO error occurs during copying.
          */
    -    public static void copyFileToDirectoryIfModified( final String source, final String destinationDirectory )
    -        throws IOException
    -    {
    -        copyFileToDirectoryIfModified( new File( source ), new File( destinationDirectory ) );
    +    public static void copyFileToDirectoryIfModified(final String source, final String destinationDirectory)
    +            throws IOException {
    +        copyFileToDirectoryIfModified(new File(source), new File(destinationDirectory));
         }
     
         /**
    @@ -904,15 +799,12 @@ public static void copyFileToDirectoryIfModified( final String source, final Str
          * @throws IOException if source does not exist, the file in destinationDirectory cannot
          *             be written to, or an IO error occurs during copying.
          */
    -    public static void copyFileToDirectory( final File source, final File destinationDirectory )
    -        throws IOException
    -    {
    -        if ( destinationDirectory.exists() && !destinationDirectory.isDirectory() )
    -        {
    -            throw new IllegalArgumentException( "Destination is not a directory" );
    +    public static void copyFileToDirectory(final File source, final File destinationDirectory) throws IOException {
    +        if (destinationDirectory.exists() && !destinationDirectory.isDirectory()) {
    +            throw new IllegalArgumentException("Destination is not a directory");
             }
     
    -        copyFile( source, new File( destinationDirectory, source.getName() ) );
    +        copyFile(source, new File(destinationDirectory, source.getName()));
         }
     
         /**
    @@ -927,39 +819,31 @@ public static void copyFileToDirectory( final File source, final File destinatio
          * @throws IOException if source does not exist, the file in destinationDirectory cannot
          *             be written to, or an IO error occurs during copying.
          */
    -    public static void copyFileToDirectoryIfModified( final File source, final File destinationDirectory )
    -        throws IOException
    -    {
    -        if ( destinationDirectory.exists() && !destinationDirectory.isDirectory() )
    -        {
    -            throw new IllegalArgumentException( "Destination is not a directory" );
    +    public static void copyFileToDirectoryIfModified(final File source, final File destinationDirectory)
    +            throws IOException {
    +        if (destinationDirectory.exists() && !destinationDirectory.isDirectory()) {
    +            throw new IllegalArgumentException("Destination is not a directory");
             }
     
    -        copyFileIfModified( source, new File( destinationDirectory, source.getName() ) );
    +        copyFileIfModified(source, new File(destinationDirectory, source.getName()));
         }
     
         /**
          * Creates a number of directories, as delivered from DirectoryScanner
    -     * 
    +     *
          * @param sourceBase The basedir used for the directory scan
          * @param dirs The getIncludedDirs from the dirscanner
          * @param destination The base dir of the output structure
          * @throws IOException io issue
          */
    -    public static void mkDirs( final File sourceBase, String[] dirs, final File destination )
    -        throws IOException
    -    {
    -        for ( String dir : dirs )
    -        {
    -            File src = new File( sourceBase, dir );
    -            File dst = new File( destination, dir );
    -            if ( NioFiles.isSymbolicLink( src ) )
    -            {
    -                File target = NioFiles.readSymbolicLink( src );
    -                NioFiles.createSymbolicLink( dst, target );
    -            }
    -            else
    -            {
    +    public static void mkDirs(final File sourceBase, String[] dirs, final File destination) throws IOException {
    +        for (String dir : dirs) {
    +            File src = new File(sourceBase, dir);
    +            File dst = new File(destination, dir);
    +            if (NioFiles.isSymbolicLink(src)) {
    +                File target = NioFiles.readSymbolicLink(src);
    +                NioFiles.createSymbolicLink(dst, target);
    +            } else {
                     dst.mkdirs();
                 }
             }
    @@ -976,43 +860,34 @@ public static void mkDirs( final File sourceBase, String[] dirs, final File dest
          * @throws java.io.FileNotFoundException if destination is a directory (use
          *             {@link #copyFileToDirectory}).
          */
    -    public static void copyFile( final File source, final File destination )
    -        throws IOException
    -    {
    +    public static void copyFile(final File source, final File destination) throws IOException {
             // check source exists
    -        if ( !source.exists() )
    -        {
    +        if (!source.exists()) {
                 final String message = "File " + source + " does not exist";
    -            throw new IOException( message );
    +            throw new IOException(message);
             }
     
             // check source != destination, see PLXUTILS-10
    -        if ( source.getCanonicalPath().equals( destination.getCanonicalPath() ) )
    -        {
    +        if (source.getCanonicalPath().equals(destination.getCanonicalPath())) {
                 // if they are equal, we can exit the method without doing any work
                 return;
             }
    -        mkdirsFor( destination );
    +        mkdirsFor(destination);
     
    -        doCopyFile( source, destination );
    +        doCopyFile(source, destination);
     
    -        if ( source.length() != destination.length() )
    -        {
    +        if (source.length() != destination.length()) {
                 String message = "Failed to copy full contents from " + source + " to " + destination;
    -            throw new IOException( message );
    +            throw new IOException(message);
             }
         }
     
    -    private static void doCopyFile( File source, File destination )
    -        throws IOException
    -    {
    -        doCopyFileUsingNewIO( source, destination );
    +    private static void doCopyFile(File source, File destination) throws IOException {
    +        doCopyFileUsingNewIO(source, destination);
         }
     
    -    private static void doCopyFileUsingNewIO( File source, File destination )
    -        throws IOException
    -    {
    -        NioFiles.copy( source, destination );
    +    private static void doCopyFileUsingNewIO(File source, File destination) throws IOException {
    +        NioFiles.copy(source, destination);
         }
     
         /**
    @@ -1026,25 +901,21 @@ private static void doCopyFileUsingNewIO( File source, File destination )
          * @throws java.io.FileNotFoundException if destination is a directory (use
          *             {@link #copyFileToDirectory}).
          */
    -    public static void linkFile( final File source, final File destination )
    -        throws IOException
    -    {
    +    public static void linkFile(final File source, final File destination) throws IOException {
             // check source exists
    -        if ( !source.exists() )
    -        {
    +        if (!source.exists()) {
                 final String message = "File " + source + " does not exist";
    -            throw new IOException( message );
    +            throw new IOException(message);
             }
     
             // check source != destination, see PLXUTILS-10
    -        if ( source.getCanonicalPath().equals( destination.getCanonicalPath() ) )
    -        {
    +        if (source.getCanonicalPath().equals(destination.getCanonicalPath())) {
                 // if they are equal, we can exit the method without doing any work
                 return;
             }
    -        mkdirsFor( destination );
    +        mkdirsFor(destination);
     
    -        NioFiles.createSymbolicLink( destination, source );
    +        NioFiles.createSymbolicLink(destination, source);
         }
     
         /**
    @@ -1058,12 +929,9 @@ public static void linkFile( final File source, final File destination )
          * @throws IOException if source does not exist, destination cannot be written to, or an
          *             IO error occurs during copying.
          */
    -    public static boolean copyFileIfModified( final File source, final File destination )
    -        throws IOException
    -    {
    -        if ( isSourceNewerThanDestination( source, destination ) )
    -        {
    -            copyFile( source, destination );
    +    public static boolean copyFileIfModified(final File source, final File destination) throws IOException {
    +        if (isSourceNewerThanDestination(source, destination)) {
    +            copyFile(source, destination);
     
                 return true;
             }
    @@ -1085,10 +953,8 @@ public static boolean copyFileIfModified( final File source, final File destinat
          *             
  • an IO error occurs during copying
  • *
*/ - public static void copyURLToFile( final URL source, final File destination ) - throws IOException - { - copyStreamToFile( new URLInputStreamFacade( source ), destination ); + public static void copyURLToFile(final URL source, final File destination) throws IOException { + copyStreamToFile(new URLInputStreamFacade(source), destination); } /** @@ -1105,36 +971,28 @@ public static void copyURLToFile( final URL source, final File destination ) *
  • an IO error occurs during copying
  • * */ - public static void copyStreamToFile( final InputStreamFacade source, final File destination ) - throws IOException - { - mkdirsFor( destination ); - checkCanWrite( destination ); + public static void copyStreamToFile(final InputStreamFacade source, final File destination) throws IOException { + mkdirsFor(destination); + checkCanWrite(destination); - try ( InputStream input = source.getInputStream(); - OutputStream output = Files.newOutputStream( destination.toPath() ) ) - { - IOUtil.copy( input, output ); + try (InputStream input = source.getInputStream(); + OutputStream output = Files.newOutputStream(destination.toPath())) { + IOUtil.copy(input, output); } } - private static void checkCanWrite( File destination ) - throws IOException - { + private static void checkCanWrite(File destination) throws IOException { // make sure we can write to destination - if ( destination.exists() && !destination.canWrite() ) - { + if (destination.exists() && !destination.canWrite()) { final String message = "Unable to open file " + destination + " for writing."; - throw new IOException( message ); + throw new IOException(message); } } - private static void mkdirsFor( File destination ) - { + private static void mkdirsFor(File destination) { // does destination directory exist ? File parentFile = destination.getParentFile(); - if ( parentFile != null && !parentFile.exists() ) - { + if (parentFile != null && !parentFile.exists()) { parentFile.mkdirs(); } } @@ -1142,7 +1000,7 @@ private static void mkdirsFor( File destination ) /** * Normalize a path. Eliminates "/../" and "/./" in a string. Returns null if the ..'s went past the * root. Eg: - * + * *
          * /foo//               -->     /foo/
          * /foo/./              -->     /foo/
    @@ -1156,45 +1014,37 @@ private static void mkdirsFor( File destination )
          * @param path the path to normalize
          * @return the normalized String, or null if too many ..'s.
          */
    -    public static String normalize( final String path )
    -    {
    +    public static String normalize(final String path) {
             String normalized = path;
             // Resolve occurrences of "//" in the normalized path
    -        while ( true )
    -        {
    -            int index = normalized.indexOf( "//" );
    -            if ( index < 0 )
    -            {
    +        while (true) {
    +            int index = normalized.indexOf("//");
    +            if (index < 0) {
                     break;
                 }
    -            normalized = normalized.substring( 0, index ) + normalized.substring( index + 1 );
    +            normalized = normalized.substring(0, index) + normalized.substring(index + 1);
             }
     
             // Resolve occurrences of "/./" in the normalized path
    -        while ( true )
    -        {
    -            int index = normalized.indexOf( "/./" );
    -            if ( index < 0 )
    -            {
    +        while (true) {
    +            int index = normalized.indexOf("/./");
    +            if (index < 0) {
                     break;
                 }
    -            normalized = normalized.substring( 0, index ) + normalized.substring( index + 2 );
    +            normalized = normalized.substring(0, index) + normalized.substring(index + 2);
             }
     
             // Resolve occurrences of "/../" in the normalized path
    -        while ( true )
    -        {
    -            int index = normalized.indexOf( "/../" );
    -            if ( index < 0 )
    -            {
    +        while (true) {
    +            int index = normalized.indexOf("/../");
    +            if (index < 0) {
                     break;
                 }
    -            if ( index == 0 )
    -            {
    +            if (index == 0) {
                     return null; // Trying to go outside our context
                 }
    -            int index2 = normalized.lastIndexOf( '/', index - 1 );
    -            normalized = normalized.substring( 0, index2 ) + normalized.substring( index + 3 );
    +            int index2 = normalized.lastIndexOf('/', index - 1);
    +            normalized = normalized.substring(0, index2) + normalized.substring(index + 3);
             }
     
             // Return the normalized path that we have completed
    @@ -1203,45 +1053,40 @@ 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...

    * * @param lookupPath a path * @param path the path to concatenate * @return The concatenated paths, or null if error occurs */ - public static String catPath( final String lookupPath, final String path ) - { + public static String catPath(final String lookupPath, final String path) { // Cut off the last slash and everything beyond - int index = lookupPath.lastIndexOf( "/" ); - String lookup = lookupPath.substring( 0, index ); + int index = lookupPath.lastIndexOf("/"); + String lookup = lookupPath.substring(0, index); String pth = path; // Deal with .. by chopping dirs off the lookup path - while ( pth.startsWith( "../" ) ) - { - if ( lookup.length() > 0 ) - { - index = lookup.lastIndexOf( "/" ); - lookup = lookup.substring( 0, index ); - } - else - { + while (pth.startsWith("../")) { + if (lookup.length() > 0) { + index = lookup.lastIndexOf("/"); + lookup = lookup.substring(0, index); + } else { // More ..'s than dirs, return null return null; } - index = pth.indexOf( "../" ) + 3; - pth = pth.substring( index ); + index = pth.indexOf("../") + 3; + pth = pth.substring(index); } - return new StringBuffer( lookup ).append( "/" ).append( pth ).toString(); + return new StringBuffer(lookup).append("/").append(pth).toString(); } /** @@ -1253,30 +1098,23 @@ public static String catPath( final String lookupPath, final String path ) * @param filename Absolute or relative file path to resolve. * @return The canonical File of filename. */ - public static File resolveFile( final File baseFile, String filename ) - { + public static File resolveFile(final File baseFile, String filename) { String filenm = filename; - if ( '/' != File.separatorChar ) - { - filenm = filename.replace( '/', File.separatorChar ); + if ('/' != File.separatorChar) { + filenm = filename.replace('/', File.separatorChar); } - if ( '\\' != File.separatorChar ) - { - filenm = filename.replace( '\\', File.separatorChar ); + if ('\\' != File.separatorChar) { + filenm = filename.replace('\\', File.separatorChar); } // deal with absolute files - if ( filenm.startsWith( File.separator ) || ( Os.isFamily( Os.FAMILY_WINDOWS ) && filenm.indexOf( ":" ) > 0 ) ) - { - File file = new File( filenm ); + if (filenm.startsWith(File.separator) || (Os.isFamily(Os.FAMILY_WINDOWS) && filenm.indexOf(":") > 0)) { + File file = new File(filenm); - try - { + try { file = file.getCanonicalFile(); - } - catch ( final IOException ioe ) - { + } catch (final IOException ioe) { // nop } @@ -1291,33 +1129,27 @@ public static File resolveFile( final File baseFile, String filename ) // on win32 at start of filename as UNC filenames can // be \\AComputer\AShare\myfile.txt int start = 0; - if ( '\\' == File.separatorChar ) - { - sb.append( filenm.charAt( 0 ) ); + if ('\\' == File.separatorChar) { + sb.append(filenm.charAt(0)); start++; } - for ( int i = start; i < chars.length; i++ ) - { + for (int i = start; i < chars.length; i++) { final boolean doubleSeparator = File.separatorChar == chars[i] && File.separatorChar == chars[i - 1]; - if ( !doubleSeparator ) - { - sb.append( chars[i] ); + if (!doubleSeparator) { + sb.append(chars[i]); } } filenm = sb.toString(); // must be relative - File file = ( new File( baseFile, filenm ) ).getAbsoluteFile(); + File file = (new File(baseFile, filenm)).getAbsoluteFile(); - try - { + try { file = file.getCanonicalFile(); - } - catch ( final IOException ioe ) - { + } catch (final IOException ioe) { // nop } @@ -1330,10 +1162,8 @@ public static File resolveFile( final File baseFile, String filename ) * @param file the file path * @throws IOException if any */ - public static void forceDelete( final String file ) - throws IOException - { - forceDelete( new File( file ) ); + public static void forceDelete(final String file) throws IOException { + forceDelete(new File(file)); } /** @@ -1342,24 +1172,18 @@ public static void forceDelete( final String file ) * @param file a file * @throws IOException if any */ - public static void forceDelete( final File file ) - throws IOException - { - if ( file.isDirectory() ) - { - deleteDirectory( file ); - } - else - { + public static void forceDelete(final File file) throws IOException { + if (file.isDirectory()) { + deleteDirectory(file); + } else { /* * NOTE: Always try to delete the file even if it appears to be non-existent. This will ensure that a * symlink whose target does not exist is deleted, too. */ boolean filePresent = file.getCanonicalFile().exists(); - if ( !deleteFile( file ) && filePresent ) - { + if (!deleteFile(file) && filePresent) { final String message = "File " + file + " unable to be deleted."; - throw new IOException( message ); + throw new IOException(message); } } } @@ -1371,29 +1195,21 @@ public static void forceDelete( final File file ) * @param file a file * @throws IOException if any */ - private static boolean deleteFile( File file ) - throws IOException - { - if ( file.isDirectory() ) - { - throw new IOException( "File " + file + " isn't a file." ); + private static boolean deleteFile(File file) throws IOException { + if (file.isDirectory()) { + throw new IOException("File " + file + " isn't a file."); } - if ( !file.delete() ) - { - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { + if (!file.delete()) { + if (Os.isFamily(Os.FAMILY_WINDOWS)) { file = file.getCanonicalFile(); System.gc(); } - try - { - Thread.sleep( 10 ); + try { + Thread.sleep(10); return file.delete(); - } - catch ( InterruptedException ignore ) - { + } catch (InterruptedException ignore) { return file.delete(); } } @@ -1407,20 +1223,14 @@ private static boolean deleteFile( File file ) * @param file a file * @throws IOException if any */ - public static void forceDeleteOnExit( final File file ) - throws IOException - { - if ( !file.exists() ) - { + public static void forceDeleteOnExit(final File file) throws IOException { + if (!file.exists()) { return; } - if ( file.isDirectory() ) - { - deleteDirectoryOnExit( file ); - } - else - { + if (file.isDirectory()) { + deleteDirectoryOnExit(file); + } else { file.deleteOnExit(); } } @@ -1431,16 +1241,13 @@ public static void forceDeleteOnExit( final File file ) * @param directory a directory * @throws IOException if any */ - private static void deleteDirectoryOnExit( final File directory ) - throws IOException - { - if ( !directory.exists() ) - { + private static void deleteDirectoryOnExit(final File directory) throws IOException { + if (!directory.exists()) { return; } directory.deleteOnExit(); // The hook reverses the list - cleanDirectoryOnExit( directory ); + cleanDirectoryOnExit(directory); } /** @@ -1449,38 +1256,29 @@ private static void deleteDirectoryOnExit( final File directory ) * @param directory a directory * @throws IOException if any */ - private static void cleanDirectoryOnExit( final File directory ) - throws IOException - { - if ( !directory.exists() ) - { + private static void cleanDirectoryOnExit(final File directory) throws IOException { + if (!directory.exists()) { final String message = directory + " does not exist"; - throw new IllegalArgumentException( message ); + throw new IllegalArgumentException(message); } - if ( !directory.isDirectory() ) - { + if (!directory.isDirectory()) { final String message = directory + " is not a directory"; - throw new IllegalArgumentException( message ); + throw new IllegalArgumentException(message); } IOException exception = null; final File[] files = directory.listFiles(); - for ( final File file : files ) - { - try - { - forceDeleteOnExit( file ); - } - catch ( final IOException ioe ) - { + for (final File file : files) { + try { + forceDeleteOnExit(file); + } catch (final IOException ioe) { exception = ioe; } } - if ( null != exception ) - { + if (null != exception) { throw exception; } } @@ -1493,34 +1291,25 @@ private static void cleanDirectoryOnExit( final File directory ) * @throws IllegalArgumentException if the file contains illegal Windows characters under Windows OS. * @see #INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME */ - public static void forceMkdir( final File file ) - throws IOException - { - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - if ( !isValidWindowsFileName( file ) ) - { - throw new IllegalArgumentException( "The file (" + file.getAbsolutePath() - + ") cannot contain any of the following characters: \n" - + StringUtils.join( INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME, " " ) ); + public static void forceMkdir(final File file) throws IOException { + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + if (!isValidWindowsFileName(file)) { + throw new IllegalArgumentException("The file (" + file.getAbsolutePath() + + ") cannot contain any of the following characters: \n" + + StringUtils.join(INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME, " ")); } } - if ( file.exists() ) - { - if ( file.isFile() ) - { + if (file.exists()) { + if (file.isFile()) { final String message = - "File " + file + " exists and is " + "not a directory. Unable to create directory."; - throw new IOException( message ); + "File " + file + " exists and is " + "not a directory. Unable to create directory."; + throw new IOException(message); } - } - else - { - if ( false == file.mkdirs() ) - { + } else { + if (false == file.mkdirs()) { final String message = "Unable to create directory " + file; - throw new IOException( message ); + throw new IOException(message); } } } @@ -1531,10 +1320,8 @@ public static void forceMkdir( final File file ) * @param directory a directory * @throws IOException if any */ - public static void deleteDirectory( final String directory ) - throws IOException - { - deleteDirectory( new File( directory ) ); + public static void deleteDirectory(final String directory) throws IOException { + deleteDirectory(new File(directory)); } /** @@ -1543,11 +1330,8 @@ public static void deleteDirectory( final String directory ) * @param directory a directory * @throws IOException if any */ - public static void deleteDirectory( final File directory ) - throws IOException - { - if ( !directory.exists() ) - { + public static void deleteDirectory(final File directory) throws IOException { + if (!directory.exists()) { return; } @@ -1555,16 +1339,14 @@ public static void deleteDirectory( final File directory ) * try delete the directory before its contents, which will take care of any directories that are really * symbolic links. */ - if ( directory.delete() ) - { + if (directory.delete()) { return; } - cleanDirectory( directory ); - if ( !directory.delete() ) - { + cleanDirectory(directory); + if (!directory.delete()) { final String message = "Directory " + directory + " unable to be deleted."; - throw new IOException( message ); + throw new IOException(message); } } @@ -1574,10 +1356,8 @@ public static void deleteDirectory( final File directory ) * @param directory a directory * @throws IOException if any */ - public static void cleanDirectory( final String directory ) - throws IOException - { - cleanDirectory( new File( directory ) ); + public static void cleanDirectory(final String directory) throws IOException { + cleanDirectory(new File(directory)); } /** @@ -1586,44 +1366,34 @@ public static void cleanDirectory( final String directory ) * @param directory a directory * @throws IOException if any */ - public static void cleanDirectory( final File directory ) - throws IOException - { - if ( !directory.exists() ) - { + public static void cleanDirectory(final File directory) throws IOException { + if (!directory.exists()) { final String message = directory + " does not exist"; - throw new IllegalArgumentException( message ); + throw new IllegalArgumentException(message); } - if ( !directory.isDirectory() ) - { + if (!directory.isDirectory()) { final String message = directory + " is not a directory"; - throw new IllegalArgumentException( message ); + throw new IllegalArgumentException(message); } IOException exception = null; final File[] files = directory.listFiles(); - if ( files == null ) - { + if (files == null) { return; } - for ( final File file : files ) - { - try - { - forceDelete( file ); - } - catch ( final IOException ioe ) - { + for (final File file : files) { + try { + forceDelete(file); + } catch (final IOException ioe) { exception = ioe; } } - if ( null != exception ) - { + if (null != exception) { throw exception; } } @@ -1634,9 +1404,8 @@ public static void cleanDirectory( final File directory ) * @param directory a directory * @return size of directory in bytes. */ - public static long sizeOfDirectory( final String directory ) - { - return sizeOfDirectory( new File( directory ) ); + public static long sizeOfDirectory(final String directory) { + return sizeOfDirectory(new File(directory)); } /** @@ -1645,31 +1414,24 @@ public static long sizeOfDirectory( final String directory ) * @param directory a directory * @return size of directory in bytes. */ - public static long sizeOfDirectory( final File directory ) - { - if ( !directory.exists() ) - { + public static long sizeOfDirectory(final File directory) { + if (!directory.exists()) { final String message = directory + " does not exist"; - throw new IllegalArgumentException( message ); + throw new IllegalArgumentException(message); } - if ( !directory.isDirectory() ) - { + if (!directory.isDirectory()) { final String message = directory + " is not a directory"; - throw new IllegalArgumentException( message ); + throw new IllegalArgumentException(message); } long size = 0; final File[] files = directory.listFiles(); - for ( final File file : files ) - { - if ( file.isDirectory() ) - { - size += sizeOfDirectory( file ); - } - else - { + for (final File file : files) { + if (file.isDirectory()) { + size += sizeOfDirectory(file); + } else { size += file.length(); } } @@ -1688,10 +1450,8 @@ public static long sizeOfDirectory( final File directory ) * @throws IOException io issue * @see #getFileNames(File, String, String, boolean) */ - public static List getFiles( File directory, String includes, String excludes ) - throws IOException - { - return getFiles( directory, includes, excludes, true ); + public static List getFiles(File directory, String includes, String excludes) throws IOException { + return getFiles(directory, includes, excludes, true); } /** @@ -1705,16 +1465,14 @@ public static List getFiles( File directory, String includes, String exclu * @throws IOException io issue * @see #getFileNames(File, String, String, boolean) */ - public static List getFiles( File directory, String includes, String excludes, boolean includeBasedir ) - throws IOException - { - List fileNames = getFileNames( directory, includes, excludes, includeBasedir ); + public static List getFiles(File directory, String includes, String excludes, boolean includeBasedir) + throws IOException { + List fileNames = getFileNames(directory, includes, excludes, includeBasedir); List files = new ArrayList(); - for ( String filename : fileNames ) - { - files.add( new File( filename ) ); + for (String filename : fileNames) { + files.add(new File(filename)); } return files; @@ -1730,10 +1488,9 @@ public static List getFiles( File directory, String includes, String exclu * @return a list of files as String * @throws IOException io issue */ - public static List getFileNames( File directory, String includes, String excludes, boolean includeBasedir ) - throws IOException - { - return getFileNames( directory, includes, excludes, includeBasedir, true ); + public static List getFileNames(File directory, String includes, String excludes, boolean includeBasedir) + throws IOException { + return getFileNames(directory, includes, excludes, includeBasedir, true); } /** @@ -1747,11 +1504,10 @@ public static List getFileNames( File directory, String includes, String * @return a list of files as String * @throws IOException io issue */ - public static List getFileNames( File directory, String includes, String excludes, boolean includeBasedir, - boolean isCaseSensitive ) - throws IOException - { - return getFileAndDirectoryNames( directory, includes, excludes, includeBasedir, isCaseSensitive, true, false ); + public static List getFileNames( + File directory, String includes, String excludes, boolean includeBasedir, boolean isCaseSensitive) + throws IOException { + return getFileAndDirectoryNames(directory, includes, excludes, includeBasedir, isCaseSensitive, true, false); } /** @@ -1764,11 +1520,9 @@ public static List getFileNames( File directory, String includes, String * @return a list of directories as String * @throws IOException io issue */ - public static List getDirectoryNames( File directory, String includes, String excludes, - boolean includeBasedir ) - throws IOException - { - return getDirectoryNames( directory, includes, excludes, includeBasedir, true ); + public static List getDirectoryNames( + File directory, String includes, String excludes, boolean includeBasedir) throws IOException { + return getDirectoryNames(directory, includes, excludes, includeBasedir, true); } /** @@ -1782,11 +1536,10 @@ public static List getDirectoryNames( File directory, String includes, S * @return a list of directories as String * @throws IOException io issue */ - public static List getDirectoryNames( File directory, String includes, String excludes, - boolean includeBasedir, boolean isCaseSensitive ) - throws IOException - { - return getFileAndDirectoryNames( directory, includes, excludes, includeBasedir, isCaseSensitive, false, true ); + public static List getDirectoryNames( + File directory, String includes, String excludes, boolean includeBasedir, boolean isCaseSensitive) + throws IOException { + return getFileAndDirectoryNames(directory, includes, excludes, includeBasedir, isCaseSensitive, false, true); } /** @@ -1802,61 +1555,53 @@ public static List getDirectoryNames( File directory, String includes, S * @return a list of files as String * @throws IOException io issue */ - public static List getFileAndDirectoryNames( File directory, String includes, String excludes, - boolean includeBasedir, boolean isCaseSensitive, - boolean getFiles, boolean getDirectories ) - throws IOException - { + public static List getFileAndDirectoryNames( + File directory, + String includes, + String excludes, + boolean includeBasedir, + boolean isCaseSensitive, + boolean getFiles, + boolean getDirectories) + throws IOException { DirectoryScanner scanner = new DirectoryScanner(); - scanner.setBasedir( directory ); + scanner.setBasedir(directory); - if ( includes != null ) - { - scanner.setIncludes( StringUtils.split( includes, "," ) ); + if (includes != null) { + scanner.setIncludes(StringUtils.split(includes, ",")); } - if ( excludes != null ) - { - scanner.setExcludes( StringUtils.split( excludes, "," ) ); + if (excludes != null) { + scanner.setExcludes(StringUtils.split(excludes, ",")); } - scanner.setCaseSensitive( isCaseSensitive ); + scanner.setCaseSensitive(isCaseSensitive); scanner.scan(); List list = new ArrayList(); - if ( getFiles ) - { + if (getFiles) { String[] files = scanner.getIncludedFiles(); - for ( String file : files ) - { - if ( includeBasedir ) - { - list.add( directory + FileUtils.FS + file ); - } - else - { - list.add( file ); + for (String file : files) { + if (includeBasedir) { + list.add(directory + FileUtils.FS + file); + } else { + list.add(file); } } } - if ( getDirectories ) - { + if (getDirectories) { String[] directories = scanner.getIncludedDirectories(); - for ( String directory1 : directories ) - { - if ( includeBasedir ) - { - list.add( directory + FileUtils.FS + directory1 ); - } - else - { - list.add( directory1 ); + for (String directory1 : directories) { + if (includeBasedir) { + list.add(directory + FileUtils.FS + directory1); + } else { + list.add(directory1); } } } @@ -1871,10 +1616,8 @@ public static List getFileAndDirectoryNames( File directory, String incl * @param destinationDirectory the target dir * @throws IOException if any */ - public static void copyDirectory( File sourceDirectory, File destinationDirectory ) - throws IOException - { - copyDirectory( sourceDirectory, destinationDirectory, "**", null ); + public static void copyDirectory(File sourceDirectory, File destinationDirectory) throws IOException { + copyDirectory(sourceDirectory, destinationDirectory, "**", null); } /** @@ -1887,26 +1630,22 @@ public static void copyDirectory( File sourceDirectory, File destinationDirector * @throws IOException if any * @see #getFiles(File, String, String) */ - public static void copyDirectory( File sourceDirectory, File destinationDirectory, String includes, - String excludes ) - throws IOException - { - if ( !sourceDirectory.exists() ) - { + public static void copyDirectory(File sourceDirectory, File destinationDirectory, String includes, String excludes) + throws IOException { + if (!sourceDirectory.exists()) { return; } - List files = getFiles( sourceDirectory, includes, excludes ); + List files = getFiles(sourceDirectory, includes, excludes); - for ( File file : files ) - { - copyFileToDirectory( file, destinationDirectory ); + for (File file : files) { + copyFileToDirectory(file, destinationDirectory); } } /** *

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

    - * + * * Note: *
      *
    • It will include empty directories. @@ -1920,69 +1659,57 @@ public static void copyDirectory( File sourceDirectory, File destinationDirector * @throws IOException if any * @since 1.5.7 */ - public static void copyDirectoryLayout( File sourceDirectory, File destinationDirectory, String[] includes, - String[] excludes ) - throws IOException - { - if ( sourceDirectory == null ) - { - throw new IOException( "source directory can't be null." ); + public static void copyDirectoryLayout( + File sourceDirectory, File destinationDirectory, String[] includes, String[] excludes) throws IOException { + if (sourceDirectory == null) { + throw new IOException("source directory can't be null."); } - if ( destinationDirectory == null ) - { - throw new IOException( "destination directory can't be null." ); + if (destinationDirectory == null) { + throw new IOException("destination directory can't be null."); } - if ( sourceDirectory.equals( destinationDirectory ) ) - { - throw new IOException( "source and destination are the same directory." ); + if (sourceDirectory.equals(destinationDirectory)) { + throw new IOException("source and destination are the same directory."); } - if ( !sourceDirectory.exists() ) - { - throw new IOException( "Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")." ); + if (!sourceDirectory.exists()) { + throw new IOException("Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")."); } DirectoryScanner scanner = new DirectoryScanner(); - scanner.setBasedir( sourceDirectory ); + scanner.setBasedir(sourceDirectory); - if ( includes != null && includes.length >= 1 ) - { - scanner.setIncludes( includes ); - } - else - { - scanner.setIncludes( new String[] { "**" } ); + if (includes != null && includes.length >= 1) { + scanner.setIncludes(includes); + } else { + scanner.setIncludes(new String[] {"**"}); } - if ( excludes != null && excludes.length >= 1 ) - { - scanner.setExcludes( excludes ); + if (excludes != null && excludes.length >= 1) { + scanner.setExcludes(excludes); } scanner.addDefaultExcludes(); scanner.scan(); - List includedDirectories = Arrays.asList( scanner.getIncludedDirectories() ); + List includedDirectories = Arrays.asList(scanner.getIncludedDirectories()); - for ( String name : includedDirectories ) - { - File source = new File( sourceDirectory, name ); + for (String name : includedDirectories) { + File source = new File(sourceDirectory, name); - if ( source.equals( sourceDirectory ) ) - { + if (source.equals(sourceDirectory)) { continue; } - File destination = new File( destinationDirectory, name ); + File destination = new File(destinationDirectory, name); destination.mkdirs(); } } /** *

      Copies a entire directory structure.

      - * + * * Note: *
        *
      • It will include empty directories. @@ -1993,15 +1720,13 @@ public static void copyDirectoryLayout( File sourceDirectory, File destinationDi * @param destinationDirectory the target dir * @throws IOException if any */ - public static void copyDirectoryStructure( File sourceDirectory, File destinationDirectory ) - throws IOException - { - copyDirectoryStructure( sourceDirectory, destinationDirectory, destinationDirectory, false ); + public static void copyDirectoryStructure(File sourceDirectory, File destinationDirectory) throws IOException { + copyDirectoryStructure(sourceDirectory, destinationDirectory, destinationDirectory, false); } /** *

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

        - * + * * Note: *
          *
        • It will include empty directories. @@ -2012,87 +1737,70 @@ public static void copyDirectoryStructure( File sourceDirectory, File destinatio * @param destinationDirectory the target dir * @throws IOException if any */ - public static void copyDirectoryStructureIfModified( File sourceDirectory, File destinationDirectory ) - throws IOException - { - copyDirectoryStructure( sourceDirectory, destinationDirectory, destinationDirectory, true ); + public static void copyDirectoryStructureIfModified(File sourceDirectory, File destinationDirectory) + throws IOException { + copyDirectoryStructure(sourceDirectory, destinationDirectory, destinationDirectory, true); } - private static void copyDirectoryStructure( File sourceDirectory, File destinationDirectory, - File rootDestinationDirectory, boolean onlyModifiedFiles ) - throws IOException - { - if ( sourceDirectory == null ) - { - throw new IOException( "source directory can't be null." ); + private static void copyDirectoryStructure( + File sourceDirectory, File destinationDirectory, File rootDestinationDirectory, boolean onlyModifiedFiles) + throws IOException { + if (sourceDirectory == null) { + throw new IOException("source directory can't be null."); } - if ( destinationDirectory == null ) - { - throw new IOException( "destination directory can't be null." ); + if (destinationDirectory == null) { + throw new IOException("destination directory can't be null."); } - if ( sourceDirectory.equals( destinationDirectory ) ) - { - throw new IOException( "source and destination are the same directory." ); + if (sourceDirectory.equals(destinationDirectory)) { + throw new IOException("source and destination are the same directory."); } - if ( !sourceDirectory.exists() ) - { - throw new IOException( "Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")." ); + if (!sourceDirectory.exists()) { + throw new IOException("Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")."); } File[] files = sourceDirectory.listFiles(); String sourcePath = sourceDirectory.getAbsolutePath(); - for ( File file : files ) - { - if ( file.equals( rootDestinationDirectory ) ) - { + for (File file : files) { + if (file.equals(rootDestinationDirectory)) { // We don't copy the destination directory in itself continue; } String dest = file.getAbsolutePath(); - dest = dest.substring( sourcePath.length() + 1 ); + dest = dest.substring(sourcePath.length() + 1); - File destination = new File( destinationDirectory, dest ); + File destination = new File(destinationDirectory, dest); - if ( file.isFile() ) - { + if (file.isFile()) { destination = destination.getParentFile(); - if ( onlyModifiedFiles ) - { - copyFileToDirectoryIfModified( file, destination ); + if (onlyModifiedFiles) { + copyFileToDirectoryIfModified(file, destination); + } else { + copyFileToDirectory(file, destination); } - else - { - copyFileToDirectory( file, destination ); - } - } - else if ( file.isDirectory() ) - { - if ( !destination.exists() && !destination.mkdirs() ) - { - throw new IOException( "Could not create destination directory '" + destination.getAbsolutePath() - + "'." ); + } else if (file.isDirectory()) { + if (!destination.exists() && !destination.mkdirs()) { + throw new IOException( + "Could not create destination directory '" + destination.getAbsolutePath() + "'."); } - copyDirectoryStructure( file, destination, rootDestinationDirectory, onlyModifiedFiles ); - } - else - { - throw new IOException( "Unknown file type: " + file.getAbsolutePath() ); + copyDirectoryStructure(file, destination, rootDestinationDirectory, onlyModifiedFiles); + } else { + throw new IOException("Unknown file type: " + file.getAbsolutePath()); } } } /** *

          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.

          * @@ -2101,41 +1809,35 @@ else if ( file.isDirectory() ) * @throws IOException if anything bad happens during this process. Note that to may have been deleted * already when this happens. */ - public static void rename( File from, File to ) - throws IOException - { - if ( to.exists() && !to.delete() ) - { - throw new IOException( "Failed to delete " + to + " while trying to rename " + from ); + public static void rename(File from, File to) throws IOException { + if (to.exists() && !to.delete()) { + throw new IOException("Failed to delete " + to + " while trying to rename " + from); } File parent = to.getParentFile(); - if ( parent != null && !parent.exists() && !parent.mkdirs() ) - { - throw new IOException( "Failed to create directory " + parent + " while trying to rename " + from ); + if (parent != null && !parent.exists() && !parent.mkdirs()) { + throw new IOException("Failed to create directory " + parent + " while trying to rename " + from); } - if ( !from.renameTo( to ) ) - { - copyFile( from, to ); - if ( !from.delete() ) - { - throw new IOException( "Failed to delete " + from + " while trying to rename it." ); + if (!from.renameTo(to)) { + copyFile(from, to); + if (!from.delete()) { + throw new IOException("Failed to delete " + from + " while trying to rename it."); } } } /** *

          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 @@ -2143,25 +1845,20 @@ public static void rename( File from, File to ) * @param parentDir Directory to create the temporary file in -java.io.tmpdir used if not specificed * @return a File reference to the new temporary file. */ - public static File createTempFile( String prefix, String suffix, File parentDir ) - { + public static File createTempFile(String prefix, String suffix, File parentDir) { File result = null; - String parent = System.getProperty( "java.io.tmpdir" ); - if ( parentDir != null ) - { + String parent = System.getProperty("java.io.tmpdir"); + if (parentDir != null) { parent = parentDir.getPath(); } - DecimalFormat fmt = new DecimalFormat( "#####" ); + DecimalFormat fmt = new DecimalFormat("#####"); SecureRandom secureRandom = new SecureRandom(); long secureInitializer = secureRandom.nextLong(); - Random rand = new Random( secureInitializer + Runtime.getRuntime().freeMemory() ); - synchronized ( rand ) - { - do - { - result = new File( parent, prefix + fmt.format( Math.abs( rand.nextInt() ) ) + suffix ); - } - while ( result.exists() ); + Random rand = new Random(secureInitializer + Runtime.getRuntime().freeMemory()); + synchronized (rand) { + do { + result = new File(parent, prefix + fmt.format(Math.abs(rand.nextInt())) + suffix); + } while (result.exists()); } return result; @@ -2176,15 +1873,12 @@ public static File createTempFile( String prefix, String suffix, File parentDir * @param wrappers array of {@link FilterWrapper} * @throws IOException if an IO error occurs during copying or filtering */ - public static void copyFile( File from, File to, String encoding, FilterWrapper[] wrappers ) - throws IOException - { - copyFile( from, to, encoding, wrappers, false ); + public static void copyFile(File from, File to, String encoding, FilterWrapper[] wrappers) throws IOException { + copyFile(from, to, encoding, wrappers, false); } - public static abstract class FilterWrapper - { - public abstract Reader getReader( Reader fileReader ); + public abstract static class FilterWrapper { + public abstract Reader getReader(Reader fileReader); } /** @@ -2198,59 +1892,48 @@ public static abstract class FilterWrapper * @throws IOException if an IO error occurs during copying or filtering * @since 1.5.2 */ - public static void copyFile( File from, File to, String encoding, FilterWrapper[] wrappers, boolean overwrite ) - throws IOException - { - if ( wrappers != null && wrappers.length > 0 ) - { + public static void copyFile(File from, File to, String encoding, FilterWrapper[] wrappers, boolean overwrite) + throws IOException { + if (wrappers != null && wrappers.length > 0) { // buffer so it isn't reading a byte at a time! Reader fileReader = null; Writer fileWriter = null; - try - { - if ( encoding == null || encoding.length() < 1 ) - { - fileReader = Files.newBufferedReader( from.toPath() ); - fileWriter = Files.newBufferedWriter( to.toPath() ); - } - else - { - OutputStream outstream = Files.newOutputStream( to.toPath() ); + try { + if (encoding == null || encoding.length() < 1) { + fileReader = Files.newBufferedReader(from.toPath()); + fileWriter = Files.newBufferedWriter(to.toPath()); + } else { + OutputStream outstream = Files.newOutputStream(to.toPath()); - fileReader = Files.newBufferedReader( from.toPath(), Charset.forName( encoding ) ); + fileReader = Files.newBufferedReader(from.toPath(), Charset.forName(encoding)); - fileWriter = new OutputStreamWriter( outstream, encoding ); + fileWriter = new OutputStreamWriter(outstream, encoding); } Reader reader = fileReader; - for ( FilterWrapper wrapper : wrappers ) - { - reader = wrapper.getReader( reader ); + for (FilterWrapper wrapper : wrappers) { + reader = wrapper.getReader(reader); } - IOUtil.copy( reader, fileWriter ); + IOUtil.copy(reader, fileWriter); fileWriter.close(); fileWriter = null; fileReader.close(); fileReader = null; + } finally { + IOUtil.close(fileReader); + IOUtil.close(fileWriter); } - finally - { - IOUtil.close( fileReader ); - IOUtil.close( fileWriter ); - } - } - else - { - if ( isSourceNewerThanDestination( from, to ) || overwrite ) - { - copyFile( from, to ); + } else { + if (isSourceNewerThanDestination(from, to) || overwrite) { + copyFile(from, to); } } } - private static boolean isSourceNewerThanDestination( File source, File destination ) { - return ( destination.lastModified() == 0L && source.lastModified() == 0L ) || destination.lastModified() < source.lastModified(); + private static boolean isSourceNewerThanDestination(File source, File destination) { + return (destination.lastModified() == 0L && source.lastModified() == 0L) + || destination.lastModified() < source.lastModified(); } /** @@ -2260,22 +1943,16 @@ private static boolean isSourceNewerThanDestination( File source, File destinati * @return a List containing every every line not starting with # and not empty * @throws IOException if any */ - public static List loadFile( File file ) - throws IOException - { + public static List loadFile(File file) throws IOException { final List lines = new ArrayList(); - if ( file.exists() ) - { - try ( BufferedReader reader = Files.newBufferedReader( file.toPath() ) ) - { - for ( String line = reader.readLine(); line != null; line = reader.readLine() ) - { + if (file.exists()) { + try (BufferedReader reader = Files.newBufferedReader(file.toPath())) { + for (String line = reader.readLine(); line != null; line = reader.readLine()) { line = line.trim(); - if ( !line.startsWith( "#" ) && line.length() != 0 ) - { - lines.add( line ); + if (!line.startsWith("#") && line.length() != 0) { + lines.add(line); } } } @@ -2294,19 +1971,15 @@ public static List loadFile( File file ) * @see #INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME * @since 1.5.2 */ - public static boolean isValidWindowsFileName( File f ) - { - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - if ( StringUtils.indexOfAny( f.getName(), INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME ) != -1 ) - { + public static boolean isValidWindowsFileName(File f) { + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + if (StringUtils.indexOfAny(f.getName(), INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME) != -1) { return false; } File parentFile = f.getParentFile(); - if ( parentFile != null ) - { - return isValidWindowsFileName( parentFile ); + if (parentFile != null) { + return isValidWindowsFileName(parentFile); } } diff --git a/src/main/java/org/codehaus/plexus/util/IOUtil.java b/src/main/java/org/codehaus/plexus/util/IOUtil.java index b431a8d9..e7f20908 100644 --- a/src/main/java/org/codehaus/plexus/util/IOUtil.java +++ b/src/main/java/org/codehaus/plexus/util/IOUtil.java @@ -132,16 +132,13 @@ * method variants to specify buffer size and encoding, each row may correspond to up to 4 methods. */ -public final class IOUtil extends BaseIOUtil -{ +public final class IOUtil extends BaseIOUtil { private static final int DEFAULT_BUFFER_SIZE = 1024 * 16; /** * Private constructor to prevent instantiation. */ - private IOUtil() - { - } + private IOUtil() {} /////////////////////////////////////////////////////////////// // Core copy methods @@ -153,10 +150,8 @@ private IOUtil() * @param output the result * @throws IOException io issue */ - public static void copy( final InputStream input, final OutputStream output ) - throws IOException - { - BaseIOUtil.copy( input, output ); + public static void copy(final InputStream input, final OutputStream output) throws IOException { + BaseIOUtil.copy(input, output); } /** @@ -166,14 +161,12 @@ public static void copy( final InputStream input, final OutputStream output ) * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static void copy( final InputStream input, final OutputStream output, final int bufferSize ) - throws IOException - { + public static void copy(final InputStream input, final OutputStream output, final int bufferSize) + throws IOException { final byte[] buffer = new byte[bufferSize]; int n = 0; - while ( 0 <= ( n = input.read( buffer ) ) ) - { - output.write( buffer, 0, n ); + while (0 <= (n = input.read(buffer))) { + output.write(buffer, 0, n); } } @@ -183,10 +176,8 @@ public static void copy( final InputStream input, final OutputStream output, fin * @param output the result * @throws IOException io issue */ - public static void copy( final Reader input, final Writer output ) - throws IOException - { - BaseIOUtil.copy( input, output ); + public static void copy(final Reader input, final Writer output) throws IOException { + BaseIOUtil.copy(input, output); } /** @@ -196,14 +187,11 @@ public static void copy( final Reader input, final Writer output ) * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static void copy( final Reader input, final Writer output, final int bufferSize ) - throws IOException - { + public static void copy(final Reader input, final Writer output, final int bufferSize) throws IOException { final char[] buffer = new char[bufferSize]; int n = 0; - while ( 0 <= ( n = input.read( buffer ) ) ) - { - output.write( buffer, 0, n ); + while (0 <= (n = input.read(buffer))) { + output.write(buffer, 0, n); } output.flush(); } @@ -223,10 +211,8 @@ public static void copy( final Reader input, final Writer output, final int buff * @param output the result * @throws IOException io issue */ - public static void copy( final InputStream input, final Writer output ) - throws IOException - { - copy( input, output, DEFAULT_BUFFER_SIZE ); + public static void copy(final InputStream input, final Writer output) throws IOException { + copy(input, output, DEFAULT_BUFFER_SIZE); } /** @@ -237,11 +223,9 @@ public static void copy( final InputStream input, final Writer output ) * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static void copy( final InputStream input, final Writer output, final int bufferSize ) - throws IOException - { - final InputStreamReader in = new InputStreamReader( input ); - copy( in, output, bufferSize ); + public static void copy(final InputStream input, final Writer output, final int bufferSize) throws IOException { + final InputStreamReader in = new InputStreamReader(input); + copy(in, output, bufferSize); } /** @@ -254,11 +238,9 @@ public static void copy( final InputStream input, final Writer output, final int * encoding types. * @throws IOException io issue */ - public static void copy( final InputStream input, final Writer output, final String encoding ) - throws IOException - { - final InputStreamReader in = new InputStreamReader( input, encoding ); - copy( in, output ); + public static void copy(final InputStream input, final Writer output, final String encoding) throws IOException { + final InputStreamReader in = new InputStreamReader(input, encoding); + copy(in, output); } /** @@ -272,11 +254,10 @@ public static void copy( final InputStream input, final Writer output, final Str * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static void copy( final InputStream input, final Writer output, final String encoding, final int bufferSize ) - throws IOException - { - final InputStreamReader in = new InputStreamReader( input, encoding ); - copy( in, output, bufferSize ); + public static void copy(final InputStream input, final Writer output, final String encoding, final int bufferSize) + throws IOException { + final InputStreamReader in = new InputStreamReader(input, encoding); + copy(in, output, bufferSize); } /////////////////////////////////////////////////////////////// @@ -288,10 +269,8 @@ public static void copy( final InputStream input, final Writer output, final Str * @param input to convert * @throws IOException io issue */ - public static String toString( final InputStream input ) - throws IOException - { - return toString( input, DEFAULT_BUFFER_SIZE ); + public static String toString(final InputStream input) throws IOException { + return toString(input, DEFAULT_BUFFER_SIZE); } /** @@ -301,11 +280,9 @@ public static String toString( final InputStream input ) * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static String toString( final InputStream input, final int bufferSize ) - throws IOException - { + public static String toString(final InputStream input, final int bufferSize) throws IOException { final StringWriter sw = new StringWriter(); - copy( input, sw, bufferSize ); + copy(input, sw, bufferSize); return sw.toString(); } @@ -317,10 +294,8 @@ public static String toString( final InputStream input, final int bufferSize ) * encoding types. * @throws IOException io issue */ - public static String toString( final InputStream input, final String encoding ) - throws IOException - { - return toString( input, encoding, DEFAULT_BUFFER_SIZE ); + public static String toString(final InputStream input, final String encoding) throws IOException { + return toString(input, encoding, DEFAULT_BUFFER_SIZE); } /** @@ -332,11 +307,10 @@ public static String toString( final InputStream input, final String encoding ) * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static String toString( final InputStream input, final String encoding, final int bufferSize ) - throws IOException - { + public static String toString(final InputStream input, final String encoding, final int bufferSize) + throws IOException { final StringWriter sw = new StringWriter(); - copy( input, sw, encoding, bufferSize ); + copy(input, sw, encoding, bufferSize); return sw.toString(); } @@ -348,10 +322,8 @@ public static String toString( final InputStream input, final String encoding, f * @param input to convert * @throws IOException io issue */ - public static byte[] toByteArray( final InputStream input ) - throws IOException - { - return toByteArray( input, DEFAULT_BUFFER_SIZE ); + public static byte[] toByteArray(final InputStream input) throws IOException { + return toByteArray(input, DEFAULT_BUFFER_SIZE); } /** @@ -360,11 +332,9 @@ public static byte[] toByteArray( final InputStream input ) * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static byte[] toByteArray( final InputStream input, final int bufferSize ) - throws IOException - { + public static byte[] toByteArray(final InputStream input, final int bufferSize) throws IOException { final ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy( input, output, bufferSize ); + copy(input, output, bufferSize); return output.toByteArray(); } @@ -382,10 +352,8 @@ public static byte[] toByteArray( final InputStream input, final int bufferSize * @param output the result * @throws IOException io issue */ - public static void copy( final Reader input, final OutputStream output ) - throws IOException - { - copy( input, output, DEFAULT_BUFFER_SIZE ); + public static void copy(final Reader input, final OutputStream output) throws IOException { + copy(input, output, DEFAULT_BUFFER_SIZE); } /** @@ -396,11 +364,9 @@ public static void copy( final Reader input, final OutputStream output ) * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static void copy( final Reader input, final OutputStream output, final int bufferSize ) - throws IOException - { - final OutputStreamWriter out = new OutputStreamWriter( output ); - copy( input, out, bufferSize ); + public static void copy(final Reader input, final OutputStream output, final int bufferSize) throws IOException { + final OutputStreamWriter out = new OutputStreamWriter(output); + copy(input, out, bufferSize); // NOTE: Unless anyone is planning on rewriting OutputStreamWriter, we have to flush // here. out.flush(); @@ -413,10 +379,8 @@ public static void copy( final Reader input, final OutputStream output, final in * @param input to convert * @throws IOException io issue */ - public static String toString( final Reader input ) - throws IOException - { - return toString( input, DEFAULT_BUFFER_SIZE ); + public static String toString(final Reader input) throws IOException { + return toString(input, DEFAULT_BUFFER_SIZE); } /** @@ -425,11 +389,9 @@ public static String toString( final Reader input ) * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static String toString( final Reader input, final int bufferSize ) - throws IOException - { + public static String toString(final Reader input, final int bufferSize) throws IOException { final StringWriter sw = new StringWriter(); - copy( input, sw, bufferSize ); + copy(input, sw, bufferSize); return sw.toString(); } @@ -440,10 +402,8 @@ public static String toString( final Reader input, final int bufferSize ) * @param input to convert * @throws IOException io issue */ - public static byte[] toByteArray( final Reader input ) - throws IOException - { - return toByteArray( input, DEFAULT_BUFFER_SIZE ); + public static byte[] toByteArray(final Reader input) throws IOException { + return toByteArray(input, DEFAULT_BUFFER_SIZE); } /** @@ -452,11 +412,9 @@ public static byte[] toByteArray( final Reader input ) * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static byte[] toByteArray( final Reader input, final int bufferSize ) - throws IOException - { + public static byte[] toByteArray(final Reader input, final int bufferSize) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy( input, output, bufferSize ); + copy(input, output, bufferSize); return output.toByteArray(); } @@ -475,26 +433,22 @@ public static byte[] toByteArray( final Reader input, final int bufferSize ) * @param output the result * @throws IOException io issue */ - public static void copy( final String input, final OutputStream output ) - throws IOException - { - copy( input, output, DEFAULT_BUFFER_SIZE ); + public static void copy(final String input, final OutputStream output) throws IOException { + copy(input, output, DEFAULT_BUFFER_SIZE); } /** * Serialize chars from a String to bytes on an OutputStream, and flush the * OutputStream. * @param input to convert - * @param output the result + * @param output the result * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static void copy( final String input, final OutputStream output, final int bufferSize ) - throws IOException - { - final StringReader in = new StringReader( input ); - final OutputStreamWriter out = new OutputStreamWriter( output ); - copy( in, out, bufferSize ); + public static void copy(final String input, final OutputStream output, final int bufferSize) throws IOException { + final StringReader in = new StringReader(input); + final OutputStreamWriter out = new OutputStreamWriter(output); + copy(in, out, bufferSize); // NOTE: Unless anyone is planning on rewriting OutputStreamWriter, we have to flush // here. out.flush(); @@ -509,10 +463,8 @@ public static void copy( final String input, final OutputStream output, final in * @param output the result * @throws IOException io issue */ - public static void copy( final String input, final Writer output ) - throws IOException - { - output.write( input ); + public static void copy(final String input, final Writer output) throws IOException { + output.write(input); } /** @@ -521,18 +473,16 @@ public static void copy( final String input, final Writer output ) * {@link #copy(InputStream, OutputStream)}, and flushing the output stream afterwards. The streams are not closed * after the copy. * @param input to convert - * @param output the result + * @param output the result * @deprecated Buffering streams is actively harmful! See the class description as to why. Use * {@link #copy(InputStream, OutputStream)} instead. * @throws IOException io issue */ @Deprecated - public static void bufferedCopy( final InputStream input, final OutputStream output ) - throws IOException - { - final BufferedInputStream in = new BufferedInputStream( input ); - final BufferedOutputStream out = new BufferedOutputStream( output ); - copy( in, out ); + public static void bufferedCopy(final InputStream input, final OutputStream output) throws IOException { + final BufferedInputStream in = new BufferedInputStream(input); + final BufferedOutputStream out = new BufferedOutputStream(output); + copy(in, out); out.flush(); } @@ -543,10 +493,8 @@ public static void bufferedCopy( final InputStream input, final OutputStream out * @param input to convert * @throws IOException io issue */ - public static byte[] toByteArray( final String input ) - throws IOException - { - return toByteArray( input, DEFAULT_BUFFER_SIZE ); + public static byte[] toByteArray(final String input) throws IOException { + return toByteArray(input, DEFAULT_BUFFER_SIZE); } /** @@ -555,11 +503,9 @@ public static byte[] toByteArray( final String input ) * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static byte[] toByteArray( final String input, final int bufferSize ) - throws IOException - { + public static byte[] toByteArray(final String input, final int bufferSize) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy( input, output, bufferSize ); + copy(input, output, bufferSize); return output.toByteArray(); } @@ -578,60 +524,53 @@ public static byte[] toByteArray( final String input, final int bufferSize ) * @param output the result * @throws IOException io issue */ - public static void copy( final byte[] input, final Writer output ) - throws IOException - { - copy( input, output, DEFAULT_BUFFER_SIZE ); + public static void copy(final byte[] input, final Writer output) throws IOException { + copy(input, output, DEFAULT_BUFFER_SIZE); } /** * Copy and convert bytes from a byte[] to chars on a Writer. The platform's default * encoding is used for the byte-to-char conversion. * @param input to convert - * @param output the result + * @param output the result * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static void copy( final byte[] input, final Writer output, final int bufferSize ) - throws IOException - { - final ByteArrayInputStream in = new ByteArrayInputStream( input ); - copy( in, output, bufferSize ); + public static void copy(final byte[] input, final Writer output, final int bufferSize) throws IOException { + final ByteArrayInputStream in = new ByteArrayInputStream(input); + copy(in, output, bufferSize); } /** * Copy and convert bytes from a byte[] to chars on a Writer, using the specified * encoding. * @param input to convert - * @param output the result + * @param output the result * @param encoding The name of a supported character encoding. See the * IANA Charset Registry for a list of valid * encoding types. * @throws IOException io issue */ - public static void copy( final byte[] input, final Writer output, final String encoding ) - throws IOException - { - final ByteArrayInputStream in = new ByteArrayInputStream( input ); - copy( in, output, encoding ); + public static void copy(final byte[] input, final Writer output, final String encoding) throws IOException { + final ByteArrayInputStream in = new ByteArrayInputStream(input); + copy(in, output, encoding); } /** * Copy and convert bytes from a byte[] to chars on a Writer, using the specified * encoding. * @param input to convert - * @param output the result + * @param output the result * @param encoding The name of a supported character encoding. See the * IANA Charset Registry for a list of valid * encoding types. * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static void copy( final byte[] input, final Writer output, final String encoding, final int bufferSize ) - throws IOException - { - final ByteArrayInputStream in = new ByteArrayInputStream( input ); - copy( in, output, encoding, bufferSize ); + public static void copy(final byte[] input, final Writer output, final String encoding, final int bufferSize) + throws IOException { + final ByteArrayInputStream in = new ByteArrayInputStream(input); + copy(in, output, encoding, bufferSize); } /////////////////////////////////////////////////////////////// @@ -643,10 +582,8 @@ public static void copy( final byte[] input, final Writer output, final String e * @param input to convert * @throws IOException io issue */ - public static String toString( final byte[] input ) - throws IOException - { - return toString( input, DEFAULT_BUFFER_SIZE ); + public static String toString(final byte[] input) throws IOException { + return toString(input, DEFAULT_BUFFER_SIZE); } /** @@ -656,11 +593,9 @@ public static String toString( final byte[] input ) * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static String toString( final byte[] input, final int bufferSize ) - throws IOException - { + public static String toString(final byte[] input, final int bufferSize) throws IOException { final StringWriter sw = new StringWriter(); - copy( input, sw, bufferSize ); + copy(input, sw, bufferSize); return sw.toString(); } @@ -672,10 +607,8 @@ public static String toString( final byte[] input, final int bufferSize ) * encoding types. * @throws IOException io issue */ - public static String toString( final byte[] input, final String encoding ) - throws IOException - { - return toString( input, encoding, DEFAULT_BUFFER_SIZE ); + public static String toString(final byte[] input, final String encoding) throws IOException { + return toString(input, encoding, DEFAULT_BUFFER_SIZE); } /** @@ -688,11 +621,9 @@ public static String toString( final byte[] input, final String encoding ) * * @throws IOException io issue */ - public static String toString( final byte[] input, final String encoding, final int bufferSize ) - throws IOException - { + public static String toString(final byte[] input, final String encoding, final int bufferSize) throws IOException { final StringWriter sw = new StringWriter(); - copy( input, sw, encoding, bufferSize ); + copy(input, sw, encoding, bufferSize); return sw.toString(); } @@ -705,10 +636,8 @@ public static String toString( final byte[] input, final String encoding, final * @param output the result * @throws IOException io issue */ - public static void copy( final byte[] input, final OutputStream output ) - throws IOException - { - copy( input, output, DEFAULT_BUFFER_SIZE ); + public static void copy(final byte[] input, final OutputStream output) throws IOException { + copy(input, output, DEFAULT_BUFFER_SIZE); } /** @@ -718,10 +647,8 @@ public static void copy( final byte[] input, final OutputStream output ) * @param bufferSize Size of internal buffer to use. * @throws IOException io issue */ - public static void copy( final byte[] input, final OutputStream output, final int bufferSize ) - throws IOException - { - output.write( input ); + public static void copy(final byte[] input, final OutputStream output, final int bufferSize) throws IOException { + output.write(input); } /** @@ -732,30 +659,23 @@ public static void copy( final byte[] input, final OutputStream output, final in * @return true if the content of the streams are equal or they both don't exist, false otherwise * @throws IOException io issue */ - public static boolean contentEquals( final InputStream input1, final InputStream input2 ) - throws IOException - { - final InputStream bufferedInput1 = new BufferedInputStream( input1 ); - final InputStream bufferedInput2 = new BufferedInputStream( input2 ); + public static boolean contentEquals(final InputStream input1, final InputStream input2) throws IOException { + final InputStream bufferedInput1 = new BufferedInputStream(input1); + final InputStream bufferedInput2 = new BufferedInputStream(input2); int ch = bufferedInput1.read(); - while ( 0 <= ch ) - { + while (0 <= ch) { final int ch2 = bufferedInput2.read(); - if ( ch != ch2 ) - { + if (ch != ch2) { return false; } ch = bufferedInput1.read(); } final int ch2 = bufferedInput2.read(); - if ( 0 <= ch2 ) - { + if (0 <= ch2) { return false; - } - else - { + } else { return true; } } @@ -766,24 +686,19 @@ public static boolean contentEquals( final InputStream input1, final InputStream /** * Closes the input stream. The input stream can be null and any IOException's will be swallowed. - * + * * @param inputStream The stream to close. * @deprecated use try-with-resources instead */ @Deprecated - public static void close( InputStream inputStream ) - { - if ( inputStream == null ) - { + public static void close(InputStream inputStream) { + if (inputStream == null) { return; } - try - { + try { inputStream.close(); - } - catch ( IOException ex ) - { + } catch (IOException ex) { // ignore } } @@ -795,91 +710,71 @@ public static void close( InputStream inputStream ) * @deprecated use try-with-resources instead */ @Deprecated - public static void close( Channel channel ) - { - if ( channel == null ) - { + public static void close(Channel channel) { + if (channel == null) { return; } - try - { + try { channel.close(); - } - catch ( IOException ex ) - { + } catch (IOException ex) { // ignore } } /** * Closes the output stream. The output stream can be null and any IOException's will be swallowed. - * + * * @param outputStream The stream to close. * @deprecated use try-with-resources instead */ @Deprecated - public static void close( OutputStream outputStream ) - { - if ( outputStream == null ) - { + public static void close(OutputStream outputStream) { + if (outputStream == null) { return; } - try - { + try { outputStream.close(); - } - catch ( IOException ex ) - { + } catch (IOException ex) { // ignore } } /** * Closes the reader. The reader can be null and any IOException's will be swallowed. - * + * * @param reader The reader to close. * @deprecated use try-with-resources instead */ @Deprecated - public static void close( Reader reader ) - { - if ( reader == null ) - { + public static void close(Reader reader) { + if (reader == null) { return; } - try - { + try { reader.close(); - } - catch ( IOException ex ) - { + } catch (IOException ex) { // ignore } } /** * Closes the writer. The writer can be null and any IOException's will be swallowed. - * + * * @param writer The writer to close. * @deprecated use try-with-resources instead */ @Deprecated - public static void close( Writer writer ) - { - if ( writer == null ) - { + public static void close(Writer writer) { + if (writer == null) { return; } - try - { + try { writer.close(); - } - catch ( IOException ex ) - { + } catch (IOException ex) { // ignore } } diff --git a/src/main/java/org/codehaus/plexus/util/InterpolationFilterReader.java b/src/main/java/org/codehaus/plexus/util/InterpolationFilterReader.java index c8515b2e..37b6768e 100644 --- a/src/main/java/org/codehaus/plexus/util/InterpolationFilterReader.java +++ b/src/main/java/org/codehaus/plexus/util/InterpolationFilterReader.java @@ -75,12 +75,10 @@ *
        • if the enclosed string is not found in the keyword Map, then no substitution is made; the token text is * passed through unaltered.
        • *
        - * + * * @see LineOrientedInterpolatingReader s */ -public class InterpolationFilterReader - extends FilterReader -{ +public class InterpolationFilterReader extends FilterReader { /** replacement text from a token */ private String replaceData = null; @@ -113,15 +111,14 @@ public class InterpolationFilterReader /** * Construct a Reader to interpolate values enclosed between the given delimiter tokens. - * + * * @param in a Reader to be wrapped for interpolation. * @param variables name/value pairs to be interpolated into the character stream. * @param beginToken an interpolation target begins with this. * @param endToken an interpolation target ends with this. */ - public InterpolationFilterReader( Reader in, Map variables, String beginToken, String endToken ) - { - super( in ); + public InterpolationFilterReader(Reader in, Map variables, String beginToken, String endToken) { + super(in); this.variables = variables; this.beginToken = beginToken; @@ -133,13 +130,12 @@ public InterpolationFilterReader( Reader in, Map variables, String be /** * Construct a Reader using the default interpolation delimiter tokens "${" and "}". - * + * * @param in a Reader to be wrapped for interpolation. * @param variables name/value pairs to be interpolated into the character stream. */ - public InterpolationFilterReader( Reader in, Map variables ) - { - this( in, variables, DEFAULT_BEGIN_TOKEN, DEFAULT_END_TOKEN ); + public InterpolationFilterReader(Reader in, Map variables) { + this(in, variables, DEFAULT_BEGIN_TOKEN, DEFAULT_END_TOKEN); } /** @@ -152,18 +148,13 @@ public InterpolationFilterReader( Reader in, Map variables ) * @exception IOException If an I/O error occurs */ @Override - public long skip( long n ) - throws IOException - { - if ( n < 0L ) - { - throw new IllegalArgumentException( "skip value is negative" ); + public long skip(long n) throws IOException { + if (n < 0L) { + throw new IllegalArgumentException("skip value is negative"); } - for ( long i = 0; i < n; i++ ) - { - if ( read() == -1 ) - { + for (long i = 0; i < n; i++) { + if (read() == -1) { return i; } } @@ -181,20 +172,13 @@ public long skip( long n ) * @exception IOException If an I/O error occurs */ @Override - public int read( char cbuf[], int off, int len ) - throws IOException - { - for ( int i = 0; i < len; i++ ) - { + public int read(char cbuf[], int off, int len) throws IOException { + for (int i = 0; i < len; i++) { int ch = read(); - if ( ch == -1 ) - { - if ( i == 0 ) - { + if (ch == -1) { + if (i == 0) { return -1; - } - else - { + } else { return i; } } @@ -210,127 +194,94 @@ public int read( char cbuf[], int off, int len ) * @exception IOException if the underlying stream throws an IOException during reading */ @Override - public int read() - throws IOException - { - if ( replaceIndex != -1 && replaceIndex < replaceData.length() ) - { - int ch = replaceData.charAt( replaceIndex++ ); - if ( replaceIndex >= replaceData.length() ) - { + public int read() throws IOException { + if (replaceIndex != -1 && replaceIndex < replaceData.length()) { + int ch = replaceData.charAt(replaceIndex++); + if (replaceIndex >= replaceData.length()) { replaceIndex = -1; } return ch; } int ch; - if ( previousIndex != -1 && previousIndex < endTokenLength ) - { - ch = endToken.charAt( previousIndex++ ); - } - else - { + if (previousIndex != -1 && previousIndex < endTokenLength) { + ch = endToken.charAt(previousIndex++); + } else { ch = in.read(); } - if ( ch == beginToken.charAt( 0 ) ) - { + if (ch == beginToken.charAt(0)) { StringBuilder key = new StringBuilder(); int beginTokenMatchPos = 1; - do - { - if ( previousIndex != -1 && previousIndex < endTokenLength ) - { - ch = endToken.charAt( previousIndex++ ); - } - else - { + do { + if (previousIndex != -1 && previousIndex < endTokenLength) { + ch = endToken.charAt(previousIndex++); + } else { ch = in.read(); } - if ( ch != -1 ) - { - key.append( (char) ch ); + if (ch != -1) { + key.append((char) ch); - if ( ( beginTokenMatchPos < beginTokenLength ) - && ( ch != beginToken.charAt( beginTokenMatchPos++ ) ) ) - { + if ((beginTokenMatchPos < beginTokenLength) && (ch != beginToken.charAt(beginTokenMatchPos++))) { ch = -1; // not really EOF but to trigger code below break; } - } - else - { + } else { break; } - } - while ( ch != endToken.charAt( 0 ) ); + } while (ch != endToken.charAt(0)); // now test endToken - if ( ch != -1 && endTokenLength > 1 ) - { + if (ch != -1 && endTokenLength > 1) { int endTokenMatchPos = 1; - do - { - if ( previousIndex != -1 && previousIndex < endTokenLength ) - { - ch = endToken.charAt( previousIndex++ ); - } - else - { + do { + if (previousIndex != -1 && previousIndex < endTokenLength) { + ch = endToken.charAt(previousIndex++); + } else { ch = in.read(); } - if ( ch != -1 ) - { - key.append( (char) ch ); + if (ch != -1) { + key.append((char) ch); - if ( ch != endToken.charAt( endTokenMatchPos++ ) ) - { + if (ch != endToken.charAt(endTokenMatchPos++)) { ch = -1; // not really EOF but to trigger code below break; } - } - else - { + } else { break; } - } - while ( endTokenMatchPos < endTokenLength ); + } while (endTokenMatchPos < endTokenLength); } // There is nothing left to read so we have the situation where the begin/end token // are in fact the same and as there is nothing left to read we have got ourselves // end of a token boundary so let it pass through. - if ( ch == -1 ) - { + if (ch == -1) { replaceData = key.toString(); replaceIndex = 0; - return beginToken.charAt( 0 ); + return beginToken.charAt(0); } - String variableKey = key.substring( beginTokenLength - 1, key.length() - endTokenLength ); + String variableKey = key.substring(beginTokenLength - 1, key.length() - endTokenLength); - Object o = variables.get( variableKey ); - if ( o != null ) - { + Object o = variables.get(variableKey); + if (o != null) { String value = o.toString(); - if ( value.length() != 0 ) - { + if (value.length() != 0) { replaceData = value; replaceIndex = 0; } return read(); - } - else - { + } else { previousIndex = 0; - replaceData = key.substring( 0, key.length() - endTokenLength ); + replaceData = key.substring(0, key.length() - endTokenLength); replaceIndex = 0; - return beginToken.charAt( 0 ); + return beginToken.charAt(0); } } diff --git a/src/main/java/org/codehaus/plexus/util/LineOrientedInterpolatingReader.java b/src/main/java/org/codehaus/plexus/util/LineOrientedInterpolatingReader.java index 8129018f..6670a411 100644 --- a/src/main/java/org/codehaus/plexus/util/LineOrientedInterpolatingReader.java +++ b/src/main/java/org/codehaus/plexus/util/LineOrientedInterpolatingReader.java @@ -16,9 +16,6 @@ * limitations under the License. */ -import org.codehaus.plexus.util.reflection.Reflector; -import org.codehaus.plexus.util.reflection.ReflectorException; - import java.io.FilterReader; import java.io.IOException; import java.io.PushbackReader; @@ -29,6 +26,9 @@ import java.util.Set; import java.util.TreeMap; +import org.codehaus.plexus.util.reflection.Reflector; +import org.codehaus.plexus.util.reflection.ReflectorException; + /** * A FilterReader which interpolates keyword values into a character stream. Keywords are recognized when enclosed * between starting and ending delimiter strings. The keywords themselves, and their values, are fetched from a Map @@ -44,17 +44,15 @@ *
      • 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 * 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.

      - * + * * @author jdcasey Created on Feb 3, 2005 * @see InterpolationFilterReader */ -public class LineOrientedInterpolatingReader - extends FilterReader -{ +public class LineOrientedInterpolatingReader extends FilterReader { public static final String DEFAULT_START_DELIM = "${"; public static final String DEFAULT_END_DELIM = "}"; @@ -85,17 +83,16 @@ public class LineOrientedInterpolatingReader /** * Construct an interpolating Reader, specifying token delimiters and the escape sequence. - * + * * @param reader the Reader to be filtered. * @param context keyword/value pairs for interpolation. * @param startDelim character sequence which (possibly) begins a token. * @param endDelim character sequence which ends a token. * @param escapeSeq escape sequence */ - public LineOrientedInterpolatingReader( Reader reader, Map context, String startDelim, String endDelim, - String escapeSeq ) - { - super( reader ); + public LineOrientedInterpolatingReader( + Reader reader, Map context, String startDelim, String endDelim, String escapeSeq) { + super(reader); this.startDelim = startDelim; @@ -106,86 +103,70 @@ public LineOrientedInterpolatingReader( Reader reader, Map context, S // Expressions have to be at least this size... this.minExpressionSize = startDelim.length() + endDelim.length() + 1; - this.context = Collections.unmodifiableMap( context ); + this.context = Collections.unmodifiableMap(context); this.reflector = new Reflector(); - if ( reader instanceof PushbackReader ) - { + if (reader instanceof PushbackReader) { this.pushbackReader = (PushbackReader) reader; - } - else - { - this.pushbackReader = new PushbackReader( reader, 1 ); + } else { + this.pushbackReader = new PushbackReader(reader, 1); } } /** * Filters a Reader using the default escape sequence "\". - * + * * @param reader the Reader to be filtered. * @param context keyword/value pairs for interpolation. * @param startDelim the character sequence which (possibly) begins a token. * @param endDelim the character sequence which ends a token. */ - public LineOrientedInterpolatingReader( Reader reader, Map context, String startDelim, String endDelim ) - { - this( reader, context, startDelim, endDelim, DEFAULT_ESCAPE_SEQ ); + public LineOrientedInterpolatingReader(Reader reader, Map context, String startDelim, String endDelim) { + this(reader, context, startDelim, endDelim, DEFAULT_ESCAPE_SEQ); } /** * Filters a Reader using the default escape sequence "\" and token delimiters "${", "}". - * + * * @param reader the Reader to be filtered. * @param context keyword/value pairs for interpolation. */ - public LineOrientedInterpolatingReader( Reader reader, Map context ) - { - this( reader, context, DEFAULT_START_DELIM, DEFAULT_END_DELIM, DEFAULT_ESCAPE_SEQ ); + public LineOrientedInterpolatingReader(Reader reader, Map context) { + this(reader, context, DEFAULT_START_DELIM, DEFAULT_END_DELIM, DEFAULT_ESCAPE_SEQ); } @Override - public int read() - throws IOException - { - if ( line == null || lineIdx >= line.length() ) - { + public int read() throws IOException { + if (line == null || lineIdx >= line.length()) { readAndInterpolateLine(); } int next = -1; - if ( line != null && lineIdx < line.length() ) - { - next = line.charAt( lineIdx++ ); + if (line != null && lineIdx < line.length()) { + next = line.charAt(lineIdx++); } return next; } @Override - public int read( char[] cbuf, int off, int len ) - throws IOException - { + public int read(char[] cbuf, int off, int len) throws IOException { int fillCount = 0; - for ( int i = off; i < off + len; i++ ) - { + for (int i = off; i < off + len; i++) { int next = read(); - if ( next > -1 ) - { + if (next > -1) { cbuf[i] = (char) next; - } - else - { + } else { break; } fillCount++; } - if ( fillCount == 0 ) - { + if (fillCount == 0) { fillCount = -1; } @@ -193,17 +174,13 @@ public int read( char[] cbuf, int off, int len ) } @Override - public long skip( long n ) - throws IOException - { + public long skip(long n) throws IOException { long skipCount = 0; - for ( long i = 0; i < n; i++ ) - { + for (long i = 0; i < n; i++) { int next = read(); - if ( next < 0 ) - { + if (next < 0) { break; } @@ -213,27 +190,21 @@ public long skip( long n ) return skipCount; } - private void readAndInterpolateLine() - throws IOException - { + private void readAndInterpolateLine() throws IOException { String rawLine = readLine(); - if ( rawLine != null ) - { - Set expressions = parseForExpressions( rawLine ); + if (rawLine != null) { + Set expressions = parseForExpressions(rawLine); - Map evaluatedExpressions = evaluateExpressions( expressions ); + Map evaluatedExpressions = evaluateExpressions(expressions); - String interpolated = replaceWithInterpolatedValues( rawLine, evaluatedExpressions ); + String interpolated = replaceWithInterpolatedValues(rawLine, evaluatedExpressions); - if ( interpolated != null && interpolated.length() > 0 ) - { + if (interpolated != null && interpolated.length() > 0) { line = interpolated; lineIdx = 0; } - } - else - { + } else { line = null; lineIdx = -1; } @@ -243,97 +214,73 @@ private void readAndInterpolateLine() * Read one line from the wrapped Reader. A line is a sequence of characters ending in CRLF, CR, or LF. The * terminating character(s) will be included in the returned line. */ - private String readLine() - throws IOException - { - StringBuilder lineBuffer = new StringBuilder( 40 ); // half of the "normal" line maxsize + private String readLine() throws IOException { + StringBuilder lineBuffer = new StringBuilder(40); // half of the "normal" line maxsize int next; boolean lastWasCR = false; - while ( ( next = pushbackReader.read() ) > -1 ) - { + while ((next = pushbackReader.read()) > -1) { char c = (char) next; - if ( c == CARRIAGE_RETURN_CHAR ) - { + if (c == CARRIAGE_RETURN_CHAR) { lastWasCR = true; - lineBuffer.append( c ); - } - else if ( c == NEWLINE_CHAR ) - { - lineBuffer.append( c ); + lineBuffer.append(c); + } else if (c == NEWLINE_CHAR) { + lineBuffer.append(c); break; // end of line. - } - else if ( lastWasCR ) - { - pushbackReader.unread( c ); + } else if (lastWasCR) { + pushbackReader.unread(c); break; - } - else - { - lineBuffer.append( c ); + } else { + lineBuffer.append(c); } } - if ( lineBuffer.length() < 1 ) - { + if (lineBuffer.length() < 1) { return null; - } - else - { + } else { return lineBuffer.toString(); } } - private String replaceWithInterpolatedValues( String rawLine, Map evaluatedExpressions ) - { + private String replaceWithInterpolatedValues(String rawLine, Map evaluatedExpressions) { String result = rawLine; - for ( Object o : evaluatedExpressions.entrySet() ) - { + for (Object o : evaluatedExpressions.entrySet()) { Map.Entry entry = (Map.Entry) o; String expression = (String) entry.getKey(); - String value = String.valueOf( entry.getValue() ); + String value = String.valueOf(entry.getValue()); - result = findAndReplaceUnlessEscaped( result, expression, value ); + result = findAndReplaceUnlessEscaped(result, expression, value); } return result; } - private Map evaluateExpressions( Set expressions ) - { + private Map evaluateExpressions(Set expressions) { Map evaluated = new TreeMap(); - for ( Object expression : expressions ) - { + for (Object expression : expressions) { String rawExpression = (String) expression; String realExpression = - rawExpression.substring( startDelim.length(), rawExpression.length() - endDelim.length() ); - - String[] parts = realExpression.split( "\\." ); - if ( parts.length > 0 ) - { - Object value = context.get( parts[0] ); - - if ( value != null ) - { - for ( int i = 1; i < parts.length; i++ ) - { - try - { - value = reflector.getObjectProperty( value, parts[i] ); - - if ( value == null ) - { + rawExpression.substring(startDelim.length(), rawExpression.length() - endDelim.length()); + + String[] parts = realExpression.split("\\."); + if (parts.length > 0) { + Object value = context.get(parts[0]); + + if (value != null) { + for (int i = 1; i < parts.length; i++) { + try { + value = reflector.getObjectProperty(value, parts[i]); + + if (value == null) { break; } - } - catch ( ReflectorException e ) - { + } catch (ReflectorException e) { // TODO: Fix this! It should report, but not interrupt. e.printStackTrace(); @@ -341,7 +288,7 @@ private Map evaluateExpressions( Set expressions ) } } - evaluated.put( rawExpression, value ); + evaluated.put(rawExpression, value); } } } @@ -349,32 +296,27 @@ private Map evaluateExpressions( Set expressions ) return evaluated; } - private Set parseForExpressions( String rawLine ) - { + private Set parseForExpressions(String rawLine) { Set expressions = new HashSet(); - if ( rawLine != null ) - { + if (rawLine != null) { int placeholder = -1; - do - { + do { // find the beginning of the next expression. - int start = findDelimiter( rawLine, startDelim, placeholder ); + int start = findDelimiter(rawLine, startDelim, placeholder); // if we can't find a start-delimiter, then there is no valid expression. Ignore everything else. - if ( start < 0 ) - { + if (start < 0) { // no expression found. break; } // find the end of the next expression. - int end = findDelimiter( rawLine, endDelim, start + 1 ); + int end = findDelimiter(rawLine, endDelim, start + 1); // if we can't find an end-delimiter, then this is not a valid expression. Ignore it. - if ( end < 0 ) - { + if (end < 0) { // no VALID expression found. break; } @@ -382,93 +324,73 @@ private Set parseForExpressions( String rawLine ) // if we reach this point, we have a valid start and end position, which // means we have a valid expression. So, we add it to the set of // expressions in need of evaluation. - expressions.add( rawLine.substring( start, end + endDelim.length() ) ); + expressions.add(rawLine.substring(start, end + endDelim.length())); // increment the placeholder so we can look beyond this expression. placeholder = end + 1; - } - while ( placeholder < rawLine.length() - minExpressionSize ); + } while (placeholder < rawLine.length() - minExpressionSize); } return expressions; } - private int findDelimiter( String rawLine, String delimiter, int lastPos ) - { + private int findDelimiter(String rawLine, String delimiter, int lastPos) { int placeholder = lastPos; int position; - do - { - position = rawLine.indexOf( delimiter, placeholder ); + do { + position = rawLine.indexOf(delimiter, placeholder); - if ( position < 0 ) - { + if (position < 0) { break; - } - else - { - int escEndIdx = rawLine.indexOf( escapeSeq, placeholder ) + escapeSeq.length(); + } else { + int escEndIdx = rawLine.indexOf(escapeSeq, placeholder) + escapeSeq.length(); - if ( escEndIdx > escapeSeq.length() - 1 && escEndIdx == position ) - { + if (escEndIdx > escapeSeq.length() - 1 && escEndIdx == position) { placeholder = position + 1; position = -1; } } - } - while ( position < 0 && placeholder < rawLine.length() - endDelim.length() ); + } while (position < 0 && placeholder < rawLine.length() - endDelim.length()); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // use length() - endDelim.length() b/c otherwise there is nothing left to search. return position; } - private String findAndReplaceUnlessEscaped( String rawLine, String search, String replace ) - { - StringBuilder lineBuffer = new StringBuilder( (int) ( rawLine.length() * 1.5 ) ); + private String findAndReplaceUnlessEscaped(String rawLine, String search, String replace) { + StringBuilder lineBuffer = new StringBuilder((int) (rawLine.length() * 1.5)); int lastReplacement = -1; - do - { - int nextReplacement = rawLine.indexOf( search, lastReplacement + 1 ); - if ( nextReplacement > -1 ) - { - if ( lastReplacement < 0 ) - { + do { + int nextReplacement = rawLine.indexOf(search, lastReplacement + 1); + if (nextReplacement > -1) { + if (lastReplacement < 0) { lastReplacement = 0; } - lineBuffer.append( rawLine, lastReplacement, nextReplacement ); + lineBuffer.append(rawLine, lastReplacement, nextReplacement); - int escIdx = rawLine.indexOf( escapeSeq, lastReplacement + 1 ); - if ( escIdx > -1 && escIdx + escapeSeq.length() == nextReplacement ) - { - lineBuffer.setLength( lineBuffer.length() - escapeSeq.length() ); - lineBuffer.append( search ); - } - else - { - lineBuffer.append( replace ); + int escIdx = rawLine.indexOf(escapeSeq, lastReplacement + 1); + if (escIdx > -1 && escIdx + escapeSeq.length() == nextReplacement) { + lineBuffer.setLength(lineBuffer.length() - escapeSeq.length()); + lineBuffer.append(search); + } else { + lineBuffer.append(replace); } lastReplacement = nextReplacement + search.length(); - } - else - { + } else { break; } - } - while ( lastReplacement > -1 ); + } while (lastReplacement > -1); - if ( lastReplacement < rawLine.length() ) - { - lineBuffer.append( rawLine, lastReplacement, rawLine.length() ); + if (lastReplacement < rawLine.length()) { + lineBuffer.append(rawLine, lastReplacement, rawLine.length()); } return lineBuffer.toString(); } - } diff --git a/src/main/java/org/codehaus/plexus/util/MatchPattern.java b/src/main/java/org/codehaus/plexus/util/MatchPattern.java index de57de21..4dc757e3 100644 --- a/src/main/java/org/codehaus/plexus/util/MatchPattern.java +++ b/src/main/java/org/codehaus/plexus/util/MatchPattern.java @@ -23,13 +23,12 @@ /** *

      Describes a match target for SelectorUtils.

      - * + * *

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

      * * @author Kristian Rosenvold */ -public class MatchPattern -{ +public class MatchPattern { private final String source; private final String regexPattern; @@ -40,107 +39,85 @@ public class MatchPattern private final char[][] tokenizedChar; - private MatchPattern( String source, String separator ) - { - regexPattern = SelectorUtils.isRegexPrefixedPattern( source ) - ? source.substring( SelectorUtils.REGEX_HANDLER_PREFIX.length(), - source.length() - SelectorUtils.PATTERN_HANDLER_SUFFIX.length() ) - : null; - this.source = SelectorUtils.isAntPrefixedPattern( source ) - ? source.substring( SelectorUtils.ANT_HANDLER_PREFIX.length(), - source.length() - SelectorUtils.PATTERN_HANDLER_SUFFIX.length() ) - : source; + private MatchPattern(String source, String separator) { + regexPattern = SelectorUtils.isRegexPrefixedPattern(source) + ? source.substring( + SelectorUtils.REGEX_HANDLER_PREFIX.length(), + source.length() - SelectorUtils.PATTERN_HANDLER_SUFFIX.length()) + : null; + this.source = SelectorUtils.isAntPrefixedPattern(source) + ? source.substring( + SelectorUtils.ANT_HANDLER_PREFIX.length(), + source.length() - SelectorUtils.PATTERN_HANDLER_SUFFIX.length()) + : source; this.separator = separator; - tokenized = tokenizePathToString( this.source, separator ); + tokenized = tokenizePathToString(this.source, separator); tokenizedChar = new char[tokenized.length][]; - for ( int i = 0; i < tokenized.length; i++ ) - { + for (int i = 0; i < tokenized.length; i++) { tokenizedChar[i] = tokenized[i].toCharArray(); } - } - public boolean matchPath( String str, boolean isCaseSensitive ) - { - if ( regexPattern != null ) - { - return str.matches( regexPattern ); - } - else - { - return SelectorUtils.matchAntPathPattern( this, str, separator, isCaseSensitive ); + public boolean matchPath(String str, boolean isCaseSensitive) { + if (regexPattern != null) { + return str.matches(regexPattern); + } else { + return SelectorUtils.matchAntPathPattern(this, str, separator, isCaseSensitive); } } - boolean matchPath( String str, char[][] strDirs, boolean isCaseSensitive ) - { - if ( regexPattern != null ) - { - return str.matches( regexPattern ); - } - else - { - return SelectorUtils.matchAntPathPattern( getTokenizedPathChars(), strDirs, isCaseSensitive ); + boolean matchPath(String str, char[][] strDirs, boolean isCaseSensitive) { + if (regexPattern != null) { + return str.matches(regexPattern); + } else { + return SelectorUtils.matchAntPathPattern(getTokenizedPathChars(), strDirs, isCaseSensitive); } } - public boolean matchPatternStart( String str, boolean isCaseSensitive ) - { - if ( regexPattern != null ) - { + public boolean matchPatternStart(String str, boolean isCaseSensitive) { + if (regexPattern != null) { // FIXME: ICK! But we can't do partial matches for regex, so we have to reserve judgement until we have // a file to deal with, or we can definitely say this is an exclusion... return true; - } - else - { - String altStr = str.replace( '\\', '/' ); + } else { + String altStr = str.replace('\\', '/'); - return SelectorUtils.matchAntPathPatternStart( this, str, File.separator, isCaseSensitive ) - || SelectorUtils.matchAntPathPatternStart( this, altStr, "/", isCaseSensitive ); + return SelectorUtils.matchAntPathPatternStart(this, str, File.separator, isCaseSensitive) + || SelectorUtils.matchAntPathPatternStart(this, altStr, "/", isCaseSensitive); } } - public String[] getTokenizedPathString() - { + public String[] getTokenizedPathString() { return tokenized; } - public char[][] getTokenizedPathChars() - { + public char[][] getTokenizedPathChars() { return tokenizedChar; } - public boolean startsWith( String string ) - { - return source.startsWith( string ); + public boolean startsWith(String string) { + return source.startsWith(string); } - static String[] tokenizePathToString( String path, String separator ) - { + static String[] tokenizePathToString(String path, String separator) { List ret = new ArrayList(); - StringTokenizer st = new StringTokenizer( path, separator ); - while ( st.hasMoreTokens() ) - { - ret.add( st.nextToken() ); + StringTokenizer st = new StringTokenizer(path, separator); + while (st.hasMoreTokens()) { + ret.add(st.nextToken()); } - return ret.toArray( new String[0] ); + return ret.toArray(new String[0]); } - static char[][] tokenizePathToCharArray( String path, String separator ) - { - String[] tokenizedName = tokenizePathToString( path, separator ); + static char[][] tokenizePathToCharArray(String path, String separator) { + String[] tokenizedName = tokenizePathToString(path, separator); char[][] tokenizedNameChar = new char[tokenizedName.length][]; - for ( int i = 0; i < tokenizedName.length; i++ ) - { + for (int i = 0; i < tokenizedName.length; i++) { tokenizedNameChar[i] = tokenizedName[i].toCharArray(); } return tokenizedNameChar; } - public static MatchPattern fromString( String source ) - { - return new MatchPattern( source, File.separator ); + public static MatchPattern fromString(String source) { + return new MatchPattern(source, File.separator); } - } diff --git a/src/main/java/org/codehaus/plexus/util/MatchPatterns.java b/src/main/java/org/codehaus/plexus/util/MatchPatterns.java index 35f9ea22..fd36a9d8 100644 --- a/src/main/java/org/codehaus/plexus/util/MatchPatterns.java +++ b/src/main/java/org/codehaus/plexus/util/MatchPatterns.java @@ -9,88 +9,71 @@ * * @author Kristian Rosenvold */ -public class MatchPatterns -{ +public class MatchPatterns { private final MatchPattern[] patterns; - private MatchPatterns( MatchPattern[] patterns ) - { + private MatchPatterns(MatchPattern[] patterns) { this.patterns = patterns; } /** *

      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 * @return true if any of the supplied patterns match */ - public boolean matches( String name, boolean isCaseSensitive ) - { - String[] tokenized = MatchPattern.tokenizePathToString( name, File.separator ); - return matches( name, tokenized, isCaseSensitive ); + public boolean matches(String name, boolean isCaseSensitive) { + String[] tokenized = MatchPattern.tokenizePathToString(name, File.separator); + return matches(name, tokenized, isCaseSensitive); } - public boolean matches( String name, String[] tokenizedName, boolean isCaseSensitive ) - { + public boolean matches(String name, String[] tokenizedName, boolean isCaseSensitive) { char[][] tokenizedNameChar = new char[tokenizedName.length][]; - for ( int i = 0; i < tokenizedName.length; i++ ) - { + for (int i = 0; i < tokenizedName.length; i++) { tokenizedNameChar[i] = tokenizedName[i].toCharArray(); } return matches(name, tokenizedNameChar, isCaseSensitive); } - public boolean matches(String name, char[][] tokenizedNameChar, boolean isCaseSensitive) - { - for ( MatchPattern pattern : patterns ) - { - if ( pattern.matchPath( name, tokenizedNameChar, isCaseSensitive ) ) - { + public boolean matches(String name, char[][] tokenizedNameChar, boolean isCaseSensitive) { + for (MatchPattern pattern : patterns) { + if (pattern.matchPath(name, tokenizedNameChar, isCaseSensitive)) { return true; } } return false; } - public boolean matchesPatternStart( String name, boolean isCaseSensitive ) - { - for ( MatchPattern includesPattern : patterns ) - { - if ( includesPattern.matchPatternStart( name, isCaseSensitive ) ) - { + public boolean matchesPatternStart(String name, boolean isCaseSensitive) { + for (MatchPattern includesPattern : patterns) { + if (includesPattern.matchPatternStart(name, isCaseSensitive)) { return true; } } return false; } - public static MatchPatterns from( String... sources ) - { + public static MatchPatterns from(String... sources) { final int length = sources.length; MatchPattern[] result = new MatchPattern[length]; - for ( int i = 0; i < length; i++ ) - { - result[i] = MatchPattern.fromString( sources[i] ); + for (int i = 0; i < length; i++) { + result[i] = MatchPattern.fromString(sources[i]); } - return new MatchPatterns( result ); + return new MatchPatterns(result); } - public static MatchPatterns from( Iterable strings ) - { - return new MatchPatterns( getMatchPatterns( strings ) ); + public static MatchPatterns from(Iterable strings) { + return new MatchPatterns(getMatchPatterns(strings)); } - private static MatchPattern[] getMatchPatterns( Iterable items ) - { + private static MatchPattern[] getMatchPatterns(Iterable items) { List result = new ArrayList(); - for ( String string : items ) - { - result.add( MatchPattern.fromString( string ) ); + for (String string : items) { + result.add(MatchPattern.fromString(string)); } - return result.toArray( new MatchPattern[0] ); + return result.toArray(new MatchPattern[0]); } - } diff --git a/src/main/java/org/codehaus/plexus/util/NioFiles.java b/src/main/java/org/codehaus/plexus/util/NioFiles.java index eb62bac7..d7a00a78 100644 --- a/src/main/java/org/codehaus/plexus/util/NioFiles.java +++ b/src/main/java/org/codehaus/plexus/util/NioFiles.java @@ -30,74 +30,57 @@ /** * Encapsulates use of java7 features, exposing mostly backward compatible types */ -@SuppressWarnings( "Since15" ) -public class NioFiles -{ - public static boolean isSymbolicLink( File file ) - { - return Files.isSymbolicLink( file.toPath() ); +@SuppressWarnings("Since15") +public class NioFiles { + public static boolean isSymbolicLink(File file) { + return Files.isSymbolicLink(file.toPath()); } - public static void chmod( File file, int mode ) - throws IOException - { + public static void chmod(File file, int mode) throws IOException { Path path = file.toPath(); - if ( !Files.isSymbolicLink( path ) ) - { - Files.setPosixFilePermissions( path, getPermissions( mode ) ); + if (!Files.isSymbolicLink(path)) { + Files.setPosixFilePermissions(path, getPermissions(mode)); } } - @SuppressWarnings( { "OctalInteger", "MagicNumber" } ) - private static Set getPermissions( int mode ) - { + @SuppressWarnings({"OctalInteger", "MagicNumber"}) + private static Set getPermissions(int mode) { Set perms = new HashSet<>(); // add owners permission - if ( ( mode & 0400 ) > 0 ) - { - perms.add( PosixFilePermission.OWNER_READ ); + if ((mode & 0400) > 0) { + perms.add(PosixFilePermission.OWNER_READ); } - if ( ( mode & 0200 ) > 0 ) - { - perms.add( PosixFilePermission.OWNER_WRITE ); + if ((mode & 0200) > 0) { + perms.add(PosixFilePermission.OWNER_WRITE); } - if ( ( mode & 0100 ) > 0 ) - { - perms.add( PosixFilePermission.OWNER_EXECUTE ); + if ((mode & 0100) > 0) { + perms.add(PosixFilePermission.OWNER_EXECUTE); } // add group permissions - if ( ( mode & 0040 ) > 0 ) - { - perms.add( PosixFilePermission.GROUP_READ ); + if ((mode & 0040) > 0) { + perms.add(PosixFilePermission.GROUP_READ); } - if ( ( mode & 0020 ) > 0 ) - { - perms.add( PosixFilePermission.GROUP_WRITE ); + if ((mode & 0020) > 0) { + perms.add(PosixFilePermission.GROUP_WRITE); } - if ( ( mode & 0010 ) > 0 ) - { - perms.add( PosixFilePermission.GROUP_EXECUTE ); + if ((mode & 0010) > 0) { + perms.add(PosixFilePermission.GROUP_EXECUTE); } // add others permissions - if ( ( mode & 0004 ) > 0 ) - { - perms.add( PosixFilePermission.OTHERS_READ ); + if ((mode & 0004) > 0) { + perms.add(PosixFilePermission.OTHERS_READ); } - if ( ( mode & 0002 ) > 0 ) - { - perms.add( PosixFilePermission.OTHERS_WRITE ); + if ((mode & 0002) > 0) { + perms.add(PosixFilePermission.OTHERS_WRITE); } - if ( ( mode & 0001 ) > 0 ) - { - perms.add( PosixFilePermission.OTHERS_EXECUTE ); + if ((mode & 0001) > 0) { + perms.add(PosixFilePermission.OTHERS_EXECUTE); } return perms; } - public static long getLastModified( File file ) - throws IOException - { - BasicFileAttributes basicFileAttributes = Files.readAttributes( file.toPath(), BasicFileAttributes.class ); + public static long getLastModified(File file) throws IOException { + BasicFileAttributes basicFileAttributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class); return basicFileAttributes.lastModifiedTime().toMillis(); } @@ -108,38 +91,30 @@ public static long getLastModified( File file ) * @return A file that is the target of the symlink * @throws java.io.IOException io issue */ - - public static File readSymbolicLink( File symlink ) - throws IOException - { - Path path = Files.readSymbolicLink( symlink.toPath() ); + public static File readSymbolicLink(File symlink) throws IOException { + Path path = Files.readSymbolicLink(symlink.toPath()); return path.toFile(); } - public static File createSymbolicLink( File symlink, File target ) - throws IOException - { + public static File createSymbolicLink(File symlink, File target) throws IOException { Path link = symlink.toPath(); - if ( Files.exists( link, LinkOption.NOFOLLOW_LINKS ) ) - { - Files.delete( link ); + if (Files.exists(link, LinkOption.NOFOLLOW_LINKS)) { + Files.delete(link); } - link = Files.createSymbolicLink( link, target.toPath() ); + link = Files.createSymbolicLink(link, target.toPath()); return link.toFile(); } - public static boolean deleteIfExists( File file ) - throws IOException - { - return Files.deleteIfExists( file.toPath() ); + public static boolean deleteIfExists(File file) throws IOException { + return Files.deleteIfExists(file.toPath()); } - public static File copy( File source, File target ) - throws IOException - { - Path copy = Files.copy( source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING, - StandardCopyOption.COPY_ATTRIBUTES ); + public static File copy(File source, File target) throws IOException { + Path copy = Files.copy( + source.toPath(), + target.toPath(), + StandardCopyOption.REPLACE_EXISTING, + StandardCopyOption.COPY_ATTRIBUTES); return copy.toFile(); } - } diff --git a/src/main/java/org/codehaus/plexus/util/Os.java b/src/main/java/org/codehaus/plexus/util/Os.java index b4ed2882..95b29cb6 100644 --- a/src/main/java/org/codehaus/plexus/util/Os.java +++ b/src/main/java/org/codehaus/plexus/util/Os.java @@ -67,8 +67,7 @@ * @since 1.0 * */ -public class Os -{ +public class Os { // define the families for easier reference public static final String FAMILY_DOS = "dos"; @@ -96,13 +95,13 @@ public class Os private static final Set validFamilies = setValidFamilies(); // get the current info - private static final String PATH_SEP = System.getProperty( "path.separator" ); + private static final String PATH_SEP = System.getProperty("path.separator"); - public static final String OS_NAME = System.getProperty( "os.name" ).toLowerCase( Locale.US ); + public static final String OS_NAME = System.getProperty("os.name").toLowerCase(Locale.US); - public static final String OS_ARCH = System.getProperty( "os.arch" ).toLowerCase( Locale.US ); + public static final String OS_ARCH = System.getProperty("os.arch").toLowerCase(Locale.US); - public static final String OS_VERSION = System.getProperty( "os.version" ).toLowerCase( Locale.US ); + public static final String OS_VERSION = System.getProperty("os.version").toLowerCase(Locale.US); // Make sure this method is called after static fields it depends on have been set! public static final String OS_FAMILY = getOsFamily(); @@ -118,44 +117,40 @@ public class Os /** * Default constructor */ - public Os() - { - } + public Os() {} /** * Constructor that sets the family attribute - * + * * @param family a String value */ - public Os( String family ) - { - setFamily( family ); + public Os(String family) { + setFamily(family); } /** * Initializes the set of valid families. */ - private static Set setValidFamilies() - { + private static Set setValidFamilies() { Set valid = new HashSet(); - valid.add( FAMILY_DOS ); - valid.add( FAMILY_MAC ); - valid.add( FAMILY_NETWARE ); - valid.add( FAMILY_OS2 ); - valid.add( FAMILY_TANDEM ); - valid.add( FAMILY_UNIX ); - valid.add( FAMILY_WINDOWS ); - valid.add( FAMILY_WIN9X ); - valid.add( FAMILY_ZOS ); - valid.add( FAMILY_OS400 ); - valid.add( FAMILY_OPENVMS ); + valid.add(FAMILY_DOS); + valid.add(FAMILY_MAC); + valid.add(FAMILY_NETWARE); + valid.add(FAMILY_OS2); + valid.add(FAMILY_TANDEM); + valid.add(FAMILY_UNIX); + valid.add(FAMILY_WINDOWS); + valid.add(FAMILY_WIN9X); + valid.add(FAMILY_ZOS); + valid.add(FAMILY_OS400); + valid.add(FAMILY_OPENVMS); return valid; } /** * Sets the desired OS family type - * + * * @param f The OS family type desired
      * Possible values: *
        @@ -172,39 +167,35 @@ private static Set setValidFamilies() *
      • openvms
      • *
      */ - public void setFamily( String f ) - { - family = f.toLowerCase( Locale.US ); + public void setFamily(String f) { + family = f.toLowerCase(Locale.US); } /** * Sets the desired OS name - * + * * @param name The OS name */ - public void setName( String name ) - { - this.name = name.toLowerCase( Locale.US ); + public void setName(String name) { + this.name = name.toLowerCase(Locale.US); } /** * Sets the desired OS architecture - * + * * @param arch The OS architecture */ - public void setArch( String arch ) - { - this.arch = arch.toLowerCase( Locale.US ); + public void setArch(String arch) { + this.arch = arch.toLowerCase(Locale.US); } /** * Sets the desired OS version - * + * * @param version The OS version */ - public void setVersion( String version ) - { - this.version = version.toLowerCase( Locale.US ); + public void setVersion(String version) { + this.version = version.toLowerCase(Locale.US); } /** @@ -213,64 +204,58 @@ public void setVersion( String version ) * @see Os#setFamily(String) * @throws Exception any errir */ - public boolean eval() - throws Exception - { - return isOs( family, name, arch, version ); + public boolean eval() throws Exception { + return isOs(family, name, arch, version); } /** * Determines if the current OS matches the given OS family. - * + * * @param family the family to check for * @return true if the OS matches * @since 1.0 */ - public static boolean isFamily( String family ) - { - return isOs( family, null, null, null ); + public static boolean isFamily(String family) { + return isOs(family, null, null, null); } /** * Determines if the current OS matches the given OS name. - * + * * @param name the OS name to check for * @return true if the OS matches * @since 1.0 */ - public static boolean isName( String name ) - { - return isOs( null, name, null, null ); + public static boolean isName(String name) { + return isOs(null, name, null, null); } /** * Determines if the current OS matches the given OS architecture. - * + * * @param arch the OS architecture to check for * @return true if the OS matches * @since 1.0 */ - public static boolean isArch( String arch ) - { - return isOs( null, null, arch, null ); + public static boolean isArch(String arch) { + return isOs(null, null, arch, null); } /** * Determines if the current OS matches the given OS version. - * + * * @param version the OS version to check for * @return true if the OS matches * @since 1.0 */ - public static boolean isVersion( String version ) - { - return isOs( null, null, null, version ); + public static boolean isVersion(String version) { + return isOs(null, null, null, version); } /** * Determines if the current OS matches the given OS family, name, architecture and version. The name, architecture * and version are compared to the System properties os.name, os.version and os.arch in a case-independent way. - * + * * @param family The OS family * @param name The OS name * @param arch The OS architecture @@ -278,84 +263,61 @@ public static boolean isVersion( String version ) * @return true if the OS matches * @since 1.0 */ - public static boolean isOs( String family, String name, String arch, String version ) - { + public static boolean isOs(String family, String name, String arch, String version) { boolean retValue = false; - if ( family != null || name != null || arch != null || version != null ) - { + if (family != null || name != null || arch != null || version != null) { boolean isFamily = true; boolean isName = true; boolean isArch = true; boolean isVersion = true; - if ( family != null ) - { - if ( family.equalsIgnoreCase( FAMILY_WINDOWS ) ) - { - isFamily = OS_NAME.contains( FAMILY_WINDOWS ); - } - else if ( family.equalsIgnoreCase( FAMILY_OS2 ) ) - { - isFamily = OS_NAME.contains( FAMILY_OS2 ); - } - else if ( family.equalsIgnoreCase( FAMILY_NETWARE ) ) - { - isFamily = OS_NAME.contains( FAMILY_NETWARE ); - } - else if ( family.equalsIgnoreCase( FAMILY_DOS ) ) - { - isFamily = PATH_SEP.equals( ";" ) && !isFamily( FAMILY_NETWARE ) && !isFamily( FAMILY_WINDOWS ) - && !isFamily( FAMILY_WIN9X ); - - } - else if ( family.equalsIgnoreCase( FAMILY_MAC ) ) - { - isFamily = OS_NAME.contains( FAMILY_MAC ); - } - else if ( family.equalsIgnoreCase( FAMILY_TANDEM ) ) - { - isFamily = OS_NAME.contains( "nonstop_kernel" ); - } - else if ( family.equalsIgnoreCase( FAMILY_UNIX ) ) - { - isFamily = PATH_SEP.equals( ":" ) && !isFamily( FAMILY_OPENVMS ) - && ( !isFamily( FAMILY_MAC ) || OS_NAME.endsWith( "x" ) ); - } - else if ( family.equalsIgnoreCase( FAMILY_WIN9X ) ) - { - isFamily = isFamily( FAMILY_WINDOWS ) && ( OS_NAME.contains( "95" ) || OS_NAME.contains( "98" ) - || OS_NAME.contains( "me" ) || OS_NAME.contains( "ce" ) ); - } - else if ( family.equalsIgnoreCase( FAMILY_ZOS ) ) - { - isFamily = OS_NAME.contains( FAMILY_ZOS ) || OS_NAME.contains( "os/390" ); - } - else if ( family.equalsIgnoreCase( FAMILY_OS400 ) ) - { - isFamily = OS_NAME.contains( FAMILY_OS400 ); - } - else if ( family.equalsIgnoreCase( FAMILY_OPENVMS ) ) - { - isFamily = OS_NAME.contains( FAMILY_OPENVMS ); - } - else - { - isFamily = OS_NAME.contains( family.toLowerCase( Locale.US ) ); + if (family != null) { + if (family.equalsIgnoreCase(FAMILY_WINDOWS)) { + isFamily = OS_NAME.contains(FAMILY_WINDOWS); + } else if (family.equalsIgnoreCase(FAMILY_OS2)) { + isFamily = OS_NAME.contains(FAMILY_OS2); + } else if (family.equalsIgnoreCase(FAMILY_NETWARE)) { + isFamily = OS_NAME.contains(FAMILY_NETWARE); + } else if (family.equalsIgnoreCase(FAMILY_DOS)) { + isFamily = PATH_SEP.equals(";") + && !isFamily(FAMILY_NETWARE) + && !isFamily(FAMILY_WINDOWS) + && !isFamily(FAMILY_WIN9X); + + } else if (family.equalsIgnoreCase(FAMILY_MAC)) { + isFamily = OS_NAME.contains(FAMILY_MAC); + } else if (family.equalsIgnoreCase(FAMILY_TANDEM)) { + isFamily = OS_NAME.contains("nonstop_kernel"); + } else if (family.equalsIgnoreCase(FAMILY_UNIX)) { + isFamily = PATH_SEP.equals(":") + && !isFamily(FAMILY_OPENVMS) + && (!isFamily(FAMILY_MAC) || OS_NAME.endsWith("x")); + } else if (family.equalsIgnoreCase(FAMILY_WIN9X)) { + isFamily = isFamily(FAMILY_WINDOWS) + && (OS_NAME.contains("95") + || OS_NAME.contains("98") + || OS_NAME.contains("me") + || OS_NAME.contains("ce")); + } else if (family.equalsIgnoreCase(FAMILY_ZOS)) { + isFamily = OS_NAME.contains(FAMILY_ZOS) || OS_NAME.contains("os/390"); + } else if (family.equalsIgnoreCase(FAMILY_OS400)) { + isFamily = OS_NAME.contains(FAMILY_OS400); + } else if (family.equalsIgnoreCase(FAMILY_OPENVMS)) { + isFamily = OS_NAME.contains(FAMILY_OPENVMS); + } else { + isFamily = OS_NAME.contains(family.toLowerCase(Locale.US)); } } - if ( name != null ) - { - isName = name.toLowerCase( Locale.US ).equals( OS_NAME ); + if (name != null) { + isName = name.toLowerCase(Locale.US).equals(OS_NAME); } - if ( arch != null ) - { - isArch = arch.toLowerCase( Locale.US ).equals( OS_ARCH ); + if (arch != null) { + isArch = arch.toLowerCase(Locale.US).equals(OS_ARCH); } - if ( version != null ) - { - isVersion = version.toLowerCase( Locale.US ).equals( OS_VERSION ); + if (version != null) { + isVersion = version.toLowerCase(Locale.US).equals(OS_VERSION); } retValue = isFamily && isName && isArch && isVersion; } @@ -364,28 +326,22 @@ else if ( family.equalsIgnoreCase( FAMILY_OPENVMS ) ) /** * Helper method to determine the current OS family. - * + * * @return name of current OS family. * @since 1.4.2 */ - private static String getOsFamily() - { + private static String getOsFamily() { // in case the order of static initialization is // wrong, get the list // safely. Set families = null; - if ( !validFamilies.isEmpty() ) - { + if (!validFamilies.isEmpty()) { families = validFamilies; - } - else - { + } else { families = setValidFamilies(); } - for ( String fam : families ) - { - if ( Os.isFamily( fam ) ) - { + for (String fam : families) { + if (Os.isFamily(fam)) { return fam; } } @@ -407,22 +363,20 @@ private static String getOsFamily() *
    • os/400
    • *
    • openvms
    • *
    - * + * * @param theFamily the family to check. * @return true if one of the valid families. * @since 1.4.2 */ - public static boolean isValidFamily( String theFamily ) - { - return ( validFamilies.contains( theFamily ) ); + public static boolean isValidFamily(String theFamily) { + return (validFamilies.contains(theFamily)); } /** * @return a copy of the valid families * @since 1.4.2 */ - public static Set getValidFamilies() - { - return new HashSet( validFamilies ); + public static Set getValidFamilies() { + return new HashSet(validFamilies); } } diff --git a/src/main/java/org/codehaus/plexus/util/PathTool.java b/src/main/java/org/codehaus/plexus/util/PathTool.java index b8392cdb..e6deab6b 100644 --- a/src/main/java/org/codehaus/plexus/util/PathTool.java +++ b/src/main/java/org/codehaus/plexus/util/PathTool.java @@ -27,17 +27,16 @@ * @author Vincent Siveton * */ -public class PathTool -{ +public class PathTool { /** *

    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.

    - * + * *
          * PathTool.getRelativePath( null, null )                                   = ""
          * PathTool.getRelativePath( null, "/usr/local/java/bin" )                  = ""
    @@ -53,17 +52,18 @@ public class PathTool
          *         slash. A zero-length string is returned if: the filename is not relative to the base directory,
          *         basedir is null or zero-length, or filename is null or zero-length.
          */
    -    public static final String getRelativePath( String basedir, String filename )
    -    {
    -        basedir = uppercaseDrive( basedir );
    -        filename = uppercaseDrive( filename );
    +    public static final String getRelativePath(String basedir, String filename) {
    +        basedir = uppercaseDrive(basedir);
    +        filename = uppercaseDrive(filename);
     
             /*
              * Verify the arguments and make sure the filename is relative to the base directory.
              */
    -        if ( basedir == null || basedir.length() == 0 || filename == null || filename.length() == 0
    -            || !filename.startsWith( basedir ) )
    -        {
    +        if (basedir == null
    +                || basedir.length() == 0
    +                || filename == null
    +                || filename.length() == 0
    +                || !filename.startsWith(basedir)) {
                 return "";
             }
     
    @@ -71,17 +71,17 @@ public static final String getRelativePath( String basedir, String filename )
              * Normalize the arguments. First, determine the file separator that is being used, then strip that off the end
              * of both the base directory and filename.
              */
    -        String separator = determineSeparator( filename );
    -        basedir = StringUtils.chompLast( basedir, separator );
    -        filename = StringUtils.chompLast( filename, separator );
    +        String separator = determineSeparator(filename);
    +        basedir = StringUtils.chompLast(basedir, separator);
    +        filename = StringUtils.chompLast(filename, separator);
     
             /*
              * Remove the base directory from the filename to end up with a relative filename (relative to the base
              * directory). This filename is then used to determine the relative path.
              */
    -        String relativeFilename = filename.substring( basedir.length() );
    +        String relativeFilename = filename.substring(basedir.length());
     
    -        return determineRelativePath( relativeFilename, separator );
    +        return determineRelativePath(relativeFilename, separator);
         }
     
         /**
    @@ -90,7 +90,7 @@ public static final String getRelativePath( String basedir, String filename )
          * 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.

    * * @param filename The filename to be parsed. @@ -98,12 +98,10 @@ public static final String getRelativePath( String basedir, String filename ) * string is returned if: filename is null or zero-length. * @see #getRelativeFilePath(String, String) */ - public static final String getRelativePath( String filename ) - { - filename = uppercaseDrive( filename ); + public static final String getRelativePath(String filename) { + filename = uppercaseDrive(filename); - if ( filename == null || filename.length() == 0 ) - { + if (filename == null || filename.length() == 0) { return ""; } @@ -112,23 +110,22 @@ public static final String getRelativePath( String filename ) * of the filename. Then, if the filename doesn't begin with a separator, add one. */ - String separator = determineSeparator( filename ); - filename = StringUtils.chompLast( filename, separator ); - if ( !filename.startsWith( separator ) ) - { + String separator = determineSeparator(filename); + filename = StringUtils.chompLast(filename, separator); + if (!filename.startsWith(separator)) { filename = separator + filename; } - return determineRelativePath( filename, separator ); + return determineRelativePath(filename, separator); } /** *

    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.

    - * + * *
          * PathTool.getDirectoryComponent( null )                                   = ""
          * PathTool.getDirectoryComponent( "/usr/local/java/bin" )                  = "/usr/local/java"
    @@ -140,18 +137,15 @@ public static final String getRelativePath( String filename )
          * @return The directory portion of the filename. If the filename does not contain a directory
          *         component, "." is returned.
          */
    -    public static final String getDirectoryComponent( String filename )
    -    {
    -        if ( filename == null || filename.length() == 0 )
    -        {
    +    public static final String getDirectoryComponent(String filename) {
    +        if (filename == null || filename.length() == 0) {
                 return "";
             }
     
    -        String separator = determineSeparator( filename );
    -        String directory = StringUtils.chomp( filename, separator );
    +        String separator = determineSeparator(filename);
    +        String directory = StringUtils.chomp(filename, separator);
     
    -        if ( filename.equals( directory ) )
    -        {
    +        if (filename.equals(directory)) {
                 return ".";
             }
     
    @@ -160,7 +154,7 @@ public static final String getDirectoryComponent( String filename )
     
         /**
          * Calculates the appropriate link given the preferred link and the relativePath of the document.
    -     * 
    +     *
          * 
          * PathTool.calculateLink( "/index.html", "../.." )                                        = "../../index.html"
          * PathTool.calculateLink( "http://plexus.codehaus.org/plexus-utils/index.html", "../.." ) = "http://plexus.codehaus.org/plexus-utils/index.html"
    @@ -173,53 +167,43 @@ public static final String getDirectoryComponent( String filename )
          * @param relativePath relative
          * @return String
          */
    -    public static final String calculateLink( String link, String relativePath )
    -    {
    -        if ( link == null )
    -        {
    +    public static final String calculateLink(String link, String relativePath) {
    +        if (link == null) {
                 link = "";
             }
    -        if ( relativePath == null )
    -        {
    +        if (relativePath == null) {
                 relativePath = "";
             }
             // This must be some historical feature
    -        if ( link.startsWith( "/site/" ) )
    -        {
    -            return link.substring( 5 );
    +        if (link.startsWith("/site/")) {
    +            return link.substring(5);
             }
     
             // Allows absolute links in nav-bars etc
    -        if ( link.startsWith( "/absolute/" ) )
    -        {
    -            return link.substring( 10 );
    +        if (link.startsWith("/absolute/")) {
    +            return link.substring(10);
             }
     
             // This traps urls like http://
    -        if ( link.contains( ":" ) )
    -        {
    +        if (link.contains(":")) {
                 return link;
             }
     
             // If relativepath is current directory, just pass the link through
    -        if ( StringUtils.equals( relativePath, "." ) )
    -        {
    -            if ( link.startsWith( "/" ) )
    -            {
    -                return link.substring( 1 );
    +        if (StringUtils.equals(relativePath, ".")) {
    +            if (link.startsWith("/")) {
    +                return link.substring(1);
                 }
     
                 return link;
             }
     
             // If we don't do this, you can end up with ..//bob.html rather than ../bob.html
    -        if ( relativePath.endsWith( "/" ) && link.startsWith( "/" ) )
    -        {
    -            return relativePath + "." + link.substring( 1 );
    +        if (relativePath.endsWith("/") && link.startsWith("/")) {
    +            return relativePath + "." + link.substring(1);
             }
     
    -        if ( relativePath.endsWith( "/" ) || link.startsWith( "/" ) )
    -        {
    +        if (relativePath.endsWith("/") || link.startsWith("/")) {
                 return relativePath + link;
             }
     
    @@ -228,7 +212,7 @@ public static final String calculateLink( String link, String relativePath )
     
         /**
          * This method can calculate the relative path between two paths on a web site.
    -     * 
    +     *
          * 
          * PathTool.getRelativeWebPath( null, null )                                          = ""
          * PathTool.getRelativeWebPath( null, "http://plexus.codehaus.org/" )                 = ""
    @@ -243,17 +227,14 @@ public static final String calculateLink( String link, String relativePath )
          * @param newPath second path
          * @return a relative web path from oldPath.
          */
    -    public static final String getRelativeWebPath( final String oldPath, final String newPath )
    -    {
    -        if ( StringUtils.isEmpty( oldPath ) || StringUtils.isEmpty( newPath ) )
    -        {
    +    public static final String getRelativeWebPath(final String oldPath, final String newPath) {
    +        if (StringUtils.isEmpty(oldPath) || StringUtils.isEmpty(newPath)) {
                 return "";
             }
     
    -        String resultPath = buildRelativePath( newPath, oldPath, '/' );
    +        String resultPath = buildRelativePath(newPath, oldPath, '/');
     
    -        if ( newPath.endsWith( "/" ) && !resultPath.endsWith( "/" ) )
    -        {
    +        if (newPath.endsWith("/") && !resultPath.endsWith("/")) {
                 return resultPath + "/";
             }
     
    @@ -262,7 +243,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.
    -     * 
    +     *
          * 
          * PathTool.getRelativeFilePath( null, null )                                   = ""
          * PathTool.getRelativeFilePath( null, "/usr/local/java/bin" )                  = ""
    @@ -275,66 +256,57 @@ public static final String getRelativeWebPath( final String oldPath, final Strin
          * PathTool.getRelativeFilePath( "/usr/local/", "/bin" )                        = "../../bin"
          * PathTool.getRelativeFilePath( "/bin", "/usr/local/" )                        = "../usr/local"
          * 
    - * + * * Note: On Windows based system, the / character should be replaced by \ character. * * @param oldPath main path * @param newPath second path * @return a relative file path from oldPath. */ - public static final String getRelativeFilePath( final String oldPath, final String newPath ) - { - if ( StringUtils.isEmpty( oldPath ) || StringUtils.isEmpty( newPath ) ) - { + public static final String getRelativeFilePath(final String oldPath, final String newPath) { + if (StringUtils.isEmpty(oldPath) || StringUtils.isEmpty(newPath)) { return ""; } // normalise the path delimiters - String fromPath = new File( oldPath ).getPath(); - String toPath = new File( newPath ).getPath(); + String fromPath = new File(oldPath).getPath(); + String toPath = new File(newPath).getPath(); // strip any leading slashes if its a windows path - if ( toPath.matches( "^\\[a-zA-Z]:" ) ) - { - toPath = toPath.substring( 1 ); + if (toPath.matches("^\\[a-zA-Z]:")) { + toPath = toPath.substring(1); } - if ( fromPath.matches( "^\\[a-zA-Z]:" ) ) - { - fromPath = fromPath.substring( 1 ); + if (fromPath.matches("^\\[a-zA-Z]:")) { + fromPath = fromPath.substring(1); } // lowercase windows drive letters. - if ( fromPath.startsWith( ":", 1 ) ) - { - fromPath = Character.toLowerCase( fromPath.charAt( 0 ) ) + fromPath.substring( 1 ); + if (fromPath.startsWith(":", 1)) { + fromPath = Character.toLowerCase(fromPath.charAt(0)) + fromPath.substring(1); } - if ( toPath.startsWith( ":", 1 ) ) - { - toPath = Character.toLowerCase( toPath.charAt( 0 ) ) + toPath.substring( 1 ); + if (toPath.startsWith(":", 1)) { + toPath = Character.toLowerCase(toPath.charAt(0)) + toPath.substring(1); } // check for the presence of windows drives. No relative way of // traversing from one to the other. - if ( ( toPath.startsWith( ":", 1 ) && fromPath.startsWith( ":", 1 ) ) - && ( !toPath.substring( 0, 1 ).equals( fromPath.substring( 0, 1 ) ) ) ) - { + if ((toPath.startsWith(":", 1) && fromPath.startsWith(":", 1)) + && (!toPath.substring(0, 1).equals(fromPath.substring(0, 1)))) { // they both have drive path element but they dont match, no // relative path return null; } - if ( ( toPath.startsWith( ":", 1 ) && !fromPath.startsWith( ":", 1 ) ) - || ( !toPath.startsWith( ":", 1 ) && fromPath.startsWith( ":", 1 ) ) ) - { + if ((toPath.startsWith(":", 1) && !fromPath.startsWith(":", 1)) + || (!toPath.startsWith(":", 1) && fromPath.startsWith(":", 1))) { // one has a drive path element and the other doesnt, no relative // path. return null; } - String resultPath = buildRelativePath( toPath, fromPath, File.separatorChar ); + String resultPath = buildRelativePath(toPath, fromPath, File.separatorChar); - if ( newPath.endsWith( File.separator ) && !resultPath.endsWith( File.separator ) ) - { + if (newPath.endsWith(File.separator) && !resultPath.endsWith(File.separator)) { return resultPath + File.separator; } @@ -354,10 +326,8 @@ public static final String getRelativeFilePath( final String oldPath, final Stri * @return The relative path of the filename. This value is not terminated with a forward slash. A zero-length * string is returned if: the filename is zero-length. */ - private static final String determineRelativePath( String filename, String separator ) - { - if ( filename.length() == 0 ) - { + private static final String determineRelativePath(String filename, String separator) { + if (filename.length() == 0) { return ""; } @@ -365,9 +335,8 @@ private static final String determineRelativePath( String filename, String separ * Count the slashes in the relative filename, but exclude the leading slash. If the path has no slashes, then * the filename is relative to the current directory. */ - int slashCount = StringUtils.countMatches( filename, separator ) - 1; - if ( slashCount <= 0 ) - { + int slashCount = StringUtils.countMatches(filename, separator) - 1; + if (slashCount <= 0) { return "."; } @@ -376,15 +345,14 @@ private static final String determineRelativePath( String filename, String separ * directories. Thus, each slash represents a "../" in the relative path. */ StringBuilder sb = new StringBuilder(); - for ( int i = 0; i < slashCount; i++ ) - { - sb.append( "../" ); + for (int i = 0; i < slashCount; i++) { + sb.append("../"); } /* * Finally, return the relative path but strip the trailing slash to mimic Anakia's behavior. */ - return StringUtils.chop( sb.toString() ); + return StringUtils.chop(sb.toString()); } /** @@ -394,10 +362,9 @@ private static final String determineRelativePath( String filename, String separ * @param filename The filename parsed to determine the file separator. * @return The file separator used within filename. This value is either a forward or backward slash. */ - private static final String determineSeparator( String filename ) - { - int forwardCount = StringUtils.countMatches( filename, "/" ); - int backwardCount = StringUtils.countMatches( filename, "\\" ); + private static final String determineSeparator(String filename) { + int forwardCount = StringUtils.countMatches(filename, "/"); + int backwardCount = StringUtils.countMatches(filename, "\\"); return forwardCount >= backwardCount ? "/" : "\\"; } @@ -408,41 +375,31 @@ private static final String determineSeparator( String filename ) * @param path * @return String */ - static final String uppercaseDrive( String path ) - { - if ( path == null ) - { + static final String uppercaseDrive(String path) { + if (path == null) { return null; } - if ( path.length() >= 2 && path.charAt( 1 ) == ':' ) - { - path = Character.toUpperCase( path.charAt( 0 ) ) + path.substring( 1 ); + if (path.length() >= 2 && path.charAt(1) == ':') { + path = Character.toUpperCase(path.charAt(0)) + path.substring(1); } return path; } - private static final String buildRelativePath( String toPath, String fromPath, final char separatorChar ) - { + private static final String buildRelativePath(String toPath, String fromPath, final char separatorChar) { // use tokeniser to traverse paths and for lazy checking - StringTokenizer toTokeniser = new StringTokenizer( toPath, String.valueOf( separatorChar ) ); - StringTokenizer fromTokeniser = new StringTokenizer( fromPath, String.valueOf( separatorChar ) ); + StringTokenizer toTokeniser = new StringTokenizer(toPath, String.valueOf(separatorChar)); + StringTokenizer fromTokeniser = new StringTokenizer(fromPath, String.valueOf(separatorChar)); int count = 0; // walk along the to path looking for divergence from the from path - while ( toTokeniser.hasMoreTokens() && fromTokeniser.hasMoreTokens() ) - { - if ( separatorChar == '\\' ) - { - if ( !fromTokeniser.nextToken().equalsIgnoreCase( toTokeniser.nextToken() ) ) - { + while (toTokeniser.hasMoreTokens() && fromTokeniser.hasMoreTokens()) { + if (separatorChar == '\\') { + if (!fromTokeniser.nextToken().equalsIgnoreCase(toTokeniser.nextToken())) { break; } - } - else - { - if ( !fromTokeniser.nextToken().equals( toTokeniser.nextToken() ) ) - { + } else { + if (!fromTokeniser.nextToken().equals(toTokeniser.nextToken())) { break; } } @@ -453,11 +410,10 @@ private static final String buildRelativePath( String toPath, String fromPath, f // reinitialise the tokenisers to count positions to retrieve the // gobbled token - toTokeniser = new StringTokenizer( toPath, String.valueOf( separatorChar ) ); - fromTokeniser = new StringTokenizer( fromPath, String.valueOf( separatorChar ) ); + toTokeniser = new StringTokenizer(toPath, String.valueOf(separatorChar)); + fromTokeniser = new StringTokenizer(fromPath, String.valueOf(separatorChar)); - while ( count-- > 0 ) - { + while (count-- > 0) { fromTokeniser.nextToken(); toTokeniser.nextToken(); } @@ -465,30 +421,25 @@ private static final String buildRelativePath( String toPath, String fromPath, f String relativePath = ""; // add back refs for the rest of from location. - while ( fromTokeniser.hasMoreTokens() ) - { + while (fromTokeniser.hasMoreTokens()) { fromTokeniser.nextToken(); relativePath += ".."; - if ( fromTokeniser.hasMoreTokens() ) - { + if (fromTokeniser.hasMoreTokens()) { relativePath += separatorChar; } } - if ( relativePath.length() != 0 && toTokeniser.hasMoreTokens() ) - { + if (relativePath.length() != 0 && toTokeniser.hasMoreTokens()) { relativePath += separatorChar; } // add fwd fills for whatevers left of newPath. - while ( toTokeniser.hasMoreTokens() ) - { + while (toTokeniser.hasMoreTokens()) { relativePath += toTokeniser.nextToken(); - if ( toTokeniser.hasMoreTokens() ) - { + if (toTokeniser.hasMoreTokens()) { relativePath += separatorChar; } } diff --git a/src/main/java/org/codehaus/plexus/util/PropertyUtils.java b/src/main/java/org/codehaus/plexus/util/PropertyUtils.java index cee5cd25..3aba1017 100644 --- a/src/main/java/org/codehaus/plexus/util/PropertyUtils.java +++ b/src/main/java/org/codehaus/plexus/util/PropertyUtils.java @@ -1,7 +1,5 @@ package org.codehaus.plexus.util; -import java.util.Objects; - /* * Copyright The Codehaus Foundation. * @@ -17,13 +15,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -import java.util.Properties; import java.io.File; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.net.URL; import java.nio.file.Files; +import java.util.Objects; +import java.util.Properties; /** * Static methods to create Properties loaded from various sources. @@ -31,36 +29,27 @@ * @author Jason van Zyl * @author Michal Maczka */ -public class PropertyUtils -{ +public class PropertyUtils { - public static Properties loadProperties( final URL url ) - throws IOException - { - return loadProperties( Objects.requireNonNull( url, "url" ).openStream() ); + public static Properties loadProperties(final URL url) throws IOException { + return loadProperties(Objects.requireNonNull(url, "url").openStream()); } - public static Properties loadProperties( final File file ) - throws IOException - { - return loadProperties( Files.newInputStream( Objects.requireNonNull( file, "file" ).toPath() ) ); + public static Properties loadProperties(final File file) throws IOException { + return loadProperties( + Files.newInputStream(Objects.requireNonNull(file, "file").toPath())); } - public static Properties loadProperties( final InputStream is ) - throws IOException - { + public static Properties loadProperties(final InputStream is) throws IOException { final Properties properties = new Properties(); - + // Make sure the properties stream is valid - if ( is != null ) - { - try ( InputStream in = is ) - { - properties.load( in ); + if (is != null) { + try (InputStream in = is) { + properties.load(in); } } return properties; } - } diff --git a/src/main/java/org/codehaus/plexus/util/ReaderFactory.java b/src/main/java/org/codehaus/plexus/util/ReaderFactory.java index a469a2c7..ea201f9f 100644 --- a/src/main/java/org/codehaus/plexus/util/ReaderFactory.java +++ b/src/main/java/org/codehaus/plexus/util/ReaderFactory.java @@ -17,7 +17,6 @@ */ import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -38,12 +37,11 @@ * * @since 1.4.3 */ -public class ReaderFactory -{ +public class ReaderFactory { /** * ISO Latin Alphabet #1, also known as ISO-LATIN-1. Every implementation of the Java platform is required to * support this character encoding. - * + * * @see Charset */ public static final String ISO_8859_1 = "ISO-8859-1"; @@ -51,7 +49,7 @@ public class ReaderFactory /** * Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block of the Unicode character set. Every * implementation of the Java platform is required to support this character encoding. - * + * * @see Charset */ public static final String US_ASCII = "US-ASCII"; @@ -60,7 +58,7 @@ public class ReaderFactory * Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either * order accepted on input, big-endian used on output). Every implementation of the Java platform is required to * support this character encoding. - * + * * @see Charset */ public static final String UTF_16 = "UTF-16"; @@ -68,7 +66,7 @@ public class ReaderFactory /** * Sixteen-bit Unicode Transformation Format, big-endian byte order. Every implementation of the Java platform is * required to support this character encoding. - * + * * @see Charset */ public static final String UTF_16BE = "UTF-16BE"; @@ -76,7 +74,7 @@ public class ReaderFactory /** * Sixteen-bit Unicode Transformation Format, little-endian byte order. Every implementation of the Java platform is * required to support this character encoding. - * + * * @see Charset */ public static final String UTF_16LE = "UTF-16LE"; @@ -84,7 +82,7 @@ public class ReaderFactory /** * Eight-bit Unicode Transformation Format. Every implementation of the Java platform is required to support this * character encoding. - * + * * @see Charset */ public static final String UTF_8 = "UTF-8"; @@ -92,7 +90,7 @@ public class ReaderFactory /** * The file.encoding System Property. */ - public static final String FILE_ENCODING = System.getProperty( "file.encoding" ); + public static final String FILE_ENCODING = System.getProperty("file.encoding"); /** * Create a new Reader with XML encoding detection rules. @@ -102,10 +100,8 @@ public class ReaderFactory * @throws IOException if any. * @see XmlStreamReader */ - public static XmlStreamReader newXmlReader( InputStream in ) - throws IOException - { - return new XmlStreamReader( in ); + public static XmlStreamReader newXmlReader(InputStream in) throws IOException { + return new XmlStreamReader(in); } /** @@ -116,10 +112,8 @@ public static XmlStreamReader newXmlReader( InputStream in ) * @throws IOException if any. * @see XmlStreamReader */ - public static XmlStreamReader newXmlReader( File file ) - throws IOException - { - return new XmlStreamReader( file ); + public static XmlStreamReader newXmlReader(File file) throws IOException { + return new XmlStreamReader(file); } /** @@ -130,10 +124,8 @@ public static XmlStreamReader newXmlReader( File file ) * @throws IOException if any. * @see XmlStreamReader */ - public static XmlStreamReader newXmlReader( URL url ) - throws IOException - { - return new XmlStreamReader( url ); + public static XmlStreamReader newXmlReader(URL url) throws IOException { + return new XmlStreamReader(url); } /** @@ -143,9 +135,8 @@ public static XmlStreamReader newXmlReader( URL url ) * @return a reader instance for the input stream using the default platform charset. * @see Charset#defaultCharset() */ - public static Reader newPlatformReader( InputStream in ) - { - return new InputStreamReader( in ); + public static Reader newPlatformReader(InputStream in) { + return new InputStreamReader(in); } /** @@ -156,10 +147,8 @@ public static Reader newPlatformReader( InputStream in ) * @throws IOException if any. * @see Charset#defaultCharset() */ - public static Reader newPlatformReader( File file ) - throws IOException - { - return Files.newBufferedReader( file.toPath() ); + public static Reader newPlatformReader(File file) throws IOException { + return Files.newBufferedReader(file.toPath()); } /** @@ -170,10 +159,8 @@ public static Reader newPlatformReader( File file ) * @throws IOException if any. * @see Charset#defaultCharset() */ - public static Reader newPlatformReader( URL url ) - throws IOException - { - return new InputStreamReader( url.openStream() ); + public static Reader newPlatformReader(URL url) throws IOException { + return new InputStreamReader(url.openStream()); } /** @@ -185,10 +172,8 @@ public static Reader newPlatformReader( URL url ) * @throws UnsupportedEncodingException if any. * @see Supported encodings */ - public static Reader newReader( InputStream in, String encoding ) - throws UnsupportedEncodingException - { - return new InputStreamReader( in, encoding ); + public static Reader newReader(InputStream in, String encoding) throws UnsupportedEncodingException { + return new InputStreamReader(in, encoding); } /** @@ -201,10 +186,8 @@ public static Reader newReader( InputStream in, String encoding ) * @throws IOException if any. * @see Supported encodings */ - public static Reader newReader( File file, String encoding ) - throws IOException - { - return new InputStreamReader( Files.newInputStream( file.toPath() ), encoding ); + public static Reader newReader(File file, String encoding) throws IOException { + return new InputStreamReader(Files.newInputStream(file.toPath()), encoding); } /** @@ -216,9 +199,7 @@ public static Reader newReader( File file, String encoding ) * @throws IOException if any. * @see Supported encodings */ - public static Reader newReader( URL url, String encoding ) - throws IOException - { - return new InputStreamReader( url.openStream(), encoding ); + public static Reader newReader(URL url, String encoding) throws IOException { + return new InputStreamReader(url.openStream(), encoding); } } diff --git a/src/main/java/org/codehaus/plexus/util/ReflectionUtils.java b/src/main/java/org/codehaus/plexus/util/ReflectionUtils.java index 3ebf3b2d..a0d3af64 100644 --- a/src/main/java/org/codehaus/plexus/util/ReflectionUtils.java +++ b/src/main/java/org/codehaus/plexus/util/ReflectionUtils.java @@ -16,59 +16,51 @@ * limitations under the License. */ +import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.lang.reflect.AccessibleObject; -import java.util.Map; -import java.util.HashMap; -import java.util.List; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * Operations on a class' fields and their setters. - * + * * @author Michal Maczka * @author Jesse McConnell * @author Trygve Laugstøl */ -public final class ReflectionUtils -{ +public final class ReflectionUtils { // ---------------------------------------------------------------------- // Field utils // ---------------------------------------------------------------------- - public static Field getFieldByNameIncludingSuperclasses( String fieldName, Class clazz ) - { + public static Field getFieldByNameIncludingSuperclasses(String fieldName, Class clazz) { Field retValue = null; - try - { - retValue = clazz.getDeclaredField( fieldName ); - } - catch ( NoSuchFieldException e ) - { + try { + retValue = clazz.getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { Class superclass = clazz.getSuperclass(); - if ( superclass != null ) - { - retValue = getFieldByNameIncludingSuperclasses( fieldName, superclass ); + if (superclass != null) { + retValue = getFieldByNameIncludingSuperclasses(fieldName, superclass); } } return retValue; } - public static List getFieldsIncludingSuperclasses( Class clazz ) - { - List fields = new ArrayList<>( Arrays.asList( clazz.getDeclaredFields() ) ); + public static List getFieldsIncludingSuperclasses(Class clazz) { + List fields = new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())); Class superclass = clazz.getSuperclass(); - if ( superclass != null ) - { - fields.addAll( getFieldsIncludingSuperclasses( superclass ) ); + if (superclass != null) { + fields.addAll(getFieldsIncludingSuperclasses(superclass)); } return fields; @@ -85,16 +77,13 @@ public static List getFieldsIncludingSuperclasses( Class clazz ) * @param clazz The class to find the method in. * @return null or the method found. */ - public static Method getSetter( String fieldName, Class clazz ) - { + public static Method getSetter(String fieldName, Class clazz) { Method[] methods = clazz.getMethods(); - fieldName = "set" + StringUtils.capitalizeFirstLetter( fieldName ); + fieldName = "set" + StringUtils.capitalizeFirstLetter(fieldName); - for ( Method method : methods ) - { - if ( method.getName().equals( fieldName ) && isSetter( method ) ) - { + for (Method method : methods) { + if (method.getName().equals(fieldName) && isSetter(method)) { return method; } } @@ -106,17 +95,14 @@ public static Method getSetter( String fieldName, Class clazz ) * @return all setters in the given class and super classes. * @param clazz the Class */ - public static List getSetters( Class clazz ) - { + public static List getSetters(Class clazz) { Method[] methods = clazz.getMethods(); List list = new ArrayList<>(); - for ( Method method : methods ) - { - if ( isSetter( method ) ) - { - list.add( method ); + for (Method method : methods) { + if (isSetter(method)) { + list.add(method); } } @@ -127,12 +113,10 @@ public static List getSetters( Class clazz ) * @param method the method * @return the class of the argument to the setter. Will throw an RuntimeException if the method isn't a setter. */ - public static Class getSetterType( Method method ) - { - if ( !isSetter( method ) ) - { - throw new RuntimeException( "The method " + method.getDeclaringClass().getName() + "." + method.getName() - + " is not a setter." ); + public static Class getSetterType(Method method) { + if (!isSetter(method)) { + throw new RuntimeException("The method " + + method.getDeclaringClass().getName() + "." + method.getName() + " is not a setter."); } return method.getParameterTypes()[0]; @@ -150,33 +134,30 @@ public static Class getSetterType( Method method ) * @param value see name * @throws IllegalAccessException if error */ - public static void setVariableValueInObject( Object object, String variable, Object value ) - throws IllegalAccessException - { - Field field = getFieldByNameIncludingSuperclasses( variable, object.getClass() ); + public static void setVariableValueInObject(Object object, String variable, Object value) + throws IllegalAccessException { + Field field = getFieldByNameIncludingSuperclasses(variable, object.getClass()); - field.setAccessible( true ); + field.setAccessible(true); - field.set( object, value ); + field.set(object, value); } /** * Generates a map of the fields and values on a given object, also pulls from superclasses - * + * * @param variable field name * @param object the object to generate the list of fields from * @return map containing the fields and their values * @throws IllegalAccessException cannot access */ - public static Object getValueIncludingSuperclasses( String variable, Object object ) - throws IllegalAccessException - { + public static Object getValueIncludingSuperclasses(String variable, Object object) throws IllegalAccessException { - Field field = getFieldByNameIncludingSuperclasses( variable, object.getClass() ); + Field field = getFieldByNameIncludingSuperclasses(variable, object.getClass()); - field.setAccessible( true ); + field.setAccessible(true); - return field.get( object ); + return field.get(object); } /** @@ -186,12 +167,11 @@ public static Object getValueIncludingSuperclasses( String variable, Object obje * @return map containing the fields and their values * @throws IllegalAccessException cannot access */ - public static Map getVariablesAndValuesIncludingSuperclasses( Object object ) - throws IllegalAccessException - { + public static Map getVariablesAndValuesIncludingSuperclasses(Object object) + throws IllegalAccessException { Map map = new HashMap<>(); - gatherVariablesAndValuesIncludingSuperclasses( object, map ); + gatherVariablesAndValuesIncludingSuperclasses(object, map); return map; } @@ -200,10 +180,11 @@ public static Map getVariablesAndValuesIncludingSuperclasses( Ob // Private // ---------------------------------------------------------------------- - public static boolean isSetter( Method method ) - { - return method.getReturnType().equals( Void.TYPE ) && // FIXME: needed /required? - !Modifier.isStatic( method.getModifiers() ) && method.getParameterTypes().length == 1; + public static boolean isSetter(Method method) { + return method.getReturnType().equals(Void.TYPE) + && // FIXME: needed /required? + !Modifier.isStatic(method.getModifiers()) + && method.getParameterTypes().length == 1; } /** @@ -212,15 +193,13 @@ public static boolean isSetter( Method method ) * @param object the object to generate the list of fields from * @param map to populate */ - private static void gatherVariablesAndValuesIncludingSuperclasses( Object object, Map map ) - throws IllegalAccessException - { + private static void gatherVariablesAndValuesIncludingSuperclasses(Object object, Map map) + throws IllegalAccessException { Class clazz = object.getClass(); - if ( Float.parseFloat( System.getProperty( "java.specification.version" ) ) >= 11 - && Class.class.getCanonicalName().equals( clazz.getCanonicalName() ) ) - { + if (Float.parseFloat(System.getProperty("java.specification.version")) >= 11 + && Class.class.getCanonicalName().equals(clazz.getCanonicalName())) { // Updating Class fields accessibility is forbidden on Java 16 (and throws warning from version 11) // No concrete use case to modify accessibility at this level return; @@ -228,19 +207,16 @@ private static void gatherVariablesAndValuesIncludingSuperclasses( Object object Field[] fields = clazz.getDeclaredFields(); - AccessibleObject.setAccessible( fields, true ); - - for ( Field field : fields ) - { - map.put( field.getName(), field.get( object ) ); + AccessibleObject.setAccessible(fields, true); + for (Field field : fields) { + map.put(field.getName(), field.get(object)); } Class superclass = clazz.getSuperclass(); - if ( !Object.class.equals( superclass ) ) - { - gatherVariablesAndValuesIncludingSuperclasses( superclass, map ); + if (!Object.class.equals(superclass)) { + gatherVariablesAndValuesIncludingSuperclasses(superclass, map); } } } diff --git a/src/main/java/org/codehaus/plexus/util/Scanner.java b/src/main/java/org/codehaus/plexus/util/Scanner.java index 20bf85fb..4d1701c1 100644 --- a/src/main/java/org/codehaus/plexus/util/Scanner.java +++ b/src/main/java/org/codehaus/plexus/util/Scanner.java @@ -22,8 +22,7 @@ /** * Scan a directory tree for files, with specified inclusions and exclusions. */ -public interface Scanner -{ +public interface Scanner { /** * Sets the list of include patterns to use. All '/' and '\' characters are replaced by @@ -34,7 +33,7 @@ public interface Scanner * @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. */ - void setIncludes( String[] includes ); + void setIncludes(String[] includes); /** * Sets the list of exclude patterns to use. All '/' and '\' characters are replaced by @@ -45,7 +44,7 @@ public interface Scanner * @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. */ - void setExcludes( String[] excludes ); + void setExcludes(String[] excludes); /** * Adds default exclusions to the current exclusions set. @@ -91,5 +90,5 @@ public interface Scanner * @param filenameComparator the Comparator instance to use * @since 3.3.0 */ - void setFilenameComparator( Comparator filenameComparator ); + void setFilenameComparator(Comparator filenameComparator); } diff --git a/src/main/java/org/codehaus/plexus/util/SelectorUtils.java b/src/main/java/org/codehaus/plexus/util/SelectorUtils.java index 234a92c5..f5122c78 100644 --- a/src/main/java/org/codehaus/plexus/util/SelectorUtils.java +++ b/src/main/java/org/codehaus/plexus/util/SelectorUtils.java @@ -63,7 +63,7 @@ *

    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.

    * * @author Arnout J. Kuiper ajkuiper@wxs.nl @@ -72,8 +72,7 @@ * * @since 1.5 */ -public final class SelectorUtils -{ +public final class SelectorUtils { public static final String PATTERN_HANDLER_PREFIX = "["; @@ -88,21 +87,18 @@ public final class SelectorUtils /** * Private Constructor */ - private SelectorUtils() - { - } + private SelectorUtils() {} /** * @return Retrieves the manager of the Singleton. */ - public static SelectorUtils getInstance() - { + public static SelectorUtils getInstance() { return instance; } /** *

    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.

    * @@ -110,14 +106,13 @@ public static SelectorUtils getInstance() * @param str The path to match, as a String. Must not be null. * @return whether or not a given path matches the start of a given pattern up to the first "**". */ - public static boolean matchPatternStart( String pattern, String str ) - { - return matchPatternStart( pattern, str, true ); + public static boolean matchPatternStart(String pattern, String str) { + return matchPatternStart(pattern, str, 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.

    * @@ -126,79 +121,67 @@ public static boolean matchPatternStart( String pattern, String str ) * @param isCaseSensitive Whether or not matching should be performed case sensitively. * @return whether or not a given path matches the start of a given pattern up to the first "**". */ - public static boolean matchPatternStart( String pattern, String str, boolean isCaseSensitive ) - { - if ( isRegexPrefixedPattern( pattern ) ) - { + public static boolean matchPatternStart(String pattern, String str, boolean isCaseSensitive) { + if (isRegexPrefixedPattern(pattern)) { // FIXME: ICK! But we can't do partial matches for regex, so we have to reserve judgement until we have // a file to deal with, or we can definitely say this is an exclusion... return true; - } - else - { - if ( isAntPrefixedPattern( pattern ) ) - { - pattern = pattern.substring( ANT_HANDLER_PREFIX.length(), - pattern.length() - PATTERN_HANDLER_SUFFIX.length() ); + } else { + if (isAntPrefixedPattern(pattern)) { + pattern = pattern.substring( + ANT_HANDLER_PREFIX.length(), pattern.length() - PATTERN_HANDLER_SUFFIX.length()); } - String altStr = str.replace( '\\', '/' ); + String altStr = str.replace('\\', '/'); - return matchAntPathPatternStart( pattern, str, File.separator, isCaseSensitive ) - || matchAntPathPatternStart( pattern, altStr, "/", isCaseSensitive ); + return matchAntPathPatternStart(pattern, str, File.separator, isCaseSensitive) + || matchAntPathPatternStart(pattern, altStr, "/", isCaseSensitive); } } - static boolean isAntPrefixedPattern( String pattern ) - { - return pattern.length() > ( ANT_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1 ) - && pattern.startsWith( ANT_HANDLER_PREFIX ) && pattern.endsWith( PATTERN_HANDLER_SUFFIX ); + static boolean isAntPrefixedPattern(String pattern) { + return pattern.length() > (ANT_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1) + && pattern.startsWith(ANT_HANDLER_PREFIX) + && pattern.endsWith(PATTERN_HANDLER_SUFFIX); } - @SuppressWarnings( "SimplifiableIfStatement" ) - static boolean matchAntPathPatternStart( MatchPattern pattern, String str, String separator, - boolean isCaseSensitive ) - { - if ( separatorPatternStartSlashMismatch( pattern, str, separator ) ) - { + @SuppressWarnings("SimplifiableIfStatement") + static boolean matchAntPathPatternStart( + MatchPattern pattern, String str, String separator, boolean isCaseSensitive) { + if (separatorPatternStartSlashMismatch(pattern, str, separator)) { return false; } - return matchAntPathPatternStart( pattern.getTokenizedPathString(), str, separator, isCaseSensitive ); + return matchAntPathPatternStart(pattern.getTokenizedPathString(), str, separator, isCaseSensitive); } - static boolean matchAntPathPatternStart( String pattern, String str, String separator, boolean isCaseSensitive ) - { + static boolean matchAntPathPatternStart(String pattern, String str, String separator, boolean isCaseSensitive) { // When str starts with a File.separator, pattern has to start with a // File.separator. // When pattern starts with a File.separator, str has to start with a // File.separator. - if ( separatorPatternStartSlashMismatch( pattern, str, separator ) ) - { + if (separatorPatternStartSlashMismatch(pattern, str, separator)) { return false; } - String[] patDirs = tokenizePathToString( pattern, separator ); - return matchAntPathPatternStart( patDirs, str, separator, isCaseSensitive ); + String[] patDirs = tokenizePathToString(pattern, separator); + return matchAntPathPatternStart(patDirs, str, separator, isCaseSensitive); } // When str starts with a File.separator, pattern has to start with a // File.separator. // When pattern starts with a File.separator, str has to start with a // File.separator. - private static boolean separatorPatternStartSlashMismatch( String pattern, String str, String separator ) - { - return str.startsWith( separator ) != pattern.startsWith( separator ); + private static boolean separatorPatternStartSlashMismatch(String pattern, String str, String separator) { + return str.startsWith(separator) != pattern.startsWith(separator); } - private static boolean separatorPatternStartSlashMismatch( MatchPattern matchPattern, String str, String separator ) - { - return str.startsWith( separator ) != matchPattern.startsWith( separator ); + private static boolean separatorPatternStartSlashMismatch(MatchPattern matchPattern, String str, String separator) { + return str.startsWith(separator) != matchPattern.startsWith(separator); } - static boolean matchAntPathPatternStart( String[] patDirs, String str, String separator, boolean isCaseSensitive ) - { - String[] strDirs = tokenizePathToString( str, separator ); + static boolean matchAntPathPatternStart(String[] patDirs, String str, String separator, boolean isCaseSensitive) { + String[] strDirs = tokenizePathToString(str, separator); int patIdxStart = 0; int patIdxEnd = patDirs.length - 1; @@ -206,15 +189,12 @@ static boolean matchAntPathPatternStart( String[] patDirs, String str, String se int strIdxEnd = strDirs.length - 1; // up to first '**' - while ( patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd ) - { + while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { String patDir = patDirs[patIdxStart]; - if ( patDir.equals( "**" ) ) - { + if (patDir.equals("**")) { break; } - if ( !match( patDir, strDirs[strIdxStart], isCaseSensitive ) ) - { + if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) { return false; } patIdxStart++; @@ -231,9 +211,8 @@ static boolean matchAntPathPatternStart( String[] patDirs, String str, String se * @param str The path to match, as a String. Must not be null. * @return true if the pattern matches against the string, or false otherwise. */ - public static boolean matchPath( String pattern, String str ) - { - return matchPath( pattern, str, true ); + public static boolean matchPath(String pattern, String str) { + return matchPath(pattern, str, true); } /** @@ -244,174 +223,140 @@ public static boolean matchPath( String pattern, String str ) * @param isCaseSensitive Whether or not matching should be performed case sensitively. * @return true if the pattern matches against the string, or false otherwise. */ - public static boolean matchPath( String pattern, String str, boolean isCaseSensitive ) - { - return matchPath( pattern, str, File.separator, isCaseSensitive ); + public static boolean matchPath(String pattern, String str, boolean isCaseSensitive) { + return matchPath(pattern, str, File.separator, isCaseSensitive); } - public static boolean matchPath( String pattern, String str, String separator, boolean isCaseSensitive ) - { - if ( isRegexPrefixedPattern( pattern ) ) - { - String localPattern = - pattern.substring( REGEX_HANDLER_PREFIX.length(), pattern.length() - PATTERN_HANDLER_SUFFIX.length() ); + public static boolean matchPath(String pattern, String str, String separator, boolean isCaseSensitive) { + if (isRegexPrefixedPattern(pattern)) { + String localPattern = pattern.substring( + REGEX_HANDLER_PREFIX.length(), pattern.length() - PATTERN_HANDLER_SUFFIX.length()); - return str.matches( localPattern ); - } - else - { - String localPattern = isAntPrefixedPattern( pattern ) - ? pattern.substring( ANT_HANDLER_PREFIX.length(), pattern.length() - PATTERN_HANDLER_SUFFIX.length() ) - : pattern; - final String osRelatedPath = toOSRelatedPath( str, separator ); - final String osRelatedPattern = toOSRelatedPath( localPattern, separator ); - return matchAntPathPattern( osRelatedPattern, osRelatedPath, separator, isCaseSensitive ); + return str.matches(localPattern); + } else { + String localPattern = isAntPrefixedPattern(pattern) + ? pattern.substring(ANT_HANDLER_PREFIX.length(), pattern.length() - PATTERN_HANDLER_SUFFIX.length()) + : pattern; + final String osRelatedPath = toOSRelatedPath(str, separator); + final String osRelatedPattern = toOSRelatedPath(localPattern, separator); + return matchAntPathPattern(osRelatedPattern, osRelatedPath, separator, isCaseSensitive); } } - private static String toOSRelatedPath( String pattern, String separator ) - { - if ( "/".equals( separator ) ) - { - return pattern.replace( "\\", separator ); + private static String toOSRelatedPath(String pattern, String separator) { + if ("/".equals(separator)) { + return pattern.replace("\\", separator); } - if ( "\\".equals( separator ) ) { - return pattern.replace( "/", separator ); + if ("\\".equals(separator)) { + return pattern.replace("/", separator); } return pattern; } - static boolean isRegexPrefixedPattern( String pattern ) - { - return pattern.length() > ( REGEX_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1 ) - && pattern.startsWith( REGEX_HANDLER_PREFIX ) && pattern.endsWith( PATTERN_HANDLER_SUFFIX ); + static boolean isRegexPrefixedPattern(String pattern) { + return pattern.length() > (REGEX_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1) + && pattern.startsWith(REGEX_HANDLER_PREFIX) + && pattern.endsWith(PATTERN_HANDLER_SUFFIX); } - static boolean matchAntPathPattern( MatchPattern matchPattern, String str, String separator, - boolean isCaseSensitive ) - { - if ( separatorPatternStartSlashMismatch( matchPattern, str, separator ) ) - { + static boolean matchAntPathPattern( + MatchPattern matchPattern, String str, String separator, boolean isCaseSensitive) { + if (separatorPatternStartSlashMismatch(matchPattern, str, separator)) { return false; } String[] patDirs = matchPattern.getTokenizedPathString(); - String[] strDirs = tokenizePathToString( str, separator ); - return matchAntPathPattern( patDirs, strDirs, isCaseSensitive ); + String[] strDirs = tokenizePathToString(str, separator); + return matchAntPathPattern(patDirs, strDirs, isCaseSensitive); } - static boolean matchAntPathPattern( String pattern, String str, String separator, boolean isCaseSensitive ) - { - if ( separatorPatternStartSlashMismatch( pattern, str, separator ) ) - { + static boolean matchAntPathPattern(String pattern, String str, String separator, boolean isCaseSensitive) { + if (separatorPatternStartSlashMismatch(pattern, str, separator)) { return false; } - String[] patDirs = tokenizePathToString( pattern, separator ); - String[] strDirs = tokenizePathToString( str, separator ); - return matchAntPathPattern( patDirs, strDirs, isCaseSensitive ); - + String[] patDirs = tokenizePathToString(pattern, separator); + String[] strDirs = tokenizePathToString(str, separator); + return matchAntPathPattern(patDirs, strDirs, isCaseSensitive); } - static boolean matchAntPathPattern( String[] patDirs, String[] strDirs, boolean isCaseSensitive ) - { + static boolean matchAntPathPattern(String[] patDirs, String[] strDirs, boolean isCaseSensitive) { int patIdxStart = 0; int patIdxEnd = patDirs.length - 1; int strIdxStart = 0; int strIdxEnd = strDirs.length - 1; // up to first '**' - while ( patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd ) - { + while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { String patDir = patDirs[patIdxStart]; - if ( patDir.equals( "**" ) ) - { + if (patDir.equals("**")) { break; } - if ( !match( patDir, strDirs[strIdxStart], isCaseSensitive ) ) - { + if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) { return false; } patIdxStart++; strIdxStart++; } - if ( strIdxStart > strIdxEnd ) - { + if (strIdxStart > strIdxEnd) { // String is exhausted - for ( int i = patIdxStart; i <= patIdxEnd; i++ ) - { - if ( !patDirs[i].equals( "**" ) ) - { + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (!patDirs[i].equals("**")) { return false; } } return true; - } - else - { - if ( patIdxStart > patIdxEnd ) - { + } else { + if (patIdxStart > patIdxEnd) { // String not exhausted, but pattern is. Failure. return false; } } // up to last '**' - while ( patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd ) - { + while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { String patDir = patDirs[patIdxEnd]; - if ( patDir.equals( "**" ) ) - { + if (patDir.equals("**")) { break; } - if ( !match( patDir, strDirs[strIdxEnd], isCaseSensitive ) ) - { + if (!match(patDir, strDirs[strIdxEnd], isCaseSensitive)) { return false; } patIdxEnd--; strIdxEnd--; } - if ( strIdxStart > strIdxEnd ) - { + if (strIdxStart > strIdxEnd) { // String is exhausted - for ( int i = patIdxStart; i <= patIdxEnd; i++ ) - { - if ( !patDirs[i].equals( "**" ) ) - { + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (!patDirs[i].equals("**")) { return false; } } return true; } - while ( patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd ) - { + while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) { int patIdxTmp = -1; - for ( int i = patIdxStart + 1; i <= patIdxEnd; i++ ) - { - if ( patDirs[i].equals( "**" ) ) - { + for (int i = patIdxStart + 1; i <= patIdxEnd; i++) { + if (patDirs[i].equals("**")) { patIdxTmp = i; break; } } - if ( patIdxTmp == patIdxStart + 1 ) - { + if (patIdxTmp == patIdxStart + 1) { // '**/**' situation, so skip one patIdxStart++; continue; } // Find the pattern between padIdxStart & padIdxTmp in str between // strIdxStart & strIdxEnd - int patLength = ( patIdxTmp - patIdxStart - 1 ); - int strLength = ( strIdxEnd - strIdxStart + 1 ); + int patLength = (patIdxTmp - patIdxStart - 1); + int strLength = (strIdxEnd - strIdxStart + 1); int foundIdx = -1; - strLoop: for ( int i = 0; i <= strLength - patLength; i++ ) - { - for ( int j = 0; j < patLength; j++ ) - { + strLoop: + for (int i = 0; i <= strLength - patLength; i++) { + for (int j = 0; j < patLength; j++) { String subPat = patDirs[patIdxStart + j + 1]; String subStr = strDirs[strIdxStart + i + j]; - if ( !match( subPat, subStr, isCaseSensitive ) ) - { + if (!match(subPat, subStr, isCaseSensitive)) { continue strLoop; } } @@ -420,8 +365,7 @@ static boolean matchAntPathPattern( String[] patDirs, String[] strDirs, boolean break; } - if ( foundIdx == -1 ) - { + if (foundIdx == -1) { return false; } @@ -429,10 +373,8 @@ static boolean matchAntPathPattern( String[] patDirs, String[] strDirs, boolean strIdxStart = foundIdx + patLength; } - for ( int i = patIdxStart; i <= patIdxEnd; i++ ) - { - if ( !patDirs[i].equals( "**" ) ) - { + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (!patDirs[i].equals("**")) { return false; } } @@ -440,107 +382,85 @@ static boolean matchAntPathPattern( String[] patDirs, String[] strDirs, boolean return true; } - static boolean matchAntPathPattern( char[][] patDirs, char[][] strDirs, boolean isCaseSensitive ) - { + static boolean matchAntPathPattern(char[][] patDirs, char[][] strDirs, boolean isCaseSensitive) { int patIdxStart = 0; int patIdxEnd = patDirs.length - 1; int strIdxStart = 0; int strIdxEnd = strDirs.length - 1; // up to first '**' - while ( patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd ) - { + while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { char[] patDir = patDirs[patIdxStart]; - if ( isDoubleStar( patDir ) ) - { + if (isDoubleStar(patDir)) { break; } - if ( !match( patDir, strDirs[strIdxStart], isCaseSensitive ) ) - { + if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) { return false; } patIdxStart++; strIdxStart++; } - if ( strIdxStart > strIdxEnd ) - { + if (strIdxStart > strIdxEnd) { // String is exhausted - for ( int i = patIdxStart; i <= patIdxEnd; i++ ) - { - if ( !isDoubleStar( patDirs[i] ) ) - { + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (!isDoubleStar(patDirs[i])) { return false; } } return true; - } - else - { - if ( patIdxStart > patIdxEnd ) - { + } else { + if (patIdxStart > patIdxEnd) { // String not exhausted, but pattern is. Failure. return false; } } // up to last '**' - while ( patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd ) - { + while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { char[] patDir = patDirs[patIdxEnd]; - if ( isDoubleStar( patDir ) ) - { + if (isDoubleStar(patDir)) { break; } - if ( !match( patDir, strDirs[strIdxEnd], isCaseSensitive ) ) - { + if (!match(patDir, strDirs[strIdxEnd], isCaseSensitive)) { return false; } patIdxEnd--; strIdxEnd--; } - if ( strIdxStart > strIdxEnd ) - { + if (strIdxStart > strIdxEnd) { // String is exhausted - for ( int i = patIdxStart; i <= patIdxEnd; i++ ) - { - if ( !isDoubleStar( patDirs[i] ) ) - { + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (!isDoubleStar(patDirs[i])) { return false; } } return true; } - while ( patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd ) - { + while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) { int patIdxTmp = -1; - for ( int i = patIdxStart + 1; i <= patIdxEnd; i++ ) - { - if ( isDoubleStar( patDirs[i] ) ) - { + for (int i = patIdxStart + 1; i <= patIdxEnd; i++) { + if (isDoubleStar(patDirs[i])) { patIdxTmp = i; break; } } - if ( patIdxTmp == patIdxStart + 1 ) - { + if (patIdxTmp == patIdxStart + 1) { // '**/**' situation, so skip one patIdxStart++; continue; } // Find the pattern between padIdxStart & padIdxTmp in str between // strIdxStart & strIdxEnd - int patLength = ( patIdxTmp - patIdxStart - 1 ); - int strLength = ( strIdxEnd - strIdxStart + 1 ); + int patLength = (patIdxTmp - patIdxStart - 1); + int strLength = (strIdxEnd - strIdxStart + 1); int foundIdx = -1; - strLoop: for ( int i = 0; i <= strLength - patLength; i++ ) - { - for ( int j = 0; j < patLength; j++ ) - { + strLoop: + for (int i = 0; i <= strLength - patLength; i++) { + for (int j = 0; j < patLength; j++) { char[] subPat = patDirs[patIdxStart + j + 1]; char[] subStr = strDirs[strIdxStart + i + j]; - if ( !match( subPat, subStr, isCaseSensitive ) ) - { + if (!match(subPat, subStr, isCaseSensitive)) { continue strLoop; } } @@ -549,8 +469,7 @@ static boolean matchAntPathPattern( char[][] patDirs, char[][] strDirs, boolean break; } - if ( foundIdx == -1 ) - { + if (foundIdx == -1) { return false; } @@ -558,10 +477,8 @@ static boolean matchAntPathPattern( char[][] patDirs, char[][] strDirs, boolean strIdxStart = foundIdx + patLength; } - for ( int i = patIdxStart; i <= patIdxEnd; i++ ) - { - if ( !isDoubleStar( patDirs[i] ) ) - { + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (!isDoubleStar(patDirs[i])) { return false; } } @@ -569,8 +486,7 @@ static boolean matchAntPathPattern( char[][] patDirs, char[][] strDirs, boolean return true; } - private static boolean isDoubleStar( char[] patDir ) - { + private static boolean isDoubleStar(char[] patDir) { return patDir != null && patDir.length == 2 && patDir[0] == '*' && patDir[1] == '*'; } @@ -583,9 +499,8 @@ private static boolean isDoubleStar( char[] patDir ) * @param str The string which must be matched against the pattern. Must not be null. * @return true if the string matches against the pattern, or false otherwise. */ - public static boolean match( String pattern, String str ) - { - return match( pattern, str, true ); + public static boolean match(String pattern, String str) { + return match(pattern, str, true); } /** @@ -598,15 +513,13 @@ public static boolean match( String pattern, String str ) * @param isCaseSensitive Whether or not matching should be performed case sensitively. * @return true if the string matches against the pattern, or false otherwise. */ - public static boolean match( String pattern, String str, boolean isCaseSensitive ) - { + public static boolean match(String pattern, String str, boolean isCaseSensitive) { char[] patArr = pattern.toCharArray(); char[] strArr = str.toCharArray(); - return match( patArr, strArr, isCaseSensitive ); + return match(patArr, strArr, isCaseSensitive); } - public static boolean match( char[] patArr, char[] strArr, boolean isCaseSensitive ) - { + public static boolean match(char[] patArr, char[] strArr, boolean isCaseSensitive) { int patIdxStart = 0; int patIdxEnd = patArr.length - 1; int strIdxStart = 0; @@ -614,56 +527,44 @@ public static boolean match( char[] patArr, char[] strArr, boolean isCaseSensiti char ch; boolean containsStar = false; - for ( char aPatArr : patArr ) - { - if ( aPatArr == '*' ) - { + for (char aPatArr : patArr) { + if (aPatArr == '*') { containsStar = true; break; } } - if ( !containsStar ) - { + if (!containsStar) { // No '*'s, so we make a shortcut - if ( patIdxEnd != strIdxEnd ) - { + if (patIdxEnd != strIdxEnd) { return false; // Pattern and string do not have the same size } - for ( int i = 0; i <= patIdxEnd; i++ ) - { + for (int i = 0; i <= patIdxEnd; i++) { ch = patArr[i]; - if ( ch != '?' && !equals( ch, strArr[i], isCaseSensitive ) ) - { + if (ch != '?' && !equals(ch, strArr[i], isCaseSensitive)) { return false; // Character mismatch } } return true; // String matches against pattern } - if ( patIdxEnd == 0 ) - { + if (patIdxEnd == 0) { return true; // Pattern contains only '*', which matches anything } // Process characters before first star - while ( ( ch = patArr[patIdxStart] ) != '*' && strIdxStart <= strIdxEnd ) - { - if ( ch != '?' && !equals( ch, strArr[strIdxStart], isCaseSensitive ) ) - { + while ((ch = patArr[patIdxStart]) != '*' && strIdxStart <= strIdxEnd) { + if (ch != '?' && !equals(ch, strArr[strIdxStart], isCaseSensitive)) { return false; // Character mismatch } patIdxStart++; strIdxStart++; } - if ( strIdxStart > strIdxEnd ) - { + if (strIdxStart > strIdxEnd) { // All characters in the string are used. Check if only '*'s are // left in the pattern. If so, we succeeded. Otherwise failure. - for ( int i = patIdxStart; i <= patIdxEnd; i++ ) - { - if ( patArr[i] != '*' ) - { + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (patArr[i] != '*') { return false; } } @@ -671,23 +572,18 @@ public static boolean match( char[] patArr, char[] strArr, boolean isCaseSensiti } // Process characters after last star - while ( ( ch = patArr[patIdxEnd] ) != '*' && strIdxStart <= strIdxEnd ) - { - if ( ch != '?' && !equals( ch, strArr[strIdxEnd], isCaseSensitive ) ) - { + while ((ch = patArr[patIdxEnd]) != '*' && strIdxStart <= strIdxEnd) { + if (ch != '?' && !equals(ch, strArr[strIdxEnd], isCaseSensitive)) { return false; // Character mismatch } patIdxEnd--; strIdxEnd--; } - if ( strIdxStart > strIdxEnd ) - { + if (strIdxStart > strIdxEnd) { // All characters in the string are used. Check if only '*'s are // left in the pattern. If so, we succeeded. Otherwise failure. - for ( int i = patIdxStart; i <= patIdxEnd; i++ ) - { - if ( patArr[i] != '*' ) - { + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (patArr[i] != '*') { return false; } } @@ -696,35 +592,29 @@ public static boolean match( char[] patArr, char[] strArr, boolean isCaseSensiti // process pattern between stars. padIdxStart and patIdxEnd point // always to a '*'. - while ( patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd ) - { + while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) { int patIdxTmp = -1; - for ( int i = patIdxStart + 1; i <= patIdxEnd; i++ ) - { - if ( patArr[i] == '*' ) - { + for (int i = patIdxStart + 1; i <= patIdxEnd; i++) { + if (patArr[i] == '*') { patIdxTmp = i; break; } } - if ( patIdxTmp == patIdxStart + 1 ) - { + if (patIdxTmp == patIdxStart + 1) { // Two stars next to each other, skip the first one. patIdxStart++; continue; } // Find the pattern between padIdxStart & padIdxTmp in str between // strIdxStart & strIdxEnd - int patLength = ( patIdxTmp - patIdxStart - 1 ); - int strLength = ( strIdxEnd - strIdxStart + 1 ); + int patLength = (patIdxTmp - patIdxStart - 1); + int strLength = (strIdxEnd - strIdxStart + 1); int foundIdx = -1; - strLoop: for ( int i = 0; i <= strLength - patLength; i++ ) - { - for ( int j = 0; j < patLength; j++ ) - { + strLoop: + for (int i = 0; i <= strLength - patLength; i++) { + for (int j = 0; j < patLength; j++) { ch = patArr[patIdxStart + j + 1]; - if ( ch != '?' && !equals( ch, strArr[strIdxStart + i + j], isCaseSensitive ) ) - { + if (ch != '?' && !equals(ch, strArr[strIdxStart + i + j], isCaseSensitive)) { continue strLoop; } } @@ -733,8 +623,7 @@ public static boolean match( char[] patArr, char[] strArr, boolean isCaseSensiti break; } - if ( foundIdx == -1 ) - { + if (foundIdx == -1) { return false; } @@ -744,10 +633,8 @@ public static boolean match( char[] patArr, char[] strArr, boolean isCaseSensiti // All characters in the string are used. Check if only '*'s are left // in the pattern. If so, we succeeded. Otherwise failure. - for ( int i = patIdxStart; i <= patIdxEnd; i++ ) - { - if ( patArr[i] != '*' ) - { + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (patArr[i] != '*') { return false; } } @@ -757,33 +644,27 @@ public static boolean match( char[] patArr, char[] strArr, boolean isCaseSensiti /** * Tests whether two characters are equal. */ - private static boolean equals( char c1, char c2, boolean isCaseSensitive ) - { - if ( c1 == c2 ) - { + private static boolean equals(char c1, char c2, boolean isCaseSensitive) { + if (c1 == c2) { return true; } - if ( !isCaseSensitive ) - { + if (!isCaseSensitive) { // NOTE: Try both upper case and lower case as done by String.equalsIgnoreCase() - if ( Character.toUpperCase( c1 ) == Character.toUpperCase( c2 ) - || Character.toLowerCase( c1 ) == Character.toLowerCase( c2 ) ) - { + if (Character.toUpperCase(c1) == Character.toUpperCase(c2) + || Character.toLowerCase(c1) == Character.toLowerCase(c2)) { return true; } } return false; } - private static String[] tokenizePathToString( String path, String separator ) - { + private static String[] tokenizePathToString(String path, String separator) { List ret = new ArrayList(); - StringTokenizer st = new StringTokenizer( path, separator ); - while ( st.hasMoreTokens() ) - { - ret.add( st.nextToken() ); + StringTokenizer st = new StringTokenizer(path, separator); + while (st.hasMoreTokens()) { + ret.add(st.nextToken()); } - return ret.toArray( new String[0] ); + return ret.toArray(new String[0]); } /** @@ -797,18 +678,14 @@ private static String[] tokenizePathToString( String path, String separator ) * @param granularity the amount in seconds of slack we will give in determining out of dateness * @return whether the target is out of date */ - public static boolean isOutOfDate( File src, File target, int granularity ) - { - if ( !src.exists() ) - { + public static boolean isOutOfDate(File src, File target, int granularity) { + if (!src.exists()) { return false; } - if ( !target.exists() ) - { + if (!target.exists()) { return true; } - if ( ( src.lastModified() - granularity ) > target.lastModified() ) - { + if ((src.lastModified() - granularity) > target.lastModified()) { return true; } return false; @@ -821,15 +698,12 @@ public static boolean isOutOfDate( File src, File target, int granularity ) * @param input a String to remove all whitespace. * @return a String that has had all whitespace removed. */ - public static String removeWhitespace( String input ) - { + public static String removeWhitespace(String input) { StringBuilder result = new StringBuilder(); - if ( input != null ) - { - StringTokenizer st = new StringTokenizer( input ); - while ( st.hasMoreTokens() ) - { - result.append( st.nextToken() ); + if (input != null) { + StringTokenizer st = new StringTokenizer(input); + while (st.hasMoreTokens()) { + result.append(st.nextToken()); } } return result.toString(); diff --git a/src/main/java/org/codehaus/plexus/util/StringInputStream.java b/src/main/java/org/codehaus/plexus/util/StringInputStream.java index ea1c46c8..1e3ca5f5 100644 --- a/src/main/java/org/codehaus/plexus/util/StringInputStream.java +++ b/src/main/java/org/codehaus/plexus/util/StringInputStream.java @@ -70,9 +70,7 @@ * {@link java.io.ByteArrayInputStream}. */ @Deprecated -public class StringInputStream - extends InputStream -{ +public class StringInputStream extends InputStream { /** Source string, stored as a StringReader */ private StringReader in; @@ -81,9 +79,8 @@ public class StringInputStream * * @param source The string to read from. Must not be null. */ - public StringInputStream( String source ) - { - in = new StringReader( source ); + public StringInputStream(String source) { + in = new StringReader(source); } /** @@ -94,9 +91,7 @@ public StringInputStream( String source ) * @exception IOException if the original StringReader fails to be read */ @Override - public int read() - throws IOException - { + public int read() throws IOException { return in.read(); } @@ -106,9 +101,7 @@ public int read() * @exception IOException if the original StringReader fails to be closed */ @Override - public void close() - throws IOException - { + public void close() throws IOException { in.close(); } @@ -118,15 +111,11 @@ public void close() * @param limit the maximum limit of bytes that can be read before the mark position becomes invalid */ @Override - public synchronized void mark( final int limit ) - { - try - { - in.mark( limit ); - } - catch ( IOException ioe ) - { - throw new RuntimeException( ioe.getMessage() ); + public synchronized void mark(final int limit) { + try { + in.mark(limit); + } catch (IOException ioe) { + throw new RuntimeException(ioe.getMessage()); } } @@ -136,9 +125,7 @@ public synchronized void mark( final int limit ) * @exception IOException if the StringReader fails to be reset */ @Override - public synchronized void reset() - throws IOException - { + public synchronized void reset() throws IOException { in.reset(); } @@ -146,8 +133,7 @@ public synchronized void reset() * @see InputStream#markSupported */ @Override - public boolean markSupported() - { + public boolean markSupported() { return in.markSupported(); } } diff --git a/src/main/java/org/codehaus/plexus/util/StringOutputStream.java b/src/main/java/org/codehaus/plexus/util/StringOutputStream.java index ef22b575..60474d81 100644 --- a/src/main/java/org/codehaus/plexus/util/StringOutputStream.java +++ b/src/main/java/org/codehaus/plexus/util/StringOutputStream.java @@ -28,37 +28,28 @@ * encoding. Instead, use {@link java.io.ByteArrayOutputStream#toString(String)}. */ @Deprecated -public class StringOutputStream - extends OutputStream -{ +public class StringOutputStream extends OutputStream { private StringBuffer buf = new StringBuffer(); @Override - public void write( byte[] b ) - throws IOException - { - buf.append( new String( b ) ); + public void write(byte[] b) throws IOException { + buf.append(new String(b)); } @Override - public void write( byte[] b, int off, int len ) - throws IOException - { - buf.append( new String( b, off, len ) ); + public void write(byte[] b, int off, int len) throws IOException { + buf.append(new String(b, off, len)); } @Override - public void write( int b ) - throws IOException - { + public void write(int b) throws IOException { byte[] bytes = new byte[1]; bytes[0] = (byte) b; - buf.append( new String( bytes ) ); + buf.append(new String(bytes)); } @Override - public String toString() - { + public String toString() { return buf.toString(); } } diff --git a/src/main/java/org/codehaus/plexus/util/StringUtils.java b/src/main/java/org/codehaus/plexus/util/StringUtils.java index 0f8518de..edae9844 100644 --- a/src/main/java/org/codehaus/plexus/util/StringUtils.java +++ b/src/main/java/org/codehaus/plexus/util/StringUtils.java @@ -82,8 +82,7 @@ * @since 1.0 * */ -public class StringUtils -{ +public class StringUtils { /** *

    * StringUtils instances should NOT be constructed in standard programming. Instead, the class should @@ -93,9 +92,7 @@ public class StringUtils * This constructor is public to permit tools that require a JavaBean manager to operate. *

    */ - public StringUtils() - { - } + public StringUtils() {} // Empty // -------------------------------------------------------------------------- @@ -110,9 +107,8 @@ public StringUtils() * @param str the String to check * @return the trimmed text (never null) */ - public static String clean( String str ) - { - return ( str == null ? "" : str.trim() ); + public static String clean(String str) { + return (str == null ? "" : str.trim()); } /** @@ -125,9 +121,8 @@ public static String clean( String str ) * @param str the String to check * @return the trimmed text (or null) */ - public static String trim( String str ) - { - return ( str == null ? null : str.trim() ); + public static String trim(String str) { + return (str == null ? null : str.trim()); } /** @@ -141,15 +136,12 @@ public static String trim( String str ) * @param str String target to delete whitespace from * @return the String without whitespaces */ - public static String deleteWhitespace( String str ) - { + public static String deleteWhitespace(String str) { StringBuilder buffer = new StringBuilder(); int sz = str.length(); - for ( int i = 0; i < sz; i++ ) - { - if ( !Character.isWhitespace( str.charAt( i ) ) ) - { - buffer.append( str.charAt( i ) ); + for (int i = 0; i < sz; i++) { + if (!Character.isWhitespace(str.charAt(i))) { + buffer.append(str.charAt(i)); } } return buffer.toString(); @@ -161,9 +153,8 @@ public static String deleteWhitespace( String str ) * @param str the String to check * @return true if the String is non-null, and not length zero */ - public static boolean isNotEmpty( String str ) - { - return ( ( str != null ) && ( !str.isEmpty() ) ); + public static boolean isNotEmpty(String str) { + return ((str != null) && (!str.isEmpty())); } /** @@ -176,9 +167,8 @@ public static boolean isNotEmpty( String str ) * @param str the String to check * @return true if the String is null, or length zero */ - public static boolean isEmpty( String str ) - { - return ( ( str == null ) || ( str.isEmpty() ) ); + public static boolean isEmpty(String str) { + return ((str == null) || (str.isEmpty())); } /** @@ -198,17 +188,13 @@ public static boolean isEmpty( String str ) * @return true if the String is null, empty or whitespace * @since 1.5.2 */ - public static boolean isBlank( String str ) - { + public static boolean isBlank(String str) { int strLen; - if ( str == null || ( strLen = str.length() ) == 0 ) - { + if (str == null || (strLen = str.length()) == 0) { return true; } - for ( int i = 0; i < strLen; i++ ) - { - if ( !Character.isWhitespace( str.charAt( i ) ) ) - { + for (int i = 0; i < strLen; i++) { + if (!Character.isWhitespace(str.charAt(i))) { return false; } } @@ -232,9 +218,8 @@ public static boolean isBlank( String str ) * @return true if the String is not empty and not null and not whitespace * @since 1.5.2 */ - public static boolean isNotBlank( String str ) - { - return !StringUtils.isBlank( str ); + public static boolean isNotBlank(String str) { + return !StringUtils.isBlank(str); } // Equals and IndexOf @@ -256,9 +241,8 @@ public static boolean isNotBlank( String str ) * @see Objects#equals(Object, Object) */ @Deprecated - public static boolean equals( String str1, String str2 ) - { - return Objects.equals( str1, str2 ); + public static boolean equals(String str1, String str2) { + return Objects.equals(str1, str2); } /** @@ -275,9 +259,8 @@ public static boolean equals( String str1, String str2 ) * @param str2 the second string * @return true if the Strings are equal, case insensitive, or both null */ - public static boolean equalsIgnoreCase( String str1, String str2 ) - { - return ( str1 == null ? str2 == null : str1.equalsIgnoreCase( str2 ) ); + public static boolean equalsIgnoreCase(String str1, String str2) { + return (str1 == null ? str2 == null : str1.equalsIgnoreCase(str2)); } /** @@ -293,10 +276,8 @@ public static boolean equalsIgnoreCase( String str1, String str2 ) * @return the first index of any of the searchStrs in str * @throws NullPointerException if any of searchStrs[i] is null */ - public static int indexOfAny( String str, String[] searchStrs ) - { - if ( ( str == null ) || ( searchStrs == null ) ) - { + public static int indexOfAny(String str, String[] searchStrs) { + if ((str == null) || (searchStrs == null)) { return -1; } int sz = searchStrs.length; @@ -305,21 +286,18 @@ public static int indexOfAny( String str, String[] searchStrs ) int ret = Integer.MAX_VALUE; int tmp; - for ( String searchStr : searchStrs ) - { - tmp = str.indexOf( searchStr ); - if ( tmp == -1 ) - { + for (String searchStr : searchStrs) { + tmp = str.indexOf(searchStr); + if (tmp == -1) { continue; } - if ( tmp < ret ) - { + if (tmp < ret) { ret = tmp; } } - return ( ret == Integer.MAX_VALUE ) ? -1 : ret; + return (ret == Integer.MAX_VALUE) ? -1 : ret; } /** @@ -335,19 +313,15 @@ public static int indexOfAny( String str, String[] searchStrs ) * @return the last index of any of the Strings * @throws NullPointerException if any of searchStrs[i] is null */ - public static int lastIndexOfAny( String str, String[] searchStrs ) - { - if ( ( str == null ) || ( searchStrs == null ) ) - { + public static int lastIndexOfAny(String str, String[] searchStrs) { + if ((str == null) || (searchStrs == null)) { return -1; } int ret = -1; int tmp; - for ( String searchStr : searchStrs ) - { - tmp = str.lastIndexOf( searchStr ); - if ( tmp > ret ) - { + for (String searchStr : searchStrs) { + tmp = str.lastIndexOf(searchStr); + if (tmp > ret) { ret = tmp; } } @@ -370,29 +344,24 @@ public static int lastIndexOfAny( String str, String[] searchStrs ) * characters * @return substring from start position */ - public static String substring( String str, int start ) - { - if ( str == null ) - { + public static String substring(String str, int start) { + if (str == null) { return null; } // handle negatives, which means last n characters - if ( start < 0 ) - { + if (start < 0) { start = str.length() + start; // remember start is negative } - if ( start < 0 ) - { + if (start < 0) { start = 0; } - if ( start > str.length() ) - { + if (start > str.length()) { return ""; } - return str.substring( start ); + return str.substring(start); } /** @@ -410,46 +379,38 @@ public static String substring( String str, int start ) * characters * @return substring from start position to end position */ - public static String substring( String str, int start, int end ) - { - if ( str == null ) - { + public static String substring(String str, int start, int end) { + if (str == null) { return null; } // handle negatives - if ( end < 0 ) - { + if (end < 0) { end = str.length() + end; // remember end is negative } - if ( start < 0 ) - { + if (start < 0) { start = str.length() + start; // remember start is negative } // check length next - if ( end > str.length() ) - { + if (end > str.length()) { // check this works. end = str.length(); } // if start is greater than end, return "" - if ( start > end ) - { + if (start > end) { return ""; } - if ( start < 0 ) - { + if (start < 0) { start = 0; } - if ( end < 0 ) - { + if (end < 0) { end = 0; } - return str.substring( start, end ); + return str.substring(start, end); } /** @@ -466,19 +427,14 @@ public static String substring( String str, int start, int end ) * @return the leftmost characters * @throws IllegalArgumentException if len is less than zero */ - public static String left( String str, int len ) - { - if ( len < 0 ) - { - throw new IllegalArgumentException( "Requested String length " + len + " is less than zero" ); + public static String left(String str, int len) { + if (len < 0) { + throw new IllegalArgumentException("Requested String length " + len + " is less than zero"); } - if ( ( str == null ) || ( str.length() <= len ) ) - { + if ((str == null) || (str.length() <= len)) { return str; - } - else - { - return str.substring( 0, len ); + } else { + return str.substring(0, len); } } @@ -496,19 +452,14 @@ public static String left( String str, int len ) * @return the leftmost characters * @throws IllegalArgumentException if len is less than zero */ - public static String right( String str, int len ) - { - if ( len < 0 ) - { - throw new IllegalArgumentException( "Requested String length " + len + " is less than zero" ); + public static String right(String str, int len) { + if (len < 0) { + throw new IllegalArgumentException("Requested String length " + len + " is less than zero"); } - if ( ( str == null ) || ( str.length() <= len ) ) - { + if ((str == null) || (str.length() <= len)) { return str; - } - else - { - return str.substring( str.length() - len ); + } else { + return str.substring(str.length() - len); } } @@ -528,27 +479,20 @@ public static String right( String str, int len ) * @throws IndexOutOfBoundsException if pos is out of bounds * @throws IllegalArgumentException if len is less than zero */ - public static String mid( String str, int pos, int len ) - { - if ( ( pos < 0 ) || ( ( str != null ) && ( pos > str.length() ) ) ) - { - throw new StringIndexOutOfBoundsException( "String index " + pos + " is out of bounds" ); + public static String mid(String str, int pos, int len) { + if ((pos < 0) || ((str != null) && (pos > str.length()))) { + throw new StringIndexOutOfBoundsException("String index " + pos + " is out of bounds"); } - if ( len < 0 ) - { - throw new IllegalArgumentException( "Requested String length " + len + " is less than zero" ); + if (len < 0) { + throw new IllegalArgumentException("Requested String length " + len + " is less than zero"); } - if ( str == null ) - { + if (str == null) { return null; } - if ( str.length() <= ( pos + len ) ) - { - return str.substring( pos ); - } - else - { - return str.substring( pos, pos + len ); + if (str.length() <= (pos + len)) { + return str.substring(pos); + } else { + return str.substring(pos, pos + len); } } @@ -566,9 +510,8 @@ public static String mid( String str, int pos, int len ) * @param str the String to parse * @return an array of parsed Strings */ - public static String[] split( String str ) - { - return split( str, null, -1 ); + public static String[] split(String str) { + return split(str, null, -1); } /** @@ -576,9 +519,8 @@ public static String[] split( String str ) * @param separator Characters used as the delimiters. If null, splits on whitespace. * @return an array of parsed Strings */ - public static String[] split( String text, String separator ) - { - return split( text, separator, -1 ); + public static String[] split(String text, String separator) { + return split(text, separator, -1); } /** @@ -599,23 +541,18 @@ public static String[] split( String text, String separator ) * @param max The maximum number of elements to include in the array. A zero or negative value implies no limit. * @return an array of parsed Strings */ - public static String[] split( String str, String separator, int max ) - { + public static String[] split(String str, String separator, int max) { StringTokenizer tok; - if ( separator == null ) - { + if (separator == null) { // Null separator means we're using StringTokenizer's default // delimiter, which comprises all whitespace characters. - tok = new StringTokenizer( str ); - } - else - { - tok = new StringTokenizer( str, separator ); + tok = new StringTokenizer(str); + } else { + tok = new StringTokenizer(str, separator); } int listSize = tok.countTokens(); - if ( ( max > 0 ) && ( listSize > max ) ) - { + if ((max > 0) && (listSize > max)) { listSize = max; } @@ -623,22 +560,18 @@ public static String[] split( String str, String separator, int max ) int i = 0; int lastTokenBegin; int lastTokenEnd = 0; - while ( tok.hasMoreTokens() ) - { - if ( ( max > 0 ) && ( i == listSize - 1 ) ) - { + while (tok.hasMoreTokens()) { + if ((max > 0) && (i == listSize - 1)) { // In the situation where we hit the max yet have // tokens left over in our input, the last list // element gets all remaining text. String endToken = tok.nextToken(); - lastTokenBegin = str.indexOf( endToken, lastTokenEnd ); - list[i] = str.substring( lastTokenBegin ); + lastTokenBegin = str.indexOf(endToken, lastTokenEnd); + list[i] = str.substring(lastTokenBegin); break; - } - else - { + } else { list[i] = tok.nextToken(); - lastTokenBegin = str.indexOf( list[i], lastTokenEnd ); + lastTokenBegin = str.indexOf(list[i], lastTokenEnd); lastTokenEnd = lastTokenBegin + list[i].length(); } i++; @@ -659,9 +592,8 @@ public static String[] split( String str, String separator, int max ) * @param array the array of values to concatenate. * @return the concatenated string. */ - public static String concatenate( Object[] array ) - { - return join( array, "" ); + public static String concatenate(Object[] array) { + return join(array, ""); } /** @@ -676,23 +608,19 @@ public static String concatenate( Object[] array ) * @param separator the separator character to use * @return the joined String */ - public static String join( Object[] array, String separator ) - { - if ( separator == null ) - { + public static String join(Object[] array, String separator) { + if (separator == null) { separator = ""; } int arraySize = array.length; - int bufSize = ( arraySize == 0 ? 0 : ( array[0].toString().length() + separator.length() ) * arraySize ); - StringBuilder buf = new StringBuilder( bufSize ); - - for ( int i = 0; i < arraySize; i++ ) - { - if ( i > 0 ) - { - buf.append( separator ); + int bufSize = (arraySize == 0 ? 0 : (array[0].toString().length() + separator.length()) * arraySize); + StringBuilder buf = new StringBuilder(bufSize); + + for (int i = 0; i < arraySize; i++) { + if (i > 0) { + buf.append(separator); } - buf.append( array[i] ); + buf.append(array[i]); } return buf.toString(); } @@ -709,19 +637,15 @@ public static String join( Object[] array, String separator ) * @param separator the separator character to use * @return the joined String */ - public static String join( Iterator iterator, String separator ) - { - if ( separator == null ) - { + public static String join(Iterator iterator, String separator) { + if (separator == null) { separator = ""; } - StringBuilder buf = new StringBuilder( 256 ); // Java default is 16, probably too small - while ( iterator.hasNext() ) - { - buf.append( iterator.next() ); - if ( iterator.hasNext() ) - { - buf.append( separator ); + StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small + while (iterator.hasNext()) { + buf.append(iterator.next()); + if (iterator.hasNext()) { + buf.append(separator); } } return buf.toString(); @@ -744,9 +668,8 @@ public static String join( Iterator iterator, String separator ) * @param with char to replace with * @return the text with any replacements processed */ - public static String replaceOnce( String text, char repl, char with ) - { - return replace( text, repl, with, 1 ); + public static String replaceOnce(String text, char repl, char with) { + return replace(text, repl, with, 1); } /** @@ -763,9 +686,8 @@ public static String replaceOnce( String text, char repl, char with ) * @param with char to replace with * @return the text with any replacements processed */ - public static String replace( String text, char repl, char with ) - { - return replace( text, repl, with, -1 ); + public static String replace(String text, char repl, char with) { + return replace(text, repl, with, -1); } /** @@ -783,9 +705,8 @@ public static String replace( String text, char repl, char with ) * @param max maximum number of values to replace, or -1 if no maximum * @return the text with any replacements processed */ - public static String replace( String text, char repl, char with, int max ) - { - return replace( text, String.valueOf( repl ), String.valueOf( with ), max ); + public static String replace(String text, char repl, char with, int max) { + return replace(text, String.valueOf(repl), String.valueOf(with), max); } /** @@ -802,9 +723,8 @@ public static String replace( String text, char repl, char with, int max ) * @param with String to replace with * @return the text with any replacements processed */ - public static String replaceOnce( String text, String repl, String with ) - { - return replace( text, repl, with, 1 ); + public static String replaceOnce(String text, String repl, String with) { + return replace(text, repl, with, 1); } /** @@ -821,9 +741,8 @@ public static String replaceOnce( String text, String repl, String with ) * @param with String to replace with * @return the text with any replacements processed */ - public static String replace( String text, String repl, String with ) - { - return replace( text, repl, with, -1 ); + public static String replace(String text, String repl, String with) { + return replace(text, repl, with, -1); } /** @@ -841,26 +760,22 @@ public static String replace( String text, String repl, String with ) * @param max maximum number of values to replace, or -1 if no maximum * @return the text with any replacements processed */ - public static String replace( String text, String repl, String with, int max ) - { - if ( ( text == null ) || ( repl == null ) || ( with == null ) || ( repl.length() == 0 ) ) - { + public static String replace(String text, String repl, String with, int max) { + if ((text == null) || (repl == null) || (with == null) || (repl.length() == 0)) { return text; } - StringBuilder buf = new StringBuilder( text.length() ); + StringBuilder buf = new StringBuilder(text.length()); int start = 0, end; - while ( ( end = text.indexOf( repl, start ) ) != -1 ) - { - buf.append( text, start, end ).append( with ); + while ((end = text.indexOf(repl, start)) != -1) { + buf.append(text, start, end).append(with); start = end + repl.length(); - if ( --max == 0 ) - { + if (--max == 0) { break; } } - buf.append( text, start, text.length() ); + buf.append(text, start, text.length()); return buf.toString(); } @@ -876,10 +791,12 @@ public static String replace( String text, String repl, String with, int max ) * @return String with overlayed text * @throws NullPointerException if text or overlay is null */ - public static String overlayString( String text, String overlay, int start, int end ) - { - return new StringBuilder( start + overlay.length() + text.length() - end - + 1 ).append( text, 0, start ).append( overlay ).append( text, end, text.length() ).toString(); + public static String overlayString(String text, String overlay, int start, int end) { + return new StringBuilder(start + overlay.length() + text.length() - end + 1) + .append(text, 0, start) + .append(overlay) + .append(text, end, text.length()) + .toString(); } // Centering @@ -898,9 +815,8 @@ public static String overlayString( String text, String overlay, int start, int * @return String containing centered String * @throws NullPointerException if str is null */ - public static String center( String str, int size ) - { - return center( str, size, " " ); + public static String center(String str, int size) { + return center(str, size, " "); } /** @@ -918,16 +834,14 @@ public static String center( String str, int size ) * @throws NullPointerException if str or delim is null * @throws ArithmeticException if delim is the empty String */ - public static String center( String str, int size, String delim ) - { + public static String center(String str, int size, String delim) { int sz = str.length(); int p = size - sz; - if ( p < 1 ) - { + if (p < 1) { return str; } - str = leftPad( str, sz + p / 2, delim ); - str = rightPad( str, size, delim ); + str = leftPad(str, sz + p / 2, delim); + str = rightPad(str, size, delim); return str; } @@ -943,9 +857,8 @@ public static String center( String str, int size, String delim ) * @return String without chomped newline * @throws NullPointerException if str is null */ - public static String chomp( String str ) - { - return chomp( str, "\n" ); + public static String chomp(String str) { + return chomp(str, "\n"); } /** @@ -958,15 +871,11 @@ public static String chomp( String str ) * @return String without chomped ending * @throws NullPointerException if str or sep is null */ - public static String chomp( String str, String sep ) - { - int idx = str.lastIndexOf( sep ); - if ( idx != -1 ) - { - return str.substring( 0, idx ); - } - else - { + public static String chomp(String str, String sep) { + int idx = str.lastIndexOf(sep); + if (idx != -1) { + return str.substring(0, idx); + } else { return str; } } @@ -980,9 +889,8 @@ public static String chomp( String str, String sep ) * @return String without chomped ending * @throws NullPointerException if str is null */ - public static String chompLast( String str ) - { - return chompLast( str, "\n" ); + public static String chompLast(String str) { + return chompLast(str, "\n"); } /** @@ -995,19 +903,14 @@ public static String chompLast( String str ) * @return String without chomped ending * @throws NullPointerException if str or sep is null */ - public static String chompLast( String str, String sep ) - { - if ( str.length() == 0 ) - { + public static String chompLast(String str, String sep) { + if (str.length() == 0) { return str; } - String sub = str.substring( str.length() - sep.length() ); - if ( sep.equals( sub ) ) - { - return str.substring( 0, str.length() - sep.length() ); - } - else - { + String sub = str.substring(str.length() - sep.length()); + if (sep.equals(sub)) { + return str.substring(0, str.length() - sep.length()); + } else { return str; } } @@ -1022,19 +925,13 @@ public static String chompLast( String str, String sep ) * @return String chomped * @throws NullPointerException if str or sep is null */ - public static String getChomp( String str, String sep ) - { - int idx = str.lastIndexOf( sep ); - if ( idx == str.length() - sep.length() ) - { + public static String getChomp(String str, String sep) { + int idx = str.lastIndexOf(sep); + if (idx == str.length() - sep.length()) { return sep; - } - else if ( idx != -1 ) - { - return str.substring( idx ); - } - else - { + } else if (idx != -1) { + return str.substring(idx); + } else { return ""; } } @@ -1049,15 +946,11 @@ else if ( idx != -1 ) * @return String without chomped beginning * @throws NullPointerException if str or sep is null */ - public static String prechomp( String str, String sep ) - { - int idx = str.indexOf( sep ); - if ( idx != -1 ) - { - return str.substring( idx + sep.length() ); - } - else - { + public static String prechomp(String str, String sep) { + int idx = str.indexOf(sep); + if (idx != -1) { + return str.substring(idx + sep.length()); + } else { return str; } } @@ -1072,15 +965,11 @@ public static String prechomp( String str, String sep ) * @return String prechomped * @throws NullPointerException if str or sep is null */ - public static String getPrechomp( String str, String sep ) - { - int idx = str.indexOf( sep ); - if ( idx != -1 ) - { - return str.substring( 0, idx + sep.length() ); - } - else - { + public static String getPrechomp(String str, String sep) { + int idx = str.indexOf(sep); + if (idx != -1) { + return str.substring(0, idx + sep.length()); + } else { return ""; } } @@ -1100,24 +989,19 @@ public static String getPrechomp( String str, String sep ) * @return String without last character * @throws NullPointerException if str is null */ - public static String chop( String str ) - { - if ( "".equals( str ) ) - { + public static String chop(String str) { + if ("".equals(str)) { return ""; } - if ( str.length() == 1 ) - { + if (str.length() == 1) { return ""; } int lastIdx = str.length() - 1; - String ret = str.substring( 0, lastIdx ); - char last = str.charAt( lastIdx ); - if ( last == '\n' ) - { - if ( ret.charAt( lastIdx - 1 ) == '\r' ) - { - return ret.substring( 0, lastIdx - 1 ); + String ret = str.substring(0, lastIdx); + char last = str.charAt(lastIdx); + if (last == '\n') { + if (ret.charAt(lastIdx - 1) == '\r') { + return ret.substring(0, lastIdx - 1); } } return ret; @@ -1133,22 +1017,17 @@ public static String chop( String str ) * @return String without newline * @throws NullPointerException if str is null */ - public static String chopNewline( String str ) - { + public static String chopNewline(String str) { int lastIdx = str.length() - 1; - char last = str.charAt( lastIdx ); - if ( last == '\n' ) - { - if ( str.charAt( lastIdx - 1 ) == '\r' ) - { + char last = str.charAt(lastIdx); + if (last == '\n') { + if (str.charAt(lastIdx - 1) == '\r') { lastIdx--; } - } - else - { + } else { lastIdx++; } - return str.substring( 0, lastIdx ); + return str.substring(0, lastIdx); } // Conversion @@ -1167,83 +1046,67 @@ public static String chopNewline( String str ) * @return String with escaped values * @throws NullPointerException if str is null */ - public static String escape( String str ) - { + public static String escape(String str) { // improved with code from cybertiger@cyberiantiger.org // unicode from him, and default for < 32's. int sz = str.length(); - StringBuilder buffer = new StringBuilder( 2 * sz ); - for ( int i = 0; i < sz; i++ ) - { - char ch = str.charAt( i ); + StringBuilder buffer = new StringBuilder(2 * sz); + for (int i = 0; i < sz; i++) { + char ch = str.charAt(i); // handle unicode - if ( ch > 0xfff ) - { - buffer.append( "\\u" + Integer.toHexString( ch ) ); - } - else if ( ch > 0xff ) - { - buffer.append( "\\u0" + Integer.toHexString( ch ) ); - } - else if ( ch > 0x7f ) - { - buffer.append( "\\u00" + Integer.toHexString( ch ) ); - } - else if ( ch < 32 ) - { - switch ( ch ) - { + if (ch > 0xfff) { + buffer.append("\\u" + Integer.toHexString(ch)); + } else if (ch > 0xff) { + buffer.append("\\u0" + Integer.toHexString(ch)); + } else if (ch > 0x7f) { + buffer.append("\\u00" + Integer.toHexString(ch)); + } else if (ch < 32) { + switch (ch) { case '\b': - buffer.append( '\\' ); - buffer.append( 'b' ); + buffer.append('\\'); + buffer.append('b'); break; case '\n': - buffer.append( '\\' ); - buffer.append( 'n' ); + buffer.append('\\'); + buffer.append('n'); break; case '\t': - buffer.append( '\\' ); - buffer.append( 't' ); + buffer.append('\\'); + buffer.append('t'); break; case '\f': - buffer.append( '\\' ); - buffer.append( 'f' ); + buffer.append('\\'); + buffer.append('f'); break; case '\r': - buffer.append( '\\' ); - buffer.append( 'r' ); + buffer.append('\\'); + buffer.append('r'); break; default: - if ( ch > 0xf ) - { - buffer.append( "\\u00" + Integer.toHexString( ch ) ); - } - else - { - buffer.append( "\\u000" + Integer.toHexString( ch ) ); + if (ch > 0xf) { + buffer.append("\\u00" + Integer.toHexString(ch)); + } else { + buffer.append("\\u000" + Integer.toHexString(ch)); } break; } - } - else - { - switch ( ch ) - { + } else { + switch (ch) { case '\'': - buffer.append( '\\' ); - buffer.append( '\'' ); + buffer.append('\\'); + buffer.append('\''); break; case '"': - buffer.append( '\\' ); - buffer.append( '"' ); + buffer.append('\\'); + buffer.append('"'); break; case '\\': - buffer.append( '\\' ); - buffer.append( '\\' ); + buffer.append('\\'); + buffer.append('\\'); break; default: - buffer.append( ch ); + buffer.append(ch); break; } } @@ -1265,12 +1128,10 @@ else if ( ch < 32 ) * @throws NegativeArraySizeException if repeat < 0 * @throws NullPointerException if str is null */ - public static String repeat( String str, int repeat ) - { - StringBuilder buffer = new StringBuilder( repeat * str.length() ); - for ( int i = 0; i < repeat; i++ ) - { - buffer.append( str ); + public static String repeat(String str, int repeat) { + StringBuilder buffer = new StringBuilder(repeat * str.length()); + for (int i = 0; i < repeat; i++) { + buffer.append(str); } return buffer.toString(); } @@ -1288,9 +1149,8 @@ public static String repeat( String str, int repeat ) * @return right padded String * @throws NullPointerException if str is null */ - public static String rightPad( String str, int size ) - { - return rightPad( str, size, " " ); + public static String rightPad(String str, int size) { + return rightPad(str, size, " "); } /** @@ -1308,12 +1168,10 @@ public static String rightPad( String str, int size ) * @throws NullPointerException if str or delim is null * @throws ArithmeticException if delim is the empty String */ - public static String rightPad( String str, int size, String delim ) - { - size = ( size - str.length() ) / delim.length(); - if ( size > 0 ) - { - str += repeat( delim, size ); + public static String rightPad(String str, int size, String delim) { + size = (size - str.length()) / delim.length(); + if (size > 0) { + str += repeat(delim, size); } return str; } @@ -1331,9 +1189,8 @@ public static String rightPad( String str, int size, String delim ) * @return left padded String * @throws NullPointerException if str or delim is null */ - public static String leftPad( String str, int size ) - { - return leftPad( str, size, " " ); + public static String leftPad(String str, int size) { + return leftPad(str, size, " "); } /** @@ -1346,12 +1203,10 @@ public static String leftPad( String str, int size ) * @throws NullPointerException if str or delim is null * @throws ArithmeticException if delim is the empty string */ - public static String leftPad( String str, int size, String delim ) - { - size = ( size - str.length() ) / delim.length(); - if ( size > 0 ) - { - str = repeat( delim, size ) + str; + public static String leftPad(String str, int size, String delim) { + size = (size - str.length()) / delim.length(); + if (size > 0) { + str = repeat(delim, size) + str; } return str; } @@ -1367,9 +1222,8 @@ public static String leftPad( String str, int size, String delim ) * @param str the String to remove whitespace from * @return the stripped String */ - public static String strip( String str ) - { - return strip( str, null ); + public static String strip(String str) { + return strip(str, null); } /** @@ -1384,10 +1238,9 @@ public static String strip( String str ) * @param delim the String to remove at start and end * @return the stripped String */ - public static String strip( String str, String delim ) - { - str = stripStart( str, delim ); - return stripEnd( str, delim ); + public static String strip(String str, String delim) { + str = stripStart(str, delim); + return stripEnd(str, delim); } /** @@ -1398,9 +1251,8 @@ public static String strip( String str, String delim ) * @param strs the Strings to remove whitespace from * @return the stripped Strings */ - public static String[] stripAll( String[] strs ) - { - return stripAll( strs, null ); + public static String[] stripAll(String[] strs) { + return stripAll(strs, null); } /** @@ -1412,17 +1264,14 @@ public static String[] stripAll( String[] strs ) * @param delimiter the String to remove at start and end * @return the stripped Strings */ - public static String[] stripAll( String[] strs, String delimiter ) - { - if ( ( strs == null ) || ( strs.length == 0 ) ) - { + public static String[] stripAll(String[] strs, String delimiter) { + if ((strs == null) || (strs.length == 0)) { return strs; } int sz = strs.length; String[] newArr = new String[sz]; - for ( int i = 0; i < sz; i++ ) - { - newArr[i] = strip( strs[i], delimiter ); + for (int i = 0; i < sz; i++) { + newArr[i] = strip(strs[i], delimiter); } return newArr; } @@ -1439,29 +1288,22 @@ public static String[] stripAll( String[] strs, String delimiter ) * @param strip the String to remove * @return the stripped String */ - public static String stripEnd( String str, String strip ) - { - if ( str == null ) - { + public static String stripEnd(String str, String strip) { + if (str == null) { return null; } int end = str.length(); - if ( strip == null ) - { - while ( ( end != 0 ) && Character.isWhitespace( str.charAt( end - 1 ) ) ) - { + if (strip == null) { + while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) { end--; } - } - else - { - while ( ( end != 0 ) && ( strip.indexOf( str.charAt( end - 1 ) ) != -1 ) ) - { + } else { + while ((end != 0) && (strip.indexOf(str.charAt(end - 1)) != -1)) { end--; } } - return str.substring( 0, end ); + return str.substring(0, end); } /** @@ -1476,10 +1318,8 @@ public static String stripEnd( String str, String strip ) * @param strip the String to remove * @return the stripped String */ - public static String stripStart( String str, String strip ) - { - if ( str == null ) - { + public static String stripStart(String str, String strip) { + if (str == null) { return null; } @@ -1487,21 +1327,16 @@ public static String stripStart( String str, String strip ) int sz = str.length(); - if ( strip == null ) - { - while ( ( start != sz ) && Character.isWhitespace( str.charAt( start ) ) ) - { + if (strip == null) { + while ((start != sz) && Character.isWhitespace(str.charAt(start))) { start++; } - } - else - { - while ( ( start != sz ) && ( strip.indexOf( str.charAt( start ) ) != -1 ) ) - { + } else { + while ((start != sz) && (strip.indexOf(str.charAt(start)) != -1)) { start++; } } - return str.substring( start ); + return str.substring(start); } // Case conversion @@ -1515,10 +1350,8 @@ public static String stripStart( String str, String strip ) * @param str the String to uppercase * @return the upper cased String */ - public static String upperCase( String str ) - { - if ( str == null ) - { + public static String upperCase(String str) { + if (str == null) { return null; } return str.toUpperCase(); @@ -1532,10 +1365,8 @@ public static String upperCase( String str ) * @param str the string to lowercase * @return the lower cased String */ - public static String lowerCase( String str ) - { - if ( str == null ) - { + public static String lowerCase(String str) { + if (str == null) { return null; } return str.toLowerCase(); @@ -1552,20 +1383,16 @@ public static String lowerCase( String str ) * @param str the String to uncapitalise * @return uncapitalised String */ - public static String uncapitalise( String str ) - { - if ( str == null ) - { + public static String uncapitalise(String str) { + if (str == null) { return null; - } - else if ( str.length() == 0 ) - { + } else if (str.length() == 0) { return ""; - } - else - { - return new StringBuilder( str.length() ).append( Character.toLowerCase( str.charAt( 0 ) ) ).append( str, 1, - str.length() ).toString(); + } else { + return new StringBuilder(str.length()) + .append(Character.toLowerCase(str.charAt(0))) + .append(str, 1, str.length()) + .toString(); } } @@ -1580,20 +1407,16 @@ else if ( str.length() == 0 ) * @param str the String to capitalise * @return capitalised String */ - public static String capitalise( String str ) - { - if ( str == null ) - { + public static String capitalise(String str) { + if (str == null) { return null; - } - else if ( str.length() == 0 ) - { + } else if (str.length() == 0) { return ""; - } - else - { - return new StringBuilder( str.length() ).append( Character.toTitleCase( str.charAt( 0 ) ) ).append( str, 1, - str.length() ).toString(); + } else { + return new StringBuilder(str.length()) + .append(Character.toTitleCase(str.charAt(0))) + .append(str, 1, str.length()) + .toString(); } } @@ -1611,47 +1434,34 @@ else if ( str.length() == 0 ) * @param str the String to swap the case of * @return the modified String */ - public static String swapCase( String str ) - { - if ( str == null ) - { + public static String swapCase(String str) { + if (str == null) { return null; } int sz = str.length(); - StringBuilder buffer = new StringBuilder( sz ); + StringBuilder buffer = new StringBuilder(sz); boolean whitespace = false; char ch; char tmp; - for ( int i = 0; i < sz; i++ ) - { - ch = str.charAt( i ); - if ( Character.isUpperCase( ch ) ) - { - tmp = Character.toLowerCase( ch ); - } - else if ( Character.isTitleCase( ch ) ) - { - tmp = Character.toLowerCase( ch ); - } - else if ( Character.isLowerCase( ch ) ) - { - if ( whitespace ) - { - tmp = Character.toTitleCase( ch ); - } - else - { - tmp = Character.toUpperCase( ch ); + for (int i = 0; i < sz; i++) { + ch = str.charAt(i); + if (Character.isUpperCase(ch)) { + tmp = Character.toLowerCase(ch); + } else if (Character.isTitleCase(ch)) { + tmp = Character.toLowerCase(ch); + } else if (Character.isLowerCase(ch)) { + if (whitespace) { + tmp = Character.toTitleCase(ch); + } else { + tmp = Character.toUpperCase(ch); } - } - else - { + } else { tmp = ch; } - buffer.append( tmp ); - whitespace = Character.isWhitespace( ch ); + buffer.append(tmp); + whitespace = Character.isWhitespace(ch); } return buffer.toString(); } @@ -1670,31 +1480,23 @@ else if ( Character.isLowerCase( ch ) ) * @param str the String to capitalise * @return capitalised String */ - public static String capitaliseAllWords( String str ) - { - if ( str == null ) - { + public static String capitaliseAllWords(String str) { + if (str == null) { return null; } int sz = str.length(); - StringBuilder buffer = new StringBuilder( sz ); + StringBuilder buffer = new StringBuilder(sz); boolean space = true; - for ( int i = 0; i < sz; i++ ) - { - char ch = str.charAt( i ); - if ( Character.isWhitespace( ch ) ) - { - buffer.append( ch ); + for (int i = 0; i < sz; i++) { + char ch = str.charAt(i); + if (Character.isWhitespace(ch)) { + buffer.append(ch); space = true; - } - else if ( space ) - { - buffer.append( Character.toTitleCase( ch ) ); + } else if (space) { + buffer.append(Character.toTitleCase(ch)); space = false; - } - else - { - buffer.append( ch ); + } else { + buffer.append(ch); } } return buffer.toString(); @@ -1714,31 +1516,23 @@ else if ( space ) * @param str the string to uncapitalise * @return uncapitalised string */ - public static String uncapitaliseAllWords( String str ) - { - if ( str == null ) - { + public static String uncapitaliseAllWords(String str) { + if (str == null) { return null; } int sz = str.length(); - StringBuilder buffer = new StringBuilder( sz ); + StringBuilder buffer = new StringBuilder(sz); boolean space = true; - for ( int i = 0; i < sz; i++ ) - { - char ch = str.charAt( i ); - if ( Character.isWhitespace( ch ) ) - { - buffer.append( ch ); + for (int i = 0; i < sz; i++) { + char ch = str.charAt(i); + if (Character.isWhitespace(ch)) { + buffer.append(ch); space = true; - } - else if ( space ) - { - buffer.append( Character.toLowerCase( ch ) ); + } else if (space) { + buffer.append(Character.toLowerCase(ch)); space = false; - } - else - { - buffer.append( ch ); + } else { + buffer.append(ch); } } return buffer.toString(); @@ -1760,9 +1554,8 @@ else if ( space ) * @return the String that was nested, or null * @throws NullPointerException if tag is null */ - public static String getNestedString( String str, String tag ) - { - return getNestedString( str, tag, tag ); + public static String getNestedString(String str, String tag) { + return getNestedString(str, tag, tag); } /** @@ -1776,19 +1569,15 @@ public static String getNestedString( String str, String tag ) * @return the String that was nested, or null * @throws NullPointerException if open or close is null */ - public static String getNestedString( String str, String open, String close ) - { - if ( str == null ) - { + public static String getNestedString(String str, String open, String close) { + if (str == null) { return null; } - int start = str.indexOf( open ); - if ( start != -1 ) - { - int end = str.indexOf( close, start + open.length() ); - if ( end != -1 ) - { - return str.substring( start + open.length(), end ); + int start = str.indexOf(open); + if (start != -1) { + int end = str.indexOf(close, start + open.length()); + if (end != -1) { + return str.substring(start + open.length(), end); } } return null; @@ -1807,20 +1596,16 @@ public static String getNestedString( String str, String open, String close ) * @return the number of occurrences, 0 if the String is null * @throws NullPointerException if sub is null */ - public static int countMatches( String str, String sub ) - { - if ( sub.equals( "" ) ) - { + public static int countMatches(String str, String sub) { + if (sub.equals("")) { return 0; } - if ( str == null ) - { + if (str == null) { return 0; } int count = 0; int idx = 0; - while ( ( idx = str.indexOf( sub, idx ) ) != -1 ) - { + while ((idx = str.indexOf(sub, idx)) != -1) { count++; idx += sub.length(); } @@ -1841,17 +1626,13 @@ public static int countMatches( String str, String sub ) * @param str the String to check * @return true if only contains letters, and is non-null */ - public static boolean isAlpha( String str ) - { - if ( str == null ) - { + public static boolean isAlpha(String str) { + if (str == null) { return false; } int sz = str.length(); - for ( int i = 0; i < sz; i++ ) - { - if ( Character.isLetter( str.charAt( i ) ) == false ) - { + for (int i = 0; i < sz; i++) { + if (Character.isLetter(str.charAt(i)) == false) { return false; } } @@ -1869,17 +1650,13 @@ public static boolean isAlpha( String str ) * @param str the String to check * @return true if only contains whitespace, and is non-null */ - public static boolean isWhitespace( String str ) - { - if ( str == null ) - { + public static boolean isWhitespace(String str) { + if (str == null) { return false; } int sz = str.length(); - for ( int i = 0; i < sz; i++ ) - { - if ( ( Character.isWhitespace( str.charAt( i ) ) == false ) ) - { + for (int i = 0; i < sz; i++) { + if ((Character.isWhitespace(str.charAt(i)) == false)) { return false; } } @@ -1897,17 +1674,13 @@ public static boolean isWhitespace( String str ) * @param str the String to check * @return true if only contains letters and space, and is non-null */ - public static boolean isAlphaSpace( String str ) - { - if ( str == null ) - { + public static boolean isAlphaSpace(String str) { + if (str == null) { return false; } int sz = str.length(); - for ( int i = 0; i < sz; i++ ) - { - if ( ( Character.isLetter( str.charAt( i ) ) == false ) && ( str.charAt( i ) != ' ' ) ) - { + for (int i = 0; i < sz; i++) { + if ((Character.isLetter(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } @@ -1925,17 +1698,13 @@ public static boolean isAlphaSpace( String str ) * @param str the String to check * @return true if only contains letters or digits, and is non-null */ - public static boolean isAlphanumeric( String str ) - { - if ( str == null ) - { + public static boolean isAlphanumeric(String str) { + if (str == null) { return false; } int sz = str.length(); - for ( int i = 0; i < sz; i++ ) - { - if ( Character.isLetterOrDigit( str.charAt( i ) ) == false ) - { + for (int i = 0; i < sz; i++) { + if (Character.isLetterOrDigit(str.charAt(i)) == false) { return false; } } @@ -1953,17 +1722,13 @@ public static boolean isAlphanumeric( String str ) * @param str the String to check * @return true if only contains letters, digits or space, and is non-null */ - public static boolean isAlphanumericSpace( String str ) - { - if ( str == null ) - { + public static boolean isAlphanumericSpace(String str) { + if (str == null) { return false; } int sz = str.length(); - for ( int i = 0; i < sz; i++ ) - { - if ( ( Character.isLetterOrDigit( str.charAt( i ) ) == false ) && ( str.charAt( i ) != ' ' ) ) - { + for (int i = 0; i < sz; i++) { + if ((Character.isLetterOrDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } @@ -1981,17 +1746,13 @@ public static boolean isAlphanumericSpace( String str ) * @param str the String to check * @return true if only contains digits, and is non-null */ - public static boolean isNumeric( String str ) - { - if ( str == null ) - { + public static boolean isNumeric(String str) { + if (str == null) { return false; } int sz = str.length(); - for ( int i = 0; i < sz; i++ ) - { - if ( Character.isDigit( str.charAt( i ) ) == false ) - { + for (int i = 0; i < sz; i++) { + if (Character.isDigit(str.charAt(i)) == false) { return false; } } @@ -2009,17 +1770,13 @@ public static boolean isNumeric( String str ) * @param str the String to check * @return true if only contains digits or space, and is non-null */ - public static boolean isNumericSpace( String str ) - { - if ( str == null ) - { + public static boolean isNumericSpace(String str) { + if (str == null) { return false; } int sz = str.length(); - for ( int i = 0; i < sz; i++ ) - { - if ( ( Character.isDigit( str.charAt( i ) ) == false ) && ( str.charAt( i ) != ' ' ) ) - { + for (int i = 0; i < sz; i++) { + if ((Character.isDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } @@ -2040,9 +1797,8 @@ public static boolean isNumericSpace( String str ) * @see Objects#toString(Object, String) */ @Deprecated - public static String defaultString( Object obj ) - { - return defaultString( obj, "" ); + public static String defaultString(Object obj) { + return defaultString(obj, ""); } /** @@ -2057,9 +1813,8 @@ public static String defaultString( Object obj ) * @see Objects#toString(Object, String) */ @Deprecated - public static String defaultString( Object obj, String defaultString ) - { - return Objects.toString( obj, defaultString ); + public static String defaultString(Object obj, String defaultString) { + return Objects.toString(obj, defaultString); } // Reversing @@ -2076,13 +1831,11 @@ public static String defaultString( Object obj, String defaultString ) * @param str the String to reverse * @return the reversed String */ - public static String reverse( String str ) - { - if ( str == null ) - { + public static String reverse(String str) { + if (str == null) { return null; } - return new StringBuilder( str ).reverse().toString(); + return new StringBuilder(str).reverse().toString(); } /** @@ -2098,13 +1851,12 @@ public static String reverse( String str ) * @param delimiter the delimiter to use * @return the reversed String */ - public static String reverseDelimitedString( String str, String delimiter ) - { + public static String reverseDelimitedString(String str, String delimiter) { // could implement manually, but simple way is to reuse other, // probably slower, methods. - String[] strs = split( str, delimiter ); - reverseArray( strs ); - return join( strs, delimiter ); + String[] strs = split(str, delimiter); + reverseArray(strs); + return join(strs, delimiter); } /** @@ -2117,14 +1869,12 @@ public static String reverseDelimitedString( String str, String delimiter ) * * @param array the array to reverse */ - private static void reverseArray( Object[] array ) - { + private static void reverseArray(Object[] array) { int i = 0; int j = array.length - 1; Object tmp; - while ( j > i ) - { + while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; @@ -2147,9 +1897,8 @@ private static void reverseArray( Object[] array ) * @param s string * @param maxWidth maximum length of result string **/ - public static String abbreviate( String s, int maxWidth ) - { - return abbreviate( s, 0, maxWidth ); + public static String abbreviate(String s, int maxWidth) { + return abbreviate(s, 0, maxWidth); } /** @@ -2162,37 +1911,29 @@ public static String abbreviate( String s, int maxWidth ) * @param offset left edge of source string * @param maxWidth maximum length of result string **/ - public static String abbreviate( String s, int offset, int maxWidth ) - { - if ( maxWidth < 4 ) - { - throw new IllegalArgumentException( "Minimum abbreviation width is 4" ); - } - if ( s.length() <= maxWidth ) - { + public static String abbreviate(String s, int offset, int maxWidth) { + if (maxWidth < 4) { + throw new IllegalArgumentException("Minimum abbreviation width is 4"); + } + if (s.length() <= maxWidth) { return s; } - if ( offset > s.length() ) - { + if (offset > s.length()) { offset = s.length(); } - if ( ( s.length() - offset ) < ( maxWidth - 3 ) ) - { - offset = s.length() - ( maxWidth - 3 ); + if ((s.length() - offset) < (maxWidth - 3)) { + offset = s.length() - (maxWidth - 3); } - if ( offset <= 4 ) - { - return s.substring( 0, maxWidth - 3 ) + "..."; + if (offset <= 4) { + return s.substring(0, maxWidth - 3) + "..."; } - if ( maxWidth < 7 ) - { - throw new IllegalArgumentException( "Minimum abbreviation width with offset is 7" ); + if (maxWidth < 7) { + throw new IllegalArgumentException("Minimum abbreviation width with offset is 7"); } - if ( ( offset + ( maxWidth - 3 ) ) < s.length() ) - { - return "..." + abbreviate( s.substring( offset ), maxWidth - 3 ); + if ((offset + (maxWidth - 3)) < s.length()) { + return "..." + abbreviate(s.substring(offset), maxWidth - 3); } - return "..." + s.substring( s.length() - ( maxWidth - 3 ) ); + return "..." + s.substring(s.length() - (maxWidth - 3)); } // Difference @@ -2207,14 +1948,12 @@ public static String abbreviate( String s, int offset, int maxWidth ) * @param s2 string * @return the portion of s2 where it differs from s1; returns the empty string ("") if they are equal **/ - public static String difference( String s1, String s2 ) - { - int at = differenceAt( s1, s2 ); - if ( at == -1 ) - { + public static String difference(String s1, String s2) { + int at = differenceAt(s1, s2); + if (at == -1) { return ""; } - return s2.substring( at ); + return s2.substring(at); } /** @@ -2226,103 +1965,88 @@ public static String difference( String s1, String s2 ) * @param s2 string * @return the index where s2 and s1 begin to differ; -1 if they are equal **/ - public static int differenceAt( String s1, String s2 ) - { + public static int differenceAt(String s1, String s2) { int i; - for ( i = 0; ( i < s1.length() ) && ( i < s2.length() ); ++i ) - { - if ( s1.charAt( i ) != s2.charAt( i ) ) - { + for (i = 0; (i < s1.length()) && (i < s2.length()); ++i) { + if (s1.charAt(i) != s2.charAt(i)) { break; } } - if ( ( i < s2.length() ) || ( i < s1.length() ) ) - { + if ((i < s2.length()) || (i < s1.length())) { return i; } return -1; } - public static String interpolate( String text, Map namespace ) - { + public static String interpolate(String text, Map namespace) { Iterator keys = namespace.keySet().iterator(); - while ( keys.hasNext() ) - { + while (keys.hasNext()) { String key = keys.next().toString(); - Object obj = namespace.get( key ); + Object obj = namespace.get(key); - if ( obj == null ) - { - throw new NullPointerException( "The value of the key '" + key + "' is null." ); + if (obj == null) { + throw new NullPointerException("The value of the key '" + key + "' is null."); } String value = obj.toString(); - text = replace( text, "${" + key + "}", value ); + text = replace(text, "${" + key + "}", value); - if ( !key.contains( " " ) ) - { - text = replace( text, "$" + key, value ); + if (!key.contains(" ")) { + text = replace(text, "$" + key, value); } } return text; } - public static String removeAndHump( String data, String replaceThis ) - { + public static String removeAndHump(String data, String replaceThis) { String temp; StringBuilder out = new StringBuilder(); temp = data; - StringTokenizer st = new StringTokenizer( temp, replaceThis ); + StringTokenizer st = new StringTokenizer(temp, replaceThis); - while ( st.hasMoreTokens() ) - { + while (st.hasMoreTokens()) { String element = (String) st.nextElement(); - out.append( capitalizeFirstLetter( element ) ); + out.append(capitalizeFirstLetter(element)); } return out.toString(); } - public static String capitalizeFirstLetter( String data ) - { - char firstLetter = Character.toTitleCase( data.substring( 0, 1 ).charAt( 0 ) ); + public static String capitalizeFirstLetter(String data) { + char firstLetter = Character.toTitleCase(data.substring(0, 1).charAt(0)); - String restLetters = data.substring( 1 ); + String restLetters = data.substring(1); return firstLetter + restLetters; } - public static String lowercaseFirstLetter( String data ) - { - char firstLetter = Character.toLowerCase( data.substring( 0, 1 ).charAt( 0 ) ); + public static String lowercaseFirstLetter(String data) { + char firstLetter = Character.toLowerCase(data.substring(0, 1).charAt(0)); - String restLetters = data.substring( 1 ); + String restLetters = data.substring(1); return firstLetter + restLetters; } - public static String addAndDeHump( String view ) - { + public static String addAndDeHump(String view) { StringBuilder sb = new StringBuilder(); - for ( int i = 0; i < view.length(); i++ ) - { - if ( ( i != 0 ) && Character.isUpperCase( view.charAt( i ) ) ) - { - sb.append( '-' ); + for (int i = 0; i < view.length(); i++) { + if ((i != 0) && Character.isUpperCase(view.charAt(i))) { + sb.append('-'); } - sb.append( view.charAt( i ) ); + sb.append(view.charAt(i)); } - return sb.toString().trim().toLowerCase( Locale.ENGLISH ); + return sb.toString().trim().toLowerCase(Locale.ENGLISH); } /** @@ -2344,9 +2068,8 @@ public static String addAndDeHump( String view ) * @since 1.5.1 * @see #quoteAndEscape(String, char, char[], char[], char, boolean) */ - public static String quoteAndEscape( String source, char quoteChar ) - { - return quoteAndEscape( source, quoteChar, new char[] { quoteChar }, new char[] { ' ' }, '\\', false ); + public static String quoteAndEscape(String source, char quoteChar) { + return quoteAndEscape(source, quoteChar, new char[] {quoteChar}, new char[] {' '}, '\\', false); } /** @@ -2361,9 +2084,8 @@ public static String quoteAndEscape( String source, char quoteChar ) * @since 1.5.1 * @see #quoteAndEscape(String, char, char[], char[], char, boolean) */ - public static String quoteAndEscape( String source, char quoteChar, char[] quotingTriggers ) - { - return quoteAndEscape( source, quoteChar, new char[] { quoteChar }, quotingTriggers, '\\', false ); + public static String quoteAndEscape(String source, char quoteChar, char[] quotingTriggers) { + return quoteAndEscape(source, quoteChar, new char[] {quoteChar}, quotingTriggers, '\\', false); } /** @@ -2376,10 +2098,9 @@ public static String quoteAndEscape( String source, char quoteChar, char[] quoti * @since 1.5.1 * @see #quoteAndEscape(String, char, char[], char[], char, boolean) */ - public static String quoteAndEscape( String source, char quoteChar, final char[] escapedChars, char escapeChar, - boolean force ) - { - return quoteAndEscape( source, quoteChar, escapedChars, new char[] { ' ' }, escapeChar, force ); + public static String quoteAndEscape( + String source, char quoteChar, final char[] escapedChars, char escapeChar, boolean force) { + return quoteAndEscape(source, quoteChar, escapedChars, new char[] {' '}, escapeChar, force); } /** @@ -2392,10 +2113,14 @@ public static String quoteAndEscape( String source, char quoteChar, final char[] * @return the String quoted and escaped * @since 1.5.1 */ - public static String quoteAndEscape( String source, char quoteChar, final char[] escapedChars, - final char[] quotingTriggers, char escapeChar, boolean force ) - { - return quoteAndEscape( source, quoteChar, escapedChars, quotingTriggers, escapeChar + "%s", force ); + public static String quoteAndEscape( + String source, + char quoteChar, + final char[] escapedChars, + final char[] quotingTriggers, + char escapeChar, + boolean force) { + return quoteAndEscape(source, quoteChar, escapedChars, quotingTriggers, escapeChar + "%s", force); } /** @@ -2408,45 +2133,40 @@ public static String quoteAndEscape( String source, char quoteChar, final char[] * @return the String quoted and escaped * @since 3.0.4 */ - public static String quoteAndEscape( String source, char quoteChar, final char[] escapedChars, - final char[] quotingTriggers, String escapePattern, boolean force ) - { - if ( source == null ) - { + public static String quoteAndEscape( + String source, + char quoteChar, + final char[] escapedChars, + final char[] quotingTriggers, + String escapePattern, + boolean force) { + if (source == null) { return null; } - if ( !force && source.startsWith( Character.toString( quoteChar ) ) - && source.endsWith( Character.toString( quoteChar ) ) ) - { + if (!force + && source.startsWith(Character.toString(quoteChar)) + && source.endsWith(Character.toString(quoteChar))) { return source; } - String escaped = escape( source, escapedChars, escapePattern ); + String escaped = escape(source, escapedChars, escapePattern); boolean quote = false; - if ( force ) - { + if (force) { quote = true; - } - else if ( !escaped.equals( source ) ) - { + } else if (!escaped.equals(source)) { quote = true; - } - else - { - for ( char quotingTrigger : quotingTriggers ) - { - if ( escaped.indexOf( quotingTrigger ) > -1 ) - { + } else { + for (char quotingTrigger : quotingTriggers) { + if (escaped.indexOf(quotingTrigger) > -1) { quote = true; break; } } } - if ( quote ) - { + if (quote) { return quoteChar + escaped + quoteChar; } @@ -2460,9 +2180,8 @@ else if ( !escaped.equals( source ) ) * @return the String escaped * @since 1.5.1 */ - public static String escape( String source, final char[] escapedChars, char escapeChar ) - { - return escape( source, escapedChars, escapeChar + "%s" ); + public static String escape(String source, final char[] escapedChars, char escapeChar) { + return escape(source, escapedChars, escapeChar + "%s"); } /** @@ -2472,31 +2191,25 @@ public static String escape( String source, final char[] escapedChars, char esca * @return the String escaped * @since 3.0.4 */ - public static String escape( String source, final char[] escapedChars, String escapePattern ) - { - if ( source == null ) - { + public static String escape(String source, final char[] escapedChars, String escapePattern) { + if (source == null) { return null; } char[] eqc = new char[escapedChars.length]; - System.arraycopy( escapedChars, 0, eqc, 0, escapedChars.length ); - Arrays.sort( eqc ); + System.arraycopy(escapedChars, 0, eqc, 0, escapedChars.length); + Arrays.sort(eqc); - StringBuilder buffer = new StringBuilder( source.length() ); + StringBuilder buffer = new StringBuilder(source.length()); - for ( int i = 0; i < source.length(); i++ ) - { - final char c = source.charAt( i ); - int result = Arrays.binarySearch( eqc, c ); + for (int i = 0; i < source.length(); i++) { + final char c = source.charAt(i); + int result = Arrays.binarySearch(eqc, c); - if ( result > -1 ) - { - buffer.append( String.format( escapePattern, c ) ); - } - else - { - buffer.append( c ); + if (result > -1) { + buffer.append(String.format(escapePattern, c)); + } else { + buffer.append(c); } } @@ -2510,18 +2223,15 @@ public static String escape( String source, final char[] escapedChars, String es * @return a string with unique whitespace. * @since 1.5.7 */ - public static String removeDuplicateWhitespace( String s ) - { + public static String removeDuplicateWhitespace(String s) { StringBuilder result = new StringBuilder(); int length = s.length(); boolean isPreviousWhiteSpace = false; - for ( int i = 0; i < length; i++ ) - { - char c = s.charAt( i ); - boolean thisCharWhiteSpace = Character.isWhitespace( c ); - if ( !( isPreviousWhiteSpace && thisCharWhiteSpace ) ) - { - result.append( c ); + for (int i = 0; i < length; i++) { + char c = s.charAt(i); + boolean thisCharWhiteSpace = Character.isWhitespace(c); + if (!(isPreviousWhiteSpace && thisCharWhiteSpace)) { + result.append(c); } isPreviousWhiteSpace = thisCharWhiteSpace; } @@ -2536,9 +2246,8 @@ public static String removeDuplicateWhitespace( String s ) * @see #unifyLineSeparators(String, String) * @since 1.5.7 */ - public static String unifyLineSeparators( String s ) - { - return unifyLineSeparators( s, System.getProperty( "line.separator" ) ); + public static String unifyLineSeparators(String s) { + return unifyLineSeparators(s, System.getProperty("line.separator")); } /** @@ -2550,44 +2259,33 @@ public static String unifyLineSeparators( String s ) * @throws IllegalArgumentException if ls is not '\n', '\r' and '\r\n' characters. * @since 1.5.7 */ - public static String unifyLineSeparators( String s, String ls ) - { - if ( s == null ) - { + public static String unifyLineSeparators(String s, String ls) { + if (s == null) { return null; } - if ( ls == null ) - { - ls = System.getProperty( "line.separator" ); + if (ls == null) { + ls = System.getProperty("line.separator"); } - if ( !( ls.equals( "\n" ) || ls.equals( "\r" ) || ls.equals( "\r\n" ) ) ) - { - throw new IllegalArgumentException( "Requested line separator is invalid." ); + if (!(ls.equals("\n") || ls.equals("\r") || ls.equals("\r\n"))) { + throw new IllegalArgumentException("Requested line separator is invalid."); } int length = s.length(); - StringBuilder buffer = new StringBuilder( length ); - for ( int i = 0; i < length; i++ ) - { - if ( s.charAt( i ) == '\r' ) - { - if ( ( i + 1 ) < length && s.charAt( i + 1 ) == '\n' ) - { + StringBuilder buffer = new StringBuilder(length); + for (int i = 0; i < length; i++) { + if (s.charAt(i) == '\r') { + if ((i + 1) < length && s.charAt(i + 1) == '\n') { i++; } - buffer.append( ls ); - } - else if ( s.charAt( i ) == '\n' ) - { - buffer.append( ls ); - } - else - { - buffer.append( s.charAt( i ) ); + buffer.append(ls); + } else if (s.charAt(i) == '\n') { + buffer.append(ls); + } else { + buffer.append(s.charAt(i)); } } @@ -2615,13 +2313,11 @@ else if ( s.charAt( i ) == '\n' ) * @return true if the String contains the search character, false if not or null string input * @since 1.5.7 */ - public static boolean contains( String str, char searchChar ) - { - if ( isEmpty( str ) ) - { + public static boolean contains(String str, char searchChar) { + if (isEmpty(str)) { return false; } - return str.indexOf( searchChar ) >= 0; + return str.indexOf(searchChar) >= 0; } /** @@ -2647,12 +2343,10 @@ public static boolean contains( String str, char searchChar ) * @return true if the String contains the search String, false if not or null string input * @since 1.5.7 */ - public static boolean contains( String str, String searchStr ) - { - if ( str == null || searchStr == null ) - { + public static boolean contains(String str, String searchStr) { + if (str == null || searchStr == null) { return false; } - return str.contains( searchStr ); + return str.contains(searchStr); } } diff --git a/src/main/java/org/codehaus/plexus/util/SweeperPool.java b/src/main/java/org/codehaus/plexus/util/SweeperPool.java index 0a2a97a4..2070b9b8 100644 --- a/src/main/java/org/codehaus/plexus/util/SweeperPool.java +++ b/src/main/java/org/codehaus/plexus/util/SweeperPool.java @@ -25,8 +25,7 @@ * @author Bert van Brakel * */ -public class SweeperPool -{ +public class SweeperPool { /***/ private static final boolean DEBUG = false; @@ -66,41 +65,34 @@ public class SweeperPool * @param intialCapacity the intial capacity *

    Any value less than 0 is automatically converted to 0

    */ - public SweeperPool( int maxSize, int minSize, int intialCapacity, int sweepInterval, int triggerSize ) - { + public SweeperPool(int maxSize, int minSize, int intialCapacity, int sweepInterval, int triggerSize) { super(); - this.maxSize = saneConvert( maxSize ); - this.minSize = saneConvert( minSize ); - this.triggerSize = saneConvert( triggerSize ); - pooledObjects = new ArrayList( intialCapacity ); + this.maxSize = saneConvert(maxSize); + this.minSize = saneConvert(minSize); + this.triggerSize = saneConvert(triggerSize); + pooledObjects = new ArrayList(intialCapacity); // only run a sweeper if sweep interval is positive - if ( sweepInterval > 0 ) - { - sweeper = new Sweeper( this, sweepInterval ); + if (sweepInterval > 0) { + sweeper = new Sweeper(this, sweepInterval); sweeper.start(); } } - private int saneConvert( int value ) - { - return Math.max( value, 0 ); + private int saneConvert(int value) { + return Math.max(value, 0); } /** * Return the pooled object * @return first available object from the pool */ - public synchronized Object get() - { - if ( ( pooledObjects.size() == 0 ) || shuttingDown ) - { + public synchronized Object get() { + if ((pooledObjects.size() == 0) || shuttingDown) { return null; - } - else - { - Object obj = pooledObjects.remove( 0 ); - objectRetrieved( obj ); + } else { + Object obj = pooledObjects.remove(0); + objectRetrieved(obj); // used.add(obj); return obj; @@ -113,20 +105,16 @@ public synchronized Object get() * @param obj the object to pool. Can be null. * @return true if the object was added to the pool, false if it was disposed or null */ - public synchronized boolean put( Object obj ) - { - objectAdded( obj ); + public synchronized boolean put(Object obj) { + objectAdded(obj); - if ( ( obj != null ) && ( pooledObjects.size() < maxSize ) && ( shuttingDown == false ) ) - { - pooledObjects.add( obj ); + if ((obj != null) && (pooledObjects.size() < maxSize) && (shuttingDown == false)) { + pooledObjects.add(obj); return true; - } - else if ( obj != null ) - { + } else if (obj != null) { // no longer need the object, so dispose it - objectDisposed( obj ); + objectDisposed(obj); } return false; @@ -137,41 +125,33 @@ else if ( obj != null ) * * @return the number of pooled objects */ - public synchronized int getSize() - { + public synchronized int getSize() { return pooledObjects.size(); } /** * Dispose of this pool. Stops the sweeper and disposes each object in the pool */ - public void dispose() - { + public void dispose() { shuttingDown = true; - if ( sweeper != null ) - { + if (sweeper != null) { sweeper.stop(); - try - { + try { sweeper.join(); - } - catch ( InterruptedException e ) - { - System.err.println( "Unexpected exception occurred: " ); + } catch (InterruptedException e) { + System.err.println("Unexpected exception occurred: "); e.printStackTrace(); } } - synchronized ( this ) - { + synchronized (this) { // use an array here as objects may still be being put back in the pool // and we don't want to throw a ConcurrentModificationException Object[] objects = pooledObjects.toArray(); - for ( Object object : objects ) - { - objectDisposed( object ); + for (Object object : objects) { + objectDisposed(object); } pooledObjects.clear(); @@ -183,16 +163,13 @@ public void dispose() * * @return true if the pool has been disposed, false otherwise */ - boolean isDisposed() - { - if ( !shuttingDown ) - { + boolean isDisposed() { + if (!shuttingDown) { return false; } // A null sweeper means one was never started. - if ( sweeper == null ) - { + if (sweeper == null) { return true; } @@ -202,14 +179,11 @@ boolean isDisposed() /** * Trim the pool down to min size */ - public synchronized void trim() - { - if ( ( ( triggerSize > 0 ) && ( pooledObjects.size() >= triggerSize ) ) - || ( ( maxSize > 0 ) && ( pooledObjects.size() >= maxSize ) ) ) - { - while ( pooledObjects.size() > minSize ) - { - objectDisposed( pooledObjects.remove( 0 ) ); + public synchronized void trim() { + if (((triggerSize > 0) && (pooledObjects.size() >= triggerSize)) + || ((maxSize > 0) && (pooledObjects.size() >= maxSize))) { + while (pooledObjects.size() > minSize) { + objectDisposed(pooledObjects.remove(0)); } } } @@ -220,18 +194,14 @@ public synchronized void trim() * * @param obj the Object */ - public void objectDisposed( Object obj ) - { - } + public void objectDisposed(Object obj) {} /** * Override this to be notified of object addition. Called before object is to be added. * * @param obj the Object */ - public void objectAdded( Object obj ) - { - } + public void objectAdded(Object obj) {} /** * Override this to be notified of object retrieval. Called after object removed from the pool, but before returned @@ -239,18 +209,14 @@ public void objectAdded( Object obj ) * * @param obj the Object */ - public void objectRetrieved( Object obj ) - { - } + public void objectRetrieved(Object obj) {} /** * Periodically at sweepInterval goes through and tests if the pool should be trimmed. * * @author bert */ - private static class Sweeper - implements Runnable - { + private static class Sweeper implements Runnable { private final transient SweeperPool pool; private transient boolean service = false; @@ -262,8 +228,7 @@ private static class Sweeper /** * */ - public Sweeper( SweeperPool pool, int sweepInterval ) - { + public Sweeper(SweeperPool pool, int sweepInterval) { super(); this.sweepInterval = sweepInterval; this.pool = pool; @@ -275,72 +240,56 @@ public Sweeper( SweeperPool pool, int sweepInterval ) * @see java.lang.Runnable#run() */ @Override - public void run() - { - debug( "started" ); - - if ( sweepInterval > 0 ) - { - synchronized ( this ) - { - while ( service ) - { - try - { + public void run() { + debug("started"); + + if (sweepInterval > 0) { + synchronized (this) { + while (service) { + try { // wait specified number of seconds // before running next sweep - wait( sweepInterval * 1000 ); - } - catch ( InterruptedException e ) - { + wait(sweepInterval * 1000); + } catch (InterruptedException e) { } runSweep(); } } } - debug( "stopped" ); + debug("stopped"); } - public void start() - { - if ( !service ) - { + public void start() { + if (!service) { service = true; - t = new Thread( this ); - t.setName( "Sweeper" ); + t = new Thread(this); + t.setName("Sweeper"); t.start(); } } - public synchronized void stop() - { + public synchronized void stop() { service = false; notifyAll(); } - void join() - throws InterruptedException - { + void join() throws InterruptedException { t.join(); } - boolean hasStopped() - { + boolean hasStopped() { return !service && !t.isAlive(); } - private final void debug( String msg ) - { - if ( DEBUG ) - { - System.err.println( this + ":" + msg ); + private final void debug(String msg) { + if (DEBUG) { + System.err.println(this + ":" + msg); } } - private void runSweep() - { - debug( "runningSweep. time=" + System.currentTimeMillis() ); + private void runSweep() { + debug("runningSweep. time=" + System.currentTimeMillis()); pool.trim(); } } diff --git a/src/main/java/org/codehaus/plexus/util/TypeFormat.java b/src/main/java/org/codehaus/plexus/util/TypeFormat.java index f950003b..e4fc64b7 100644 --- a/src/main/java/org/codehaus/plexus/util/TypeFormat.java +++ b/src/main/java/org/codehaus/plexus/util/TypeFormat.java @@ -16,7 +16,7 @@ *

    * For class instances, formatting is typically performed using specialized java.text.Format * (Locale sensitive) and/or using conventional methods (class sensitive). For example: - * + * *
      *     public class Foo {
      *         public static Foo valueOf(CharSequence chars) {...} // Parses.
    @@ -33,21 +33,20 @@
      * @author Jean-Marie Dautelle
      * @version 4.6, June 22, 2003
      */
    -public final class TypeFormat
    -{
    +public final class TypeFormat {
     
         /**
          * Holds the characters used to represent numbers.
          */
    -    private final static char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
    -        'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
    +    private static final char[] DIGITS = {
    +        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
    +        'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
    +    };
     
         /**
          * Default constructor (forbids derivation).
          */
    -    private TypeFormat()
    -    {
    -    }
    +    private TypeFormat() {}
     
         /**
          * Searches for a particular sequence within a character sequence (general purpose parsing function).
    @@ -58,38 +57,29 @@ private TypeFormat()
          * @return the index in the range [fromIndex, chars.length()-pattern.length()] or -1 if
          *         the character sequence is not found.
          */
    -    public static int indexOf( CharSequence pattern, CharSequence chars, int fromIndex )
    -    {
    +    public static int indexOf(CharSequence pattern, CharSequence chars, int fromIndex) {
             int patternLength = pattern.length();
    -        fromIndex = Math.max( 0, fromIndex );
    -        if ( patternLength != 0 )
    -        { // At least one character to search for.
    -            char firstChar = pattern.charAt( 0 );
    +        fromIndex = Math.max(0, fromIndex);
    +        if (patternLength != 0) { // At least one character to search for.
    +            char firstChar = pattern.charAt(0);
                 int last = chars.length() - patternLength;
    -            for ( int i = fromIndex; i <= last; i++ )
    -            {
    -                if ( chars.charAt( i ) == firstChar )
    -                {
    +            for (int i = fromIndex; i <= last; i++) {
    +                if (chars.charAt(i) == firstChar) {
                         boolean match = true;
    -                    for ( int j = 1; j < patternLength; j++ )
    -                    {
    -                        if ( chars.charAt( i + j ) != pattern.charAt( j ) )
    -                        {
    +                    for (int j = 1; j < patternLength; j++) {
    +                        if (chars.charAt(i + j) != pattern.charAt(j)) {
                                 match = false;
                                 break;
                             }
                         }
    -                    if ( match )
    -                    {
    +                    if (match) {
                             return i;
                         }
                     }
                 }
                 return -1;
    -        }
    -        else
    -        {
    -            return Math.min( 0, fromIndex );
    +        } else {
    +            return Math.min(0, fromIndex);
             }
         }
     
    @@ -99,12 +89,12 @@ public static int indexOf( CharSequence pattern, CharSequence chars, int fromInd
          * @param chars the character sequence to parse.
          * @return the corresponding boolean.
          */
    -    public static boolean parseBoolean( CharSequence chars )
    -    {
    -        return ( chars.length() == 4 ) && ( chars.charAt( 0 ) == 't' || chars.charAt( 0 ) == 'T' )
    -            && ( chars.charAt( 1 ) == 'r' || chars.charAt( 1 ) == 'R' )
    -            && ( chars.charAt( 2 ) == 'u' || chars.charAt( 2 ) == 'U' )
    -            && ( chars.charAt( 3 ) == 'e' || chars.charAt( 3 ) == 'E' );
    +    public static boolean parseBoolean(CharSequence chars) {
    +        return (chars.length() == 4)
    +                && (chars.charAt(0) == 't' || chars.charAt(0) == 'T')
    +                && (chars.charAt(1) == 'r' || chars.charAt(1) == 'R')
    +                && (chars.charAt(2) == 'u' || chars.charAt(2) == 'U')
    +                && (chars.charAt(3) == 'e' || chars.charAt(3) == 'E');
         }
     
         /**
    @@ -115,9 +105,8 @@ public static boolean parseBoolean( CharSequence chars )
          * @throws NumberFormatException if the specified character sequence does not contain a parsable short.
          * @see #parseShort(CharSequence, int)
          */
    -    public static short parseShort( CharSequence chars )
    -    {
    -        return parseShort( chars, 10 );
    +    public static short parseShort(CharSequence chars) {
    +        return parseShort(chars, 10);
         }
     
         /**
    @@ -130,36 +119,29 @@ public static short parseShort( CharSequence chars )
          * @return the corresponding short.
          * @throws NumberFormatException if the specified character sequence does not contain a parsable short.
          */
    -    public static short parseShort( CharSequence chars, int radix )
    -    {
    -        try
    -        {
    -            boolean isNegative = ( chars.charAt( 0 ) == '-' ) ? true : false;
    +    public static short parseShort(CharSequence chars, int radix) {
    +        try {
    +            boolean isNegative = (chars.charAt(0) == '-') ? true : false;
                 int result = 0;
    -            int limit = ( isNegative ) ? Short.MIN_VALUE : -Short.MAX_VALUE;
    +            int limit = (isNegative) ? Short.MIN_VALUE : -Short.MAX_VALUE;
                 int multmin = limit / radix;
                 int length = chars.length();
    -            int i = ( isNegative || ( chars.charAt( 0 ) == '+' ) ) ? 1 : 0;
    -            while ( true )
    -            {
    -                int digit = Character.digit( chars.charAt( i ), radix );
    +            int i = (isNegative || (chars.charAt(0) == '+')) ? 1 : 0;
    +            while (true) {
    +                int digit = Character.digit(chars.charAt(i), radix);
                     int tmp = result * radix;
    -                if ( ( digit < 0 ) || ( result < multmin ) || ( tmp < limit + digit ) )
    -                { // Overflow.
    -                    throw new NumberFormatException( "For input characters: \"" + chars.toString() + "\"" );
    +                if ((digit < 0) || (result < multmin) || (tmp < limit + digit)) { // Overflow.
    +                    throw new NumberFormatException("For input characters: \"" + chars.toString() + "\"");
                     }
                     // Accumulates negatively.
                     result = tmp - digit;
    -                if ( ++i >= length )
    -                {
    +                if (++i >= length) {
                         break;
                     }
                 }
    -            return (short) ( isNegative ? result : -result );
    -        }
    -        catch ( IndexOutOfBoundsException e )
    -        {
    -            throw new NumberFormatException( "For input characters: \"" + chars.toString() + "\"" );
    +            return (short) (isNegative ? result : -result);
    +        } catch (IndexOutOfBoundsException e) {
    +            throw new NumberFormatException("For input characters: \"" + chars.toString() + "\"");
             }
         }
     
    @@ -171,9 +153,8 @@ public static short parseShort( CharSequence chars, int radix )
          * @throws NumberFormatException if the specified character sequence does not contain a parsable int.
          * @see #parseInt(CharSequence, int)
          */
    -    public static int parseInt( CharSequence chars )
    -    {
    -        return parseInt( chars, 10 );
    +    public static int parseInt(CharSequence chars) {
    +        return parseInt(chars, 10);
         }
     
         /**
    @@ -186,36 +167,29 @@ public static int parseInt( CharSequence chars )
          * @return the corresponding int.
          * @throws NumberFormatException if the specified character sequence does not contain a parsable int.
          */
    -    public static int parseInt( CharSequence chars, int radix )
    -    {
    -        try
    -        {
    -            boolean isNegative = ( chars.charAt( 0 ) == '-' ) ? true : false;
    +    public static int parseInt(CharSequence chars, int radix) {
    +        try {
    +            boolean isNegative = (chars.charAt(0) == '-') ? true : false;
                 int result = 0;
    -            int limit = ( isNegative ) ? Integer.MIN_VALUE : -Integer.MAX_VALUE;
    +            int limit = (isNegative) ? Integer.MIN_VALUE : -Integer.MAX_VALUE;
                 int multmin = limit / radix;
                 int length = chars.length();
    -            int i = ( isNegative || ( chars.charAt( 0 ) == '+' ) ) ? 1 : 0;
    -            while ( true )
    -            {
    -                int digit = Character.digit( chars.charAt( i ), radix );
    +            int i = (isNegative || (chars.charAt(0) == '+')) ? 1 : 0;
    +            while (true) {
    +                int digit = Character.digit(chars.charAt(i), radix);
                     int tmp = result * radix;
    -                if ( ( digit < 0 ) || ( result < multmin ) || ( tmp < limit + digit ) )
    -                { // Overflow.
    -                    throw new NumberFormatException( "For input characters: \"" + chars.toString() + "\"" );
    +                if ((digit < 0) || (result < multmin) || (tmp < limit + digit)) { // Overflow.
    +                    throw new NumberFormatException("For input characters: \"" + chars.toString() + "\"");
                     }
                     // Accumulates negatively to avoid surprises near MAX_VALUE
                     result = tmp - digit;
    -                if ( ++i >= length )
    -                {
    +                if (++i >= length) {
                         break;
                     }
                 }
                 return isNegative ? result : -result;
    -        }
    -        catch ( IndexOutOfBoundsException e )
    -        {
    -            throw new NumberFormatException( "For input characters: \"" + chars.toString() + "\"" );
    +        } catch (IndexOutOfBoundsException e) {
    +            throw new NumberFormatException("For input characters: \"" + chars.toString() + "\"");
             }
         }
     
    @@ -227,9 +201,8 @@ public static int parseInt( CharSequence chars, int radix )
          * @throws NumberFormatException if the specified character sequence does not contain a parsable long.
          * @see #parseLong(CharSequence, int)
          */
    -    public static long parseLong( CharSequence chars )
    -    {
    -        return parseLong( chars, 10 );
    +    public static long parseLong(CharSequence chars) {
    +        return parseLong(chars, 10);
         }
     
         /**
    @@ -242,36 +215,29 @@ public static long parseLong( CharSequence chars )
          * @return the corresponding long.
          * @throws NumberFormatException if the specified character sequence does not contain a parsable long.
          */
    -    public static long parseLong( CharSequence chars, int radix )
    -    {
    -        try
    -        {
    -            boolean isNegative = ( chars.charAt( 0 ) == '-' ) ? true : false;
    +    public static long parseLong(CharSequence chars, int radix) {
    +        try {
    +            boolean isNegative = (chars.charAt(0) == '-') ? true : false;
                 long result = 0;
    -            long limit = ( isNegative ) ? Long.MIN_VALUE : -Long.MAX_VALUE;
    +            long limit = (isNegative) ? Long.MIN_VALUE : -Long.MAX_VALUE;
                 long multmin = limit / radix;
                 int length = chars.length();
    -            int i = ( isNegative || ( chars.charAt( 0 ) == '+' ) ) ? 1 : 0;
    -            while ( true )
    -            {
    -                int digit = Character.digit( chars.charAt( i ), radix );
    +            int i = (isNegative || (chars.charAt(0) == '+')) ? 1 : 0;
    +            while (true) {
    +                int digit = Character.digit(chars.charAt(i), radix);
                     long tmp = result * radix;
    -                if ( ( digit < 0 ) || ( result < multmin ) || ( tmp < limit + digit ) )
    -                { // Overflow.
    -                    throw new NumberFormatException( "For input characters: \"" + chars.toString() + "\"" );
    +                if ((digit < 0) || (result < multmin) || (tmp < limit + digit)) { // Overflow.
    +                    throw new NumberFormatException("For input characters: \"" + chars.toString() + "\"");
                     }
                     // Accumulates negatively to avoid surprises near MAX_VALUE
                     result = tmp - digit;
    -                if ( ++i >= length )
    -                {
    +                if (++i >= length) {
                         break;
                     }
                 }
                 return isNegative ? result : -result;
    -        }
    -        catch ( IndexOutOfBoundsException e )
    -        {
    -            throw new NumberFormatException( "For input characters: \"" + chars.toString() + "\"" );
    +        } catch (IndexOutOfBoundsException e) {
    +            throw new NumberFormatException("For input characters: \"" + chars.toString() + "\"");
             }
         }
     
    @@ -282,16 +248,12 @@ public static long parseLong( CharSequence chars, int radix )
          * @return the float number represented by the specified character sequence.
          * @throws NumberFormatException if the character sequence does not contain a parsable float.
          */
    -    public static float parseFloat( CharSequence chars )
    -    {
    -        double d = parseDouble( chars );
    -        if ( ( d >= Float.MIN_VALUE ) && ( d <= Float.MAX_VALUE ) )
    -        {
    +    public static float parseFloat(CharSequence chars) {
    +        double d = parseDouble(chars);
    +        if ((d >= Float.MIN_VALUE) && (d <= Float.MAX_VALUE)) {
                 return (float) d;
    -        }
    -        else
    -        {
    -            throw new NumberFormatException( "Float overflow for input characters: \"" + chars.toString() + "\"" );
    +        } else {
    +            throw new NumberFormatException("Float overflow for input characters: \"" + chars.toString() + "\"");
             }
         }
     
    @@ -302,87 +264,63 @@ public static float parseFloat( CharSequence chars )
          * @return the double number represented by this character sequence.
          * @throws NumberFormatException if the character sequence does not contain a parsable double.
          */
    -    public static double parseDouble( CharSequence chars )
    -        throws NumberFormatException
    -    {
    -        try
    -        {
    +    public static double parseDouble(CharSequence chars) throws NumberFormatException {
    +        try {
                 int length = chars.length();
                 double result = 0.0;
                 int exp = 0;
     
    -            boolean isNegative = ( chars.charAt( 0 ) == '-' ) ? true : false;
    -            int i = ( isNegative || ( chars.charAt( 0 ) == '+' ) ) ? 1 : 0;
    +            boolean isNegative = (chars.charAt(0) == '-') ? true : false;
    +            int i = (isNegative || (chars.charAt(0) == '+')) ? 1 : 0;
     
                 // Checks special cases NaN or Infinity.
    -            if ( ( chars.charAt( i ) == 'N' ) || ( chars.charAt( i ) == 'I' ) )
    -            {
    -                if ( chars.toString().equals( "NaN" ) )
    -                {
    +            if ((chars.charAt(i) == 'N') || (chars.charAt(i) == 'I')) {
    +                if (chars.toString().equals("NaN")) {
                         return Double.NaN;
    -                }
    -                else if ( chars.subSequence( i, length ).toString().equals( "Infinity" ) )
    -                {
    +                } else if (chars.subSequence(i, length).toString().equals("Infinity")) {
                         return isNegative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
                     }
                 }
     
                 // Reads decimal number.
                 boolean fraction = false;
    -            while ( true )
    -            {
    -                char c = chars.charAt( i );
    -                if ( ( c == '.' ) && ( !fraction ) )
    -                {
    +            while (true) {
    +                char c = chars.charAt(i);
    +                if ((c == '.') && (!fraction)) {
                         fraction = true;
    -                }
    -                else if ( ( c == 'e' ) || ( c == 'E' ) )
    -                {
    +                } else if ((c == 'e') || (c == 'E')) {
                         break;
    -                }
    -                else if ( ( c >= '0' ) && ( c <= '9' ) )
    -                {
    -                    result = result * 10 + ( c - '0' );
    -                    if ( fraction )
    -                    {
    +                } else if ((c >= '0') && (c <= '9')) {
    +                    result = result * 10 + (c - '0');
    +                    if (fraction) {
                             exp--;
                         }
    +                } else {
    +                    throw new NumberFormatException("For input characters: \"" + chars.toString() + "\"");
                     }
    -                else
    -                {
    -                    throw new NumberFormatException( "For input characters: \"" + chars.toString() + "\"" );
    -                }
    -                if ( ++i >= length )
    -                {
    +                if (++i >= length) {
                         break;
                     }
                 }
                 result = isNegative ? -result : result;
     
                 // Reads exponent (if any).
    -            if ( i < length )
    -            {
    +            if (i < length) {
                     i++;
    -                boolean negE = ( chars.charAt( i ) == '-' ) ? true : false;
    -                i = ( negE || ( chars.charAt( i ) == '+' ) ) ? i + 1 : i;
    +                boolean negE = (chars.charAt(i) == '-') ? true : false;
    +                i = (negE || (chars.charAt(i) == '+')) ? i + 1 : i;
                     int valE = 0;
    -                while ( true )
    -                {
    -                    char c = chars.charAt( i );
    -                    if ( ( c >= '0' ) && ( c <= '9' ) )
    -                    {
    -                        valE = valE * 10 + ( c - '0' );
    -                        if ( valE > 10000000 )
    -                        { // Hard-limit to avoid overflow.
    +                while (true) {
    +                    char c = chars.charAt(i);
    +                    if ((c >= '0') && (c <= '9')) {
    +                        valE = valE * 10 + (c - '0');
    +                        if (valE > 10000000) { // Hard-limit to avoid overflow.
                                 valE = 10000000;
                             }
    +                    } else {
    +                        throw new NumberFormatException("For input characters: \"" + chars.toString() + "\"");
                         }
    -                    else
    -                    {
    -                        throw new NumberFormatException( "For input characters: \"" + chars.toString() + "\"" );
    -                    }
    -                    if ( ++i >= length )
    -                    {
    +                    if (++i >= length) {
                             break;
                         }
                     }
    @@ -390,12 +328,10 @@ else if ( ( c >= '0' ) && ( c <= '9' ) )
                 }
     
                 // Returns product decimal number with exponent.
    -            return multE( result, exp );
    +            return multE(result, exp);
     
    -        }
    -        catch ( IndexOutOfBoundsException e )
    -        {
    -            throw new NumberFormatException( "For input characters: \"" + chars.toString() + "\"" );
    +        } catch (IndexOutOfBoundsException e) {
    +            throw new NumberFormatException("For input characters: \"" + chars.toString() + "\"");
             }
         }
     
    @@ -408,9 +344,8 @@ else if ( ( c >= '0' ) && ( c <= '9' ) )
          * @return the specified StringBuffer object.
          * @see #parseBoolean
          */
    -    public static StringBuffer format( boolean b, StringBuffer sb )
    -    {
    -        return b ? sb.append( "true" ) : sb.append( "false" );
    +    public static StringBuffer format(boolean b, StringBuffer sb) {
    +        return b ? sb.append("true") : sb.append("false");
         }
     
         /**
    @@ -427,9 +362,8 @@ public static StringBuffer format( boolean b, StringBuffer sb )
          * @return the specified StringBuffer object.
          * @see #parseShort
          */
    -    public static StringBuffer format( short s, StringBuffer sb )
    -    {
    -        return format( (int) s, sb ); // Forwards to int formatting (fast).
    +    public static StringBuffer format(short s, StringBuffer sb) {
    +        return format((int) s, sb); // Forwards to int formatting (fast).
         }
     
         /**
    @@ -442,9 +376,8 @@ public static StringBuffer format( short s, StringBuffer sb )
          * @return the specified StringBuffer object.
          * @see #parseShort(CharSequence, int) throws IllegalArgumentException if radix is not in [2 .. 36] range.
          */
    -    public static StringBuffer format( short s, int radix, StringBuffer sb )
    -    {
    -        return format( (int) s, radix, sb ); // Forwards to int formatting (fast).
    +    public static StringBuffer format(short s, int radix, StringBuffer sb) {
    +        return format((int) s, radix, sb); // Forwards to int formatting (fast).
         }
     
         /**
    @@ -461,42 +394,33 @@ public static StringBuffer format( short s, int radix, StringBuffer sb )
          * @return the specified StringBuffer object.
          * @see #parseInt
          */
    -    public static StringBuffer format( int i, StringBuffer sb )
    -    {
    -        if ( i <= 0 )
    -        {
    -            if ( i == Integer.MIN_VALUE )
    -            { // Negation would overflow.
    -                return sb.append( "-2147483648" ); // 11 char max.
    -            }
    -            else if ( i == 0 )
    -            {
    -                return sb.append( '0' );
    +    public static StringBuffer format(int i, StringBuffer sb) {
    +        if (i <= 0) {
    +            if (i == Integer.MIN_VALUE) { // Negation would overflow.
    +                return sb.append("-2147483648"); // 11 char max.
    +            } else if (i == 0) {
    +                return sb.append('0');
                 }
                 i = -i;
    -            sb.append( '-' );
    +            sb.append('-');
             }
             int j = 1;
    -        for ( ; ( j < 10 ) && ( i >= INT_POW_10[j] ); j++ )
    -        {
    -        }
    +        for (; (j < 10) && (i >= INT_POW_10[j]); j++) {}
             // POW_10[j] > i >= POW_10[j-1]
    -        for ( j--; j >= 0; j-- )
    -        {
    +        for (j--; j >= 0; j--) {
                 int pow10 = INT_POW_10[j];
                 int digit = i / pow10;
                 i -= digit * pow10;
    -            sb.append( DIGITS[digit] );
    +            sb.append(DIGITS[digit]);
             }
             return sb;
         }
     
         private static final int[] INT_POW_10 = new int[10];
    -    static
    -    {
    +
    +    static {
             int pow = 1;
    -        for ( int i = 0; i < 10; i++ )
    -        {
    +        for (int i = 0; i < 10; i++) {
                 INT_POW_10[i] = pow;
                 pow *= 10;
             }
    @@ -512,38 +436,27 @@ else if ( i == 0 )
          * @return the specified StringBuffer object.
          * @see #parseInt(CharSequence, int) throws IllegalArgumentException if radix is not in [2 .. 36] range.
          */
    -    public static StringBuffer format( int i, int radix, StringBuffer sb )
    -    {
    -        if ( radix == 10 )
    -        {
    -            return format( i, sb ); // Faster version.
    -        }
    -        else if ( radix < 2 || radix > 36 )
    -        {
    -            throw new IllegalArgumentException( "radix: " + radix );
    -        }
    -        if ( i < 0 )
    -        {
    -            sb.append( '-' );
    -        }
    -        else
    -        {
    +    public static StringBuffer format(int i, int radix, StringBuffer sb) {
    +        if (radix == 10) {
    +            return format(i, sb); // Faster version.
    +        } else if (radix < 2 || radix > 36) {
    +            throw new IllegalArgumentException("radix: " + radix);
    +        }
    +        if (i < 0) {
    +            sb.append('-');
    +        } else {
                 i = -i;
             }
    -        format2( i, radix, sb );
    +        format2(i, radix, sb);
             return sb;
         }
     
    -    private static void format2( int i, int radix, StringBuffer sb )
    -    {
    -        if ( i <= -radix )
    -        {
    -            format2( i / radix, radix, sb );
    -            sb.append( DIGITS[-( i % radix )] );
    -        }
    -        else
    -        {
    -            sb.append( DIGITS[-i] );
    +    private static void format2(int i, int radix, StringBuffer sb) {
    +        if (i <= -radix) {
    +            format2(i / radix, radix, sb);
    +            sb.append(DIGITS[-(i % radix)]);
    +        } else {
    +            sb.append(DIGITS[-i]);
             }
         }
     
    @@ -561,42 +474,33 @@ private static void format2( int i, int radix, StringBuffer sb )
          * @return the specified StringBuffer object.
          * @see #parseLong
          */
    -    public static StringBuffer format( long l, StringBuffer sb )
    -    {
    -        if ( l <= 0 )
    -        {
    -            if ( l == Long.MIN_VALUE )
    -            { // Negation would overflow.
    -                return sb.append( "-9223372036854775808" ); // 20 characters max.
    -            }
    -            else if ( l == 0 )
    -            {
    -                return sb.append( '0' );
    +    public static StringBuffer format(long l, StringBuffer sb) {
    +        if (l <= 0) {
    +            if (l == Long.MIN_VALUE) { // Negation would overflow.
    +                return sb.append("-9223372036854775808"); // 20 characters max.
    +            } else if (l == 0) {
    +                return sb.append('0');
                 }
                 l = -l;
    -            sb.append( '-' );
    +            sb.append('-');
             }
             int j = 1;
    -        for ( ; ( j < 19 ) && ( l >= LONG_POW_10[j] ); j++ )
    -        {
    -        }
    +        for (; (j < 19) && (l >= LONG_POW_10[j]); j++) {}
             // POW_10[j] > l >= POW_10[j-1]
    -        for ( j--; j >= 0; j-- )
    -        {
    +        for (j--; j >= 0; j--) {
                 long pow10 = LONG_POW_10[j];
    -            int digit = (int) ( l / pow10 );
    +            int digit = (int) (l / pow10);
                 l -= digit * pow10;
    -            sb.append( DIGITS[digit] );
    +            sb.append(DIGITS[digit]);
             }
             return sb;
         }
     
         private static final long[] LONG_POW_10 = new long[19];
    -    static
    -    {
    +
    +    static {
             long pow = 1;
    -        for ( int i = 0; i < 19; i++ )
    -        {
    +        for (int i = 0; i < 19; i++) {
                 LONG_POW_10[i] = pow;
                 pow *= 10;
             }
    @@ -612,38 +516,27 @@ else if ( l == 0 )
          * @return the specified StringBuffer object.
          * @see #parseLong(CharSequence, int) throws IllegalArgumentException if radix is not in [2 .. 36] range.
          */
    -    public static StringBuffer format( long l, int radix, StringBuffer sb )
    -    {
    -        if ( radix == 10 )
    -        {
    -            return format( l, sb ); // Faster version.
    -        }
    -        else if ( radix < 2 || radix > 36 )
    -        {
    -            throw new IllegalArgumentException( "radix: " + radix );
    -        }
    -        if ( l < 0 )
    -        {
    -            sb.append( '-' );
    -        }
    -        else
    -        {
    +    public static StringBuffer format(long l, int radix, StringBuffer sb) {
    +        if (radix == 10) {
    +            return format(l, sb); // Faster version.
    +        } else if (radix < 2 || radix > 36) {
    +            throw new IllegalArgumentException("radix: " + radix);
    +        }
    +        if (l < 0) {
    +            sb.append('-');
    +        } else {
                 l = -l;
             }
    -        format2( l, radix, sb );
    +        format2(l, radix, sb);
             return sb;
         }
     
    -    private static void format2( long l, int radix, StringBuffer sb )
    -    {
    -        if ( l <= -radix )
    -        {
    -            format2( l / radix, radix, sb );
    -            sb.append( DIGITS[(int) -( l % radix )] );
    -        }
    -        else
    -        {
    -            sb.append( DIGITS[(int) -l] );
    +    private static void format2(long l, int radix, StringBuffer sb) {
    +        if (l <= -radix) {
    +            format2(l / radix, radix, sb);
    +            sb.append(DIGITS[(int) -(l % radix)]);
    +        } else {
    +            sb.append(DIGITS[(int) -l]);
             }
         }
     
    @@ -656,9 +549,8 @@ private static void format2( long l, int radix, StringBuffer sb )
          * @return format(f, 0.0f, sb)
          * @see #format(float, float, StringBuffer)
          */
    -    public static StringBuffer format( float f, StringBuffer sb )
    -    {
    -        return format( f, 0.0f, sb );
    +    public static StringBuffer format(float f, StringBuffer sb) {
    +        return format(f, 0.0f, sb);
         }
     
         /**
    @@ -680,31 +572,22 @@ public static StringBuffer format( float f, StringBuffer sb )
          * @return the specified StringBuffer object.
          * @throws IllegalArgumentException if the specified precision is negative or would result in too many digits (19+).
          */
    -    public static StringBuffer format( float f, float precision, StringBuffer sb )
    -    {
    +    public static StringBuffer format(float f, float precision, StringBuffer sb) {
             // Adjusts precision.
             boolean precisionOnLastDigit;
    -        if ( precision > 0.0f )
    -        {
    +        if (precision > 0.0f) {
                 precisionOnLastDigit = true;
    -        }
    -        else if ( precision == 0.0f )
    -        {
    -            if ( f != 0.0f )
    -            {
    +        } else if (precision == 0.0f) {
    +            if (f != 0.0f) {
                     precisionOnLastDigit = false;
    -                precision = Math.max( Math.abs( f * FLOAT_RELATIVE_ERROR ), Float.MIN_VALUE );
    +                precision = Math.max(Math.abs(f * FLOAT_RELATIVE_ERROR), Float.MIN_VALUE);
    +            } else {
    +                return sb.append("0.0"); // Exact zero.
                 }
    -            else
    -            {
    -                return sb.append( "0.0" ); // Exact zero.
    -            }
    -        }
    -        else
    -        {
    -            throw new IllegalArgumentException( "precision: Negative values not allowed" );
    +        } else {
    +            throw new IllegalArgumentException("precision: Negative values not allowed");
             }
    -        return format( f, precision, precisionOnLastDigit, sb );
    +        return format(f, precision, precisionOnLastDigit, sb);
         }
     
         /**
    @@ -723,9 +606,8 @@ else if ( precision == 0.0f )
          * @return format(d, 0.0, sb)
          * @see #format(double, double, StringBuffer)
          */
    -    public static StringBuffer format( double d, StringBuffer sb )
    -    {
    -        return format( d, 0.0, sb );
    +    public static StringBuffer format(double d, StringBuffer sb) {
    +        return format(d, 0.0, sb);
         }
     
         /**
    @@ -738,16 +620,12 @@ public static StringBuffer format( double d, StringBuffer sb )
          * @return the specified StringBuffer object.
          * @throws IllegalArgumentException if the number of digits is not in range [1..19].
          */
    -    public static StringBuffer format( double d, int digits, StringBuffer sb )
    -    {
    -        if ( ( digits >= 1 ) && ( digits <= 19 ) )
    -        {
    -            double precision = Math.abs( d / DOUBLE_POW_10[digits - 1] );
    -            return format( d, precision, sb );
    -        }
    -        else
    -        {
    -            throw new java.lang.IllegalArgumentException( "digits: " + digits + " is not in range [1 .. 19]" );
    +    public static StringBuffer format(double d, int digits, StringBuffer sb) {
    +        if ((digits >= 1) && (digits <= 19)) {
    +            double precision = Math.abs(d / DOUBLE_POW_10[digits - 1]);
    +            return format(d, precision, sb);
    +        } else {
    +            throw new java.lang.IllegalArgumentException("digits: " + digits + " is not in range [1 .. 19]");
             }
         }
     
    @@ -770,30 +648,21 @@ public static StringBuffer format( double d, int digits, StringBuffer sb )
          * @return the specified StringBuffer object.
          * @throws IllegalArgumentException if the specified precision is negative or would result in too many digits (19+).
          */
    -    public static StringBuffer format( double d, double precision, StringBuffer sb )
    -    {
    +    public static StringBuffer format(double d, double precision, StringBuffer sb) {
             // Adjusts precision.
             boolean precisionOnLastDigit = false;
    -        if ( precision > 0.0 )
    -        {
    +        if (precision > 0.0) {
                 precisionOnLastDigit = true;
    -        }
    -        else if ( precision == 0.0 )
    -        {
    -            if ( d != 0.0 )
    -            {
    -                precision = Math.max( Math.abs( d * DOUBLE_RELATIVE_ERROR ), Double.MIN_VALUE );
    -            }
    -            else
    -            {
    -                return sb.append( "0.0" ); // Exact zero.
    +        } else if (precision == 0.0) {
    +            if (d != 0.0) {
    +                precision = Math.max(Math.abs(d * DOUBLE_RELATIVE_ERROR), Double.MIN_VALUE);
    +            } else {
    +                return sb.append("0.0"); // Exact zero.
                 }
    +        } else if (precision < 0.0) { // Not NaN
    +            throw new IllegalArgumentException("precision: Negative values not allowed");
             }
    -        else if ( precision < 0.0 )
    -        { // Not NaN
    -            throw new IllegalArgumentException( "precision: Negative values not allowed" );
    -        }
    -        return format( d, precision, precisionOnLastDigit, sb );
    +        return format(d, precision, precisionOnLastDigit, sb);
         }
     
         /**
    @@ -806,96 +675,77 @@ else if ( precision < 0.0 )
          * @param sb the StringBuffer to append.
          * @return the specified StringBuffer object.
          */
    -    private static StringBuffer format( double d, double precision, boolean precisionOnLastDigit, StringBuffer sb )
    -    {
    +    private static StringBuffer format(double d, double precision, boolean precisionOnLastDigit, StringBuffer sb) {
             // Special cases.
    -        if ( Double.isNaN( d ) )
    -        {
    -            return sb.append( "NaN" );
    -        }
    -        else if ( Double.isInfinite( d ) )
    -        {
    -            return ( d >= 0 ) ? sb.append( "Infinity" ) : sb.append( "-Infinity" );
    +        if (Double.isNaN(d)) {
    +            return sb.append("NaN");
    +        } else if (Double.isInfinite(d)) {
    +            return (d >= 0) ? sb.append("Infinity") : sb.append("-Infinity");
             }
    -        if ( d < 0 )
    -        {
    +        if (d < 0) {
                 d = -d;
    -            sb.append( '-' );
    +            sb.append('-');
             }
     
             // Formats decimal part.
    -        int rank = (int) Math.floor( Math.log( precision ) / LOG_10 );
    -        double digitValue = multE( d, -rank );
    -        if ( digitValue >= Long.MAX_VALUE )
    -        {
    -            throw new IllegalArgumentException( "Specified precision would result in too many digits" );
    +        int rank = (int) Math.floor(Math.log(precision) / LOG_10);
    +        double digitValue = multE(d, -rank);
    +        if (digitValue >= Long.MAX_VALUE) {
    +            throw new IllegalArgumentException("Specified precision would result in too many digits");
             }
             int digitStart = sb.length();
    -        format( Math.round( digitValue ), sb );
    +        format(Math.round(digitValue), sb);
             int digitLength = sb.length() - digitStart;
             int dotPos = digitLength + rank;
             boolean useScientificNotation = false;
     
             // Inserts dot ('.')
    -        if ( ( dotPos <= -LEADING_ZEROS.length ) || ( dotPos > digitLength ) )
    -        {
    +        if ((dotPos <= -LEADING_ZEROS.length) || (dotPos > digitLength)) {
                 // Scientific notation has to be used ("x.xxxEyy").
    -            sb.insert( digitStart + 1, '.' );
    +            sb.insert(digitStart + 1, '.');
                 useScientificNotation = true;
    -        }
    -        else if ( dotPos > 0 )
    -        {
    +        } else if (dotPos > 0) {
                 // Dot within the string ("xxxx.xxxxx").
    -            sb.insert( digitStart + dotPos, '.' );
    -        }
    -        else
    -        {
    +            sb.insert(digitStart + dotPos, '.');
    +        } else {
                 // Leading zeros ("0.xxxxx").
    -            sb.insert( digitStart, LEADING_ZEROS[-dotPos] );
    +            sb.insert(digitStart, LEADING_ZEROS[-dotPos]);
             }
     
             // Removes trailing zeros.
    -        if ( !precisionOnLastDigit )
    -        {
    +        if (!precisionOnLastDigit) {
                 int newLength = sb.length();
    -            do
    -            {
    +            do {
                     newLength--;
    -            }
    -            while ( sb.charAt( newLength ) == '0' );
    -            sb.setLength( newLength + 1 );
    +            } while (sb.charAt(newLength) == '0');
    +            sb.setLength(newLength + 1);
             }
     
             // Avoids trailing '.'
    -        if ( sb.charAt( sb.length() - 1 ) == '.' )
    -        {
    -            if ( precisionOnLastDigit )
    -            {
    -                sb.setLength( sb.length() - 1 ); // Prefers "xxx" to "xxx."
    -            }
    -            else
    -            {
    -                sb.append( '0' ); // Prefer "xxx.0" to "xxx."
    +        if (sb.charAt(sb.length() - 1) == '.') {
    +            if (precisionOnLastDigit) {
    +                sb.setLength(sb.length() - 1); // Prefers "xxx" to "xxx."
    +            } else {
    +                sb.append('0'); // Prefer "xxx.0" to "xxx."
                 }
             }
     
             // Writes exponent.
    -        if ( useScientificNotation )
    -        {
    -            sb.append( 'E' );
    -            format( dotPos - 1, sb );
    +        if (useScientificNotation) {
    +            sb.append('E');
    +            format(dotPos - 1, sb);
             }
     
             return sb;
         }
     
    -    private static final double LOG_10 = Math.log( 10 );
    +    private static final double LOG_10 = Math.log(10);
     
    -    private static final float FLOAT_RELATIVE_ERROR = (float) Math.pow( 2, -24 );
    +    private static final float FLOAT_RELATIVE_ERROR = (float) Math.pow(2, -24);
     
    -    private static final double DOUBLE_RELATIVE_ERROR = Math.pow( 2, -53 );
    +    private static final double DOUBLE_RELATIVE_ERROR = Math.pow(2, -53);
     
    -    private static String[] LEADING_ZEROS = { "0.", "0.0", "0.00" };
    +    private static String[] LEADING_ZEROS = {"0.", "0.0", "0.00"};
     
         /**
          * Returns the product of the specified value with 10 raised at the specified power exponent.
    @@ -904,33 +754,23 @@ else if ( dotPos > 0 )
          * @param E the exponent.
          * @return value * 10^E
          */
    -    private static final double multE( double value, int E )
    -    {
    -        if ( E >= 0 )
    -        {
    -            if ( E <= 308 )
    -            {
    +    private static final double multE(double value, int E) {
    +        if (E >= 0) {
    +            if (E <= 308) {
                     // Max: 1.7976931348623157E+308
                     return value * DOUBLE_POW_10[E];
    -            }
    -            else
    -            {
    +            } else {
                     value *= 1E21; // Exact multiplicand.
    -                E = Math.min( 308, E - 21 );
    +                E = Math.min(308, E - 21);
                     return value * DOUBLE_POW_10[E];
                 }
    -        }
    -        else
    -        {
    -            if ( E >= -308 )
    -            {
    +        } else {
    +            if (E >= -308) {
                     return value / DOUBLE_POW_10[-E];
    -            }
    -            else
    -            {
    +            } else {
                     // Min: 4.9E-324
                     value /= 1E21; // Exact divisor.
    -                E = Math.max( -308, E + 21 );
    +                E = Math.max(-308, E + 21);
                     return value / DOUBLE_POW_10[-E];
                 }
             }
    @@ -939,30 +779,25 @@ private static final double multE( double value, int E )
         // Note: Approximation for exponents > 21. This may introduce round-off
         // errors (e.g. 1E23 represented as "9.999999999999999E22").
         private static final double[] DOUBLE_POW_10 = new double[] {
    -
             1E000, 1E001, 1E002, 1E003, 1E004, 1E005, 1E006, 1E007, 1E008, 1E009, 1E010, 1E011, 1E012, 1E013, 1E014, 1E015,
             1E016, 1E017, 1E018, 1E019, 1E020, 1E021, 1E022, 1E023, 1E024, 1E025, 1E026, 1E027, 1E028, 1E029, 1E030, 1E031,
             1E032, 1E033, 1E034, 1E035, 1E036, 1E037, 1E038, 1E039, 1E040, 1E041, 1E042, 1E043, 1E044, 1E045, 1E046, 1E047,
             1E048, 1E049, 1E050, 1E051, 1E052, 1E053, 1E054, 1E055, 1E056, 1E057, 1E058, 1E059, 1E060, 1E061, 1E062, 1E063,
             1E064, 1E065, 1E066, 1E067, 1E068, 1E069, 1E070, 1E071, 1E072, 1E073, 1E074, 1E075, 1E076, 1E077, 1E078, 1E079,
             1E080, 1E081, 1E082, 1E083, 1E084, 1E085, 1E086, 1E087, 1E088, 1E089, 1E090, 1E091, 1E092, 1E093, 1E094, 1E095,
    -        1E096, 1E097, 1E098, 1E099,
    -
    -        1E100, 1E101, 1E102, 1E103, 1E104, 1E105, 1E106, 1E107, 1E108, 1E109, 1E110, 1E111, 1E112, 1E113, 1E114, 1E115,
    -        1E116, 1E117, 1E118, 1E119, 1E120, 1E121, 1E122, 1E123, 1E124, 1E125, 1E126, 1E127, 1E128, 1E129, 1E130, 1E131,
    -        1E132, 1E133, 1E134, 1E135, 1E136, 1E137, 1E138, 1E139, 1E140, 1E141, 1E142, 1E143, 1E144, 1E145, 1E146, 1E147,
    -        1E148, 1E149, 1E150, 1E151, 1E152, 1E153, 1E154, 1E155, 1E156, 1E157, 1E158, 1E159, 1E160, 1E161, 1E162, 1E163,
    -        1E164, 1E165, 1E166, 1E167, 1E168, 1E169, 1E170, 1E171, 1E172, 1E173, 1E174, 1E175, 1E176, 1E177, 1E178, 1E179,
    -        1E180, 1E181, 1E182, 1E183, 1E184, 1E185, 1E186, 1E187, 1E188, 1E189, 1E190, 1E191, 1E192, 1E193, 1E194, 1E195,
    -        1E196, 1E197, 1E198, 1E199,
    -
    -        1E200, 1E201, 1E202, 1E203, 1E204, 1E205, 1E206, 1E207, 1E208, 1E209, 1E210, 1E211, 1E212, 1E213, 1E214, 1E215,
    -        1E216, 1E217, 1E218, 1E219, 1E220, 1E221, 1E222, 1E223, 1E224, 1E225, 1E226, 1E227, 1E228, 1E229, 1E230, 1E231,
    -        1E232, 1E233, 1E234, 1E235, 1E236, 1E237, 1E238, 1E239, 1E240, 1E241, 1E242, 1E243, 1E244, 1E245, 1E246, 1E247,
    -        1E248, 1E249, 1E250, 1E251, 1E252, 1E253, 1E254, 1E255, 1E256, 1E257, 1E258, 1E259, 1E260, 1E261, 1E262, 1E263,
    -        1E264, 1E265, 1E266, 1E267, 1E268, 1E269, 1E270, 1E271, 1E272, 1E273, 1E274, 1E275, 1E276, 1E277, 1E278, 1E279,
    -        1E280, 1E281, 1E282, 1E283, 1E284, 1E285, 1E286, 1E287, 1E288, 1E289, 1E290, 1E291, 1E292, 1E293, 1E294, 1E295,
    -        1E296, 1E297, 1E298, 1E299,
    -
    -        1E300, 1E301, 1E302, 1E303, 1E304, 1E305, 1E306, 1E307, 1E308 };
    -}
    \ No newline at end of file
    +        1E096, 1E097, 1E098, 1E099, 1E100, 1E101, 1E102, 1E103, 1E104, 1E105, 1E106, 1E107, 1E108, 1E109, 1E110, 1E111,
    +        1E112, 1E113, 1E114, 1E115, 1E116, 1E117, 1E118, 1E119, 1E120, 1E121, 1E122, 1E123, 1E124, 1E125, 1E126, 1E127,
    +        1E128, 1E129, 1E130, 1E131, 1E132, 1E133, 1E134, 1E135, 1E136, 1E137, 1E138, 1E139, 1E140, 1E141, 1E142, 1E143,
    +        1E144, 1E145, 1E146, 1E147, 1E148, 1E149, 1E150, 1E151, 1E152, 1E153, 1E154, 1E155, 1E156, 1E157, 1E158, 1E159,
    +        1E160, 1E161, 1E162, 1E163, 1E164, 1E165, 1E166, 1E167, 1E168, 1E169, 1E170, 1E171, 1E172, 1E173, 1E174, 1E175,
    +        1E176, 1E177, 1E178, 1E179, 1E180, 1E181, 1E182, 1E183, 1E184, 1E185, 1E186, 1E187, 1E188, 1E189, 1E190, 1E191,
    +        1E192, 1E193, 1E194, 1E195, 1E196, 1E197, 1E198, 1E199, 1E200, 1E201, 1E202, 1E203, 1E204, 1E205, 1E206, 1E207,
    +        1E208, 1E209, 1E210, 1E211, 1E212, 1E213, 1E214, 1E215, 1E216, 1E217, 1E218, 1E219, 1E220, 1E221, 1E222, 1E223,
    +        1E224, 1E225, 1E226, 1E227, 1E228, 1E229, 1E230, 1E231, 1E232, 1E233, 1E234, 1E235, 1E236, 1E237, 1E238, 1E239,
    +        1E240, 1E241, 1E242, 1E243, 1E244, 1E245, 1E246, 1E247, 1E248, 1E249, 1E250, 1E251, 1E252, 1E253, 1E254, 1E255,
    +        1E256, 1E257, 1E258, 1E259, 1E260, 1E261, 1E262, 1E263, 1E264, 1E265, 1E266, 1E267, 1E268, 1E269, 1E270, 1E271,
    +        1E272, 1E273, 1E274, 1E275, 1E276, 1E277, 1E278, 1E279, 1E280, 1E281, 1E282, 1E283, 1E284, 1E285, 1E286, 1E287,
    +        1E288, 1E289, 1E290, 1E291, 1E292, 1E293, 1E294, 1E295, 1E296, 1E297, 1E298, 1E299, 1E300, 1E301, 1E302, 1E303,
    +        1E304, 1E305, 1E306, 1E307, 1E308
    +    };
    +}
    diff --git a/src/main/java/org/codehaus/plexus/util/WriterFactory.java b/src/main/java/org/codehaus/plexus/util/WriterFactory.java
    index cf8326c4..b82e8fc9 100644
    --- a/src/main/java/org/codehaus/plexus/util/WriterFactory.java
    +++ b/src/main/java/org/codehaus/plexus/util/WriterFactory.java
    @@ -36,12 +36,11 @@
      *
      * @since 1.4.4
      */
    -public class WriterFactory
    -{
    +public class WriterFactory {
         /**
          * ISO Latin Alphabet #1, also known as ISO-LATIN-1. Every implementation of the Java platform is required to
          * support this character encoding.
    -     * 
    +     *
          * @see Charset
          */
         public static final String ISO_8859_1 = "ISO-8859-1";
    @@ -49,7 +48,7 @@ public class WriterFactory
         /**
          * Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block of the Unicode character set. Every
          * implementation of the Java platform is required to support this character encoding.
    -     * 
    +     *
          * @see Charset
          */
         public static final String US_ASCII = "US-ASCII";
    @@ -58,7 +57,7 @@ public class WriterFactory
          * Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either
          * order accepted on input, big-endian used on output). Every implementation of the Java platform is required to
          * support this character encoding.
    -     * 
    +     *
          * @see Charset
          */
         public static final String UTF_16 = "UTF-16";
    @@ -66,7 +65,7 @@ public class WriterFactory
         /**
          * Sixteen-bit Unicode Transformation Format, big-endian byte order. Every implementation of the Java platform is
          * required to support this character encoding.
    -     * 
    +     *
          * @see Charset
          */
         public static final String UTF_16BE = "UTF-16BE";
    @@ -74,7 +73,7 @@ public class WriterFactory
         /**
          * Sixteen-bit Unicode Transformation Format, little-endian byte order. Every implementation of the Java platform is
          * required to support this character encoding.
    -     * 
    +     *
          * @see Charset
          */
         public static final String UTF_16LE = "UTF-16LE";
    @@ -82,7 +81,7 @@ public class WriterFactory
         /**
          * Eight-bit Unicode Transformation Format. Every implementation of the Java platform is required to support this
          * character encoding.
    -     * 
    +     *
          * @see Charset
          */
         public static final String UTF_8 = "UTF-8";
    @@ -90,7 +89,7 @@ public class WriterFactory
         /**
          * The file.encoding System Property.
          */
    -    public static final String FILE_ENCODING = System.getProperty( "file.encoding" );
    +    public static final String FILE_ENCODING = System.getProperty("file.encoding");
     
         /**
          * Create a new Writer with XML encoding detection rules.
    @@ -100,10 +99,8 @@ public class WriterFactory
          * @throws IOException if any.
          * @see XmlStreamWriter
          */
    -    public static XmlStreamWriter newXmlWriter( OutputStream out )
    -        throws IOException
    -    {
    -        return new XmlStreamWriter( out );
    +    public static XmlStreamWriter newXmlWriter(OutputStream out) throws IOException {
    +        return new XmlStreamWriter(out);
         }
     
         /**
    @@ -114,10 +111,8 @@ public static XmlStreamWriter newXmlWriter( OutputStream out )
          * @throws IOException if any.
          * @see XmlStreamWriter
          */
    -    public static XmlStreamWriter newXmlWriter( File file )
    -        throws IOException
    -    {
    -        return new XmlStreamWriter( file );
    +    public static XmlStreamWriter newXmlWriter(File file) throws IOException {
    +        return new XmlStreamWriter(file);
         }
     
         /**
    @@ -127,9 +122,8 @@ public static XmlStreamWriter newXmlWriter( File file )
          * @return a writer instance for the output stream using the default platform charset.
          * @see Charset#defaultCharset()
          */
    -    public static Writer newPlatformWriter( OutputStream out )
    -    {
    -        return new OutputStreamWriter( out );
    +    public static Writer newPlatformWriter(OutputStream out) {
    +        return new OutputStreamWriter(out);
         }
     
         /**
    @@ -140,10 +134,8 @@ public static Writer newPlatformWriter( OutputStream out )
          * @throws IOException if any.
          * @see Charset#defaultCharset()
          */
    -    public static Writer newPlatformWriter( File file )
    -        throws IOException
    -    {
    -        return Files.newBufferedWriter( file.toPath() );
    +    public static Writer newPlatformWriter(File file) throws IOException {
    +        return Files.newBufferedWriter(file.toPath());
         }
     
         /**
    @@ -155,10 +147,8 @@ public static Writer newPlatformWriter( File file )
          * @throws UnsupportedEncodingException if any.
          * @see Supported encodings
          */
    -    public static Writer newWriter( OutputStream out, String encoding )
    -        throws UnsupportedEncodingException
    -    {
    -        return new OutputStreamWriter( out, encoding );
    +    public static Writer newWriter(OutputStream out, String encoding) throws UnsupportedEncodingException {
    +        return new OutputStreamWriter(out, encoding);
         }
     
         /**
    @@ -170,9 +160,7 @@ public static Writer newWriter( OutputStream out, String encoding )
          * @throws IOException if any.
          * @see Supported encodings
          */
    -    public static Writer newWriter( File file, String encoding )
    -        throws IOException
    -    {
    -        return newWriter( Files.newOutputStream( file.toPath() ), encoding );
    +    public static Writer newWriter(File file, String encoding) throws IOException {
    +        return newWriter(Files.newOutputStream(file.toPath()), encoding);
         }
     }
    diff --git a/src/main/java/org/codehaus/plexus/util/cli/AbstractStreamHandler.java b/src/main/java/org/codehaus/plexus/util/cli/AbstractStreamHandler.java
    index 2ad16366..64b9deba 100644
    --- a/src/main/java/org/codehaus/plexus/util/cli/AbstractStreamHandler.java
    +++ b/src/main/java/org/codehaus/plexus/util/cli/AbstractStreamHandler.java
    @@ -19,40 +19,30 @@
     /**
      * @author Kristian Rosenvold
      */
    -public class AbstractStreamHandler
    -    extends Thread
    -{
    +public class AbstractStreamHandler extends Thread {
         private boolean done;
     
         private volatile boolean disabled;
     
    -    public boolean isDone()
    -    {
    +    public boolean isDone() {
             return done;
         }
     
    -    public synchronized void waitUntilDone()
    -        throws InterruptedException
    -    {
    -        while ( !isDone() )
    -        {
    +    public synchronized void waitUntilDone() throws InterruptedException {
    +        while (!isDone()) {
                 wait();
             }
         }
     
    -    protected boolean isDisabled()
    -    {
    +    protected boolean isDisabled() {
             return disabled;
         }
     
    -    public void disable()
    -    {
    +    public void disable() {
             disabled = true;
         }
     
    -    public void setDone()
    -    {
    +    public void setDone() {
             done = true;
         }
    -
     }
    diff --git a/src/main/java/org/codehaus/plexus/util/cli/Arg.java b/src/main/java/org/codehaus/plexus/util/cli/Arg.java
    index 75886ef9..4650288c 100644
    --- a/src/main/java/org/codehaus/plexus/util/cli/Arg.java
    +++ b/src/main/java/org/codehaus/plexus/util/cli/Arg.java
    @@ -18,13 +18,12 @@
     
     import java.io.File;
     
    -public interface Arg
    -{
    -    void setValue( String value );
    +public interface Arg {
    +    void setValue(String value);
     
    -    void setLine( String line );
    +    void setLine(String line);
     
    -    void setFile( File value );
    +    void setFile(File value);
     
         String[] getParts();
     }
    diff --git a/src/main/java/org/codehaus/plexus/util/cli/CommandLineCallable.java b/src/main/java/org/codehaus/plexus/util/cli/CommandLineCallable.java
    index 0a861a75..f80a8bc1 100644
    --- a/src/main/java/org/codehaus/plexus/util/cli/CommandLineCallable.java
    +++ b/src/main/java/org/codehaus/plexus/util/cli/CommandLineCallable.java
    @@ -20,13 +20,10 @@
     
     /**
      * Callable wrapper that exposes the proper exception type to the client.
    - * 
    + *
      * @author Kristian Rosenvold
      */
    -public interface CommandLineCallable
    -    extends Callable
    -{
    +public interface CommandLineCallable extends Callable {
         @Override
    -    Integer call()
    -        throws CommandLineException;
    +    Integer call() throws CommandLineException;
     }
    diff --git a/src/main/java/org/codehaus/plexus/util/cli/CommandLineException.java b/src/main/java/org/codehaus/plexus/util/cli/CommandLineException.java
    index 9d0a439e..a6bf993c 100644
    --- a/src/main/java/org/codehaus/plexus/util/cli/CommandLineException.java
    +++ b/src/main/java/org/codehaus/plexus/util/cli/CommandLineException.java
    @@ -20,16 +20,12 @@
      * @author Trygve Laugstøl
      *
      */
    -public class CommandLineException
    -    extends Exception
    -{
    -    public CommandLineException( String message )
    -    {
    -        super( message );
    +public class CommandLineException extends Exception {
    +    public CommandLineException(String message) {
    +        super(message);
         }
     
    -    public CommandLineException( String message, Throwable cause )
    -    {
    -        super( message, cause );
    +    public CommandLineException(String message, Throwable cause) {
    +        super(message, cause);
         }
     }
    diff --git a/src/main/java/org/codehaus/plexus/util/cli/CommandLineTimeOutException.java b/src/main/java/org/codehaus/plexus/util/cli/CommandLineTimeOutException.java
    index 9d90c674..fcfdf3c1 100644
    --- a/src/main/java/org/codehaus/plexus/util/cli/CommandLineTimeOutException.java
    +++ b/src/main/java/org/codehaus/plexus/util/cli/CommandLineTimeOutException.java
    @@ -24,18 +24,13 @@
      * @since 1.5.9
      *
      */
    -public class CommandLineTimeOutException
    -    extends CommandLineException
    -{
    +public class CommandLineTimeOutException extends CommandLineException {
     
    -    public CommandLineTimeOutException( String message )
    -    {
    -        super( message );
    +    public CommandLineTimeOutException(String message) {
    +        super(message);
         }
     
    -    public CommandLineTimeOutException( String message, Throwable cause )
    -    {
    -        super( message, cause );
    +    public CommandLineTimeOutException(String message, Throwable cause) {
    +        super(message, cause);
         }
    -
     }
    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 0e168c04..81b053b9 100644
    --- a/src/main/java/org/codehaus/plexus/util/cli/CommandLineUtils.java
    +++ b/src/main/java/org/codehaus/plexus/util/cli/CommandLineUtils.java
    @@ -16,7 +16,6 @@
      * limitations under the License.
      */
     
    -import java.io.IOException;
     import java.io.InputStream;
     import java.util.Locale;
     import java.util.Map;
    @@ -31,33 +30,27 @@
      * @author Trygve Laugstøl 
      *
      */
    -public abstract class CommandLineUtils
    -{
    +public abstract class CommandLineUtils {
     
         /**
          * A {@code StreamConsumer} providing consumed lines as a {@code String}.
          *
          * @see #getOutput()
          */
    -    public static class StringStreamConsumer
    -        implements StreamConsumer
    -    {
    +    public static class StringStreamConsumer implements StreamConsumer {
     
             private StringBuffer string = new StringBuffer();
     
    -        private String ls = System.getProperty( "line.separator" );
    +        private String ls = System.getProperty("line.separator");
     
             @Override
    -        public void consumeLine( String line )
    -        {
    -            string.append( line ).append( ls );
    +        public void consumeLine(String line) {
    +            string.append(line).append(ls);
             }
     
    -        public String getOutput()
    -        {
    +        public String getOutput() {
                 return string.toString();
             }
    -
         }
     
         /**
    @@ -70,24 +63,21 @@ public String getOutput()
          */
         private static final long NANOS_PER_SECOND = 1000000000L;
     
    -    public static int executeCommandLine( Commandline cl, StreamConsumer systemOut, StreamConsumer systemErr )
    -        throws CommandLineException
    -    {
    -        return executeCommandLine( cl, null, systemOut, systemErr, 0 );
    +    public static int executeCommandLine(Commandline cl, StreamConsumer systemOut, StreamConsumer systemErr)
    +            throws CommandLineException {
    +        return executeCommandLine(cl, null, systemOut, systemErr, 0);
         }
     
    -    public static int executeCommandLine( Commandline cl, StreamConsumer systemOut, StreamConsumer systemErr,
    -                                          int timeoutInSeconds )
    -        throws CommandLineException
    -    {
    -        return executeCommandLine( cl, null, systemOut, systemErr, timeoutInSeconds );
    +    public static int executeCommandLine(
    +            Commandline cl, StreamConsumer systemOut, StreamConsumer systemErr, int timeoutInSeconds)
    +            throws CommandLineException {
    +        return executeCommandLine(cl, null, systemOut, systemErr, timeoutInSeconds);
         }
     
    -    public static int executeCommandLine( Commandline cl, InputStream systemIn, StreamConsumer systemOut,
    -                                          StreamConsumer systemErr )
    -        throws CommandLineException
    -    {
    -        return executeCommandLine( cl, systemIn, systemOut, systemErr, 0 );
    +    public static int executeCommandLine(
    +            Commandline cl, InputStream systemIn, StreamConsumer systemOut, StreamConsumer systemErr)
    +            throws CommandLineException {
    +        return executeCommandLine(cl, systemIn, systemOut, systemErr, 0);
         }
     
         /**
    @@ -99,12 +89,15 @@ public static int executeCommandLine( Commandline cl, InputStream systemIn, Stre
          * @return A return value, see {@link Process#exitValue()}
          * @throws CommandLineException or CommandLineTimeOutException if time out occurs
          */
    -    public static int executeCommandLine( Commandline cl, InputStream systemIn, StreamConsumer systemOut,
    -                                          StreamConsumer systemErr, int timeoutInSeconds )
    -        throws CommandLineException
    -    {
    +    public static int executeCommandLine(
    +            Commandline cl,
    +            InputStream systemIn,
    +            StreamConsumer systemOut,
    +            StreamConsumer systemErr,
    +            int timeoutInSeconds)
    +            throws CommandLineException {
             final CommandLineCallable future =
    -            executeCommandLineAsCallable( cl, systemIn, systemOut, systemErr, timeoutInSeconds );
    +                executeCommandLineAsCallable(cl, systemIn, systemOut, systemErr, timeoutInSeconds);
             return future.call();
         }
     
    @@ -121,83 +114,70 @@ public static int executeCommandLine( Commandline cl, InputStream systemIn, Stre
          *         internal state before after the completion of the call statements
          * @throws CommandLineException or CommandLineTimeOutException if time out occurs
          */
    -    public static CommandLineCallable executeCommandLineAsCallable( final Commandline cl, final InputStream systemIn,
    -                                                                    final StreamConsumer systemOut,
    -                                                                    final StreamConsumer systemErr,
    -                                                                    final int timeoutInSeconds )
    -        throws CommandLineException
    -    {
    -        if ( cl == null )
    -        {
    -            throw new IllegalArgumentException( "cl cannot be null." );
    +    public static CommandLineCallable executeCommandLineAsCallable(
    +            final Commandline cl,
    +            final InputStream systemIn,
    +            final StreamConsumer systemOut,
    +            final StreamConsumer systemErr,
    +            final int timeoutInSeconds)
    +            throws CommandLineException {
    +        if (cl == null) {
    +            throw new IllegalArgumentException("cl cannot be null.");
             }
     
             final Process p = cl.execute();
     
    -        final Thread processHook = new Thread()
    -        {
    +        final Thread processHook = new Thread() {
     
                 {
    -                this.setName( "CommandLineUtils process shutdown hook" );
    -                this.setContextClassLoader( null );
    +                this.setName("CommandLineUtils process shutdown hook");
    +                this.setContextClassLoader(null);
                 }
     
                 @Override
    -            public void run()
    -            {
    +            public void run() {
                     p.destroy();
                 }
    -
             };
     
    -        ShutdownHookUtils.addShutDownHook( processHook );
    +        ShutdownHookUtils.addShutDownHook(processHook);
     
    -        return new CommandLineCallable()
    -        {
    +        return new CommandLineCallable() {
     
                 @Override
    -            public Integer call()
    -                throws CommandLineException
    -            {
    +            public Integer call() throws CommandLineException {
                     StreamFeeder inputFeeder = null;
                     StreamPumper outputPumper = null;
                     StreamPumper errorPumper = null;
                     boolean success = false;
    -                try
    -                {
    -                    if ( systemIn != null )
    -                    {
    -                        inputFeeder = new StreamFeeder( systemIn, p.getOutputStream() );
    +                try {
    +                    if (systemIn != null) {
    +                        inputFeeder = new StreamFeeder(systemIn, p.getOutputStream());
                             inputFeeder.start();
                         }
     
    -                    outputPumper = new StreamPumper( p.getInputStream(), systemOut );
    +                    outputPumper = new StreamPumper(p.getInputStream(), systemOut);
                         outputPumper.start();
     
    -                    errorPumper = new StreamPumper( p.getErrorStream(), systemErr );
    +                    errorPumper = new StreamPumper(p.getErrorStream(), systemErr);
                         errorPumper.start();
     
                         int returnValue;
    -                    if ( timeoutInSeconds <= 0 )
    -                    {
    +                    if (timeoutInSeconds <= 0) {
                             returnValue = p.waitFor();
    -                    }
    -                    else
    -                    {
    +                    } else {
                             final long now = System.nanoTime();
                             final long timeout = now + NANOS_PER_SECOND * timeoutInSeconds;
     
    -                        while ( isAlive( p ) && ( System.nanoTime() < timeout ) )
    -                        {
    +                        while (isAlive(p) && (System.nanoTime() < timeout)) {
                                 // The timeout is specified in seconds. Therefore we must not sleep longer than one second
                                 // but we should sleep as long as possible to reduce the number of iterations performed.
    -                            Thread.sleep( MILLIS_PER_SECOND - 1L );
    +                            Thread.sleep(MILLIS_PER_SECOND - 1L);
                             }
     
    -                        if ( isAlive( p ) )
    -                        {
    -                            throw new InterruptedException( String.format( "Process timed out after %d seconds.",
    -                                                                           timeoutInSeconds ) );
    +                        if (isAlive(p)) {
    +                            throw new InterruptedException(
    +                                    String.format("Process timed out after %d seconds.", timeoutInSeconds));
                             }
     
                             returnValue = p.exitValue();
    @@ -224,96 +204,72 @@ public Integer call()
                         // errorPumper.waitUntilDone();
                         // }
                         // }
    -                    if ( inputFeeder != null )
    -                    {
    +                    if (inputFeeder != null) {
                             inputFeeder.waitUntilDone();
                         }
     
                         outputPumper.waitUntilDone();
                         errorPumper.waitUntilDone();
     
    -                    if ( inputFeeder != null )
    -                    {
    +                    if (inputFeeder != null) {
                             inputFeeder.close();
    -                        handleException( inputFeeder, "stdin" );
    +                        handleException(inputFeeder, "stdin");
                         }
     
                         outputPumper.close();
    -                    handleException( outputPumper, "stdout" );
    +                    handleException(outputPumper, "stdout");
     
                         errorPumper.close();
    -                    handleException( errorPumper, "stderr" );
    +                    handleException(errorPumper, "stderr");
     
                         success = true;
                         return returnValue;
    -                }
    -                catch ( InterruptedException ex )
    -                {
    -                    throw new CommandLineTimeOutException( "Error while executing external command, process killed.",
    -                                                           ex );
    +                } catch (InterruptedException ex) {
    +                    throw new CommandLineTimeOutException(
    +                            "Error while executing external command, process killed.", ex);
     
    -                }
    -                finally
    -                {
    -                    if ( inputFeeder != null )
    -                    {
    +                } finally {
    +                    if (inputFeeder != null) {
                             inputFeeder.disable();
                         }
    -                    if ( outputPumper != null )
    -                    {
    +                    if (outputPumper != null) {
                             outputPumper.disable();
                         }
    -                    if ( errorPumper != null )
    -                    {
    +                    if (errorPumper != null) {
                             errorPumper.disable();
                         }
     
    -                    try
    -                    {
    -                        ShutdownHookUtils.removeShutdownHook( processHook );
    +                    try {
    +                        ShutdownHookUtils.removeShutdownHook(processHook);
                             processHook.run();
    -                    }
    -                    finally
    -                    {
    -                        try
    -                        {
    -                            if ( inputFeeder != null )
    -                            {
    +                    } finally {
    +                        try {
    +                            if (inputFeeder != null) {
                                     inputFeeder.close();
     
    -                                if ( success )
    -                                {
    +                                if (success) {
                                         success = false;
    -                                    handleException( inputFeeder, "stdin" );
    +                                    handleException(inputFeeder, "stdin");
                                         success = true; // Only reached when no exception has been thrown.
                                     }
                                 }
    -                        }
    -                        finally
    -                        {
    -                            try
    -                            {
    -                                if ( outputPumper != null )
    -                                {
    +                        } finally {
    +                            try {
    +                                if (outputPumper != null) {
                                         outputPumper.close();
     
    -                                    if ( success )
    -                                    {
    +                                    if (success) {
                                             success = false;
    -                                        handleException( outputPumper, "stdout" );
    +                                        handleException(outputPumper, "stdout");
                                             success = true; // Only reached when no exception has been thrown.
                                         }
                                     }
    -                            }
    -                            finally
    -                            {
    -                                if ( errorPumper != null )
    -                                {
    +                            } finally {
    +                                if (errorPumper != null) {
                                         errorPumper.close();
     
    -                                    if ( success )
    -                                    {
    -                                        handleException( errorPumper, "stderr" );
    +                                    if (success) {
    +                                        handleException(errorPumper, "stderr");
                                         }
                                     }
                                 }
    @@ -321,29 +277,22 @@ public Integer call()
                         }
                     }
                 }
    -
             };
         }
     
    -    private static void handleException( final StreamPumper streamPumper, final String streamName )
    -        throws CommandLineException
    -    {
    -        if ( streamPumper.getException() != null )
    -        {
    -            throw new CommandLineException( String.format( "Failure processing %s.", streamName ),
    -                                            streamPumper.getException() );
    -
    +    private static void handleException(final StreamPumper streamPumper, final String streamName)
    +            throws CommandLineException {
    +        if (streamPumper.getException() != null) {
    +            throw new CommandLineException(
    +                    String.format("Failure processing %s.", streamName), streamPumper.getException());
             }
         }
     
    -    private static void handleException( final StreamFeeder streamFeeder, final String streamName )
    -        throws CommandLineException
    -    {
    -        if ( streamFeeder.getException() != null )
    -        {
    -            throw new CommandLineException( String.format( "Failure processing %s.", streamName ),
    -                                            streamFeeder.getException() );
    -
    +    private static void handleException(final StreamFeeder streamFeeder, final String streamName)
    +            throws CommandLineException {
    +        if (streamFeeder.getException() != null) {
    +            throw new CommandLineException(
    +                    String.format("Failure processing %s.", streamName), streamFeeder.getException());
             }
         }
     
    @@ -357,9 +306,8 @@ private static void handleException( final StreamFeeder streamFeeder, final Stri
          * @see System#getenv() System.getenv() API, new in JDK 5.0, to get the same result since 2.0.2 System#getenv()
          *      will be used if available in the current running jvm.
          */
    -    public static Properties getSystemEnvVars()
    -    {
    -        return getSystemEnvVars( !Os.isFamily( Os.FAMILY_WINDOWS ) );
    +    public static Properties getSystemEnvVars() {
    +        return getSystemEnvVars(!Os.isFamily(Os.FAMILY_WINDOWS));
         }
     
         /**
    @@ -371,45 +319,34 @@ public static Properties getSystemEnvVars()
          * @see System#getenv() System.getenv() API, new in JDK 5.0, to get the same result since 2.0.2 System#getenv()
          *      will be used if available in the current running jvm.
          */
    -    public static Properties getSystemEnvVars( boolean caseSensitive )
    -    {
    +    public static Properties getSystemEnvVars(boolean caseSensitive) {
             Properties envVars = new Properties();
             Map envs = System.getenv();
    -        for ( String key : envs.keySet() )
    -        {
    -            String value = envs.get( key );
    -            if ( !caseSensitive )
    -            {
    -                key = key.toUpperCase( Locale.ENGLISH );
    +        for (String key : envs.keySet()) {
    +            String value = envs.get(key);
    +            if (!caseSensitive) {
    +                key = key.toUpperCase(Locale.ENGLISH);
                 }
    -            envVars.put( key, value );
    +            envVars.put(key, value);
             }
             return envVars;
         }
     
    -    public static boolean isAlive( Process p )
    -    {
    -        if ( p == null )
    -        {
    +    public static boolean isAlive(Process p) {
    +        if (p == null) {
                 return false;
             }
     
    -        try
    -        {
    +        try {
                 p.exitValue();
                 return false;
    -        }
    -        catch ( IllegalThreadStateException e )
    -        {
    +        } catch (IllegalThreadStateException e) {
                 return true;
             }
         }
     
    -    public static String[] translateCommandline( String toProcess )
    -        throws Exception
    -    {
    -        if ( ( toProcess == null ) || ( toProcess.length() == 0 ) )
    -        {
    +    public static String[] translateCommandline(String toProcess) throws Exception {
    +        if ((toProcess == null) || (toProcess.length() == 0)) {
                 return new String[0];
             }
     
    @@ -419,72 +356,54 @@ public static String[] translateCommandline( String toProcess )
             final int inQuote = 1;
             final int inDoubleQuote = 2;
             int state = normal;
    -        StringTokenizer tok = new StringTokenizer( toProcess, "\"\' ", true );
    +        StringTokenizer tok = new StringTokenizer(toProcess, "\"\' ", true);
             Vector v = new Vector();
             StringBuilder current = new StringBuilder();
     
    -        while ( tok.hasMoreTokens() )
    -        {
    +        while (tok.hasMoreTokens()) {
                 String nextTok = tok.nextToken();
    -            switch ( state )
    -            {
    +            switch (state) {
                     case inQuote:
    -                    if ( "\'".equals( nextTok ) )
    -                    {
    +                    if ("\'".equals(nextTok)) {
                             state = normal;
    -                    }
    -                    else
    -                    {
    -                        current.append( nextTok );
    +                    } else {
    +                        current.append(nextTok);
                         }
                         break;
                     case inDoubleQuote:
    -                    if ( "\"".equals( nextTok ) )
    -                    {
    +                    if ("\"".equals(nextTok)) {
                             state = normal;
    -                    }
    -                    else
    -                    {
    -                        current.append( nextTok );
    +                    } else {
    +                        current.append(nextTok);
                         }
                         break;
                     default:
    -                    if ( "\'".equals( nextTok ) )
    -                    {
    +                    if ("\'".equals(nextTok)) {
                             state = inQuote;
    -                    }
    -                    else if ( "\"".equals( nextTok ) )
    -                    {
    +                    } else if ("\"".equals(nextTok)) {
                             state = inDoubleQuote;
    -                    }
    -                    else if ( " ".equals( nextTok ) )
    -                    {
    -                        if ( current.length() != 0 )
    -                        {
    -                            v.addElement( current.toString() );
    -                            current.setLength( 0 );
    +                    } else if (" ".equals(nextTok)) {
    +                        if (current.length() != 0) {
    +                            v.addElement(current.toString());
    +                            current.setLength(0);
                             }
    -                    }
    -                    else
    -                    {
    -                        current.append( nextTok );
    +                    } else {
    +                        current.append(nextTok);
                         }
                         break;
                 }
             }
     
    -        if ( current.length() != 0 )
    -        {
    -            v.addElement( current.toString() );
    +        if (current.length() != 0) {
    +            v.addElement(current.toString());
             }
     
    -        if ( ( state == inQuote ) || ( state == inDoubleQuote ) )
    -        {
    -            throw new CommandLineException( "unbalanced quotes in " + toProcess );
    +        if ((state == inQuote) || (state == inDoubleQuote)) {
    +            throw new CommandLineException("unbalanced quotes in " + toProcess);
             }
     
             String[] args = new String[v.size()];
    -        v.copyInto( args );
    +        v.copyInto(args);
             return args;
         }
     
    @@ -504,11 +423,9 @@ else if ( " ".equals( nextTok ) )
          *             {@link StringUtils#quoteAndEscape(String, char)} instead.
          */
         @Deprecated
    -    @SuppressWarnings( { "JavaDoc", "deprecation" } )
    -    public static String quote( String argument )
    -        throws CommandLineException
    -    {
    -        return quote( argument, false, false, true );
    +    @SuppressWarnings({"JavaDoc", "deprecation"})
    +    public static String quote(String argument) throws CommandLineException {
    +        return quote(argument, false, false, true);
         }
     
         /**
    @@ -528,11 +445,9 @@ public static String quote( String argument )
          *             {@link StringUtils#quoteAndEscape(String, char)} instead.
          */
         @Deprecated
    -    @SuppressWarnings( { "JavaDoc", "UnusedDeclaration", "deprecation" } )
    -    public static String quote( String argument, boolean wrapExistingQuotes )
    -        throws CommandLineException
    -    {
    -        return quote( argument, false, false, wrapExistingQuotes );
    +    @SuppressWarnings({"JavaDoc", "UnusedDeclaration", "deprecation"})
    +    public static String quote(String argument, boolean wrapExistingQuotes) throws CommandLineException {
    +        return quote(argument, false, false, wrapExistingQuotes);
         }
     
         /**
    @@ -547,48 +462,30 @@ public static String quote( String argument, boolean wrapExistingQuotes )
          *             {@link StringUtils#quoteAndEscape(String, char)} instead.
          */
         @Deprecated
    -    @SuppressWarnings( { "JavaDoc" } )
    -    public static String quote( String argument, boolean escapeSingleQuotes, boolean escapeDoubleQuotes,
    -                                boolean wrapExistingQuotes )
    -        throws CommandLineException
    -    {
    -        if ( argument.contains( "\"" ) )
    -        {
    -            if ( argument.contains( "\'" ) )
    -            {
    -                throw new CommandLineException( "Can't handle single and double quotes in same argument" );
    -            }
    -            else
    -            {
    -                if ( escapeSingleQuotes )
    -                {
    +    @SuppressWarnings({"JavaDoc"})
    +    public static String quote(
    +            String argument, boolean escapeSingleQuotes, boolean escapeDoubleQuotes, boolean wrapExistingQuotes)
    +            throws CommandLineException {
    +        if (argument.contains("\"")) {
    +            if (argument.contains("\'")) {
    +                throw new CommandLineException("Can't handle single and double quotes in same argument");
    +            } else {
    +                if (escapeSingleQuotes) {
                         return "\\\'" + argument + "\\\'";
    -                }
    -                else if ( wrapExistingQuotes )
    -                {
    +                } else if (wrapExistingQuotes) {
                         return '\'' + argument + '\'';
                     }
                 }
    -        }
    -        else if ( argument.contains( "\'" ) )
    -        {
    -            if ( escapeDoubleQuotes )
    -            {
    +        } else if (argument.contains("\'")) {
    +            if (escapeDoubleQuotes) {
                     return "\\\"" + argument + "\\\"";
    -            }
    -            else if ( wrapExistingQuotes )
    -            {
    +            } else if (wrapExistingQuotes) {
                     return '\"' + argument + '\"';
                 }
    -        }
    -        else if ( argument.contains( " " ) )
    -        {
    -            if ( escapeDoubleQuotes )
    -            {
    +        } else if (argument.contains(" ")) {
    +            if (escapeDoubleQuotes) {
                     return "\\\"" + argument + "\\\"";
    -            }
    -            else
    -            {
    +            } else {
                     return '\"' + argument + '\"';
                 }
             }
    @@ -596,32 +493,24 @@ else if ( argument.contains( " " ) )
             return argument;
         }
     
    -    public static String toString( String[] line )
    -    {
    +    public static String toString(String[] line) {
             // empty path return empty string
    -        if ( ( line == null ) || ( line.length == 0 ) )
    -        {
    +        if ((line == null) || (line.length == 0)) {
                 return "";
             }
     
             // path containing one or more elements
             final StringBuilder result = new StringBuilder();
    -        for ( int i = 0; i < line.length; i++ )
    -        {
    -            if ( i > 0 )
    -            {
    -                result.append( ' ' );
    +        for (int i = 0; i < line.length; i++) {
    +            if (i > 0) {
    +                result.append(' ');
                 }
    -            try
    -            {
    -                result.append( StringUtils.quoteAndEscape( line[i], '\"' ) );
    -            }
    -            catch ( Exception e )
    -            {
    -                System.err.println( "Error quoting argument: " + e.getMessage() );
    +            try {
    +                result.append(StringUtils.quoteAndEscape(line[i], '\"'));
    +            } catch (Exception e) {
    +                System.err.println("Error quoting argument: " + e.getMessage());
                 }
             }
             return result.toString();
         }
    -
     }
    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 c06147a9..db145c50 100644
    --- a/src/main/java/org/codehaus/plexus/util/cli/Commandline.java
    +++ b/src/main/java/org/codehaus/plexus/util/cli/Commandline.java
    @@ -57,13 +57,6 @@
      * ====================================================================
      */
     
    -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.CommandShell;
    -import org.codehaus.plexus.util.cli.shell.Shell;
    -
     import java.io.File;
     import java.io.IOException;
     import java.util.Collections;
    @@ -72,12 +65,19 @@
     import java.util.Properties;
     import java.util.Vector;
     
    +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.CommandShell;
    +import org.codehaus.plexus.util.cli.shell.Shell;
    +
     /**
      * 

    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">
    @@ -87,16 +87,14 @@ *   </acommandline>
    * </someelement>
    *
    - * + * *

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

    * * @author thomas.haas@softwired-inc.com * @author Stefan Bodewig */ -public class Commandline - implements Cloneable -{ +public class Commandline implements Cloneable { /** * @deprecated Use {@link org.codehaus.plexus.util.Os} class instead. */ @@ -113,7 +111,7 @@ public class Commandline // protected Vector envVars = new Vector(); // synchronized added to preserve synchronize of Vector class - protected Map envVars = Collections.synchronizedMap( new LinkedHashMap() ); + protected Map envVars = Collections.synchronizedMap(new LinkedHashMap()); private long pid = -1; @@ -139,25 +137,19 @@ public class Commandline * @param toProcess sh to process * @param shell Shell to use */ - public Commandline( String toProcess, Shell shell ) - { + public Commandline(String toProcess, Shell shell) { this.shell = shell; String[] tmp = new String[0]; - try - { - tmp = CommandLineUtils.translateCommandline( toProcess ); - } - catch ( Exception e ) - { - System.err.println( "Error translating Commandline." ); - } - if ( ( tmp != null ) && ( tmp.length > 0 ) ) - { - setExecutable( tmp[0] ); - for ( int i = 1; i < tmp.length; i++ ) - { - createArgument().setValue( tmp[i] ); + try { + tmp = CommandLineUtils.translateCommandline(toProcess); + } catch (Exception e) { + System.err.println("Error translating Commandline."); + } + if ((tmp != null) && (tmp.length > 0)) { + setExecutable(tmp[0]); + for (int i = 1; i < tmp.length; i++) { + createArgument().setValue(tmp[i]); } } } @@ -167,8 +159,7 @@ public Commandline( String toProcess, Shell shell ) * generating code for remote execution. * @param shell the Shell */ - public Commandline( Shell shell ) - { + public Commandline(Shell shell) { this.shell = shell; } @@ -177,24 +168,18 @@ public Commandline( Shell shell ) * * @param toProcess the process */ - public Commandline( String toProcess ) - { + public Commandline(String toProcess) { setDefaultShell(); String[] tmp = new String[0]; - try - { - tmp = CommandLineUtils.translateCommandline( toProcess ); - } - catch ( Exception e ) - { - System.err.println( "Error translating Commandline." ); - } - if ( ( tmp != null ) && ( tmp.length > 0 ) ) - { - setExecutable( tmp[0] ); - for ( int i = 1; i < tmp.length; i++ ) - { - createArgument().setValue( tmp[i] ); + try { + tmp = CommandLineUtils.translateCommandline(toProcess); + } catch (Exception e) { + System.err.println("Error translating Commandline."); + } + if ((tmp != null) && (tmp.length > 0)) { + setExecutable(tmp[0]); + for (int i = 1; i < tmp.length; i++) { + createArgument().setValue(tmp[i]); } } } @@ -202,23 +187,19 @@ public Commandline( String toProcess ) /** * Create a new command line object. */ - public Commandline() - { + public Commandline() { setDefaultShell(); } - public long getPid() - { - if ( pid == -1 ) - { - pid = Long.parseLong( String.valueOf( System.currentTimeMillis() ) ); + public long getPid() { + if (pid == -1) { + pid = Long.parseLong(String.valueOf(System.currentTimeMillis())); } return pid; } - public void setPid( long pid ) - { + public void setPid(long pid) { this.pid = pid; } @@ -228,31 +209,26 @@ public void setPid( long pid ) //

    This class is there to support the srcfile and targetfile // elements of <execon> and <transform> - don't know // whether there might be additional use cases.

    --SB - public class Marker - { + public class Marker { private int position; private int realPos = -1; - Marker( int position ) - { + Marker(int position) { this.position = position; } /** * @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() - { - if ( realPos == -1 ) - { - realPos = ( getLiteralExecutable() == null ? 0 : 1 ); - for ( int i = 0; i < position; i++ ) - { - Arg arg = arguments.elementAt( i ); + public int getPosition() { + if (realPos == -1) { + realPos = (getLiteralExecutable() == null ? 0 : 1); + for (int i = 0; i < position; i++) { + Arg arg = arguments.elementAt(i); realPos += arg.getParts().length; } } @@ -265,29 +241,22 @@ public int getPosition() * Sets the shell or command-line interpreter for the detected operating system, and the shell arguments. *

    */ - private void setDefaultShell() - { + private void setDefaultShell() { // If this is windows set the shell to command.com or cmd.exe with correct arguments. - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - if ( Os.isFamily( Os.FAMILY_WIN9X ) ) - { - setShell( new CommandShell() ); - } - else - { - setShell( new CmdShell() ); + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + if (Os.isFamily(Os.FAMILY_WIN9X)) { + setShell(new CommandShell()); + } else { + setShell(new CmdShell()); } - } - else - { - setShell( new BourneShell() ); + } else { + setShell(new BourneShell()); } } /** *

    Creates an argument object.

    - * + * *

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

    * @@ -296,14 +265,13 @@ private void setDefaultShell() * @deprecated Use {@link Commandline#createArg()} instead */ @Deprecated - public Argument createArgument() - { - return this.createArgument( false ); + public Argument createArgument() { + return this.createArgument(false); } /** *

    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 @@ -312,52 +280,43 @@ public Argument createArgument() * @return Argument the argument Object */ @Deprecated - public Argument createArgument( boolean insertAtStart ) - { + public Argument createArgument(boolean insertAtStart) { Argument argument = new Argument(); - if ( insertAtStart ) - { - arguments.insertElementAt( argument, 0 ); - } - else - { - arguments.addElement( argument ); + if (insertAtStart) { + arguments.insertElementAt(argument, 0); + } else { + arguments.addElement(argument); } return argument; } /** *

    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) */ - public Arg createArg() - { - return this.createArg( false ); + public Arg createArg() { + return this.createArg(false); } /** * @return 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. */ - public Arg createArg( boolean insertAtStart ) - { + public Arg createArg(boolean insertAtStart) { Arg argument = new Argument(); - if ( insertAtStart ) - { - arguments.insertElementAt( argument, 0 ); - } - else - { - arguments.addElement( argument ); + if (insertAtStart) { + arguments.insertElementAt(argument, 0); + } else { + arguments.addElement(argument); } return argument; } @@ -366,9 +325,8 @@ public Arg createArg( boolean insertAtStart ) * @param argument the argument * @see #addArg(Arg,boolean) */ - public void addArg( Arg argument ) - { - this.addArg( argument, false ); + public void addArg(Arg argument) { + this.addArg(argument, false); } /** @@ -377,15 +335,11 @@ public void addArg( Arg argument ) * @param insertAtStart if true, the argument is inserted at the beginning of the list of args, otherwise it is * appended. */ - public void addArg( Arg argument, boolean insertAtStart ) - { - if ( insertAtStart ) - { - arguments.insertElementAt( argument, 0 ); - } - else - { - arguments.addElement( argument ); + public void addArg(Arg argument, boolean insertAtStart) { + if (insertAtStart) { + arguments.insertElementAt(argument, 0); + } else { + arguments.addElement(argument); } } @@ -393,17 +347,15 @@ public void addArg( Arg argument, boolean insertAtStart ) * Sets the executable to run. * @param executable the executable */ - public void setExecutable( String executable ) - { - shell.setExecutable( executable ); + public void setExecutable(String executable) { + shell.setExecutable(executable); this.executable = executable; } /** * @return Executable to be run, as a literal string (no shell quoting/munging) */ - public String getLiteralExecutable() - { + public String getLiteralExecutable() { return executable; } @@ -413,23 +365,19 @@ public String getLiteralExecutable() * * @return Executable to be run, quoted for shell interpretation */ - public String getExecutable() - { + public String getExecutable() { String exec = shell.getExecutable(); - if ( exec == null ) - { + if (exec == null) { exec = executable; } return exec; } - public void addArguments( String[] line ) - { - for ( String aLine : line ) - { - createArgument().setValue( aLine ); + public void addArguments(String[] line) { + for (String aLine : line) { + createArgument().setValue(aLine); } } @@ -438,27 +386,22 @@ public void addArguments( String[] line ) * @param name name * @param value value */ - public void addEnvironment( String name, String value ) - { + public void addEnvironment(String name, String value) { // envVars.add( name + "=" + value ); - envVars.put( name, value ); + envVars.put(name, value); } /** * Add system environment variables * @throws Exception if error */ - public void addSystemEnvironment() - throws Exception - { + public void addSystemEnvironment() throws Exception { Properties systemEnvVars = CommandLineUtils.getSystemEnvVars(); - for ( Object o : systemEnvVars.keySet() ) - { + for (Object o : systemEnvVars.keySet()) { String key = (String) o; - if ( !envVars.containsKey( key ) ) - { - addEnvironment( key, systemEnvVars.getProperty( key ) ); + if (!envVars.containsKey(key)) { + addEnvironment(key, systemEnvVars.getProperty(key)); } } } @@ -467,23 +410,17 @@ public void addSystemEnvironment() * @return String[] Return the list of environment variables * @throws CommandLineException if error */ - public String[] getEnvironmentVariables() - throws CommandLineException - { - try - { + public String[] getEnvironmentVariables() throws CommandLineException { + try { addSystemEnvironment(); - } - catch ( Exception e ) - { - throw new CommandLineException( "Error setting up environmental variables", e ); + } catch (Exception e) { + throw new CommandLineException("Error setting up environmental variables", e); } String[] environmentVars = new String[envVars.size()]; int i = 0; - for ( Object o : envVars.keySet() ) - { + for (Object o : envVars.keySet()) { String name = (String) o; - String value = envVars.get( name ); + String value = envVars.get(name); environmentVars[i] = name + "=" + value; i++; } @@ -494,10 +431,8 @@ public String[] getEnvironmentVariables() * @return Returns the executable and all defined arguments. * For Windows Family, {@link Commandline#getShellCommandline()} is returned */ - public String[] getCommandline() - { - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { + public String[] getCommandline() { + if (Os.isFamily(Os.FAMILY_WINDOWS)) { return getShellCommandline(); } @@ -508,87 +443,76 @@ public String[] getCommandline() * Returns the executable and all defined arguments. * @return the command line as array not escaped neither quoted */ - public String[] getRawCommandline() - { + public String[] getRawCommandline() { final String[] args = getArguments(); String executable = getLiteralExecutable(); - if ( executable == null ) - { + if (executable == null) { return args; } final String[] result = new String[args.length + 1]; result[0] = executable; - System.arraycopy( args, 0, result, 1, args.length ); + System.arraycopy(args, 0, result, 1, args.length); return result; } - /** + /** * Returns the shell, executable and all defined arguments. Shell usage is only desirable when generating code for * remote execution. * @return the command line as array */ - public String[] getShellCommandline() - { + public String[] getShellCommandline() { // TODO: Provided only for backward compat. with <= 1.4 verifyShellState(); - return getShell().getShellCommandLine( getArguments() ).toArray( new String[0] ); + return getShell().getShellCommandLine(getArguments()).toArray(new String[0]); } /** * @return Returns all arguments defined by addLine, addValue or the argument object. */ - public String[] getArguments() - { - Vector result = new Vector<>( arguments.size() * 2 ); - for ( int i = 0; i < arguments.size(); i++ ) - { - Arg arg = arguments.elementAt( i ); + public String[] getArguments() { + Vector result = new Vector<>(arguments.size() * 2); + for (int i = 0; i < arguments.size(); i++) { + Arg arg = arguments.elementAt(i); String[] s = arg.getParts(); - if ( s != null ) - { - for ( String value : s ) - { - result.addElement( value ); + if (s != null) { + for (String value : s) { + result.addElement(value); } } } String[] res = new String[result.size()]; - result.copyInto( res ); + result.copyInto(res); return res; } @Override - public String toString() - { - return StringUtils.join( getShellCommandline(), " " ); + public String toString() { + return StringUtils.join(getShellCommandline(), " "); } - public int size() - { + public int size() { return getCommandline().length; } @Override - public Object clone() - { - Commandline c = new Commandline( (Shell) shell.clone() ); + public Object clone() { + Commandline c = new Commandline((Shell) shell.clone()); c.executable = executable; c.workingDir = workingDir; - c.addArguments( getArguments() ); + c.addArguments(getArguments()); return c; } /** * Clear out the whole command line. */ - public void clear() - { + public void clear() { executable = null; workingDir = null; - shell.setExecutable( null ); + shell.setExecutable(null); shell.clearArguments(); arguments.removeAllElements(); } @@ -596,8 +520,7 @@ public void clear() /** * Clear out the arguments but leave the executable in place for another operation. */ - public void clearArgs() - { + public void clearArgs() { arguments.removeAllElements(); } @@ -608,37 +531,32 @@ public void clearArgs() *

    * @return Return a marker. */ - public Marker createMarker() - { - return new Marker( arguments.size() ); + public Marker createMarker() { + return new Marker(arguments.size()); } /** * Sets execution directory. * @param path the working directory as String */ - public void setWorkingDirectory( String path ) - { - shell.setWorkingDirectory( path ); - workingDir = new File( path ); + public void setWorkingDirectory(String path) { + shell.setWorkingDirectory(path); + workingDir = new File(path); } /** * Sets execution directory. * @param workingDirectory the File used as working directory */ - public void setWorkingDirectory( File workingDirectory ) - { - shell.setWorkingDirectory( workingDirectory ); + public void setWorkingDirectory(File workingDirectory) { + shell.setWorkingDirectory(workingDirectory); workingDir = workingDirectory; } - public File getWorkingDirectory() - { + public File getWorkingDirectory() { File workDir = shell.getWorkingDirectory(); - if ( workDir == null ) - { + if (workDir == null) { workDir = workingDir; } @@ -650,9 +568,7 @@ public File getWorkingDirectory() * @return the Process * @throws CommandLineException if error */ - public Process execute() - throws CommandLineException - { + public Process execute() throws CommandLineException { // TODO: Provided only for backward compat. with <= 1.4 verifyShellState(); @@ -664,31 +580,22 @@ public Process execute() File workingDir = shell.getWorkingDirectory(); - try - { - if ( workingDir == null ) - { - process = Runtime.getRuntime().exec( getCommandline(), environment, workingDir ); - } - else - { - if ( !workingDir.exists() ) - { - throw new CommandLineException( "Working directory \"" + workingDir.getPath() - + "\" does not exist!" ); - } - else if ( !workingDir.isDirectory() ) - { - throw new CommandLineException( "Path \"" + workingDir.getPath() - + "\" does not specify a directory." ); + try { + if (workingDir == null) { + process = Runtime.getRuntime().exec(getCommandline(), environment, workingDir); + } else { + if (!workingDir.exists()) { + throw new CommandLineException( + "Working directory \"" + workingDir.getPath() + "\" does not exist!"); + } else if (!workingDir.isDirectory()) { + throw new CommandLineException( + "Path \"" + workingDir.getPath() + "\" does not specify a directory."); } - process = Runtime.getRuntime().exec( getCommandline(), environment, workingDir ); + process = Runtime.getRuntime().exec(getCommandline(), environment, workingDir); } - } - catch ( IOException ex ) - { - throw new CommandLineException( "Error while executing process.", ex ); + } catch (IOException ex) { + throw new CommandLineException("Error while executing process.", ex); } return process; @@ -698,22 +605,17 @@ else if ( !workingDir.isDirectory() ) * @deprecated Remove once backward compat with plexus-utils <= 1.4 is no longer a consideration */ @Deprecated - private void verifyShellState() - { - if ( shell.getWorkingDirectory() == null ) - { - shell.setWorkingDirectory( workingDir ); + private void verifyShellState() { + if (shell.getWorkingDirectory() == null) { + shell.setWorkingDirectory(workingDir); } - if ( shell.getOriginalExecutable() == null ) - { - shell.setExecutable( executable ); + if (shell.getOriginalExecutable() == null) { + shell.setExecutable(executable); } } - public Properties getSystemEnvVars() - throws Exception - { + public Properties getSystemEnvVars() throws Exception { return CommandLineUtils.getSystemEnvVars(); } @@ -724,20 +626,18 @@ public Properties getSystemEnvVars() * @param shell Shell to use * @since 1.2 */ - public void setShell( Shell shell ) - { + public void setShell(Shell shell) { this.shell = shell; } /** * Get the shell to be used in this command line. Shell usage is only desirable when generating code for remote * execution. - * + * * @since 1.2 * @return the Shell */ - public Shell getShell() - { + public Shell getShell() { return shell; } @@ -748,10 +648,8 @@ public Shell getShell() * @deprecated Use {@link CommandLineUtils#translateCommandline(String)} instead. */ @Deprecated - public static String[] translateCommandline( String toProcess ) - throws Exception - { - return CommandLineUtils.translateCommandline( toProcess ); + public static String[] translateCommandline(String toProcess) throws Exception { + return CommandLineUtils.translateCommandline(toProcess); } /** @@ -761,10 +659,8 @@ public static String[] translateCommandline( String toProcess ) * @deprecated Use {@link CommandLineUtils#quote(String)} instead. */ @Deprecated - public static String quoteArgument( String argument ) - throws CommandLineException - { - return CommandLineUtils.quote( argument ); + public static String quoteArgument(String argument) throws CommandLineException { + return CommandLineUtils.quote(argument); } /** @@ -773,14 +669,11 @@ public static String quoteArgument( String argument ) * @return lines as single String */ @Deprecated - public static String toString( String[] line ) - { - return CommandLineUtils.toString( line ); + public static String toString(String[] line) { + return CommandLineUtils.toString(line); } - public static class Argument - implements Arg - { + public static class Argument implements Arg { private String[] parts; /* @@ -788,11 +681,9 @@ public static class Argument * @see org.codehaus.plexus.util.cli.Argument#setValue(java.lang.String) */ @Override - public void setValue( String value ) - { - if ( value != null ) - { - parts = new String[] { value }; + public void setValue(String value) { + if (value != null) { + parts = new String[] {value}; } } @@ -801,19 +692,14 @@ public void setValue( String value ) * @see org.codehaus.plexus.util.cli.Argument#setLine(java.lang.String) */ @Override - public void setLine( String line ) - { - if ( line == null ) - { + public void setLine(String line) { + if (line == null) { return; } - try - { - parts = CommandLineUtils.translateCommandline( line ); - } - catch ( Exception e ) - { - System.err.println( "Error translating Commandline." ); + try { + parts = CommandLineUtils.translateCommandline(line); + } catch (Exception e) { + System.err.println("Error translating Commandline."); } } @@ -822,9 +708,8 @@ public void setLine( String line ) * @see org.codehaus.plexus.util.cli.Argument#setFile(java.io.File) */ @Override - public void setFile( File value ) - { - parts = new String[] { value.getAbsolutePath() }; + public void setFile(File value) { + parts = new String[] {value.getAbsolutePath()}; } /* @@ -832,8 +717,7 @@ public void setFile( File value ) * @see org.codehaus.plexus.util.cli.Argument#getParts() */ @Override - public String[] getParts() - { + public String[] getParts() { return parts; } } diff --git a/src/main/java/org/codehaus/plexus/util/cli/DefaultConsumer.java b/src/main/java/org/codehaus/plexus/util/cli/DefaultConsumer.java index 802dfb02..3808db81 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/DefaultConsumer.java +++ b/src/main/java/org/codehaus/plexus/util/cli/DefaultConsumer.java @@ -22,20 +22,14 @@ * @author Emmanuel Venisse * */ -public class DefaultConsumer - implements StreamConsumer -{ +public class DefaultConsumer implements StreamConsumer { @Override - public void consumeLine( String line ) - throws IOException - { - System.out.println( line ); + public void consumeLine(String line) throws IOException { + System.out.println(line); - if ( System.out.checkError() ) - { - throw new IOException( String.format( "Failure printing line '%s' to stdout.", line ) ); + if (System.out.checkError()) { + throw new IOException(String.format("Failure printing line '%s' to stdout.", line)); } } - } diff --git a/src/main/java/org/codehaus/plexus/util/cli/EnhancedStringTokenizer.java b/src/main/java/org/codehaus/plexus/util/cli/EnhancedStringTokenizer.java index 2db89002..565a87cf 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/EnhancedStringTokenizer.java +++ b/src/main/java/org/codehaus/plexus/util/cli/EnhancedStringTokenizer.java @@ -21,11 +21,10 @@ /** * The java.util.StringTokenizer is horribly broken. Given the string 1,,,3,,4 (, delim) It will return 1,3,4 Which is * clearly wrong - 1,EMPTY,EMPTY,3,EMPTY,4 is what it should return - * + * * */ -public final class EnhancedStringTokenizer -{ +public final class EnhancedStringTokenizer { private StringTokenizer cst = null; String cdelim; @@ -40,98 +39,73 @@ public final class EnhancedStringTokenizer boolean delimLast = true; - public EnhancedStringTokenizer( String str ) - { - this( str, " \t\n\r\f", false ); + public EnhancedStringTokenizer(String str) { + this(str, " \t\n\r\f", false); } - public EnhancedStringTokenizer( String str, String delim ) - { - this( str, delim, false ); + public EnhancedStringTokenizer(String str, String delim) { + this(str, delim, false); } - public EnhancedStringTokenizer( String str, String delim, boolean returnDelims ) - { - cst = new StringTokenizer( str, delim, true ); + public EnhancedStringTokenizer(String str, String delim, boolean returnDelims) { + cst = new StringTokenizer(str, delim, true); cdelim = delim; creturnDelims = returnDelims; - cdelimSingleChar = ( delim.length() == 1 ); - cdelimChar = delim.charAt( 0 ); + cdelimSingleChar = (delim.length() == 1); + cdelimChar = delim.charAt(0); } - public boolean hasMoreTokens() - { + public boolean hasMoreTokens() { return cst.hasMoreTokens(); } - private String internalNextToken() - { - if ( lastToken != null ) - { + private String internalNextToken() { + if (lastToken != null) { String last = lastToken; lastToken = null; return last; } String token = cst.nextToken(); - if ( isDelim( token ) ) - { - if ( delimLast ) - { + if (isDelim(token)) { + if (delimLast) { lastToken = token; return ""; - } - else - { + } else { delimLast = true; return token; } - } - else - { + } else { delimLast = false; return token; } } - public String nextToken() - { + public String nextToken() { String token = internalNextToken(); - if ( creturnDelims ) - { + if (creturnDelims) { return token; } - if ( isDelim( token ) ) - { + if (isDelim(token)) { return hasMoreTokens() ? internalNextToken() : ""; - } - else - { + } else { return token; } } - private boolean isDelim( String str ) - { - if ( str.length() == 1 ) - { - char ch = str.charAt( 0 ); - if ( cdelimSingleChar ) - { - if ( cdelimChar == ch ) - { + private boolean isDelim(String str) { + if (str.length() == 1) { + char ch = str.charAt(0); + if (cdelimSingleChar) { + if (cdelimChar == ch) { return true; } - } - else - { - if ( cdelim.indexOf( ch ) >= 0 ) - { + } else { + if (cdelim.indexOf(ch) >= 0) { return true; } } } return false; - } } diff --git a/src/main/java/org/codehaus/plexus/util/cli/ShutdownHookUtils.java b/src/main/java/org/codehaus/plexus/util/cli/ShutdownHookUtils.java index 453b566e..bb967b42 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/ShutdownHookUtils.java +++ b/src/main/java/org/codehaus/plexus/util/cli/ShutdownHookUtils.java @@ -24,36 +24,21 @@ * * @author Kristian Rosenvold */ -class ShutdownHookUtils -{ +class ShutdownHookUtils { - public static void addShutDownHook( Thread hook ) - { - try - { - Runtime.getRuntime().addShutdownHook( hook ); + public static void addShutDownHook(Thread hook) { + try { + Runtime.getRuntime().addShutdownHook(hook); + } catch (IllegalStateException ignore) { + } catch (AccessControlException ignore) { } - catch ( IllegalStateException ignore ) - { - } - catch ( AccessControlException ignore ) - { - } - } - public static void removeShutdownHook( Thread hook ) - { - try - { - Runtime.getRuntime().removeShutdownHook( hook ); - } - catch ( IllegalStateException ignore ) - { - } - catch ( AccessControlException ignore ) - { + public static void removeShutdownHook(Thread hook) { + try { + Runtime.getRuntime().removeShutdownHook(hook); + } catch (IllegalStateException ignore) { + } catch (AccessControlException ignore) { } } - } diff --git a/src/main/java/org/codehaus/plexus/util/cli/StreamConsumer.java b/src/main/java/org/codehaus/plexus/util/cli/StreamConsumer.java index e01bda2c..7367ccdc 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/StreamConsumer.java +++ b/src/main/java/org/codehaus/plexus/util/cli/StreamConsumer.java @@ -52,7 +52,6 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ********************************************************************************/ - import java.io.IOException; /** @@ -64,14 +63,12 @@ * @author Paul Julius * */ -public interface StreamConsumer -{ +public interface StreamConsumer { /** * Called when the StreamPumper pumps a line from the Stream. - * + * * @param line The line to be consumed. * @throws IOException if consuming {@code line} fails. */ - public void consumeLine( String line ) - throws IOException; + public void consumeLine(String line) throws IOException; } diff --git a/src/main/java/org/codehaus/plexus/util/cli/StreamFeeder.java b/src/main/java/org/codehaus/plexus/util/cli/StreamFeeder.java index 270d7d8b..81289044 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/StreamFeeder.java +++ b/src/main/java/org/codehaus/plexus/util/cli/StreamFeeder.java @@ -26,9 +26,7 @@ * @author Trygve Laugstøl * */ -public class StreamFeeder - extends AbstractStreamHandler -{ +public class StreamFeeder extends AbstractStreamHandler { private InputStream input; @@ -42,33 +40,24 @@ public class StreamFeeder * @param input Stream to read from * @param output Stream to write to */ - public StreamFeeder( InputStream input, OutputStream output ) - { + public StreamFeeder(InputStream input, OutputStream output) { super(); this.input = input; this.output = output; } @Override - public void run() - { - try - { + public void run() { + try { feed(); - } - catch ( Throwable ex ) - { - if ( exception == null ) - { + } catch (Throwable ex) { + if (exception == null) { exception = ex; } - } - finally - { + } finally { close(); - synchronized ( this ) - { + synchronized (this) { setDone(); this.notifyAll(); @@ -76,20 +65,13 @@ public void run() } } - public void close() - { - if ( input != null ) - { - synchronized ( input ) - { - try - { + public void close() { + if (input != null) { + synchronized (input) { + try { input.close(); - } - catch ( IOException ex ) - { - if ( exception == null ) - { + } catch (IOException ex) { + if (exception == null) { exception = ex; } } @@ -98,18 +80,12 @@ public void close() } } - if ( output != null ) - { - synchronized ( output ) - { - try - { + if (output != null) { + synchronized (output) { + try { output.close(); - } - catch ( IOException ex ) - { - if ( exception == null ) - { + } catch (IOException ex) { + if (exception == null) { exception = ex; } } @@ -123,24 +99,18 @@ public void close() * @since 3.1.0 * @return the Exception */ - public Throwable getException() - { + public Throwable getException() { return exception; } - private void feed() - throws IOException - { + private void feed() throws IOException { boolean flush = false; int data = input.read(); - while ( !isDone() && data != -1 ) - { - synchronized ( output ) - { - if ( !isDisabled() ) - { - output.write( data ); + while (!isDone() && data != -1) { + synchronized (output) { + if (!isDisabled()) { + output.write(data); flush = true; } @@ -148,10 +118,8 @@ private void feed() } } - if ( flush ) - { + if (flush) { output.flush(); } } - } diff --git a/src/main/java/org/codehaus/plexus/util/cli/StreamPumper.java b/src/main/java/org/codehaus/plexus/util/cli/StreamPumper.java index 12126e88..9c4865ff 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/StreamPumper.java +++ b/src/main/java/org/codehaus/plexus/util/cli/StreamPumper.java @@ -84,9 +84,7 @@ * * @since June 11, 2001 */ -public class StreamPumper - extends AbstractStreamHandler -{ +public class StreamPumper extends AbstractStreamHandler { private final BufferedReader in; private final StreamConsumer consumer; @@ -97,93 +95,68 @@ public class StreamPumper private static final int SIZE = 1024; - public StreamPumper( InputStream in ) - { - this( in, (StreamConsumer) null ); + public StreamPumper(InputStream in) { + this(in, (StreamConsumer) null); } - public StreamPumper( InputStream in, StreamConsumer consumer ) - { - this( in, null, consumer ); + public StreamPumper(InputStream in, StreamConsumer consumer) { + this(in, null, consumer); } - public StreamPumper( InputStream in, PrintWriter writer ) - { - this( in, writer, null ); + public StreamPumper(InputStream in, PrintWriter writer) { + this(in, writer, null); } - public StreamPumper( InputStream in, PrintWriter writer, StreamConsumer consumer ) - { + public StreamPumper(InputStream in, PrintWriter writer, StreamConsumer consumer) { super(); - this.in = new BufferedReader( new InputStreamReader( in ), SIZE ); + this.in = new BufferedReader(new InputStreamReader(in), SIZE); this.out = writer; this.consumer = consumer; } @Override - public void run() - { + public void run() { boolean outError = out != null ? out.checkError() : false; - try - { - for ( String line = in.readLine(); line != null; line = in.readLine() ) - { - try - { - if ( exception == null && consumer != null && !isDisabled() ) - { - consumer.consumeLine( line ); + try { + for (String line = in.readLine(); line != null; line = in.readLine()) { + try { + if (exception == null && consumer != null && !isDisabled()) { + consumer.consumeLine(line); } - } - catch ( Exception t ) - { + } catch (Exception t) { exception = t; } - if ( out != null && !outError ) - { - out.println( line ); + if (out != null && !outError) { + out.println(line); out.flush(); - if ( out.checkError() ) - { + if (out.checkError()) { outError = true; - try - { + try { // Thrown to fill in stack trace elements. - throw new IOException( String.format( "Failure printing line '%s'.", line ) ); - } - catch ( final IOException e ) - { + throw new IOException(String.format("Failure printing line '%s'.", line)); + } catch (final IOException e) { exception = e; } } } } - } - catch ( IOException e ) - { + } catch (IOException e) { exception = e; - } - finally - { - try - { + } finally { + try { in.close(); - } - catch ( final IOException e2 ) - { - if ( exception == null ) - { + } catch (final IOException e2) { + if (exception == null) { exception = e2; } } - synchronized ( this ) - { + synchronized (this) { setDone(); this.notifyAll(); @@ -191,50 +164,37 @@ public void run() } } - public void flush() - { - if ( out != null ) - { + public void flush() { + if (out != null) { out.flush(); - if ( out.checkError() && exception == null ) - { - try - { + if (out.checkError() && exception == null) { + try { // Thrown to fill in stack trace elements. - throw new IOException( "Failure flushing output." ); - } - catch ( final IOException e ) - { + throw new IOException("Failure flushing output."); + } catch (final IOException e) { exception = e; } } } } - public void close() - { - if ( out != null ) - { + public void close() { + if (out != null) { out.close(); - if ( out.checkError() && exception == null ) - { - try - { + if (out.checkError() && exception == null) { + try { // Thrown to fill in stack trace elements. - throw new IOException( "Failure closing output." ); - } - catch ( final IOException e ) - { + throw new IOException("Failure closing output."); + } catch (final IOException e) { exception = e; } } } } - public Exception getException() - { + public Exception getException() { return exception; } } diff --git a/src/main/java/org/codehaus/plexus/util/cli/WriterStreamConsumer.java b/src/main/java/org/codehaus/plexus/util/cli/WriterStreamConsumer.java index ed24136e..b8e6cc2e 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/WriterStreamConsumer.java +++ b/src/main/java/org/codehaus/plexus/util/cli/WriterStreamConsumer.java @@ -23,20 +23,16 @@ * @author Jason van Zyl * */ -public class WriterStreamConsumer - implements StreamConsumer -{ +public class WriterStreamConsumer implements StreamConsumer { private PrintWriter writer; - public WriterStreamConsumer( Writer writer ) - { - this.writer = new PrintWriter( writer ); + public WriterStreamConsumer(Writer writer) { + this.writer = new PrintWriter(writer); } @Override - public void consumeLine( String line ) - { - writer.println( line ); + public void consumeLine(String line) { + writer.println(line); writer.flush(); } diff --git a/src/main/java/org/codehaus/plexus/util/cli/shell/BourneShell.java b/src/main/java/org/codehaus/plexus/util/cli/shell/BourneShell.java index 089bc6fd..912a431b 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/shell/BourneShell.java +++ b/src/main/java/org/codehaus/plexus/util/cli/shell/BourneShell.java @@ -16,83 +16,71 @@ * limitations under the License. */ -import org.codehaus.plexus.util.Os; - import java.util.ArrayList; import java.util.List; +import org.codehaus.plexus.util.Os; + /** * @author Jason van Zyl * */ -public class BourneShell - extends Shell -{ +public class BourneShell extends Shell { - public BourneShell() - { - this( false ); + public BourneShell() { + this(false); } - public BourneShell( boolean isLoginShell ) - { - setUnconditionalQuoting( true ); - setShellCommand( "/bin/sh" ); - setArgumentQuoteDelimiter( '\'' ); - setExecutableQuoteDelimiter( '\'' ); - setSingleQuotedArgumentEscaped( true ); - setSingleQuotedExecutableEscaped( false ); - setQuotedExecutableEnabled( true ); - setArgumentEscapePattern( "'\\%s'" ); - - if ( isLoginShell ) - { - addShellArg( "-l" ); + public BourneShell(boolean isLoginShell) { + setUnconditionalQuoting(true); + setShellCommand("/bin/sh"); + setArgumentQuoteDelimiter('\''); + setExecutableQuoteDelimiter('\''); + setSingleQuotedArgumentEscaped(true); + setSingleQuotedExecutableEscaped(false); + setQuotedExecutableEnabled(true); + setArgumentEscapePattern("'\\%s'"); + + if (isLoginShell) { + addShellArg("-l"); } } /** {@inheritDoc} */ @Override - public String getExecutable() - { - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { + public String getExecutable() { + if (Os.isFamily(Os.FAMILY_WINDOWS)) { return super.getExecutable(); } - return quoteOneItem( super.getOriginalExecutable(), true ); + return quoteOneItem(super.getOriginalExecutable(), true); } @Override - public List getShellArgsList() - { + public List getShellArgsList() { List shellArgs = new ArrayList(); List existingShellArgs = super.getShellArgsList(); - if ( ( existingShellArgs != null ) && !existingShellArgs.isEmpty() ) - { - shellArgs.addAll( existingShellArgs ); + if ((existingShellArgs != null) && !existingShellArgs.isEmpty()) { + shellArgs.addAll(existingShellArgs); } - shellArgs.add( "-c" ); + shellArgs.add("-c"); return shellArgs; } @Override - public String[] getShellArgs() - { + public String[] getShellArgs() { String[] shellArgs = super.getShellArgs(); - if ( shellArgs == null ) - { + if (shellArgs == null) { shellArgs = new String[0]; } - if ( ( shellArgs.length > 0 ) && !shellArgs[shellArgs.length - 1].equals( "-c" ) ) - { + if ((shellArgs.length > 0) && !shellArgs[shellArgs.length - 1].equals("-c")) { String[] newArgs = new String[shellArgs.length + 1]; - System.arraycopy( shellArgs, 0, newArgs, 0, shellArgs.length ); + System.arraycopy(shellArgs, 0, newArgs, 0, shellArgs.length); newArgs[shellArgs.length] = "-c"; shellArgs = newArgs; @@ -102,19 +90,17 @@ public String[] getShellArgs() } @Override - protected String getExecutionPreamble() - { - if ( getWorkingDirectoryAsString() == null ) - { + protected String getExecutionPreamble() { + if (getWorkingDirectoryAsString() == null) { return null; } String dir = getWorkingDirectoryAsString(); StringBuilder sb = new StringBuilder(); - sb.append( "cd " ); + sb.append("cd "); - sb.append( quoteOneItem( dir, false ) ); - sb.append( " && " ); + sb.append(quoteOneItem(dir, false)); + sb.append(" && "); return sb.toString(); } @@ -139,17 +125,15 @@ protected String getExecutionPreamble() * @return the path unified correctly for the Bourne shell. */ @Override - protected String quoteOneItem( String path, boolean isExecutable ) - { - if ( path == null ) - { + protected String quoteOneItem(String path, boolean isExecutable) { + if (path == null) { return null; } StringBuilder sb = new StringBuilder(); - sb.append( "'" ); - sb.append( path.replace( "'", "'\"'\"'" ) ); - sb.append( "'" ); + sb.append("'"); + sb.append(path.replace("'", "'\"'\"'")); + sb.append("'"); return sb.toString(); } diff --git a/src/main/java/org/codehaus/plexus/util/cli/shell/CmdShell.java b/src/main/java/org/codehaus/plexus/util/cli/shell/CmdShell.java index aa0af43a..47cc5154 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/shell/CmdShell.java +++ b/src/main/java/org/codehaus/plexus/util/cli/shell/CmdShell.java @@ -28,14 +28,11 @@ * @since 1.2 * */ -public class CmdShell - extends Shell -{ - public CmdShell() - { - setShellCommand( "cmd.exe" ); - setQuotedExecutableEnabled( true ); - setShellArgs( new String[] { "/X", "/C" } ); +public class CmdShell extends Shell { + public CmdShell() { + setShellCommand("cmd.exe"); + setQuotedExecutableEnabled(true); + setShellArgs(new String[] {"/X", "/C"}); } /** @@ -77,13 +74,12 @@ public CmdShell() *

    */ @Override - public List getCommandLine( String executable, String[] arguments ) - { + public List getCommandLine(String executable, String[] arguments) { StringBuilder sb = new StringBuilder(); - sb.append( "\"" ); - sb.append( super.getCommandLine( executable, arguments ).get( 0 ) ); - sb.append( "\"" ); + sb.append("\""); + sb.append(super.getCommandLine(executable, arguments).get(0)); + sb.append("\""); - return Arrays.asList( new String[] { sb.toString() } ); + return Arrays.asList(new String[] {sb.toString()}); } } diff --git a/src/main/java/org/codehaus/plexus/util/cli/shell/CommandShell.java b/src/main/java/org/codehaus/plexus/util/cli/shell/CommandShell.java index 4aa4c2af..947045f9 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/shell/CommandShell.java +++ b/src/main/java/org/codehaus/plexus/util/cli/shell/CommandShell.java @@ -25,13 +25,9 @@ * @since 1.2 * */ -public class CommandShell - extends Shell -{ - public CommandShell() - { - setShellCommand( "command.com" ); - setShellArgs( new String[] { "/C" } ); +public class CommandShell extends Shell { + public CommandShell() { + setShellCommand("command.com"); + setShellArgs(new String[] {"/C"}); } - } 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 c3c911dd..03a6065c 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 @@ -16,13 +16,13 @@ * limitations under the License. */ -import org.codehaus.plexus.util.StringUtils; - import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import org.codehaus.plexus.util.StringUtils; + /** * Class that abstracts the Shell functionality, with subclasses for shells that behave particularly, like *
      @@ -34,10 +34,8 @@ * @since 1.2 * */ -public class Shell - implements Cloneable -{ - private static final char[] DEFAULT_QUOTING_TRIGGER_CHARS = { ' ' }; +public class Shell implements Cloneable { + private static final char[] DEFAULT_QUOTING_TRIGGER_CHARS = {' '}; private String shellCommand; @@ -72,8 +70,7 @@ public class Shell * * @param unconditionallyQuote see name */ - public void setUnconditionalQuoting( boolean unconditionallyQuote ) - { + public void setUnconditionalQuoting(boolean unconditionallyQuote) { this.unconditionallyQuote = unconditionallyQuote; } @@ -82,8 +79,7 @@ public void setUnconditionalQuoting( boolean unconditionallyQuote ) * * @param shellCommand see name */ - public void setShellCommand( String shellCommand ) - { + public void setShellCommand(String shellCommand) { this.shellCommand = shellCommand; } @@ -92,8 +88,7 @@ public void setShellCommand( String shellCommand ) * * @return the command */ - public String getShellCommand() - { + public String getShellCommand() { return shellCommand; } @@ -102,24 +97,19 @@ public String getShellCommand() * * @param shellArgs see name */ - public void setShellArgs( String[] shellArgs ) - { + public void setShellArgs(String[] shellArgs) { this.shellArgs.clear(); - this.shellArgs.addAll( Arrays.asList( shellArgs ) ); + this.shellArgs.addAll(Arrays.asList(shellArgs)); } /** * @return the shell arguments */ - public String[] getShellArgs() - { - if ( ( shellArgs == null ) || shellArgs.isEmpty() ) - { + public String[] getShellArgs() { + if ((shellArgs == null) || shellArgs.isEmpty()) { return null; - } - else - { - return shellArgs.toArray( new String[0] ); + } else { + return shellArgs.toArray(new String[0]); } } @@ -130,139 +120,115 @@ public String[] getShellArgs() * @param arguments arguments for the executable, not the shell * @return List with one String object with executable and arguments quoted as needed */ - public List getCommandLine( String executable, String[] arguments ) - { - return getRawCommandLine( executable, arguments ); + public List getCommandLine(String executable, String[] arguments) { + return getRawCommandLine(executable, arguments); } - protected String quoteOneItem( String inputString, boolean isExecutable ) - { - char[] escapeChars = getEscapeChars( isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped() ); - return StringUtils.quoteAndEscape( inputString, - isExecutable ? getExecutableQuoteDelimiter() : getArgumentQuoteDelimiter(), - escapeChars, getQuotingTriggerChars(), '\\', unconditionallyQuote ); + protected String quoteOneItem(String inputString, boolean isExecutable) { + char[] escapeChars = getEscapeChars(isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped()); + return StringUtils.quoteAndEscape( + inputString, + isExecutable ? getExecutableQuoteDelimiter() : getArgumentQuoteDelimiter(), + escapeChars, + getQuotingTriggerChars(), + '\\', + unconditionallyQuote); } - protected List getRawCommandLine( String executable, String[] arguments ) - { + protected List getRawCommandLine(String executable, String[] arguments) { List commandLine = new ArrayList(); StringBuilder sb = new StringBuilder(); - if ( executable != null ) - { + if (executable != null) { String preamble = getExecutionPreamble(); - if ( preamble != null ) - { - sb.append( preamble ); + if (preamble != null) { + sb.append(preamble); } - if ( isQuotedExecutableEnabled() ) - { - sb.append( quoteOneItem( getOriginalExecutable(), true ) ); - } - else - { - sb.append( getExecutable() ); + if (isQuotedExecutableEnabled()) { + sb.append(quoteOneItem(getOriginalExecutable(), true)); + } else { + sb.append(getExecutable()); } } - for ( String argument : arguments ) - { - if ( sb.length() > 0 ) - { - sb.append( " " ); + for (String argument : arguments) { + if (sb.length() > 0) { + sb.append(" "); } - if ( isQuotedArgumentsEnabled() ) - { - sb.append( quoteOneItem( argument, false ) ); - } - else - { - sb.append( argument ); + if (isQuotedArgumentsEnabled()) { + sb.append(quoteOneItem(argument, false)); + } else { + sb.append(argument); } } - commandLine.add( sb.toString() ); + commandLine.add(sb.toString()); return commandLine; } - protected char[] getQuotingTriggerChars() - { + protected char[] getQuotingTriggerChars() { return DEFAULT_QUOTING_TRIGGER_CHARS; } - protected String getExecutionPreamble() - { + protected String getExecutionPreamble() { return null; } - protected char[] getEscapeChars( boolean includeSingleQuote, boolean includeDoubleQuote ) - { - StringBuilder buf = new StringBuilder( 2 ); - if ( includeSingleQuote ) - { - buf.append( '\'' ); + protected char[] getEscapeChars(boolean includeSingleQuote, boolean includeDoubleQuote) { + StringBuilder buf = new StringBuilder(2); + if (includeSingleQuote) { + buf.append('\''); } - if ( includeDoubleQuote ) - { - buf.append( '\"' ); + if (includeDoubleQuote) { + buf.append('\"'); } char[] result = new char[buf.length()]; - buf.getChars( 0, buf.length(), result, 0 ); + buf.getChars(0, buf.length(), result, 0); return result; } - protected boolean isDoubleQuotedArgumentEscaped() - { + protected boolean isDoubleQuotedArgumentEscaped() { return doubleQuotedArgumentEscaped; } - protected boolean isSingleQuotedArgumentEscaped() - { + protected boolean isSingleQuotedArgumentEscaped() { return singleQuotedArgumentEscaped; } - protected boolean isDoubleQuotedExecutableEscaped() - { + protected boolean isDoubleQuotedExecutableEscaped() { return doubleQuotedExecutableEscaped; } - protected boolean isSingleQuotedExecutableEscaped() - { + protected boolean isSingleQuotedExecutableEscaped() { return singleQuotedExecutableEscaped; } - protected void setArgumentQuoteDelimiter( char argQuoteDelimiter ) - { + protected void setArgumentQuoteDelimiter(char argQuoteDelimiter) { this.argQuoteDelimiter = argQuoteDelimiter; } - protected char getArgumentQuoteDelimiter() - { + protected char getArgumentQuoteDelimiter() { return argQuoteDelimiter; } - protected void setExecutableQuoteDelimiter( char exeQuoteDelimiter ) - { + protected void setExecutableQuoteDelimiter(char exeQuoteDelimiter) { this.exeQuoteDelimiter = exeQuoteDelimiter; } - protected char getExecutableQuoteDelimiter() - { + protected char getExecutableQuoteDelimiter() { return exeQuoteDelimiter; } - protected void setArgumentEscapePattern( String argumentEscapePattern ) - { + protected void setArgumentEscapePattern(String argumentEscapePattern) { this.argumentEscapePattern = argumentEscapePattern; } - protected String getArgumentEscapePattern() - { + protected String getArgumentEscapePattern() { return argumentEscapePattern; } @@ -274,54 +240,44 @@ protected String getArgumentEscapePattern() * @return List of String objects, whose array version is suitable to be used as argument of * Runtime.getRuntime().exec() */ - public List getShellCommandLine( String[] arguments ) - { + public List getShellCommandLine(String[] arguments) { List commandLine = new ArrayList(); - if ( getShellCommand() != null ) - { - commandLine.add( getShellCommand() ); + if (getShellCommand() != null) { + commandLine.add(getShellCommand()); } - if ( getShellArgs() != null ) - { - commandLine.addAll( getShellArgsList() ); + if (getShellArgs() != null) { + commandLine.addAll(getShellArgsList()); } - commandLine.addAll( getCommandLine( getOriginalExecutable(), arguments ) ); + commandLine.addAll(getCommandLine(getOriginalExecutable(), arguments)); return commandLine; - } - public List getShellArgsList() - { + public List getShellArgsList() { return shellArgs; } - public void addShellArg( String arg ) - { - shellArgs.add( arg ); + public void addShellArg(String arg) { + shellArgs.add(arg); } - public void setQuotedArgumentsEnabled( boolean quotedArgumentsEnabled ) - { + public void setQuotedArgumentsEnabled(boolean quotedArgumentsEnabled) { this.quotedArgumentsEnabled = quotedArgumentsEnabled; } - public boolean isQuotedArgumentsEnabled() - { + public boolean isQuotedArgumentsEnabled() { return quotedArgumentsEnabled; } - public void setQuotedExecutableEnabled( boolean quotedExecutableEnabled ) - { + public void setQuotedExecutableEnabled(boolean quotedExecutableEnabled) { this.quotedExecutableEnabled = quotedExecutableEnabled; } - public boolean isQuotedExecutableEnabled() - { + public boolean isQuotedExecutableEnabled() { return quotedExecutableEnabled; } @@ -329,27 +285,22 @@ public boolean isQuotedExecutableEnabled() * * @param executable Sets the executable to run. */ - public void setExecutable( String executable ) - { - if ( ( executable == null ) || ( executable.length() == 0 ) ) - { + public void setExecutable(String executable) { + if ((executable == null) || (executable.length() == 0)) { return; } - this.executable = executable.replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); + this.executable = executable.replace('/', File.separatorChar).replace('\\', File.separatorChar); } - public String getExecutable() - { + public String getExecutable() { return executable; } /** * @param path Sets execution directory. */ - public void setWorkingDirectory( String path ) - { - if ( path != null ) - { + public void setWorkingDirectory(String path) { + if (path != null) { workingDir = path; } } @@ -357,66 +308,54 @@ public void setWorkingDirectory( String path ) /** * @param workingDir Sets execution directory. */ - public void setWorkingDirectory( File workingDir ) - { - if ( workingDir != null ) - { + public void setWorkingDirectory(File workingDir) { + if (workingDir != null) { this.workingDir = workingDir.getAbsolutePath(); } } - public File getWorkingDirectory() - { - return workingDir == null ? null : new File( workingDir ); + public File getWorkingDirectory() { + return workingDir == null ? null : new File(workingDir); } - public String getWorkingDirectoryAsString() - { + public String getWorkingDirectoryAsString() { return workingDir; } - public void clearArguments() - { + public void clearArguments() { shellArgs.clear(); } @Override - public Object clone() - { + public Object clone() { Shell shell = new Shell(); - shell.setExecutable( getExecutable() ); - shell.setWorkingDirectory( getWorkingDirectory() ); - shell.setShellArgs( getShellArgs() ); + shell.setExecutable(getExecutable()); + shell.setWorkingDirectory(getWorkingDirectory()); + shell.setShellArgs(getShellArgs()); return shell; } - public String getOriginalExecutable() - { + public String getOriginalExecutable() { return executable; } - public List getOriginalCommandLine( String executable, String[] arguments ) - { - return getRawCommandLine( executable, arguments ); + public List getOriginalCommandLine(String executable, String[] arguments) { + return getRawCommandLine(executable, arguments); } - protected void setDoubleQuotedArgumentEscaped( boolean doubleQuotedArgumentEscaped ) - { + protected void setDoubleQuotedArgumentEscaped(boolean doubleQuotedArgumentEscaped) { this.doubleQuotedArgumentEscaped = doubleQuotedArgumentEscaped; } - protected void setDoubleQuotedExecutableEscaped( boolean doubleQuotedExecutableEscaped ) - { + protected void setDoubleQuotedExecutableEscaped(boolean doubleQuotedExecutableEscaped) { this.doubleQuotedExecutableEscaped = doubleQuotedExecutableEscaped; } - protected void setSingleQuotedArgumentEscaped( boolean singleQuotedArgumentEscaped ) - { + protected void setSingleQuotedArgumentEscaped(boolean singleQuotedArgumentEscaped) { this.singleQuotedArgumentEscaped = singleQuotedArgumentEscaped; } - protected void setSingleQuotedExecutableEscaped( boolean singleQuotedExecutableEscaped ) - { + protected void setSingleQuotedExecutableEscaped(boolean singleQuotedExecutableEscaped) { this.singleQuotedExecutableEscaped = singleQuotedExecutableEscaped; } } diff --git a/src/main/java/org/codehaus/plexus/util/dag/CycleDetectedException.java b/src/main/java/org/codehaus/plexus/util/dag/CycleDetectedException.java index e350af9d..c4b99e44 100644 --- a/src/main/java/org/codehaus/plexus/util/dag/CycleDetectedException.java +++ b/src/main/java/org/codehaus/plexus/util/dag/CycleDetectedException.java @@ -19,43 +19,34 @@ import java.util.Iterator; import java.util.List; -public class CycleDetectedException - extends Exception -{ +public class CycleDetectedException extends Exception { private List cycle; - public CycleDetectedException( final String message, final List cycle ) - { - super( message ); + public CycleDetectedException(final String message, final List cycle) { + super(message); this.cycle = cycle; - } - public List getCycle() - { + public List getCycle() { return cycle; } - public String cycleToString() - { + public String cycleToString() { final StringBuilder buffer = new StringBuilder(); - for ( Iterator iterator = cycle.iterator(); iterator.hasNext(); ) - { - buffer.append( iterator.next() ); + for (Iterator iterator = cycle.iterator(); iterator.hasNext(); ) { + buffer.append(iterator.next()); - if ( iterator.hasNext() ) - { - buffer.append( " --> " ); + if (iterator.hasNext()) { + buffer.append(" --> "); } } return buffer.toString(); } @Override - public String getMessage() - { + public String getMessage() { return super.getMessage() + " " + cycleToString(); } } diff --git a/src/main/java/org/codehaus/plexus/util/dag/CycleDetector.java b/src/main/java/org/codehaus/plexus/util/dag/CycleDetector.java index 6f810043..98c2f451 100644 --- a/src/main/java/org/codehaus/plexus/util/dag/CycleDetector.java +++ b/src/main/java/org/codehaus/plexus/util/dag/CycleDetector.java @@ -26,31 +26,26 @@ * @author Michal Maczka * */ -public class CycleDetector -{ +public class CycleDetector { - private final static Integer NOT_VISITED = 0; + private static final Integer NOT_VISITED = 0; - private final static Integer VISITING = 1; + private static final Integer VISITING = 1; - private final static Integer VISITED = 2; + private static final Integer VISITED = 2; - public static List hasCycle( final DAG graph ) - { + public static List hasCycle(final DAG graph) { final List vertices = graph.getVertices(); final Map vertexStateMap = new HashMap<>(); List retValue = null; - for ( Vertex vertex : vertices ) - { - if ( isNotVisited( vertex, vertexStateMap ) ) - { - retValue = introducesCycle( vertex, vertexStateMap ); + for (Vertex vertex : vertices) { + if (isNotVisited(vertex, vertexStateMap)) { + retValue = introducesCycle(vertex, vertexStateMap); - if ( retValue != null ) - { + if (retValue != null) { break; } } @@ -67,14 +62,12 @@ public static List hasCycle( final DAG graph ) * @param vertexStateMap the vertex Map * @return the found cycle */ - public static List introducesCycle( final Vertex vertex, final Map vertexStateMap ) - { + public static List introducesCycle(final Vertex vertex, final Map vertexStateMap) { final LinkedList cycleStack = new LinkedList<>(); - final boolean hasCycle = dfsVisit( vertex, cycleStack, vertexStateMap ); + final boolean hasCycle = dfsVisit(vertex, cycleStack, vertexStateMap); - if ( hasCycle ) - { + if (hasCycle) { // we have a situation like: [b, a, c, d, b, f, g, h]. // Label of Vertex which introduced the cycle is at the first position in the list // We have to find second occurrence of this label and use its position in the list @@ -83,11 +76,11 @@ public static List introducesCycle( final Vertex vertex, final Map cycle = cycleStack.subList( 0, pos + 1 ); + final List cycle = cycleStack.subList(0, pos + 1); - Collections.reverse( cycle ); + Collections.reverse(cycle); return cycle; } @@ -95,57 +88,47 @@ public static List introducesCycle( final Vertex vertex, final Map introducesCycle( final Vertex vertex ) - { + public static List introducesCycle(final Vertex vertex) { final Map vertexStateMap = new HashMap<>(); - return introducesCycle( vertex, vertexStateMap ); + return introducesCycle(vertex, vertexStateMap); } - private static boolean isNotVisited( final Vertex vertex, final Map vertexStateMap ) - { - final Integer state = vertexStateMap.get( vertex ); + private static boolean isNotVisited(final Vertex vertex, final Map vertexStateMap) { + final Integer state = vertexStateMap.get(vertex); - return ( state == null ) || NOT_VISITED.equals( state ); + return (state == null) || NOT_VISITED.equals(state); } - private static boolean isVisiting( final Vertex vertex, final Map vertexStateMap ) - { - final Integer state = vertexStateMap.get( vertex ); + private static boolean isVisiting(final Vertex vertex, final Map vertexStateMap) { + final Integer state = vertexStateMap.get(vertex); - return VISITING.equals( state ); + return VISITING.equals(state); } - private static boolean dfsVisit( final Vertex vertex, final LinkedList cycle, - final Map vertexStateMap ) - { - cycle.addFirst( vertex.getLabel() ); + private static boolean dfsVisit( + final Vertex vertex, final LinkedList cycle, final Map vertexStateMap) { + cycle.addFirst(vertex.getLabel()); - vertexStateMap.put( vertex, VISITING ); + vertexStateMap.put(vertex, VISITING); - for ( Vertex v : vertex.getChildren() ) - { - if ( isNotVisited( v, vertexStateMap ) ) - { - final boolean hasCycle = dfsVisit( v, cycle, vertexStateMap ); + for (Vertex v : vertex.getChildren()) { + if (isNotVisited(v, vertexStateMap)) { + final boolean hasCycle = dfsVisit(v, cycle, vertexStateMap); - if ( hasCycle ) - { + if (hasCycle) { return true; } - } - else if ( isVisiting( v, vertexStateMap ) ) - { - cycle.addFirst( v.getLabel() ); + } else if (isVisiting(v, vertexStateMap)) { + cycle.addFirst(v.getLabel()); return true; } } - vertexStateMap.put( vertex, VISITED ); + vertexStateMap.put(vertex, VISITED); cycle.removeFirst(); return false; } - } 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 4d0f9a45..a652fcd0 100644 --- a/src/main/java/org/codehaus/plexus/util/dag/DAG.java +++ b/src/main/java/org/codehaus/plexus/util/dag/DAG.java @@ -30,9 +30,7 @@ * * TODO this class should be renamed from DAG to Dag */ -public class DAG - implements Cloneable, Serializable -{ +public class DAG implements Cloneable, Serializable { // ------------------------------------------------------------ // Fields // ------------------------------------------------------------ @@ -56,8 +54,7 @@ public class DAG /** * */ - public DAG() - { + public DAG() { super(); } @@ -68,8 +65,7 @@ public DAG() /** * @return the vertices */ - public List getVertices() - { + public List getVertices() { return vertexList; } @@ -78,13 +74,11 @@ public List getVertices() * @return the vertices */ @Deprecated - public List getVerticies() - { + public List getVerticies() { return getVertices(); } - public Set getLabels() - { + public Set getLabels() { return vertexMap.keySet(); } @@ -99,101 +93,86 @@ public Set getLabels() * @return New vertex if vertex of given label was not present in the DAG or existing vertex if vertex of given * label was already added to DAG */ - public Vertex addVertex( final String label ) - { + public Vertex addVertex(final String label) { Vertex retValue = null; // check if vertex is already in DAG - if ( vertexMap.containsKey( label ) ) - { - retValue = vertexMap.get( label ); - } - else - { - retValue = new Vertex( label ); + if (vertexMap.containsKey(label)) { + retValue = vertexMap.get(label); + } else { + retValue = new Vertex(label); - vertexMap.put( label, retValue ); + vertexMap.put(label, retValue); - vertexList.add( retValue ); + vertexList.add(retValue); } return retValue; } - public void addEdge( final String from, final String to ) - throws CycleDetectedException - { - final Vertex v1 = addVertex( from ); + public void addEdge(final String from, final String to) throws CycleDetectedException { + final Vertex v1 = addVertex(from); - final Vertex v2 = addVertex( to ); + final Vertex v2 = addVertex(to); - addEdge( v1, v2 ); + addEdge(v1, v2); } - public void addEdge( final Vertex from, final Vertex to ) - throws CycleDetectedException - { + public void addEdge(final Vertex from, final Vertex to) throws CycleDetectedException { - from.addEdgeTo( to ); + from.addEdgeTo(to); - to.addEdgeFrom( from ); + to.addEdgeFrom(from); - final List cycle = CycleDetector.introducesCycle( to ); + final List cycle = CycleDetector.introducesCycle(to); - if ( cycle != null ) - { + if (cycle != null) { // remove edge which introduced cycle - removeEdge( from, to ); + removeEdge(from, to); final String msg = "Edge between '" + from + "' and '" + to + "' introduces to cycle in the graph"; - throw new CycleDetectedException( msg, cycle ); + throw new CycleDetectedException(msg, cycle); } } - public void removeEdge( final String from, final String to ) - { - final Vertex v1 = addVertex( from ); + public void removeEdge(final String from, final String to) { + final Vertex v1 = addVertex(from); - final Vertex v2 = addVertex( to ); + final Vertex v2 = addVertex(to); - removeEdge( v1, v2 ); + removeEdge(v1, v2); } - public void removeEdge( final Vertex from, final Vertex to ) - { - from.removeEdgeTo( to ); + public void removeEdge(final Vertex from, final Vertex to) { + from.removeEdgeTo(to); - to.removeEdgeFrom( from ); + to.removeEdgeFrom(from); } - public Vertex getVertex( final String label ) - { - final Vertex retValue = vertexMap.get( label ); + public Vertex getVertex(final String label) { + final Vertex retValue = vertexMap.get(label); return retValue; } - public boolean hasEdge( final String label1, final String label2 ) - { - final Vertex v1 = getVertex( label1 ); + public boolean hasEdge(final String label1, final String label2) { + final Vertex v1 = getVertex(label1); - final Vertex v2 = getVertex( label2 ); + final Vertex v2 = getVertex(label2); - final boolean retValue = v1.getChildren().contains( v2 ); + final boolean retValue = v1.getChildren().contains(v2); return retValue; - } /** * @param label see name * @return the childs */ - public List getChildLabels( final String label ) - { - final Vertex vertex = getVertex( label ); + public List getChildLabels(final String label) { + final Vertex vertex = getVertex(label); return vertex.getChildLabels(); } @@ -202,9 +181,8 @@ public List getChildLabels( final String label ) * @param label see name * @return the parents */ - public List getParentLabels( final String label ) - { - final Vertex vertex = getVertex( label ); + public List getParentLabels(final String label) { + final Vertex vertex = getVertex(label); return vertex.getParentLabels(); } @@ -213,9 +191,7 @@ public List getParentLabels( final String label ) * @see java.lang.Object#clone() */ @Override - public Object clone() - throws CloneNotSupportedException - { + public Object clone() throws CloneNotSupportedException { // this is what's failing.. final Object retValue = super.clone(); @@ -227,14 +203,12 @@ public Object clone() * @param label the label * @return true if this vertex is connected with other vertex,false otherwise */ - public boolean isConnected( final String label ) - { - final Vertex vertex = getVertex( label ); + public boolean isConnected(final String label) { + final Vertex vertex = getVertex(label); final boolean retValue = vertex.isConnected(); return retValue; - } /** @@ -244,25 +218,20 @@ public boolean isConnected( final String label ) * @return The list of labels. Returned list contains also the label passed as parameter to this method. This label * should always be the last item in the list. */ - public List getSuccessorLabels( final String label ) - { - final Vertex vertex = getVertex( label ); + public List getSuccessorLabels(final String label) { + final Vertex vertex = getVertex(label); final List retValue; // optimization. - if ( vertex.isLeaf() ) - { - retValue = new ArrayList<>( 1 ); + if (vertex.isLeaf()) { + retValue = new ArrayList<>(1); - retValue.add( label ); - } - else - { - retValue = TopologicalSorter.sort( vertex ); + retValue.add(label); + } else { + retValue = TopologicalSorter.sort(vertex); } return retValue; } - } diff --git a/src/main/java/org/codehaus/plexus/util/dag/TopologicalSorter.java b/src/main/java/org/codehaus/plexus/util/dag/TopologicalSorter.java index b2736255..da801335 100644 --- a/src/main/java/org/codehaus/plexus/util/dag/TopologicalSorter.java +++ b/src/main/java/org/codehaus/plexus/util/dag/TopologicalSorter.java @@ -25,74 +25,63 @@ * @author Michal Maczka * */ -public class TopologicalSorter -{ +public class TopologicalSorter { - private final static Integer NOT_VISITED = 0; + private static final Integer NOT_VISITED = 0; - private final static Integer VISITING = 1; + private static final Integer VISITING = 1; - private final static Integer VISITED = 2; + private static final Integer VISITED = 2; /** * @param graph the graph * @return List of String (vertex labels) */ - public static List sort( final DAG graph ) - { - return dfs( graph ); + public static List sort(final DAG graph) { + return dfs(graph); } - public static List sort( final Vertex vertex ) - { + public static List sort(final Vertex vertex) { // we need to use addFirst method so we will use LinkedList explicitly final List retValue = new LinkedList<>(); - dfsVisit( vertex, new HashMap(), retValue ); + dfsVisit(vertex, new HashMap(), retValue); return retValue; } - private static List dfs( final DAG graph ) - { + private static List dfs(final DAG graph) { // we need to use addFirst method so we will use LinkedList explicitly final List retValue = new LinkedList<>(); final Map vertexStateMap = new HashMap<>(); - for ( Vertex vertex : graph.getVertices() ) - { - if ( isNotVisited( vertex, vertexStateMap ) ) - { - dfsVisit( vertex, vertexStateMap, retValue ); + for (Vertex vertex : graph.getVertices()) { + if (isNotVisited(vertex, vertexStateMap)) { + dfsVisit(vertex, vertexStateMap, retValue); } } return retValue; } - private static boolean isNotVisited( final Vertex vertex, final Map vertexStateMap ) - { - final Integer state = vertexStateMap.get( vertex ); + private static boolean isNotVisited(final Vertex vertex, final Map vertexStateMap) { + final Integer state = vertexStateMap.get(vertex); - return ( state == null ) || NOT_VISITED.equals( state ); + return (state == null) || NOT_VISITED.equals(state); } - private static void dfsVisit( final Vertex vertex, final Map vertexStateMap, - final List list ) - { - vertexStateMap.put( vertex, VISITING ); + private static void dfsVisit( + final Vertex vertex, final Map vertexStateMap, final List list) { + vertexStateMap.put(vertex, VISITING); - for ( Vertex v : vertex.getChildren() ) - { - if ( isNotVisited( v, vertexStateMap ) ) - { - dfsVisit( v, vertexStateMap, list ); + for (Vertex v : vertex.getChildren()) { + if (isNotVisited(v, vertexStateMap)) { + dfsVisit(v, vertexStateMap, list); } } - vertexStateMap.put( vertex, VISITED ); + vertexStateMap.put(vertex, VISITED); - list.add( vertex.getLabel() ); + list.add(vertex.getLabel()); } - } 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 489b6185..bb3cfcc1 100644 --- a/src/main/java/org/codehaus/plexus/util/dag/Vertex.java +++ b/src/main/java/org/codehaus/plexus/util/dag/Vertex.java @@ -24,9 +24,7 @@ * @author Michal Maczka * */ -public class Vertex - implements Cloneable, Serializable -{ +public class Vertex implements Cloneable, Serializable { // ------------------------------------------------------------ // Fields // ------------------------------------------------------------ @@ -40,8 +38,7 @@ public class Vertex // Constructors // ------------------------------------------------------------ - public Vertex( final String label ) - { + public Vertex(final String label) { this.label = label; } @@ -49,33 +46,27 @@ public Vertex( final String label ) // Accessors // ------------------------------------------------------------ - public String getLabel() - { + public String getLabel() { return label; } - public void addEdgeTo( final Vertex vertex ) - { - children.add( vertex ); + public void addEdgeTo(final Vertex vertex) { + children.add(vertex); } - public void removeEdgeTo( final Vertex vertex ) - { - children.remove( vertex ); + public void removeEdgeTo(final Vertex vertex) { + children.remove(vertex); } - public void addEdgeFrom( final Vertex vertex ) - { - parents.add( vertex ); + public void addEdgeFrom(final Vertex vertex) { + parents.add(vertex); } - public void removeEdgeFrom( final Vertex vertex ) - { - parents.remove( vertex ); + public void removeEdgeFrom(final Vertex vertex) { + parents.remove(vertex); } - public List getChildren() - { + public List getChildren() { return children; } @@ -84,13 +75,11 @@ public List getChildren() * * @return the labels used by the most direct children. */ - public List getChildLabels() - { - final List retValue = new ArrayList<>( children.size() ); + public List getChildLabels() { + final List retValue = new ArrayList<>(children.size()); - for ( Vertex vertex : children ) - { - retValue.add( vertex.getLabel() ); + for (Vertex vertex : children) { + retValue.add(vertex.getLabel()); } return retValue; } @@ -100,8 +89,7 @@ public List getChildLabels() * * @return list of parents */ - public List getParents() - { + public List getParents() { return parents; } @@ -110,13 +98,11 @@ public List getParents() * * @return the labels used parents */ - public List getParentLabels() - { - final List retValue = new ArrayList<>( parents.size() ); + public List getParentLabels() { + final List retValue = new ArrayList<>(parents.size()); - for ( Vertex vertex : parents ) - { - retValue.add( vertex.getLabel() ); + for (Vertex vertex : parents) { + retValue.add(vertex.getLabel()); } return retValue; } @@ -126,8 +112,7 @@ public List getParentLabels() * * @return true if this vertex has no child, false otherwise */ - public boolean isLeaf() - { + public boolean isLeaf() { return children.size() == 0; } @@ -136,8 +121,7 @@ public boolean isLeaf() * * @return true if this vertex has no parent, false otherwise */ - public boolean isRoot() - { + public boolean isRoot() { return parents.size() == 0; } @@ -146,15 +130,12 @@ public boolean isRoot() * * @return true if this vertex is connected with other vertex,false otherwise */ - public boolean isConnected() - { + public boolean isConnected() { return isRoot() || isLeaf(); } @Override - public Object clone() - throws CloneNotSupportedException - { + public Object clone() throws CloneNotSupportedException { // this is what's failing.. final Object retValue = super.clone(); @@ -162,9 +143,7 @@ public Object clone() } @Override - public String toString() - { + public String toString() { return "Vertex{" + "label='" + label + "'" + "}"; } - } 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 6e0c8be2..472419df 100644 --- a/src/main/java/org/codehaus/plexus/util/introspection/ClassMap.java +++ b/src/main/java/org/codehaus/plexus/util/introspection/ClassMap.java @@ -31,11 +31,8 @@ * @author Geir Magnusson Jr. * */ -public class ClassMap -{ - private static final class CacheMiss - { - } +public class ClassMap { + private static final class CacheMiss {} private static final CacheMiss CACHE_MISS = new CacheMiss(); @@ -44,7 +41,6 @@ private static final class CacheMiss /** * Class passed into the constructor used to as the basis for the Method map. */ - private final Class clazz; /** @@ -58,8 +54,7 @@ private static final class CacheMiss * Standard constructor * @param clazz the Class */ - public ClassMap( Class clazz ) - { + public ClassMap(Class clazz) { this.clazz = clazz; populateMethodCache(); } @@ -67,58 +62,47 @@ public ClassMap( Class clazz ) /** * @return the class object whose methods are cached by this map. */ - Class getCachedClass() - { + Class getCachedClass() { return clazz; } /** *

      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.

      * @param name method name * @param params method params * @return the find Method or null * @throws org.codehaus.plexus.util.introspection.MethodMap.AmbiguousException if ambiguous name */ - public Method findMethod( String name, Object[] params ) - throws MethodMap.AmbiguousException - { - String methodKey = makeMethodKey( name, params ); - Object cacheEntry = methodCache.get( methodKey ); - - if ( cacheEntry == CACHE_MISS ) - { + public Method findMethod(String name, Object[] params) throws MethodMap.AmbiguousException { + String methodKey = makeMethodKey(name, params); + Object cacheEntry = methodCache.get(methodKey); + + if (cacheEntry == CACHE_MISS) { return null; } - if ( cacheEntry == null ) - { - try - { - cacheEntry = methodMap.find( name, params ); - } - catch ( MethodMap.AmbiguousException ae ) - { + if (cacheEntry == null) { + try { + cacheEntry = methodMap.find(name, params); + } catch (MethodMap.AmbiguousException ae) { /* * that's a miss :) */ - methodCache.put( methodKey, CACHE_MISS ); + methodCache.put(methodKey, CACHE_MISS); throw ae; } - if ( cacheEntry == null ) - { - methodCache.put( methodKey, CACHE_MISS ); - } - else - { - methodCache.put( methodKey, cacheEntry ); + if (cacheEntry == null) { + methodCache.put(methodKey, CACHE_MISS); + } else { + methodCache.put(methodKey, cacheEntry); } } @@ -130,28 +114,26 @@ public Method findMethod( String name, Object[] params ) /** * Populate the Map of direct hits. These are taken from all the public methods that our class provides. */ - private void populateMethodCache() - { + private void populateMethodCache() { StringBuffer methodKey; /* * get all publicly accessible methods */ - Method[] methods = getAccessibleMethods( clazz ); + Method[] methods = getAccessibleMethods(clazz); /* * map and cache them */ - for ( Method method : methods ) - { + for (Method method : methods) { /* * now get the 'public method', the method declared by a public interface or class. (because the actual * implementing class may be a facade... */ - Method publicMethod = getPublicMethod( method ); + Method publicMethod = getPublicMethod(method); /* * it is entirely possible that there is no public method for the methods of this class (i.e. in the facade, @@ -159,10 +141,9 @@ private void populateMethodCache() * cache */ - if ( publicMethod != null ) - { - methodMap.add( publicMethod ); - methodCache.put( makeMethodKey( publicMethod ), publicMethod ); + if (publicMethod != null) { + methodMap.add(publicMethod); + methodCache.put(makeMethodKey(publicMethod), publicMethod); } } } @@ -170,76 +151,53 @@ private void populateMethodCache() /** * Make a methodKey for the given method using the concatenation of the name and the types of the method parameters. */ - private String makeMethodKey( Method method ) - { + private String makeMethodKey(Method method) { Class[] parameterTypes = method.getParameterTypes(); - StringBuilder methodKey = new StringBuilder( method.getName() ); + StringBuilder methodKey = new StringBuilder(method.getName()); - for ( Class parameterType : parameterTypes ) - { + for (Class parameterType : parameterTypes) { /* * If the argument type is primitive then we want to convert our primitive type signature to the * corresponding Object type so introspection for methods with primitive types will work correctly. */ - if ( parameterType.isPrimitive() ) - { - if ( parameterType.equals( Boolean.TYPE ) ) - { - methodKey.append( "java.lang.Boolean" ); - } - else if ( parameterType.equals( Byte.TYPE ) ) - { - methodKey.append( "java.lang.Byte" ); - } - else if ( parameterType.equals( Character.TYPE ) ) - { - methodKey.append( "java.lang.Character" ); + if (parameterType.isPrimitive()) { + if (parameterType.equals(Boolean.TYPE)) { + methodKey.append("java.lang.Boolean"); + } else if (parameterType.equals(Byte.TYPE)) { + methodKey.append("java.lang.Byte"); + } else if (parameterType.equals(Character.TYPE)) { + methodKey.append("java.lang.Character"); + } else if (parameterType.equals(Double.TYPE)) { + methodKey.append("java.lang.Double"); + } else if (parameterType.equals(Float.TYPE)) { + methodKey.append("java.lang.Float"); + } else if (parameterType.equals(Integer.TYPE)) { + methodKey.append("java.lang.Integer"); + } else if (parameterType.equals(Long.TYPE)) { + methodKey.append("java.lang.Long"); + } else if (parameterType.equals(Short.TYPE)) { + methodKey.append("java.lang.Short"); } - else if ( parameterType.equals( Double.TYPE ) ) - { - methodKey.append( "java.lang.Double" ); - } - else if ( parameterType.equals( Float.TYPE ) ) - { - methodKey.append( "java.lang.Float" ); - } - else if ( parameterType.equals( Integer.TYPE ) ) - { - methodKey.append( "java.lang.Integer" ); - } - else if ( parameterType.equals( Long.TYPE ) ) - { - methodKey.append( "java.lang.Long" ); - } - else if ( parameterType.equals( Short.TYPE ) ) - { - methodKey.append( "java.lang.Short" ); - } - } - else - { - methodKey.append( parameterType.getName() ); + } else { + methodKey.append(parameterType.getName()); } } return methodKey.toString(); } - private static String makeMethodKey( String method, Object[] params ) - { - StringBuilder methodKey = new StringBuilder().append( method ); + private static String makeMethodKey(String method, Object[] params) { + StringBuilder methodKey = new StringBuilder().append(method); - for ( Object param : params ) - { + for (Object param : params) { Object arg = param; - if ( arg == null ) - { + if (arg == null) { arg = OBJECT; } - methodKey.append( arg.getClass().getName() ); + methodKey.append(arg.getClass().getName()); } return methodKey.toString(); @@ -250,16 +208,14 @@ private static String makeMethodKey( String method, Object[] params ) * its public methods from public superclasses and interfaces (if they exist). Basically upcasts every method to the * nearest accessible method. */ - private static Method[] getAccessibleMethods( Class clazz ) - { + private static Method[] getAccessibleMethods(Class clazz) { Method[] methods = clazz.getMethods(); /* * Short circuit for the (hopefully) majority of cases where the clazz is public */ - if ( Modifier.isPublic( clazz.getModifiers() ) ) - { + if (Modifier.isPublic(clazz.getModifiers())) { return methods; } @@ -269,27 +225,23 @@ private static Method[] getAccessibleMethods( Class clazz ) MethodInfo[] methodInfos = new MethodInfo[methods.length]; - for ( int i = methods.length; i-- > 0; ) - { - methodInfos[i] = new MethodInfo( methods[i] ); + for (int i = methods.length; i-- > 0; ) { + methodInfos[i] = new MethodInfo(methods[i]); } - int upcastCount = getAccessibleMethods( clazz, methodInfos, 0 ); + int upcastCount = getAccessibleMethods(clazz, methodInfos, 0); /* * Reallocate array in case some method had no accessible counterpart. */ - if ( upcastCount < methods.length ) - { + if (upcastCount < methods.length) { methods = new Method[upcastCount]; } int j = 0; - for ( MethodInfo methodInfo : methodInfos ) - { - if ( methodInfo.upcast ) - { + for (MethodInfo methodInfo : methodInfos) { + if (methodInfo.upcast) { methods[j++] = methodInfo.method; } } @@ -305,30 +257,23 @@ private static Method[] getAccessibleMethods( Class clazz ) * @param upcastCount current number of methods we have matched * @return count of matched methods */ - private static int getAccessibleMethods( Class clazz, MethodInfo[] methodInfos, int upcastCount ) - { + private static int getAccessibleMethods(Class clazz, MethodInfo[] methodInfos, int upcastCount) { int l = methodInfos.length; /* * if this class is public, then check each of the currently 'non-upcasted' methods to see if we have a match */ - if ( Modifier.isPublic( clazz.getModifiers() ) ) - { - for ( int i = 0; i < l && upcastCount < l; ++i ) - { - try - { + if (Modifier.isPublic(clazz.getModifiers())) { + for (int i = 0; i < l && upcastCount < l; ++i) { + try { MethodInfo methodInfo = methodInfos[i]; - if ( !methodInfo.upcast ) - { - methodInfo.tryUpcasting( clazz ); + if (!methodInfo.upcast) { + methodInfo.tryUpcasting(clazz); upcastCount++; } - } - catch ( NoSuchMethodException e ) - { + } catch (NoSuchMethodException e) { /* * Intentionally ignored - it means it wasn't found in the current class */ @@ -339,8 +284,7 @@ private static int getAccessibleMethods( Class clazz, MethodInfo[] methodInfos, * Short circuit if all methods were upcast */ - if ( upcastCount == l ) - { + if (upcastCount == l) { return upcastCount; } } @@ -351,16 +295,14 @@ private static int getAccessibleMethods( Class clazz, MethodInfo[] methodInfos, Class superclazz = clazz.getSuperclass(); - if ( superclazz != null ) - { - upcastCount = getAccessibleMethods( superclazz, methodInfos, upcastCount ); + if (superclazz != null) { + upcastCount = getAccessibleMethods(superclazz, methodInfos, upcastCount); /* * Short circuit if all methods were upcast */ - if ( upcastCount == l ) - { + if (upcastCount == l) { return upcastCount; } } @@ -372,16 +314,14 @@ private static int getAccessibleMethods( Class clazz, MethodInfo[] methodInfos, Class[] interfaces = clazz.getInterfaces(); - for ( int i = interfaces.length; i-- > 0; ) - { - upcastCount = getAccessibleMethods( interfaces[i], methodInfos, upcastCount ); + for (int i = interfaces.length; i-- > 0; ) { + upcastCount = getAccessibleMethods(interfaces[i], methodInfos, upcastCount); /* * Short circuit if all methods were upcast */ - if ( upcastCount == l ) - { + if (upcastCount == l) { return upcastCount; } } @@ -398,20 +338,18 @@ private static int getAccessibleMethods( Class clazz, MethodInfo[] methodInfos, * @return the publicly callable counterpart method. Note that if the parameter method is itself declared by a * public class, this method is an identity function. */ - public static Method getPublicMethod( Method method ) - { + public static Method getPublicMethod(Method method) { Class clazz = method.getDeclaringClass(); /* * Short circuit for (hopefully the majority of) cases where the declaring class is public. */ - if ( ( clazz.getModifiers() & Modifier.PUBLIC ) != 0 ) - { + if ((clazz.getModifiers() & Modifier.PUBLIC) != 0) { return method; } - return getPublicMethod( clazz, method.getName(), method.getParameterTypes() ); + return getPublicMethod(clazz, method.getName(), method.getParameterTypes()); } /** @@ -422,20 +360,15 @@ public static Method getPublicMethod( Method method ) * @param name the name of the method * @param paramTypes the classes of method parameters */ - private static Method getPublicMethod( Class clazz, String name, Class[] paramTypes ) - { + private static Method getPublicMethod(Class clazz, String name, Class[] paramTypes) { /* * if this class is public, then try to get it */ - if ( ( clazz.getModifiers() & Modifier.PUBLIC ) != 0 ) - { - try - { - return clazz.getMethod( name, paramTypes ); - } - catch ( NoSuchMethodException e ) - { + if ((clazz.getModifiers() & Modifier.PUBLIC) != 0) { + try { + return clazz.getMethod(name, paramTypes); + } catch (NoSuchMethodException e) { /* * If the class does not have the method, then neither its superclass nor any of its interfaces has it * so quickly return null. @@ -450,12 +383,10 @@ private static Method getPublicMethod( Class clazz, String name, Class[] paramTy Class superclazz = clazz.getSuperclass(); - if ( superclazz != null ) - { - Method superclazzMethod = getPublicMethod( superclazz, name, paramTypes ); + if (superclazz != null) { + Method superclazzMethod = getPublicMethod(superclazz, name, paramTypes); - if ( superclazzMethod != null ) - { + if (superclazzMethod != null) { return superclazzMethod; } } @@ -466,12 +397,10 @@ private static Method getPublicMethod( Class clazz, String name, Class[] paramTy Class[] interfaces = clazz.getInterfaces(); - for ( Class anInterface : interfaces ) - { - Method interfaceMethod = getPublicMethod( anInterface, name, paramTypes ); + for (Class anInterface : interfaces) { + Method interfaceMethod = getPublicMethod(anInterface, name, paramTypes); - if ( interfaceMethod != null ) - { + if (interfaceMethod != null) { return interfaceMethod; } } @@ -482,8 +411,7 @@ private static Method getPublicMethod( Class clazz, String name, Class[] paramTy /** * Used for the iterative discovery process for public methods. */ - private static final class MethodInfo - { + private static final class MethodInfo { Method method; String name; @@ -492,18 +420,15 @@ private static final class MethodInfo boolean upcast; - MethodInfo( Method method ) - { + MethodInfo(Method method) { this.method = null; name = method.getName(); parameterTypes = method.getParameterTypes(); upcast = false; } - void tryUpcasting( Class clazz ) - throws NoSuchMethodException - { - method = clazz.getMethod( name, parameterTypes ); + void tryUpcasting(Class clazz) throws NoSuchMethodException { + method = clazz.getMethod(name, parameterTypes); name = null; parameterTypes = null; upcast = true; diff --git a/src/main/java/org/codehaus/plexus/util/introspection/MethodMap.java b/src/main/java/org/codehaus/plexus/util/introspection/MethodMap.java index 51420cca..52493ce0 100644 --- a/src/main/java/org/codehaus/plexus/util/introspection/MethodMap.java +++ b/src/main/java/org/codehaus/plexus/util/introspection/MethodMap.java @@ -32,8 +32,7 @@ * @author Attila Szegedi * */ -public class MethodMap -{ +public class MethodMap { private static final int MORE_SPECIFIC = 0; private static final int LESS_SPECIFIC = 1; @@ -48,22 +47,20 @@ public class MethodMap /** * Add a method to a list of methods by name. For a particular class we are keeping track of all the methods with * the same name. - * + * * @param method The method */ - public void add( Method method ) - { + public void add(Method method) { String methodName = method.getName(); - List l = get( methodName ); + List l = get(methodName); - if ( l == null ) - { + if (l == null) { l = new ArrayList(); - methodByNameMap.put( methodName, l ); + methodByNameMap.put(methodName, l); } - l.add( method ); + l.add(method); } /** @@ -72,9 +69,8 @@ public void add( Method method ) * @param key The name of the method. * @return List list of methods */ - public List get( String key ) - { - return methodByNameMap.get( key ); + public List get(String key) { + return methodByNameMap.get(key); } /** @@ -94,21 +90,17 @@ public List get( String key ) * @return the most specific applicable method, or null if no method is applicable. * @throws AmbiguousException if there is more than one maximally specific applicable method */ - public Method find( String methodName, Object[] args ) - throws AmbiguousException - { - List methodList = get( methodName ); + public Method find(String methodName, Object[] args) throws AmbiguousException { + List methodList = get(methodName); - if ( methodList == null ) - { + if (methodList == null) { return null; } int l = args.length; Class[] classes = new Class[l]; - for ( int i = 0; i < l; ++i ) - { + for (int i = 0; i < l; ++i) { Object arg = args[i]; /* @@ -118,29 +110,22 @@ public Method find( String methodName, Object[] args ) classes[i] = arg == null ? null : arg.getClass(); } - return getMostSpecific( methodList, classes ); + return getMostSpecific(methodList, classes); } /** * simple distinguishable exception, used when we run across ambiguous overloading */ - public static class AmbiguousException - extends Exception - { - } + public static class AmbiguousException extends Exception {} - private static Method getMostSpecific( List methods, Class[] classes ) - throws AmbiguousException - { - LinkedList applicables = getApplicables( methods, classes ); + private static Method getMostSpecific(List methods, Class[] classes) throws AmbiguousException { + LinkedList applicables = getApplicables(methods, classes); - if ( applicables.isEmpty() ) - { + if (applicables.isEmpty()) { return null; } - if ( applicables.size() == 1 ) - { + if (applicables.size() == 1) { return applicables.getFirst(); } @@ -151,19 +136,15 @@ private static Method getMostSpecific( List methods, Class[] classes ) LinkedList maximals = new LinkedList(); - for ( Method app : applicables ) - { + for (Method app : applicables) { Class[] appArgs = app.getParameterTypes(); boolean lessSpecific = false; - for ( Iterator maximal = maximals.iterator(); !lessSpecific && maximal.hasNext(); ) - { + for (Iterator maximal = maximals.iterator(); !lessSpecific && maximal.hasNext(); ) { Method max = maximal.next(); - switch ( moreSpecific( appArgs, max.getParameterTypes() ) ) - { - case MORE_SPECIFIC: - { + switch (moreSpecific(appArgs, max.getParameterTypes())) { + case MORE_SPECIFIC: { /* * This method is more specific than the previously known maximally specific, so remove the old * maximum. @@ -173,8 +154,7 @@ private static Method getMostSpecific( List methods, Class[] classes ) break; } - case LESS_SPECIFIC: - { + case LESS_SPECIFIC: { /* * This method is less specific than some of the currently known maximally specific methods, so * we won't add it into the set of maximally specific methods @@ -186,14 +166,12 @@ private static Method getMostSpecific( List methods, Class[] classes ) } } - if ( !lessSpecific ) - { - maximals.addLast( app ); + if (!lessSpecific) { + maximals.addLast(app); } } - if ( maximals.size() > 1 ) - { + if (maximals.size() > 1) { // We have more than one maximally specific method throw new AmbiguousException(); } @@ -204,30 +182,25 @@ private static Method getMostSpecific( List methods, Class[] classes ) /** * Determines which method signature (represented by a class array) is more specific. This defines a partial * ordering on the method signatures. - * + * * @param c1 first signature to compare * @param c2 second signature to compare * @return MORE_SPECIFIC if c1 is more specific than c2, LESS_SPECIFIC if c1 is less specific than c2, INCOMPARABLE * if they are incomparable. */ - private static int moreSpecific( Class[] c1, Class[] c2 ) - { + private static int moreSpecific(Class[] c1, Class[] c2) { boolean c1MoreSpecific = false; boolean c2MoreSpecific = false; - for ( int i = 0; i < c1.length; ++i ) - { - if ( c1[i] != c2[i] ) - { - c1MoreSpecific = c1MoreSpecific || isStrictMethodInvocationConvertible( c2[i], c1[i] ); - c2MoreSpecific = c2MoreSpecific || isStrictMethodInvocationConvertible( c1[i], c2[i] ); + for (int i = 0; i < c1.length; ++i) { + if (c1[i] != c2[i]) { + c1MoreSpecific = c1MoreSpecific || isStrictMethodInvocationConvertible(c2[i], c1[i]); + c2MoreSpecific = c2MoreSpecific || isStrictMethodInvocationConvertible(c1[i], c2[i]); } } - if ( c1MoreSpecific ) - { - if ( c2MoreSpecific ) - { + if (c1MoreSpecific) { + if (c2MoreSpecific) { /* * Incomparable due to cross-assignable arguments (i.e. foo(String, Object) vs. foo(Object, String)) */ @@ -238,8 +211,7 @@ private static int moreSpecific( Class[] c1, Class[] c2 ) return MORE_SPECIFIC; } - if ( c2MoreSpecific ) - { + if (c2MoreSpecific) { return LESS_SPECIFIC; } @@ -252,49 +224,41 @@ private static int moreSpecific( Class[] c1, Class[] c2 ) /** * Returns all methods that are applicable to actual argument types. - * + * * @param methods list of all candidate methods * @param classes the actual types of the arguments * @return a list that contains only applicable methods (number of formal and actual arguments matches, and argument * types are assignable to formal types through a method invocation conversion). */ - private static LinkedList getApplicables( List methods, Class[] classes ) - { + private static LinkedList getApplicables(List methods, Class[] classes) { LinkedList list = new LinkedList(); - for ( Object method1 : methods ) - { + for (Object method1 : methods) { Method method = (Method) method1; - if ( isApplicable( method, classes ) ) - { - list.add( method ); + if (isApplicable(method, classes)) { + list.add(method); } - } return list; } /** * Returns true if the supplied method is applicable to actual argument types. - * + * * @param method The method to check for applicability * @param classes The arguments * @return true if the method applies to the parameter types */ - private static boolean isApplicable( Method method, Class[] classes ) - { + private static boolean isApplicable(Method method, Class[] classes) { Class[] methodArgs = method.getParameterTypes(); - if ( methodArgs.length != classes.length ) - { + if (methodArgs.length != classes.length) { return false; } - for ( int i = 0; i < classes.length; ++i ) - { - if ( !isMethodInvocationConvertible( methodArgs[i], classes[i] ) ) - { + for (int i = 0; i < classes.length; ++i) { + if (!isMethodInvocationConvertible(methodArgs[i], classes[i])) { return false; } } @@ -315,13 +279,11 @@ private static boolean isApplicable( Method method, Class[] classes ) * its corresponding object type or an object type of a primitive type that can be converted to the formal * type. */ - private static boolean isMethodInvocationConvertible( Class formal, Class actual ) - { + private static boolean isMethodInvocationConvertible(Class formal, Class actual) { /* * if it's a null, it means the arg was null */ - if ( actual == null && !formal.isPrimitive() ) - { + if (actual == null && !formal.isPrimitive()) { return true; } @@ -329,8 +291,7 @@ private static boolean isMethodInvocationConvertible( Class formal, Class actual * Check for identity or widening reference conversion */ - if ( actual != null && formal.isAssignableFrom( actual ) ) - { + if (actual != null && formal.isAssignableFrom(actual)) { return true; } @@ -338,28 +299,31 @@ private static boolean isMethodInvocationConvertible( Class formal, Class actual * Check for boxing with widening primitive conversion. Note that actual parameters are never primitives. */ - if ( formal.isPrimitive() ) - { - if ( formal == Boolean.TYPE && actual == Boolean.class ) - return true; - if ( formal == Character.TYPE && actual == Character.class ) - return true; - if ( formal == Byte.TYPE && actual == Byte.class ) - return true; - if ( formal == Short.TYPE && ( actual == Short.class || actual == Byte.class ) ) - return true; - if ( formal == Integer.TYPE - && ( actual == Integer.class || actual == Short.class || actual == Byte.class ) ) - return true; - if ( formal == Long.TYPE && ( actual == Long.class || actual == Integer.class || actual == Short.class - || actual == Byte.class ) ) - return true; - if ( formal == Float.TYPE && ( actual == Float.class || actual == Long.class || actual == Integer.class - || actual == Short.class || actual == Byte.class ) ) - return true; - if ( formal == Double.TYPE && ( actual == Double.class || actual == Float.class || actual == Long.class - || actual == Integer.class || actual == Short.class || actual == Byte.class ) ) + if (formal.isPrimitive()) { + if (formal == Boolean.TYPE && actual == Boolean.class) return true; + if (formal == Character.TYPE && actual == Character.class) return true; + if (formal == Byte.TYPE && actual == Byte.class) return true; + if (formal == Short.TYPE && (actual == Short.class || actual == Byte.class)) return true; + if (formal == Integer.TYPE && (actual == Integer.class || actual == Short.class || actual == Byte.class)) return true; + if (formal == Long.TYPE + && (actual == Long.class + || actual == Integer.class + || actual == Short.class + || actual == Byte.class)) return true; + if (formal == Float.TYPE + && (actual == Float.class + || actual == Long.class + || actual == Integer.class + || actual == Short.class + || actual == Byte.class)) return true; + if (formal == Double.TYPE + && (actual == Double.class + || actual == Float.class + || actual == Long.class + || actual == Integer.class + || actual == Short.class + || actual == Byte.class)) return true; } return false; @@ -375,13 +339,11 @@ private static boolean isMethodInvocationConvertible( Class formal, Class actual * @return true if either formal type is assignable from actual type, or formal and actual are both primitive types * and actual can be subject to widening conversion to formal. */ - private static boolean isStrictMethodInvocationConvertible( Class formal, Class actual ) - { + private static boolean isStrictMethodInvocationConvertible(Class formal, Class actual) { /* * we shouldn't get a null into, but if so */ - if ( actual == null && !formal.isPrimitive() ) - { + if (actual == null && !formal.isPrimitive()) { return true; } @@ -389,8 +351,7 @@ private static boolean isStrictMethodInvocationConvertible( Class formal, Class * Check for identity or widening reference conversion */ - if ( formal.isAssignableFrom( actual ) ) - { + if (formal.isAssignableFrom(actual)) { return true; } @@ -398,20 +359,20 @@ private static boolean isStrictMethodInvocationConvertible( Class formal, Class * Check for widening primitive conversion. */ - if ( formal.isPrimitive() ) - { - if ( formal == Short.TYPE && ( actual == Byte.TYPE ) ) - return true; - if ( formal == Integer.TYPE && ( actual == Short.TYPE || actual == Byte.TYPE ) ) - return true; - if ( formal == Long.TYPE && ( actual == Integer.TYPE || actual == Short.TYPE || actual == Byte.TYPE ) ) - return true; - if ( formal == Float.TYPE - && ( actual == Long.TYPE || actual == Integer.TYPE || actual == Short.TYPE || actual == Byte.TYPE ) ) + if (formal.isPrimitive()) { + if (formal == Short.TYPE && (actual == Byte.TYPE)) return true; + if (formal == Integer.TYPE && (actual == Short.TYPE || actual == Byte.TYPE)) return true; + if (formal == Long.TYPE && (actual == Integer.TYPE || actual == Short.TYPE || actual == Byte.TYPE)) return true; - if ( formal == Double.TYPE && ( actual == Float.TYPE || actual == Long.TYPE || actual == Integer.TYPE - || actual == Short.TYPE || actual == Byte.TYPE ) ) + if (formal == Float.TYPE + && (actual == Long.TYPE || actual == Integer.TYPE || actual == Short.TYPE || actual == Byte.TYPE)) return true; + if (formal == Double.TYPE + && (actual == Float.TYPE + || actual == Long.TYPE + || actual == Integer.TYPE + || actual == Short.TYPE + || actual == Byte.TYPE)) return true; } return false; } 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 656c8201..0ca46b7f 100644 --- a/src/main/java/org/codehaus/plexus/util/introspection/ReflectionValueExtractor.java +++ b/src/main/java/org/codehaus/plexus/util/introspection/ReflectionValueExtractor.java @@ -34,15 +34,14 @@ *

      * The implementation supports indexed, nested and mapped properties similar to the JSP way. *

      - * + * * @author Jason van Zyl * @author Vincent Siveton * * @see http://struts.apache.org/1.x/struts-taglib/indexedprops.html */ -public class ReflectionValueExtractor -{ +public class ReflectionValueExtractor { private static final Class[] CLASS_ARGS = new Class[0]; private static final Object[] OBJECT_ARGS = new Object[0]; @@ -52,7 +51,7 @@ public class ReflectionValueExtractor * space overflows due to retention of discarded classloaders. */ private static final Map, WeakReference> classMaps = - new WeakHashMap, WeakReference>(); + new WeakHashMap, WeakReference>(); static final int EOF = -1; @@ -66,83 +65,69 @@ public class ReflectionValueExtractor static final char MAPPED_END = ')'; - static class Tokenizer - { + static class Tokenizer { final String expression; int idx; - public Tokenizer( String expression ) - { + public Tokenizer(String expression) { this.expression = expression; } - public int peekChar() - { - return idx < expression.length() ? expression.charAt( idx ) : EOF; + public int peekChar() { + return idx < expression.length() ? expression.charAt(idx) : EOF; } - public int skipChar() - { - return idx < expression.length() ? expression.charAt( idx++ ) : EOF; + public int skipChar() { + return idx < expression.length() ? expression.charAt(idx++) : EOF; } - public String nextToken( char delimiter ) - { + public String nextToken(char delimiter) { int start = idx; - while ( idx < expression.length() && delimiter != expression.charAt( idx ) ) - { + while (idx < expression.length() && delimiter != expression.charAt(idx)) { idx++; } // delimiter MUST be present - if ( idx <= start || idx >= expression.length() ) - { + if (idx <= start || idx >= expression.length()) { return null; } - return expression.substring( start, idx++ ); + return expression.substring(start, idx++); } - public String nextPropertyName() - { + public String nextPropertyName() { final int start = idx; - while ( idx < expression.length() && Character.isJavaIdentifierPart( expression.charAt( idx ) ) ) - { + while (idx < expression.length() && Character.isJavaIdentifierPart(expression.charAt(idx))) { idx++; } // property name does not require delimiter - if ( idx <= start || idx > expression.length() ) - { + if (idx <= start || idx > expression.length()) { return null; } - return expression.substring( start, idx ); + return expression.substring(start, idx); } - public int getPosition() - { + public int getPosition() { return idx < expression.length() ? idx : EOF; } // to make tokenizer look pretty in debugger @Override - public String toString() - { - return idx < expression.length() ? expression.substring( idx ) : ""; + public String toString() { + return idx < expression.length() ? expression.substring(idx) : ""; } } - private ReflectionValueExtractor() - { - } + private ReflectionValueExtractor() {} /** *

      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+)\\] @@ -150,21 +135,19 @@ private ReflectionValueExtractor() *
      • mapped properties should be contains (\\w+)\\((.+)\\) pattern, i.e. * "user.addresses(myAddress).street"
      • *
      - * + * * @param expression not null expression * @param root not null object * @return the object defined by the expression * @throws Exception if any */ - public static Object evaluate( String expression, Object root ) - throws Exception - { - return evaluate( expression, root, true ); + public static Object evaluate(String expression, Object root) throws Exception { + return evaluate(expression, root, true); } /** *

      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+)\\] @@ -172,7 +155,7 @@ public static Object evaluate( String expression, Object root ) *
      • mapped properties should be contains (\\w+)\\((.+)\\) pattern, i.e. * "user.addresses(myAddress).street"
      • *
      - * + * * @param expression not null expression * @param root not null object * @param trimRootToken root start @@ -180,9 +163,7 @@ public static Object evaluate( String expression, Object root ) * @throws Exception if any */ // TODO: don't throw Exception - public static Object evaluate( String expression, final Object root, final boolean trimRootToken ) - throws Exception - { + public static Object evaluate(String expression, final Object root, final boolean trimRootToken) throws Exception { Object value = root; // ---------------------------------------------------------------------- @@ -190,44 +171,45 @@ public static Object evaluate( String expression, final Object root, final boole // MavenProject instance. // ---------------------------------------------------------------------- - if ( StringUtils.isEmpty( expression ) || !Character.isJavaIdentifierStart( expression.charAt( 0 ) ) ) - { + if (StringUtils.isEmpty(expression) || !Character.isJavaIdentifierStart(expression.charAt(0))) { return null; } - boolean hasDots = expression.indexOf( PROPERTY_START ) >= 0; + boolean hasDots = expression.indexOf(PROPERTY_START) >= 0; final Tokenizer tokenizer; - if ( trimRootToken && hasDots ) - { - tokenizer = new Tokenizer( expression ); + if (trimRootToken && hasDots) { + tokenizer = new Tokenizer(expression); tokenizer.nextPropertyName(); - if ( tokenizer.getPosition() == EOF ) - { + if (tokenizer.getPosition() == EOF) { return null; } - } - else - { - tokenizer = new Tokenizer( "." + expression ); + } else { + tokenizer = new Tokenizer("." + expression); } int propertyPosition = tokenizer.getPosition(); - while ( value != null && tokenizer.peekChar() != EOF ) - { - switch ( tokenizer.skipChar() ) - { + while (value != null && tokenizer.peekChar() != EOF) { + switch (tokenizer.skipChar()) { case INDEXED_START: - value = getIndexedValue( expression, propertyPosition, tokenizer.getPosition(), value, - tokenizer.nextToken( INDEXED_END ) ); + value = getIndexedValue( + expression, + propertyPosition, + tokenizer.getPosition(), + value, + tokenizer.nextToken(INDEXED_END)); break; case MAPPED_START: - value = getMappedValue( expression, propertyPosition, tokenizer.getPosition(), value, - tokenizer.nextToken( MAPPED_END ) ); + value = getMappedValue( + expression, + propertyPosition, + tokenizer.getPosition(), + value, + tokenizer.nextToken(MAPPED_END)); break; case PROPERTY_START: propertyPosition = tokenizer.getPosition(); - value = getPropertyValue( value, tokenizer.nextPropertyName() ); + value = getPropertyValue(value, tokenizer.nextPropertyName()); break; default: // could not parse expression @@ -238,122 +220,100 @@ public static Object evaluate( String expression, final Object root, final boole return value; } - private static Object getMappedValue( final String expression, final int from, final int to, final Object value, - final String key ) - throws Exception - { - if ( value == null || key == null ) - { + private static Object getMappedValue( + final String expression, final int from, final int to, final Object value, final String key) + throws Exception { + if (value == null || key == null) { return null; } - if ( value instanceof Map ) - { - Object[] localParams = new Object[] { key }; - ClassMap classMap = getClassMap( value.getClass() ); - Method method = classMap.findMethod( "get", localParams ); - return method.invoke( value, localParams ); + if (value instanceof Map) { + Object[] localParams = new Object[] {key}; + ClassMap classMap = getClassMap(value.getClass()); + Method method = classMap.findMethod("get", localParams); + return method.invoke(value, localParams); } - final String message = - String.format( "The token '%s' at position '%d' refers to a java.util.Map, but the value seems is an instance of '%s'", - expression.subSequence( from, to ), from, value.getClass() ); + final String message = String.format( + "The token '%s' at position '%d' refers to a java.util.Map, but the value seems is an instance of '%s'", + expression.subSequence(from, to), from, value.getClass()); - throw new Exception( message ); + throw new Exception(message); } - private static Object getIndexedValue( final String expression, final int from, final int to, final Object value, - final String indexStr ) - throws Exception - { - try - { - int index = Integer.parseInt( indexStr ); - - if ( value.getClass().isArray() ) - { - return Array.get( value, index ); + private static Object getIndexedValue( + final String expression, final int from, final int to, final Object value, final String indexStr) + throws Exception { + try { + int index = Integer.parseInt(indexStr); + + if (value.getClass().isArray()) { + return Array.get(value, index); } - if ( value instanceof List ) - { - ClassMap classMap = getClassMap( value.getClass() ); + if (value instanceof List) { + ClassMap classMap = getClassMap(value.getClass()); // use get method on List interface - Object[] localParams = new Object[] { index }; - Method method = classMap.findMethod( "get", localParams ); - return method.invoke( value, localParams ); + Object[] localParams = new Object[] {index}; + Method method = classMap.findMethod("get", localParams); + return method.invoke(value, localParams); } - } - catch ( NumberFormatException e ) - { + } catch (NumberFormatException e) { return null; - } - catch ( InvocationTargetException e ) - { + } catch (InvocationTargetException e) { // catch array index issues gracefully, otherwise release - if ( e.getCause() instanceof IndexOutOfBoundsException ) - { + if (e.getCause() instanceof IndexOutOfBoundsException) { return null; } throw e; } - final String message = - String.format( "The token '%s' at position '%d' refers to a java.util.List or an array, but the value seems is an instance of '%s'", - expression.subSequence( from, to ), from, value.getClass() ); + final String message = String.format( + "The token '%s' at position '%d' refers to a java.util.List or an array, but the value seems is an instance of '%s'", + expression.subSequence(from, to), from, value.getClass()); - throw new Exception( message ); + throw new Exception(message); } - private static Object getPropertyValue( Object value, String property ) - throws Exception - { - if ( value == null || property == null ) - { + private static Object getPropertyValue(Object value, String property) throws Exception { + if (value == null || property == null) { return null; } - ClassMap classMap = getClassMap( value.getClass() ); - String methodBase = StringUtils.capitalizeFirstLetter( property ); + ClassMap classMap = getClassMap(value.getClass()); + String methodBase = StringUtils.capitalizeFirstLetter(property); String methodName = "get" + methodBase; - Method method = classMap.findMethod( methodName, CLASS_ARGS ); + Method method = classMap.findMethod(methodName, CLASS_ARGS); - if ( method == null ) - { + if (method == null) { // perhaps this is a boolean property?? methodName = "is" + methodBase; - method = classMap.findMethod( methodName, CLASS_ARGS ); + method = classMap.findMethod(methodName, CLASS_ARGS); } - if ( method == null ) - { + if (method == null) { return null; } - try - { - return method.invoke( value, OBJECT_ARGS ); - } - catch ( InvocationTargetException e ) - { + try { + return method.invoke(value, OBJECT_ARGS); + } catch (InvocationTargetException e) { throw e; } } - private static ClassMap getClassMap( Class clazz ) - { + private static ClassMap getClassMap(Class clazz) { - WeakReference softRef = classMaps.get( clazz ); + WeakReference softRef = classMaps.get(clazz); ClassMap classMap; - if ( softRef == null || ( classMap = softRef.get() ) == null ) - { - classMap = new ClassMap( clazz ); + if (softRef == null || (classMap = softRef.get()) == null) { + classMap = new ClassMap(clazz); - classMaps.put( clazz, new WeakReference( classMap ) ); + classMaps.put(clazz, new WeakReference(classMap)); } return classMap; diff --git a/src/main/java/org/codehaus/plexus/util/io/CachingOutputStream.java b/src/main/java/org/codehaus/plexus/util/io/CachingOutputStream.java index 4bea628a..4023b053 100644 --- a/src/main/java/org/codehaus/plexus/util/io/CachingOutputStream.java +++ b/src/main/java/org/codehaus/plexus/util/io/CachingOutputStream.java @@ -22,153 +22,124 @@ import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.FileTime; -import java.time.Instant; import java.util.Objects; /** * Caching OutputStream to avoid overwriting a file with * the same content. */ -public class CachingOutputStream extends OutputStream -{ +public class CachingOutputStream extends OutputStream { private final Path path; private FileChannel channel; private ByteBuffer readBuffer; private ByteBuffer writeBuffer; private boolean modified; - public CachingOutputStream( File path ) throws IOException - { - this( Objects.requireNonNull( path ).toPath() ); + public CachingOutputStream(File path) throws IOException { + this(Objects.requireNonNull(path).toPath()); } - public CachingOutputStream( Path path ) throws IOException - { - this( path, 32 * 1024 ); + public CachingOutputStream(Path path) throws IOException { + this(path, 32 * 1024); } - public CachingOutputStream( Path path, int bufferSize ) throws IOException - { - this.path = Objects.requireNonNull( path ); - this.channel = FileChannel.open( path, - StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE ); - this.readBuffer = ByteBuffer.allocate( bufferSize ); - this.writeBuffer = ByteBuffer.allocate( bufferSize ); + public CachingOutputStream(Path path, int bufferSize) throws IOException { + this.path = Objects.requireNonNull(path); + this.channel = + FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); + this.readBuffer = ByteBuffer.allocate(bufferSize); + this.writeBuffer = ByteBuffer.allocate(bufferSize); } @Override - public void write( int b ) throws IOException - { - if ( writeBuffer.remaining() < 1 ) - { - ( ( Buffer ) writeBuffer ).flip(); - flushBuffer( writeBuffer ); - ( ( Buffer ) writeBuffer ).clear(); + public void write(int b) throws IOException { + if (writeBuffer.remaining() < 1) { + ((Buffer) writeBuffer).flip(); + flushBuffer(writeBuffer); + ((Buffer) writeBuffer).clear(); } - writeBuffer.put( ( byte ) b ); + writeBuffer.put((byte) b); } @Override - public void write( byte[] b ) throws IOException - { - write( b, 0, b.length ); + public void write(byte[] b) throws IOException { + write(b, 0, b.length); } @Override - public void write( byte[] b, int off, int len ) throws IOException - { - if ( writeBuffer.remaining() < len ) - { - ( ( Buffer ) writeBuffer ).flip(); - flushBuffer( writeBuffer ); - ( ( Buffer ) writeBuffer ).clear(); + public void write(byte[] b, int off, int len) throws IOException { + if (writeBuffer.remaining() < len) { + ((Buffer) writeBuffer).flip(); + flushBuffer(writeBuffer); + ((Buffer) writeBuffer).clear(); } int capacity = writeBuffer.capacity(); - while ( len >= capacity ) - { - flushBuffer( ByteBuffer.wrap( b, off, capacity ) ); + while (len >= capacity) { + flushBuffer(ByteBuffer.wrap(b, off, capacity)); off += capacity; len -= capacity; } - if ( len > 0 ) - { - writeBuffer.put( b, off, len ); + if (len > 0) { + writeBuffer.put(b, off, len); } } @Override - public void flush() throws IOException - { - ( ( Buffer ) writeBuffer ).flip(); - flushBuffer( writeBuffer ); - ( ( Buffer ) writeBuffer ).clear(); + public void flush() throws IOException { + ((Buffer) writeBuffer).flip(); + flushBuffer(writeBuffer); + ((Buffer) writeBuffer).clear(); super.flush(); } - private void flushBuffer( ByteBuffer writeBuffer ) throws IOException - { - if ( modified ) - { - channel.write( writeBuffer ); - } - else - { + private void flushBuffer(ByteBuffer writeBuffer) throws IOException { + if (modified) { + channel.write(writeBuffer); + } else { int len = writeBuffer.remaining(); ByteBuffer readBuffer; - if ( this.readBuffer.capacity() >= len ) - { + if (this.readBuffer.capacity() >= len) { readBuffer = this.readBuffer; - ( ( Buffer ) readBuffer ).clear(); - readBuffer.limit( len ); - } - else - { - readBuffer = ByteBuffer.allocate( len ); + ((Buffer) readBuffer).clear(); + readBuffer.limit(len); + } else { + readBuffer = ByteBuffer.allocate(len); } - while ( len > 0 ) - { - int read = channel.read( readBuffer ); - if ( read <= 0 ) - { + while (len > 0) { + int read = channel.read(readBuffer); + if (read <= 0) { modified = true; - channel.position( channel.position() - readBuffer.position() ); - channel.write( writeBuffer ); + channel.position(channel.position() - readBuffer.position()); + channel.write(writeBuffer); return; } len -= read; } - ( ( Buffer ) readBuffer ).flip(); - if ( readBuffer.compareTo( writeBuffer ) != 0 ) - { + ((Buffer) readBuffer).flip(); + if (readBuffer.compareTo(writeBuffer) != 0) { modified = true; - channel.position( channel.position() - readBuffer.remaining() ); - channel.write( writeBuffer ); + channel.position(channel.position() - readBuffer.remaining()); + channel.write(writeBuffer); } } } @Override - public void close() throws IOException - { - if ( channel.isOpen() ) - { + public void close() throws IOException { + if (channel.isOpen()) { flush(); long position = channel.position(); - if ( position != channel.size() ) - { + if (position != channel.size()) { modified = true; - channel.truncate( position ); + channel.truncate(position); } channel.close(); } } - public boolean isModified() - { + public boolean isModified() { return modified; } } diff --git a/src/main/java/org/codehaus/plexus/util/io/CachingWriter.java b/src/main/java/org/codehaus/plexus/util/io/CachingWriter.java index 23cc4411..98698712 100644 --- a/src/main/java/org/codehaus/plexus/util/io/CachingWriter.java +++ b/src/main/java/org/codehaus/plexus/util/io/CachingWriter.java @@ -19,44 +19,35 @@ import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; -import java.io.StringWriter; import java.nio.charset.Charset; -import java.nio.file.Files; import java.nio.file.Path; -import java.util.Arrays; import java.util.Objects; /** * Caching Writer to avoid overwriting a file with * the same content. */ -public class CachingWriter extends OutputStreamWriter -{ +public class CachingWriter extends OutputStreamWriter { private final CachingOutputStream cos; - public CachingWriter( File path, Charset charset ) throws IOException - { - this( Objects.requireNonNull( path ).toPath(), charset ); + public CachingWriter(File path, Charset charset) throws IOException { + this(Objects.requireNonNull(path).toPath(), charset); } - public CachingWriter( Path path, Charset charset ) throws IOException - { - this( path, charset, 32 * 1024 ); + public CachingWriter(Path path, Charset charset) throws IOException { + this(path, charset, 32 * 1024); } - public CachingWriter( Path path, Charset charset, int bufferSize ) throws IOException - { - this( new CachingOutputStream( path, bufferSize ), charset ); + public CachingWriter(Path path, Charset charset, int bufferSize) throws IOException { + this(new CachingOutputStream(path, bufferSize), charset); } - private CachingWriter( CachingOutputStream outputStream, Charset charset ) throws IOException - { - super( outputStream, charset ); + private CachingWriter(CachingOutputStream outputStream, Charset charset) throws IOException { + super(outputStream, charset); this.cos = outputStream; } - public boolean isModified() - { + public boolean isModified() { return cos.isModified(); } } diff --git a/src/main/java/org/codehaus/plexus/util/io/InputStreamFacade.java b/src/main/java/org/codehaus/plexus/util/io/InputStreamFacade.java index bfa5c471..ff6112f0 100644 --- a/src/main/java/org/codehaus/plexus/util/io/InputStreamFacade.java +++ b/src/main/java/org/codehaus/plexus/util/io/InputStreamFacade.java @@ -23,13 +23,11 @@ * Interface of a wrapper for input streams. This facade is used by methods, which are being implemented for files, * URL's, or input streams. */ -public interface InputStreamFacade -{ +public interface InputStreamFacade { /** * The caller must assume, that this method may be invoked only once. * @return Retrieves the actual {@link InputStream}. * @throws IOException if io issue */ - InputStream getInputStream() - throws IOException; + InputStream getInputStream() throws IOException; } diff --git a/src/main/java/org/codehaus/plexus/util/io/RawInputStreamFacade.java b/src/main/java/org/codehaus/plexus/util/io/RawInputStreamFacade.java index e634b95f..02fac256 100644 --- a/src/main/java/org/codehaus/plexus/util/io/RawInputStreamFacade.java +++ b/src/main/java/org/codehaus/plexus/util/io/RawInputStreamFacade.java @@ -22,21 +22,16 @@ /** * Implementation of {@link InputStreamFacade} for raw input streams. */ -@SuppressWarnings( { "UnusedDeclaration" } ) -public class RawInputStreamFacade - implements InputStreamFacade -{ +@SuppressWarnings({"UnusedDeclaration"}) +public class RawInputStreamFacade implements InputStreamFacade { final InputStream stream; - public RawInputStreamFacade( InputStream stream ) - { + public RawInputStreamFacade(InputStream stream) { this.stream = stream; } @Override - public InputStream getInputStream() - throws IOException - { + public InputStream getInputStream() throws IOException { return stream; } } diff --git a/src/main/java/org/codehaus/plexus/util/io/URLInputStreamFacade.java b/src/main/java/org/codehaus/plexus/util/io/URLInputStreamFacade.java index da09b4c1..be5a67ed 100644 --- a/src/main/java/org/codehaus/plexus/util/io/URLInputStreamFacade.java +++ b/src/main/java/org/codehaus/plexus/util/io/URLInputStreamFacade.java @@ -23,20 +23,15 @@ /** * Implementation of {@link InputStreamFacade} for URL's. */ -public class URLInputStreamFacade - implements InputStreamFacade -{ +public class URLInputStreamFacade implements InputStreamFacade { private final URL url; - public URLInputStreamFacade( URL url ) - { + public URLInputStreamFacade(URL url) { this.url = url; } @Override - public InputStream getInputStream() - throws IOException - { + public InputStream getInputStream() throws IOException { return url.openStream(); } } diff --git a/src/main/java/org/codehaus/plexus/util/reflection/Reflector.java b/src/main/java/org/codehaus/plexus/util/reflection/Reflector.java index 4f3a9d84..df530ffb 100644 --- a/src/main/java/org/codehaus/plexus/util/reflection/Reflector.java +++ b/src/main/java/org/codehaus/plexus/util/reflection/Reflector.java @@ -20,7 +20,6 @@ import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; - import java.util.HashMap; import java.util.Map; @@ -30,19 +29,16 @@ * * @author John Casey */ -public final class Reflector -{ +public final class Reflector { private static final String CONSTRUCTOR_METHOD_NAME = "$$CONSTRUCTOR$$"; private static final String GET_INSTANCE_METHOD_NAME = "getInstance"; private Map>> classMaps = - new HashMap>>(); + new HashMap>>(); /** Ensure no instances of Reflector are created...this is a utility. */ - public Reflector() - { - } + public Reflector() {} /** * Create a new instance of a class, given the array of parameters... Uses constructor caching to find a constructor @@ -54,50 +50,41 @@ public Reflector() * @return The instantiated object * @throws ReflectorException In case anything goes wrong here... */ - @SuppressWarnings( { "UnusedDeclaration" } ) - public T newInstance( Class theClass, Object[] params ) - throws ReflectorException - { - if ( params == null ) - { + @SuppressWarnings({"UnusedDeclaration"}) + public T newInstance(Class theClass, Object[] params) throws ReflectorException { + if (params == null) { params = new Object[0]; } Class[] paramTypes = new Class[params.length]; - for ( int i = 0, len = params.length; i < len; i++ ) - { + for (int i = 0, len = params.length; i < len; i++) { paramTypes[i] = params[i].getClass(); } - try - { - Constructor con = getConstructor( theClass, paramTypes ); + try { + Constructor con = getConstructor(theClass, paramTypes); - if ( con == null ) - { + if (con == null) { StringBuilder buffer = new StringBuilder(); - buffer.append( "Constructor not found for class: " ); - buffer.append( theClass.getName() ); - buffer.append( " with specified or ancestor parameter classes: " ); + buffer.append("Constructor not found for class: "); + buffer.append(theClass.getName()); + buffer.append(" with specified or ancestor parameter classes: "); - for ( Class paramType : paramTypes ) - { - buffer.append( paramType.getName() ); - buffer.append( ',' ); + for (Class paramType : paramTypes) { + buffer.append(paramType.getName()); + buffer.append(','); } - buffer.setLength( buffer.length() - 1 ); + buffer.setLength(buffer.length() - 1); - throw new ReflectorException( buffer.toString() ); + throw new ReflectorException(buffer.toString()); } - return con.newInstance( params ); - } - catch ( InstantiationException | InvocationTargetException | IllegalAccessException ex ) - { - throw new ReflectorException( ex ); + return con.newInstance(params); + } catch (InstantiationException | InvocationTargetException | IllegalAccessException ex) { + throw new ReflectorException(ex); } } @@ -111,27 +98,21 @@ public T newInstance( Class theClass, Object[] params ) * @return The singleton object * @throws ReflectorException In case anything goes wrong here... */ - @SuppressWarnings( { "UnusedDeclaration" } ) - public T getSingleton( Class theClass, Object[] initParams ) - throws ReflectorException - { + @SuppressWarnings({"UnusedDeclaration"}) + public T getSingleton(Class theClass, Object[] initParams) throws ReflectorException { Class[] paramTypes = new Class[initParams.length]; - for ( int i = 0, len = initParams.length; i < len; i++ ) - { + for (int i = 0, len = initParams.length; i < len; i++) { paramTypes[i] = initParams[i].getClass(); } - try - { - Method method = getMethod( theClass, GET_INSTANCE_METHOD_NAME, paramTypes ); + try { + Method method = getMethod(theClass, GET_INSTANCE_METHOD_NAME, paramTypes); // noinspection unchecked - return (T) method.invoke( null, initParams ); - } - catch ( InvocationTargetException | IllegalAccessException ex ) - { - throw new ReflectorException( ex ); + return (T) method.invoke(null, initParams); + } catch (InvocationTargetException | IllegalAccessException ex) { + throw new ReflectorException(ex); } } @@ -144,113 +125,86 @@ public T getSingleton( Class theClass, Object[] initParams ) * @return The result of the method call * @throws ReflectorException In case of an error looking up or invoking the method. */ - @SuppressWarnings( { "UnusedDeclaration" } ) - public Object invoke( Object target, String methodName, Object[] params ) - throws ReflectorException - { - if ( params == null ) - { + @SuppressWarnings({"UnusedDeclaration"}) + public Object invoke(Object target, String methodName, Object[] params) throws ReflectorException { + if (params == null) { params = new Object[0]; } Class[] paramTypes = new Class[params.length]; - for ( int i = 0, len = params.length; i < len; i++ ) - { + for (int i = 0, len = params.length; i < len; i++) { paramTypes[i] = params[i].getClass(); } - try - { - Method method = getMethod( target.getClass(), methodName, paramTypes ); + try { + Method method = getMethod(target.getClass(), methodName, paramTypes); - if ( method == null ) - { + if (method == null) { StringBuilder buffer = new StringBuilder(); - buffer.append( "Singleton-producing method named '" ).append( methodName ).append( "' not found with specified parameter classes: " ); + buffer.append("Singleton-producing method named '") + .append(methodName) + .append("' not found with specified parameter classes: "); - for ( Class paramType : paramTypes ) - { - buffer.append( paramType.getName() ); - buffer.append( ',' ); + for (Class paramType : paramTypes) { + buffer.append(paramType.getName()); + buffer.append(','); } - buffer.setLength( buffer.length() - 1 ); + buffer.setLength(buffer.length() - 1); - throw new ReflectorException( buffer.toString() ); + throw new ReflectorException(buffer.toString()); } - return method.invoke( target, params ); - } - catch ( InvocationTargetException | IllegalAccessException ex ) - { - throw new ReflectorException( ex ); + return method.invoke(target, params); + } catch (InvocationTargetException | IllegalAccessException ex) { + throw new ReflectorException(ex); } } - @SuppressWarnings( { "UnusedDeclaration" } ) - public Object getStaticField( Class targetClass, String fieldName ) - throws ReflectorException - { - try - { - Field field = targetClass.getField( fieldName ); + @SuppressWarnings({"UnusedDeclaration"}) + public Object getStaticField(Class targetClass, String fieldName) throws ReflectorException { + try { + Field field = targetClass.getField(fieldName); - return field.get( null ); - } - catch ( SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e ) - { - throw new ReflectorException( e ); + return field.get(null); + } catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { + throw new ReflectorException(e); } } - @SuppressWarnings( { "UnusedDeclaration" } ) - public Object getField( Object target, String fieldName ) - throws ReflectorException - { - return getField( target, fieldName, false ); + @SuppressWarnings({"UnusedDeclaration"}) + public Object getField(Object target, String fieldName) throws ReflectorException { + return getField(target, fieldName, false); } - public Object getField( Object target, String fieldName, boolean breakAccessibility ) - throws ReflectorException - { + public Object getField(Object target, String fieldName, boolean breakAccessibility) throws ReflectorException { Class targetClass = target.getClass(); - while ( targetClass != null ) - { - try - { - Field field = targetClass.getDeclaredField( fieldName ); + while (targetClass != null) { + try { + Field field = targetClass.getDeclaredField(fieldName); boolean accessibilityBroken = false; - if ( !field.isAccessible() && breakAccessibility ) - { - field.setAccessible( true ); + if (!field.isAccessible() && breakAccessibility) { + field.setAccessible(true); accessibilityBroken = true; } - Object result = field.get( target ); + Object result = field.get(target); - if ( accessibilityBroken ) - { - field.setAccessible( false ); + if (accessibilityBroken) { + field.setAccessible(false); } return result; - } - catch ( SecurityException e ) - { - throw new ReflectorException( e ); - } - catch ( NoSuchFieldException e ) - { - if ( targetClass == Object.class ) - throw new ReflectorException( e ); + } catch (SecurityException e) { + throw new ReflectorException(e); + } catch (NoSuchFieldException e) { + if (targetClass == Object.class) throw new ReflectorException(e); targetClass = targetClass.getSuperclass(); - } - catch ( IllegalAccessException e ) - { - throw new ReflectorException( e ); + } catch (IllegalAccessException e) { + throw new ReflectorException(e); } } // Never reached, but needed to satisfy compiler @@ -266,48 +220,41 @@ public Object getField( Object target, String fieldName, boolean breakAccessibil * @return The result of the method call * @throws ReflectorException In case of an error looking up or invoking the method. */ - @SuppressWarnings( { "UnusedDeclaration" } ) - public Object invokeStatic( Class targetClass, String methodName, Object[] params ) - throws ReflectorException - { - if ( params == null ) - { + @SuppressWarnings({"UnusedDeclaration"}) + public Object invokeStatic(Class targetClass, String methodName, Object[] params) throws ReflectorException { + if (params == null) { params = new Object[0]; } Class[] paramTypes = new Class[params.length]; - for ( int i = 0, len = params.length; i < len; i++ ) - { + for (int i = 0, len = params.length; i < len; i++) { paramTypes[i] = params[i].getClass(); } - try - { - Method method = getMethod( targetClass, methodName, paramTypes ); + try { + Method method = getMethod(targetClass, methodName, paramTypes); - if ( method == null ) - { + if (method == null) { StringBuilder buffer = new StringBuilder(); - buffer.append( "Singleton-producing method named \'" ).append( methodName ).append( "\' not found with specified parameter classes: " ); + buffer.append("Singleton-producing method named \'") + .append(methodName) + .append("\' not found with specified parameter classes: "); - for ( Class paramType : paramTypes ) - { - buffer.append( paramType.getName() ); - buffer.append( ',' ); + for (Class paramType : paramTypes) { + buffer.append(paramType.getName()); + buffer.append(','); } - buffer.setLength( buffer.length() - 1 ); + buffer.setLength(buffer.length() - 1); - throw new ReflectorException( buffer.toString() ); + throw new ReflectorException(buffer.toString()); } - return method.invoke( null, params ); - } - catch ( InvocationTargetException | IllegalAccessException ex ) - { - throw new ReflectorException( ex ); + return method.invoke(null, params); + } catch (InvocationTargetException | IllegalAccessException ex) { + throw new ReflectorException(ex); } } @@ -320,142 +267,112 @@ public Object invokeStatic( Class targetClass, String methodName, Object[] param * @return the Constructor object that matches. * @throws ReflectorException In case we can't retrieve the proper constructor. */ - public Constructor getConstructor( Class targetClass, Class[] params ) - throws ReflectorException - { - Map> constructorMap = getConstructorMap( targetClass ); + public Constructor getConstructor(Class targetClass, Class[] params) throws ReflectorException { + Map> constructorMap = getConstructorMap(targetClass); - StringBuilder key = new StringBuilder( 200 ); + StringBuilder key = new StringBuilder(200); - key.append( "(" ); + key.append("("); - for ( Class param : params ) - { - key.append( param.getName() ); - key.append( "," ); + for (Class param : params) { + key.append(param.getName()); + key.append(","); } - if ( params.length > 0 ) - { - key.setLength( key.length() - 1 ); + if (params.length > 0) { + key.setLength(key.length() - 1); } - key.append( ")" ); + key.append(")"); Constructor constructor; String paramKey = key.toString(); - synchronized ( paramKey.intern() ) - { - constructor = constructorMap.get( paramKey ); + synchronized (paramKey.intern()) { + constructor = constructorMap.get(paramKey); - if ( constructor == null ) - { - @SuppressWarnings( { "unchecked" } ) + if (constructor == null) { + @SuppressWarnings({"unchecked"}) Constructor[] cands = (Constructor[]) targetClass.getConstructors(); - for ( Constructor cand : cands ) - { + for (Constructor cand : cands) { Class[] types = cand.getParameterTypes(); - if ( params.length != types.length ) - { + if (params.length != types.length) { continue; } - for ( int j = 0, len2 = params.length; j < len2; j++ ) - { - if ( !types[j].isAssignableFrom( params[j] ) ) - { + for (int j = 0, len2 = params.length; j < len2; j++) { + if (!types[j].isAssignableFrom(params[j])) { continue; } } // we got it, so store it! constructor = cand; - constructorMap.put( paramKey, constructor ); + constructorMap.put(paramKey, constructor); } } } - if ( constructor == null ) - { - throw new ReflectorException( "Error retrieving constructor object for: " + targetClass.getName() - + paramKey ); + if (constructor == null) { + throw new ReflectorException( + "Error retrieving constructor object for: " + targetClass.getName() + paramKey); } return constructor; } - public Object getObjectProperty( Object target, String propertyName ) - throws ReflectorException - { + public Object getObjectProperty(Object target, String propertyName) throws ReflectorException { Object returnValue; - if ( propertyName == null || propertyName.trim().length() < 1 ) - { - throw new ReflectorException( "Cannot retrieve value for empty property." ); + if (propertyName == null || propertyName.trim().length() < 1) { + throw new ReflectorException("Cannot retrieve value for empty property."); } - String beanAccessor = "get" + Character.toUpperCase( propertyName.charAt( 0 ) ); - if ( propertyName.trim().length() > 1 ) - { - beanAccessor += propertyName.substring( 1 ).trim(); + String beanAccessor = "get" + Character.toUpperCase(propertyName.charAt(0)); + if (propertyName.trim().length() > 1) { + beanAccessor += propertyName.substring(1).trim(); } Class targetClass = target.getClass(); Class[] emptyParams = {}; - Method method = _getMethod( targetClass, beanAccessor, emptyParams ); - if ( method == null ) - { - method = _getMethod( targetClass, propertyName, emptyParams ); - } - if ( method != null ) - { - try - { - returnValue = method.invoke( target, new Object[] {} ); - } - catch ( IllegalAccessException e ) - { - throw new ReflectorException( "Error retrieving property \'" + propertyName + "\' from \'" + targetClass - + "\'", e ); - } - catch ( InvocationTargetException e ) - { - throw new ReflectorException( "Error retrieving property \'" + propertyName + "\' from \'" + targetClass - + "\'", e ); + Method method = _getMethod(targetClass, beanAccessor, emptyParams); + if (method == null) { + method = _getMethod(targetClass, propertyName, emptyParams); + } + if (method != null) { + try { + returnValue = method.invoke(target, new Object[] {}); + } catch (IllegalAccessException e) { + throw new ReflectorException( + "Error retrieving property \'" + propertyName + "\' from \'" + targetClass + "\'", e); + } catch (InvocationTargetException e) { + throw new ReflectorException( + "Error retrieving property \'" + propertyName + "\' from \'" + targetClass + "\'", e); } } - if ( method != null ) - { - try - { - returnValue = method.invoke( target, new Object[] {} ); - } - catch ( IllegalAccessException e ) - { - throw new ReflectorException( "Error retrieving property \'" + propertyName + "\' from \'" + targetClass - + "\'", e ); + if (method != null) { + try { + returnValue = method.invoke(target, new Object[] {}); + } catch (IllegalAccessException e) { + throw new ReflectorException( + "Error retrieving property \'" + propertyName + "\' from \'" + targetClass + "\'", e); + } catch (InvocationTargetException e) { + throw new ReflectorException( + "Error retrieving property \'" + propertyName + "\' from \'" + targetClass + "\'", e); } - catch ( InvocationTargetException e ) - { - throw new ReflectorException( "Error retrieving property \'" + propertyName + "\' from \'" + targetClass - + "\'", e ); - } - } - else - { - returnValue = getField( target, propertyName, true ); - if ( returnValue == null ) - { + } else { + returnValue = getField(target, propertyName, true); + if (returnValue == null) { // TODO: Check if exception is the right action! Field exists, but contains null - throw new ReflectorException( "Neither method: \'" + propertyName + "\' nor bean accessor: \'" - + beanAccessor + "\' can be found for class: \'" + targetClass + "\', and retrieval of field: \'" - + propertyName + "\' returned null as value." ); + throw new ReflectorException("Neither method: \'" + propertyName + "\' nor bean accessor: \'" + + beanAccessor + "\' can be found for class: \'" + targetClass + + "\', and retrieval of field: \'" + + propertyName + "\' returned null as value."); } } @@ -471,76 +388,62 @@ public Object getObjectProperty( Object target, String propertyName ) * @return the Method object that matches. * @throws ReflectorException In case we can't retrieve the proper method. */ - public Method getMethod( Class targetClass, String methodName, Class[] params ) - throws ReflectorException - { - Method method = _getMethod( targetClass, methodName, params ); - - if ( method == null ) - { - throw new ReflectorException( "Method: \'" + methodName + "\' not found in class: \'" + targetClass - + "\'" ); + public Method getMethod(Class targetClass, String methodName, Class[] params) throws ReflectorException { + Method method = _getMethod(targetClass, methodName, params); + + if (method == null) { + throw new ReflectorException("Method: \'" + methodName + "\' not found in class: \'" + targetClass + "\'"); } return method; } - private Method _getMethod( Class targetClass, String methodName, Class[] params ) - throws ReflectorException - { - Map methodMap = (Map) getMethodMap( targetClass, methodName ); + private Method _getMethod(Class targetClass, String methodName, Class[] params) throws ReflectorException { + Map methodMap = (Map) getMethodMap(targetClass, methodName); - StringBuilder key = new StringBuilder( 200 ); + StringBuilder key = new StringBuilder(200); - key.append( "(" ); + key.append("("); - for ( Class param : params ) - { - key.append( param.getName() ); - key.append( "," ); + for (Class param : params) { + key.append(param.getName()); + key.append(","); } - key.append( ")" ); + key.append(")"); Method method; String paramKey = key.toString(); - synchronized ( paramKey.intern() ) - { - method = methodMap.get( paramKey ); + synchronized (paramKey.intern()) { + method = methodMap.get(paramKey); - if ( method == null ) - { + if (method == null) { Method[] cands = targetClass.getMethods(); - for ( Method cand : cands ) - { + for (Method cand : cands) { String name = cand.getName(); - if ( !methodName.equals( name ) ) - { + if (!methodName.equals(name)) { continue; } Class[] types = cand.getParameterTypes(); - if ( params.length != types.length ) - { + if (params.length != types.length) { continue; } - for ( int j = 0, len2 = params.length; j < len2; j++ ) - { - if ( !types[j].isAssignableFrom( params[j] ) ) - { + for (int j = 0, len2 = params.length; j < len2; j++) { + if (!types[j].isAssignableFrom(params[j])) { continue; } } // we got it, so store it! method = cand; - methodMap.put( paramKey, method ); + methodMap.put(paramKey, method); } } } @@ -555,10 +458,8 @@ private Method _getMethod( Class targetClass, String methodName, Class[] params * @return The cache of constructors. * @throws ReflectorException in case of a lookup error. */ - private Map> getConstructorMap( Class theClass ) - throws ReflectorException - { - return (Map>) getMethodMap( theClass, CONSTRUCTOR_METHOD_NAME ); + private Map> getConstructorMap(Class theClass) throws ReflectorException { + return (Map>) getMethodMap(theClass, CONSTRUCTOR_METHOD_NAME); } /** @@ -569,41 +470,32 @@ private Map> getConstructorMap( Class theClass ) * @return The cache of constructors. * @throws ReflectorException in case of a lookup error. */ - private Map getMethodMap( Class theClass, String methodName ) - throws ReflectorException - { + private Map getMethodMap(Class theClass, String methodName) throws ReflectorException { Map methodMap; - if ( theClass == null ) - { + if (theClass == null) { return null; } String className = theClass.getName(); - synchronized ( className.intern() ) - { - Map> classMethods = classMaps.get( className ); + synchronized (className.intern()) { + Map> classMethods = classMaps.get(className); - if ( classMethods == null ) - { + if (classMethods == null) { classMethods = new HashMap<>(); methodMap = new HashMap<>(); - classMethods.put( methodName, methodMap ); - classMaps.put( className, classMethods ); - } - else - { + classMethods.put(methodName, methodMap); + classMaps.put(className, classMethods); + } else { String key = className + "::" + methodName; - synchronized ( key.intern() ) - { - methodMap = classMethods.get( methodName ); + synchronized (key.intern()) { + methodMap = classMethods.get(methodName); - if ( methodMap == null ) - { + if (methodMap == null) { methodMap = new HashMap<>(); - classMethods.put( methodName, methodMap ); + classMethods.put(methodName, methodMap); } } } diff --git a/src/main/java/org/codehaus/plexus/util/reflection/ReflectorException.java b/src/main/java/org/codehaus/plexus/util/reflection/ReflectorException.java index 01952f7b..4608e175 100644 --- a/src/main/java/org/codehaus/plexus/util/reflection/ReflectorException.java +++ b/src/main/java/org/codehaus/plexus/util/reflection/ReflectorException.java @@ -22,22 +22,17 @@ * * @author John Casey */ -public class ReflectorException - extends Exception -{ - @SuppressWarnings( { "UnusedDeclaration" } ) - public ReflectorException() - { - } +public class ReflectorException extends Exception { + @SuppressWarnings({"UnusedDeclaration"}) + public ReflectorException() {} /** * Create a new ReflectorException with the specified message. * * @param msg The message. */ - public ReflectorException( String msg ) - { - super( msg ); + public ReflectorException(String msg) { + super(msg); } /** @@ -45,9 +40,8 @@ public ReflectorException( String msg ) * * @param root The root cause. */ - public ReflectorException( Throwable root ) - { - super( root ); + public ReflectorException(Throwable root) { + super(root); } /** @@ -56,8 +50,7 @@ public ReflectorException( Throwable root ) * @param msg The message. * @param root The root cause. */ - public ReflectorException( String msg, Throwable root ) - { - super( msg, root ); + public ReflectorException(String msg, Throwable root) { + super(msg, root); } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/util/xml/CompactXMLWriter.java b/src/main/java/org/codehaus/plexus/util/xml/CompactXMLWriter.java index 85835210..d7ceaa05 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/CompactXMLWriter.java +++ b/src/main/java/org/codehaus/plexus/util/xml/CompactXMLWriter.java @@ -22,23 +22,18 @@ /** * */ -public class CompactXMLWriter - extends PrettyPrintXMLWriter -{ +public class CompactXMLWriter extends PrettyPrintXMLWriter { - public CompactXMLWriter( PrintWriter writer ) - { - super( writer ); + public CompactXMLWriter(PrintWriter writer) { + super(writer); } - public CompactXMLWriter( Writer writer ) - { - super( writer ); + public CompactXMLWriter(Writer writer) { + super(writer); } @Override - protected void endOfLine() - { + protected void endOfLine() { // override parent: don't write anything at end of line } } diff --git a/src/main/java/org/codehaus/plexus/util/xml/PrettyPrintXMLWriter.java b/src/main/java/org/codehaus/plexus/util/xml/PrettyPrintXMLWriter.java index c4387317..9fa36413 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/PrettyPrintXMLWriter.java +++ b/src/main/java/org/codehaus/plexus/util/xml/PrettyPrintXMLWriter.java @@ -29,11 +29,9 @@ * * */ -public class PrettyPrintXMLWriter - implements XMLWriter -{ +public class PrettyPrintXMLWriter implements XMLWriter { /** Line separator ("\n" on UNIX) */ - protected static final String LS = System.getProperty( "line.separator" ); + protected static final String LS = System.getProperty("line.separator"); private PrintWriter writer; @@ -59,34 +57,30 @@ public class PrettyPrintXMLWriter * @param writer not null * @param lineIndenter could be null, but the normal way is some spaces. */ - public PrettyPrintXMLWriter( PrintWriter writer, String lineIndenter ) - { - this( writer, lineIndenter, null, null ); + public PrettyPrintXMLWriter(PrintWriter writer, String lineIndenter) { + this(writer, lineIndenter, null, null); } /** * @param writer not null * @param lineIndenter could be null, but the normal way is some spaces. */ - public PrettyPrintXMLWriter( Writer writer, String lineIndenter ) - { - this( new PrintWriter( writer ), lineIndenter ); + public PrettyPrintXMLWriter(Writer writer, String lineIndenter) { + this(new PrintWriter(writer), lineIndenter); } /** * @param writer not null */ - public PrettyPrintXMLWriter( PrintWriter writer ) - { - this( writer, null, null ); + public PrettyPrintXMLWriter(PrintWriter writer) { + this(writer, null, null); } /** * @param writer not null */ - public PrettyPrintXMLWriter( Writer writer ) - { - this( new PrintWriter( writer ) ); + public PrettyPrintXMLWriter(Writer writer) { + this(new PrintWriter(writer)); } /** @@ -95,9 +89,8 @@ public PrettyPrintXMLWriter( Writer writer ) * @param encoding could be null or invalid. * @param doctype could be null. */ - public PrettyPrintXMLWriter( PrintWriter writer, String lineIndenter, String encoding, String doctype ) - { - this( writer, lineIndenter, LS, encoding, doctype ); + public PrettyPrintXMLWriter(PrintWriter writer, String lineIndenter, String encoding, String doctype) { + this(writer, lineIndenter, LS, encoding, doctype); } /** @@ -106,9 +99,8 @@ public PrettyPrintXMLWriter( PrintWriter writer, String lineIndenter, String enc * @param encoding could be null or invalid. * @param doctype could be null. */ - public PrettyPrintXMLWriter( Writer writer, String lineIndenter, String encoding, String doctype ) - { - this( new PrintWriter( writer ), lineIndenter, encoding, doctype ); + public PrettyPrintXMLWriter(Writer writer, String lineIndenter, String encoding, String doctype) { + this(new PrintWriter(writer), lineIndenter, encoding, doctype); } /** @@ -116,9 +108,8 @@ public PrettyPrintXMLWriter( Writer writer, String lineIndenter, String encoding * @param encoding could be null or invalid. * @param doctype could be null. */ - public PrettyPrintXMLWriter( PrintWriter writer, String encoding, String doctype ) - { - this( writer, " ", encoding, doctype ); + public PrettyPrintXMLWriter(PrintWriter writer, String encoding, String doctype) { + this(writer, " ", encoding, doctype); } /** @@ -126,9 +117,8 @@ public PrettyPrintXMLWriter( PrintWriter writer, String encoding, String doctype * @param encoding could be null or invalid. * @param doctype could be null. */ - public PrettyPrintXMLWriter( Writer writer, String encoding, String doctype ) - { - this( new PrintWriter( writer ), encoding, doctype ); + public PrettyPrintXMLWriter(Writer writer, String encoding, String doctype) { + this(new PrintWriter(writer), encoding, doctype); } /** @@ -138,42 +128,39 @@ public PrettyPrintXMLWriter( Writer writer, String encoding, String doctype ) * @param encoding could be null or invalid. * @param doctype could be null. */ - public PrettyPrintXMLWriter( PrintWriter writer, String lineIndenter, String lineSeparator, String encoding, - String doctype ) - { - setWriter( writer ); + public PrettyPrintXMLWriter( + PrintWriter writer, String lineIndenter, String lineSeparator, String encoding, String doctype) { + setWriter(writer); - setLineIndenter( lineIndenter ); + setLineIndenter(lineIndenter); - setLineSeparator( lineSeparator ); + setLineSeparator(lineSeparator); - setEncoding( encoding ); + setEncoding(encoding); - setDocType( doctype ); + setDocType(doctype); - if ( doctype != null || encoding != null ) - { + if (doctype != null || encoding != null) { writeDocumentHeaders(); } } /** {@inheritDoc} */ @Override - public void startElement( String name ) - { + public void startElement(String name) { tagIsEmpty = false; finishTag(); - write( "<" ); + write("<"); - write( name ); + write(name); - elementStack.addLast( name ); + elementStack.addLast(name); tagInProgress = true; - setDepth( getDepth() + 1 ); + setDepth(getDepth() + 1); readyForNewLine = true; @@ -182,65 +169,55 @@ public void startElement( String name ) /** {@inheritDoc} */ @Override - public void writeText( String text ) - { - writeText( text, true ); + public void writeText(String text) { + writeText(text, true); } /** {@inheritDoc} */ @Override - public void writeMarkup( String text ) - { - writeText( text, false ); + public void writeMarkup(String text) { + writeText(text, false); } - private void writeText( String text, boolean escapeXml ) - { + private void writeText(String text, boolean escapeXml) { readyForNewLine = false; tagIsEmpty = false; finishTag(); - if ( escapeXml ) - { - text = escapeXml( text ); + if (escapeXml) { + text = escapeXml(text); } - write( StringUtils.unifyLineSeparators( text, lineSeparator ) ); + write(StringUtils.unifyLineSeparators(text, lineSeparator)); } - private static final Pattern amp = Pattern.compile( "&" ); + private static final Pattern amp = Pattern.compile("&"); - private static final Pattern lt = Pattern.compile( "<" ); + private static final Pattern lt = Pattern.compile("<"); - private static final Pattern gt = Pattern.compile( ">" ); + private static final Pattern gt = Pattern.compile(">"); - private static final Pattern dqoute = Pattern.compile( "\"" ); + private static final Pattern dqoute = Pattern.compile("\""); - private static final Pattern sqoute = Pattern.compile( "\'" ); + private static final Pattern sqoute = Pattern.compile("\'"); - private static String escapeXml( String text ) - { - if ( text.indexOf( '&' ) >= 0 ) - { - text = amp.matcher( text ).replaceAll( "&" ); + private static String escapeXml(String text) { + if (text.indexOf('&') >= 0) { + text = amp.matcher(text).replaceAll("&"); } - if ( text.indexOf( '<' ) >= 0 ) - { - text = lt.matcher( text ).replaceAll( "<" ); + if (text.indexOf('<') >= 0) { + text = lt.matcher(text).replaceAll("<"); } - if ( text.indexOf( '>' ) >= 0 ) - { - text = gt.matcher( text ).replaceAll( ">" ); + if (text.indexOf('>') >= 0) { + text = gt.matcher(text).replaceAll(">"); } - if ( text.indexOf( '"' ) >= 0 ) - { - text = dqoute.matcher( text ).replaceAll( """ ); + if (text.indexOf('"') >= 0) { + text = dqoute.matcher(text).replaceAll("""); } - if ( text.indexOf( '\'' ) >= 0 ) - { - text = sqoute.matcher( text ).replaceAll( "'" ); + if (text.indexOf('\'') >= 0) { + text = sqoute.matcher(text).replaceAll("'"); } return text; @@ -248,65 +225,57 @@ private static String escapeXml( String text ) private static final String crlf_str = "\r\n"; - private static final Pattern crlf = Pattern.compile( crlf_str ); + private static final Pattern crlf = Pattern.compile(crlf_str); - private static final Pattern lowers = Pattern.compile( "([\000-\037])" ); + private static final Pattern lowers = Pattern.compile("([\000-\037])"); - private static String escapeXmlAttribute( String text ) - { - text = escapeXml( text ); + private static String escapeXmlAttribute(String text) { + text = escapeXml(text); // Windows - Matcher crlfmatcher = crlf.matcher( text ); - if ( text.contains( crlf_str ) ) - { - text = crlfmatcher.replaceAll( " " ); + Matcher crlfmatcher = crlf.matcher(text); + if (text.contains(crlf_str)) { + text = crlfmatcher.replaceAll(" "); } - Matcher m = lowers.matcher( text ); + Matcher m = lowers.matcher(text); StringBuffer b = new StringBuffer(); - while ( m.find() ) - { - m = m.appendReplacement( b, "&#" + Integer.toString( m.group( 1 ).charAt( 0 ) ) + ";" ); + while (m.find()) { + m = m.appendReplacement(b, "&#" + Integer.toString(m.group(1).charAt(0)) + ";"); } - m.appendTail( b ); + m.appendTail(b); return b.toString(); } /** {@inheritDoc} */ @Override - public void addAttribute( String key, String value ) - { - write( " " ); + public void addAttribute(String key, String value) { + write(" "); - write( key ); + write(key); - write( "=\"" ); + write("=\""); - write( escapeXmlAttribute( value ) ); + write(escapeXmlAttribute(value)); - write( "\"" ); + write("\""); } /** {@inheritDoc} */ @Override - public void endElement() - { - setDepth( getDepth() - 1 ); + public void endElement() { + setDepth(getDepth() - 1); - if ( tagIsEmpty ) - { - write( "/" ); + if (tagIsEmpty) { + write("/"); readyForNewLine = false; finishTag(); elementStack.removeLast(); - } - else - { + } else { finishTag(); // see issue #51: https://github.com/codehaus-plexus/plexus-utils/issues/51 @@ -314,9 +283,9 @@ public void endElement() // (this avoids the string concatenation optimization bug detected in Java 7) // TODO: change the below code to a more efficient expression when the library // be ready to target Java 8. - write( "" ); + write(""); } readyForNewLine = true; @@ -324,25 +293,21 @@ public void endElement() /** * Write a string to the underlying writer - * + * * @param str */ - private void write( String str ) - { - getWriter().write( str ); + private void write(String str) { + getWriter().write(str); } - private void finishTag() - { - if ( tagInProgress ) - { - write( ">" ); + private void finishTag() { + if (tagInProgress) { + write(">"); } tagInProgress = false; - if ( readyForNewLine ) - { + if (readyForNewLine) { endOfLine(); } readyForNewLine = false; @@ -355,8 +320,7 @@ private void finishTag() * * @return the line indenter */ - protected String getLineIndenter() - { + protected String getLineIndenter() { return lineIndenter; } @@ -365,8 +329,7 @@ protected String getLineIndenter() * * @param lineIndenter new line indenter, could be null, but the normal way is some spaces. */ - protected void setLineIndenter( String lineIndenter ) - { + protected void setLineIndenter(String lineIndenter) { this.lineIndenter = lineIndenter; } @@ -376,8 +339,7 @@ protected void setLineIndenter( String lineIndenter ) * @return the line separator * @see #LS */ - protected String getLineSeparator() - { + protected String getLineSeparator() { return lineSeparator; } @@ -386,8 +348,7 @@ protected String getLineSeparator() * * @param lineSeparator new line separator, could be null but the normal way is valid line separator ("\n" on UNIX). */ - protected void setLineSeparator( String lineSeparator ) - { + protected void setLineSeparator(String lineSeparator) { this.lineSeparator = lineSeparator; } @@ -397,36 +358,31 @@ protected void setLineSeparator( String lineSeparator ) * @see #getLineIndenter() * @see #getLineSeparator() */ - protected void endOfLine() - { - write( getLineSeparator() ); + protected void endOfLine() { + write(getLineSeparator()); - for ( int i = 0; i < getDepth(); i++ ) - { - write( getLineIndenter() ); + for (int i = 0; i < getDepth(); i++) { + write(getLineIndenter()); } } - private void writeDocumentHeaders() - { - write( "" ); + write("?>"); endOfLine(); - if ( getDocType() != null ) - { - write( "" ); + write(">"); endOfLine(); } @@ -437,11 +393,9 @@ private void writeDocumentHeaders() * * @param writer not null writer */ - protected void setWriter( PrintWriter writer ) - { - if ( writer == null ) - { - throw new IllegalArgumentException( "writer could not be null" ); + protected void setWriter(PrintWriter writer) { + if (writer == null) { + throw new IllegalArgumentException("writer could not be null"); } this.writer = writer; @@ -452,8 +406,7 @@ protected void setWriter( PrintWriter writer ) * * @return the underlying writer */ - protected PrintWriter getWriter() - { + protected PrintWriter getWriter() { return writer; } @@ -462,8 +415,7 @@ protected PrintWriter getWriter() * * @param depth new depth */ - protected void setDepth( int depth ) - { + protected void setDepth(int depth) { this.depth = depth; } @@ -472,8 +424,7 @@ protected void setDepth( int depth ) * * @return the current depth */ - protected int getDepth() - { + protected int getDepth() { return depth; } @@ -482,8 +433,7 @@ protected int getDepth() * * @param encoding new encoding */ - protected void setEncoding( String encoding ) - { + protected void setEncoding(String encoding) { this.encoding = encoding; } @@ -492,8 +442,7 @@ protected void setEncoding( String encoding ) * * @return the current encoding */ - protected String getEncoding() - { + protected String getEncoding() { return encoding; } @@ -502,8 +451,7 @@ protected String getEncoding() * * @param docType new docType */ - protected void setDocType( String docType ) - { + protected void setDocType(String docType) { this.docType = docType; } @@ -512,16 +460,14 @@ protected void setDocType( String docType ) * * @return the current docType */ - protected String getDocType() - { + protected String getDocType() { return docType; } /** * @return the current elementStack; */ - protected LinkedList getElementStack() - { + protected LinkedList getElementStack() { return elementStack; } } diff --git a/src/main/java/org/codehaus/plexus/util/xml/SerializerXMLWriter.java b/src/main/java/org/codehaus/plexus/util/xml/SerializerXMLWriter.java index 488103d4..6309b165 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/SerializerXMLWriter.java +++ b/src/main/java/org/codehaus/plexus/util/xml/SerializerXMLWriter.java @@ -16,23 +16,21 @@ * limitations under the License. */ -import org.codehaus.plexus.util.xml.pull.XmlSerializer; - import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Stack; +import org.codehaus.plexus.util.xml.pull.XmlSerializer; + /** * Write to an MXSerializer. * * @author Brett Porter * */ -public class SerializerXMLWriter - implements XMLWriter -{ +public class SerializerXMLWriter implements XMLWriter { private final XmlSerializer serializer; private final String namespace; @@ -41,93 +39,68 @@ public class SerializerXMLWriter private List exceptions; - public SerializerXMLWriter( String namespace, XmlSerializer serializer ) - { + public SerializerXMLWriter(String namespace, XmlSerializer serializer) { this.serializer = serializer; this.namespace = namespace; } @Override - public void startElement( String name ) - { - try - { - serializer.startTag( namespace, name ); - elements.push( name ); - } - catch ( IOException e ) - { - storeException( e ); + public void startElement(String name) { + try { + serializer.startTag(namespace, name); + elements.push(name); + } catch (IOException e) { + storeException(e); } } @Override - public void addAttribute( String key, String value ) - { - try - { - serializer.attribute( namespace, key, value ); - } - catch ( IOException e ) - { - storeException( e ); + public void addAttribute(String key, String value) { + try { + serializer.attribute(namespace, key, value); + } catch (IOException e) { + storeException(e); } } @Override - public void writeText( String text ) - { - try - { - serializer.text( text ); - } - catch ( IOException e ) - { - storeException( e ); + public void writeText(String text) { + try { + serializer.text(text); + } catch (IOException e) { + storeException(e); } } @Override - public void writeMarkup( String text ) - { - try - { - serializer.cdsect( text ); - } - catch ( IOException e ) - { - storeException( e ); + public void writeMarkup(String text) { + try { + serializer.cdsect(text); + } catch (IOException e) { + storeException(e); } } @Override - public void endElement() - { - try - { - serializer.endTag( namespace, elements.pop() ); - } - catch ( IOException e ) - { - storeException( e ); + public void endElement() { + try { + serializer.endTag(namespace, elements.pop()); + } catch (IOException e) { + storeException(e); } } /** * @todo Maybe the interface should allow IOExceptions on each? */ - private void storeException( IOException e ) - { - if ( exceptions == null ) - { + private void storeException(IOException e) { + if (exceptions == null) { exceptions = new ArrayList(); } - exceptions.add( e ); + exceptions.add(e); } - public List getExceptions() - { + public List getExceptions() { return exceptions == null ? Collections.emptyList() : exceptions; } - } diff --git a/src/main/java/org/codehaus/plexus/util/xml/XMLWriter.java b/src/main/java/org/codehaus/plexus/util/xml/XMLWriter.java index 364849ba..c8bcbc2b 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/XMLWriter.java +++ b/src/main/java/org/codehaus/plexus/util/xml/XMLWriter.java @@ -19,16 +19,14 @@ /** * */ -public interface XMLWriter -{ - void startElement( String name ); +public interface XMLWriter { + void startElement(String name); - void addAttribute( String key, String value ); + void addAttribute(String key, String value); - void writeText( String text ); + void writeText(String text); - void writeMarkup( String text ); + void writeMarkup(String text); void endElement(); - } 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 e7c7cc47..71fba5dd 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/XmlReader.java +++ b/src/main/java/org/codehaus/plexus/util/xml/XmlReader.java @@ -24,28 +24,28 @@ import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; +import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; -import java.net.HttpURLConnection; +import java.text.MessageFormat; import java.util.Locale; -import java.util.regex.Pattern; import java.util.regex.Matcher; -import java.text.MessageFormat; +import java.util.regex.Pattern; /** *

      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 * (following HTTP MIME and XML specifications). All this is nicely explained by Mark Pilgrim in his blog, * Determining the character encoding of a @@ -58,9 +58,7 @@ * @since 1.4.3 */ @Deprecated -public class XmlReader - extends Reader -{ +public class XmlReader extends Reader { private static final int BUFFER_SIZE = 4096; private static final String UTF_8 = "UTF-8"; @@ -86,28 +84,26 @@ public class XmlReader /** *

      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. */ - public static void setDefaultEncoding( String encoding ) - { + public static void setDefaultEncoding(String encoding) { _staticDefaultEncoding = 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.

      * * @return the default encoding to use. */ - public static String getDefaultEncoding() - { + public static String getDefaultEncoding() { return _staticDefaultEncoding; } @@ -123,10 +119,8 @@ public static String getDefaultEncoding() * @param file File to create a Reader from. * @throws IOException thrown if there is a problem reading the file. */ - public XmlReader( File file ) - throws IOException - { - this( Files.newInputStream( file.toPath() ) ); + public XmlReader(File file) throws IOException { + this(Files.newInputStream(file.toPath())); } /** @@ -140,10 +134,8 @@ public XmlReader( File file ) * @param is InputStream to create a Reader from. * @throws IOException thrown if there is a problem reading the stream. */ - public XmlReader( InputStream is ) - throws IOException - { - this( is, true ); + public XmlReader(InputStream is) throws IOException { + this(is, true); } /** @@ -170,23 +162,15 @@ public XmlReader( InputStream is ) * @throws IOException thrown if there is a problem reading the stream. * @throws XmlStreamReaderException thrown if the charset encoding could not be determined according to the specs. */ - public XmlReader( InputStream is, boolean lenient ) - throws IOException, XmlStreamReaderException - { + public XmlReader(InputStream is, boolean lenient) throws IOException, XmlStreamReaderException { _defaultEncoding = _staticDefaultEncoding; - try - { - doRawStream( is, lenient ); - } - catch ( XmlStreamReaderException ex ) - { - if ( !lenient ) - { + try { + doRawStream(is, lenient); + } catch (XmlStreamReaderException ex) { + if (!lenient) { throw ex; - } - else - { - doLenientDetection( null, ex ); + } else { + doLenientDetection(null, ex); } } } @@ -206,10 +190,8 @@ public XmlReader( InputStream is, boolean lenient ) * @param url URL to create a Reader from. * @throws IOException thrown if there is a problem reading the stream of the URL. */ - public XmlReader( URL url ) - throws IOException - { - this( url.openConnection() ); + public XmlReader(URL url) throws IOException { + this(url.openConnection()); } /** @@ -227,42 +209,26 @@ public XmlReader( URL url ) * @param conn URLConnection to create a Reader from. * @throws IOException thrown if there is a problem reading the stream of the URLConnection. */ - public XmlReader( URLConnection conn ) - throws IOException - { + public XmlReader(URLConnection conn) throws IOException { _defaultEncoding = _staticDefaultEncoding; boolean lenient = true; - if ( conn instanceof HttpURLConnection ) - { - try - { - doHttpStream( conn.getInputStream(), conn.getContentType(), lenient ); - } - catch ( XmlStreamReaderException ex ) - { - doLenientDetection( conn.getContentType(), ex ); + if (conn instanceof HttpURLConnection) { + try { + doHttpStream(conn.getInputStream(), conn.getContentType(), lenient); + } catch (XmlStreamReaderException ex) { + doLenientDetection(conn.getContentType(), ex); } - } - else if ( conn.getContentType() != null ) - { - try - { - doHttpStream( conn.getInputStream(), conn.getContentType(), lenient ); + } else if (conn.getContentType() != null) { + try { + doHttpStream(conn.getInputStream(), conn.getContentType(), lenient); + } catch (XmlStreamReaderException ex) { + doLenientDetection(conn.getContentType(), ex); } - catch ( XmlStreamReaderException ex ) - { - doLenientDetection( conn.getContentType(), ex ); - } - } - else - { - try - { - doRawStream( conn.getInputStream(), lenient ); - } - catch ( XmlStreamReaderException ex ) - { - doLenientDetection( null, ex ); + } else { + try { + doRawStream(conn.getInputStream(), lenient); + } catch (XmlStreamReaderException ex) { + doLenientDetection(null, ex); } } } @@ -281,10 +247,8 @@ else if ( conn.getContentType() != null ) * @param httpContentType content-type header to use for the resolution of the charset encoding. * @throws IOException thrown if there is a problem reading the file. */ - public XmlReader( InputStream is, String httpContentType ) - throws IOException - { - this( is, httpContentType, true ); + public XmlReader(InputStream is, String httpContentType) throws IOException { + this(is, httpContentType, true); } /** @@ -316,23 +280,16 @@ public XmlReader( InputStream is, String httpContentType ) * @throws IOException thrown if there is a problem reading the file. * @throws XmlStreamReaderException thrown if the charset encoding could not be determined according to the specs. */ - public XmlReader( InputStream is, String httpContentType, boolean lenient, String defaultEncoding ) - throws IOException, XmlStreamReaderException - { - _defaultEncoding = ( defaultEncoding == null ) ? _staticDefaultEncoding : defaultEncoding; - try - { - doHttpStream( is, httpContentType, lenient ); - } - catch ( XmlStreamReaderException ex ) - { - if ( !lenient ) - { + public XmlReader(InputStream is, String httpContentType, boolean lenient, String defaultEncoding) + throws IOException, XmlStreamReaderException { + _defaultEncoding = (defaultEncoding == null) ? _staticDefaultEncoding : defaultEncoding; + try { + doHttpStream(is, httpContentType, lenient); + } catch (XmlStreamReaderException ex) { + if (!lenient) { throw ex; - } - else - { - doLenientDetection( httpContentType, ex ); + } else { + doLenientDetection(httpContentType, ex); } } } @@ -365,44 +322,33 @@ public XmlReader( InputStream is, String httpContentType, boolean lenient, Strin * @throws IOException thrown if there is a problem reading the file. * @throws XmlStreamReaderException thrown if the charset encoding could not be determined according to the specs. */ - public XmlReader( InputStream is, String httpContentType, boolean lenient ) - throws IOException, XmlStreamReaderException - { - this( is, httpContentType, lenient, null ); + public XmlReader(InputStream is, String httpContentType, boolean lenient) + throws IOException, XmlStreamReaderException { + this(is, httpContentType, lenient, null); } - private void doLenientDetection( String httpContentType, XmlStreamReaderException ex ) - throws IOException - { - if ( httpContentType != null ) - { - if ( httpContentType.startsWith( "text/html" ) ) - { - httpContentType = httpContentType.substring( "text/html".length() ); + private void doLenientDetection(String httpContentType, XmlStreamReaderException ex) throws IOException { + if (httpContentType != null) { + if (httpContentType.startsWith("text/html")) { + httpContentType = httpContentType.substring("text/html".length()); httpContentType = "text/xml" + httpContentType; - try - { - doHttpStream( ex.getInputStream(), httpContentType, true ); + try { + doHttpStream(ex.getInputStream(), httpContentType, true); ex = null; - } - catch ( XmlStreamReaderException ex2 ) - { + } catch (XmlStreamReaderException ex2) { ex = ex2; } } } - if ( ex != null ) - { + if (ex != null) { String encoding = ex.getXmlEncoding(); - if ( encoding == null ) - { + if (encoding == null) { encoding = ex.getContentTypeEncoding(); } - if ( encoding == null ) - { - encoding = ( _defaultEncoding == null ) ? UTF_8 : _defaultEncoding; + if (encoding == null) { + encoding = (_defaultEncoding == null) ? UTF_8 : _defaultEncoding; } - prepareReader( ex.getInputStream(), encoding ); + prepareReader(ex.getInputStream(), encoding); } } @@ -412,16 +358,13 @@ private void doLenientDetection( String httpContentType, XmlStreamReaderExceptio * * @return charset encoding. */ - public String getEncoding() - { + public String getEncoding() { return _encoding; } @Override - public int read( char[] buf, int offset, int len ) - throws IOException - { - return _reader.read( buf, offset, len ); + public int read(char[] buf, int offset, int len) throws IOException { + return _reader.read(buf, offset, len); } /** @@ -431,183 +374,157 @@ public int read( char[] buf, int offset, int len ) * @throws IOException thrown if there was a problem closing the stream. */ @Override - public void close() - throws IOException - { + public void close() throws IOException { _reader.close(); } - private void doRawStream( InputStream is, boolean lenient ) - throws IOException - { - BufferedInputStream pis = new BufferedInputStream( is, BUFFER_SIZE ); - String bomEnc = getBOMEncoding( pis ); - String xmlGuessEnc = getXMLGuessEncoding( pis ); - String xmlEnc = getXmlProlog( pis, xmlGuessEnc ); - String encoding = calculateRawEncoding( bomEnc, xmlGuessEnc, xmlEnc, pis ); - prepareReader( pis, encoding ); + private void doRawStream(InputStream is, boolean lenient) throws IOException { + BufferedInputStream pis = new BufferedInputStream(is, BUFFER_SIZE); + String bomEnc = getBOMEncoding(pis); + String xmlGuessEnc = getXMLGuessEncoding(pis); + String xmlEnc = getXmlProlog(pis, xmlGuessEnc); + String encoding = calculateRawEncoding(bomEnc, xmlGuessEnc, xmlEnc, pis); + prepareReader(pis, encoding); } - private void doHttpStream( InputStream is, String httpContentType, boolean lenient ) - throws IOException - { - BufferedInputStream pis = new BufferedInputStream( is, BUFFER_SIZE ); - String cTMime = getContentTypeMime( httpContentType ); - String cTEnc = getContentTypeEncoding( httpContentType ); - String bomEnc = getBOMEncoding( pis ); - String xmlGuessEnc = getXMLGuessEncoding( pis ); - String xmlEnc = getXmlProlog( pis, xmlGuessEnc ); - String encoding = calculateHttpEncoding( cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc, pis, lenient ); - prepareReader( pis, encoding ); + private void doHttpStream(InputStream is, String httpContentType, boolean lenient) throws IOException { + BufferedInputStream pis = new BufferedInputStream(is, BUFFER_SIZE); + String cTMime = getContentTypeMime(httpContentType); + String cTEnc = getContentTypeEncoding(httpContentType); + String bomEnc = getBOMEncoding(pis); + String xmlGuessEnc = getXMLGuessEncoding(pis); + String xmlEnc = getXmlProlog(pis, xmlGuessEnc); + String encoding = calculateHttpEncoding(cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc, pis, lenient); + prepareReader(pis, encoding); } - private void prepareReader( InputStream is, String encoding ) - throws IOException - { - _reader = new InputStreamReader( is, encoding ); + private void prepareReader(InputStream is, String encoding) throws IOException { + _reader = new InputStreamReader(is, encoding); _encoding = encoding; } // InputStream is passed for XmlStreamReaderException creation only - private String calculateRawEncoding( String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is ) - throws IOException - { + private String calculateRawEncoding(String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is) + throws IOException { String encoding; - if ( bomEnc == null ) - { - if ( xmlGuessEnc == null || xmlEnc == null ) - { - encoding = ( _defaultEncoding == null ) ? UTF_8 : _defaultEncoding; - } - else if ( xmlEnc.equals( UTF_16 ) && ( xmlGuessEnc.equals( UTF_16BE ) || xmlGuessEnc.equals( UTF_16LE ) ) ) - { + if (bomEnc == null) { + if (xmlGuessEnc == null || xmlEnc == null) { + encoding = (_defaultEncoding == null) ? UTF_8 : _defaultEncoding; + } else if (xmlEnc.equals(UTF_16) && (xmlGuessEnc.equals(UTF_16BE) || xmlGuessEnc.equals(UTF_16LE))) { encoding = xmlGuessEnc; - } - else - { + } else { encoding = xmlEnc; } - } - else if ( bomEnc.equals( UTF_8 ) ) - { - if ( xmlGuessEnc != null && !xmlGuessEnc.equals( UTF_8 ) ) - { - throw new XmlStreamReaderException( RAW_EX_1.format( new Object[] { bomEnc, xmlGuessEnc, xmlEnc } ), - bomEnc, xmlGuessEnc, xmlEnc, is ); + } else if (bomEnc.equals(UTF_8)) { + if (xmlGuessEnc != null && !xmlGuessEnc.equals(UTF_8)) { + throw new XmlStreamReaderException( + RAW_EX_1.format(new Object[] {bomEnc, xmlGuessEnc, xmlEnc}), bomEnc, xmlGuessEnc, xmlEnc, is); } - if ( xmlEnc != null && !xmlEnc.equals( UTF_8 ) ) - { - throw new XmlStreamReaderException( RAW_EX_1.format( new Object[] { bomEnc, xmlGuessEnc, xmlEnc } ), - bomEnc, xmlGuessEnc, xmlEnc, is ); + if (xmlEnc != null && !xmlEnc.equals(UTF_8)) { + throw new XmlStreamReaderException( + RAW_EX_1.format(new Object[] {bomEnc, xmlGuessEnc, xmlEnc}), bomEnc, xmlGuessEnc, xmlEnc, is); } encoding = UTF_8; - } - else if ( bomEnc.equals( UTF_16BE ) || bomEnc.equals( UTF_16LE ) ) - { - if ( xmlGuessEnc != null && !xmlGuessEnc.equals( bomEnc ) ) - { - throw new IOException( RAW_EX_1.format( new Object[] { bomEnc, xmlGuessEnc, xmlEnc } ) ); + } else if (bomEnc.equals(UTF_16BE) || bomEnc.equals(UTF_16LE)) { + if (xmlGuessEnc != null && !xmlGuessEnc.equals(bomEnc)) { + throw new IOException(RAW_EX_1.format(new Object[] {bomEnc, xmlGuessEnc, xmlEnc})); } - if ( xmlEnc != null && !xmlEnc.equals( UTF_16 ) && !xmlEnc.equals( bomEnc ) ) - { - throw new XmlStreamReaderException( RAW_EX_1.format( new Object[] { bomEnc, xmlGuessEnc, xmlEnc } ), - bomEnc, xmlGuessEnc, xmlEnc, is ); + if (xmlEnc != null && !xmlEnc.equals(UTF_16) && !xmlEnc.equals(bomEnc)) { + throw new XmlStreamReaderException( + RAW_EX_1.format(new Object[] {bomEnc, xmlGuessEnc, xmlEnc}), bomEnc, xmlGuessEnc, xmlEnc, is); } encoding = bomEnc; - } - else - { - throw new XmlStreamReaderException( RAW_EX_2.format( new Object[] { bomEnc, xmlGuessEnc, xmlEnc } ), bomEnc, - xmlGuessEnc, xmlEnc, is ); + } else { + throw new XmlStreamReaderException( + RAW_EX_2.format(new Object[] {bomEnc, xmlGuessEnc, xmlEnc}), bomEnc, xmlGuessEnc, xmlEnc, is); } return encoding; } // InputStream is passed for XmlStreamReaderException creation only - private String calculateHttpEncoding( String cTMime, String cTEnc, String bomEnc, String xmlGuessEnc, String xmlEnc, - InputStream is, boolean lenient ) - throws IOException - { + private String calculateHttpEncoding( + String cTMime, + String cTEnc, + String bomEnc, + String xmlGuessEnc, + String xmlEnc, + InputStream is, + boolean lenient) + throws IOException { String encoding; - if ( lenient & xmlEnc != null ) - { + if (lenient & xmlEnc != null) { encoding = xmlEnc; - } - else - { - boolean appXml = isAppXml( cTMime ); - boolean textXml = isTextXml( cTMime ); - if ( appXml || textXml ) - { - if ( cTEnc == null ) - { - if ( appXml ) - { - encoding = calculateRawEncoding( bomEnc, xmlGuessEnc, xmlEnc, is ); - } - else - { - encoding = ( _defaultEncoding == null ) ? US_ASCII : _defaultEncoding; + } else { + boolean appXml = isAppXml(cTMime); + boolean textXml = isTextXml(cTMime); + if (appXml || textXml) { + if (cTEnc == null) { + if (appXml) { + encoding = calculateRawEncoding(bomEnc, xmlGuessEnc, xmlEnc, is); + } else { + encoding = (_defaultEncoding == null) ? US_ASCII : _defaultEncoding; } - } - else if ( bomEnc != null && ( cTEnc.equals( UTF_16BE ) || cTEnc.equals( UTF_16LE ) ) ) - { - throw new XmlStreamReaderException( HTTP_EX_1.format( new Object[] { cTMime, cTEnc, bomEnc, - xmlGuessEnc, xmlEnc } ), cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc, is ); - } - else if ( cTEnc.equals( UTF_16 ) ) - { - if ( bomEnc != null && bomEnc.startsWith( UTF_16 ) ) - { + } else if (bomEnc != null && (cTEnc.equals(UTF_16BE) || cTEnc.equals(UTF_16LE))) { + throw new XmlStreamReaderException( + HTTP_EX_1.format(new Object[] {cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc}), + cTMime, + cTEnc, + bomEnc, + xmlGuessEnc, + xmlEnc, + is); + } else if (cTEnc.equals(UTF_16)) { + if (bomEnc != null && bomEnc.startsWith(UTF_16)) { encoding = bomEnc; + } else { + throw new XmlStreamReaderException( + HTTP_EX_2.format(new Object[] {cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc}), + cTMime, + cTEnc, + bomEnc, + xmlGuessEnc, + xmlEnc, + is); } - else - { - throw new XmlStreamReaderException( HTTP_EX_2.format( new Object[] { cTMime, cTEnc, bomEnc, - xmlGuessEnc, xmlEnc } ), cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc, is ); - } - } - else - { + } else { encoding = cTEnc; } - } - else - { - throw new XmlStreamReaderException( HTTP_EX_3.format( new Object[] { cTMime, cTEnc, bomEnc, xmlGuessEnc, - xmlEnc } ), cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc, is ); + } else { + throw new XmlStreamReaderException( + HTTP_EX_3.format(new Object[] {cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc}), + cTMime, + cTEnc, + bomEnc, + xmlGuessEnc, + xmlEnc, + is); } } return encoding; } // returns MIME type or NULL if httpContentType is NULL - private static String getContentTypeMime( String httpContentType ) - { + private static String getContentTypeMime(String httpContentType) { String mime = null; - if ( httpContentType != null ) - { - int i = httpContentType.indexOf( ";" ); - mime = ( ( i == -1 ) ? httpContentType : httpContentType.substring( 0, i ) ).trim(); + if (httpContentType != null) { + int i = httpContentType.indexOf(";"); + mime = ((i == -1) ? httpContentType : httpContentType.substring(0, i)).trim(); } return mime; } - private static final Pattern CHARSET_PATTERN = Pattern.compile( "charset=([.[^; ]]*)" ); + private static final Pattern CHARSET_PATTERN = Pattern.compile("charset=([.[^; ]]*)"); // returns charset parameter value, NULL if not present, NULL if httpContentType is NULL - private static String getContentTypeEncoding( String httpContentType ) - { + private static String getContentTypeEncoding(String httpContentType) { String encoding = null; - if ( httpContentType != null ) - { - int i = httpContentType.indexOf( ";" ); - if ( i > -1 ) - { - String postMime = httpContentType.substring( i + 1 ); - Matcher m = CHARSET_PATTERN.matcher( postMime ); - encoding = ( m.find() ) ? m.group( 1 ) : null; - encoding = ( encoding != null ) ? encoding.toUpperCase( Locale.ENGLISH ) : null; + if (httpContentType != null) { + int i = httpContentType.indexOf(";"); + if (i > -1) { + String postMime = httpContentType.substring(i + 1); + Matcher m = CHARSET_PATTERN.matcher(postMime); + encoding = (m.find()) ? m.group(1) : null; + encoding = (encoding != null) ? encoding.toUpperCase(Locale.ENGLISH) : null; } } return encoding; @@ -615,127 +532,97 @@ private static String getContentTypeEncoding( String httpContentType ) // returns the BOM in the stream, NULL if not present, // if there was BOM the in the stream it is consumed - private static String getBOMEncoding( BufferedInputStream is ) - throws IOException - { + private static String getBOMEncoding(BufferedInputStream is) throws IOException { String encoding = null; int[] bytes = new int[3]; - is.mark( 3 ); + is.mark(3); bytes[0] = is.read(); bytes[1] = is.read(); bytes[2] = is.read(); - if ( bytes[0] == 0xFE && bytes[1] == 0xFF ) - { + if (bytes[0] == 0xFE && bytes[1] == 0xFF) { encoding = UTF_16BE; is.reset(); is.read(); is.read(); - } - else if ( bytes[0] == 0xFF && bytes[1] == 0xFE ) - { + } else if (bytes[0] == 0xFF && bytes[1] == 0xFE) { encoding = UTF_16LE; is.reset(); is.read(); is.read(); - } - else if ( bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ) - { + } else if (bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) { encoding = UTF_8; - } - else - { + } else { is.reset(); } return encoding; } // returns the best guess for the encoding by looking the first bytes of the stream, ', NULL if none - private static String getXmlProlog( BufferedInputStream is, String guessedEnc ) - throws IOException - { + private static String getXmlProlog(BufferedInputStream is, String guessedEnc) throws IOException { String encoding = null; - if ( guessedEnc != null ) - { + if (guessedEnc != null) { byte[] bytes = new byte[BUFFER_SIZE]; - is.mark( BUFFER_SIZE ); + is.mark(BUFFER_SIZE); int offset = 0; int max = BUFFER_SIZE; - int c = is.read( bytes, offset, max ); + int c = is.read(bytes, offset, max); int firstGT = -1; String xmlProlog = null; - while ( c != -1 && firstGT == -1 && offset < BUFFER_SIZE ) - { + while (c != -1 && firstGT == -1 && offset < BUFFER_SIZE) { offset += c; max -= c; - c = is.read( bytes, offset, max ); - xmlProlog = new String( bytes, 0, offset, guessedEnc ); - firstGT = xmlProlog.indexOf( '>' ); + c = is.read(bytes, offset, max); + xmlProlog = new String(bytes, 0, offset, guessedEnc); + firstGT = xmlProlog.indexOf('>'); } - if ( firstGT == -1 ) - { - if ( c == -1 ) - { - throw new IOException( "Unexpected end of XML stream" ); - } - else - { - throw new IOException( "XML prolog or ROOT element not found on first " + offset + " bytes" ); + if (firstGT == -1) { + if (c == -1) { + throw new IOException("Unexpected end of XML stream"); + } else { + throw new IOException("XML prolog or ROOT element not found on first " + offset + " bytes"); } } int bytesRead = offset; - if ( bytesRead > 0 ) - { + if (bytesRead > 0) { is.reset(); - BufferedReader bReader = - new BufferedReader( new StringReader( xmlProlog.substring( 0, firstGT + 1 ) ) ); + BufferedReader bReader = new BufferedReader(new StringReader(xmlProlog.substring(0, firstGT + 1))); StringBuilder prolog = new StringBuilder(); String line = bReader.readLine(); - while ( line != null ) - { - prolog.append( line ); + while (line != null) { + prolog.append(line); line = bReader.readLine(); } - Matcher m = ENCODING_PATTERN.matcher( prolog ); - if ( m.find() ) - { - encoding = m.group( 1 ).toUpperCase( Locale.ENGLISH ); - encoding = encoding.substring( 1, encoding.length() - 1 ); + Matcher m = ENCODING_PATTERN.matcher(prolog); + if (m.find()) { + encoding = m.group(1).toUpperCase(Locale.ENGLISH); + encoding = encoding.substring(1, encoding.length() - 1); } } } @@ -743,33 +630,34 @@ private static String getXmlProlog( BufferedInputStream is, String guessedEnc ) } // indicates if the MIME type belongs to the APPLICATION XML family - private static boolean isAppXml( String mime ) - { - return mime != null && ( mime.equals( "application/xml" ) || mime.equals( "application/xml-dtd" ) - || mime.equals( "application/xml-external-parsed-entity" ) - || ( mime.startsWith( "application/" ) && mime.endsWith( "+xml" ) ) ); + private static boolean isAppXml(String mime) { + return mime != null + && (mime.equals("application/xml") + || mime.equals("application/xml-dtd") + || mime.equals("application/xml-external-parsed-entity") + || (mime.startsWith("application/") && mime.endsWith("+xml"))); } // indicates if the MIME type belongs to the TEXT XML family - private static boolean isTextXml( String mime ) - { - return mime != null && ( mime.equals( "text/xml" ) || mime.equals( "text/xml-external-parsed-entity" ) - || ( mime.startsWith( "text/" ) && mime.endsWith( "+xml" ) ) ); + private static boolean isTextXml(String mime) { + return mime != null + && (mime.equals("text/xml") + || mime.equals("text/xml-external-parsed-entity") + || (mime.startsWith("text/") && mime.endsWith("+xml"))); } private static final MessageFormat RAW_EX_1 = - new MessageFormat( "Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] encoding mismatch" ); + new MessageFormat("Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] encoding mismatch"); private static final MessageFormat RAW_EX_2 = - new MessageFormat( "Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] unknown BOM" ); - - private static final MessageFormat HTTP_EX_1 = - new MessageFormat( "Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], BOM must be NULL" ); + new MessageFormat("Invalid encoding, BOM [{0}] XML guess [{1}] XML prolog [{2}] unknown BOM"); - private static final MessageFormat HTTP_EX_2 = - new MessageFormat( "Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], encoding mismatch" ); + private static final MessageFormat HTTP_EX_1 = new MessageFormat( + "Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], BOM must be NULL"); - private static final MessageFormat HTTP_EX_3 = - new MessageFormat( "Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], Invalid MIME" ); + private static final MessageFormat HTTP_EX_2 = new MessageFormat( + "Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], encoding mismatch"); + private static final MessageFormat HTTP_EX_3 = new MessageFormat( + "Invalid encoding, CT-MIME [{0}] CT-Enc [{1}] BOM [{2}] XML guess [{3}] XML prolog [{4}], Invalid MIME"); } diff --git a/src/main/java/org/codehaus/plexus/util/xml/XmlReaderException.java b/src/main/java/org/codehaus/plexus/util/xml/XmlReaderException.java index 1e015506..5fb2dcab 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/XmlReaderException.java +++ b/src/main/java/org/codehaus/plexus/util/xml/XmlReaderException.java @@ -16,8 +16,8 @@ */ package org.codehaus.plexus.util.xml; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; /** * The XmlReaderException is thrown by the XmlReader constructors if the charset encoding can not be determined @@ -31,9 +31,7 @@ * @version revision 1.1 taken on 26/06/2007 from Rome (see * https://rome.dev.java.net/source/browse/rome/src/java/com/sun/syndication/io/XmlReaderException.java) */ -public class XmlReaderException - extends IOException -{ +public class XmlReaderException extends IOException { private String _bomEncoding; private String _xmlGuessEncoding; @@ -58,9 +56,8 @@ public class XmlReaderException * @param xmlEnc XML prolog encoding. * @param is the unconsumed InputStream. */ - public XmlReaderException( String msg, String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is ) - { - this( msg, null, null, bomEnc, xmlGuessEnc, xmlEnc, is ); + public XmlReaderException(String msg, String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is) { + this(msg, null, null, bomEnc, xmlGuessEnc, xmlEnc, is); } /** @@ -77,10 +74,9 @@ public XmlReaderException( String msg, String bomEnc, String xmlGuessEnc, String * @param xmlEnc XML prolog encoding. * @param is the unconsumed InputStream. */ - public XmlReaderException( String msg, String ctMime, String ctEnc, String bomEnc, String xmlGuessEnc, - String xmlEnc, InputStream is ) - { - super( msg ); + public XmlReaderException( + String msg, String ctMime, String ctEnc, String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is) { + super(msg); _contentTypeMime = ctMime; _contentTypeEncoding = ctEnc; _bomEncoding = bomEnc; @@ -95,8 +91,7 @@ public XmlReaderException( String msg, String ctMime, String ctEnc, String bomEn * * @return the BOM encoding, null if none. */ - public String getBomEncoding() - { + public String getBomEncoding() { return _bomEncoding; } @@ -106,8 +101,7 @@ public String getBomEncoding() * * @return the encoding guess, null if it couldn't be guessed. */ - public String getXmlGuessEncoding() - { + public String getXmlGuessEncoding() { return _xmlGuessEncoding; } @@ -117,8 +111,7 @@ public String getXmlGuessEncoding() * * @return the encoding of the XML prolog, null if none. */ - public String getXmlEncoding() - { + public String getXmlEncoding() { return _xmlEncoding; } @@ -129,8 +122,7 @@ public String getXmlEncoding() * @return the MIME type in the content-type, null if there was not content-type or the encoding detection did not * involve HTTP. */ - public String getContentTypeMime() - { + public String getContentTypeMime() { return _contentTypeMime; } @@ -141,8 +133,7 @@ public String getContentTypeMime() * @return the encoding in the content-type, null if there was not content-type, no encoding in it or the encoding * detection did not involve HTTP. */ - public String getContentTypeEncoding() - { + public String getContentTypeEncoding() { return _contentTypeEncoding; } @@ -153,8 +144,7 @@ public String getContentTypeEncoding() * * @return the unconsumed InputStream. */ - public InputStream getInputStream() - { + public InputStream getInputStream() { return _is; } } diff --git a/src/main/java/org/codehaus/plexus/util/xml/XmlStreamReader.java b/src/main/java/org/codehaus/plexus/util/xml/XmlStreamReader.java index 5c26aa98..1520481a 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/XmlStreamReader.java +++ b/src/main/java/org/codehaus/plexus/util/xml/XmlStreamReader.java @@ -40,15 +40,13 @@ *
      Determining the character encoding of a * feed. *

      - * + * * @author Alejandro Abdelnur * @version revision 1.17 taken on 26/06/2007 from Rome (see * https://rome.dev.java.net/source/browse/rome/src/java/com/sun/syndication/io/XmlReader.java) * @since 1.4.4 */ -public class XmlStreamReader - extends XmlReader -{ +public class XmlStreamReader extends XmlReader { /** * Creates a Reader for a File. *

      @@ -57,14 +55,12 @@ public class XmlStreamReader *

      * It does a lenient charset encoding detection, check the constructor with the lenient parameter for details. *

      - * + * * @param file File to create a Reader from. * @throws IOException thrown if there is a problem reading the file. */ - public XmlStreamReader( File file ) - throws IOException - { - super( file ); + public XmlStreamReader(File file) throws IOException { + super(file); } /** @@ -74,14 +70,12 @@ public XmlStreamReader( File file ) *

      * It does a lenient charset encoding detection, check the constructor with the lenient parameter for details. *

      - * + * * @param is InputStream to create a Reader from. * @throws IOException thrown if there is a problem reading the stream. */ - public XmlStreamReader( InputStream is ) - throws IOException - { - super( is ); + public XmlStreamReader(InputStream is) throws IOException { + super(is); } /** @@ -102,16 +96,14 @@ public XmlStreamReader( InputStream is ) *

      * If lenient detection is indicated an XmlStreamReaderException is never thrown. *

      - * + * * @param is InputStream to create a Reader from. * @param lenient indicates if the charset encoding detection should be relaxed. * @throws IOException thrown if there is a problem reading the stream. * @throws XmlStreamReaderException thrown if the charset encoding could not be determined according to the specs. */ - public XmlStreamReader( InputStream is, boolean lenient ) - throws IOException, XmlStreamReaderException - { - super( is, lenient ); + public XmlStreamReader(InputStream is, boolean lenient) throws IOException, XmlStreamReaderException { + super(is, lenient); } /** @@ -125,14 +117,12 @@ public XmlStreamReader( InputStream is, boolean lenient ) *

      * It does a lenient charset encoding detection, check the constructor with the lenient parameter for details. *

      - * + * * @param url URL to create a Reader from. * @throws IOException thrown if there is a problem reading the stream of the URL. */ - public XmlStreamReader( URL url ) - throws IOException - { - super( url ); + public XmlStreamReader(URL url) throws IOException { + super(url); } /** @@ -146,14 +136,12 @@ public XmlStreamReader( URL url ) *

      * It does a lenient charset encoding detection, check the constructor with the lenient parameter for details. *

      - * + * * @param conn URLConnection to create a Reader from. * @throws IOException thrown if there is a problem reading the stream of the URLConnection. */ - public XmlStreamReader( URLConnection conn ) - throws IOException - { - super( conn ); + public XmlStreamReader(URLConnection conn) throws IOException { + super(conn); } /** @@ -165,15 +153,13 @@ public XmlStreamReader( URLConnection conn ) *

      * It does a lenient charset encoding detection, check the constructor with the lenient parameter for details. *

      - * + * * @param is InputStream to create the reader from. * @param httpContentType content-type header to use for the resolution of the charset encoding. * @throws IOException thrown if there is a problem reading the file. */ - public XmlStreamReader( InputStream is, String httpContentType ) - throws IOException - { - super( is, httpContentType ); + public XmlStreamReader(InputStream is, String httpContentType) throws IOException { + super(is, httpContentType); } /** @@ -197,7 +183,7 @@ public XmlStreamReader( InputStream is, String httpContentType ) *

      * If lenient detection is indicated an XmlStreamReaderException is never thrown. *

      - * + * * @param is InputStream to create the reader from. * @param httpContentType content-type header to use for the resolution of the charset encoding. * @param lenient indicates if the charset encoding detection should be relaxed. @@ -205,10 +191,9 @@ public XmlStreamReader( InputStream is, String httpContentType ) * @throws IOException thrown if there is a problem reading the file. * @throws XmlStreamReaderException thrown if the charset encoding could not be determined according to the specs. */ - public XmlStreamReader( InputStream is, String httpContentType, boolean lenient, String defaultEncoding ) - throws IOException, XmlStreamReaderException - { - super( is, httpContentType, lenient, defaultEncoding ); + public XmlStreamReader(InputStream is, String httpContentType, boolean lenient, String defaultEncoding) + throws IOException, XmlStreamReaderException { + super(is, httpContentType, lenient, defaultEncoding); } /** @@ -232,16 +217,15 @@ public XmlStreamReader( InputStream is, String httpContentType, boolean lenient, *

      * If lenient detection is indicated an XmlStreamReaderException is never thrown. *

      - * + * * @param is InputStream to create the reader from. * @param httpContentType content-type header to use for the resolution of the charset encoding. * @param lenient indicates if the charset encoding detection should be relaxed. * @throws IOException thrown if there is a problem reading the file. * @throws XmlStreamReaderException thrown if the charset encoding could not be determined according to the specs. */ - public XmlStreamReader( InputStream is, String httpContentType, boolean lenient ) - throws IOException, XmlStreamReaderException - { - super( is, httpContentType, lenient ); + public XmlStreamReader(InputStream is, String httpContentType, boolean lenient) + throws IOException, XmlStreamReaderException { + super(is, httpContentType, lenient); } } diff --git a/src/main/java/org/codehaus/plexus/util/xml/XmlStreamReaderException.java b/src/main/java/org/codehaus/plexus/util/xml/XmlStreamReaderException.java index dc919981..1901c40c 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/XmlStreamReaderException.java +++ b/src/main/java/org/codehaus/plexus/util/xml/XmlStreamReaderException.java @@ -31,9 +31,7 @@ * @version revision 1.1 taken on 26/06/2007 from Rome (see * https://rome.dev.java.net/source/browse/rome/src/java/com/sun/syndication/io/XmlReaderException.java) */ -public class XmlStreamReaderException - extends XmlReaderException -{ +public class XmlStreamReaderException extends XmlReaderException { /** * Creates an exception instance if the charset encoding could not be determined. *

      @@ -46,9 +44,8 @@ public class XmlStreamReaderException * @param xmlEnc XML prolog encoding. * @param is the unconsumed InputStream. */ - public XmlStreamReaderException( String msg, String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is ) - { - super( msg, bomEnc, xmlGuessEnc, xmlEnc, is ); + public XmlStreamReaderException(String msg, String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is) { + super(msg, bomEnc, xmlGuessEnc, xmlEnc, is); } /** @@ -65,9 +62,8 @@ public XmlStreamReaderException( String msg, String bomEnc, String xmlGuessEnc, * @param xmlEnc XML prolog encoding. * @param is the unconsumed InputStream. */ - public XmlStreamReaderException( String msg, String ctMime, String ctEnc, String bomEnc, String xmlGuessEnc, - String xmlEnc, InputStream is ) - { - super( msg, ctMime, ctEnc, bomEnc, xmlGuessEnc, xmlEnc, is ); + public XmlStreamReaderException( + String msg, String ctMime, String ctEnc, String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is) { + super(msg, ctMime, ctEnc, bomEnc, xmlGuessEnc, xmlEnc, is); } } diff --git a/src/main/java/org/codehaus/plexus/util/xml/XmlStreamWriter.java b/src/main/java/org/codehaus/plexus/util/xml/XmlStreamWriter.java index 9b5f0a92..aec451aa 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/XmlStreamWriter.java +++ b/src/main/java/org/codehaus/plexus/util/xml/XmlStreamWriter.java @@ -30,17 +30,15 @@ /** * Character stream that handles (or at least attempts to) all the necessary Voodo to figure out the charset encoding of * the XML document written to the stream. - * + * * @author Herve Boutemy * * @since 1.4.4 */ -public class XmlStreamWriter - extends Writer -{ +public class XmlStreamWriter extends Writer { private static final int BUFFER_SIZE = 4096; - private StringWriter xmlPrologWriter = new StringWriter( BUFFER_SIZE ); + private StringWriter xmlPrologWriter = new StringWriter(BUFFER_SIZE); private OutputStream out; @@ -48,117 +46,86 @@ public class XmlStreamWriter private String encoding; - public XmlStreamWriter( OutputStream out ) - { + public XmlStreamWriter(OutputStream out) { this.out = out; } - public XmlStreamWriter( File file ) - throws IOException - { - this( Files.newOutputStream( file.toPath() ) ); + public XmlStreamWriter(File file) throws IOException { + this(Files.newOutputStream(file.toPath())); } - public String getEncoding() - { + public String getEncoding() { return encoding; } @Override - public void close() - throws IOException - { - if ( writer == null ) - { + public void close() throws IOException { + if (writer == null) { encoding = "UTF-8"; - writer = new OutputStreamWriter( out, encoding ); - writer.write( xmlPrologWriter.toString() ); + writer = new OutputStreamWriter(out, encoding); + writer.write(xmlPrologWriter.toString()); } writer.close(); } @Override - public void flush() - throws IOException - { - if ( writer != null ) - { + public void flush() throws IOException { + if (writer != null) { writer.flush(); } } - private void detectEncoding( char[] cbuf, int off, int len ) - throws IOException - { + private void detectEncoding(char[] cbuf, int off, int len) throws IOException { int size = len; StringBuffer xmlProlog = xmlPrologWriter.getBuffer(); - if ( xmlProlog.length() + len > BUFFER_SIZE ) - { + if (xmlProlog.length() + len > BUFFER_SIZE) { size = BUFFER_SIZE - xmlProlog.length(); } - xmlPrologWriter.write( cbuf, off, size ); + xmlPrologWriter.write(cbuf, off, size); // try to determine encoding - if ( xmlProlog.length() >= 5 ) - { - if ( xmlProlog.substring( 0, 5 ).equals( "= 5) { + if (xmlProlog.substring(0, 5).equals("" ); - if ( xmlPrologEnd > 0 ) - { + int xmlPrologEnd = xmlProlog.indexOf("?>"); + if (xmlPrologEnd > 0) { // ok, full XML prolog written: let's extract encoding - Matcher m = ENCODING_PATTERN.matcher( xmlProlog.substring( 0, xmlPrologEnd ) ); - if ( m.find() ) - { - encoding = m.group( 1 ).toUpperCase( Locale.ENGLISH ); - encoding = encoding.substring( 1, encoding.length() - 1 ); - } - else - { + Matcher m = ENCODING_PATTERN.matcher(xmlProlog.substring(0, xmlPrologEnd)); + if (m.find()) { + encoding = m.group(1).toUpperCase(Locale.ENGLISH); + encoding = encoding.substring(1, encoding.length() - 1); + } else { // no encoding found in XML prolog: using default encoding encoding = "UTF-8"; } - } - else - { - if ( xmlProlog.length() >= BUFFER_SIZE ) - { + } else { + if (xmlProlog.length() >= BUFFER_SIZE) { // no encoding found in first characters: using default encoding encoding = "UTF-8"; } } - } - else - { + } else { // no XML prolog: using default encoding encoding = "UTF-8"; } - if ( encoding != null ) - { + if (encoding != null) { // encoding has been chosen: let's do it xmlPrologWriter = null; - writer = new OutputStreamWriter( out, encoding ); - writer.write( xmlProlog.toString() ); - if ( len > size ) - { - writer.write( cbuf, off + size, len - size ); + writer = new OutputStreamWriter(out, encoding); + writer.write(xmlProlog.toString()); + if (len > size) { + writer.write(cbuf, off + size, len - size); } } } } @Override - public void write( char[] cbuf, int off, int len ) - throws IOException - { - if ( xmlPrologWriter != null ) - { - detectEncoding( cbuf, off, len ); - } - else - { - writer.write( cbuf, off, len ); + public void write(char[] cbuf, int off, int len) throws IOException { + if (xmlPrologWriter != null) { + detectEncoding(cbuf, off, len); + } else { + writer.write(cbuf, off, len); } } diff --git a/src/main/java/org/codehaus/plexus/util/xml/XmlUtil.java b/src/main/java/org/codehaus/plexus/util/xml/XmlUtil.java index 73464b8e..6610ffd6 100644 --- a/src/main/java/org/codehaus/plexus/util/xml/XmlUtil.java +++ b/src/main/java/org/codehaus/plexus/util/xml/XmlUtil.java @@ -38,13 +38,12 @@ * * @since 1.5.7 */ -public class XmlUtil -{ +public class XmlUtil { /** The default line indenter size i.e. 2. */ public static final int DEFAULT_INDENTATION_SIZE = 2; /** The default line separator ("\n" on UNIX) */ - public static final String DEFAULT_LINE_SEPARATOR = System.getProperty( "line.separator" ); + public static final String DEFAULT_LINE_SEPARATOR = System.getProperty("line.separator"); /** * Determines if a given File shall be handled as XML. @@ -52,40 +51,34 @@ public class XmlUtil * @param f not null file * @return true if the given file has XML content, false otherwise. */ - public static boolean isXml( File f ) - { - if ( f == null ) - { - throw new IllegalArgumentException( "f could not be null." ); + public static boolean isXml(File f) { + if (f == null) { + throw new IllegalArgumentException("f could not be null."); } - if ( !f.isFile() ) - { - throw new IllegalArgumentException( "The file '" + f.getAbsolutePath() + "' is not a file." ); + if (!f.isFile()) { + throw new IllegalArgumentException("The file '" + f.getAbsolutePath() + "' is not a file."); } - try ( Reader reader = ReaderFactory.newXmlReader( f ) ) - { + try (Reader reader = ReaderFactory.newXmlReader(f)) { XmlPullParser parser = new MXParser(); - parser.setInput( reader ); + parser.setInput(reader); parser.nextToken(); return true; - } - catch ( Exception e ) - { + } catch (Exception e) { return false; } } /** * Pretty format the input reader. For instance, the following input: - * + * *

            * <div><b>content</b></div>
            * 
      - * + * * becomes - * + * *
            * <div>
            *   <b>content</b>
      @@ -99,21 +92,19 @@ public static boolean isXml( File f )
            * @see ReaderFactory to read an xml content
            * @see WriterFactory to write an xml content
            */
      -    public static void prettyFormat( Reader reader, Writer writer )
      -        throws IOException
      -    {
      -        prettyFormat( reader, writer, DEFAULT_INDENTATION_SIZE, DEFAULT_LINE_SEPARATOR );
      +    public static void prettyFormat(Reader reader, Writer writer) throws IOException {
      +        prettyFormat(reader, writer, DEFAULT_INDENTATION_SIZE, DEFAULT_LINE_SEPARATOR);
           }
       
           /**
            * Pretty format the input reader. For instance, the following input:
      -     * 
      +     *
            * 
            * <div><b>content</b></div>
            * 
      - * + * * becomes - * + * *
            * <div>
            *   <b>content</b>
      @@ -128,48 +119,41 @@ public static void prettyFormat( Reader reader, Writer writer )
            * @see ReaderFactory to read an xml content
            * @see WriterFactory to write an xml content
            */
      -    public static void prettyFormat( Reader reader, Writer writer, int indentSize, String lineSeparator )
      -        throws IOException
      -    {
      -        if ( reader == null )
      -        {
      -            throw new IllegalArgumentException( "The reader is null" );
      +    public static void prettyFormat(Reader reader, Writer writer, int indentSize, String lineSeparator)
      +            throws IOException {
      +        if (reader == null) {
      +            throw new IllegalArgumentException("The reader is null");
               }
      -        if ( writer == null )
      -        {
      -            throw new IllegalArgumentException( "The writer is null" );
      +        if (writer == null) {
      +            throw new IllegalArgumentException("The writer is null");
               }
      -        if ( indentSize < 0 )
      -        {
      +        if (indentSize < 0) {
                   indentSize = 0;
               }
       
      -        PrettyPrintXMLWriter xmlWriter = new PrettyPrintXMLWriter( writer );
      -        xmlWriter.setLineIndenter( StringUtils.repeat( " ", indentSize ) );
      -        xmlWriter.setLineSeparator( lineSeparator );
      +        PrettyPrintXMLWriter xmlWriter = new PrettyPrintXMLWriter(writer);
      +        xmlWriter.setLineIndenter(StringUtils.repeat(" ", indentSize));
      +        xmlWriter.setLineSeparator(lineSeparator);
       
               XmlPullParser parser = new MXParser();
      -        try
      -        {
      -            parser.setInput( reader );
      +        try {
      +            parser.setInput(reader);
       
      -            prettyFormatInternal( parser, xmlWriter );
      -        }
      -        catch ( XmlPullParserException e )
      -        {
      -            throw new IOException( "Unable to parse the XML: " + e.getMessage() );
      +            prettyFormatInternal(parser, xmlWriter);
      +        } catch (XmlPullParserException e) {
      +            throw new IOException("Unable to parse the XML: " + e.getMessage());
               }
           }
       
           /**
            * Pretty format the input stream. For instance, the following input:
      -     * 
      +     *
            * 
            * <div><b>content</b></div>
            * 
      - * + * * becomes - * + * *
            * <div>
            *   <b>content</b>
      @@ -181,21 +165,19 @@ public static void prettyFormat( Reader reader, Writer writer, int indentSize, S
            * @throws IOException if any or invalid xml content
            * @see #prettyFormat(InputStream, OutputStream, int, String)
            */
      -    public static void prettyFormat( InputStream is, OutputStream os )
      -        throws IOException
      -    {
      -        prettyFormat( is, os, DEFAULT_INDENTATION_SIZE, DEFAULT_LINE_SEPARATOR );
      +    public static void prettyFormat(InputStream is, OutputStream os) throws IOException {
      +        prettyFormat(is, os, DEFAULT_INDENTATION_SIZE, DEFAULT_LINE_SEPARATOR);
           }
       
           /**
            * Pretty format the input stream. For instance, the following input:
      -     * 
      +     *
            * 
            * <div><b>content</b></div>
            * 
      - * + * * becomes - * + * *
            * <div>
            *   <b>content</b>
      @@ -208,37 +190,30 @@ public static void prettyFormat( InputStream is, OutputStream os )
            * @param lineSeparator the wanted line separator
            * @throws IOException if any or invalid xml content
            */
      -    public static void prettyFormat( InputStream is, OutputStream os, int indentSize, String lineSeparator )
      -        throws IOException
      -    {
      -        if ( is == null )
      -        {
      -            throw new IllegalArgumentException( "The is is null" );
      +    public static void prettyFormat(InputStream is, OutputStream os, int indentSize, String lineSeparator)
      +            throws IOException {
      +        if (is == null) {
      +            throw new IllegalArgumentException("The is is null");
               }
      -        if ( os == null )
      -        {
      -            throw new IllegalArgumentException( "The os is null" );
      +        if (os == null) {
      +            throw new IllegalArgumentException("The os is null");
               }
      -        if ( indentSize < 0 )
      -        {
      +        if (indentSize < 0) {
                   indentSize = 0;
               }
       
      -        try ( Reader reader = ReaderFactory.newXmlReader( is );
      -              Writer writer = new OutputStreamWriter( os ) )
      -        {
      -            final PrettyPrintXMLWriter xmlWriter = new PrettyPrintXMLWriter( writer );
      -            xmlWriter.setLineIndenter( StringUtils.repeat( " ", indentSize ) );
      -            xmlWriter.setLineSeparator( lineSeparator );
      +        try (Reader reader = ReaderFactory.newXmlReader(is);
      +                Writer writer = new OutputStreamWriter(os)) {
      +            final PrettyPrintXMLWriter xmlWriter = new PrettyPrintXMLWriter(writer);
      +            xmlWriter.setLineIndenter(StringUtils.repeat(" ", indentSize));
      +            xmlWriter.setLineSeparator(lineSeparator);
       
                   final XmlPullParser parser = new MXParser();
      -            parser.setInput( reader );
      +            parser.setInput(reader);
       
      -            prettyFormatInternal( parser, xmlWriter );
      -        }
      -        catch ( XmlPullParserException e )
      -        {
      -            throw new IOException( "Unable to parse the XML: " + e.getMessage() );
      +            prettyFormatInternal(parser, xmlWriter);
      +        } catch (XmlPullParserException e) {
      +            throw new IOException("Unable to parse the XML: " + e.getMessage());
               }
           }
       
      @@ -248,82 +223,58 @@ public static void prettyFormat( InputStream is, OutputStream os, int indentSize
            * @throws XmlPullParserException if any
            * @throws IOException if any
            */
      -    private static void prettyFormatInternal( XmlPullParser parser, PrettyPrintXMLWriter writer )
      -        throws XmlPullParserException, IOException
      -    {
      +    private static void prettyFormatInternal(XmlPullParser parser, PrettyPrintXMLWriter writer)
      +            throws XmlPullParserException, IOException {
               boolean hasTag = false;
               boolean hasComment = false;
               int eventType = parser.getEventType();
      -        while ( eventType != XmlPullParser.END_DOCUMENT )
      -        {
      -            if ( eventType == XmlPullParser.START_TAG )
      -            {
      +        while (eventType != XmlPullParser.END_DOCUMENT) {
      +            if (eventType == XmlPullParser.START_TAG) {
                       hasTag = true;
      -                if ( hasComment )
      -                {
      -                    writer.writeText( writer.getLineIndenter() );
      +                if (hasComment) {
      +                    writer.writeText(writer.getLineIndenter());
                           hasComment = false;
                       }
      -                writer.startElement( parser.getName() );
      -                for ( int i = 0; i < parser.getAttributeCount(); i++ )
      -                {
      -                    String key = parser.getAttributeName( i );
      -                    String value = parser.getAttributeValue( i );
      -                    writer.addAttribute( key, value );
      +                writer.startElement(parser.getName());
      +                for (int i = 0; i < parser.getAttributeCount(); i++) {
      +                    String key = parser.getAttributeName(i);
      +                    String value = parser.getAttributeValue(i);
      +                    writer.addAttribute(key, value);
                       }
      -            }
      -            else if ( eventType == XmlPullParser.TEXT )
      -            {
      +            } else if (eventType == XmlPullParser.TEXT) {
                       String text = parser.getText();
      -                if ( !text.trim().equals( "" ) )
      -                {
      -                    text = StringUtils.removeDuplicateWhitespace( text );
      -                    writer.writeText( text );
      +                if (!text.trim().equals("")) {
      +                    text = StringUtils.removeDuplicateWhitespace(text);
      +                    writer.writeText(text);
                       }
      -            }
      -            else if ( eventType == XmlPullParser.END_TAG )
      -            {
      +            } else if (eventType == XmlPullParser.END_TAG) {
                       hasTag = false;
                       writer.endElement();
      -            }
      -            else if ( eventType == XmlPullParser.COMMENT )
      -            {
      +            } else if (eventType == XmlPullParser.COMMENT) {
                       hasComment = true;
      -                if ( !hasTag )
      -                {
      -                    writer.writeMarkup( writer.getLineSeparator() );
      -                    for ( int i = 0; i < writer.getDepth(); i++ )
      -                    {
      -                        writer.writeMarkup( writer.getLineIndenter() );
      +                if (!hasTag) {
      +                    writer.writeMarkup(writer.getLineSeparator());
      +                    for (int i = 0; i < writer.getDepth(); i++) {
      +                        writer.writeMarkup(writer.getLineIndenter());
                           }
                       }
      -                writer.writeMarkup( "" );
      -                if ( !hasTag )
      -                {
      -                    writer.writeMarkup( writer.getLineSeparator() );
      -                    for ( int i = 0; i < writer.getDepth() - 1; i++ )
      -                    {
      -                        writer.writeMarkup( writer.getLineIndenter() );
      +                writer.writeMarkup("");
      +                if (!hasTag) {
      +                    writer.writeMarkup(writer.getLineSeparator());
      +                    for (int i = 0; i < writer.getDepth() - 1; i++) {
      +                        writer.writeMarkup(writer.getLineIndenter());
                           }
                       }
      -            }
      -            else if ( eventType == XmlPullParser.DOCDECL )
      -            {
      -                writer.writeMarkup( "" );
      +            } else if (eventType == XmlPullParser.DOCDECL) {
      +                writer.writeMarkup("");
                       writer.endOfLine();
      -            }
      -            else if ( eventType == XmlPullParser.PROCESSING_INSTRUCTION )
      -            {
      -                writer.writeMarkup( "" );
      +            } else if (eventType == XmlPullParser.PROCESSING_INSTRUCTION) {
      +                writer.writeMarkup("");
                       writer.endOfLine();
      -            }
      -            else if ( eventType == XmlPullParser.CDSECT )
      -            {
      -                writer.writeMarkup( "" );
      -            }
      -            else if ( eventType == XmlPullParser.ENTITY_REF )
      -            {
      -                writer.writeMarkup( "&" + parser.getName() + ";" );
      +            } else if (eventType == XmlPullParser.CDSECT) {
      +                writer.writeMarkup("");
      +            } else if (eventType == XmlPullParser.ENTITY_REF) {
      +                writer.writeMarkup("&" + parser.getName() + ";");
                   }
       
                   eventType = parser.nextToken();
      diff --git a/src/main/java/org/codehaus/plexus/util/xml/XmlWriterUtil.java b/src/main/java/org/codehaus/plexus/util/xml/XmlWriterUtil.java
      index 22527a1b..024482e3 100644
      --- a/src/main/java/org/codehaus/plexus/util/xml/XmlWriterUtil.java
      +++ b/src/main/java/org/codehaus/plexus/util/xml/XmlWriterUtil.java
      @@ -24,10 +24,9 @@
        * @author Vincent Siveton
        *
        */
      -public class XmlWriterUtil
      -{
      +public class XmlWriterUtil {
           /** The vm line separator */
      -    public static final String LS = System.getProperty( "line.separator" );
      +    public static final String LS = System.getProperty("line.separator");
       
           /** The default line indenter size i.e. 2. */
           public static final int DEFAULT_INDENTATION_SIZE = 2;
      @@ -40,9 +39,8 @@ public class XmlWriterUtil
            *
            * @param writer not null writer
            */
      -    public static void writeLineBreak( XMLWriter writer )
      -    {
      -        writeLineBreak( writer, 1 );
      +    public static void writeLineBreak(XMLWriter writer) {
      +        writeLineBreak(writer, 1);
           }
       
           /**
      @@ -51,11 +49,9 @@ public static void writeLineBreak( XMLWriter writer )
            * @param writer not null
            * @param repeat positive number
            */
      -    public static void writeLineBreak( XMLWriter writer, int repeat )
      -    {
      -        for ( int i = 0; i < repeat; i++ )
      -        {
      -            writer.writeMarkup( LS );
      +    public static void writeLineBreak(XMLWriter writer, int repeat) {
      +        for (int i = 0; i < repeat; i++) {
      +            writer.writeMarkup(LS);
               }
           }
       
      @@ -68,9 +64,8 @@ public static void writeLineBreak( XMLWriter writer, int repeat )
            * @see #DEFAULT_INDENTATION_SIZE
            * @see #writeLineBreak(XMLWriter, int, int, int)
            */
      -    public static void writeLineBreak( XMLWriter writer, int repeat, int indent )
      -    {
      -        writeLineBreak( writer, repeat, indent, DEFAULT_INDENTATION_SIZE );
      +    public static void writeLineBreak(XMLWriter writer, int repeat, int indent) {
      +        writeLineBreak(writer, repeat, indent, DEFAULT_INDENTATION_SIZE);
           }
       
           /**
      @@ -81,21 +76,18 @@ public static void writeLineBreak( XMLWriter writer, int repeat, int indent )
            * @param indent positive number
            * @param indentSize positive number
            */
      -    public static void writeLineBreak( XMLWriter writer, int repeat, int indent, int indentSize )
      -    {
      -        writeLineBreak( writer, repeat );
      +    public static void writeLineBreak(XMLWriter writer, int repeat, int indent, int indentSize) {
      +        writeLineBreak(writer, repeat);
       
      -        if ( indent < 0 )
      -        {
      +        if (indent < 0) {
                   indent = 0;
               }
       
      -        if ( indentSize < 0 )
      -        {
      +        if (indentSize < 0) {
                   indentSize = 0;
               }
       
      -        writer.writeText( StringUtils.repeat( " ", indent * indentSize ) );
      +        writer.writeText(StringUtils.repeat(" ", indent * indentSize));
           }
       
           /**
      @@ -105,9 +97,8 @@ public static void writeLineBreak( XMLWriter writer, int repeat, int indent, int
            * @see #DEFAULT_COLUMN_LINE
            * @see #writeCommentLineBreak(XMLWriter, int)
            */
      -    public static void writeCommentLineBreak( XMLWriter writer )
      -    {
      -        writeCommentLineBreak( writer, DEFAULT_COLUMN_LINE );
      +    public static void writeCommentLineBreak(XMLWriter writer) {
      +        writeCommentLineBreak(writer, DEFAULT_COLUMN_LINE);
           }
       
           /**
      @@ -116,14 +107,12 @@ public static void writeCommentLineBreak( XMLWriter writer )
            * @param writer not null
            * @param columnSize positive number
            */
      -    public static void writeCommentLineBreak( XMLWriter writer, int columnSize )
      -    {
      -        if ( columnSize < 10 )
      -        {
      +    public static void writeCommentLineBreak(XMLWriter writer, int columnSize) {
      +        if (columnSize < 10) {
                   columnSize = DEFAULT_COLUMN_LINE;
               }
       
      -        writer.writeMarkup( "" + LS );
      +        writer.writeMarkup("" + LS);
           }
       
           /**
      @@ -135,9 +124,8 @@ public static void writeCommentLineBreak( XMLWriter writer, int columnSize )
            * @see #DEFAULT_INDENTATION_SIZE
            * @see #writeComment(XMLWriter, String, int, int)
            */
      -    public static void writeComment( XMLWriter writer, String comment )
      -    {
      -        writeComment( writer, comment, 0, DEFAULT_INDENTATION_SIZE );
      +    public static void writeComment(XMLWriter writer, String comment) {
      +        writeComment(writer, comment, 0, DEFAULT_INDENTATION_SIZE);
           }
       
           /**
      @@ -150,9 +138,8 @@ public static void writeComment( XMLWriter writer, String comment )
            * @see #DEFAULT_INDENTATION_SIZE
            * @see #writeComment(XMLWriter, String, int, int)
            */
      -    public static void writeComment( XMLWriter writer, String comment, int indent )
      -    {
      -        writeComment( writer, comment, indent, DEFAULT_INDENTATION_SIZE );
      +    public static void writeComment(XMLWriter writer, String comment, int indent) {
      +        writeComment(writer, comment, indent, DEFAULT_INDENTATION_SIZE);
           }
       
           /**
      @@ -166,9 +153,8 @@ public static void writeComment( XMLWriter writer, String comment, int indent )
            * @see #DEFAULT_COLUMN_LINE
            * @see #writeComment(XMLWriter, String, int, int, int)
            */
      -    public static void writeComment( XMLWriter writer, String comment, int indent, int indentSize )
      -    {
      -        writeComment( writer, comment, indent, indentSize, DEFAULT_COLUMN_LINE );
      +    public static void writeComment(XMLWriter writer, String comment, int indent, int indentSize) {
      +        writeComment(writer, comment, indent, indentSize, DEFAULT_COLUMN_LINE);
           }
       
           /**
      @@ -181,85 +167,69 @@ public static void writeComment( XMLWriter writer, String comment, int indent, i
            * @param indentSize positive number
            * @param columnSize positive number
            */
      -    public static void writeComment( XMLWriter writer, String comment, int indent, int indentSize, int columnSize )
      -    {
      -        if ( comment == null )
      -        {
      +    public static void writeComment(XMLWriter writer, String comment, int indent, int indentSize, int columnSize) {
      +        if (comment == null) {
                   comment = "null";
               }
       
      -        while ( comment.contains( "" ) )
      -        {
      -            comment = comment.replace( "-->", "" );
      +        while (comment.contains("-->")) {
      +            comment = comment.replace("-->", "");
               }
       
      -        if ( indent < 0 )
      -        {
      +        if (indent < 0) {
                   indent = 0;
               }
       
      -        if ( indentSize < 0 )
      -        {
      +        if (indentSize < 0) {
                   indentSize = 0;
               }
       
      -        if ( columnSize < 0 )
      -        {
      +        if (columnSize < 0) {
                   columnSize = DEFAULT_COLUMN_LINE;
               }
       
      -        String indentation = StringUtils.repeat( " ", indent * indentSize );
      +        String indentation = StringUtils.repeat(" ", indent * indentSize);
               int magicNumber = indentation.length() + columnSize - "-->".length() - 1;
      -        String[] sentences = StringUtils.split( comment, LS );
      -
      -        StringBuffer line = new StringBuffer( indentation + "" ).append( LS );
      -                        writer.writeMarkup( line.toString() );
      +                        line.append("-->").append(LS);
      +                        writer.writeMarkup(line.toString());
                           }
      -                    line = new StringBuffer( indentation + "" ).append( LS );
      +        line.append("-->").append(LS);
       
      -        writer.writeMarkup( line.toString() );
      +        writer.writeMarkup(line.toString());
           }
       
           /**
      @@ -270,9 +240,8 @@ public static void writeComment( XMLWriter writer, String comment, int indent, i
            * @see #DEFAULT_INDENTATION_SIZE
            * @see #writeCommentText(XMLWriter, String, int, int)
            */
      -    public static void writeCommentText( XMLWriter writer, String comment )
      -    {
      -        writeCommentText( writer, comment, 0, DEFAULT_INDENTATION_SIZE );
      +    public static void writeCommentText(XMLWriter writer, String comment) {
      +        writeCommentText(writer, comment, 0, DEFAULT_INDENTATION_SIZE);
           }
       
           /**
      @@ -285,9 +254,8 @@ public static void writeCommentText( XMLWriter writer, String comment )
            * @see #DEFAULT_INDENTATION_SIZE
            * @see #writeCommentText(XMLWriter, String, int, int)
            */
      -    public static void writeCommentText( XMLWriter writer, String comment, int indent )
      -    {
      -        writeCommentText( writer, comment, indent, DEFAULT_INDENTATION_SIZE );
      +    public static void writeCommentText(XMLWriter writer, String comment, int indent) {
      +        writeCommentText(writer, comment, indent, DEFAULT_INDENTATION_SIZE);
           }
       
           /**
      @@ -301,9 +269,8 @@ public static void writeCommentText( XMLWriter writer, String comment, int inden
            * @see #DEFAULT_COLUMN_LINE
            * @see #writeCommentText(XMLWriter, String, int, int, int)
            */
      -    public static void writeCommentText( XMLWriter writer, String comment, int indent, int indentSize )
      -    {
      -        writeCommentText( writer, comment, indent, indentSize, DEFAULT_COLUMN_LINE );
      +    public static void writeCommentText(XMLWriter writer, String comment, int indent, int indentSize) {
      +        writeCommentText(writer, comment, indent, indentSize, DEFAULT_COLUMN_LINE);
           }
       
           /**
      @@ -316,33 +283,29 @@ public static void writeCommentText( XMLWriter writer, String comment, int inden
            * @param indentSize positive number
            * @param columnSize positive number
            */
      -    public static void writeCommentText( XMLWriter writer, String comment, int indent, int indentSize, int columnSize )
      -    {
      -        if ( indent < 0 )
      -        {
      +    public static void writeCommentText(XMLWriter writer, String comment, int indent, int indentSize, int columnSize) {
      +        if (indent < 0) {
                   indent = 0;
               }
       
      -        if ( indentSize < 0 )
      -        {
      +        if (indentSize < 0) {
                   indentSize = 0;
               }
       
      -        if ( columnSize < 0 )
      -        {
      +        if (columnSize < 0) {
                   columnSize = DEFAULT_COLUMN_LINE;
               }
       
      -        writeLineBreak( writer, 1 );
      +        writeLineBreak(writer, 1);
       
      -        writer.writeMarkup( StringUtils.repeat( " ", indent * indentSize ) );
      -        writeCommentLineBreak( writer, columnSize );
      +        writer.writeMarkup(StringUtils.repeat(" ", indent * indentSize));
      +        writeCommentLineBreak(writer, columnSize);
       
      -        writeComment( writer, comment, indent, indentSize, columnSize );
      +        writeComment(writer, comment, indent, indentSize, columnSize);
       
      -        writer.writeMarkup( StringUtils.repeat( " ", indent * indentSize ) );
      -        writeCommentLineBreak( writer, columnSize );
      +        writer.writeMarkup(StringUtils.repeat(" ", indent * indentSize));
      +        writeCommentLineBreak(writer, columnSize);
       
      -        writeLineBreak( writer, 1, indent, indentSize );
      +        writeLineBreak(writer, 1, indent, indentSize);
           }
       }
      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 f6e46b46..fb358847 100644
      --- a/src/main/java/org/codehaus/plexus/util/xml/Xpp3Dom.java
      +++ b/src/main/java/org/codehaus/plexus/util/xml/Xpp3Dom.java
      @@ -16,9 +16,6 @@
        * limitations under the License.
        */
       
      -import org.codehaus.plexus.util.StringUtils;
      -import org.codehaus.plexus.util.xml.pull.XmlSerializer;
      -
       import java.io.IOException;
       import java.io.Serializable;
       import java.io.StringWriter;
      @@ -30,12 +27,13 @@
       import java.util.ListIterator;
       import java.util.Map;
       
      +import org.codehaus.plexus.util.StringUtils;
      +import org.codehaus.plexus.util.xml.pull.XmlSerializer;
      +
       /**
        *  NOTE: remove all the util code in here when separated, this class should be pure data.
        */
      -public class Xpp3Dom
      -    implements Serializable
      -{
      +public class Xpp3Dom implements Serializable {
           private static final long serialVersionUID = 2567894443061173996L;
       
           protected String name;
      @@ -86,8 +84,7 @@ public class Xpp3Dom
            */
           public static final String DEFAULT_SELF_COMBINATION_MODE = SELF_COMBINATION_MERGE;
       
      -    public Xpp3Dom( String name )
      -    {
      +    public Xpp3Dom(String name) {
               this.name = name;
               childList = new ArrayList<>();
           }
      @@ -97,9 +94,8 @@ public Xpp3Dom( String name )
            * @param inputLocation The input location.
            * @param name The name of the Dom.
            */
      -    public Xpp3Dom( String name, Object inputLocation )
      -    {
      -        this( name );
      +    public Xpp3Dom(String name, Object inputLocation) {
      +        this(name);
               this.inputLocation = inputLocation;
           }
       
      @@ -107,9 +103,8 @@ public Xpp3Dom( String name, Object inputLocation )
            * Copy constructor.
            * @param src The source Dom.
            */
      -    public Xpp3Dom( Xpp3Dom src )
      -    {
      -        this( src, src.getName() );
      +    public Xpp3Dom(Xpp3Dom src) {
      +        this(src, src.getName());
           }
       
           /**
      @@ -117,26 +112,23 @@ public Xpp3Dom( Xpp3Dom src )
            * @param src The source Dom.
            * @param name The name of the Dom.
            */
      -    public Xpp3Dom( Xpp3Dom src, String name )
      -    {
      +    public Xpp3Dom(Xpp3Dom src, String name) {
               this.name = name;
               this.inputLocation = src.inputLocation;
       
               int childCount = src.getChildCount();
       
      -        childList = new ArrayList( childCount );
      +        childList = new ArrayList(childCount);
       
      -        setValue( src.getValue() );
      +        setValue(src.getValue());
       
               String[] attributeNames = src.getAttributeNames();
      -        for ( String attributeName : attributeNames )
      -        {
      -            setAttribute( attributeName, src.getAttribute( attributeName ) );
      +        for (String attributeName : attributeNames) {
      +            setAttribute(attributeName, src.getAttribute(attributeName));
               }
       
      -        for ( int i = 0; i < childCount; i++ )
      -        {
      -            addChild( new Xpp3Dom( src.getChild( i ) ) );
      +        for (int i = 0; i < childCount; i++) {
      +            addChild(new Xpp3Dom(src.getChild(i)));
               }
           }
       
      @@ -144,8 +136,7 @@ public Xpp3Dom( Xpp3Dom src, String name )
           // Name handling
           // ----------------------------------------------------------------------
       
      -    public String getName()
      -    {
      +    public String getName() {
               return name;
           }
       
      @@ -153,13 +144,11 @@ public String getName()
           // Value handling
           // ----------------------------------------------------------------------
       
      -    public String getValue()
      -    {
      +    public String getValue() {
               return value;
           }
       
      -    public void setValue( String value )
      -    {
      +    public void setValue(String value) {
               this.value = value;
           }
       
      @@ -167,21 +156,16 @@ public void setValue( String value )
           // Attribute handling
           // ----------------------------------------------------------------------
       
      -    public String[] getAttributeNames()
      -    {
      -        if ( null == attributes || attributes.isEmpty() )
      -        {
      +    public String[] getAttributeNames() {
      +        if (null == attributes || attributes.isEmpty()) {
                   return EMPTY_STRING_ARRAY;
      -        }
      -        else
      -        {
      -            return attributes.keySet().toArray( EMPTY_STRING_ARRAY );
      +        } else {
      +            return attributes.keySet().toArray(EMPTY_STRING_ARRAY);
               }
           }
       
      -    public String getAttribute( String name )
      -    {
      -        return ( null != attributes ) ? attributes.get( name ) : null;
      +    public String getAttribute(String name) {
      +        return (null != attributes) ? attributes.get(name) : null;
           }
       
           /**
      @@ -190,54 +174,44 @@ public String getAttribute( String name )
            * @return true if the attribute has been removed
            * @since 3.4.0
            */
      -    public boolean removeAttribute( String name )
      -    {
      -        return StringUtils.isEmpty( name ) ? false: attributes.remove( name ) == null;
      +    public boolean removeAttribute(String name) {
      +        return StringUtils.isEmpty(name) ? false : attributes.remove(name) == null;
           }
       
           /**
            * Set the attribute value
      -     * 
      +     *
            * @param name String not null
            * @param value String not null
            */
      -    public void setAttribute( String name, String value )
      -    {
      -        if ( null == value )
      -        {
      -            throw new NullPointerException( "Attribute value can not be null" );
      +    public void setAttribute(String name, String value) {
      +        if (null == value) {
      +            throw new NullPointerException("Attribute value can not be null");
               }
      -        if ( null == name )
      -        {
      -            throw new NullPointerException( "Attribute name can not be null" );
      +        if (null == name) {
      +            throw new NullPointerException("Attribute name can not be null");
               }
      -        if ( null == attributes )
      -        {
      +        if (null == attributes) {
                   attributes = new HashMap();
               }
       
      -        attributes.put( name, value );
      +        attributes.put(name, value);
           }
       
           // ----------------------------------------------------------------------
           // Child handling
           // ----------------------------------------------------------------------
       
      -    public Xpp3Dom getChild( int i )
      -    {
      -        return childList.get( i );
      +    public Xpp3Dom getChild(int i) {
      +        return childList.get(i);
           }
       
      -    public Xpp3Dom getChild( String name )
      -    {
      -        if ( name != null )
      -        {
      -            ListIterator it = childList.listIterator( childList.size() );
      -            while ( it.hasPrevious() )
      -            {
      +    public Xpp3Dom getChild(String name) {
      +        if (name != null) {
      +            ListIterator it = childList.listIterator(childList.size());
      +            while (it.hasPrevious()) {
                       Xpp3Dom child = it.previous();
      -                if ( name.equals( child.getName() ) )
      -                {
      +                if (name.equals(child.getName())) {
                           return child;
                       }
                   }
      @@ -245,98 +219,76 @@ public Xpp3Dom getChild( String name )
               return null;
           }
       
      -    public void addChild( Xpp3Dom xpp3Dom )
      -    {
      -        xpp3Dom.setParent( this );
      -        childList.add( xpp3Dom );
      +    public void addChild(Xpp3Dom xpp3Dom) {
      +        xpp3Dom.setParent(this);
      +        childList.add(xpp3Dom);
           }
       
      -    public Xpp3Dom[] getChildren()
      -    {
      -        if ( null == childList || childList.isEmpty() )
      -        {
      +    public Xpp3Dom[] getChildren() {
      +        if (null == childList || childList.isEmpty()) {
                   return EMPTY_DOM_ARRAY;
      -        }
      -        else
      -        {
      -            return childList.toArray( EMPTY_DOM_ARRAY );
      +        } else {
      +            return childList.toArray(EMPTY_DOM_ARRAY);
               }
           }
       
      -    public Xpp3Dom[] getChildren( String name )
      -    {
      -        return getChildrenAsList( name ).toArray( EMPTY_DOM_ARRAY );
      +    public Xpp3Dom[] getChildren(String name) {
      +        return getChildrenAsList(name).toArray(EMPTY_DOM_ARRAY);
           }
       
      -    private List getChildrenAsList( String name )
      -    {
      -        if ( null == childList )
      -        {
      +    private List getChildrenAsList(String name) {
      +        if (null == childList) {
                   return Collections.emptyList();
      -        }
      -        else
      -        {
      +        } else {
                   ArrayList children = null;
       
      -            for ( Xpp3Dom configuration : childList )
      -            {
      -                if ( name.equals( configuration.getName() ) )
      -                {
      -                    if ( children == null )
      -                    {
      +            for (Xpp3Dom configuration : childList) {
      +                if (name.equals(configuration.getName())) {
      +                    if (children == null) {
                               children = new ArrayList();
                           }
      -                    children.add( configuration );
      +                    children.add(configuration);
                       }
                   }
       
      -            if ( children != null )
      -            {
      +            if (children != null) {
                       return children;
      -            }
      -            else
      -            {
      +            } else {
                       return Collections.emptyList();
                   }
               }
           }
       
      -    public int getChildCount()
      -    {
      -        if ( null == childList )
      -        {
      +    public int getChildCount() {
      +        if (null == childList) {
                   return 0;
               }
       
               return childList.size();
           }
       
      -    public void removeChild( int i )
      -    {
      -        Xpp3Dom child = getChild( i );
      -        childList.remove( i );
      +    public void removeChild(int i) {
      +        Xpp3Dom child = getChild(i);
      +        childList.remove(i);
               // In case of any dangling references
      -        child.setParent( null );
      +        child.setParent(null);
           }
       
      -    public void removeChild( Xpp3Dom child )
      -    {
      -        childList.remove( child );
      +    public void removeChild(Xpp3Dom child) {
      +        childList.remove(child);
               // In case of any dangling references
      -        child.setParent( null );
      +        child.setParent(null);
           }
       
           // ----------------------------------------------------------------------
           // Parent handling
           // ----------------------------------------------------------------------
       
      -    public Xpp3Dom getParent()
      -    {
      +    public Xpp3Dom getParent() {
               return parent;
           }
       
      -    public void setParent( Xpp3Dom parent )
      -    {
      +    public void setParent(Xpp3Dom parent) {
               this.parent = parent;
           }
       
      @@ -348,8 +300,7 @@ public void setParent( Xpp3Dom parent )
            * @since 3.2.0
            * @return input location
            */
      -    public Object getInputLocation()
      -    {
      +    public Object getInputLocation() {
               return inputLocation;
           }
       
      @@ -357,8 +308,7 @@ public Object getInputLocation()
            * @since 3.2.0
            * @param inputLocation input location to set
            */
      -    public void setInputLocation( Object inputLocation )
      -    {
      +    public void setInputLocation(Object inputLocation) {
               this.inputLocation = inputLocation;
           }
       
      @@ -366,16 +316,13 @@ public void setInputLocation( Object inputLocation )
           // Helpers
           // ----------------------------------------------------------------------
       
      -    public void writeToSerializer( String namespace, XmlSerializer serializer )
      -        throws IOException
      -    {
      +    public void writeToSerializer(String namespace, XmlSerializer serializer) throws IOException {
               // TODO: WARNING! Later versions of plexus-utils psit out an  header due to thinking this is a new
               // document - not the desired behaviour!
      -        SerializerXMLWriter xmlWriter = new SerializerXMLWriter( namespace, serializer );
      -        Xpp3DomWriter.write( xmlWriter, this );
      -        if ( xmlWriter.getExceptions().size() > 0 )
      -        {
      -            throw (IOException) xmlWriter.getExceptions().get( 0 );
      +        SerializerXMLWriter xmlWriter = new SerializerXMLWriter(namespace, serializer);
      +        Xpp3DomWriter.write(xmlWriter, this);
      +        if (xmlWriter.getExceptions().size() > 0) {
      +            throw (IOException) xmlWriter.getExceptions().get(0);
               }
           }
       
      @@ -416,116 +363,88 @@ public void writeToSerializer( String namespace, XmlSerializer serializer )
            *   
            * 
            */
      -    private static void mergeIntoXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive, Boolean childMergeOverride )
      -    {
      +    private static void mergeIntoXpp3Dom(Xpp3Dom dominant, Xpp3Dom recessive, Boolean childMergeOverride) {
               // TODO: share this as some sort of assembler, implement a walk interface?
      -        if ( recessive == null )
      -        {
      +        if (recessive == null) {
                   return;
               }
       
               boolean mergeSelf = true;
       
      -        String selfMergeMode = dominant.getAttribute( SELF_COMBINATION_MODE_ATTRIBUTE );
      +        String selfMergeMode = dominant.getAttribute(SELF_COMBINATION_MODE_ATTRIBUTE);
       
      -        if ( SELF_COMBINATION_OVERRIDE.equals( selfMergeMode ) )
      -        {
      +        if (SELF_COMBINATION_OVERRIDE.equals(selfMergeMode)) {
                   mergeSelf = false;
               }
       
      -        if ( mergeSelf )
      -        {
      -            if ( isEmpty( dominant.getValue() ) && !isEmpty( recessive.getValue() ) )
      -            {
      -                dominant.setValue( recessive.getValue() );
      -                dominant.setInputLocation( recessive.getInputLocation() );
      +        if (mergeSelf) {
      +            if (isEmpty(dominant.getValue()) && !isEmpty(recessive.getValue())) {
      +                dominant.setValue(recessive.getValue());
      +                dominant.setInputLocation(recessive.getInputLocation());
                   }
       
      -            if ( recessive.attributes != null )
      -            {
      -                for ( String attr : recessive.attributes.keySet() )
      -                {
      -                    if ( isEmpty( dominant.getAttribute( attr ) ) )
      -                    {
      -                        dominant.setAttribute( attr, recessive.getAttribute( attr ) );
      +            if (recessive.attributes != null) {
      +                for (String attr : recessive.attributes.keySet()) {
      +                    if (isEmpty(dominant.getAttribute(attr))) {
      +                        dominant.setAttribute(attr, recessive.getAttribute(attr));
                           }
                       }
                   }
       
      -            if ( recessive.getChildCount() > 0 )
      -            {
      +            if (recessive.getChildCount() > 0) {
                       boolean mergeChildren = true;
       
      -                if ( childMergeOverride != null )
      -                {
      +                if (childMergeOverride != null) {
                           mergeChildren = childMergeOverride;
      -                }
      -                else
      -                {
      -                    String childMergeMode = dominant.getAttribute( CHILDREN_COMBINATION_MODE_ATTRIBUTE );
      +                } else {
      +                    String childMergeMode = dominant.getAttribute(CHILDREN_COMBINATION_MODE_ATTRIBUTE);
       
      -                    if ( CHILDREN_COMBINATION_APPEND.equals( childMergeMode ) )
      -                    {
      +                    if (CHILDREN_COMBINATION_APPEND.equals(childMergeMode)) {
                               mergeChildren = false;
                           }
                       }
       
      -                if ( !mergeChildren )
      -                {
      +                if (!mergeChildren) {
                           Xpp3Dom[] dominantChildren = dominant.getChildren();
                           // remove these now, so we can append them to the recessive list later.
                           dominant.childList.clear();
       
      -                    for ( int i = 0, recessiveChildCount = recessive.getChildCount(); i < recessiveChildCount; i++ )
      -                    {
      -                        Xpp3Dom recessiveChild = recessive.getChild( i );
      -                        dominant.addChild( new Xpp3Dom( recessiveChild ) );
      +                    for (int i = 0, recessiveChildCount = recessive.getChildCount(); i < recessiveChildCount; i++) {
      +                        Xpp3Dom recessiveChild = recessive.getChild(i);
      +                        dominant.addChild(new Xpp3Dom(recessiveChild));
                           }
       
                           // now, re-add these children so they'll be appended to the recessive list.
      -                    for ( Xpp3Dom aDominantChildren : dominantChildren )
      -                    {
      -                        dominant.addChild( aDominantChildren );
      +                    for (Xpp3Dom aDominantChildren : dominantChildren) {
      +                        dominant.addChild(aDominantChildren);
                           }
      -                }
      -                else
      -                {
      +                } else {
                           Map> commonChildren = new HashMap>();
       
      -                    for ( Xpp3Dom recChild : recessive.childList )
      -                    {
      -                        if ( commonChildren.containsKey( recChild.name ) )
      -                        {
      +                    for (Xpp3Dom recChild : recessive.childList) {
      +                        if (commonChildren.containsKey(recChild.name)) {
                                   continue;
                               }
      -                        List dominantChildren = dominant.getChildrenAsList( recChild.name );
      -                        if ( dominantChildren.size() > 0 )
      -                        {
      -                            commonChildren.put( recChild.name, dominantChildren.iterator() );
      +                        List dominantChildren = dominant.getChildrenAsList(recChild.name);
      +                        if (dominantChildren.size() > 0) {
      +                            commonChildren.put(recChild.name, dominantChildren.iterator());
                               }
                           }
       
      -                    for ( int i = 0, recessiveChildCount = recessive.getChildCount(); i < recessiveChildCount; i++ )
      -                    {
      -                        Xpp3Dom recessiveChild = recessive.getChild( i );
      -                        Iterator it = commonChildren.get( recessiveChild.getName() );
      -                        if ( it == null )
      -                        {
      -                            dominant.addChild( new Xpp3Dom( recessiveChild ) );
      -                        }
      -                        else if ( it.hasNext() )
      -                        {
      +                    for (int i = 0, recessiveChildCount = recessive.getChildCount(); i < recessiveChildCount; i++) {
      +                        Xpp3Dom recessiveChild = recessive.getChild(i);
      +                        Iterator it = commonChildren.get(recessiveChild.getName());
      +                        if (it == null) {
      +                            dominant.addChild(new Xpp3Dom(recessiveChild));
      +                        } else if (it.hasNext()) {
                                   Xpp3Dom dominantChild = it.next();
       
                                   String dominantChildCombinationMode =
      -                                dominantChild.getAttribute( SELF_COMBINATION_MODE_ATTRIBUTE );
      -                            if ( SELF_COMBINATION_REMOVE.equals( dominantChildCombinationMode ) )
      -                            {
      -                                dominant.removeChild( dominantChild );
      -                            }
      -                            else
      -                            {
      -                                mergeIntoXpp3Dom( dominantChild, recessiveChild, childMergeOverride );
      +                                    dominantChild.getAttribute(SELF_COMBINATION_MODE_ATTRIBUTE);
      +                            if (SELF_COMBINATION_REMOVE.equals(dominantChildCombinationMode)) {
      +                                dominant.removeChild(dominantChild);
      +                            } else {
      +                                mergeIntoXpp3Dom(dominantChild, recessiveChild, childMergeOverride);
                                   }
                               }
                           }
      @@ -545,11 +464,9 @@ else if ( it.hasNext() )
            *            dominant DOM
            * @return merged DOM
            */
      -    public static Xpp3Dom mergeXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive, Boolean childMergeOverride )
      -    {
      -        if ( dominant != null )
      -        {
      -            mergeIntoXpp3Dom( dominant, recessive, childMergeOverride );
      +    public static Xpp3Dom mergeXpp3Dom(Xpp3Dom dominant, Xpp3Dom recessive, Boolean childMergeOverride) {
      +        if (dominant != null) {
      +            mergeIntoXpp3Dom(dominant, recessive, childMergeOverride);
                   return dominant;
               }
               return recessive;
      @@ -565,11 +482,9 @@ public static Xpp3Dom mergeXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive, Boolean
            * @param recessive The recessive DOM, which will be merged into the dominant DOM
            * @return merged DOM
            */
      -    public static Xpp3Dom mergeXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive )
      -    {
      -        if ( dominant != null )
      -        {
      -            mergeIntoXpp3Dom( dominant, recessive, null );
      +    public static Xpp3Dom mergeXpp3Dom(Xpp3Dom dominant, Xpp3Dom recessive) {
      +        if (dominant != null) {
      +            mergeIntoXpp3Dom(dominant, recessive, null);
                   return dominant;
               }
               return recessive;
      @@ -580,82 +495,64 @@ public static Xpp3Dom mergeXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive )
           // ----------------------------------------------------------------------
       
           @Override
      -    public boolean equals( Object obj )
      -    {
      -        if ( obj == this )
      -        {
      +    public boolean equals(Object obj) {
      +        if (obj == this) {
                   return true;
               }
       
      -        if ( !( obj instanceof Xpp3Dom ) )
      -        {
      +        if (!(obj instanceof Xpp3Dom)) {
                   return false;
               }
       
               Xpp3Dom dom = (Xpp3Dom) obj;
       
      -        if ( name == null ? dom.name != null : !name.equals( dom.name ) )
      -        {
      +        if (name == null ? dom.name != null : !name.equals(dom.name)) {
                   return false;
      -        }
      -        else if ( value == null ? dom.value != null : !value.equals( dom.value ) )
      -        {
      +        } else if (value == null ? dom.value != null : !value.equals(dom.value)) {
                   return false;
      -        }
      -        else if ( attributes == null ? dom.attributes != null : !attributes.equals( dom.attributes ) )
      -        {
      +        } else if (attributes == null ? dom.attributes != null : !attributes.equals(dom.attributes)) {
                   return false;
      -        }
      -        else if ( childList == null ? dom.childList != null : !childList.equals( dom.childList ) )
      -        {
      +        } else if (childList == null ? dom.childList != null : !childList.equals(dom.childList)) {
                   return false;
      -        }
      -        else
      -        {
      +        } else {
                   return true;
               }
           }
       
           @Override
      -    public int hashCode()
      -    {
      +    public int hashCode() {
               int result = 17;
      -        result = 37 * result + ( name != null ? name.hashCode() : 0 );
      -        result = 37 * result + ( value != null ? value.hashCode() : 0 );
      -        result = 37 * result + ( attributes != null ? attributes.hashCode() : 0 );
      -        result = 37 * result + ( childList != null ? childList.hashCode() : 0 );
      +        result = 37 * result + (name != null ? name.hashCode() : 0);
      +        result = 37 * result + (value != null ? value.hashCode() : 0);
      +        result = 37 * result + (attributes != null ? attributes.hashCode() : 0);
      +        result = 37 * result + (childList != null ? childList.hashCode() : 0);
               return result;
           }
       
           @Override
      -    public String toString()
      -    {
      +    public String toString() {
               // TODO: WARNING! Later versions of plexus-utils psit out an  header due to thinking this is a new
               // document - not the desired behaviour!
               StringWriter writer = new StringWriter();
      -        XMLWriter xmlWriter = new PrettyPrintXMLWriter( writer, "UTF-8", null );
      -        Xpp3DomWriter.write( xmlWriter, this );
      +        XMLWriter xmlWriter = new PrettyPrintXMLWriter(writer, "UTF-8", null);
      +        Xpp3DomWriter.write(xmlWriter, this);
               return writer.toString();
           }
       
      -    public String toUnescapedString()
      -    {
      +    public String toUnescapedString() {
               // TODO: WARNING! Later versions of plexus-utils psit out an  header due to thinking this is a new
               // document - not the desired behaviour!
               StringWriter writer = new StringWriter();
      -        XMLWriter xmlWriter = new PrettyPrintXMLWriter( writer, "UTF-8", null );
      -        Xpp3DomWriter.write( xmlWriter, this, false );
      +        XMLWriter xmlWriter = new PrettyPrintXMLWriter(writer, "UTF-8", null);
      +        Xpp3DomWriter.write(xmlWriter, this, false);
               return writer.toString();
           }
       
      -    public static boolean isNotEmpty( String str )
      -    {
      -        return ( ( str != null ) && ( str.length() > 0 ) );
      +    public static boolean isNotEmpty(String str) {
      +        return ((str != null) && (str.length() > 0));
           }
       
      -    public static boolean isEmpty( String str )
      -    {
      -        return ( ( str == null ) || ( str.trim().length() == 0 ) );
      +    public static boolean isEmpty(String str) {
      +        return ((str == null) || (str.trim().length() == 0));
           }
      -
       }
      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 6749dd25..c22eafdc 100644
      --- a/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomBuilder.java
      +++ b/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomBuilder.java
      @@ -16,28 +16,25 @@
        * limitations under the License.
        */
       
      -import org.codehaus.plexus.util.IOUtil;
      -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 java.io.IOException;
       import java.io.InputStream;
       import java.io.Reader;
       import java.util.ArrayList;
       import java.util.List;
       
      +import org.codehaus.plexus.util.IOUtil;
      +import org.codehaus.plexus.util.xml.pull.MXParser;
      +import org.codehaus.plexus.util.xml.pull.XmlPullParser;
      +import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
      +
       /**
        *
        */
      -public class Xpp3DomBuilder
      -{
      +public class Xpp3DomBuilder {
           private static final boolean DEFAULT_TRIM = true;
       
      -    public static Xpp3Dom build( Reader reader )
      -        throws XmlPullParserException, IOException
      -    {
      -        return build( reader, null );
      +    public static Xpp3Dom build(Reader reader) throws XmlPullParserException, IOException {
      +        return build(reader, null);
           }
       
           /**
      @@ -48,42 +45,33 @@ public static Xpp3Dom build( Reader reader )
            * @throws XmlPullParserException xml exception
            * @throws IOException io
            */
      -    public static Xpp3Dom build( Reader reader, InputLocationBuilder locationBuilder )
      -        throws XmlPullParserException, IOException
      -    {
      -        return build( reader, DEFAULT_TRIM, locationBuilder );
      +    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 )
      -        throws XmlPullParserException, IOException
      -    {
      -        return build( is, encoding, DEFAULT_TRIM );
      +    public static Xpp3Dom build(InputStream is, String encoding) throws XmlPullParserException, IOException {
      +        return build(is, encoding, DEFAULT_TRIM);
           }
       
      -    public static Xpp3Dom build( InputStream is, String encoding, boolean trim )
      -        throws XmlPullParserException, IOException
      -    {
      -        try
      -        {
      +    public static Xpp3Dom build(InputStream is, String encoding, boolean trim)
      +            throws XmlPullParserException, IOException {
      +        try {
                   final XmlPullParser parser = new MXParser();
      -            parser.setInput( is, encoding );
      +            parser.setInput(is, encoding);
       
      -            final Xpp3Dom xpp3Dom = build( parser, trim );
      +            final Xpp3Dom xpp3Dom = build(parser, trim);
                   is.close();
                   is = null;
       
                   return xpp3Dom;
      -        }
      -        finally
      -        {
      -            IOUtil.close( is );
      +        } finally {
      +            IOUtil.close(is);
               }
           }
       
      -    public static Xpp3Dom build( Reader reader, boolean trim )
      -        throws XmlPullParserException, IOException
      -    {
      -        return build( reader, trim, null );
      +    public static Xpp3Dom build(Reader reader, boolean trim) throws XmlPullParserException, IOException {
      +        return build(reader, trim, null);
           }
       
           /**
      @@ -95,36 +83,28 @@ public static Xpp3Dom build( Reader reader, boolean trim )
            * @throws XmlPullParserException xml exception
            * @throws IOException io
            */
      -    public static Xpp3Dom build( Reader reader, boolean trim, InputLocationBuilder locationBuilder )
      -        throws XmlPullParserException, IOException
      -    {
      -        try
      -        {
      +    public static Xpp3Dom build(Reader reader, boolean trim, InputLocationBuilder locationBuilder)
      +            throws XmlPullParserException, IOException {
      +        try {
                   final XmlPullParser parser = new MXParser();
      -            parser.setInput( reader );
      +            parser.setInput(reader);
       
      -            final Xpp3Dom xpp3Dom = build( parser, trim, locationBuilder );
      +            final Xpp3Dom xpp3Dom = build(parser, trim, locationBuilder);
                   reader.close();
                   reader = null;
       
                   return xpp3Dom;
      -        }
      -        finally
      -        {
      -            IOUtil.close( reader );
      +        } finally {
      +            IOUtil.close(reader);
               }
           }
       
      -    public static Xpp3Dom build( XmlPullParser parser )
      -        throws XmlPullParserException, IOException
      -    {
      -        return build( parser, DEFAULT_TRIM );
      +    public static Xpp3Dom build(XmlPullParser parser) throws XmlPullParserException, IOException {
      +        return build(parser, DEFAULT_TRIM);
           }
       
      -    public static Xpp3Dom build( XmlPullParser parser, boolean trim )
      -        throws XmlPullParserException, IOException
      -    {
      -        return build( parser, trim, null );
      +    public static Xpp3Dom build(XmlPullParser parser, boolean trim) throws XmlPullParserException, IOException {
      +        return build(parser, trim, null);
           }
       
           /**
      @@ -136,9 +116,8 @@ public static Xpp3Dom build( XmlPullParser parser, boolean trim )
            * @throws XmlPullParserException xml exception
            * @throws IOException io
            */
      -    public static Xpp3Dom build( XmlPullParser parser, boolean trim, InputLocationBuilder locationBuilder )
      -        throws XmlPullParserException, IOException
      -    {
      +    public static Xpp3Dom build(XmlPullParser parser, boolean trim, InputLocationBuilder locationBuilder)
      +            throws XmlPullParserException, IOException {
               List elements = new ArrayList<>();
       
               List values = new ArrayList<>();
      @@ -147,93 +126,75 @@ public static Xpp3Dom build( XmlPullParser parser, boolean trim, InputLocationBu
       
               boolean spacePreserve = false;
       
      -        while ( eventType != XmlPullParser.END_DOCUMENT )
      -        {
      -            if ( eventType == XmlPullParser.START_TAG )
      -            {
      +        while (eventType != XmlPullParser.END_DOCUMENT) {
      +            if (eventType == XmlPullParser.START_TAG) {
                       spacePreserve = false;
       
                       String rawName = parser.getName();
       
      -                Xpp3Dom childConfiguration = new Xpp3Dom( rawName );
      +                Xpp3Dom childConfiguration = new Xpp3Dom(rawName);
       
      -                if ( locationBuilder != null )
      -                {
      -                    childConfiguration.setInputLocation( locationBuilder.toInputLocation( parser ) );
      +                if (locationBuilder != null) {
      +                    childConfiguration.setInputLocation(locationBuilder.toInputLocation(parser));
                       }
       
                       int depth = elements.size();
       
      -                if ( depth > 0 )
      -                {
      -                    Xpp3Dom parent = elements.get( depth - 1 );
      +                if (depth > 0) {
      +                    Xpp3Dom parent = elements.get(depth - 1);
       
      -                    parent.addChild( childConfiguration );
      +                    parent.addChild(childConfiguration);
                       }
       
      -                elements.add( childConfiguration );
      +                elements.add(childConfiguration);
       
      -                if ( parser.isEmptyElementTag() )
      -                {
      -                    values.add( null );
      -                }
      -                else
      -                {
      -                    values.add( new StringBuilder() );
      +                if (parser.isEmptyElementTag()) {
      +                    values.add(null);
      +                } else {
      +                    values.add(new StringBuilder());
                       }
       
                       int attributesSize = parser.getAttributeCount();
       
      -                for ( int i = 0; i < attributesSize; i++ )
      -                {
      -                    String name = parser.getAttributeName( i );
      +                for (int i = 0; i < attributesSize; i++) {
      +                    String name = parser.getAttributeName(i);
       
      -                    String value = parser.getAttributeValue( i );
      +                    String value = parser.getAttributeValue(i);
       
      -                    childConfiguration.setAttribute( name, value );
      +                    childConfiguration.setAttribute(name, value);
       
      -                    spacePreserve = spacePreserve || ( "xml:space".equals( name ) && "preserve".equals( value ) );
      +                    spacePreserve = spacePreserve || ("xml:space".equals(name) && "preserve".equals(value));
                       }
      -            }
      -            else if ( eventType == XmlPullParser.TEXT )
      -            {
      +            } else if (eventType == XmlPullParser.TEXT) {
                       int depth = values.size() - 1;
       
      -                @SuppressWarnings( "MismatchedQueryAndUpdateOfStringBuilder" )
      -                StringBuilder valueBuffer = values.get( depth );
      +                @SuppressWarnings("MismatchedQueryAndUpdateOfStringBuilder")
      +                StringBuilder valueBuffer = values.get(depth);
       
                       String text = parser.getText();
       
      -                if ( trim && !spacePreserve )
      -                {
      +                if (trim && !spacePreserve) {
                           text = text.trim();
                       }
       
      -                valueBuffer.append( text );
      -            }
      -            else if ( eventType == XmlPullParser.END_TAG )
      -            {
      +                valueBuffer.append(text);
      +            } else if (eventType == XmlPullParser.END_TAG) {
                       int depth = elements.size() - 1;
       
      -                Xpp3Dom finishedConfiguration = elements.remove( depth );
      +                Xpp3Dom finishedConfiguration = elements.remove(depth);
       
                       /* this Object could be null if it is a singleton tag */
      -                Object accumulatedValue = values.remove( depth );
      +                Object accumulatedValue = values.remove(depth);
       
      -                if ( finishedConfiguration.getChildCount() == 0 )
      -                {
      -                    if ( accumulatedValue == null )
      -                    {
      -                        finishedConfiguration.setValue( null );
      -                    }
      -                    else
      -                    {
      -                        finishedConfiguration.setValue( accumulatedValue.toString() );
      +                if (finishedConfiguration.getChildCount() == 0) {
      +                    if (accumulatedValue == null) {
      +                        finishedConfiguration.setValue(null);
      +                    } else {
      +                        finishedConfiguration.setValue(accumulatedValue.toString());
                           }
                       }
       
      -                if ( depth == 0 )
      -                {
      +                if (depth == 0) {
                           return finishedConfiguration;
                       }
                   }
      @@ -241,7 +202,7 @@ else if ( eventType == XmlPullParser.END_TAG )
                   eventType = parser.next();
               }
       
      -        throw new IllegalStateException( "End of document found before returning to 0 depth" );
      +        throw new IllegalStateException("End of document found before returning to 0 depth");
           }
       
           /**
      @@ -249,8 +210,7 @@ else if ( eventType == XmlPullParser.END_TAG )
            *
            * @since 3.2.0
            */
      -    public static interface InputLocationBuilder
      -    {
      -        Object toInputLocation( XmlPullParser parser );
      +    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 555f481e..19203428 100644
      --- a/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomUtils.java
      +++ b/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomUtils.java
      @@ -1,13 +1,9 @@
       package org.codehaus.plexus.util.xml;
       
      -import java.io.IOException;
      -import java.util.HashMap;
      -import java.util.Map;
      -
       /*
        * Copyright The Codehaus Foundation.
        *
      - * Licensed under the Apache License, Version 2.0 (the "License");
      + * Licensed under the Apache cense, Version 2.0 (the "License");
        * you may not use this file except in compliance with the License.
        * You may obtain a copy of the License at
        *
      @@ -19,12 +15,14 @@
        * See the License for the specific language governing permissions and
        * limitations under the License.
        */
      +import java.io.IOException;
      +import java.util.HashMap;
      +import java.util.Map;
       
       import org.codehaus.plexus.util.xml.pull.XmlSerializer;
       
       /** @author Jason van Zyl */
      -public class Xpp3DomUtils
      -{
      +public class Xpp3DomUtils {
           public static final String CHILDREN_COMBINATION_MODE_ATTRIBUTE = "combine.children";
       
           public static final String CHILDREN_COMBINATION_MERGE = "merge";
      @@ -46,15 +44,15 @@ public class Xpp3DomUtils
       
           /**
            * In case of complex XML structures, combining can be done based on id.
      -     * 
      +     *
            * @since 3.0.22
            */
           public static final String ID_COMBINATION_MODE_ATTRIBUTE = "combine.id";
      -    
      +
           /**
            * In case of complex XML structures, combining can be done based on keys.
            * This is a comma separated list of attribute names.
      -     * 
      +     *
            * @since 3.4.0
            */
           public static final String KEYS_COMBINATION_MODE_ATTRIBUTE = "combine.keys";
      @@ -67,16 +65,13 @@ public class Xpp3DomUtils
            */
           public static final String DEFAULT_SELF_COMBINATION_MODE = SELF_COMBINATION_MERGE;
       
      -    public void writeToSerializer( String namespace, XmlSerializer serializer, Xpp3Dom dom )
      -        throws IOException
      -    {
      +    public void writeToSerializer(String namespace, XmlSerializer serializer, Xpp3Dom dom) throws IOException {
               // TODO: WARNING! Later versions of plexus-utils psit out an  header due to thinking this is a new
               // document - not the desired behaviour!
      -        SerializerXMLWriter xmlWriter = new SerializerXMLWriter( namespace, serializer );
      -        Xpp3DomWriter.write( xmlWriter, dom );
      -        if ( xmlWriter.getExceptions().size() > 0 )
      -        {
      -            throw (IOException) xmlWriter.getExceptions().get( 0 );
      +        SerializerXMLWriter xmlWriter = new SerializerXMLWriter(namespace, serializer);
      +        Xpp3DomWriter.write(xmlWriter, dom);
      +        if (xmlWriter.getExceptions().size() > 0) {
      +            throw (IOException) xmlWriter.getExceptions().get(0);
               }
           }
       
      @@ -119,108 +114,83 @@ public void writeToSerializer( String namespace, XmlSerializer serializer, Xpp3D
            *   
            * 
            */
      -    private static void mergeIntoXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive, Boolean childMergeOverride )
      -    {
      +    private static void mergeIntoXpp3Dom(Xpp3Dom dominant, Xpp3Dom recessive, Boolean childMergeOverride) {
               // TODO: share this as some sort of assembler, implement a walk interface?
      -        if ( recessive == null )
      -        {
      +        if (recessive == null) {
                   return;
               }
       
               boolean mergeSelf = true;
       
      -        String selfMergeMode = dominant.getAttribute( SELF_COMBINATION_MODE_ATTRIBUTE );
      +        String selfMergeMode = dominant.getAttribute(SELF_COMBINATION_MODE_ATTRIBUTE);
       
      -        if ( isNotEmpty( selfMergeMode ) && SELF_COMBINATION_OVERRIDE.equals( selfMergeMode ) )
      -        {
      +        if (isNotEmpty(selfMergeMode) && SELF_COMBINATION_OVERRIDE.equals(selfMergeMode)) {
                   mergeSelf = false;
               }
       
      -        if ( mergeSelf )
      -        {
      +        if (mergeSelf) {
                   String[] recessiveAttrs = recessive.getAttributeNames();
      -            for ( String attr : recessiveAttrs )
      -            {
      -                if ( isEmpty( dominant.getAttribute( attr ) ) )
      -                {
      -                    dominant.setAttribute( attr, recessive.getAttribute( attr ) );
      +            for (String attr : recessiveAttrs) {
      +                if (isEmpty(dominant.getAttribute(attr))) {
      +                    dominant.setAttribute(attr, recessive.getAttribute(attr));
                       }
                   }
       
                   boolean mergeChildren = true;
       
      -            if ( childMergeOverride != null )
      -            {
      +            if (childMergeOverride != null) {
                       mergeChildren = childMergeOverride;
      -            }
      -            else
      -            {
      -                String childMergeMode = dominant.getAttribute( CHILDREN_COMBINATION_MODE_ATTRIBUTE );
      +            } else {
      +                String childMergeMode = dominant.getAttribute(CHILDREN_COMBINATION_MODE_ATTRIBUTE);
       
      -                if ( isNotEmpty( childMergeMode ) && CHILDREN_COMBINATION_APPEND.equals( childMergeMode ) )
      -                {
      +                if (isNotEmpty(childMergeMode) && CHILDREN_COMBINATION_APPEND.equals(childMergeMode)) {
                           mergeChildren = false;
                       }
                   }
       
      -            final String keysValue = recessive.getAttribute( KEYS_COMBINATION_MODE_ATTRIBUTE );
      +            final String keysValue = recessive.getAttribute(KEYS_COMBINATION_MODE_ATTRIBUTE);
       
                   Xpp3Dom[] children = recessive.getChildren();
      -            for ( Xpp3Dom recessiveChild : children )
      -            {
      -                String idValue = recessiveChild.getAttribute( ID_COMBINATION_MODE_ATTRIBUTE );
      +            for (Xpp3Dom recessiveChild : children) {
      +                String idValue = recessiveChild.getAttribute(ID_COMBINATION_MODE_ATTRIBUTE);
       
                       Xpp3Dom childDom = null;
      -                if ( isNotEmpty( idValue ) )
      -                {
      -                    for ( Xpp3Dom dominantChild : dominant.getChildren() )
      -                    {
      -                        if ( idValue.equals( dominantChild.getAttribute( ID_COMBINATION_MODE_ATTRIBUTE ) ) )
      -                        {
      +                if (isNotEmpty(idValue)) {
      +                    for (Xpp3Dom dominantChild : dominant.getChildren()) {
      +                        if (idValue.equals(dominantChild.getAttribute(ID_COMBINATION_MODE_ATTRIBUTE))) {
                                   childDom = dominantChild;
                                   // we have a match, so don't append but merge
                                   mergeChildren = true;
                               }
                           }
      -                }
      -                else if ( isNotEmpty( keysValue ) ) 
      -                {
      -                    String[] keys = keysValue.split( "," );
      -                    Map recessiveKeyValues = new HashMap<>( keys.length );
      -                    for ( String key : keys )
      -                    {
      -                        recessiveKeyValues.put( key, recessiveChild.getAttribute( key ) );
      +                } else if (isNotEmpty(keysValue)) {
      +                    String[] keys = keysValue.split(",");
      +                    Map recessiveKeyValues = new HashMap<>(keys.length);
      +                    for (String key : keys) {
      +                        recessiveKeyValues.put(key, recessiveChild.getAttribute(key));
                           }
      -                    
      -                    for ( Xpp3Dom dominantChild : dominant.getChildren() )
      -                    {
      -                        Map dominantKeyValues = new HashMap<>( keys.length );
      -                        for ( String key : keys )
      -                        {
      -                            dominantKeyValues.put( key, dominantChild.getAttribute( key ) );
      +
      +                    for (Xpp3Dom dominantChild : dominant.getChildren()) {
      +                        Map dominantKeyValues = new HashMap<>(keys.length);
      +                        for (String key : keys) {
      +                            dominantKeyValues.put(key, dominantChild.getAttribute(key));
                               }
       
      -                        if ( recessiveKeyValues.equals( dominantKeyValues ) )
      -                        {
      +                        if (recessiveKeyValues.equals(dominantKeyValues)) {
                                   childDom = dominantChild;
                                   // we have a match, so don't append but merge
                                   mergeChildren = true;
                               }
                           }
      -                    
      -                }
      -                else
      -                {
      -                    childDom = dominant.getChild( recessiveChild.getName() );
      -                }
       
      -                if ( mergeChildren && childDom != null )
      -                {
      -                    mergeIntoXpp3Dom( childDom, recessiveChild, childMergeOverride );
      +                } else {
      +                    childDom = dominant.getChild(recessiveChild.getName());
                       }
      -                else
      -                {
      -                    dominant.addChild( new Xpp3Dom( recessiveChild ) );
      +
      +                if (mergeChildren && childDom != null) {
      +                    mergeIntoXpp3Dom(childDom, recessiveChild, childMergeOverride);
      +                } else {
      +                    dominant.addChild(new Xpp3Dom(recessiveChild));
                       }
                   }
               }
      @@ -237,11 +207,9 @@ else if ( isNotEmpty( keysValue ) )
            *            dominant DOM
            * @return merged DOM
            */
      -    public static Xpp3Dom mergeXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive, Boolean childMergeOverride )
      -    {
      -        if ( dominant != null )
      -        {
      -            mergeIntoXpp3Dom( dominant, recessive, childMergeOverride );
      +    public static Xpp3Dom mergeXpp3Dom(Xpp3Dom dominant, Xpp3Dom recessive, Boolean childMergeOverride) {
      +        if (dominant != null) {
      +            mergeIntoXpp3Dom(dominant, recessive, childMergeOverride);
                   return dominant;
               }
               return recessive;
      @@ -257,11 +225,9 @@ public static Xpp3Dom mergeXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive, Boolean
            * @param recessive The recessive DOM, which will be merged into the dominant DOM
            * @return merged DOM
            */
      -    public static Xpp3Dom mergeXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive )
      -    {
      -        if ( dominant != null )
      -        {
      -            mergeIntoXpp3Dom( dominant, recessive, null );
      +    public static Xpp3Dom mergeXpp3Dom(Xpp3Dom dominant, Xpp3Dom recessive) {
      +        if (dominant != null) {
      +            mergeIntoXpp3Dom(dominant, recessive, null);
                   return dominant;
               }
               return recessive;
      @@ -271,17 +237,15 @@ public static Xpp3Dom mergeXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive )
            * @deprecated Use {@link org.codehaus.plexus.util.StringUtils#isNotEmpty(String)} instead
            */
           @Deprecated
      -    public static boolean isNotEmpty( String str )
      -    {
      -        return ( str != null && str.length() > 0 );
      +    public static boolean isNotEmpty(String str) {
      +        return (str != null && str.length() > 0);
           }
       
           /**
            * @deprecated Use {@link org.codehaus.plexus.util.StringUtils#isEmpty(String)} instead
            */
           @Deprecated
      -    public static boolean isEmpty( String str )
      -    {
      -        return ( str == null || str.length() == 0 );
      +    public static boolean isEmpty(String str) {
      +        return (str == null || str.length() == 0);
           }
       }
      diff --git a/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomWriter.java b/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomWriter.java
      index 91770cab..35ecec33 100644
      --- a/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomWriter.java
      +++ b/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomWriter.java
      @@ -22,52 +22,40 @@
       /**
        *
        */
      -public class Xpp3DomWriter
      -{
      -    public static void write( Writer writer, Xpp3Dom dom )
      -    {
      -        write( new PrettyPrintXMLWriter( writer ), dom );
      +public class Xpp3DomWriter {
      +    public static void write(Writer writer, Xpp3Dom dom) {
      +        write(new PrettyPrintXMLWriter(writer), dom);
           }
       
      -    public static void write( PrintWriter writer, Xpp3Dom dom )
      -    {
      -        write( new PrettyPrintXMLWriter( writer ), dom );
      +    public static void write(PrintWriter writer, Xpp3Dom dom) {
      +        write(new PrettyPrintXMLWriter(writer), dom);
           }
       
      -    public static void write( XMLWriter xmlWriter, Xpp3Dom dom )
      -    {
      -        write( xmlWriter, dom, true );
      +    public static void write(XMLWriter xmlWriter, Xpp3Dom dom) {
      +        write(xmlWriter, dom, true);
           }
       
      -    public static void write( XMLWriter xmlWriter, Xpp3Dom dom, boolean escape )
      -    {
      +    public static void write(XMLWriter xmlWriter, Xpp3Dom dom, boolean escape) {
               // TODO: move to XMLWriter?
      -        xmlWriter.startElement( dom.getName() );
      +        xmlWriter.startElement(dom.getName());
               String[] attributeNames = dom.getAttributeNames();
      -        for ( String attributeName : attributeNames )
      -        {
      -            xmlWriter.addAttribute( attributeName, dom.getAttribute( attributeName ) );
      +        for (String attributeName : attributeNames) {
      +            xmlWriter.addAttribute(attributeName, dom.getAttribute(attributeName));
               }
               Xpp3Dom[] children = dom.getChildren();
      -        for ( Xpp3Dom aChildren : children )
      -        {
      -            write( xmlWriter, aChildren, escape );
      +        for (Xpp3Dom aChildren : children) {
      +            write(xmlWriter, aChildren, escape);
               }
       
               String value = dom.getValue();
      -        if ( value != null )
      -        {
      -            if ( escape )
      -            {
      -                xmlWriter.writeText( value );
      -            }
      -            else
      -            {
      -                xmlWriter.writeMarkup( value );
      +        if (value != null) {
      +            if (escape) {
      +                xmlWriter.writeText(value);
      +            } else {
      +                xmlWriter.writeMarkup(value);
                   }
               }
       
               xmlWriter.endElement();
           }
      -
       }
      diff --git a/src/main/java/org/codehaus/plexus/util/xml/pull/EntityReplacementMap.java b/src/main/java/org/codehaus/plexus/util/xml/pull/EntityReplacementMap.java
      index 476cb774..8af68d3a 100644
      --- a/src/main/java/org/codehaus/plexus/util/xml/pull/EntityReplacementMap.java
      +++ b/src/main/java/org/codehaus/plexus/util/xml/pull/EntityReplacementMap.java
      @@ -15,8 +15,7 @@
        * See the License for the specific language governing permissions and
        * limitations under the License.
        */
      -public class EntityReplacementMap
      -{
      +public class EntityReplacementMap {
           final String entityName[];
       
           final char[] entityNameBuf[];
      @@ -29,8 +28,7 @@ public class EntityReplacementMap
       
           final int entityNameHash[];
       
      -    public EntityReplacementMap( String[][] replacements )
      -    {
      +    public EntityReplacementMap(String[][] replacements) {
               int length = replacements.length;
               entityName = new String[length];
               entityNameBuf = new char[length][];
      @@ -38,21 +36,16 @@ public EntityReplacementMap( String[][] replacements )
               entityReplacementBuf = new char[length][];
               entityNameHash = new int[length];
       
      -        for ( String[] replacement : replacements )
      -        {
      -            defineEntityReplacementText( replacement[0], replacement[1] );
      +        for (String[] replacement : replacements) {
      +            defineEntityReplacementText(replacement[0], replacement[1]);
               }
           }
       
      -    private void defineEntityReplacementText( String entityName, String replacementText )
      -    {
      -        if ( !replacementText.startsWith( "&#" ) && this.entityName != null && replacementText.length() > 1 )
      -        {
      -            String tmp = replacementText.substring( 1, replacementText.length() - 1 );
      -            for ( int i = 0; i < this.entityName.length; i++ )
      -            {
      -                if ( this.entityName[i] != null && this.entityName[i].equals( tmp ) )
      -                {
      +    private void defineEntityReplacementText(String entityName, String replacementText) {
      +        if (!replacementText.startsWith("&#") && this.entityName != null && replacementText.length() > 1) {
      +            String tmp = replacementText.substring(1, replacementText.length() - 1);
      +            for (int i = 0; i < this.entityName.length; i++) {
      +                if (this.entityName[i] != null && this.entityName[i].equals(tmp)) {
                           replacementText = this.entityReplacement[i];
                       }
                   }
      @@ -61,116 +54,301 @@ private void defineEntityReplacementText( String entityName, String replacementT
               // this is to make sure that if interning works we will take advantage of it ...
               char[] entityNameCharData = entityName.toCharArray();
               // noinspection ConstantConditions
      -        this.entityName[entityEnd] = newString( entityNameCharData, 0, entityName.length() );
      +        this.entityName[entityEnd] = newString(entityNameCharData, 0, entityName.length());
               entityNameBuf[entityEnd] = entityNameCharData;
       
               entityReplacement[entityEnd] = replacementText;
               entityReplacementBuf[entityEnd] = replacementText.toCharArray();
      -        entityNameHash[entityEnd] = fastHash( entityNameBuf[entityEnd], 0, entityNameBuf[entityEnd].length );
      +        entityNameHash[entityEnd] = fastHash(entityNameBuf[entityEnd], 0, entityNameBuf[entityEnd].length);
               ++entityEnd;
               // TODO disallow < or & in entity replacement text (or ]]>???)
               // TODO keepEntityNormalizedForAttributeValue cached as well ...
           }
       
      -    private String newString( char[] cbuf, int off, int len )
      -    {
      -        return new String( cbuf, off, len );
      +    private String newString(char[] cbuf, int off, int len) {
      +        return new String(cbuf, off, len);
           }
       
           /**
            * simplistic implementation of hash function that has constant time to compute - so it also means
            * diminishing hash quality for long strings but for XML parsing it should be good enough ...
            */
      -    private static int fastHash( char ch[], int off, int len )
      -    {
      -        if ( len == 0 )
      -            return 0;
      +    private static int fastHash(char ch[], int off, int len) {
      +        if (len == 0) return 0;
               // assert len >0
               int hash = ch[off]; // hash at beginning
               // try {
      -        hash = ( hash << 7 ) + ch[off + len - 1]; // hash at the end
      +        hash = (hash << 7) + ch[off + len - 1]; // hash at the end
               // } catch(ArrayIndexOutOfBoundsException aie) {
               // aie.printStackTrace(); //should never happen ...
               // throw new RuntimeException("this is violation of pre-condition");
               // }
      -        if ( len > 16 )
      -            hash = ( hash << 7 ) + ch[off + ( len / 4 )]; // 1/4 from beginning
      -        if ( len > 8 )
      -            hash = ( hash << 7 ) + ch[off + ( len / 2 )]; // 1/2 of string size ...
      +        if (len > 16) hash = (hash << 7) + ch[off + (len / 4)]; // 1/4 from beginning
      +        if (len > 8) hash = (hash << 7) + ch[off + (len / 2)]; // 1/2 of string size ...
               // notice that hash is at most done 3 times <<7 so shifted by 21 bits 8 bit value
               // so max result == 29 bits so it is quite just below 31 bits for long (2^32) ...
               // assert hash >= 0;
               return hash;
           }
       
      -    public static final EntityReplacementMap defaultEntityReplacementMap = new EntityReplacementMap( new String[][] {
      -        { "nbsp", "\u00a0" }, { "iexcl", "\u00a1" }, { "cent", "\u00a2" }, { "pound", "\u00a3" },
      -        { "curren", "\u00a4" }, { "yen", "\u00a5" }, { "brvbar", "\u00a6" }, { "sect", "\u00a7" }, { "uml", "\u00a8" },
      -        { "copy", "\u00a9" }, { "ordf", "\u00aa" }, { "laquo", "\u00ab" }, { "not", "\u00ac" }, { "shy", "\u00ad" },
      -        { "reg", "\u00ae" }, { "macr", "\u00af" }, { "deg", "\u00b0" }, { "plusmn", "\u00b1" }, { "sup2", "\u00b2" },
      -        { "sup3", "\u00b3" }, { "acute", "\u00b4" }, { "micro", "\u00b5" }, { "para", "\u00b6" },
      -        { "middot", "\u00b7" }, { "cedil", "\u00b8" }, { "sup1", "\u00b9" }, { "ordm", "\u00ba" },
      -        { "raquo", "\u00bb" }, { "frac14", "\u00bc" }, { "frac12", "\u00bd" }, { "frac34", "\u00be" },
      -        { "iquest", "\u00bf" }, { "Agrave", "\u00c0" }, { "Aacute", "\u00c1" }, { "Acirc", "\u00c2" },
      -        { "Atilde", "\u00c3" }, { "Auml", "\u00c4" }, { "Aring", "\u00c5" }, { "AElig", "\u00c6" },
      -        { "Ccedil", "\u00c7" }, { "Egrave", "\u00c8" }, { "Eacute", "\u00c9" }, { "Ecirc", "\u00ca" },
      -        { "Euml", "\u00cb" }, { "Igrave", "\u00cc" }, { "Iacute", "\u00cd" }, { "Icirc", "\u00ce" },
      -        { "Iuml", "\u00cf" }, { "ETH", "\u00d0" }, { "Ntilde", "\u00d1" }, { "Ograve", "\u00d2" },
      -        { "Oacute", "\u00d3" }, { "Ocirc", "\u00d4" }, { "Otilde", "\u00d5" }, { "Ouml", "\u00d6" },
      -        { "times", "\u00d7" }, { "Oslash", "\u00d8" }, { "Ugrave", "\u00d9" }, { "Uacute", "\u00da" },
      -        { "Ucirc", "\u00db" }, { "Uuml", "\u00dc" }, { "Yacute", "\u00dd" }, { "THORN", "\u00de" },
      -        { "szlig", "\u00df" }, { "agrave", "\u00e0" }, { "aacute", "\u00e1" }, { "acirc", "\u00e2" },
      -        { "atilde", "\u00e3" }, { "auml", "\u00e4" }, { "aring", "\u00e5" }, { "aelig", "\u00e6" },
      -        { "ccedil", "\u00e7" }, { "egrave", "\u00e8" }, { "eacute", "\u00e9" }, { "ecirc", "\u00ea" },
      -        { "euml", "\u00eb" }, { "igrave", "\u00ec" }, { "iacute", "\u00ed" }, { "icirc", "\u00ee" },
      -        { "iuml", "\u00ef" }, { "eth", "\u00f0" }, { "ntilde", "\u00f1" }, { "ograve", "\u00f2" },
      -        { "oacute", "\u00f3" }, { "ocirc", "\u00f4" }, { "otilde", "\u00f5" }, { "ouml", "\u00f6" },
      -        { "divide", "\u00f7" }, { "oslash", "\u00f8" }, { "ugrave", "\u00f9" }, { "uacute", "\u00fa" },
      -        { "ucirc", "\u00fb" }, { "uuml", "\u00fc" }, { "yacute", "\u00fd" }, { "thorn", "\u00fe" },
      -        { "yuml", "\u00ff" },
      +    public static final EntityReplacementMap defaultEntityReplacementMap = new EntityReplacementMap(new String[][] {
      +        {"nbsp", "\u00a0"},
      +        {"iexcl", "\u00a1"},
      +        {"cent", "\u00a2"},
      +        {"pound", "\u00a3"},
      +        {"curren", "\u00a4"},
      +        {"yen", "\u00a5"},
      +        {"brvbar", "\u00a6"},
      +        {"sect", "\u00a7"},
      +        {"uml", "\u00a8"},
      +        {"copy", "\u00a9"},
      +        {"ordf", "\u00aa"},
      +        {"laquo", "\u00ab"},
      +        {"not", "\u00ac"},
      +        {"shy", "\u00ad"},
      +        {"reg", "\u00ae"},
      +        {"macr", "\u00af"},
      +        {"deg", "\u00b0"},
      +        {"plusmn", "\u00b1"},
      +        {"sup2", "\u00b2"},
      +        {"sup3", "\u00b3"},
      +        {"acute", "\u00b4"},
      +        {"micro", "\u00b5"},
      +        {"para", "\u00b6"},
      +        {"middot", "\u00b7"},
      +        {"cedil", "\u00b8"},
      +        {"sup1", "\u00b9"},
      +        {"ordm", "\u00ba"},
      +        {"raquo", "\u00bb"},
      +        {"frac14", "\u00bc"},
      +        {"frac12", "\u00bd"},
      +        {"frac34", "\u00be"},
      +        {"iquest", "\u00bf"},
      +        {"Agrave", "\u00c0"},
      +        {"Aacute", "\u00c1"},
      +        {"Acirc", "\u00c2"},
      +        {"Atilde", "\u00c3"},
      +        {"Auml", "\u00c4"},
      +        {"Aring", "\u00c5"},
      +        {"AElig", "\u00c6"},
      +        {"Ccedil", "\u00c7"},
      +        {"Egrave", "\u00c8"},
      +        {"Eacute", "\u00c9"},
      +        {"Ecirc", "\u00ca"},
      +        {"Euml", "\u00cb"},
      +        {"Igrave", "\u00cc"},
      +        {"Iacute", "\u00cd"},
      +        {"Icirc", "\u00ce"},
      +        {"Iuml", "\u00cf"},
      +        {"ETH", "\u00d0"},
      +        {"Ntilde", "\u00d1"},
      +        {"Ograve", "\u00d2"},
      +        {"Oacute", "\u00d3"},
      +        {"Ocirc", "\u00d4"},
      +        {"Otilde", "\u00d5"},
      +        {"Ouml", "\u00d6"},
      +        {"times", "\u00d7"},
      +        {"Oslash", "\u00d8"},
      +        {"Ugrave", "\u00d9"},
      +        {"Uacute", "\u00da"},
      +        {"Ucirc", "\u00db"},
      +        {"Uuml", "\u00dc"},
      +        {"Yacute", "\u00dd"},
      +        {"THORN", "\u00de"},
      +        {"szlig", "\u00df"},
      +        {"agrave", "\u00e0"},
      +        {"aacute", "\u00e1"},
      +        {"acirc", "\u00e2"},
      +        {"atilde", "\u00e3"},
      +        {"auml", "\u00e4"},
      +        {"aring", "\u00e5"},
      +        {"aelig", "\u00e6"},
      +        {"ccedil", "\u00e7"},
      +        {"egrave", "\u00e8"},
      +        {"eacute", "\u00e9"},
      +        {"ecirc", "\u00ea"},
      +        {"euml", "\u00eb"},
      +        {"igrave", "\u00ec"},
      +        {"iacute", "\u00ed"},
      +        {"icirc", "\u00ee"},
      +        {"iuml", "\u00ef"},
      +        {"eth", "\u00f0"},
      +        {"ntilde", "\u00f1"},
      +        {"ograve", "\u00f2"},
      +        {"oacute", "\u00f3"},
      +        {"ocirc", "\u00f4"},
      +        {"otilde", "\u00f5"},
      +        {"ouml", "\u00f6"},
      +        {"divide", "\u00f7"},
      +        {"oslash", "\u00f8"},
      +        {"ugrave", "\u00f9"},
      +        {"uacute", "\u00fa"},
      +        {"ucirc", "\u00fb"},
      +        {"uuml", "\u00fc"},
      +        {"yacute", "\u00fd"},
      +        {"thorn", "\u00fe"},
      +        {"yuml", "\u00ff"},
       
               // ----------------------------------------------------------------------
               // Special entities
               // ----------------------------------------------------------------------
       
      -        { "OElig", "\u0152" }, { "oelig", "\u0153" }, { "Scaron", "\u0160" }, { "scaron", "\u0161" },
      -        { "Yuml", "\u0178" }, { "circ", "\u02c6" }, { "tilde", "\u02dc" }, { "ensp", "\u2002" }, { "emsp", "\u2003" },
      -        { "thinsp", "\u2009" }, { "zwnj", "\u200c" }, { "zwj", "\u200d" }, { "lrm", "\u200e" }, { "rlm", "\u200f" },
      -        { "ndash", "\u2013" }, { "mdash", "\u2014" }, { "lsquo", "\u2018" }, { "rsquo", "\u2019" },
      -        { "sbquo", "\u201a" }, { "ldquo", "\u201c" }, { "rdquo", "\u201d" }, { "bdquo", "\u201e" },
      -        { "dagger", "\u2020" }, { "Dagger", "\u2021" }, { "permil", "\u2030" }, { "lsaquo", "\u2039" },
      -        { "rsaquo", "\u203a" }, { "euro", "\u20ac" },
      +        {"OElig", "\u0152"},
      +        {"oelig", "\u0153"},
      +        {"Scaron", "\u0160"},
      +        {"scaron", "\u0161"},
      +        {"Yuml", "\u0178"},
      +        {"circ", "\u02c6"},
      +        {"tilde", "\u02dc"},
      +        {"ensp", "\u2002"},
      +        {"emsp", "\u2003"},
      +        {"thinsp", "\u2009"},
      +        {"zwnj", "\u200c"},
      +        {"zwj", "\u200d"},
      +        {"lrm", "\u200e"},
      +        {"rlm", "\u200f"},
      +        {"ndash", "\u2013"},
      +        {"mdash", "\u2014"},
      +        {"lsquo", "\u2018"},
      +        {"rsquo", "\u2019"},
      +        {"sbquo", "\u201a"},
      +        {"ldquo", "\u201c"},
      +        {"rdquo", "\u201d"},
      +        {"bdquo", "\u201e"},
      +        {"dagger", "\u2020"},
      +        {"Dagger", "\u2021"},
      +        {"permil", "\u2030"},
      +        {"lsaquo", "\u2039"},
      +        {"rsaquo", "\u203a"},
      +        {"euro", "\u20ac"},
       
               // ----------------------------------------------------------------------
               // Symbol entities
               // ----------------------------------------------------------------------
       
      -        { "fnof", "\u0192" }, { "Alpha", "\u0391" }, { "Beta", "\u0392" }, { "Gamma", "\u0393" }, { "Delta", "\u0394" },
      -        { "Epsilon", "\u0395" }, { "Zeta", "\u0396" }, { "Eta", "\u0397" }, { "Theta", "\u0398" }, { "Iota", "\u0399" },
      -        { "Kappa", "\u039a" }, { "Lambda", "\u039b" }, { "Mu", "\u039c" }, { "Nu", "\u039d" }, { "Xi", "\u039e" },
      -        { "Omicron", "\u039f" }, { "Pi", "\u03a0" }, { "Rho", "\u03a1" }, { "Sigma", "\u03a3" }, { "Tau", "\u03a4" },
      -        { "Upsilon", "\u03a5" }, { "Phi", "\u03a6" }, { "Chi", "\u03a7" }, { "Psi", "\u03a8" }, { "Omega", "\u03a9" },
      -        { "alpha", "\u03b1" }, { "beta", "\u03b2" }, { "gamma", "\u03b3" }, { "delta", "\u03b4" },
      -        { "epsilon", "\u03b5" }, { "zeta", "\u03b6" }, { "eta", "\u03b7" }, { "theta", "\u03b8" }, { "iota", "\u03b9" },
      -        { "kappa", "\u03ba" }, { "lambda", "\u03bb" }, { "mu", "\u03bc" }, { "nu", "\u03bd" }, { "xi", "\u03be" },
      -        { "omicron", "\u03bf" }, { "pi", "\u03c0" }, { "rho", "\u03c1" }, { "sigmaf", "\u03c2" }, { "sigma", "\u03c3" },
      -        { "tau", "\u03c4" }, { "upsilon", "\u03c5" }, { "phi", "\u03c6" }, { "chi", "\u03c7" }, { "psi", "\u03c8" },
      -        { "omega", "\u03c9" }, { "thetasym", "\u03d1" }, { "upsih", "\u03d2" }, { "piv", "\u03d6" },
      -        { "bull", "\u2022" }, { "hellip", "\u2026" }, { "prime", "\u2032" }, { "Prime", "\u2033" },
      -        { "oline", "\u203e" }, { "frasl", "\u2044" }, { "weierp", "\u2118" }, { "image", "\u2111" },
      -        { "real", "\u211c" }, { "trade", "\u2122" }, { "alefsym", "\u2135" }, { "larr", "\u2190" },
      -        { "uarr", "\u2191" }, { "rarr", "\u2192" }, { "darr", "\u2193" }, { "harr", "\u2194" }, { "crarr", "\u21b5" },
      -        { "lArr", "\u21d0" }, { "uArr", "\u21d1" }, { "rArr", "\u21d2" }, { "dArr", "\u21d3" }, { "hArr", "\u21d4" },
      -        { "forall", "\u2200" }, { "part", "\u2202" }, { "exist", "\u2203" }, { "empty", "\u2205" },
      -        { "nabla", "\u2207" }, { "isin", "\u2208" }, { "notin", "\u2209" }, { "ni", "\u220b" }, { "prod", "\u220f" },
      -        { "sum", "\u2211" }, { "minus", "\u2212" }, { "lowast", "\u2217" }, { "radic", "\u221a" }, { "prop", "\u221d" },
      -        { "infin", "\u221e" }, { "ang", "\u2220" }, { "and", "\u2227" }, { "or", "\u2228" }, { "cap", "\u2229" },
      -        { "cup", "\u222a" }, { "int", "\u222b" }, { "there4", "\u2234" }, { "sim", "\u223c" }, { "cong", "\u2245" },
      -        { "asymp", "\u2248" }, { "ne", "\u2260" }, { "equiv", "\u2261" }, { "le", "\u2264" }, { "ge", "\u2265" },
      -        { "sub", "\u2282" }, { "sup", "\u2283" }, { "nsub", "\u2284" }, { "sube", "\u2286" }, { "supe", "\u2287" },
      -        { "oplus", "\u2295" }, { "otimes", "\u2297" }, { "perp", "\u22a5" }, { "sdot", "\u22c5" },
      -        { "lceil", "\u2308" }, { "rceil", "\u2309" }, { "lfloor", "\u230a" }, { "rfloor", "\u230b" },
      -        { "lang", "\u2329" }, { "rang", "\u232a" }, { "loz", "\u25ca" }, { "spades", "\u2660" }, { "clubs", "\u2663" },
      -        { "hearts", "\u2665" }, { "diams", "\u2666" } } );
      -
      +        {"fnof", "\u0192"},
      +        {"Alpha", "\u0391"},
      +        {"Beta", "\u0392"},
      +        {"Gamma", "\u0393"},
      +        {"Delta", "\u0394"},
      +        {"Epsilon", "\u0395"},
      +        {"Zeta", "\u0396"},
      +        {"Eta", "\u0397"},
      +        {"Theta", "\u0398"},
      +        {"Iota", "\u0399"},
      +        {"Kappa", "\u039a"},
      +        {"Lambda", "\u039b"},
      +        {"Mu", "\u039c"},
      +        {"Nu", "\u039d"},
      +        {"Xi", "\u039e"},
      +        {"Omicron", "\u039f"},
      +        {"Pi", "\u03a0"},
      +        {"Rho", "\u03a1"},
      +        {"Sigma", "\u03a3"},
      +        {"Tau", "\u03a4"},
      +        {"Upsilon", "\u03a5"},
      +        {"Phi", "\u03a6"},
      +        {"Chi", "\u03a7"},
      +        {"Psi", "\u03a8"},
      +        {"Omega", "\u03a9"},
      +        {"alpha", "\u03b1"},
      +        {"beta", "\u03b2"},
      +        {"gamma", "\u03b3"},
      +        {"delta", "\u03b4"},
      +        {"epsilon", "\u03b5"},
      +        {"zeta", "\u03b6"},
      +        {"eta", "\u03b7"},
      +        {"theta", "\u03b8"},
      +        {"iota", "\u03b9"},
      +        {"kappa", "\u03ba"},
      +        {"lambda", "\u03bb"},
      +        {"mu", "\u03bc"},
      +        {"nu", "\u03bd"},
      +        {"xi", "\u03be"},
      +        {"omicron", "\u03bf"},
      +        {"pi", "\u03c0"},
      +        {"rho", "\u03c1"},
      +        {"sigmaf", "\u03c2"},
      +        {"sigma", "\u03c3"},
      +        {"tau", "\u03c4"},
      +        {"upsilon", "\u03c5"},
      +        {"phi", "\u03c6"},
      +        {"chi", "\u03c7"},
      +        {"psi", "\u03c8"},
      +        {"omega", "\u03c9"},
      +        {"thetasym", "\u03d1"},
      +        {"upsih", "\u03d2"},
      +        {"piv", "\u03d6"},
      +        {"bull", "\u2022"},
      +        {"hellip", "\u2026"},
      +        {"prime", "\u2032"},
      +        {"Prime", "\u2033"},
      +        {"oline", "\u203e"},
      +        {"frasl", "\u2044"},
      +        {"weierp", "\u2118"},
      +        {"image", "\u2111"},
      +        {"real", "\u211c"},
      +        {"trade", "\u2122"},
      +        {"alefsym", "\u2135"},
      +        {"larr", "\u2190"},
      +        {"uarr", "\u2191"},
      +        {"rarr", "\u2192"},
      +        {"darr", "\u2193"},
      +        {"harr", "\u2194"},
      +        {"crarr", "\u21b5"},
      +        {"lArr", "\u21d0"},
      +        {"uArr", "\u21d1"},
      +        {"rArr", "\u21d2"},
      +        {"dArr", "\u21d3"},
      +        {"hArr", "\u21d4"},
      +        {"forall", "\u2200"},
      +        {"part", "\u2202"},
      +        {"exist", "\u2203"},
      +        {"empty", "\u2205"},
      +        {"nabla", "\u2207"},
      +        {"isin", "\u2208"},
      +        {"notin", "\u2209"},
      +        {"ni", "\u220b"},
      +        {"prod", "\u220f"},
      +        {"sum", "\u2211"},
      +        {"minus", "\u2212"},
      +        {"lowast", "\u2217"},
      +        {"radic", "\u221a"},
      +        {"prop", "\u221d"},
      +        {"infin", "\u221e"},
      +        {"ang", "\u2220"},
      +        {"and", "\u2227"},
      +        {"or", "\u2228"},
      +        {"cap", "\u2229"},
      +        {"cup", "\u222a"},
      +        {"int", "\u222b"},
      +        {"there4", "\u2234"},
      +        {"sim", "\u223c"},
      +        {"cong", "\u2245"},
      +        {"asymp", "\u2248"},
      +        {"ne", "\u2260"},
      +        {"equiv", "\u2261"},
      +        {"le", "\u2264"},
      +        {"ge", "\u2265"},
      +        {"sub", "\u2282"},
      +        {"sup", "\u2283"},
      +        {"nsub", "\u2284"},
      +        {"sube", "\u2286"},
      +        {"supe", "\u2287"},
      +        {"oplus", "\u2295"},
      +        {"otimes", "\u2297"},
      +        {"perp", "\u22a5"},
      +        {"sdot", "\u22c5"},
      +        {"lceil", "\u2308"},
      +        {"rceil", "\u2309"},
      +        {"lfloor", "\u230a"},
      +        {"rfloor", "\u230b"},
      +        {"lang", "\u2329"},
      +        {"rang", "\u232a"},
      +        {"loz", "\u25ca"},
      +        {"spades", "\u2660"},
      +        {"clubs", "\u2663"},
      +        {"hearts", "\u2665"},
      +        {"diams", "\u2666"}
      +    });
       }
      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 e9fc1182..7681c922 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
      @@ -18,14 +18,14 @@
       import org.codehaus.plexus.util.ReaderFactory;
       import org.codehaus.plexus.util.xml.XmlReader;
       
      -//import java.util.Hashtable;
      +// import java.util.Hashtable;
       
      -//TODO best handling of interning issues
      +// TODO best handling of interning issues
       //   have isAllNewStringInterned ???
       
      -//TODO handling surrogate pairs: http://www.unicode.org/unicode/faq/utf_bom.html#6
      +// TODO handling surrogate pairs: http://www.unicode.org/unicode/faq/utf_bom.html#6
       
      -//TODO review code for use of bufAbsoluteStart when keeping pos between next()/fillBuf()
      +// TODO review code for use of bufAbsoluteStart when keeping pos between next()/fillBuf()
       
       /**
        * Absolutely minimal implementation of XMLPULL V1 API. Encoding handling done with XmlReader
      @@ -33,31 +33,26 @@
        * @see org.codehaus.plexus.util.xml.XmlReader
        * @author Aleksander Slominski
        */
      -
      -public class MXParser
      -    implements XmlPullParser
      -{
      +public class MXParser implements XmlPullParser {
           // NOTE: no interning of those strings --> by Java leng spec they MUST be already interned
      -    private final static String XML_URI = "http://www.w3.org/XML/1998/namespace";
      +    private static final String XML_URI = "http://www.w3.org/XML/1998/namespace";
       
      -    private final static String XMLNS_URI = "http://www.w3.org/2000/xmlns/";
      +    private static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/";
       
      -    private final static String FEATURE_XML_ROUNDTRIP =
      -        // "http://xmlpull.org/v1/doc/features.html#xml-roundtrip";
      -        "http://xmlpull.org/v1/doc/features.html#xml-roundtrip";
      +    private static final String FEATURE_XML_ROUNDTRIP =
      +            // "http://xmlpull.org/v1/doc/features.html#xml-roundtrip";
      +            "http://xmlpull.org/v1/doc/features.html#xml-roundtrip";
       
      -    private final static String FEATURE_NAMES_INTERNED = "http://xmlpull.org/v1/doc/features.html#names-interned";
      +    private static final String FEATURE_NAMES_INTERNED = "http://xmlpull.org/v1/doc/features.html#names-interned";
       
      -    private final static String PROPERTY_XMLDECL_VERSION =
      -        "http://xmlpull.org/v1/doc/properties.html#xmldecl-version";
      +    private static final String PROPERTY_XMLDECL_VERSION = "http://xmlpull.org/v1/doc/properties.html#xmldecl-version";
       
      -    private final static String PROPERTY_XMLDECL_STANDALONE =
      -        "http://xmlpull.org/v1/doc/properties.html#xmldecl-standalone";
      +    private static final String PROPERTY_XMLDECL_STANDALONE =
      +            "http://xmlpull.org/v1/doc/properties.html#xmldecl-standalone";
       
      -    private final static String PROPERTY_XMLDECL_CONTENT =
      -        "http://xmlpull.org/v1/doc/properties.html#xmldecl-content";
      +    private static final String PROPERTY_XMLDECL_CONTENT = "http://xmlpull.org/v1/doc/properties.html#xmldecl-content";
       
      -    private final static String PROPERTY_LOCATION = "http://xmlpull.org/v1/doc/properties.html#location";
      +    private static final String PROPERTY_LOCATION = "http://xmlpull.org/v1/doc/properties.html#location";
       
           /**
            * Implementation notice: the is instance variable that controls if newString() is interning.
      @@ -69,19 +64,16 @@ public class MXParser
            */
           private boolean allStringsInterned;
       
      -    private void resetStringCache()
      -    {
      +    private void resetStringCache() {
               // System.out.println("resetStringCache() minimum called");
           }
       
      -    private String newString( char[] cbuf, int off, int len )
      -    {
      -        return new String( cbuf, off, len );
      +    private String newString(char[] cbuf, int off, int len) {
      +        return new String(cbuf, off, len);
           }
       
      -    private String newStringIntern( char[] cbuf, int off, int len )
      -    {
      -        return ( new String( cbuf, off, len ) ).intern();
      +    private String newStringIntern(char[] cbuf, int off, int len) {
      +        return (new String(cbuf, off, len)).intern();
           }
       
           private static final boolean TRACE_SIZING = false;
      @@ -130,40 +122,31 @@ private String newStringIntern( char[] cbuf, int off, int len )
            * Make sure that we have enough space to keep element stack if passed size. It will always create one additional
            * slot then current depth
            */
      -    private void ensureElementsCapacity()
      -    {
      +    private void ensureElementsCapacity() {
               final int elStackSize = elName != null ? elName.length : 0;
      -        if ( ( depth + 1 ) >= elStackSize )
      -        {
      +        if ((depth + 1) >= elStackSize) {
                   // we add at least one extra slot ...
      -            final int newSize = ( depth >= 7 ? 2 * depth : 8 ) + 2; // = lucky 7 + 1 //25
      -            if ( TRACE_SIZING )
      -            {
      -                System.err.println( "TRACE_SIZING elStackSize " + elStackSize + " ==> " + newSize );
      +            final int newSize = (depth >= 7 ? 2 * depth : 8) + 2; // = lucky 7 + 1 //25
      +            if (TRACE_SIZING) {
      +                System.err.println("TRACE_SIZING elStackSize " + elStackSize + " ==> " + newSize);
                   }
                   final boolean needsCopying = elStackSize > 0;
                   String[] arr = null;
                   // resue arr local variable slot
                   arr = new String[newSize];
      -            if ( needsCopying )
      -                System.arraycopy( elName, 0, arr, 0, elStackSize );
      +            if (needsCopying) System.arraycopy(elName, 0, arr, 0, elStackSize);
                   elName = arr;
                   arr = new String[newSize];
      -            if ( needsCopying )
      -                System.arraycopy( elPrefix, 0, arr, 0, elStackSize );
      +            if (needsCopying) System.arraycopy(elPrefix, 0, arr, 0, elStackSize);
                   elPrefix = arr;
                   arr = new String[newSize];
      -            if ( needsCopying )
      -                System.arraycopy( elUri, 0, arr, 0, elStackSize );
      +            if (needsCopying) System.arraycopy(elUri, 0, arr, 0, elStackSize);
                   elUri = arr;
       
                   int[] iarr = new int[newSize];
      -            if ( needsCopying )
      -            {
      -                System.arraycopy( elNamespaceCount, 0, iarr, 0, elStackSize );
      -            }
      -            else
      -            {
      +            if (needsCopying) {
      +                System.arraycopy(elNamespaceCount, 0, iarr, 0, elStackSize);
      +            } else {
                       // special initialization
                       iarr[0] = 0;
                   }
      @@ -171,23 +154,20 @@ private void ensureElementsCapacity()
       
                   // TODO: avoid using element raw name ...
                   iarr = new int[newSize];
      -            if ( needsCopying )
      -            {
      -                System.arraycopy( elRawNameEnd, 0, iarr, 0, elStackSize );
      +            if (needsCopying) {
      +                System.arraycopy(elRawNameEnd, 0, iarr, 0, elStackSize);
                   }
                   elRawNameEnd = iarr;
       
                   iarr = new int[newSize];
      -            if ( needsCopying )
      -            {
      -                System.arraycopy( elRawNameLine, 0, iarr, 0, elStackSize );
      +            if (needsCopying) {
      +                System.arraycopy(elRawNameLine, 0, iarr, 0, elStackSize);
                   }
                   elRawNameLine = iarr;
       
                   final char[][] carr = new char[newSize][];
      -            if ( needsCopying )
      -            {
      -                System.arraycopy( elRawName, 0, carr, 0, elStackSize );
      +            if (needsCopying) {
      +                System.arraycopy(elRawName, 0, carr, 0, elStackSize);
                   }
                   elRawName = carr;
                   // arr = new String[newSize];
      @@ -225,44 +205,35 @@ private void ensureElementsCapacity()
           // private int attributeValueEnd[];
       
           // Make sure that in attributes temporary array is enough space.
      -    private void ensureAttributesCapacity( int size )
      -    {
      +    private void ensureAttributesCapacity(int size) {
               final int attrPosSize = attributeName != null ? attributeName.length : 0;
      -        if ( size >= attrPosSize )
      -        {
      +        if (size >= attrPosSize) {
                   final int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25
      -            if ( TRACE_SIZING )
      -            {
      -                System.err.println( "TRACE_SIZING attrPosSize " + attrPosSize + " ==> " + newSize );
      +            if (TRACE_SIZING) {
      +                System.err.println("TRACE_SIZING attrPosSize " + attrPosSize + " ==> " + newSize);
                   }
                   final boolean needsCopying = attrPosSize > 0;
                   String[] arr = null;
       
                   arr = new String[newSize];
      -            if ( needsCopying )
      -                System.arraycopy( attributeName, 0, arr, 0, attrPosSize );
      +            if (needsCopying) System.arraycopy(attributeName, 0, arr, 0, attrPosSize);
                   attributeName = arr;
       
                   arr = new String[newSize];
      -            if ( needsCopying )
      -                System.arraycopy( attributePrefix, 0, arr, 0, attrPosSize );
      +            if (needsCopying) System.arraycopy(attributePrefix, 0, arr, 0, attrPosSize);
                   attributePrefix = arr;
       
                   arr = new String[newSize];
      -            if ( needsCopying )
      -                System.arraycopy( attributeUri, 0, arr, 0, attrPosSize );
      +            if (needsCopying) System.arraycopy(attributeUri, 0, arr, 0, attrPosSize);
                   attributeUri = arr;
       
                   arr = new String[newSize];
      -            if ( needsCopying )
      -                System.arraycopy( attributeValue, 0, arr, 0, attrPosSize );
      +            if (needsCopying) System.arraycopy(attributeValue, 0, arr, 0, attrPosSize);
                   attributeValue = arr;
       
      -            if ( !allStringsInterned )
      -            {
      +            if (!allStringsInterned) {
                       final int[] iarr = new int[newSize];
      -                if ( needsCopying )
      -                    System.arraycopy( attributeNameHash, 0, iarr, 0, attrPosSize );
      +                if (needsCopying) System.arraycopy(attributeNameHash, 0, iarr, 0, attrPosSize);
                       attributeNameHash = iarr;
                   }
       
      @@ -280,32 +251,26 @@ private void ensureAttributesCapacity( int size )
       
           private String namespaceUri[];
       
      -    private void ensureNamespacesCapacity( int size )
      -    {
      +    private void ensureNamespacesCapacity(int size) {
               final int namespaceSize = namespacePrefix != null ? namespacePrefix.length : 0;
      -        if ( size >= namespaceSize )
      -        {
      +        if (size >= namespaceSize) {
                   final int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25
      -            if ( TRACE_SIZING )
      -            {
      -                System.err.println( "TRACE_SIZING namespaceSize " + namespaceSize + " ==> " + newSize );
      +            if (TRACE_SIZING) {
      +                System.err.println("TRACE_SIZING namespaceSize " + namespaceSize + " ==> " + newSize);
                   }
                   final String[] newNamespacePrefix = new String[newSize];
                   final String[] newNamespaceUri = new String[newSize];
      -            if ( namespacePrefix != null )
      -            {
      -                System.arraycopy( namespacePrefix, 0, newNamespacePrefix, 0, namespaceEnd );
      -                System.arraycopy( namespaceUri, 0, newNamespaceUri, 0, namespaceEnd );
      +            if (namespacePrefix != null) {
      +                System.arraycopy(namespacePrefix, 0, newNamespacePrefix, 0, namespaceEnd);
      +                System.arraycopy(namespaceUri, 0, newNamespaceUri, 0, namespaceEnd);
                   }
                   namespacePrefix = newNamespacePrefix;
                   namespaceUri = newNamespaceUri;
       
      -            if ( !allStringsInterned )
      -            {
      +            if (!allStringsInterned) {
                       final int[] newNamespacePrefixHash = new int[newSize];
      -                if ( namespacePrefixHash != null )
      -                {
      -                    System.arraycopy( namespacePrefixHash, 0, newNamespacePrefixHash, 0, namespaceEnd );
      +                if (namespacePrefixHash != null) {
      +                    System.arraycopy(namespacePrefixHash, 0, newNamespacePrefixHash, 0, namespaceEnd);
                       }
                       namespacePrefixHash = newNamespacePrefixHash;
                   }
      @@ -314,26 +279,21 @@ private void ensureNamespacesCapacity( int size )
               }
           }
       
      +    // simplistic implementation of hash function that has constant time to compute - so it also means
      +    // diminishing hash quality for long strings but for XML parsing it should be good enough ...
       
      -     // simplistic implementation of hash function that has constant time to compute - so it also means
      -     // diminishing hash quality for long strings but for XML parsing it should be good enough ...
      -
      -    private static final int fastHash( char ch[], int off, int len )
      -    {
      -        if ( len == 0 )
      -            return 0;
      +    private static final int fastHash(char ch[], int off, int len) {
      +        if (len == 0) return 0;
               // assert len >0
               int hash = ch[off]; // hash at beginning
               // try {
      -        hash = ( hash << 7 ) + ch[off + len - 1]; // hash at the end
      +        hash = (hash << 7) + ch[off + len - 1]; // hash at the end
               // } catch(ArrayIndexOutOfBoundsException aie) {
               // aie.printStackTrace(); //should never happen ...
               // throw new RuntimeException("this is violation of pre-condition");
               // }
      -        if ( len > 16 )
      -            hash = ( hash << 7 ) + ch[off + ( len / 4 )]; // 1/4 from beginning
      -        if ( len > 8 )
      -            hash = ( hash << 7 ) + ch[off + ( len / 2 )]; // 1/2 of string size ...
      +        if (len > 16) hash = (hash << 7) + ch[off + (len / 4)]; // 1/4 from beginning
      +        if (len > 8) hash = (hash << 7) + ch[off + (len / 2)]; // 1/2 of string size ...
               // notice that hash is at most done 3 times <<7 so shifted by 21 bits 8 bit value
               // so max result == 29 bits so it is quite just below 31 bits for long (2^32) ...
               // assert hash >= 0;
      @@ -355,38 +315,32 @@ private static final int fastHash( char ch[], int off, int len )
       
           private final EntityReplacementMap replacementMapTemplate;
       
      -    private void ensureEntityCapacity()
      -    {
      +    private void ensureEntityCapacity() {
               final int entitySize = entityReplacementBuf != null ? entityReplacementBuf.length : 0;
      -        if ( entityEnd >= entitySize )
      -        {
      +        if (entityEnd >= entitySize) {
                   final int newSize = entityEnd > 7 ? 2 * entityEnd : 8; // = lucky 7 + 1 //25
      -            if ( TRACE_SIZING )
      -            {
      -                System.err.println( "TRACE_SIZING entitySize " + entitySize + " ==> " + newSize );
      +            if (TRACE_SIZING) {
      +                System.err.println("TRACE_SIZING entitySize " + entitySize + " ==> " + newSize);
                   }
                   final String[] newEntityName = new String[newSize];
                   final char[] newEntityNameBuf[] = new char[newSize][];
                   final String[] newEntityReplacement = new String[newSize];
                   final char[] newEntityReplacementBuf[] = new char[newSize][];
      -            if ( entityName != null )
      -            {
      -                System.arraycopy( entityName, 0, newEntityName, 0, entityEnd );
      -                System.arraycopy( entityNameBuf, 0, newEntityNameBuf, 0, entityEnd );
      -                System.arraycopy( entityReplacement, 0, newEntityReplacement, 0, entityEnd );
      -                System.arraycopy( entityReplacementBuf, 0, newEntityReplacementBuf, 0, entityEnd );
      +            if (entityName != null) {
      +                System.arraycopy(entityName, 0, newEntityName, 0, entityEnd);
      +                System.arraycopy(entityNameBuf, 0, newEntityNameBuf, 0, entityEnd);
      +                System.arraycopy(entityReplacement, 0, newEntityReplacement, 0, entityEnd);
      +                System.arraycopy(entityReplacementBuf, 0, newEntityReplacementBuf, 0, entityEnd);
                   }
                   entityName = newEntityName;
                   entityNameBuf = newEntityNameBuf;
                   entityReplacement = newEntityReplacement;
                   entityReplacementBuf = newEntityReplacementBuf;
       
      -            if ( !allStringsInterned )
      -            {
      +            if (!allStringsInterned) {
                       final int[] newEntityNameHash = new int[newSize];
      -                if ( entityNameHash != null )
      -                {
      -                    System.arraycopy( entityNameHash, 0, newEntityNameHash, 0, entityEnd );
      +                if (entityNameHash != null) {
      +                    System.arraycopy(entityNameHash, 0, newEntityNameHash, 0, entityEnd);
                       }
                       entityNameHash = newEntityNameHash;
                   }
      @@ -405,9 +359,9 @@ private void ensureEntityCapacity()
       
           private float bufferLoadFactor = bufLoadFactor / 100f;
       
      -	private char buf[] = new char[Runtime.getRuntime().freeMemory() > 1000000L ? READ_CHUNK_SIZE : 256];
      +    private char buf[] = new char[Runtime.getRuntime().freeMemory() > 1000000L ? READ_CHUNK_SIZE : 256];
       
      -	private int bufSoftLimit = (int) ( bufferLoadFactor * buf.length ); // desirable size of buffer
      +    private int bufSoftLimit = (int) (bufferLoadFactor * buf.length); // desirable size of buffer
       
           private boolean preventBufferCompaction;
       
      @@ -459,8 +413,7 @@ private void ensureEntityCapacity()
       
           private String xmlDeclContent;
       
      -    private void reset()
      -    {
      +    private void reset() {
               // System.out.println("reset() called");
               location = null;
               lineNumber = 1;
      @@ -505,20 +458,16 @@ private void reset()
               resetStringCache();
           }
       
      -    public MXParser()
      -    {
      +    public MXParser() {
               replacementMapTemplate = null;
           }
       
      -    public MXParser( EntityReplacementMap entityReplacementMap )
      -    {
      +    public MXParser(EntityReplacementMap entityReplacementMap) {
               this.replacementMapTemplate = entityReplacementMap;
           }
       
      -    public void setupFromTemplate()
      -    {
      -        if ( replacementMapTemplate != null )
      -        {
      +    public void setupFromTemplate() {
      +        if (replacementMapTemplate != null) {
                   int length = replacementMapTemplate.entityEnd;
       
                   // This is a bit cheeky, since the EntityReplacementMap contains exact-sized arrays,
      @@ -541,49 +490,35 @@ public void setupFromTemplate()
            * @throws XmlPullParserException issue
            */
           @Override
      -    public void setFeature( String name, boolean state )
      -        throws XmlPullParserException
      -    {
      -        if ( name == null )
      -            throw new IllegalArgumentException( "feature name should not be null" );
      -        if ( FEATURE_PROCESS_NAMESPACES.equals( name ) )
      -        {
      -            if ( eventType != START_DOCUMENT )
      -                throw new XmlPullParserException( "namespace processing feature can only be changed before parsing",
      -                                                  this, null );
      +    public void setFeature(String name, boolean state) throws XmlPullParserException {
      +        if (name == null) throw new IllegalArgumentException("feature name should not be null");
      +        if (FEATURE_PROCESS_NAMESPACES.equals(name)) {
      +            if (eventType != START_DOCUMENT)
      +                throw new XmlPullParserException(
      +                        "namespace processing feature can only be changed before parsing", this, null);
                   processNamespaces = state;
                   // } else if(FEATURE_REPORT_NAMESPACE_ATTRIBUTES.equals(name)) {
                   // if(type != START_DOCUMENT) throw new XmlPullParserException(
                   // "namespace reporting feature can only be changed before parsing", this, null);
                   // reportNsAttribs = state;
      -        }
      -        else if ( FEATURE_NAMES_INTERNED.equals( name ) )
      -        {
      -            if ( state != false )
      -            {
      -                throw new XmlPullParserException( "interning names in this implementation is not supported" );
      +        } else if (FEATURE_NAMES_INTERNED.equals(name)) {
      +            if (state != false) {
      +                throw new XmlPullParserException("interning names in this implementation is not supported");
                   }
      -        }
      -        else if ( FEATURE_PROCESS_DOCDECL.equals( name ) )
      -        {
      -            if ( state != false )
      -            {
      -                throw new XmlPullParserException( "processing DOCDECL is not supported" );
      +        } else if (FEATURE_PROCESS_DOCDECL.equals(name)) {
      +            if (state != false) {
      +                throw new XmlPullParserException("processing DOCDECL is not supported");
                   }
                   // } else if(REPORT_DOCDECL.equals(name)) {
                   // paramNotifyDoctype = state;
      -        }
      -        else if ( FEATURE_XML_ROUNDTRIP.equals( name ) )
      -        {
      +        } else if (FEATURE_XML_ROUNDTRIP.equals(name)) {
                   // if(state == false) {
                   // throw new XmlPullParserException(
                   // "roundtrip feature can not be switched off");
                   // }
                   roundtripSupported = state;
      -        }
      -        else
      -        {
      -            throw new XmlPullParserException( "unsupported feature " + name );
      +        } else {
      +            throw new XmlPullParserException("unsupported feature " + name);
               }
           }
       
      @@ -591,28 +526,19 @@ else if ( FEATURE_XML_ROUNDTRIP.equals( name ) )
            * Unknown properties are always returned as false
            */
           @Override
      -    public boolean getFeature( String name )
      -    {
      -        if ( name == null )
      -            throw new IllegalArgumentException( "feature name should not be null" );
      -        if ( FEATURE_PROCESS_NAMESPACES.equals( name ) )
      -        {
      +    public boolean getFeature(String name) {
      +        if (name == null) throw new IllegalArgumentException("feature name should not be null");
      +        if (FEATURE_PROCESS_NAMESPACES.equals(name)) {
                   return processNamespaces;
                   // } else if(FEATURE_REPORT_NAMESPACE_ATTRIBUTES.equals(name)) {
                   // return reportNsAttribs;
      -        }
      -        else if ( FEATURE_NAMES_INTERNED.equals( name ) )
      -        {
      +        } else if (FEATURE_NAMES_INTERNED.equals(name)) {
                   return false;
      -        }
      -        else if ( FEATURE_PROCESS_DOCDECL.equals( name ) )
      -        {
      +        } else if (FEATURE_PROCESS_DOCDECL.equals(name)) {
                   return false;
                   // } else if(REPORT_DOCDECL.equals(name)) {
                   // return paramNotifyDoctype;
      -        }
      -        else if ( FEATURE_XML_ROUNDTRIP.equals( name ) )
      -        {
      +        } else if (FEATURE_XML_ROUNDTRIP.equals(name)) {
                   // return true;
                   return roundtripSupported;
               }
      @@ -620,118 +546,82 @@ else if ( FEATURE_XML_ROUNDTRIP.equals( name ) )
           }
       
           @Override
      -    public void setProperty( String name, Object value )
      -        throws XmlPullParserException
      -    {
      -        if ( PROPERTY_LOCATION.equals( name ) )
      -        {
      +    public void setProperty(String name, Object value) throws XmlPullParserException {
      +        if (PROPERTY_LOCATION.equals(name)) {
                   location = (String) value;
      -        }
      -        else
      -        {
      -            throw new XmlPullParserException( "unsupported property: '" + name + "'" );
      +        } else {
      +            throw new XmlPullParserException("unsupported property: '" + name + "'");
               }
           }
       
           @Override
      -    public Object getProperty( String name )
      -    {
      -        if ( name == null )
      -            throw new IllegalArgumentException( "property name should not be null" );
      -        if ( PROPERTY_XMLDECL_VERSION.equals( name ) )
      -        {
      +    public Object getProperty(String name) {
      +        if (name == null) throw new IllegalArgumentException("property name should not be null");
      +        if (PROPERTY_XMLDECL_VERSION.equals(name)) {
                   return xmlDeclVersion;
      -        }
      -        else if ( PROPERTY_XMLDECL_STANDALONE.equals( name ) )
      -        {
      +        } else if (PROPERTY_XMLDECL_STANDALONE.equals(name)) {
                   return xmlDeclStandalone;
      -        }
      -        else if ( PROPERTY_XMLDECL_CONTENT.equals( name ) )
      -        {
      +        } else if (PROPERTY_XMLDECL_CONTENT.equals(name)) {
                   return xmlDeclContent;
      -        }
      -        else if ( PROPERTY_LOCATION.equals( name ) )
      -        {
      +        } else if (PROPERTY_LOCATION.equals(name)) {
                   return location;
               }
               return null;
           }
       
           @Override
      -    public void setInput( Reader in )
      -        throws XmlPullParserException
      -    {
      +    public void setInput(Reader in) throws XmlPullParserException {
               reset();
               reader = in;
       
      -        if ( reader instanceof XmlReader ) {
      +        if (reader instanceof XmlReader) {
                   // encoding already detected
                   XmlReader xsr = (XmlReader) reader;
                   fileEncoding = xsr.getEncoding();
      -        }
      -        else if ( reader instanceof InputStreamReader )
      -        {
      +        } else if (reader instanceof InputStreamReader) {
                   InputStreamReader isr = (InputStreamReader) reader;
      -            if ( isr.getEncoding() != null )
      -            {
      +            if (isr.getEncoding() != null) {
                       fileEncoding = isr.getEncoding().toUpperCase();
                   }
               }
           }
       
           @Override
      -    public void setInput( java.io.InputStream inputStream, String inputEncoding )
      -        throws XmlPullParserException
      -    {
      -        if ( inputStream == null )
      -        {
      -            throw new IllegalArgumentException( "input stream can not be null" );
      +    public void setInput(java.io.InputStream inputStream, String inputEncoding) throws XmlPullParserException {
      +        if (inputStream == null) {
      +            throw new IllegalArgumentException("input stream can not be null");
               }
               Reader reader;
      -        try
      -        {
      -            if ( inputEncoding != null )
      -            {
      -                reader = ReaderFactory.newReader( inputStream, inputEncoding );
      -            }
      -            else
      -            {
      -                reader = ReaderFactory.newXmlReader( inputStream );
      -            }
      -        }
      -        catch ( UnsupportedEncodingException une )
      -        {
      -            throw new XmlPullParserException( "could not create reader for encoding " + inputEncoding + " : " + une,
      -                                              this, une );
      -        }
      -        catch ( IOException e )
      -        {
      -            throw new XmlPullParserException( "could not create reader : " + e, this, e );
      -        }
      -        setInput( reader );
      +        try {
      +            if (inputEncoding != null) {
      +                reader = ReaderFactory.newReader(inputStream, inputEncoding);
      +            } else {
      +                reader = ReaderFactory.newXmlReader(inputStream);
      +            }
      +        } catch (UnsupportedEncodingException une) {
      +            throw new XmlPullParserException(
      +                    "could not create reader for encoding " + inputEncoding + " : " + une, this, une);
      +        } catch (IOException e) {
      +            throw new XmlPullParserException("could not create reader : " + e, this, e);
      +        }
      +        setInput(reader);
               // must be here as reset() was called in setInput() and has set this.inputEncoding to null ...
               this.inputEncoding = inputEncoding;
           }
       
           @Override
      -    public String getInputEncoding()
      -    {
      +    public String getInputEncoding() {
               return inputEncoding;
           }
       
           @Override
      -    public void defineEntityReplacementText( String entityName, String replacementText )
      -        throws XmlPullParserException
      -    {
      +    public void defineEntityReplacementText(String entityName, String replacementText) throws XmlPullParserException {
               // throw new XmlPullParserException("not allowed");
       
      -        if ( !replacementText.startsWith( "&#" ) && this.entityName != null && replacementText.length() > 1 )
      -        {
      -            String tmp = replacementText.substring( 1, replacementText.length() - 1 );
      -            for ( int i = 0; i < this.entityName.length; i++ )
      -            {
      -                if ( this.entityName[i] != null && this.entityName[i].equals( tmp ) )
      -                {
      +        if (!replacementText.startsWith("&#") && this.entityName != null && replacementText.length() > 1) {
      +            String tmp = replacementText.substring(1, replacementText.length() - 1);
      +            for (int i = 0; i < this.entityName.length; i++) {
      +                if (this.entityName[i] != null && this.entityName[i].equals(tmp)) {
                           replacementText = this.entityReplacement[i];
                       }
                   }
      @@ -742,14 +632,13 @@ public void defineEntityReplacementText( String entityName, String replacementTe
       
               // this is to make sure that if interning works we will take advantage of it ...
               char[] entityNameCharData = entityName.toCharArray();
      -        this.entityName[entityEnd] = newString( entityNameCharData, 0, entityName.length() );
      +        this.entityName[entityEnd] = newString(entityNameCharData, 0, entityName.length());
               entityNameBuf[entityEnd] = entityNameCharData;
       
               entityReplacement[entityEnd] = replacementText;
               entityReplacementBuf[entityEnd] = replacementText.toCharArray();
      -        if ( !allStringsInterned )
      -        {
      -            entityNameHash[entityEnd] = fastHash( entityNameBuf[entityEnd], 0, entityNameBuf[entityEnd].length );
      +        if (!allStringsInterned) {
      +            entityNameHash[entityEnd] = fastHash(entityNameBuf[entityEnd], 0, entityNameBuf[entityEnd].length);
               }
               ++entityEnd;
               // TODO disallow < or & in entity replacement text (or ]]>???)
      @@ -757,121 +646,89 @@ public void defineEntityReplacementText( String entityName, String replacementTe
           }
       
           @Override
      -    public int getNamespaceCount( int depth )
      -        throws XmlPullParserException
      -    {
      -        if ( !processNamespaces || depth == 0 )
      -        {
      +    public int getNamespaceCount(int depth) throws XmlPullParserException {
      +        if (!processNamespaces || depth == 0) {
                   return 0;
               }
               // int maxDepth = eventType == END_TAG ? this.depth + 1 : this.depth;
               // if(depth < 0 || depth > maxDepth) throw new IllegalArgumentException(
      -        if ( depth < 0 || depth > this.depth )
      -            throw new IllegalArgumentException( "namespace count may be for depth 0.." + this.depth + " not " + depth );
      +        if (depth < 0 || depth > this.depth)
      +            throw new IllegalArgumentException("namespace count may be for depth 0.." + this.depth + " not " + depth);
               return elNamespaceCount[depth];
           }
       
           @Override
      -    public String getNamespacePrefix( int pos )
      -        throws XmlPullParserException
      -    {
      +    public String getNamespacePrefix(int pos) throws XmlPullParserException {
       
               // int end = eventType == END_TAG ? elNamespaceCount[ depth + 1 ] : namespaceEnd;
               // if(pos < end) {
      -        if ( pos < namespaceEnd )
      -        {
      +        if (pos < namespaceEnd) {
                   return namespacePrefix[pos];
      -        }
      -        else
      -        {
      -            throw new XmlPullParserException( "position " + pos + " exceeded number of available namespaces "
      -                + namespaceEnd );
      +        } else {
      +            throw new XmlPullParserException(
      +                    "position " + pos + " exceeded number of available namespaces " + namespaceEnd);
               }
           }
       
           @Override
      -    public String getNamespaceUri( int pos )
      -        throws XmlPullParserException
      -    {
      +    public String getNamespaceUri(int pos) throws XmlPullParserException {
               // int end = eventType == END_TAG ? elNamespaceCount[ depth + 1 ] : namespaceEnd;
               // if(pos < end) {
      -        if ( pos < namespaceEnd )
      -        {
      +        if (pos < namespaceEnd) {
                   return namespaceUri[pos];
      -        }
      -        else
      -        {
      -            throw new XmlPullParserException( "position " + pos + " exceeded number of available namespaces "
      -                + namespaceEnd );
      +        } else {
      +            throw new XmlPullParserException(
      +                    "position " + pos + " exceeded number of available namespaces " + namespaceEnd);
               }
           }
       
           @Override
      -    public String getNamespace( String prefix )
      -    // throws XmlPullParserException
      -    {
      -        // int count = namespaceCount[ depth ];
      -        if ( prefix != null )
      -        {
      -            for ( int i = namespaceEnd - 1; i >= 0; i-- )
      +    public String getNamespace(String prefix)
      +                // throws XmlPullParserException
                   {
      -                if ( prefix.equals( namespacePrefix[i] ) )
      -                {
      +        // int count = namespaceCount[ depth ];
      +        if (prefix != null) {
      +            for (int i = namespaceEnd - 1; i >= 0; i--) {
      +                if (prefix.equals(namespacePrefix[i])) {
                           return namespaceUri[i];
                       }
                   }
      -            if ( "xml".equals( prefix ) )
      -            {
      +            if ("xml".equals(prefix)) {
                       return XML_URI;
      -            }
      -            else if ( "xmlns".equals( prefix ) )
      -            {
      +            } else if ("xmlns".equals(prefix)) {
                       return XMLNS_URI;
                   }
      -        }
      -        else
      -        {
      -            for ( int i = namespaceEnd - 1; i >= 0; i-- )
      -            {
      -                if ( namespacePrefix[i] == null )
      -                { // "") { //null ) { //TODO check FIXME Alek
      +        } else {
      +            for (int i = namespaceEnd - 1; i >= 0; i--) {
      +                if (namespacePrefix[i] == null) { // "") { //null ) { //TODO check FIXME Alek
                           return namespaceUri[i];
                       }
                   }
      -
               }
               return null;
           }
       
           @Override
      -    public int getDepth()
      -    {
      +    public int getDepth() {
               return depth;
           }
       
      -    private static int findFragment( int bufMinPos, char[] b, int start, int end )
      -    {
      +    private static int findFragment(int bufMinPos, char[] b, int start, int end) {
               // System.err.println("bufStart="+bufStart+" b="+printable(new String(b, start, end - start))+" start="+start+"
               // end="+end);
      -        if ( start < bufMinPos )
      -        {
      +        if (start < bufMinPos) {
                   start = bufMinPos;
      -            if ( start > end )
      -                start = end;
      +            if (start > end) start = end;
                   return start;
               }
      -        if ( end - start > 65 )
      -        {
      +        if (end - start > 65) {
                   start = end - 10; // try to find good location
               }
               int i = start + 1;
      -        while ( --i > bufMinPos )
      -        {
      -            if ( ( end - i ) > 65 )
      -                break;
      +        while (--i > bufMinPos) {
      +            if ((end - i) > 65) break;
                   final char c = b[i];
      -            if ( c == '<' && ( start - i ) > 10 )
      -                break;
      +            if (c == '<' && (start - i) > 10) break;
               }
               return i;
           }
      @@ -880,137 +737,104 @@ private static int findFragment( int bufMinPos, char[] b, int start, int end )
            * Return string describing current position of parsers as text 'STATE [seen %s...] @line:column'.
            */
           @Override
      -    public String getPositionDescription()
      -    {
      +    public String getPositionDescription() {
               String fragment = null;
      -        if ( posStart <= pos )
      -        {
      -            final int start = findFragment( 0, buf, posStart, pos );
      +        if (posStart <= pos) {
      +            final int start = findFragment(0, buf, posStart, pos);
                   // System.err.println("start="+start);
      -            if ( start < pos )
      -            {
      -                fragment = new String( buf, start, pos - start );
      +            if (start < pos) {
      +                fragment = new String(buf, start, pos - start);
                   }
      -            if ( bufAbsoluteStart > 0 || start > 0 )
      -                fragment = "..." + fragment;
      +            if (bufAbsoluteStart > 0 || start > 0) fragment = "..." + fragment;
               }
               // return " at line "+tokenizerPosRow
               // +" and column "+(tokenizerPosCol-1)
               // +(fragment != null ? " seen "+printable(fragment)+"..." : "");
      -        return " " + TYPES[eventType] + ( fragment != null ? " seen " + printable( fragment ) + "..." : "" ) + " "
      -            + ( location != null ? location : "" ) + "@" + getLineNumber() + ":" + getColumnNumber();
      +        return " " + TYPES[eventType] + (fragment != null ? " seen " + printable(fragment) + "..." : "") + " "
      +                + (location != null ? location : "") + "@" + getLineNumber() + ":" + getColumnNumber();
           }
       
           @Override
      -    public int getLineNumber()
      -    {
      +    public int getLineNumber() {
               return lineNumber;
           }
       
           @Override
      -    public int getColumnNumber()
      -    {
      +    public int getColumnNumber() {
               return columnNumber;
           }
       
           @Override
      -    public boolean isWhitespace()
      -        throws XmlPullParserException
      -    {
      -        if ( eventType == TEXT || eventType == CDSECT )
      -        {
      -            if ( usePC )
      -            {
      -                for ( int i = pcStart; i < pcEnd; i++ )
      -                {
      -                    if ( !isS( pc[i] ) )
      -                        return false;
      +    public boolean isWhitespace() throws XmlPullParserException {
      +        if (eventType == TEXT || eventType == CDSECT) {
      +            if (usePC) {
      +                for (int i = pcStart; i < pcEnd; i++) {
      +                    if (!isS(pc[i])) return false;
                       }
                       return true;
      -            }
      -            else
      -            {
      -                for ( int i = posStart; i < posEnd; i++ )
      -                {
      -                    if ( !isS( buf[i] ) )
      -                        return false;
      +            } else {
      +                for (int i = posStart; i < posEnd; i++) {
      +                    if (!isS(buf[i])) return false;
                       }
                       return true;
                   }
      -        }
      -        else if ( eventType == IGNORABLE_WHITESPACE )
      -        {
      +        } else if (eventType == IGNORABLE_WHITESPACE) {
                   return true;
               }
      -        throw new XmlPullParserException( "no content available to check for whitespaces" );
      +        throw new XmlPullParserException("no content available to check for whitespaces");
           }
       
           @Override
      -    public String getText()
      -    {
      -        if ( eventType == START_DOCUMENT || eventType == END_DOCUMENT )
      -        {
      +    public String getText() {
      +        if (eventType == START_DOCUMENT || eventType == END_DOCUMENT) {
                   // throw new XmlPullParserException("no content available to read");
                   // if(roundtripSupported) {
                   // text = new String(buf, posStart, posEnd - posStart);
                   // } else {
                   return null;
                   // }
      -        }
      -        else if ( eventType == ENTITY_REF )
      -        {
      +        } else if (eventType == ENTITY_REF) {
                   return text;
               }
      -        if ( text == null )
      -        {
      -            if ( !usePC || eventType == START_TAG || eventType == END_TAG )
      -            {
      -                text = new String( buf, posStart, posEnd - posStart );
      -            }
      -            else
      -            {
      -                text = new String( pc, pcStart, pcEnd - pcStart );
      +        if (text == null) {
      +            if (!usePC || eventType == START_TAG || eventType == END_TAG) {
      +                text = new String(buf, posStart, posEnd - posStart);
      +            } else {
      +                text = new String(pc, pcStart, pcEnd - pcStart);
                   }
               }
               return text;
           }
       
           @Override
      -    public char[] getTextCharacters( int[] holderForStartAndLength )
      -    {
      -        if ( eventType == TEXT )
      -        {
      -            if ( usePC )
      -            {
      +    public char[] getTextCharacters(int[] holderForStartAndLength) {
      +        if (eventType == TEXT) {
      +            if (usePC) {
                       holderForStartAndLength[0] = pcStart;
                       holderForStartAndLength[1] = pcEnd - pcStart;
                       return pc;
      -            }
      -            else
      -            {
      +            } else {
                       holderForStartAndLength[0] = posStart;
                       holderForStartAndLength[1] = posEnd - posStart;
                       return buf;
      -
                   }
      -        }
      -        else if ( eventType == START_TAG || eventType == END_TAG || eventType == CDSECT || eventType == COMMENT
      -            || eventType == ENTITY_REF || eventType == PROCESSING_INSTRUCTION || eventType == IGNORABLE_WHITESPACE
      -            || eventType == DOCDECL )
      -        {
      +        } else if (eventType == START_TAG
      +                || eventType == END_TAG
      +                || eventType == CDSECT
      +                || eventType == COMMENT
      +                || eventType == ENTITY_REF
      +                || eventType == PROCESSING_INSTRUCTION
      +                || eventType == IGNORABLE_WHITESPACE
      +                || eventType == DOCDECL) {
                   holderForStartAndLength[0] = posStart;
                   holderForStartAndLength[1] = posEnd - posStart;
                   return buf;
      -        }
      -        else if ( eventType == START_DOCUMENT || eventType == END_DOCUMENT )
      -        {
      +        } else if (eventType == START_DOCUMENT || eventType == END_DOCUMENT) {
                   // throw new XmlPullParserException("no content available to read");
                   holderForStartAndLength[0] = holderForStartAndLength[1] = -1;
                   return null;
      -        }
      -        else
      -        {
      -            throw new IllegalArgumentException( "unknown text eventType: " + eventType );
      +        } else {
      +            throw new IllegalArgumentException("unknown text eventType: " + eventType);
               }
               // String s = getText();
               // char[] cb = null;
      @@ -1024,15 +848,11 @@ else if ( eventType == START_DOCUMENT || eventType == END_DOCUMENT )
           }
       
           @Override
      -    public String getNamespace()
      -    {
      -        if ( eventType == START_TAG )
      -        {
      +    public String getNamespace() {
      +        if (eventType == START_TAG) {
                   // return processNamespaces ? elUri[ depth - 1 ] : NO_NAMESPACE;
                   return processNamespaces ? elUri[depth] : NO_NAMESPACE;
      -        }
      -        else if ( eventType == END_TAG )
      -        {
      +        } else if (eventType == END_TAG) {
                   return processNamespaces ? elUri[depth] : NO_NAMESPACE;
               }
               return null;
      @@ -1055,41 +875,28 @@ else if ( eventType == END_TAG )
           }
       
           @Override
      -    public String getName()
      -    {
      -        if ( eventType == START_TAG )
      -        {
      +    public String getName() {
      +        if (eventType == START_TAG) {
                   // return elName[ depth - 1 ] ;
                   return elName[depth];
      -        }
      -        else if ( eventType == END_TAG )
      -        {
      +        } else if (eventType == END_TAG) {
                   return elName[depth];
      -        }
      -        else if ( eventType == ENTITY_REF )
      -        {
      -            if ( entityRefName == null )
      -            {
      -                entityRefName = newString( buf, posStart, posEnd - posStart );
      +        } else if (eventType == ENTITY_REF) {
      +            if (entityRefName == null) {
      +                entityRefName = newString(buf, posStart, posEnd - posStart);
                   }
                   return entityRefName;
      -        }
      -        else
      -        {
      +        } else {
                   return null;
               }
           }
       
           @Override
      -    public String getPrefix()
      -    {
      -        if ( eventType == START_TAG )
      -        {
      +    public String getPrefix() {
      +        if (eventType == START_TAG) {
                   // return elPrefix[ depth - 1 ] ;
                   return elPrefix[depth];
      -        }
      -        else if ( eventType == END_TAG )
      -        {
      +        } else if (eventType == END_TAG) {
                   return elPrefix[depth];
               }
               return null;
      @@ -1099,132 +906,104 @@ else if ( eventType == END_TAG )
           }
       
           @Override
      -    public boolean isEmptyElementTag()
      -        throws XmlPullParserException
      -    {
      -        if ( eventType != START_TAG )
      -            throw new XmlPullParserException( "parser must be on START_TAG to check for empty element", this, null );
      +    public boolean isEmptyElementTag() throws XmlPullParserException {
      +        if (eventType != START_TAG)
      +            throw new XmlPullParserException("parser must be on START_TAG to check for empty element", this, null);
               return emptyElementTag;
           }
       
           @Override
      -    public int getAttributeCount()
      -    {
      -        if ( eventType != START_TAG )
      -            return -1;
      +    public int getAttributeCount() {
      +        if (eventType != START_TAG) return -1;
               return attributeCount;
           }
       
           @Override
      -    public String getAttributeNamespace( int index )
      -    {
      -        if ( eventType != START_TAG )
      -            throw new IndexOutOfBoundsException( "only START_TAG can have attributes" );
      -        if ( !processNamespaces )
      -            return NO_NAMESPACE;
      -        if ( index < 0 || index >= attributeCount )
      -            throw new IndexOutOfBoundsException( "attribute position must be 0.." + ( attributeCount - 1 ) + " and not "
      -                + index );
      +    public String getAttributeNamespace(int index) {
      +        if (eventType != START_TAG) throw new IndexOutOfBoundsException("only START_TAG can have attributes");
      +        if (!processNamespaces) return NO_NAMESPACE;
      +        if (index < 0 || index >= attributeCount)
      +            throw new IndexOutOfBoundsException(
      +                    "attribute position must be 0.." + (attributeCount - 1) + " and not " + index);
               return attributeUri[index];
           }
       
           @Override
      -    public String getAttributeName( int index )
      -    {
      -        if ( eventType != START_TAG )
      -            throw new IndexOutOfBoundsException( "only START_TAG can have attributes" );
      -        if ( index < 0 || index >= attributeCount )
      -            throw new IndexOutOfBoundsException( "attribute position must be 0.." + ( attributeCount - 1 ) + " and not "
      -                + index );
      +    public String getAttributeName(int index) {
      +        if (eventType != START_TAG) throw new IndexOutOfBoundsException("only START_TAG can have attributes");
      +        if (index < 0 || index >= attributeCount)
      +            throw new IndexOutOfBoundsException(
      +                    "attribute position must be 0.." + (attributeCount - 1) + " and not " + index);
               return attributeName[index];
           }
       
           @Override
      -    public String getAttributePrefix( int index )
      -    {
      -        if ( eventType != START_TAG )
      -            throw new IndexOutOfBoundsException( "only START_TAG can have attributes" );
      -        if ( !processNamespaces )
      -            return null;
      -        if ( index < 0 || index >= attributeCount )
      -            throw new IndexOutOfBoundsException( "attribute position must be 0.." + ( attributeCount - 1 ) + " and not "
      -                + index );
      +    public String getAttributePrefix(int index) {
      +        if (eventType != START_TAG) throw new IndexOutOfBoundsException("only START_TAG can have attributes");
      +        if (!processNamespaces) return null;
      +        if (index < 0 || index >= attributeCount)
      +            throw new IndexOutOfBoundsException(
      +                    "attribute position must be 0.." + (attributeCount - 1) + " and not " + index);
               return attributePrefix[index];
           }
       
           @Override
      -    public String getAttributeType( int index )
      -    {
      -        if ( eventType != START_TAG )
      -            throw new IndexOutOfBoundsException( "only START_TAG can have attributes" );
      -        if ( index < 0 || index >= attributeCount )
      -            throw new IndexOutOfBoundsException( "attribute position must be 0.." + ( attributeCount - 1 ) + " and not "
      -                + index );
      +    public String getAttributeType(int index) {
      +        if (eventType != START_TAG) throw new IndexOutOfBoundsException("only START_TAG can have attributes");
      +        if (index < 0 || index >= attributeCount)
      +            throw new IndexOutOfBoundsException(
      +                    "attribute position must be 0.." + (attributeCount - 1) + " and not " + index);
               return "CDATA";
           }
       
           @Override
      -    public boolean isAttributeDefault( int index )
      -    {
      -        if ( eventType != START_TAG )
      -            throw new IndexOutOfBoundsException( "only START_TAG can have attributes" );
      -        if ( index < 0 || index >= attributeCount )
      -            throw new IndexOutOfBoundsException( "attribute position must be 0.." + ( attributeCount - 1 ) + " and not "
      -                + index );
      +    public boolean isAttributeDefault(int index) {
      +        if (eventType != START_TAG) throw new IndexOutOfBoundsException("only START_TAG can have attributes");
      +        if (index < 0 || index >= attributeCount)
      +            throw new IndexOutOfBoundsException(
      +                    "attribute position must be 0.." + (attributeCount - 1) + " and not " + index);
               return false;
           }
       
           @Override
      -    public String getAttributeValue( int index )
      -    {
      -        if ( eventType != START_TAG )
      -            throw new IndexOutOfBoundsException( "only START_TAG can have attributes" );
      -        if ( index < 0 || index >= attributeCount )
      -            throw new IndexOutOfBoundsException( "attribute position must be 0.." + ( attributeCount - 1 ) + " and not "
      -                + index );
      +    public String getAttributeValue(int index) {
      +        if (eventType != START_TAG) throw new IndexOutOfBoundsException("only START_TAG can have attributes");
      +        if (index < 0 || index >= attributeCount)
      +            throw new IndexOutOfBoundsException(
      +                    "attribute position must be 0.." + (attributeCount - 1) + " and not " + index);
               return attributeValue[index];
           }
       
           @Override
      -    public String getAttributeValue( String namespace, String name )
      -    {
      -        if ( eventType != START_TAG )
      -            throw new IndexOutOfBoundsException( "only START_TAG can have attributes" + getPositionDescription() );
      -        if ( name == null )
      -        {
      -            throw new IllegalArgumentException( "attribute name can not be null" );
      +    public String getAttributeValue(String namespace, String name) {
      +        if (eventType != START_TAG)
      +            throw new IndexOutOfBoundsException("only START_TAG can have attributes" + getPositionDescription());
      +        if (name == null) {
      +            throw new IllegalArgumentException("attribute name can not be null");
               }
               // TODO make check if namespace is interned!!! etc. for names!!!
      -        if ( processNamespaces )
      -        {
      -            if ( namespace == null )
      -            {
      +        if (processNamespaces) {
      +            if (namespace == null) {
                       namespace = "";
                   }
       
      -            for ( int i = 0; i < attributeCount; ++i )
      -            {
      -                if ( ( namespace == attributeUri[i] || namespace.equals( attributeUri[i] ) )
      -                    // (namespace != null && namespace.equals(attributeUri[ i ]))
      -                    // taking advantage of String.intern()
      -                    && name.equals( attributeName[i] ) )
      -                {
      +            for (int i = 0; i < attributeCount; ++i) {
      +                if ((namespace == attributeUri[i] || namespace.equals(attributeUri[i]))
      +                        // (namespace != null && namespace.equals(attributeUri[ i ]))
      +                        // taking advantage of String.intern()
      +                        && name.equals(attributeName[i])) {
                           return attributeValue[i];
                       }
                   }
      -        }
      -        else
      -        {
      -            if ( namespace != null && namespace.length() == 0 )
      -            {
      +        } else {
      +            if (namespace != null && namespace.length() == 0) {
                       namespace = null;
                   }
      -            if ( namespace != null )
      -                throw new IllegalArgumentException( "when namespaces processing is disabled attribute namespace must be null" );
      -            for ( int i = 0; i < attributeCount; ++i )
      -            {
      -                if ( name.equals( attributeName[i] ) )
      -                {
      +            if (namespace != null)
      +                throw new IllegalArgumentException(
      +                        "when namespaces processing is disabled attribute namespace must be null");
      +            for (int i = 0; i < attributeCount; ++i) {
      +                if (name.equals(attributeName[i])) {
                           return attributeValue[i];
                       }
                   }
      @@ -1233,37 +1012,38 @@ public String getAttributeValue( String namespace, String name )
           }
       
           @Override
      -    public int getEventType()
      -        throws XmlPullParserException
      -    {
      +    public int getEventType() throws XmlPullParserException {
               return eventType;
           }
       
           @Override
      -    public void require( int type, String namespace, String name )
      -        throws XmlPullParserException, IOException
      -    {
      -        if ( !processNamespaces && namespace != null )
      -        {
      -            throw new XmlPullParserException( "processing namespaces must be enabled on parser (or factory)"
      -                + " to have possible namespaces declared on elements" + ( " (position:" + getPositionDescription() )
      -                + ")" );
      -        }
      -        if ( type != getEventType() || ( namespace != null && !namespace.equals( getNamespace() ) )
      -            || ( name != null && !name.equals( getName() ) ) )
      -        {
      -            throw new XmlPullParserException( "expected event " + TYPES[type]
      -                + ( name != null ? " with name '" + name + "'" : "" )
      -                + ( namespace != null && name != null ? " and" : "" )
      -                + ( namespace != null ? " with namespace '" + namespace + "'" : "" ) + " but got"
      -                + ( type != getEventType() ? " " + TYPES[getEventType()] : "" )
      -                + ( name != null && getName() != null && !name.equals( getName() ) ? " name '" + getName() + "'" : "" )
      -                + ( namespace != null && name != null && getName() != null && !name.equals( getName() )
      -                    && getNamespace() != null && !namespace.equals( getNamespace() ) ? " and" : "" )
      -                + ( namespace != null && getNamespace() != null && !namespace.equals( getNamespace() )
      -                                ? " namespace '" + getNamespace() + "'"
      -                                : "" )
      -                + ( " (position:" + getPositionDescription() ) + ")" );
      +    public void require(int type, String namespace, String name) throws XmlPullParserException, IOException {
      +        if (!processNamespaces && namespace != null) {
      +            throw new XmlPullParserException("processing namespaces must be enabled on parser (or factory)"
      +                    + " to have possible namespaces declared on elements" + (" (position:" + getPositionDescription())
      +                    + ")");
      +        }
      +        if (type != getEventType()
      +                || (namespace != null && !namespace.equals(getNamespace()))
      +                || (name != null && !name.equals(getName()))) {
      +            throw new XmlPullParserException("expected event " + TYPES[type]
      +                    + (name != null ? " with name '" + name + "'" : "")
      +                    + (namespace != null && name != null ? " and" : "")
      +                    + (namespace != null ? " with namespace '" + namespace + "'" : "") + " but got"
      +                    + (type != getEventType() ? " " + TYPES[getEventType()] : "")
      +                    + (name != null && getName() != null && !name.equals(getName()) ? " name '" + getName() + "'" : "")
      +                    + (namespace != null
      +                                    && name != null
      +                                    && getName() != null
      +                                    && !name.equals(getName())
      +                                    && getNamespace() != null
      +                                    && !namespace.equals(getNamespace())
      +                            ? " and"
      +                            : "")
      +                    + (namespace != null && getNamespace() != null && !namespace.equals(getNamespace())
      +                            ? " namespace '" + getNamespace() + "'"
      +                            : "")
      +                    + (" (position:" + getPositionDescription()) + ")");
               }
           }
       
      @@ -1273,20 +1053,14 @@ && getNamespace() != null && !namespace.equals( getNamespace() ) ? " and" : "" )
            * @throws XmlPullParserException issue
            * @throws IOException io
            */
      -    public void skipSubTree()
      -        throws XmlPullParserException, IOException
      -    {
      -        require( START_TAG, null, null );
      +    public void skipSubTree() throws XmlPullParserException, IOException {
      +        require(START_TAG, null, null);
               int level = 1;
      -        while ( level > 0 )
      -        {
      +        while (level > 0) {
                   int eventType = next();
      -            if ( eventType == END_TAG )
      -            {
      +            if (eventType == END_TAG) {
                       --level;
      -            }
      -            else if ( eventType == START_TAG )
      -            {
      +            } else if (eventType == START_TAG) {
                       ++level;
                   }
               }
      @@ -1301,9 +1075,7 @@ else if ( eventType == START_TAG )
           // }
       
           @Override
      -    public String nextText()
      -        throws XmlPullParserException, IOException
      -    {
      +    public String nextText() throws XmlPullParserException, IOException {
               // String result = null;
               // boolean onStartTag = false;
               // if(eventType == START_TAG) {
      @@ -1324,96 +1096,73 @@ public String nextText()
               // "event TEXT it must be immediately followed by END_TAG", this, null);
               // }
               // return result;
      -        if ( getEventType() != START_TAG )
      -        {
      -            throw new XmlPullParserException( "parser must be on START_TAG to read next text", this, null );
      +        if (getEventType() != START_TAG) {
      +            throw new XmlPullParserException("parser must be on START_TAG to read next text", this, null);
               }
               int eventType = next();
      -        if ( eventType == TEXT )
      -        {
      +        if (eventType == TEXT) {
                   final String result = getText();
                   eventType = next();
      -            if ( eventType != END_TAG )
      -            {
      -                throw new XmlPullParserException( "TEXT must be immediately followed by END_TAG and not "
      -                    + TYPES[getEventType()], this, null );
      +            if (eventType != END_TAG) {
      +                throw new XmlPullParserException(
      +                        "TEXT must be immediately followed by END_TAG and not " + TYPES[getEventType()], this, null);
                   }
                   return result;
      -        }
      -        else if ( eventType == END_TAG )
      -        {
      +        } else if (eventType == END_TAG) {
                   return "";
      -        }
      -        else
      -        {
      -            throw new XmlPullParserException( "parser must be on START_TAG or TEXT to read text", this, null );
      +        } else {
      +            throw new XmlPullParserException("parser must be on START_TAG or TEXT to read text", this, null);
               }
           }
       
           @Override
      -    public int nextTag()
      -        throws XmlPullParserException, IOException
      -    {
      +    public int nextTag() throws XmlPullParserException, IOException {
               next();
      -        if ( eventType == TEXT && isWhitespace() )
      -        { // skip whitespace
      +        if (eventType == TEXT && isWhitespace()) { // skip whitespace
                   next();
               }
      -        if ( eventType != START_TAG && eventType != END_TAG )
      -        {
      -            throw new XmlPullParserException( "expected START_TAG or END_TAG not " + TYPES[getEventType()], this,
      -                                              null );
      +        if (eventType != START_TAG && eventType != END_TAG) {
      +            throw new XmlPullParserException("expected START_TAG or END_TAG not " + TYPES[getEventType()], this, null);
               }
               return eventType;
           }
       
           @Override
      -    public int next()
      -        throws XmlPullParserException, IOException
      -    {
      +    public int next() throws XmlPullParserException, IOException {
               tokenize = false;
               return nextImpl();
           }
       
           @Override
      -    public int nextToken()
      -        throws XmlPullParserException, IOException
      -    {
      +    public int nextToken() throws XmlPullParserException, IOException {
               tokenize = true;
               return nextImpl();
           }
       
      -    private int nextImpl()
      -        throws XmlPullParserException, IOException
      -    {
      +    private int nextImpl() throws XmlPullParserException, IOException {
               text = null;
               pcEnd = pcStart = 0;
               usePC = false;
               bufStart = posEnd;
      -        if ( pastEndTag )
      -        {
      +        if (pastEndTag) {
                   pastEndTag = false;
                   --depth;
                   namespaceEnd = elNamespaceCount[depth]; // less namespaces available
               }
      -        if ( emptyElementTag )
      -        {
      +        if (emptyElementTag) {
                   emptyElementTag = false;
                   pastEndTag = true;
                   return eventType = END_TAG;
               }
       
               // [1] document ::= prolog element Misc*
      -        if ( depth > 0 )
      -        {
      +        if (depth > 0) {
       
      -            if ( seenStartTag )
      -            {
      +            if (seenStartTag) {
                       seenStartTag = false;
                       return eventType = parseStartTag();
                   }
      -            if ( seenEndTag )
      -            {
      +            if (seenEndTag) {
                       seenEndTag = false;
                       return eventType = parseEndTag();
                   }
      @@ -1421,18 +1170,13 @@ private int nextImpl()
                   // ASSUMPTION: we are _on_ first character of content or markup!!!!
                   // [43] content ::= CharData? ((element | Reference | CDSect | PI | Comment) CharData?)*
                   char ch;
      -            if ( seenMarkup )
      -            { // we have read ahead ...
      +            if (seenMarkup) { // we have read ahead ...
                       seenMarkup = false;
                       ch = '<';
      -            }
      -            else if ( seenAmpersand )
      -            {
      +            } else if (seenAmpersand) {
                       seenAmpersand = false;
                       ch = '&';
      -            }
      -            else
      -            {
      +            } else {
                       ch = more();
                   }
                   posStart = pos - 1; // VERY IMPORTANT: this is correct start of event!!!
      @@ -1443,67 +1187,50 @@ else if ( seenAmpersand )
                   // when true TEXT data is not continuous (like ) and requires PC merging
                   boolean needsMerging = false;
       
      -            MAIN_LOOP: while ( true )
      -            {
      +            MAIN_LOOP:
      +            while (true) {
                       // work on MARKUP
      -                if ( ch == '<' )
      -                {
      -                    if ( hadCharData )
      -                    {
      +                if (ch == '<') {
      +                    if (hadCharData) {
                               // posEnd = pos - 1;
      -                        if ( tokenize )
      -                        {
      +                        if (tokenize) {
                                   seenMarkup = true;
                                   return eventType = TEXT;
                               }
                           }
                           ch = more();
      -                    if ( ch == '/' )
      -                    {
      -                        if ( !tokenize && hadCharData )
      -                        {
      +                    if (ch == '/') {
      +                        if (!tokenize && hadCharData) {
                                   seenEndTag = true;
                                   // posEnd = pos - 2;
                                   return eventType = TEXT;
                               }
                               return eventType = parseEndTag();
      -                    }
      -                    else if ( ch == '!' )
      -                    {
      +                    } else if (ch == '!') {
                               ch = more();
      -                        if ( ch == '-' )
      -                        {
      +                        if (ch == '-') {
                                   // note: if(tokenize == false) posStart/End is NOT changed!!!!
                                   parseComment();
      -                            if ( tokenize )
      -                                return eventType = COMMENT;
      -                            if ( !usePC && hadCharData )
      -                            {
      +                            if (tokenize) return eventType = COMMENT;
      +                            if (!usePC && hadCharData) {
                                       needsMerging = true;
      -                            }
      -                            else
      -                            {
      +                            } else {
                                       posStart = pos; // completely ignore comment
                                   }
      -                        }
      -                        else if ( ch == '[' )
      -                        {
      +                        } else if (ch == '[') {
                                   // posEnd = pos - 3;
                                   // must remember previous posStart/End as it merges with content of CDATA
                                   // int oldStart = posStart + bufAbsoluteStart;
                                   // int oldEnd = posEnd + bufAbsoluteStart;
      -                            parseCDSect( hadCharData );
      -                            if ( tokenize )
      -                                return eventType = CDSECT;
      +                            parseCDSect(hadCharData);
      +                            if (tokenize) return eventType = CDSECT;
                                   final int cdStart = posStart;
                                   final int cdEnd = posEnd;
                                   final int cdLen = cdEnd - cdStart;
       
      -                            if ( cdLen > 0 )
      -                            { // was there anything inside CDATA section?
      +                            if (cdLen > 0) { // was there anything inside CDATA section?
                                       hadCharData = true;
      -                                if ( !usePC )
      -                                {
      +                                if (!usePC) {
                                           needsMerging = true;
                                       }
                                   }
      @@ -1545,106 +1272,76 @@ else if ( ch == '[' )
                                   // needsMerging = true;
                                   // }
                                   // }
      +                        } else {
      +                            throw new XmlPullParserException(
      +                                    "unexpected character in markup " + printable(ch), this, null);
                               }
      -                        else
      -                        {
      -                            throw new XmlPullParserException( "unexpected character in markup " + printable( ch ), this,
      -                                                              null );
      -                        }
      -                    }
      -                    else if ( ch == '?' )
      -                    {
      +                    } else if (ch == '?') {
                               parsePI();
      -                        if ( tokenize )
      -                            return eventType = PROCESSING_INSTRUCTION;
      -                        if ( !usePC && hadCharData )
      -                        {
      +                        if (tokenize) return eventType = PROCESSING_INSTRUCTION;
      +                        if (!usePC && hadCharData) {
                                   needsMerging = true;
      -                        }
      -                        else
      -                        {
      +                        } else {
                                   posStart = pos; // completely ignore PI
                               }
       
      -                    }
      -                    else if ( isNameStartChar( ch ) )
      -                    {
      -                        if ( !tokenize && hadCharData )
      -                        {
      +                    } else if (isNameStartChar(ch)) {
      +                        if (!tokenize && hadCharData) {
                                   seenStartTag = true;
                                   // posEnd = pos - 2;
                                   return eventType = TEXT;
                               }
                               return eventType = parseStartTag();
      -                    }
      -                    else
      -                    {
      -                        throw new XmlPullParserException( "unexpected character in markup " + printable( ch ), this,
      -                                                          null );
      +                    } else {
      +                        throw new XmlPullParserException("unexpected character in markup " + printable(ch), this, null);
                           }
                           // do content compaction if it makes sense!!!!
       
      -                }
      -                else if ( ch == '&' )
      -                {
      +                } else if (ch == '&') {
                           // work on ENTITY
                           // posEnd = pos - 1;
      -                    if ( tokenize && hadCharData )
      -                    {
      +                    if (tokenize && hadCharData) {
                               seenAmpersand = true;
                               return eventType = TEXT;
                           }
                           final int oldStart = posStart + bufAbsoluteStart;
                           final int oldEnd = posEnd + bufAbsoluteStart;
                           parseEntityRef();
      -                    if ( tokenize )
      -                        return eventType = ENTITY_REF;
      +                    if (tokenize) return eventType = ENTITY_REF;
                           // check if replacement text can be resolved !!!
      -                    if ( resolvedEntityRefCharBuf == BUF_NOT_RESOLVED )
      -                    {
      -                        if ( entityRefName == null )
      -                        {
      -                            entityRefName = newString( buf, posStart, posEnd - posStart );
      +                    if (resolvedEntityRefCharBuf == BUF_NOT_RESOLVED) {
      +                        if (entityRefName == null) {
      +                            entityRefName = newString(buf, posStart, posEnd - posStart);
                               }
      -                        throw new XmlPullParserException( "could not resolve entity named '"
      -                            + printable( entityRefName ) + "'", this, null );
      +                        throw new XmlPullParserException(
      +                                "could not resolve entity named '" + printable(entityRefName) + "'", this, null);
                           }
                           // int entStart = posStart;
                           // int entEnd = posEnd;
                           posStart = oldStart - bufAbsoluteStart;
                           posEnd = oldEnd - bufAbsoluteStart;
      -                    if ( !usePC )
      -                    {
      -                        if ( hadCharData )
      -                        {
      +                    if (!usePC) {
      +                        if (hadCharData) {
                                   joinPC(); // posEnd is already set correctly!!!
                                   needsMerging = false;
      -                        }
      -                        else
      -                        {
      +                        } else {
                                   usePC = true;
                                   pcStart = pcEnd = 0;
                               }
                           }
                           // assert usePC == true;
                           // write into PC replacement text - do merge for replacement text!!!!
      -                    for ( char aResolvedEntity : resolvedEntityRefCharBuf )
      -                    {
      -                        if ( pcEnd >= pc.length )
      -                        {
      -                            ensurePC( pcEnd );
      +                    for (char aResolvedEntity : resolvedEntityRefCharBuf) {
      +                        if (pcEnd >= pc.length) {
      +                            ensurePC(pcEnd);
                               }
                               pc[pcEnd++] = aResolvedEntity;
      -
                           }
                           hadCharData = true;
                           // assert needsMerging == false;
      -                }
      -                else
      -                {
      +                } else {
       
      -                    if ( needsMerging )
      -                    {
      +                    if (needsMerging) {
                               // assert usePC == false;
                               joinPC(); // posEnd is already set correctly!!!
                               // posStart = pos - 1;
      @@ -1662,75 +1359,50 @@ else if ( ch == '&' )
                           // use loop locality here!!!!
                           boolean seenBracket = false;
                           boolean seenBracketBracket = false;
      -                    do
      -                    {
      +                    do {
       
                               // check that ]]> does not show in
      -                        if ( ch == ']' )
      -                        {
      -                            if ( seenBracket )
      -                            {
      +                        if (ch == ']') {
      +                            if (seenBracket) {
                                       seenBracketBracket = true;
      -                            }
      -                            else
      -                            {
      +                            } else {
                                       seenBracket = true;
                                   }
      -                        }
      -                        else if ( seenBracketBracket && ch == '>' )
      -                        {
      -                            throw new XmlPullParserException( "characters ]]> are not allowed in content", this, null );
      -                        }
      -                        else
      -                        {
      -                            if ( seenBracket )
      -                            {
      +                        } else if (seenBracketBracket && ch == '>') {
      +                            throw new XmlPullParserException("characters ]]> are not allowed in content", this, null);
      +                        } else {
      +                            if (seenBracket) {
                                       seenBracketBracket = seenBracket = false;
                                   }
                                   // assert seenTwoBrackets == seenBracket == false;
                               }
      -                        if ( normalizeInput )
      -                        {
      +                        if (normalizeInput) {
                                   // deal with normalization issues ...
      -                            if ( ch == '\r' )
      -                            {
      +                            if (ch == '\r') {
                                       normalizedCR = true;
                                       posEnd = pos - 1;
                                       // posEnd is already set
      -                                if ( !usePC )
      -                                {
      -                                    if ( posEnd > posStart )
      -                                    {
      +                                if (!usePC) {
      +                                    if (posEnd > posStart) {
                                               joinPC();
      -                                    }
      -                                    else
      -                                    {
      +                                    } else {
                                               usePC = true;
                                               pcStart = pcEnd = 0;
                                           }
                                       }
                                       // assert usePC == true;
      -                                if ( pcEnd >= pc.length )
      -                                    ensurePC( pcEnd );
      +                                if (pcEnd >= pc.length) ensurePC(pcEnd);
                                       pc[pcEnd++] = '\n';
      -                            }
      -                            else if ( ch == '\n' )
      -                            {
      +                            } else if (ch == '\n') {
                                       // if(!usePC) { joinPC(); } else { if(pcEnd >= pc.length) ensurePC(); }
      -                                if ( !normalizedCR && usePC )
      -                                {
      -                                    if ( pcEnd >= pc.length )
      -                                        ensurePC( pcEnd );
      +                                if (!normalizedCR && usePC) {
      +                                    if (pcEnd >= pc.length) ensurePC(pcEnd);
                                           pc[pcEnd++] = '\n';
                                       }
                                       normalizedCR = false;
      -                            }
      -                            else
      -                            {
      -                                if ( usePC )
      -                                {
      -                                    if ( pcEnd >= pc.length )
      -                                        ensurePC( pcEnd );
      +                            } else {
      +                                if (usePC) {
      +                                    if (pcEnd >= pc.length) ensurePC(pcEnd);
                                           pc[pcEnd++] = ch;
                                       }
                                       normalizedCR = false;
      @@ -1738,66 +1410,50 @@ else if ( ch == '\n' )
                               }
       
                               ch = more();
      -                    }
      -                    while ( ch != '<' && ch != '&' );
      +                    } while (ch != '<' && ch != '&');
                           posEnd = pos - 1;
                           continue MAIN_LOOP; // skip ch = more() from below - we are already ahead ...
                       }
                       ch = more();
                   } // endless while(true)
      -        }
      -        else
      -        {
      -            if ( seenRoot )
      -            {
      +        } else {
      +            if (seenRoot) {
                       return parseEpilog();
      -            }
      -            else
      -            {
      +            } else {
                       return parseProlog();
                   }
               }
           }
       
      -    private int parseProlog()
      -        throws XmlPullParserException, IOException
      -    {
      +    private int parseProlog() throws XmlPullParserException, IOException {
               // [2] prolog: ::= XMLDecl? Misc* (doctypedecl Misc*)? and look for [39] element
       
               char ch;
      -        if ( seenMarkup )
      -        {
      +        if (seenMarkup) {
                   ch = buf[pos - 1];
      -        }
      -        else
      -        {
      +        } else {
                   ch = more();
               }
       
      -        if ( eventType == START_DOCUMENT )
      -        {
      +        if (eventType == START_DOCUMENT) {
                   // bootstrap parsing with getting first character input!
                   // deal with BOM
                   // detect BOM and crop it (Unicode int Order Mark)
      -            if ( ch == '\uFFFE' )
      -            {
      -                throw new XmlPullParserException( "first character in input was UNICODE noncharacter (0xFFFE)"
      -                    + "- input requires int swapping", this, null );
      +            if (ch == '\uFFFE') {
      +                throw new XmlPullParserException(
      +                        "first character in input was UNICODE noncharacter (0xFFFE)" + "- input requires int swapping",
      +                        this,
      +                        null);
                   }
      -            if ( ch == '\uFEFF' )
      -            {
      +            if (ch == '\uFEFF') {
                       // skipping UNICODE int Order Mark (so called BOM)
                       ch = more();
      -            }
      -            else if ( ch == '\uFFFD' )
      -            {
      +            } else if (ch == '\uFFFD') {
                       // UTF-16 BOM in an UTF-8 encoded file?
                       // This is a hack...not the best way to check for BOM in UTF-16
                       ch = more();
      -                if ( ch == '\uFFFD' )
      -                {
      -                    throw new XmlPullParserException( "UTF-16 BOM in a UTF-8 encoded file is incompatible", this,
      -                                                      null );
      +                if (ch == '\uFFFD') {
      +                    throw new XmlPullParserException("UTF-16 BOM in a UTF-8 encoded file is incompatible", this, null);
                       }
                   }
               }
      @@ -1806,331 +1462,227 @@ else if ( ch == '\uFFFD' )
               posStart = pos - 1;
               final boolean normalizeIgnorableWS = tokenize && !roundtripSupported;
               boolean normalizedCR = false;
      -        while ( true )
      -        {
      +        while (true) {
                   // deal with Misc
                   // [27] Misc ::= Comment | PI | S
                   // deal with docdecl --> mark it!
                   // else parseStartTag seen <[^/]
      -            if ( ch == '<' )
      -            {
      -                if ( gotS && tokenize )
      -                {
      +            if (ch == '<') {
      +                if (gotS && tokenize) {
                           posEnd = pos - 1;
                           seenMarkup = true;
                           return eventType = IGNORABLE_WHITESPACE;
                       }
                       ch = more();
      -                if ( ch == '?' )
      -                {
      +                if (ch == '?') {
                           // check if it is 'xml'
                           // deal with XMLDecl
                           boolean isXMLDecl = parsePI();
      -                    if ( tokenize )
      -                    {
      -                        if ( isXMLDecl )
      -                        {
      +                    if (tokenize) {
      +                        if (isXMLDecl) {
                                   return eventType = START_DOCUMENT;
                               }
                               return eventType = PROCESSING_INSTRUCTION;
                           }
      -                }
      -                else if ( ch == '!' )
      -                {
      +                } else if (ch == '!') {
                           ch = more();
      -                    if ( ch == 'D' )
      -                    {
      -                        if ( seenDocdecl )
      -                        {
      -                            throw new XmlPullParserException( "only one docdecl allowed in XML document", this, null );
      +                    if (ch == 'D') {
      +                        if (seenDocdecl) {
      +                            throw new XmlPullParserException("only one docdecl allowed in XML document", this, null);
                               }
                               seenDocdecl = true;
                               parseDocdecl();
      -                        if ( tokenize )
      -                            return eventType = DOCDECL;
      -                    }
      -                    else if ( ch == '-' )
      -                    {
      +                        if (tokenize) return eventType = DOCDECL;
      +                    } else if (ch == '-') {
                               parseComment();
      -                        if ( tokenize )
      -                            return eventType = COMMENT;
      -                    }
      -                    else
      -                    {
      -                        throw new XmlPullParserException( "unexpected markup  posStart )
      -                            {
      +                            if (posEnd > posStart) {
                                       joinPC();
      -                            }
      -                            else
      -                            {
      +                            } else {
                                       usePC = true;
                                       pcStart = pcEnd = 0;
                                   }
                               }
                               // assert usePC == true;
      -                        if ( pcEnd >= pc.length )
      -                            ensurePC( pcEnd );
      +                        if (pcEnd >= pc.length) ensurePC(pcEnd);
                               pc[pcEnd++] = '\n';
      -                    }
      -                    else if ( ch == '\n' )
      -                    {
      -                        if ( !normalizedCR && usePC )
      -                        {
      -                            if ( pcEnd >= pc.length )
      -                                ensurePC( pcEnd );
      +                    } else if (ch == '\n') {
      +                        if (!normalizedCR && usePC) {
      +                            if (pcEnd >= pc.length) ensurePC(pcEnd);
                                   pc[pcEnd++] = '\n';
                               }
                               normalizedCR = false;
      -                    }
      -                    else
      -                    {
      -                        if ( usePC )
      -                        {
      -                            if ( pcEnd >= pc.length )
      -                                ensurePC( pcEnd );
      +                    } else {
      +                        if (usePC) {
      +                            if (pcEnd >= pc.length) ensurePC(pcEnd);
                                   pc[pcEnd++] = ch;
                               }
                               normalizedCR = false;
                           }
                       }
      -            }
      -            else
      -            {
      -                throw new XmlPullParserException( "only whitespace content allowed before start tag and not "
      -                    + printable( ch ), this, null );
      +            } else {
      +                throw new XmlPullParserException(
      +                        "only whitespace content allowed before start tag and not " + printable(ch), this, null);
                   }
                   ch = more();
               }
           }
       
      -    private int parseEpilog()
      -        throws XmlPullParserException, IOException
      -    {
      -        if ( eventType == END_DOCUMENT )
      -        {
      -            throw new XmlPullParserException( "already reached end of XML input", this, null );
      +    private int parseEpilog() throws XmlPullParserException, IOException {
      +        if (eventType == END_DOCUMENT) {
      +            throw new XmlPullParserException("already reached end of XML input", this, null);
               }
      -        if ( reachedEnd )
      -        {
      +        if (reachedEnd) {
                   return eventType = END_DOCUMENT;
               }
               boolean gotS = false;
               final boolean normalizeIgnorableWS = tokenize && !roundtripSupported;
               boolean normalizedCR = false;
      -        try
      -        {
      +        try {
                   // epilog: Misc*
                   char ch;
      -            if ( seenMarkup )
      -            {
      +            if (seenMarkup) {
                       ch = buf[pos - 1];
      -            }
      -            else
      -            {
      +            } else {
                       ch = more();
                   }
                   seenMarkup = false;
                   posStart = pos - 1;
      -            if ( !reachedEnd )
      -            {
      -                while ( true )
      -                {
      +            if (!reachedEnd) {
      +                while (true) {
                           // deal with Misc
                           // [27] Misc ::= Comment | PI | S
      -                    if ( ch == '<' )
      -                    {
      -                        if ( gotS && tokenize )
      -                        {
      +                    if (ch == '<') {
      +                        if (gotS && tokenize) {
                                   posEnd = pos - 1;
                                   seenMarkup = true;
                                   return eventType = IGNORABLE_WHITESPACE;
                               }
                               ch = more();
      -                        if ( reachedEnd )
      -                        {
      +                        if (reachedEnd) {
                                   break;
                               }
      -                        if ( ch == '?' )
      -                        {
      +                        if (ch == '?') {
                                   // check if it is 'xml'
                                   // deal with XMLDecl
                                   parsePI();
      -                            if ( tokenize )
      -                                return eventType = PROCESSING_INSTRUCTION;
      +                            if (tokenize) return eventType = PROCESSING_INSTRUCTION;
       
      -                        }
      -                        else if ( ch == '!' )
      -                        {
      +                        } else if (ch == '!') {
                                   ch = more();
      -                            if ( reachedEnd )
      -                            {
      +                            if (reachedEnd) {
                                       break;
                                   }
      -                            if ( ch == 'D' )
      -                            {
      +                            if (ch == 'D') {
                                       parseDocdecl(); // FIXME
      -                                if ( tokenize )
      -                                    return eventType = DOCDECL;
      -                            }
      -                            else if ( ch == '-' )
      -                            {
      +                                if (tokenize) return eventType = DOCDECL;
      +                            } else if (ch == '-') {
                                       parseComment();
      -                                if ( tokenize )
      -                                    return eventType = COMMENT;
      +                                if (tokenize) return eventType = COMMENT;
      +                            } else {
      +                                throw new XmlPullParserException("unexpected markup  posStart )
      -                                    {
      +                                    if (posEnd > posStart) {
                                               joinPC();
      -                                    }
      -                                    else
      -                                    {
      +                                    } else {
                                               usePC = true;
                                               pcStart = pcEnd = 0;
                                           }
                                       }
                                       // assert usePC == true;
      -                                if ( pcEnd >= pc.length )
      -                                    ensurePC( pcEnd );
      +                                if (pcEnd >= pc.length) ensurePC(pcEnd);
                                       pc[pcEnd++] = '\n';
      -                            }
      -                            else if ( ch == '\n' )
      -                            {
      -                                if ( !normalizedCR && usePC )
      -                                {
      -                                    if ( pcEnd >= pc.length )
      -                                        ensurePC( pcEnd );
      +                            } else if (ch == '\n') {
      +                                if (!normalizedCR && usePC) {
      +                                    if (pcEnd >= pc.length) ensurePC(pcEnd);
                                           pc[pcEnd++] = '\n';
                                       }
                                       normalizedCR = false;
      -                            }
      -                            else
      -                            {
      -                                if ( usePC )
      -                                {
      -                                    if ( pcEnd >= pc.length )
      -                                        ensurePC( pcEnd );
      +                            } else {
      +                                if (usePC) {
      +                                    if (pcEnd >= pc.length) ensurePC(pcEnd);
                                           pc[pcEnd++] = ch;
                                       }
                                       normalizedCR = false;
                                   }
                               }
      -                    }
      -                    else
      -                    {
      -                        throw new XmlPullParserException( "in epilog non whitespace content is not allowed but got "
      -                            + printable( ch ), this, null );
      +                    } else {
      +                        throw new XmlPullParserException(
      +                                "in epilog non whitespace content is not allowed but got " + printable(ch), this, null);
                           }
                           ch = more();
      -                    if ( reachedEnd )
      -                    {
      +                    if (reachedEnd) {
                               break;
                           }
      -
                       }
                   }
       
                   // throw Exception("unexpected content in epilog
                   // catch EOFException return END_DOCUMENT
                   // try {
      -        }
      -        catch ( EOFException ex )
      -        {
      +        } catch (EOFException ex) {
                   reachedEnd = true;
               }
      -        if ( tokenize && gotS )
      -        {
      +        if (tokenize && gotS) {
                   posEnd = pos; // well - this is LAST available character pos
                   return eventType = IGNORABLE_WHITESPACE;
               }
               return eventType = END_DOCUMENT;
           }
       
      -    public int parseEndTag()
      -        throws XmlPullParserException, IOException
      -    {
      +    public int parseEndTag() throws XmlPullParserException, IOException {
               // ASSUMPTION ch is past "'
               char ch = more();
      -        if ( !isNameStartChar( ch ) )
      -        {
      -            throw new XmlPullParserException( "expected name start and not " + printable( ch ), this, null );
      +        if (!isNameStartChar(ch)) {
      +            throw new XmlPullParserException("expected name start and not " + printable(ch), this, null);
               }
               posStart = pos - 3;
               final int nameStart = pos - 1 + bufAbsoluteStart;
      -        do
      -        {
      +        do {
                   ch = more();
      -        }
      -        while ( isNameChar( ch ) );
      +        } while (isNameChar(ch));
       
               // now we go one level down -- do checks
               // --depth; //FIXME
      @@ -2141,36 +1693,39 @@ public int parseEndTag()
               // int last = pos - 1;
               int off = nameStart - bufAbsoluteStart;
               // final int len = last - off;
      -        final int len = ( pos - 1 ) - off;
      +        final int len = (pos - 1) - off;
               final char[] cbuf = elRawName[depth];
      -        if ( elRawNameEnd[depth] != len )
      -        {
      +        if (elRawNameEnd[depth] != len) {
                   // construct strings for exception
      -            final String startname = new String( cbuf, 0, elRawNameEnd[depth] );
      -            final String endname = new String( buf, off, len );
      -            throw new XmlPullParserException( "end tag name  must match start tag name <" + startname
      -                + ">" + " from line " + elRawNameLine[depth], this, null );
      -        }
      -        for ( int i = 0; i < len; i++ )
      -        {
      -            if ( buf[off++] != cbuf[i] )
      -            {
      +            final String startname = new String(cbuf, 0, elRawNameEnd[depth]);
      +            final String endname = new String(buf, off, len);
      +            throw new XmlPullParserException(
      +                    "end tag name  must match start tag name <" + startname + ">" + " from line "
      +                            + elRawNameLine[depth],
      +                    this,
      +                    null);
      +        }
      +        for (int i = 0; i < len; i++) {
      +            if (buf[off++] != cbuf[i]) {
                       // construct strings for exception
      -                final String startname = new String( cbuf, 0, len );
      -                final String endname = new String( buf, off - i - 1, len );
      -                throw new XmlPullParserException( "end tag name  must be the same as start tag <"
      -                    + startname + ">" + " from line " + elRawNameLine[depth], this, null );
      +                final String startname = new String(cbuf, 0, len);
      +                final String endname = new String(buf, off - i - 1, len);
      +                throw new XmlPullParserException(
      +                        "end tag name  must be the same as start tag <" + startname + ">"
      +                                + " from line " + elRawNameLine[depth],
      +                        this,
      +                        null);
                   }
               }
       
      -        while ( isS( ch ) )
      -        {
      +        while (isS(ch)) {
                   ch = more();
               } // skip additional white spaces
      -        if ( ch != '>' )
      -        {
      -            throw new XmlPullParserException( "expected > to finsh end tag not " + printable( ch ) + " from line "
      -                + elRawNameLine[depth], this, null );
      +        if (ch != '>') {
      +            throw new XmlPullParserException(
      +                    "expected > to finsh end tag not " + printable(ch) + " from line " + elRawNameLine[depth],
      +                    this,
      +                    null);
               }
       
               // namespaceEnd = elNamespaceCount[ depth ]; //FIXME
      @@ -2180,9 +1735,7 @@ public int parseEndTag()
               return eventType = END_TAG;
           }
       
      -    public int parseStartTag()
      -        throws XmlPullParserException, IOException
      -    {
      +    public int parseStartTag() throws XmlPullParserException, IOException {
               // ASSUMPTION ch is past '
               // [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'
      @@ -2196,19 +1749,16 @@ public int parseStartTag()
               final int nameStart = pos - 1 + bufAbsoluteStart;
               int colonPos = -1;
               char ch = buf[pos - 1];
      -        if ( ch == ':' && processNamespaces )
      -            throw new XmlPullParserException( "when namespaces processing enabled colon can not be at element name start",
      -                                              this, null );
      -        while ( true )
      -        {
      +        if (ch == ':' && processNamespaces)
      +            throw new XmlPullParserException(
      +                    "when namespaces processing enabled colon can not be at element name start", this, null);
      +        while (true) {
                   ch = more();
      -            if ( !isNameChar( ch ) )
      -                break;
      -            if ( ch == ':' && processNamespaces )
      -            {
      -                if ( colonPos != -1 )
      -                    throw new XmlPullParserException( "only one colon is allowed in name of element when namespaces are enabled",
      -                                                      this, null );
      +            if (!isNameChar(ch)) break;
      +            if (ch == ':' && processNamespaces) {
      +                if (colonPos != -1)
      +                    throw new XmlPullParserException(
      +                            "only one colon is allowed in name of element when namespaces are enabled", this, null);
                       colonPos = pos - 1 + bufAbsoluteStart;
                   }
               }
      @@ -2218,12 +1768,11 @@ public int parseStartTag()
       
               // TODO check for efficient interning and then use elRawNameInterned!!!!
       
      -        int elLen = ( pos - 1 ) - ( nameStart - bufAbsoluteStart );
      -        if ( elRawName[depth] == null || elRawName[depth].length < elLen )
      -        {
      +        int elLen = (pos - 1) - (nameStart - bufAbsoluteStart);
      +        if (elRawName[depth] == null || elRawName[depth].length < elLen) {
                   elRawName[depth] = new char[2 * elLen];
               }
      -        System.arraycopy( buf, nameStart - bufAbsoluteStart, elRawName[depth], 0, elLen );
      +        System.arraycopy(buf, nameStart - bufAbsoluteStart, elRawName[depth], 0, elLen);
               elRawNameEnd[depth] = elLen;
               elRawNameLine[depth] = lineNumber;
       
      @@ -2231,79 +1780,57 @@ public int parseStartTag()
       
               // work on prefixes and namespace URI
               String prefix = null;
      -        if ( processNamespaces )
      -        {
      -            if ( colonPos != -1 )
      -            {
      -                prefix = elPrefix[depth] = newString( buf, nameStart - bufAbsoluteStart, colonPos - nameStart );
      -                name = elName[depth] = newString( buf, colonPos + 1 - bufAbsoluteStart,
      -                                                  // (pos -1) - (colonPos + 1));
      -                                                  pos - 2 - ( colonPos - bufAbsoluteStart ) );
      -            }
      -            else
      -            {
      +        if (processNamespaces) {
      +            if (colonPos != -1) {
      +                prefix = elPrefix[depth] = newString(buf, nameStart - bufAbsoluteStart, colonPos - nameStart);
      +                name = elName[depth] = newString(
      +                        buf,
      +                        colonPos + 1 - bufAbsoluteStart,
      +                        // (pos -1) - (colonPos + 1));
      +                        pos - 2 - (colonPos - bufAbsoluteStart));
      +            } else {
                       prefix = elPrefix[depth] = null;
      -                name = elName[depth] = newString( buf, nameStart - bufAbsoluteStart, elLen );
      +                name = elName[depth] = newString(buf, nameStart - bufAbsoluteStart, elLen);
                   }
      -        }
      -        else
      -        {
      -
      -            name = elName[depth] = newString( buf, nameStart - bufAbsoluteStart, elLen );
      +        } else {
       
      +            name = elName[depth] = newString(buf, nameStart - bufAbsoluteStart, elLen);
               }
       
      -        while ( true )
      -        {
      +        while (true) {
       
      -            while ( isS( ch ) )
      -            {
      +            while (isS(ch)) {
                       ch = more();
                   } // skip additional white spaces
       
      -            if ( ch == '>' )
      -            {
      +            if (ch == '>') {
                       break;
      -            }
      -            else if ( ch == '/' )
      -            {
      -                if ( emptyElementTag )
      -                    throw new XmlPullParserException( "repeated / in tag declaration", this, null );
      +            } else if (ch == '/') {
      +                if (emptyElementTag) throw new XmlPullParserException("repeated / in tag declaration", this, null);
                       emptyElementTag = true;
                       ch = more();
      -                if ( ch != '>' )
      -                    throw new XmlPullParserException( "expected > to end empty tag not " + printable( ch ), this,
      -                                                      null );
      +                if (ch != '>')
      +                    throw new XmlPullParserException("expected > to end empty tag not " + printable(ch), this, null);
                       break;
      -            }
      -            else if ( isNameStartChar( ch ) )
      -            {
      +            } else if (isNameStartChar(ch)) {
                       ch = parseAttribute();
                       ch = more();
      -            }
      -            else
      -            {
      -                throw new XmlPullParserException( "start tag unexpected character " + printable( ch ), this, null );
      +            } else {
      +                throw new XmlPullParserException("start tag unexpected character " + printable(ch), this, null);
                   }
                   // ch = more(); // skip space
               }
       
               // now when namespaces were declared we can resolve them
      -        if ( processNamespaces )
      -        {
      -            String uri = getNamespace( prefix );
      -            if ( uri == null )
      -            {
      -                if ( prefix == null )
      -                { // no prefix and no uri => use default namespace
      +        if (processNamespaces) {
      +            String uri = getNamespace(prefix);
      +            if (uri == null) {
      +                if (prefix == null) { // no prefix and no uri => use default namespace
                           uri = NO_NAMESPACE;
      +                } else {
      +                    throw new XmlPullParserException(
      +                            "could not determine namespace bound to element prefix " + prefix, this, null);
                       }
      -                else
      -                {
      -                    throw new XmlPullParserException( "could not determine namespace bound to element prefix " + prefix,
      -                                                      this, null );
      -                }
      -
                   }
                   elUri[depth] = uri;
       
      @@ -2312,22 +1839,16 @@ else if ( isNameStartChar( ch ) )
                   // uri = "";
                   // }
                   // resolve attribute namespaces
      -            for ( int i = 0; i < attributeCount; i++ )
      -            {
      +            for (int i = 0; i < attributeCount; i++) {
                       final String attrPrefix = attributePrefix[i];
      -                if ( attrPrefix != null )
      -                {
      -                    final String attrUri = getNamespace( attrPrefix );
      -                    if ( attrUri == null )
      -                    {
      -                        throw new XmlPullParserException( "could not determine namespace bound to attribute prefix "
      -                            + attrPrefix, this, null );
      -
      +                if (attrPrefix != null) {
      +                    final String attrUri = getNamespace(attrPrefix);
      +                    if (attrUri == null) {
      +                        throw new XmlPullParserException(
      +                                "could not determine namespace bound to attribute prefix " + attrPrefix, this, null);
                           }
                           attributeUri[i] = attrUri;
      -                }
      -                else
      -                {
      +                } else {
                           attributeUri[i] = NO_NAMESPACE;
                       }
                   }
      @@ -2336,51 +1857,41 @@ else if ( isNameStartChar( ch ) )
                   // [ WFC: Unique Att Spec ]
                   // check namespaced attribute uniqueness constraint!!!
       
      -            for ( int i = 1; i < attributeCount; i++ )
      -            {
      -                for ( int j = 0; j < i; j++ )
      -                {
      -                    if ( attributeUri[j] == attributeUri[i]
      -                        && ( allStringsInterned && attributeName[j].equals( attributeName[i] )
      -                            || ( !allStringsInterned && attributeNameHash[j] == attributeNameHash[i]
      -                                && attributeName[j].equals( attributeName[i] ) ) )
      -
      -                    )
      -                    {
      +            for (int i = 1; i < attributeCount; i++) {
      +                for (int j = 0; j < i; j++) {
      +                    if (attributeUri[j] == attributeUri[i]
      +                            && (allStringsInterned && attributeName[j].equals(attributeName[i])
      +                                    || (!allStringsInterned
      +                                            && attributeNameHash[j] == attributeNameHash[i]
      +                                            && attributeName[j].equals(attributeName[i])))) {
      +
                               // prepare data for nice error message?
                               String attr1 = attributeName[j];
      -                        if ( attributeUri[j] != null )
      -                            attr1 = attributeUri[j] + ":" + attr1;
      +                        if (attributeUri[j] != null) attr1 = attributeUri[j] + ":" + attr1;
                               String attr2 = attributeName[i];
      -                        if ( attributeUri[i] != null )
      -                            attr2 = attributeUri[i] + ":" + attr2;
      -                        throw new XmlPullParserException( "duplicated attributes " + attr1 + " and " + attr2, this,
      -                                                          null );
      +                        if (attributeUri[i] != null) attr2 = attributeUri[i] + ":" + attr2;
      +                        throw new XmlPullParserException(
      +                                "duplicated attributes " + attr1 + " and " + attr2, this, null);
                           }
                       }
                   }
       
      -        }
      -        else
      -        { // ! processNamespaces
      +        } else { // ! processNamespaces
       
                   // [ WFC: Unique Att Spec ]
                   // check raw attribute uniqueness constraint!!!
      -            for ( int i = 1; i < attributeCount; i++ )
      -            {
      -                for ( int j = 0; j < i; j++ )
      -                {
      -                    if ( ( allStringsInterned && attributeName[j].equals( attributeName[i] )
      -                        || ( !allStringsInterned && attributeNameHash[j] == attributeNameHash[i]
      -                            && attributeName[j].equals( attributeName[i] ) ) )
      -
      -                    )
      -                    {
      +            for (int i = 1; i < attributeCount; i++) {
      +                for (int j = 0; j < i; j++) {
      +                    if ((allStringsInterned && attributeName[j].equals(attributeName[i])
      +                            || (!allStringsInterned
      +                                    && attributeNameHash[j] == attributeNameHash[i]
      +                                    && attributeName[j].equals(attributeName[i])))) {
      +
                               // prepare data for nice error message?
                               final String attr1 = attributeName[j];
                               final String attr2 = attributeName[i];
      -                        throw new XmlPullParserException( "duplicated attributes " + attr1 + " and " + attr2, this,
      -                                                          null );
      +                        throw new XmlPullParserException(
      +                                "duplicated attributes " + attr1 + " and " + attr2, this, null);
                           }
                       }
                   }
      @@ -2391,9 +1902,7 @@ else if ( isNameStartChar( ch ) )
               return eventType = START_TAG;
           }
       
      -    private char parseAttribute()
      -        throws XmlPullParserException, IOException
      -    {
      +    private char parseAttribute() throws XmlPullParserException, IOException {
               // parse attribute
               // [41] Attribute ::= Name Eq AttValue
               // [WFC: No External Entity References]
      @@ -2402,144 +1911,115 @@ private char parseAttribute()
               final int nameStart = pos - 1 + bufAbsoluteStart;
               int colonPos = -1;
               char ch = buf[pos - 1];
      -        if ( ch == ':' && processNamespaces )
      -            throw new XmlPullParserException( "when namespaces processing enabled colon can not be at attribute name start",
      -                                              this, null );
      +        if (ch == ':' && processNamespaces)
      +            throw new XmlPullParserException(
      +                    "when namespaces processing enabled colon can not be at attribute name start", this, null);
       
               boolean startsWithXmlns = processNamespaces && ch == 'x';
               int xmlnsPos = 0;
       
               ch = more();
      -        while ( isNameChar( ch ) )
      -        {
      -            if ( processNamespaces )
      -            {
      -                if ( startsWithXmlns && xmlnsPos < 5 )
      -                {
      +        while (isNameChar(ch)) {
      +            if (processNamespaces) {
      +                if (startsWithXmlns && xmlnsPos < 5) {
                           ++xmlnsPos;
      -                    if ( xmlnsPos == 1 )
      -                    {
      -                        if ( ch != 'm' )
      -                            startsWithXmlns = false;
      -                    }
      -                    else if ( xmlnsPos == 2 )
      -                    {
      -                        if ( ch != 'l' )
      -                            startsWithXmlns = false;
      -                    }
      -                    else if ( xmlnsPos == 3 )
      -                    {
      -                        if ( ch != 'n' )
      -                            startsWithXmlns = false;
      -                    }
      -                    else if ( xmlnsPos == 4 )
      -                    {
      -                        if ( ch != 's' )
      -                            startsWithXmlns = false;
      -                    }
      -                    else if ( xmlnsPos == 5 )
      -                    {
      -                        if ( ch != ':' )
      -                            throw new XmlPullParserException( "after xmlns in attribute name must be colon"
      -                                + "when namespaces are enabled", this, null );
      +                    if (xmlnsPos == 1) {
      +                        if (ch != 'm') startsWithXmlns = false;
      +                    } else if (xmlnsPos == 2) {
      +                        if (ch != 'l') startsWithXmlns = false;
      +                    } else if (xmlnsPos == 3) {
      +                        if (ch != 'n') startsWithXmlns = false;
      +                    } else if (xmlnsPos == 4) {
      +                        if (ch != 's') startsWithXmlns = false;
      +                    } else if (xmlnsPos == 5) {
      +                        if (ch != ':')
      +                            throw new XmlPullParserException(
      +                                    "after xmlns in attribute name must be colon" + "when namespaces are enabled",
      +                                    this,
      +                                    null);
                               // colonPos = pos - 1 + bufAbsoluteStart;
                           }
                       }
      -                if ( ch == ':' )
      -                {
      -                    if ( colonPos != -1 )
      -                        throw new XmlPullParserException( "only one colon is allowed in attribute name"
      -                            + " when namespaces are enabled", this, null );
      +                if (ch == ':') {
      +                    if (colonPos != -1)
      +                        throw new XmlPullParserException(
      +                                "only one colon is allowed in attribute name" + " when namespaces are enabled",
      +                                this,
      +                                null);
                           colonPos = pos - 1 + bufAbsoluteStart;
                       }
                   }
                   ch = more();
               }
       
      -        ensureAttributesCapacity( attributeCount );
      +        ensureAttributesCapacity(attributeCount);
       
               // --- start processing attributes
               String name = null;
               String prefix = null;
               // work on prefixes and namespace URI
      -        if ( processNamespaces )
      -        {
      -            if ( xmlnsPos < 4 )
      -                startsWithXmlns = false;
      -            if ( startsWithXmlns )
      -            {
      -                if ( colonPos != -1 )
      -                {
      +        if (processNamespaces) {
      +            if (xmlnsPos < 4) startsWithXmlns = false;
      +            if (startsWithXmlns) {
      +                if (colonPos != -1) {
                           // prefix = attributePrefix[ attributeCount ] = null;
      -                    final int nameLen = pos - 2 - ( colonPos - bufAbsoluteStart );
      -                    if ( nameLen == 0 )
      -                    {
      -                        throw new XmlPullParserException( "namespace prefix is required after xmlns: "
      -                            + " when namespaces are enabled", this, null );
      +                    final int nameLen = pos - 2 - (colonPos - bufAbsoluteStart);
      +                    if (nameLen == 0) {
      +                        throw new XmlPullParserException(
      +                                "namespace prefix is required after xmlns: " + " when namespaces are enabled",
      +                                this,
      +                                null);
                           }
                           name = // attributeName[ attributeCount ] =
      -                        newString( buf, colonPos - bufAbsoluteStart + 1, nameLen );
      +                            newString(buf, colonPos - bufAbsoluteStart + 1, nameLen);
                           // pos - 1 - (colonPos + 1 - bufAbsoluteStart)
                       }
      -            }
      -            else
      -            {
      -                if ( colonPos != -1 )
      -                {
      +            } else {
      +                if (colonPos != -1) {
                           int prefixLen = colonPos - nameStart;
      -                    prefix =
      -                        attributePrefix[attributeCount] = newString( buf, nameStart - bufAbsoluteStart, prefixLen );
      +                    prefix = attributePrefix[attributeCount] = newString(buf, nameStart - bufAbsoluteStart, prefixLen);
                           // colonPos - (nameStart - bufAbsoluteStart));
      -                    int nameLen = pos - 2 - ( colonPos - bufAbsoluteStart );
      -                    name = attributeName[attributeCount] = newString( buf, colonPos - bufAbsoluteStart + 1, nameLen );
      +                    int nameLen = pos - 2 - (colonPos - bufAbsoluteStart);
      +                    name = attributeName[attributeCount] = newString(buf, colonPos - bufAbsoluteStart + 1, nameLen);
                           // pos - 1 - (colonPos + 1 - bufAbsoluteStart));
       
                           // name.substring(0, colonPos-nameStart);
      -                }
      -                else
      -                {
      +                } else {
                           prefix = attributePrefix[attributeCount] = null;
                           name = attributeName[attributeCount] =
      -                        newString( buf, nameStart - bufAbsoluteStart, pos - 1 - ( nameStart - bufAbsoluteStart ) );
      +                            newString(buf, nameStart - bufAbsoluteStart, pos - 1 - (nameStart - bufAbsoluteStart));
                       }
      -                if ( !allStringsInterned )
      -                {
      +                if (!allStringsInterned) {
                           attributeNameHash[attributeCount] = name.hashCode();
                       }
                   }
       
      -        }
      -        else
      -        {
      +        } else {
                   // retrieve name
                   name = attributeName[attributeCount] =
      -                newString( buf, nameStart - bufAbsoluteStart, pos - 1 - ( nameStart - bufAbsoluteStart ) );
      +                    newString(buf, nameStart - bufAbsoluteStart, pos - 1 - (nameStart - bufAbsoluteStart));
                   //// assert name != null;
      -            if ( !allStringsInterned )
      -            {
      +            if (!allStringsInterned) {
                       attributeNameHash[attributeCount] = name.hashCode();
                   }
               }
       
               // [25] Eq ::= S? '=' S?
      -        while ( isS( ch ) )
      -        {
      +        while (isS(ch)) {
                   ch = more();
               } // skip additional spaces
      -        if ( ch != '=' )
      -            throw new XmlPullParserException( "expected = after attribute name", this, null );
      +        if (ch != '=') throw new XmlPullParserException("expected = after attribute name", this, null);
               ch = more();
      -        while ( isS( ch ) )
      -        {
      +        while (isS(ch)) {
                   ch = more();
               } // skip additional spaces
       
               // [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
               // | "'" ([^<&'] | Reference)* "'"
               final char delimit = ch;
      -        if ( delimit != '"' && delimit != '\'' )
      -            throw new XmlPullParserException( "attribute value must start with quotation or apostrophe not "
      -                + printable( delimit ), this, null );
      +        if (delimit != '"' && delimit != '\'')
      +            throw new XmlPullParserException(
      +                    "attribute value must start with quotation or apostrophe not " + printable(delimit), this, null);
               // parse until delimit or < and resolve Reference
               // [67] Reference ::= EntityRef | CharRef
               // int valueStart = pos + bufAbsoluteStart;
      @@ -2549,95 +2029,68 @@ else if ( xmlnsPos == 5 )
               pcStart = pcEnd;
               posStart = pos;
       
      -        while ( true )
      -        {
      +        while (true) {
                   ch = more();
      -            if ( ch == delimit )
      -            {
      +            if (ch == delimit) {
                       break;
                   }
      -            if ( ch == '<' )
      -            {
      -                throw new XmlPullParserException( "markup not allowed inside attribute value - illegal < ", this,
      -                                                  null );
      +            if (ch == '<') {
      +                throw new XmlPullParserException("markup not allowed inside attribute value - illegal < ", this, null);
                   }
      -            if ( ch == '&' )
      -            {
      +            if (ch == '&') {
                       extractEntityRef();
      -            }
      -            else if ( ch == '\t' || ch == '\n' || ch == '\r' )
      -            {
      +            } else if (ch == '\t' || ch == '\n' || ch == '\r') {
                       // do attribute value normalization
                       // as described in http://www.w3.org/TR/REC-xml#AVNormalize
                       // TODO add test for it form spec ...
                       // handle EOL normalization ...
      -                if ( !usePC )
      -                {
      +                if (!usePC) {
                           posEnd = pos - 1;
      -                    if ( posEnd > posStart )
      -                    {
      +                    if (posEnd > posStart) {
                               joinPC();
      -                    }
      -                    else
      -                    {
      +                    } else {
                               usePC = true;
                               pcEnd = pcStart = 0;
                           }
                       }
                       // assert usePC == true;
      -                if ( pcEnd >= pc.length )
      -                    ensurePC( pcEnd );
      -                if ( ch != '\n' || !normalizedCR )
      -                {
      +                if (pcEnd >= pc.length) ensurePC(pcEnd);
      +                if (ch != '\n' || !normalizedCR) {
                           pc[pcEnd++] = ' '; // '\n';
                       }
       
      -            }
      -            else
      -            {
      -                if ( usePC )
      -                {
      -                    if ( pcEnd >= pc.length )
      -                        ensurePC( pcEnd );
      +            } else {
      +                if (usePC) {
      +                    if (pcEnd >= pc.length) ensurePC(pcEnd);
                           pc[pcEnd++] = ch;
                       }
                   }
                   normalizedCR = ch == '\r';
               }
       
      -        if ( processNamespaces && startsWithXmlns )
      -        {
      +        if (processNamespaces && startsWithXmlns) {
                   String ns = null;
      -            if ( !usePC )
      -            {
      -                ns = newStringIntern( buf, posStart, pos - 1 - posStart );
      +            if (!usePC) {
      +                ns = newStringIntern(buf, posStart, pos - 1 - posStart);
      +            } else {
      +                ns = newStringIntern(pc, pcStart, pcEnd - pcStart);
                   }
      -            else
      -            {
      -                ns = newStringIntern( pc, pcStart, pcEnd - pcStart );
      -            }
      -            ensureNamespacesCapacity( namespaceEnd );
      +            ensureNamespacesCapacity(namespaceEnd);
                   int prefixHash = -1;
      -            if ( colonPos != -1 )
      -            {
      -                if ( ns.length() == 0 )
      -                {
      -                    throw new XmlPullParserException( "non-default namespace can not be declared to be empty string",
      -                                                      this, null );
      +            if (colonPos != -1) {
      +                if (ns.length() == 0) {
      +                    throw new XmlPullParserException(
      +                            "non-default namespace can not be declared to be empty string", this, null);
                       }
                       // declare new namespace
                       namespacePrefix[namespaceEnd] = name;
      -                if ( !allStringsInterned )
      -                {
      +                if (!allStringsInterned) {
                           prefixHash = namespacePrefixHash[namespaceEnd] = name.hashCode();
                       }
      -            }
      -            else
      -            {
      +            } else {
                       // declare new default namespace...
                       namespacePrefix[namespaceEnd] = null; // ""; //null; //TODO check FIXME Alek
      -                if ( !allStringsInterned )
      -                {
      +                if (!allStringsInterned) {
                           prefixHash = namespacePrefixHash[namespaceEnd] = -1;
                       }
                   }
      @@ -2645,29 +2098,25 @@ else if ( ch == '\t' || ch == '\n' || ch == '\r' )
       
                   // detect duplicate namespace declarations!!!
                   final int startNs = elNamespaceCount[depth - 1];
      -            for ( int i = namespaceEnd - 1; i >= startNs; --i )
      -            {
      -                if ( ( ( allStringsInterned || name == null ) && namespacePrefix[i] == name ) || ( !allStringsInterned
      -                    && name != null && namespacePrefixHash[i] == prefixHash && name.equals( namespacePrefix[i] ) ) )
      -                {
      +            for (int i = namespaceEnd - 1; i >= startNs; --i) {
      +                if (((allStringsInterned || name == null) && namespacePrefix[i] == name)
      +                        || (!allStringsInterned
      +                                && name != null
      +                                && namespacePrefixHash[i] == prefixHash
      +                                && name.equals(namespacePrefix[i]))) {
                           final String s = name == null ? "default" : "'" + name + "'";
      -                    throw new XmlPullParserException( "duplicated namespace declaration for " + s + " prefix", this,
      -                                                      null );
      +                    throw new XmlPullParserException(
      +                            "duplicated namespace declaration for " + s + " prefix", this, null);
                       }
                   }
       
                   ++namespaceEnd;
       
      -        }
      -        else
      -        {
      -            if ( !usePC )
      -            {
      -                attributeValue[attributeCount] = new String( buf, posStart, pos - 1 - posStart );
      -            }
      -            else
      -            {
      -                attributeValue[attributeCount] = new String( pc, pcStart, pcEnd - pcStart );
      +        } else {
      +            if (!usePC) {
      +                attributeValue[attributeCount] = new String(buf, posStart, pos - 1 - posStart);
      +            } else {
      +                attributeValue[attributeCount] = new String(pc, pcStart, pcEnd - pcStart);
                   }
                   ++attributeCount;
               }
      @@ -2679,11 +2128,11 @@ else if ( ch == '\t' || ch == '\n' || ch == '\r' )
           private static final char[] BUF_NOT_RESOLVED = new char[0];
       
           // predefined entity refs
      -    private static final char[] BUF_LT = new char[] { '<' };
      -    private static final char[] BUF_AMP = new char[] { '&' };
      -    private static final char[] BUF_GT = new char[] { '>' };
      -    private static final char[] BUF_APO = new char[] { '\'' };
      -    private static final char[] BUF_QUOT = new char[] { '"' };
      +    private static final char[] BUF_LT = new char[] {'<'};
      +    private static final char[] BUF_AMP = new char[] {'&'};
      +    private static final char[] BUF_GT = new char[] {'>'};
      +    private static final char[] BUF_APO = new char[] {'\''};
      +    private static final char[] BUF_QUOT = new char[] {'"'};
       
           private char[] resolvedEntityRefCharBuf = BUF_NOT_RESOLVED;
       
      @@ -2696,9 +2145,7 @@ else if ( ch == '\t' || ch == '\n' || ch == '\r' )
            * @throws XmlPullParserException if invalid XML is detected.
            * @throws IOException if an I/O error is found.
            */
      -    private int parseCharOrPredefinedEntityRef()
      -        throws XmlPullParserException, IOException
      -    {
      +    private int parseCharOrPredefinedEntityRef() throws XmlPullParserException, IOException {
               // entity reference http://www.w3.org/TR/2000/REC-xml-20001006#NT-Reference
               // [67] Reference ::= EntityRef | CharRef
       
      @@ -2708,125 +2155,96 @@ private int parseCharOrPredefinedEntityRef()
               int len = 0;
               resolvedEntityRefCharBuf = BUF_NOT_RESOLVED;
               char ch = more();
      -        if ( ch == '#' )
      -        {
      +        if (ch == '#') {
                   // parse character reference
       
                   char charRef = 0;
                   ch = more();
                   StringBuilder sb = new StringBuilder();
      -            boolean isHex = ( ch == 'x' );
      +            boolean isHex = (ch == 'x');
       
      -            if ( isHex )
      -            {
      +            if (isHex) {
                       // encoded in hex
      -                while ( true )
      -                {
      +                while (true) {
                           ch = more();
      -                    if ( ch >= '0' && ch <= '9' )
      -                    {
      -                        charRef = (char) ( charRef * 16 + ( ch - '0' ) );
      -                        sb.append( ch );
      -                    }
      -                    else if ( ch >= 'a' && ch <= 'f' )
      -                    {
      -                        charRef = (char) ( charRef * 16 + ( ch - ( 'a' - 10 ) ) );
      -                        sb.append( ch );
      -                    }
      -                    else if ( ch >= 'A' && ch <= 'F' )
      -                    {
      -                        charRef = (char) ( charRef * 16 + ( ch - ( 'A' - 10 ) ) );
      -                        sb.append( ch );
      -                    }
      -                    else if ( ch == ';' )
      -                    {
      +                    if (ch >= '0' && ch <= '9') {
      +                        charRef = (char) (charRef * 16 + (ch - '0'));
      +                        sb.append(ch);
      +                    } else if (ch >= 'a' && ch <= 'f') {
      +                        charRef = (char) (charRef * 16 + (ch - ('a' - 10)));
      +                        sb.append(ch);
      +                    } else if (ch >= 'A' && ch <= 'F') {
      +                        charRef = (char) (charRef * 16 + (ch - ('A' - 10)));
      +                        sb.append(ch);
      +                    } else if (ch == ';') {
                               break;
      -                    }
      -                    else
      -                    {
      -                        throw new XmlPullParserException( "character reference (with hex value) may not contain "
      -                            + printable( ch ), this, null );
      +                    } else {
      +                        throw new XmlPullParserException(
      +                                "character reference (with hex value) may not contain " + printable(ch), this, null);
                           }
                       }
      -            }
      -            else
      -            {
      +            } else {
                       // encoded in decimal
      -                while ( true )
      -                {
      -                    if ( ch >= '0' && ch <= '9' )
      -                    {
      -                        charRef = (char) ( charRef * 10 + ( ch - '0' ) );
      -                        sb.append( ch );
      -                    }
      -                    else if ( ch == ';' )
      -                    {
      +                while (true) {
      +                    if (ch >= '0' && ch <= '9') {
      +                        charRef = (char) (charRef * 10 + (ch - '0'));
      +                        sb.append(ch);
      +                    } else if (ch == ';') {
                               break;
      -                    }
      -                    else
      -                    {
      -                        throw new XmlPullParserException( "character reference (with decimal value) may not contain "
      -                            + printable( ch ), this, null );
      +                    } else {
      +                        throw new XmlPullParserException(
      +                                "character reference (with decimal value) may not contain " + printable(ch),
      +                                this,
      +                                null);
                           }
                           ch = more();
                       }
                   }
       
                   boolean isValidCodePoint = true;
      -            try
      -            {
      -                int codePoint = Integer.parseInt( sb.toString(), isHex ? 16 : 10 );
      -                isValidCodePoint = isValidCodePoint( codePoint );
      -                if ( isValidCodePoint )
      -                {
      -                    resolvedEntityRefCharBuf = Character.toChars( codePoint );
      +            try {
      +                int codePoint = Integer.parseInt(sb.toString(), isHex ? 16 : 10);
      +                isValidCodePoint = isValidCodePoint(codePoint);
      +                if (isValidCodePoint) {
      +                    resolvedEntityRefCharBuf = Character.toChars(codePoint);
                       }
      -            }
      -            catch ( IllegalArgumentException e )
      -            {
      +            } catch (IllegalArgumentException e) {
                       isValidCodePoint = false;
                   }
       
      -            if ( !isValidCodePoint )
      -            {
      -                throw new XmlPullParserException( "character reference (with " + ( isHex ? "hex" : "decimal" )
      -                    + " value " + sb.toString() + ") is invalid", this, null );
      +            if (!isValidCodePoint) {
      +                throw new XmlPullParserException(
      +                        "character reference (with " + (isHex ? "hex" : "decimal") + " value " + sb.toString()
      +                                + ") is invalid",
      +                        this,
      +                        null);
                   }
       
      -            if ( tokenize )
      -            {
      -                text = newString( resolvedEntityRefCharBuf, 0, resolvedEntityRefCharBuf.length );
      +            if (tokenize) {
      +                text = newString(resolvedEntityRefCharBuf, 0, resolvedEntityRefCharBuf.length);
                   }
                   len = resolvedEntityRefCharBuf.length;
      -        }
      -        else
      -        {
      +        } else {
                   // [68] EntityRef ::= '&' Name ';'
                   // scan name until ;
      -            if ( !isNameStartChar( ch ) )
      -            {
      -                throw new XmlPullParserException( "entity reference names can not start with character '"
      -                    + printable( ch ) + "'", this, null );
      +            if (!isNameStartChar(ch)) {
      +                throw new XmlPullParserException(
      +                        "entity reference names can not start with character '" + printable(ch) + "'", this, null);
                   }
      -            while ( true )
      -            {
      +            while (true) {
                       ch = more();
      -                if ( ch == ';' )
      -                {
      +                if (ch == ';') {
                           break;
                       }
      -                if ( !isNameChar( ch ) )
      -                {
      -                    throw new XmlPullParserException( "entity reference name can not contain character "
      -                        + printable( ch ) + "'", this, null );
      +                if (!isNameChar(ch)) {
      +                    throw new XmlPullParserException(
      +                            "entity reference name can not contain character " + printable(ch) + "'", this, null);
                       }
                   }
                   // determine what name maps to
      -            len = ( pos - 1 ) - posStart;
      -            if ( len == 2 && buf[posStart] == 'l' && buf[posStart + 1] == 't' )
      -            {
      -                if ( tokenize )
      -                {
      +            len = (pos - 1) - posStart;
      +            if (len == 2 && buf[posStart] == 'l' && buf[posStart + 1] == 't') {
      +                if (tokenize) {
                           text = "<";
                       }
                       resolvedEntityRefCharBuf = BUF_LT;
      @@ -2834,37 +2252,31 @@ else if ( ch >= 'A' && ch <= 'F' )
                       // if(pcEnd >= pc.length) ensurePC();
                       // pc[pcEnd++] = '<';
                       // }
      -            }
      -            else if ( len == 3 && buf[posStart] == 'a' && buf[posStart + 1] == 'm' && buf[posStart + 2] == 'p' )
      -            {
      -                if ( tokenize )
      -                {
      +            } else if (len == 3 && buf[posStart] == 'a' && buf[posStart + 1] == 'm' && buf[posStart + 2] == 'p') {
      +                if (tokenize) {
                           text = "&";
                       }
                       resolvedEntityRefCharBuf = BUF_AMP;
      -            }
      -            else if ( len == 2 && buf[posStart] == 'g' && buf[posStart + 1] == 't' )
      -            {
      -                if ( tokenize )
      -                {
      +            } else if (len == 2 && buf[posStart] == 'g' && buf[posStart + 1] == 't') {
      +                if (tokenize) {
                           text = ">";
                       }
                       resolvedEntityRefCharBuf = BUF_GT;
      -            }
      -            else if ( len == 4 && buf[posStart] == 'a' && buf[posStart + 1] == 'p' && buf[posStart + 2] == 'o'
      -                && buf[posStart + 3] == 's' )
      -            {
      -                if ( tokenize )
      -                {
      +            } else if (len == 4
      +                    && buf[posStart] == 'a'
      +                    && buf[posStart + 1] == 'p'
      +                    && buf[posStart + 2] == 'o'
      +                    && buf[posStart + 3] == 's') {
      +                if (tokenize) {
                           text = "'";
                       }
                       resolvedEntityRefCharBuf = BUF_APO;
      -            }
      -            else if ( len == 4 && buf[posStart] == 'q' && buf[posStart + 1] == 'u' && buf[posStart + 2] == 'o'
      -                && buf[posStart + 3] == 't' )
      -            {
      -                if ( tokenize )
      -                {
      +            } else if (len == 4
      +                    && buf[posStart] == 'q'
      +                    && buf[posStart + 1] == 'u'
      +                    && buf[posStart + 2] == 'o'
      +                    && buf[posStart + 3] == 't') {
      +                if (tokenize) {
                           text = "\"";
                       }
                       resolvedEntityRefCharBuf = BUF_QUOT;
      @@ -2882,19 +2294,15 @@ else if ( len == 4 && buf[posStart] == 'q' && buf[posStart + 1] == 'u' && buf[po
            * @throws XmlPullParserException if invalid XML is detected.
            * @throws IOException if an I/O error is found.
            */
      -    private void parseEntityRefInDocDecl()
      -        throws XmlPullParserException, IOException
      -    {
      +    private void parseEntityRefInDocDecl() throws XmlPullParserException, IOException {
               parseCharOrPredefinedEntityRef();
               if (usePC) {
                   posStart--; // include in PC the starting '&' of the entity
                   joinPC();
               }
       
      -        if ( resolvedEntityRefCharBuf != BUF_NOT_RESOLVED )
      -            return;
      -        if ( tokenize )
      -            text = null;
      +        if (resolvedEntityRefCharBuf != BUF_NOT_RESOLVED) return;
      +        if (tokenize) text = null;
           }
       
           /**
      @@ -2903,24 +2311,20 @@ private void parseEntityRefInDocDecl()
            * @throws XmlPullParserException if invalid XML is detected.
            * @throws IOException if an I/O error is found.
            */
      -    private void parseEntityRef()
      -        throws XmlPullParserException, IOException
      -    {
      +    private void parseEntityRef() throws XmlPullParserException, IOException {
               final int len = parseCharOrPredefinedEntityRef();
       
               posEnd--; // don't involve the final ';' from the entity in the search
       
      -        if ( resolvedEntityRefCharBuf != BUF_NOT_RESOLVED ) {
      +        if (resolvedEntityRefCharBuf != BUF_NOT_RESOLVED) {
                   return;
               }
       
      -        resolvedEntityRefCharBuf = lookuEntityReplacement( len );
      -        if ( resolvedEntityRefCharBuf != BUF_NOT_RESOLVED )
      -        {
      +        resolvedEntityRefCharBuf = lookuEntityReplacement(len);
      +        if (resolvedEntityRefCharBuf != BUF_NOT_RESOLVED) {
                   return;
               }
      -        if ( tokenize )
      -            text = null;
      +        if (tokenize) text = null;
           }
       
           /**
      @@ -2930,44 +2334,36 @@ private void parseEntityRef()
            * @param codePoint the numeric value to check
            * @return true if it is a valid numeric character reference. False otherwise.
            */
      -    private static boolean isValidCodePoint( int codePoint )
      -    {
      +    private static boolean isValidCodePoint(int codePoint) {
               // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
      -        return codePoint == 0x9 || codePoint == 0xA || codePoint == 0xD || ( 0x20 <= codePoint && codePoint <= 0xD7FF )
      -            || ( 0xE000 <= codePoint && codePoint <= 0xFFFD ) || ( 0x10000 <= codePoint && codePoint <= 0x10FFFF );
      -    }
      -
      -    private char[] lookuEntityReplacement( int entityNameLen )
      -    {
      -        if ( !allStringsInterned )
      -        {
      -            final int hash = fastHash( buf, posStart, posEnd - posStart );
      -            LOOP: for ( int i = entityEnd - 1; i >= 0; --i )
      -            {
      -                if ( hash == entityNameHash[i] && entityNameLen == entityNameBuf[i].length )
      -                {
      +        return codePoint == 0x9
      +                || codePoint == 0xA
      +                || codePoint == 0xD
      +                || (0x20 <= codePoint && codePoint <= 0xD7FF)
      +                || (0xE000 <= codePoint && codePoint <= 0xFFFD)
      +                || (0x10000 <= codePoint && codePoint <= 0x10FFFF);
      +    }
      +
      +    private char[] lookuEntityReplacement(int entityNameLen) {
      +        if (!allStringsInterned) {
      +            final int hash = fastHash(buf, posStart, posEnd - posStart);
      +            LOOP:
      +            for (int i = entityEnd - 1; i >= 0; --i) {
      +                if (hash == entityNameHash[i] && entityNameLen == entityNameBuf[i].length) {
                           final char[] entityBuf = entityNameBuf[i];
      -                    for ( int j = 0; j < entityNameLen; j++ )
      -                    {
      -                        if ( buf[posStart + j] != entityBuf[j] )
      -                            continue LOOP;
      +                    for (int j = 0; j < entityNameLen; j++) {
      +                        if (buf[posStart + j] != entityBuf[j]) continue LOOP;
                           }
      -                    if ( tokenize )
      -                        text = entityReplacement[i];
      +                    if (tokenize) text = entityReplacement[i];
                           return entityReplacementBuf[i];
                       }
                   }
      -        }
      -        else
      -        {
      -            entityRefName = newString( buf, posStart, posEnd - posStart );
      -            for ( int i = entityEnd - 1; i >= 0; --i )
      -            {
      +        } else {
      +            entityRefName = newString(buf, posStart, posEnd - posStart);
      +            for (int i = entityEnd - 1; i >= 0; --i) {
                       // take advantage that interning for newString is enforced
      -                if ( entityRefName == entityName[i] )
      -                {
      -                    if ( tokenize )
      -                        text = entityReplacement[i];
      +                if (entityRefName == entityName[i]) {
      +                    if (tokenize) text = entityReplacement[i];
                           return entityReplacementBuf[i];
                       }
                   }
      @@ -2975,120 +2371,86 @@ private char[] lookuEntityReplacement( int entityNameLen )
               return BUF_NOT_RESOLVED;
           }
       
      -    private void parseComment()
      -        throws XmlPullParserException, IOException
      -    {
      +    private void parseComment() throws XmlPullParserException, IOException {
               // implements XML 1.0 Section 2.5 Comments
       
               // ASSUMPTION: seen 
                       cch = more();
                       int ch;
                       char cch2;
      -                if ( Character.isHighSurrogate( cch ) )
      -                {
      +                if (Character.isHighSurrogate(cch)) {
                           cch2 = more();
      -                    ch = Character.toCodePoint( cch, cch2 );
      -                }
      -                else
      -                {
      +                    ch = Character.toCodePoint(cch, cch2);
      +                } else {
                           cch2 = 0;
                           ch = cch;
                       }
      -                if ( seenDashDash && ch != '>' )
      -                {
      -                    throw new XmlPullParserException( "in comment after two dashes (--) next character must be >"
      -                        + " not " + printable( ch ), this, null );
      +                if (seenDashDash && ch != '>') {
      +                    throw new XmlPullParserException(
      +                            "in comment after two dashes (--) next character must be >" + " not " + printable(ch),
      +                            this,
      +                            null);
                       }
      -                if ( ch == '-' )
      -                {
      -                    if ( !seenDash )
      -                    {
      +                if (ch == '-') {
      +                    if (!seenDash) {
                               seenDash = true;
      -                    }
      -                    else
      -                    {
      +                    } else {
                               seenDashDash = true;
                           }
      -                }
      -                else if ( ch == '>' )
      -                {
      -                    if ( seenDashDash )
      -                    {
      +                } else if (ch == '>') {
      +                    if (seenDashDash) {
                               break; // found end sequence!!!!
                           }
                           seenDash = false;
      -                }
      -                else if (isValidCodePoint( ch ))
      -                {
      +                } else if (isValidCodePoint(ch)) {
                           seenDash = false;
      +                } else {
      +                    throw new XmlPullParserException(
      +                            "Illegal character 0x" + Integer.toHexString(ch) + " found in comment", this, null);
                       }
      -                else
      -                {
      -                    throw new XmlPullParserException( "Illegal character 0x" + Integer.toHexString(ch) + " found in comment", this, null );
      -                }
      -                if ( normalizeIgnorableWS )
      -                {
      -                    if ( ch == '\r' )
      -                    {
      +                if (normalizeIgnorableWS) {
      +                    if (ch == '\r') {
                               normalizedCR = true;
                               // posEnd = pos -1;
                               // joinPC();
                               // posEnd is alreadys set
      -                        if ( !usePC )
      -                        {
      +                        if (!usePC) {
                                   posEnd = pos - 1;
      -                            if ( posEnd > posStart )
      -                            {
      +                            if (posEnd > posStart) {
                                       joinPC();
      -                            }
      -                            else
      -                            {
      +                            } else {
                                       usePC = true;
                                       pcStart = pcEnd = 0;
                                   }
                               }
                               // assert usePC == true;
      -                        if ( pcEnd >= pc.length )
      -                            ensurePC( pcEnd );
      +                        if (pcEnd >= pc.length) ensurePC(pcEnd);
                               pc[pcEnd++] = '\n';
      -                    }
      -                    else if ( ch == '\n' )
      -                    {
      -                        if ( !normalizedCR && usePC )
      -                        {
      -                            if ( pcEnd >= pc.length )
      -                                ensurePC( pcEnd );
      +                    } else if (ch == '\n') {
      +                        if (!normalizedCR && usePC) {
      +                            if (pcEnd >= pc.length) ensurePC(pcEnd);
                                   pc[pcEnd++] = '\n';
                               }
                               normalizedCR = false;
      -                    }
      -                    else
      -                    {
      -                        if ( usePC )
      -                        {
      -                            if ( pcEnd >= pc.length )
      -                                ensurePC( pcEnd );
      +                    } else {
      +                        if (usePC) {
      +                            if (pcEnd >= pc.length) ensurePC(pcEnd);
                                   pc[pcEnd++] = cch;
      -                            if ( cch2 != 0 )
      -                            {
      +                            if (cch2 != 0) {
                                       pc[pcEnd++] = cch2;
                                   }
                               }
      @@ -3097,33 +2459,26 @@ else if ( ch == '\n' )
                       }
                   }
       
      -        }
      -        catch ( EOFException ex )
      -        {
      +        } catch (EOFException ex) {
                   // detect EOF and create meaningful error ...
      -            throw new XmlPullParserException( "comment started on line " + curLine + " and column " + curColumn
      -                + " was not closed", this, ex );
      +            throw new XmlPullParserException(
      +                    "comment started on line " + curLine + " and column " + curColumn + " was not closed", this, ex);
               }
      -        if ( tokenize )
      -        {
      +        if (tokenize) {
                   posEnd = pos - 3;
      -            if ( usePC )
      -            {
      +            if (usePC) {
                       pcEnd -= 2;
                   }
               }
           }
       
      -    private boolean parsePI()
      -        throws XmlPullParserException, IOException
      -    {
      +    private boolean parsePI() throws XmlPullParserException, IOException {
               // implements XML 1.0 Section 2.6 Processing Instructions
       
               // [16] PI ::= '' Char*)))? '?>'
               // [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
               // ASSUMPTION: seen 
                       // ch = more();
       
      -                if ( ch == '?' )
      -                {
      -                    if ( !seenPITarget )
      -                    {
      -                        throw new XmlPullParserException( "processing instruction PITarget name not found", this,
      -                                                          null );
      +                if (ch == '?') {
      +                    if (!seenPITarget) {
      +                        throw new XmlPullParserException("processing instruction PITarget name not found", this, null);
                           }
                           seenQ = true;
      -                }
      -                else if ( ch == '>' )
      -                {
      -                    if ( seenQ )
      -                    {
      +                } else if (ch == '>') {
      +                    if (seenQ) {
                               break; // found end sequence!!!!
                           }
       
      -                    if ( !seenPITarget )
      -                    {
      -                        throw new XmlPullParserException( "processing instruction PITarget name not found", this,
      -                                                          null );
      -                    }
      -                    else if ( !seenInnerTag )
      -                    {
      +                    if (!seenPITarget) {
      +                        throw new XmlPullParserException("processing instruction PITarget name not found", this, null);
      +                    } else if (!seenInnerTag) {
                               // seenPITarget && !seenQ
      -                        throw new XmlPullParserException( "processing instruction started on line " + curLine
      -                            + " and column " + curColumn + " was not closed", this, null );
      -                    }
      -                    else
      -                    {
      +                        throw new XmlPullParserException(
      +                                "processing instruction started on line " + curLine + " and column " + curColumn
      +                                        + " was not closed",
      +                                this,
      +                                null);
      +                    } else {
                               seenInnerTag = false;
                           }
      -                }
      -                else if ( ch == '<' )
      -                {
      +                } else if (ch == '<') {
                           seenInnerTag = true;
      -                }
      -                else
      -                {
      -                    if ( piTargetEnd == -1 && isS( ch ) )
      -                    {
      +                } else {
      +                    if (piTargetEnd == -1 && isS(ch)) {
                               piTargetEnd = pos - 1;
       
                               // [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
      -                        if ( ( piTargetEnd - piTargetStart ) >= 3 )
      -                        {
      -                            if ( ( buf[piTargetStart] == 'x' || buf[piTargetStart] == 'X' )
      -                                && ( buf[piTargetStart + 1] == 'm' || buf[piTargetStart + 1] == 'M' )
      -                                && ( buf[piTargetStart + 2] == 'l' || buf[piTargetStart + 2] == 'L' ) )
      -                            {
      -                                if ( piTargetStart > 3 )
      -                                { // = 3) {
      +                            if ((buf[piTargetStart] == 'x' || buf[piTargetStart] == 'X')
      +                                    && (buf[piTargetStart + 1] == 'm' || buf[piTargetStart + 1] == 'M')
      +                                    && (buf[piTargetStart + 2] == 'l' || buf[piTargetStart + 2] == 'L')) {
      +                                if (piTargetStart > 3) { //  posStart )
      -                            {
      +                            if (posEnd > posStart) {
                                       joinPC();
      -                            }
      -                            else
      -                            {
      +                            } else {
                                       usePC = true;
                                       pcStart = pcEnd = 0;
                                   }
                               }
                               // assert usePC == true;
      -                        if ( pcEnd >= pc.length )
      -                            ensurePC( pcEnd );
      +                        if (pcEnd >= pc.length) ensurePC(pcEnd);
                               pc[pcEnd++] = '\n';
      -                    }
      -                    else if ( ch == '\n' )
      -                    {
      -                        if ( !normalizedCR && usePC )
      -                        {
      -                            if ( pcEnd >= pc.length )
      -                                ensurePC( pcEnd );
      +                    } else if (ch == '\n') {
      +                        if (!normalizedCR && usePC) {
      +                            if (pcEnd >= pc.length) ensurePC(pcEnd);
                                   pc[pcEnd++] = '\n';
                               }
                               normalizedCR = false;
      -                    }
      -                    else
      -                    {
      -                        if ( usePC )
      -                        {
      -                            if ( pcEnd >= pc.length )
      -                                ensurePC( pcEnd );
      +                    } else {
      +                        if (usePC) {
      +                            if (pcEnd >= pc.length) ensurePC(pcEnd);
                                   pc[pcEnd++] = ch;
                               }
                               normalizedCR = false;
      @@ -3273,24 +2594,22 @@ else if ( ch == '\n' )
                       seenPITarget = true;
                       ch = more();
                   }
      -        }
      -        catch ( EOFException ex )
      -        {
      +        } catch (EOFException ex) {
                   // detect EOF and create meaningful error ...
      -            throw new XmlPullParserException( "processing instruction started on line " + curLine + " and column "
      -                + curColumn + " was not closed", this, ex );
      +            throw new XmlPullParserException(
      +                    "processing instruction started on line " + curLine + " and column " + curColumn
      +                            + " was not closed",
      +                    this,
      +                    ex);
               }
      -        if ( piTargetEnd == -1 )
      -        {
      +        if (piTargetEnd == -1) {
                   piTargetEnd = pos - 2 + bufAbsoluteStart;
                   // throw new XmlPullParserException(
                   // "processing instruction must have PITarget name", this, null);
               }
      -        if ( tokenize )
      -        {
      +        if (tokenize) {
                   posEnd = pos - 2;
      -            if ( normalizeIgnorableWS )
      -            {
      +            if (normalizeIgnorableWS) {
                       --pcEnd;
                   }
               }
      @@ -3303,19 +2622,17 @@ else if ( ch == '\n' )
           // protected final static char[] YES = {'y','e','s'};
           // protected final static char[] NO = {'n','o'};
       
      -    private final static char[] VERSION = "version".toCharArray();
      +    private static final char[] VERSION = "version".toCharArray();
       
      -    private final static char[] NCODING = "ncoding".toCharArray();
      +    private static final char[] NCODING = "ncoding".toCharArray();
       
      -    private final static char[] TANDALONE = "tandalone".toCharArray();
      +    private static final char[] TANDALONE = "tandalone".toCharArray();
       
      -    private final static char[] YES = "yes".toCharArray();
      +    private static final char[] YES = "yes".toCharArray();
       
      -    private final static char[] NO = "no".toCharArray();
      +    private static final char[] NO = "no".toCharArray();
       
      -    private void parseXmlDecl( char ch )
      -        throws XmlPullParserException, IOException
      -    {
      +    private void parseXmlDecl(char ch) throws XmlPullParserException, IOException {
               // [23] XMLDecl ::= ''
       
               // first make sure that relative positions will stay OK
      @@ -3326,218 +2643,203 @@ private void parseXmlDecl( char ch )
       
               // [24] VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"')
               // parse is positioned just on first S past  'z' ) && ( ch < 'A' || ch > 'Z' ) && ( ch < '0' || ch > '9' ) && ch != '_'
      -                && ch != '.' && ch != ':' && ch != '-' )
      -            {
      -                throw new XmlPullParserException( " 'z')
      +                    && (ch < 'A' || ch > 'Z')
      +                    && (ch < '0' || ch > '9')
      +                    && ch != '_'
      +                    && ch != '.'
      +                    && ch != ':'
      +                    && ch != '-') {
      +                throw new XmlPullParserException(
      +                        "' )
      -        {
      -            throw new XmlPullParserException( "unexpected character " + printable( ch ), this, null );
      +        if (ch != 'e' && ch != 's' && ch != '?' && ch != '>') {
      +            throw new XmlPullParserException("unexpected character " + printable(ch), this, null);
               }
       
      -        if ( ch == 'e' )
      -        {
      -            if ( !isS( prevCh ) )
      -            {
      -                throw new XmlPullParserException( "expected a space after " + lastParsedAttr + " and not "
      -                    + printable( ch ), this, null );
      +        if (ch == 'e') {
      +            if (!isS(prevCh)) {
      +                throw new XmlPullParserException(
      +                        "expected a space after " + lastParsedAttr + " and not " + printable(ch), this, null);
                   }
                   ch = more();
      -            ch = requireInput( ch, NCODING );
      -            ch = skipS( ch );
      -            if ( ch != '=' )
      -            {
      -                throw new XmlPullParserException( "expected equals sign (=) after encoding and not " + printable( ch ),
      -                                                  this, null );
      +            ch = requireInput(ch, NCODING);
      +            ch = skipS(ch);
      +            if (ch != '=') {
      +                throw new XmlPullParserException(
      +                        "expected equals sign (=) after encoding and not " + printable(ch), this, null);
                   }
                   ch = more();
      -            ch = skipS( ch );
      -            if ( ch != '\'' && ch != '"' )
      -            {
      -                throw new XmlPullParserException( "expected apostrophe (') or quotation mark (\") after encoding and not "
      -                    + printable( ch ), this, null );
      +            ch = skipS(ch);
      +            if (ch != '\'' && ch != '"') {
      +                throw new XmlPullParserException(
      +                        "expected apostrophe (') or quotation mark (\") after encoding and not " + printable(ch),
      +                        this,
      +                        null);
                   }
                   final char quotChar = ch;
                   final int encodingStart = pos;
                   ch = more();
                   // [81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*
      -            if ( ( ch < 'a' || ch > 'z' ) && ( ch < 'A' || ch > 'Z' ) )
      -            {
      -                throw new XmlPullParserException( " 'z') && (ch < 'A' || ch > 'Z')) {
      +                throw new XmlPullParserException(
      +                        " 'z' ) && ( ch < 'A' || ch > 'Z' ) && ( ch < '0' || ch > '9' ) && ch != '.'
      -                    && ch != '_' && ch != '-' )
      -                {
      -                    throw new XmlPullParserException( " 'z')
      +                        && (ch < 'A' || ch > 'Z')
      +                        && (ch < '0' || ch > '9')
      +                        && ch != '.'
      +                        && ch != '_'
      +                        && ch != '-') {
      +                    throw new XmlPullParserException(
      +                            " as last part of  as last part of ' )
      -        {
      -            throw new XmlPullParserException( "expected ?> as last part of ') {
      +            throw new XmlPullParserException("expected ?> as last part of ' && bracketLevel == 0 )
      -                break;
      -            else if ( ch == '&' )
      -            {
      +            if (ch == '[') ++bracketLevel;
      +            else if (ch == ']') --bracketLevel;
      +            else if (ch == '>' && bracketLevel == 0) break;
      +            else if (ch == '&') {
                       extractEntityRefInDocDecl();
                       continue;
                   }
      -            if ( normalizeIgnorableWS )
      -            {
      -                if ( ch == '\r' )
      -                {
      +            if (normalizeIgnorableWS) {
      +                if (ch == '\r') {
                           normalizedCR = true;
                           // posEnd = pos -1;
                           // joinPC();
                           // posEnd is alreadys set
      -                    if ( !usePC )
      -                    {
      +                    if (!usePC) {
                               posEnd = pos - 1;
      -                        if ( posEnd > posStart )
      -                        {
      +                        if (posEnd > posStart) {
                                   joinPC();
      -                        }
      -                        else
      -                        {
      +                        } else {
                                   usePC = true;
                                   pcStart = pcEnd = 0;
                               }
                           }
                           // assert usePC == true;
      -                    if ( pcEnd >= pc.length )
      -                        ensurePC( pcEnd );
      +                    if (pcEnd >= pc.length) ensurePC(pcEnd);
                           pc[pcEnd++] = '\n';
      -                }
      -                else if ( ch == '\n' )
      -                {
      -                    if ( !normalizedCR && usePC )
      -                    {
      -                        if ( pcEnd >= pc.length )
      -                            ensurePC( pcEnd );
      +                } else if (ch == '\n') {
      +                    if (!normalizedCR && usePC) {
      +                        if (pcEnd >= pc.length) ensurePC(pcEnd);
                               pc[pcEnd++] = '\n';
                           }
                           normalizedCR = false;
      -                }
      -                else
      -                {
      -                    if ( usePC )
      -                    {
      -                        if ( pcEnd >= pc.length )
      -                            ensurePC( pcEnd );
      +                } else {
      +                    if (usePC) {
      +                        if (pcEnd >= pc.length) ensurePC(pcEnd);
                               pc[pcEnd++] = ch;
                           }
                           normalizedCR = false;
                       }
                   }
      -
               }
               posEnd = pos - 1;
               text = null;
           }
       
      -    private void extractEntityRefInDocDecl()
      -        throws XmlPullParserException, IOException
      -    {
      +    private void extractEntityRefInDocDecl() throws XmlPullParserException, IOException {
               // extractEntityRef
               posEnd = pos - 1;
       
      @@ -3625,21 +2904,15 @@ private void extractEntityRefInDocDecl()
               posStart = prevPosStart;
           }
       
      -    private void extractEntityRef()
      -        throws XmlPullParserException, IOException
      -    {
      +    private void extractEntityRef() throws XmlPullParserException, IOException {
               // extractEntityRef
               posEnd = pos - 1;
      -        if ( !usePC )
      -        {
      +        if (!usePC) {
                   final boolean hadCharData = posEnd > posStart;
      -            if ( hadCharData )
      -            {
      +            if (hadCharData) {
                       // posEnd is already set correctly!!!
                       joinPC();
      -            }
      -            else
      -            {
      +            } else {
                       usePC = true;
                       pcStart = pcEnd = 0;
                   }
      @@ -3648,29 +2921,23 @@ private void extractEntityRef()
       
               parseEntityRef();
               // check if replacement text can be resolved !!!
      -        if ( resolvedEntityRefCharBuf == BUF_NOT_RESOLVED )
      -        {
      -            if ( entityRefName == null )
      -            {
      -                entityRefName = newString( buf, posStart, posEnd - posStart );
      +        if (resolvedEntityRefCharBuf == BUF_NOT_RESOLVED) {
      +            if (entityRefName == null) {
      +                entityRefName = newString(buf, posStart, posEnd - posStart);
                   }
      -            throw new XmlPullParserException( "could not resolve entity named '" + printable( entityRefName )
      -                + "'", this, null );
      +            throw new XmlPullParserException(
      +                    "could not resolve entity named '" + printable(entityRefName) + "'", this, null);
               }
               // write into PC replacement text - do merge for replacement text!!!!
      -        for ( char aResolvedEntity : resolvedEntityRefCharBuf )
      -        {
      -            if ( pcEnd >= pc.length )
      -            {
      -                ensurePC( pcEnd );
      +        for (char aResolvedEntity : resolvedEntityRefCharBuf) {
      +            if (pcEnd >= pc.length) {
      +                ensurePC(pcEnd);
                   }
                   pc[pcEnd++] = aResolvedEntity;
               }
           }
       
      -    private void parseCDSect( boolean hadCharData )
      -        throws XmlPullParserException, IOException
      -    {
      +    private void parseCDSect(boolean hadCharData) throws XmlPullParserException, IOException {
               // implements XML 1.0 Section 2.7 CDATA Sections
       
               // [18] CDSect ::= CDStart CData CDEnd
      @@ -3680,44 +2947,31 @@ private void parseCDSect( boolean hadCharData )
       
               // ASSUMPTION: seen  posStart )
      -                        {
      +                        if (posEnd > posStart) {
                                   joinPC();
      -                        }
      -                        else
      -                        {
      +                        } else {
                                   usePC = true;
                                   pcStart = pcEnd = 0;
                               }
      @@ -3727,99 +2981,69 @@ private void parseCDSect( boolean hadCharData )
                   boolean seenBracket = false;
                   boolean seenBracketBracket = false;
                   boolean normalizedCR = false;
      -            while ( true )
      -            {
      +            while (true) {
                       // scan until it hits "]]>"
                       ch = more();
      -                if ( ch == ']' )
      -                {
      -                    if ( !seenBracket )
      -                    {
      +                if (ch == ']') {
      +                    if (!seenBracket) {
                               seenBracket = true;
      -                    }
      -                    else
      -                    {
      +                    } else {
                               seenBracketBracket = true;
                               // seenBracket = false;
                           }
      -                }
      -                else if ( ch == '>' )
      -                {
      -                    if ( seenBracket && seenBracketBracket )
      -                    {
      +                } else if (ch == '>') {
      +                    if (seenBracket && seenBracketBracket) {
                               break; // found end sequence!!!!
      -                    }
      -                    else
      -                    {
      +                    } else {
                               seenBracketBracket = false;
                           }
                           seenBracket = false;
      -                }
      -                else
      -                {
      -                    if ( seenBracket )
      -                    {
      +                } else {
      +                    if (seenBracket) {
                               seenBracket = false;
                           }
                       }
      -                if ( normalizeInput )
      -                {
      +                if (normalizeInput) {
                           // deal with normalization issues ...
      -                    if ( ch == '\r' )
      -                    {
      +                    if (ch == '\r') {
                               normalizedCR = true;
                               posStart = cdStart - bufAbsoluteStart;
                               posEnd = pos - 1; // posEnd is alreadys set
      -                        if ( !usePC )
      -                        {
      -                            if ( posEnd > posStart )
      -                            {
      +                        if (!usePC) {
      +                            if (posEnd > posStart) {
                                       joinPC();
      -                            }
      -                            else
      -                            {
      +                            } else {
                                       usePC = true;
                                       pcStart = pcEnd = 0;
                                   }
                               }
                               // assert usePC == true;
      -                        if ( pcEnd >= pc.length )
      -                            ensurePC( pcEnd );
      +                        if (pcEnd >= pc.length) ensurePC(pcEnd);
                               pc[pcEnd++] = '\n';
      -                    }
      -                    else if ( ch == '\n' )
      -                    {
      -                        if ( !normalizedCR && usePC )
      -                        {
      -                            if ( pcEnd >= pc.length )
      -                                ensurePC( pcEnd );
      +                    } else if (ch == '\n') {
      +                        if (!normalizedCR && usePC) {
      +                            if (pcEnd >= pc.length) ensurePC(pcEnd);
                                   pc[pcEnd++] = '\n';
                               }
                               normalizedCR = false;
      -                    }
      -                    else
      -                    {
      -                        if ( usePC )
      -                        {
      -                            if ( pcEnd >= pc.length )
      -                                ensurePC( pcEnd );
      +                    } else {
      +                        if (usePC) {
      +                            if (pcEnd >= pc.length) ensurePC(pcEnd);
                                   pc[pcEnd++] = ch;
                               }
                               normalizedCR = false;
                           }
                       }
                   }
      -        }
      -        catch ( EOFException ex )
      -        {
      +        } catch (EOFException ex) {
                   // detect EOF and create meaningful error ...
      -            throw new XmlPullParserException( "CDATA section started on line " + curLine + " and column " + curColumn
      -                + " was not closed", this, ex );
      +            throw new XmlPullParserException(
      +                    "CDATA section started on line " + curLine + " and column " + curColumn + " was not closed",
      +                    this,
      +                    ex);
               }
      -        if ( normalizeInput )
      -        {
      -            if ( usePC )
      -            {
      +        if (normalizeInput) {
      +            if (usePC) {
                       pcEnd = pcEnd - 2;
                   }
               }
      @@ -3827,46 +3051,36 @@ else if ( ch == '\n' )
               posEnd = pos - 3;
           }
       
      -    private void fillBuf()
      -        throws IOException, XmlPullParserException
      -    {
      -        if ( reader == null )
      -            throw new XmlPullParserException( "reader must be set before parsing is started" );
      +    private void fillBuf() throws IOException, XmlPullParserException {
      +        if (reader == null) throw new XmlPullParserException("reader must be set before parsing is started");
       
               // see if we are in compaction area
      -        if ( bufEnd > bufSoftLimit )
      -        {
      +        if (bufEnd > bufSoftLimit) {
       
                   // check if we need to compact or expand the buffer
      -            boolean compact = !preventBufferCompaction
      -                    && ( bufStart > bufSoftLimit || bufStart >= buf.length / 2 );
      +            boolean compact = !preventBufferCompaction && (bufStart > bufSoftLimit || bufStart >= buf.length / 2);
       
                   // if buffer almost full then compact it
      -            if ( compact )
      -            {
      +            if (compact) {
                       // TODO: look on trashing
                       // //assert bufStart > 0
      -                System.arraycopy( buf, bufStart, buf, 0, bufEnd - bufStart );
      -                if ( TRACE_SIZING )
      -                    System.out.println( "TRACE_SIZING fillBuf() compacting " + bufStart + " bufEnd=" + bufEnd + " pos="
      -                        + pos + " posStart=" + posStart + " posEnd=" + posEnd + " buf first 100 chars:"
      -                        + new String( buf, bufStart, Math.min(bufEnd - bufStart, 100)) );
      +                System.arraycopy(buf, bufStart, buf, 0, bufEnd - bufStart);
      +                if (TRACE_SIZING)
      +                    System.out.println("TRACE_SIZING fillBuf() compacting " + bufStart + " bufEnd=" + bufEnd + " pos="
      +                            + pos + " posStart=" + posStart + " posEnd=" + posEnd + " buf first 100 chars:"
      +                            + new String(buf, bufStart, Math.min(bufEnd - bufStart, 100)));
       
      -            }
      -            else
      -            {
      +            } else {
                       final int newSize = 2 * buf.length;
                       final char[] newBuf = new char[newSize];
      -                if ( TRACE_SIZING )
      -                    System.out.println( "TRACE_SIZING fillBuf() " + buf.length + " => " + newSize );
      -                System.arraycopy( buf, bufStart, newBuf, 0, bufEnd - bufStart );
      +                if (TRACE_SIZING) System.out.println("TRACE_SIZING fillBuf() " + buf.length + " => " + newSize);
      +                System.arraycopy(buf, bufStart, newBuf, 0, bufEnd - bufStart);
                       buf = newBuf;
      -                if ( bufLoadFactor > 0 )
      -                {
      -                    // Include a fix for https://web.archive.org/web/20070831191548/http://www.extreme.indiana.edu/bugzilla/show_bug.cgi?id=228
      -					bufSoftLimit = (int) ( bufferLoadFactor * buf.length );
      +                if (bufLoadFactor > 0) {
      +                    // Include a fix for
      +                    // https://web.archive.org/web/20070831191548/http://www.extreme.indiana.edu/bugzilla/show_bug.cgi?id=228
      +                    bufSoftLimit = (int) (bufferLoadFactor * buf.length);
                       }
      -
                   }
                   bufEnd -= bufStart;
                   pos -= bufStart;
      @@ -3874,123 +3088,107 @@ private void fillBuf()
                   posEnd -= bufStart;
                   bufAbsoluteStart += bufStart;
                   bufStart = 0;
      -            if ( TRACE_SIZING )
      -                System.out.println( "TRACE_SIZING fillBuf() after bufEnd=" + bufEnd + " pos=" + pos + " posStart="
      -                    + posStart + " posEnd=" + posEnd + " buf first 100 chars:"
      -                    + new String( buf, 0, Math.min(bufEnd, 100)) );
      +            if (TRACE_SIZING)
      +                System.out.println("TRACE_SIZING fillBuf() after bufEnd=" + bufEnd + " pos=" + pos + " posStart="
      +                        + posStart + " posEnd=" + posEnd + " buf first 100 chars:"
      +                        + new String(buf, 0, Math.min(bufEnd, 100)));
               }
               // at least one character must be read or error
               final int len = Math.min(buf.length - bufEnd, READ_CHUNK_SIZE);
      -        final int ret = reader.read( buf, bufEnd, len );
      -        if ( ret > 0 )
      -        {
      +        final int ret = reader.read(buf, bufEnd, len);
      +        if (ret > 0) {
                   bufEnd += ret;
      -            if ( TRACE_SIZING )
      -                System.out.println( "TRACE_SIZING fillBuf() after filling in buffer" + " buf first 100 chars:"
      -                    + new String( buf, 0, Math.min(bufEnd, 100)) );
      +            if (TRACE_SIZING)
      +                System.out.println("TRACE_SIZING fillBuf() after filling in buffer" + " buf first 100 chars:"
      +                        + new String(buf, 0, Math.min(bufEnd, 100)));
       
                   return;
               }
      -        if ( ret == -1 )
      -        {
      -            if ( bufAbsoluteStart == 0 && pos == 0 )
      -            {
      -                throw new EOFException( "input contained no data" );
      -            }
      -            else
      -            {
      -                if ( seenRoot && depth == 0 )
      -                { // inside parsing epilog!!!
      +        if (ret == -1) {
      +            if (bufAbsoluteStart == 0 && pos == 0) {
      +                throw new EOFException("input contained no data");
      +            } else {
      +                if (seenRoot && depth == 0) { // inside parsing epilog!!!
                           reachedEnd = true;
                           return;
      -                }
      -                else
      -                {
      +                } else {
                           StringBuilder expectedTagStack = new StringBuilder();
      -                    if ( depth > 0 )
      -                    {
      -                        if ( elRawName == null || elRawName[depth] == null )
      -                        {
      -                            String tagName = new String( buf, posStart + 1, pos - posStart - 1 );
      -                            expectedTagStack.append( " - expected the opening tag <" ).append( tagName ).append( "...>" );
      -                        }
      -                        else
      -                        {
      +                    if (depth > 0) {
      +                        if (elRawName == null || elRawName[depth] == null) {
      +                            String tagName = new String(buf, posStart + 1, pos - posStart - 1);
      +                            expectedTagStack
      +                                    .append(" - expected the opening tag <")
      +                                    .append(tagName)
      +                                    .append("...>");
      +                        } else {
                                   // final char[] cbuf = elRawName[depth];
                                   // final String startname = new String(cbuf, 0, elRawNameEnd[depth]);
      -                            expectedTagStack.append( " - expected end tag" );
      -                            if ( depth > 1 )
      -                            {
      -                                expectedTagStack.append( "s" ); // more than one end tag
      +                            expectedTagStack.append(" - expected end tag");
      +                            if (depth > 1) {
      +                                expectedTagStack.append("s"); // more than one end tag
                                   }
      -                            expectedTagStack.append( " " );
      -
      -                            for ( int i = depth; i > 0; i-- )
      -                            {
      -                                if ( elRawName == null || elRawName[i] == null )
      -                                {
      -                                    String tagName = new String( buf, posStart + 1, pos - posStart - 1 );
      -                                    expectedTagStack.append( " - expected the opening tag <" ).append( tagName ).append( "...>" );
      -                                }
      -                                else
      -                                {
      -                                    String tagName = new String( elRawName[i], 0, elRawNameEnd[i] );
      -                                    expectedTagStack.append( "' );
      +                            expectedTagStack.append(" ");
      +
      +                            for (int i = depth; i > 0; i--) {
      +                                if (elRawName == null || elRawName[i] == null) {
      +                                    String tagName = new String(buf, posStart + 1, pos - posStart - 1);
      +                                    expectedTagStack
      +                                            .append(" - expected the opening tag <")
      +                                            .append(tagName)
      +                                            .append("...>");
      +                                } else {
      +                                    String tagName = new String(elRawName[i], 0, elRawNameEnd[i]);
      +                                    expectedTagStack
      +                                            .append("');
                                       }
                                   }
      -                            expectedTagStack.append( " to close" );
      -                            for ( int i = depth; i > 0; i-- )
      -                            {
      -                                if ( i != depth )
      -                                {
      -                                    expectedTagStack.append( " and" ); // more than one end tag
      -                                }
      -                                if ( elRawName == null || elRawName[i] == null )
      -                                {
      -                                    String tagName = new String( buf, posStart + 1, pos - posStart - 1 );
      -                                    expectedTagStack.append( " start tag <" ).append( tagName ).append( ">" );
      -                                    expectedTagStack.append( " from line " ).append( elRawNameLine[i] );
      +                            expectedTagStack.append(" to close");
      +                            for (int i = depth; i > 0; i--) {
      +                                if (i != depth) {
      +                                    expectedTagStack.append(" and"); // more than one end tag
                                       }
      -                                else
      -                                {
      -                                String tagName = new String( elRawName[i], 0, elRawNameEnd[i] );
      -                                expectedTagStack.append( " start tag <" ).append( tagName ).append( ">" );
      -                                expectedTagStack.append( " from line " ).append( elRawNameLine[i] );
      +                                if (elRawName == null || elRawName[i] == null) {
      +                                    String tagName = new String(buf, posStart + 1, pos - posStart - 1);
      +                                    expectedTagStack
      +                                            .append(" start tag <")
      +                                            .append(tagName)
      +                                            .append(">");
      +                                    expectedTagStack.append(" from line ").append(elRawNameLine[i]);
      +                                } else {
      +                                    String tagName = new String(elRawName[i], 0, elRawNameEnd[i]);
      +                                    expectedTagStack
      +                                            .append(" start tag <")
      +                                            .append(tagName)
      +                                            .append(">");
      +                                    expectedTagStack.append(" from line ").append(elRawNameLine[i]);
                                       }
                                   }
      -                            expectedTagStack.append( ", parser stopped on" );
      +                            expectedTagStack.append(", parser stopped on");
                               }
                           }
      -                    throw new EOFException( "no more data available" + expectedTagStack.toString()
      -                        + getPositionDescription() );
      +                    throw new EOFException(
      +                            "no more data available" + expectedTagStack.toString() + getPositionDescription());
                       }
                   }
      -        }
      -        else
      -        {
      -            throw new IOException( "error reading input, returned " + ret );
      +        } else {
      +            throw new IOException("error reading input, returned " + ret);
               }
           }
       
      -    private char more()
      -        throws IOException, XmlPullParserException
      -    {
      -        if ( pos >= bufEnd )
      -        {
      +    private char more() throws IOException, XmlPullParserException {
      +        if (pos >= bufEnd) {
                   fillBuf();
                   // this return value should be ignored as it is used in epilog parsing ...
      -            if ( reachedEnd )
      -                throw new EOFException( "no more data available" + getPositionDescription() );
      +            if (reachedEnd) throw new EOFException("no more data available" + getPositionDescription());
               }
               final char ch = buf[pos++];
               // line/columnNumber
      -        if ( ch == '\n' )
      -        {
      +        if (ch == '\n') {
                   ++lineNumber;
                   columnNumber = 1;
      -        }
      -        else
      -        {
      +        } else {
                   ++columnNumber;
               }
               // System.out.print(ch);
      @@ -4007,53 +3205,44 @@ private char more()
           // return pos + bufAbsoluteStart;
           // }
       
      -    private void ensurePC( int end )
      -    {
      +    private void ensurePC(int end) {
               // assert end >= pc.length;
               final int newSize = end > READ_CHUNK_SIZE ? 2 * end : 2 * READ_CHUNK_SIZE;
               final char[] newPC = new char[newSize];
      -        if ( TRACE_SIZING )
      -            System.out.println( "TRACE_SIZING ensurePC() " + pc.length + " ==> " + newSize + " end=" + end );
      -        System.arraycopy( pc, 0, newPC, 0, pcEnd );
      +        if (TRACE_SIZING)
      +            System.out.println("TRACE_SIZING ensurePC() " + pc.length + " ==> " + newSize + " end=" + end);
      +        System.arraycopy(pc, 0, newPC, 0, pcEnd);
               pc = newPC;
               // assert end < pc.length;
           }
       
      -    private void joinPC()
      -    {
      +    private void joinPC() {
               // assert usePC == false;
               // assert posEnd > posStart;
               final int len = posEnd - posStart;
               final int newEnd = pcEnd + len + 1;
      -        if ( newEnd >= pc.length )
      -            ensurePC( newEnd ); // add 1 for extra space for one char
      +        if (newEnd >= pc.length) ensurePC(newEnd); // add 1 for extra space for one char
               // assert newEnd < pc.length;
      -        System.arraycopy( buf, posStart, pc, pcEnd, len );
      +        System.arraycopy(buf, posStart, pc, pcEnd, len);
               pcEnd += len;
               usePC = true;
      -
           }
       
      -    private char requireInput( char ch, char[] input )
      -        throws XmlPullParserException, IOException
      -    {
      -        for ( char anInput : input )
      -        {
      -            if ( ch != anInput )
      -            {
      -                throw new XmlPullParserException( "expected " + printable( anInput ) + " in " + new String( input )
      -                    + " and not " + printable( ch ), this, null );
      +    private char requireInput(char ch, char[] input) throws XmlPullParserException, IOException {
      +        for (char anInput : input) {
      +            if (ch != anInput) {
      +                throw new XmlPullParserException(
      +                        "expected " + printable(anInput) + " in " + new String(input) + " and not " + printable(ch),
      +                        this,
      +                        null);
                   }
                   ch = more();
               }
               return ch;
           }
       
      -    private char skipS( char ch )
      -        throws XmlPullParserException, IOException
      -    {
      -        while ( isS( ch ) )
      -        {
      +    private char skipS(char ch) throws XmlPullParserException, IOException {
      +        while (isS(ch)) {
                   ch = more();
               } // skip additional spaces
               return ch;
      @@ -4070,48 +3259,40 @@ private char skipS( char ch )
       
           private static final boolean[] lookupNameChar = new boolean[LOOKUP_MAX];
       
      -    private static void setName( char ch )
      -    // { lookupNameChar[ (int)ch / 32 ] |= (1 << (ch % 32)); }
      -    {
      +    private static void setName(char ch)
      +                // { lookupNameChar[ (int)ch / 32 ] |= (1 << (ch % 32)); }
      +            {
               lookupNameChar[ch] = true;
           }
       
      -    private static void setNameStart( char ch )
      -    // { lookupNameStartChar[ (int)ch / 32 ] |= (1 << (ch % 32)); setName(ch); }
      -    {
      +    private static void setNameStart(char ch)
      +                // { lookupNameStartChar[ (int)ch / 32 ] |= (1 << (ch % 32)); setName(ch); }
      +            {
               lookupNameStartChar[ch] = true;
      -        setName( ch );
      +        setName(ch);
           }
       
      -    static
      -    {
      -        setNameStart( ':' );
      -        for ( char ch = 'A'; ch <= 'Z'; ++ch )
      -            setNameStart( ch );
      -        setNameStart( '_' );
      -        for ( char ch = 'a'; ch <= 'z'; ++ch )
      -            setNameStart( ch );
      -        for ( char ch = '\u00c0'; ch <= '\u02FF'; ++ch )
      -            setNameStart( ch );
      -        for ( char ch = '\u0370'; ch <= '\u037d'; ++ch )
      -            setNameStart( ch );
      -        for ( char ch = '\u037f'; ch < '\u0400'; ++ch )
      -            setNameStart( ch );
      -
      -        setName( '-' );
      -        setName( '.' );
      -        for ( char ch = '0'; ch <= '9'; ++ch )
      -            setName( ch );
      -        setName( '\u00b7' );
      -        for ( char ch = '\u0300'; ch <= '\u036f'; ++ch )
      -            setName( ch );
      +    static {
      +        setNameStart(':');
      +        for (char ch = 'A'; ch <= 'Z'; ++ch) setNameStart(ch);
      +        setNameStart('_');
      +        for (char ch = 'a'; ch <= 'z'; ++ch) setNameStart(ch);
      +        for (char ch = '\u00c0'; ch <= '\u02FF'; ++ch) setNameStart(ch);
      +        for (char ch = '\u0370'; ch <= '\u037d'; ++ch) setNameStart(ch);
      +        for (char ch = '\u037f'; ch < '\u0400'; ++ch) setNameStart(ch);
      +
      +        setName('-');
      +        setName('.');
      +        for (char ch = '0'; ch <= '9'; ++ch) setName(ch);
      +        setName('\u00b7');
      +        for (char ch = '\u0300'; ch <= '\u036f'; ++ch) setName(ch);
           }
       
           // protected boolean isNameStartChar( char ch )
      -    private static boolean isNameStartChar( char ch )
      -    {
      -        return ch < LOOKUP_MAX_CHAR ? lookupNameStartChar[ch] : ( ch <= '\u2027' )
      -            || ( ch >= '\u202A' && ch <= '\u218F' ) || ( ch >= '\u2800' && ch <= '\uFFEF' );
      +    private static boolean isNameStartChar(char ch) {
      +        return ch < LOOKUP_MAX_CHAR
      +                ? lookupNameStartChar[ch]
      +                : (ch <= '\u2027') || (ch >= '\u202A' && ch <= '\u218F') || (ch >= '\u2800' && ch <= '\uFFEF');
       
               // if(ch < LOOKUP_MAX_CHAR) return lookupNameStartChar[ ch ];
               // else return ch <= '\u2027'
      @@ -4135,14 +3316,14 @@ private static boolean isNameStartChar( char ch )
           }
       
           // protected boolean isNameChar( char ch )
      -    private static boolean isNameChar( char ch )
      -    {
      +    private static boolean isNameChar(char ch) {
               // return isNameStartChar(ch);
       
               // if(ch < LOOKUP_MAX_CHAR) return (lookupNameChar[ (int)ch / 32 ] & (1 << (ch % 32))) != 0;
       
      -        return ch < LOOKUP_MAX_CHAR ? lookupNameChar[ch] : ( ch <= '\u2027' )
      -            || ( ch >= '\u202A' && ch <= '\u218F' ) || ( ch >= '\u2800' && ch <= '\uFFEF' );
      +        return ch < LOOKUP_MAX_CHAR
      +                ? lookupNameChar[ch]
      +                : (ch <= '\u2027') || (ch >= '\u202A' && ch <= '\u218F') || (ch >= '\u2800' && ch <= '\uFFEF');
               // return false;
               // return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == ':'
               // || (ch >= '0' && ch <= '9');
      @@ -4159,9 +3340,8 @@ private static boolean isNameChar( char ch )
               // else return false;
           }
       
      -    private static boolean isS( char ch )
      -    {
      -        return ( ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' );
      +    private static boolean isS(char ch) {
      +        return (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t');
               // || (supportXml11 && (ch == '\u0085' || ch == '\u2028');
           }
       
      @@ -4169,52 +3349,36 @@ private static boolean isS( char ch )
           // ch != '\u0000' ch < '\uFFFE'
       
           // private char printable(char ch) { return ch; }
      -    private static String printable( int ch )
      -    {
      -        if ( ch == '\n' )
      -        {
      +    private static String printable(int ch) {
      +        if (ch == '\n') {
                   return "\\n";
      -        }
      -        else if ( ch == '\r' )
      -        {
      +        } else if (ch == '\r') {
                   return "\\r";
      -        }
      -        else if ( ch == '\t' )
      -        {
      +        } else if (ch == '\t') {
                   return "\\t";
      -        }
      -        else if ( ch == '\'' )
      -        {
      +        } else if (ch == '\'') {
                   return "\\'";
               }
      -        if ( ch > 127 || ch < 32 )
      -        {
      -            return "\\u" + Integer.toHexString( ch );
      -        }
      -        if ( Character.isBmpCodePoint( ch ) )
      -        {
      -            return Character.toString( ( char ) ch );
      +        if (ch > 127 || ch < 32) {
      +            return "\\u" + Integer.toHexString(ch);
               }
      -        else
      -        {
      -            return new String( new char[] { Character.highSurrogate( ch ), Character.lowSurrogate( ch ) } );
      +        if (Character.isBmpCodePoint(ch)) {
      +            return Character.toString((char) ch);
      +        } else {
      +            return new String(new char[] {Character.highSurrogate(ch), Character.lowSurrogate(ch)});
               }
           }
       
      -    private static String printable( String s )
      -    {
      -        if ( s == null )
      -            return null;
      +    private static String printable(String s) {
      +        if (s == null) return null;
               final int sLen = s.codePointCount(0, s.length());
      -        StringBuilder buf = new StringBuilder( sLen + 10 );
      -        for ( int i = 0; i < sLen; ++i )
      -        {
      -            buf.append( printable( s.codePointAt( i ) ) );
      +        StringBuilder buf = new StringBuilder(sLen + 10);
      +        for (int i = 0; i < sLen; ++i) {
      +            buf.append(printable(s.codePointAt(i)));
               }
               s = buf.toString();
               return s;
           }
      -
       }
       
       /*
      diff --git a/src/main/java/org/codehaus/plexus/util/xml/pull/MXSerializer.java b/src/main/java/org/codehaus/plexus/util/xml/pull/MXSerializer.java
      index c69db3f4..e69d28f8 100644
      --- a/src/main/java/org/codehaus/plexus/util/xml/pull/MXSerializer.java
      +++ b/src/main/java/org/codehaus/plexus/util/xml/pull/MXSerializer.java
      @@ -25,27 +25,25 @@
        * 
    • PROPERTY_SERIALIZER_LINE_SEPARATOR *
    */ -public class MXSerializer - implements XmlSerializer -{ - protected final static String XML_URI = "http://www.w3.org/XML/1998/namespace"; +public class MXSerializer implements XmlSerializer { + protected static final String XML_URI = "http://www.w3.org/XML/1998/namespace"; - protected final static String XMLNS_URI = "http://www.w3.org/2000/xmlns/"; + protected static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/"; private static final boolean TRACE_SIZING = false; protected final String FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE = - "http://xmlpull.org/v1/doc/features.html#serializer-attvalue-use-apostrophe"; + "http://xmlpull.org/v1/doc/features.html#serializer-attvalue-use-apostrophe"; protected final String FEATURE_NAMES_INTERNED = "http://xmlpull.org/v1/doc/features.html#names-interned"; protected final String PROPERTY_SERIALIZER_INDENTATION = - "http://xmlpull.org/v1/doc/properties.html#serializer-indentation"; + "http://xmlpull.org/v1/doc/properties.html#serializer-indentation"; protected final String PROPERTY_SERIALIZER_LINE_SEPARATOR = - "http://xmlpull.org/v1/doc/properties.html#serializer-line-separator"; + "http://xmlpull.org/v1/doc/properties.html#serializer-line-separator"; - protected final static String PROPERTY_LOCATION = "http://xmlpull.org/v1/doc/properties.html#location"; + protected static final String PROPERTY_LOCATION = "http://xmlpull.org/v1/doc/properties.html#location"; // properties/features protected boolean namesInterned; @@ -101,36 +99,30 @@ public class MXSerializer protected static final String precomputedPrefixes[]; - static - { + static { precomputedPrefixes = new String[32]; // arbitrary number ... - for ( int i = 0; i < precomputedPrefixes.length; i++ ) - { - precomputedPrefixes[i] = ( "n" + i ).intern(); + for (int i = 0; i < precomputedPrefixes.length; i++) { + precomputedPrefixes[i] = ("n" + i).intern(); } } private boolean checkNamesInterned = false; - private void checkInterning( String name ) - { - if ( namesInterned && name != name.intern() ) - { - throw new IllegalArgumentException( "all names passed as arguments must be interned" - + "when NAMES INTERNED feature is enabled" ); + private void checkInterning(String name) { + if (namesInterned && name != name.intern()) { + throw new IllegalArgumentException( + "all names passed as arguments must be interned" + "when NAMES INTERNED feature is enabled"); } } - protected void reset() - { + protected void reset() { location = null; out = null; autoDeclaredPrefixes = 0; depth = 0; // nullify references on all levels to allow it to be GCed - for ( int i = 0; i < elNamespaceCount.length; i++ ) - { + for (int i = 0; i < elNamespaceCount.length; i++) { elName[i] = null; elNamespace[i] = null; elNamespaceCount[i] = 2; @@ -165,59 +157,49 @@ protected void reset() seenBracketBracket = false; } - protected void ensureElementsCapacity() - { + protected void ensureElementsCapacity() { final int elStackSize = elName.length; // assert (depth + 1) >= elName.length; // we add at least one extra slot ... - final int newSize = ( depth >= 7 ? 2 * depth : 8 ) + 2; // = lucky 7 + 1 //25 - if ( TRACE_SIZING ) - { - System.err.println( getClass().getName() + " elStackSize " + elStackSize + " ==> " + newSize ); + final int newSize = (depth >= 7 ? 2 * depth : 8) + 2; // = lucky 7 + 1 //25 + if (TRACE_SIZING) { + System.err.println(getClass().getName() + " elStackSize " + elStackSize + " ==> " + newSize); } final boolean needsCopying = elStackSize > 0; String[] arr = null; // reuse arr local variable slot arr = new String[newSize]; - if ( needsCopying ) - System.arraycopy( elName, 0, arr, 0, elStackSize ); + if (needsCopying) System.arraycopy(elName, 0, arr, 0, elStackSize); elName = arr; arr = new String[newSize]; - if ( needsCopying ) - System.arraycopy( elNamespace, 0, arr, 0, elStackSize ); + if (needsCopying) System.arraycopy(elNamespace, 0, arr, 0, elStackSize); elNamespace = arr; final int[] iarr = new int[newSize]; - if ( needsCopying ) - { - System.arraycopy( elNamespaceCount, 0, iarr, 0, elStackSize ); - } - else - { + if (needsCopying) { + System.arraycopy(elNamespaceCount, 0, iarr, 0, elStackSize); + } else { // special initialization iarr[0] = 0; } elNamespaceCount = iarr; } - protected void ensureNamespacesCapacity() - { // int size) { + protected void ensureNamespacesCapacity() { // int size) { // int namespaceSize = namespacePrefix != null ? namespacePrefix.length : 0; // assert (namespaceEnd >= namespacePrefix.length); // if(size >= namespaceSize) { // int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25 final int newSize = namespaceEnd > 7 ? 2 * namespaceEnd : 8; - if ( TRACE_SIZING ) - { - System.err.println( getClass().getName() + " namespaceSize " + namespacePrefix.length + " ==> " + newSize ); + if (TRACE_SIZING) { + System.err.println(getClass().getName() + " namespaceSize " + namespacePrefix.length + " ==> " + newSize); } final String[] newNamespacePrefix = new String[newSize]; final String[] newNamespaceUri = new String[newSize]; - if ( namespacePrefix != null ) - { - System.arraycopy( namespacePrefix, 0, newNamespacePrefix, 0, namespaceEnd ); - System.arraycopy( namespaceUri, 0, newNamespaceUri, 0, namespaceEnd ); + if (namespacePrefix != null) { + System.arraycopy(namespacePrefix, 0, newNamespacePrefix, 0, namespaceEnd); + System.arraycopy(namespaceUri, 0, newNamespaceUri, 0, namespaceEnd); } namespacePrefix = newNamespacePrefix; namespaceUri = newNamespaceUri; @@ -237,45 +219,29 @@ protected void ensureNamespacesCapacity() } @Override - public void setFeature( String name, boolean state ) - throws IllegalArgumentException, IllegalStateException - { - if ( name == null ) - { - throw new IllegalArgumentException( "feature name can not be null" ); + public void setFeature(String name, boolean state) throws IllegalArgumentException, IllegalStateException { + if (name == null) { + throw new IllegalArgumentException("feature name can not be null"); } - if ( FEATURE_NAMES_INTERNED.equals( name ) ) - { + if (FEATURE_NAMES_INTERNED.equals(name)) { namesInterned = state; - } - else if ( FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE.equals( name ) ) - { + } else if (FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE.equals(name)) { attributeUseApostrophe = state; - } - else - { - throw new IllegalStateException( "unsupported feature " + name ); + } else { + throw new IllegalStateException("unsupported feature " + name); } } @Override - public boolean getFeature( String name ) - throws IllegalArgumentException - { - if ( name == null ) - { - throw new IllegalArgumentException( "feature name can not be null" ); + public boolean getFeature(String name) throws IllegalArgumentException { + if (name == null) { + throw new IllegalArgumentException("feature name can not be null"); } - if ( FEATURE_NAMES_INTERNED.equals( name ) ) - { + if (FEATURE_NAMES_INTERNED.equals(name)) { return namesInterned; - } - else if ( FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE.equals( name ) ) - { + } else if (FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE.equals(name)) { return attributeUseApostrophe; - } - else - { + } else { return false; } } @@ -297,86 +263,64 @@ else if ( FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE.equals( name ) ) * For maximum efficiency when writing indents the required output is pre-computed This is internal function that * recomputes buffer after user requested changes. */ - protected void rebuildIndentationBuf() - { - if ( doIndent == false ) - return; + protected void rebuildIndentationBuf() { + if (doIndent == false) return; final int maxIndent = 65; // hardcoded maximum indentation size in characters int bufSize = 0; offsetNewLine = 0; - if ( writeLineSeparator ) - { + if (writeLineSeparator) { offsetNewLine = lineSeparator.length(); bufSize += offsetNewLine; } maxIndentLevel = 0; - if ( writeIndentation ) - { + if (writeIndentation) { indentationJump = indentationString.length(); maxIndentLevel = maxIndent / indentationJump; bufSize += maxIndentLevel * indentationJump; } - if ( indentationBuf == null || indentationBuf.length < bufSize ) - { + if (indentationBuf == null || indentationBuf.length < bufSize) { indentationBuf = new char[bufSize + 8]; } int bufPos = 0; - if ( writeLineSeparator ) - { - for ( int i = 0; i < lineSeparator.length(); i++ ) - { - indentationBuf[bufPos++] = lineSeparator.charAt( i ); + if (writeLineSeparator) { + for (int i = 0; i < lineSeparator.length(); i++) { + indentationBuf[bufPos++] = lineSeparator.charAt(i); } } - if ( writeIndentation ) - { - for ( int i = 0; i < maxIndentLevel; i++ ) - { - for ( int j = 0; j < indentationString.length(); j++ ) - { - indentationBuf[bufPos++] = indentationString.charAt( j ); + if (writeIndentation) { + for (int i = 0; i < maxIndentLevel; i++) { + for (int j = 0; j < indentationString.length(); j++) { + indentationBuf[bufPos++] = indentationString.charAt(j); } } } } // if(doIndent) writeIndent(); - protected void writeIndent() - throws IOException - { + protected void writeIndent() throws IOException { final int start = writeLineSeparator ? 0 : offsetNewLine; - final int level = ( depth > maxIndentLevel ) ? maxIndentLevel : depth; - out.write( indentationBuf, start, ( level * indentationJump ) + offsetNewLine ); + final int level = (depth > maxIndentLevel) ? maxIndentLevel : depth; + out.write(indentationBuf, start, (level * indentationJump) + offsetNewLine); } @Override - public void setProperty( String name, Object value ) - throws IllegalArgumentException, IllegalStateException - { - if ( name == null ) - { - throw new IllegalArgumentException( "property name can not be null" ); + public void setProperty(String name, Object value) throws IllegalArgumentException, IllegalStateException { + if (name == null) { + throw new IllegalArgumentException("property name can not be null"); } - if ( PROPERTY_SERIALIZER_INDENTATION.equals( name ) ) - { + if (PROPERTY_SERIALIZER_INDENTATION.equals(name)) { indentationString = (String) value; - } - else if ( PROPERTY_SERIALIZER_LINE_SEPARATOR.equals( name ) ) - { + } else if (PROPERTY_SERIALIZER_LINE_SEPARATOR.equals(name)) { lineSeparator = (String) value; - } - else if ( PROPERTY_LOCATION.equals( name ) ) - { + } else if (PROPERTY_LOCATION.equals(name)) { location = (String) value; - } - else - { - throw new IllegalStateException( "unsupported property " + name ); + } else { + throw new IllegalStateException("unsupported property " + name); } writeLineSeparator = lineSeparator != null && lineSeparator.length() > 0; writeIndentation = indentationString != null && indentationString.length() > 0; // optimize - do not write when nothing to write ... - doIndent = indentationString != null && ( writeLineSeparator || writeIndentation ); + doIndent = indentationString != null && (writeLineSeparator || writeIndentation); // NOTE: when indentationString == null there is no indentation // (even though writeLineSeparator may be true ...) rebuildIndentationBuf(); @@ -384,125 +328,91 @@ else if ( PROPERTY_LOCATION.equals( name ) ) } @Override - public Object getProperty( String name ) - throws IllegalArgumentException - { - if ( name == null ) - { - throw new IllegalArgumentException( "property name can not be null" ); + public Object getProperty(String name) throws IllegalArgumentException { + if (name == null) { + throw new IllegalArgumentException("property name can not be null"); } - if ( PROPERTY_SERIALIZER_INDENTATION.equals( name ) ) - { + if (PROPERTY_SERIALIZER_INDENTATION.equals(name)) { return indentationString; - } - else if ( PROPERTY_SERIALIZER_LINE_SEPARATOR.equals( name ) ) - { + } else if (PROPERTY_SERIALIZER_LINE_SEPARATOR.equals(name)) { return lineSeparator; - } - else if ( PROPERTY_LOCATION.equals( name ) ) - { + } else if (PROPERTY_LOCATION.equals(name)) { return location; - } - else - { + } else { return null; } } - private String getLocation() - { + private String getLocation() { return location != null ? " @" + location : ""; } // this is special method that can be accessed directly to retrieve Writer serializer is using - public Writer getWriter() - { + public Writer getWriter() { return out; } @Override - public void setOutput( Writer writer ) - { + public void setOutput(Writer writer) { reset(); out = writer; } @Override - public void setOutput( OutputStream os, String encoding ) - throws IOException - { - if ( os == null ) - throw new IllegalArgumentException( "output stream can not be null" ); + public void setOutput(OutputStream os, String encoding) throws IOException { + if (os == null) throw new IllegalArgumentException("output stream can not be null"); reset(); - if ( encoding != null ) - { - out = new OutputStreamWriter( os, encoding ); - } - else - { - out = new OutputStreamWriter( os ); + if (encoding != null) { + out = new OutputStreamWriter(os, encoding); + } else { + out = new OutputStreamWriter(os); } } @Override - public void startDocument( String encoding, Boolean standalone ) - throws IOException - { + public void startDocument(String encoding, Boolean standalone) throws IOException { char apos = attributeUseApostrophe ? '\'' : '"'; - if ( attributeUseApostrophe ) - { - out.write( "" ); - if ( writeLineSeparator ) - { - out.write( lineSeparator ); + out.write("?>"); + if (writeLineSeparator) { + out.write(lineSeparator); } } @Override - public void endDocument() - throws IOException - { + public void endDocument() throws IOException { // close all unclosed tag; - while ( depth > 0 ) - { - endTag( elNamespace[depth], elName[depth] ); + while (depth > 0) { + endTag(elNamespace[depth], elName[depth]); } - if ( writeLineSeparator ) - { - out.write( lineSeparator ); + if (writeLineSeparator) { + out.write(lineSeparator); } // assert depth == 0; // assert startTagIncomplete == false; @@ -511,54 +421,37 @@ public void endDocument() } @Override - public void setPrefix( String prefix, String namespace ) - throws IOException - { - if ( startTagIncomplete ) - closeStartTag(); + public void setPrefix(String prefix, String namespace) throws IOException { + if (startTagIncomplete) closeStartTag(); // assert prefix != null; // assert namespace != null; - if ( prefix == null ) - { + if (prefix == null) { prefix = ""; } - if ( !namesInterned ) - { + if (!namesInterned) { prefix = prefix.intern(); // will throw NPE if prefix==null - } - else if ( checkNamesInterned ) - { - checkInterning( prefix ); - } - else if ( prefix == null ) - { - throw new IllegalArgumentException( "prefix must be not null" + getLocation() ); + } else if (checkNamesInterned) { + checkInterning(prefix); + } else if (prefix == null) { + throw new IllegalArgumentException("prefix must be not null" + getLocation()); } // check that prefix is not duplicated ... - for ( int i = elNamespaceCount[depth]; i < namespaceEnd; i++ ) - { - if ( prefix == namespacePrefix[i] ) - { - throw new IllegalStateException( "duplicated prefix " + printable( prefix ) + getLocation() ); + for (int i = elNamespaceCount[depth]; i < namespaceEnd; i++) { + if (prefix == namespacePrefix[i]) { + throw new IllegalStateException("duplicated prefix " + printable(prefix) + getLocation()); } } - if ( !namesInterned ) - { + if (!namesInterned) { namespace = namespace.intern(); - } - else if ( checkNamesInterned ) - { - checkInterning( namespace ); - } - else if ( namespace == null ) - { - throw new IllegalArgumentException( "namespace must be not null" + getLocation() ); + } else if (checkNamesInterned) { + checkInterning(namespace); + } else if (namespace == null) { + throw new IllegalArgumentException("namespace must be not null" + getLocation()); } - if ( namespaceEnd >= namespacePrefix.length ) - { + if (namespaceEnd >= namespacePrefix.length) { ensureNamespacesCapacity(); } namespacePrefix[namespaceEnd] = prefix; @@ -567,44 +460,33 @@ else if ( namespace == null ) setPrefixCalled = true; } - protected String lookupOrDeclarePrefix( String namespace ) - { - return getPrefix( namespace, true ); + protected String lookupOrDeclarePrefix(String namespace) { + return getPrefix(namespace, true); } @Override - public String getPrefix( String namespace, boolean generatePrefix ) - { + public String getPrefix(String namespace, boolean generatePrefix) { // assert namespace != null; - if ( !namesInterned ) - { + if (!namesInterned) { // when String is interned we can do much faster namespace stack lookups ... namespace = namespace.intern(); - } - else if ( checkNamesInterned ) - { - checkInterning( namespace ); + } else if (checkNamesInterned) { + checkInterning(namespace); // assert namespace != namespace.intern(); } - if ( namespace == null ) - { - throw new IllegalArgumentException( "namespace must be not null" + getLocation() ); - } - else if ( namespace.length() == 0 ) - { - throw new IllegalArgumentException( "default namespace cannot have prefix" + getLocation() ); + if (namespace == null) { + throw new IllegalArgumentException("namespace must be not null" + getLocation()); + } else if (namespace.length() == 0) { + throw new IllegalArgumentException("default namespace cannot have prefix" + getLocation()); } // first check if namespace is already in scope - for ( int i = namespaceEnd - 1; i >= 0; --i ) - { - if ( namespace == namespaceUri[i] ) - { + for (int i = namespaceEnd - 1; i >= 0; --i) { + if (namespace == namespaceUri[i]) { final String prefix = namespacePrefix[i]; // now check that prefix is still in scope - for ( int p = namespaceEnd - 1; p > i; --p ) - { - if ( prefix == namespacePrefix[p] ) + for (int p = namespaceEnd - 1; p > i; --p) { + if (prefix == namespacePrefix[p]) continue; // too bad - prefix is redeclared with different namespace } return prefix; @@ -612,35 +494,29 @@ else if ( namespace.length() == 0 ) } // so not found it ... - if ( !generatePrefix ) - { + if (!generatePrefix) { return null; } - return generatePrefix( namespace ); + return generatePrefix(namespace); } - private String generatePrefix( String namespace ) - { + private String generatePrefix(String namespace) { // assert namespace == namespace.intern(); - while ( true ) - { + while (true) { ++autoDeclaredPrefixes; // fast lookup uses table that was pre-initialized in static{} .... - final String prefix = - autoDeclaredPrefixes < precomputedPrefixes.length ? precomputedPrefixes[autoDeclaredPrefixes] - : ( "n" + autoDeclaredPrefixes ).intern(); + final String prefix = autoDeclaredPrefixes < precomputedPrefixes.length + ? precomputedPrefixes[autoDeclaredPrefixes] + : ("n" + autoDeclaredPrefixes).intern(); // make sure this prefix is not declared in any scope (avoid hiding in-scope prefixes)! - for ( int i = namespaceEnd - 1; i >= 0; --i ) - { - if ( prefix == namespacePrefix[i] ) - { + for (int i = namespaceEnd - 1; i >= 0; --i) { + if (prefix == namespacePrefix[i]) { continue; // prefix is already declared - generate new and try again } } // declare prefix - if ( namespaceEnd >= namespacePrefix.length ) - { + if (namespaceEnd >= namespacePrefix.length) { ensureNamespacesCapacity(); } namespacePrefix[namespaceEnd] = prefix; @@ -652,84 +528,66 @@ private String generatePrefix( String namespace ) } @Override - public int getDepth() - { + public int getDepth() { return depth; } @Override - public String getNamespace() - { + public String getNamespace() { return elNamespace[depth]; } @Override - public String getName() - { + public String getName() { return elName[depth]; } @Override - public XmlSerializer startTag( String namespace, String name ) - throws IOException - { + public XmlSerializer startTag(String namespace, String name) throws IOException { - if ( startTagIncomplete ) - { + if (startTagIncomplete) { closeStartTag(); } seenBracket = seenBracketBracket = false; - if ( doIndent && depth > 0 && seenTag ) - { + if (doIndent && depth > 0 && seenTag) { writeIndent(); } seenTag = true; setPrefixCalled = false; startTagIncomplete = true; ++depth; - if ( ( depth + 1 ) >= elName.length ) - { + if ((depth + 1) >= elName.length) { ensureElementsCapacity(); } //// assert namespace != null; - if ( checkNamesInterned && namesInterned ) - checkInterning( namespace ); - elNamespace[depth] = ( namesInterned || namespace == null ) ? namespace : namespace.intern(); + if (checkNamesInterned && namesInterned) checkInterning(namespace); + elNamespace[depth] = (namesInterned || namespace == null) ? namespace : namespace.intern(); // assert name != null; // elName[ depth ] = name; - if ( checkNamesInterned && namesInterned ) - checkInterning( name ); - elName[depth] = ( namesInterned || name == null ) ? name : name.intern(); - if ( out == null ) - { - throw new IllegalStateException( "setOutput() must called set before serialization can start" ); + if (checkNamesInterned && namesInterned) checkInterning(name); + elName[depth] = (namesInterned || name == null) ? name : name.intern(); + if (out == null) { + throw new IllegalStateException("setOutput() must called set before serialization can start"); } - out.write( '<' ); - if ( namespace != null ) - { + out.write('<'); + if (namespace != null) { - if ( namespace.length() > 0 ) - { + if (namespace.length() > 0) { // ALEK: in future make it as feature on serializer String prefix = null; - if ( depth > 0 && ( namespaceEnd - elNamespaceCount[depth - 1] ) == 1 ) - { + if (depth > 0 && (namespaceEnd - elNamespaceCount[depth - 1]) == 1) { // if only one prefix was declared un-declare it if prefix is already declared on parent el with the // same URI String uri = namespaceUri[namespaceEnd - 1]; - if ( uri == namespace || uri.equals( namespace ) ) - { + if (uri == namespace || uri.equals(namespace)) { String elPfx = namespacePrefix[namespaceEnd - 1]; // 2 == to skip predefined namespaces (xml and xmlns ...) - for ( int pos = elNamespaceCount[depth - 1] - 1; pos >= 2; --pos ) - { + for (int pos = elNamespaceCount[depth - 1] - 1; pos >= 2; --pos) { String pf = namespacePrefix[pos]; - if ( pf == elPfx || pf.equals( elPfx ) ) - { + if (pf == elPfx || pf.equals(elPfx)) { String n = namespaceUri[pos]; - if ( n == uri || n.equals( uri ) ) - { + if (n == uri || n.equals(uri)) { --namespaceEnd; // un-declare namespace prefix = elPfx; } @@ -738,224 +596,175 @@ public XmlSerializer startTag( String namespace, String name ) } } } - if ( prefix == null ) - { - prefix = lookupOrDeclarePrefix( namespace ); + if (prefix == null) { + prefix = lookupOrDeclarePrefix(namespace); } // assert prefix != null; // make sure that default ("") namespace to not print ":" - if ( prefix.length() > 0 ) - { - out.write( prefix ); - out.write( ':' ); + if (prefix.length() > 0) { + out.write(prefix); + out.write(':'); } - } - else - { + } else { // make sure that default namespace can be declared - for ( int i = namespaceEnd - 1; i >= 0; --i ) - { - if ( namespacePrefix[i] == "" ) - { + for (int i = namespaceEnd - 1; i >= 0; --i) { + if (namespacePrefix[i] == "") { final String uri = namespaceUri[i]; - if ( uri == null ) - { + if (uri == null) { // declare default namespace - setPrefix( "", "" ); - } - else if ( uri.length() > 0 ) - { - throw new IllegalStateException( "start tag can not be written in empty default namespace " - + "as default namespace is currently bound to '" + uri + "'" + getLocation() ); + setPrefix("", ""); + } else if (uri.length() > 0) { + throw new IllegalStateException("start tag can not be written in empty default namespace " + + "as default namespace is currently bound to '" + uri + "'" + getLocation()); } break; } } } - } - out.write( name ); + out.write(name); return this; } @Override - public XmlSerializer attribute( String namespace, String name, String value ) - throws IOException - { - if ( !startTagIncomplete ) - { - throw new IllegalArgumentException( "startTag() must be called before attribute()" + getLocation() ); + public XmlSerializer attribute(String namespace, String name, String value) throws IOException { + if (!startTagIncomplete) { + throw new IllegalArgumentException("startTag() must be called before attribute()" + getLocation()); } // assert setPrefixCalled == false; - out.write( ' ' ); + out.write(' '); //// assert namespace != null; - if ( namespace != null && namespace.length() > 0 ) - { + if (namespace != null && namespace.length() > 0) { // namespace = namespace.intern(); - if ( !namesInterned ) - { + if (!namesInterned) { namespace = namespace.intern(); + } else if (checkNamesInterned) { + checkInterning(namespace); } - else if ( checkNamesInterned ) - { - checkInterning( namespace ); - } - String prefix = lookupOrDeclarePrefix( namespace ); + String prefix = lookupOrDeclarePrefix(namespace); // assert( prefix != null); - if ( prefix.length() == 0 ) - { + if (prefix.length() == 0) { // needs to declare prefix to hold default namespace // NOTE: attributes such as a='b' are in NO namespace - prefix = generatePrefix( namespace ); + prefix = generatePrefix(namespace); } - out.write( prefix ); - out.write( ':' ); + out.write(prefix); + out.write(':'); // if(prefix.length() > 0) { // out.write(prefix); // out.write(':'); // } } // assert name != null; - out.write( name ); - out.write( '=' ); + out.write(name); + out.write('='); // assert value != null; - out.write( attributeUseApostrophe ? '\'' : '"' ); - writeAttributeValue( value, out ); - out.write( attributeUseApostrophe ? '\'' : '"' ); + out.write(attributeUseApostrophe ? '\'' : '"'); + writeAttributeValue(value, out); + out.write(attributeUseApostrophe ? '\'' : '"'); return this; } - protected void closeStartTag() - throws IOException - { - if ( finished ) - { - throw new IllegalArgumentException( "trying to write past already finished output" + getLocation() ); + protected void closeStartTag() throws IOException { + if (finished) { + throw new IllegalArgumentException("trying to write past already finished output" + getLocation()); } - if ( seenBracket ) - { + if (seenBracket) { seenBracket = seenBracketBracket = false; } - if ( startTagIncomplete || setPrefixCalled ) - { - if ( setPrefixCalled ) - { - throw new IllegalArgumentException( "startTag() must be called immediately after setPrefix()" - + getLocation() ); + if (startTagIncomplete || setPrefixCalled) { + if (setPrefixCalled) { + throw new IllegalArgumentException( + "startTag() must be called immediately after setPrefix()" + getLocation()); } - if ( !startTagIncomplete ) - { - throw new IllegalArgumentException( "trying to close start tag that is not opened" + getLocation() ); + if (!startTagIncomplete) { + throw new IllegalArgumentException("trying to close start tag that is not opened" + getLocation()); } // write all namespace declarations! writeNamespaceDeclarations(); - out.write( '>' ); + out.write('>'); elNamespaceCount[depth] = namespaceEnd; startTagIncomplete = false; } } - private void writeNamespaceDeclarations() - throws IOException - { + private void writeNamespaceDeclarations() throws IOException { // int start = elNamespaceCount[ depth - 1 ]; - for ( int i = elNamespaceCount[depth - 1]; i < namespaceEnd; i++ ) - { - if ( doIndent && namespaceUri[i].length() > 40 ) - { + for (int i = elNamespaceCount[depth - 1]; i < namespaceEnd; i++) { + if (doIndent && namespaceUri[i].length() > 40) { writeIndent(); - out.write( " " ); + out.write(" "); } - if ( namespacePrefix[i] != "" ) - { - out.write( " xmlns:" ); - out.write( namespacePrefix[i] ); - out.write( '=' ); + if (namespacePrefix[i] != "") { + out.write(" xmlns:"); + out.write(namespacePrefix[i]); + out.write('='); + } else { + out.write(" xmlns="); } - else - { - out.write( " xmlns=" ); - } - out.write( attributeUseApostrophe ? '\'' : '"' ); + out.write(attributeUseApostrophe ? '\'' : '"'); // NOTE: escaping of namespace value the same way as attributes!!!! - writeAttributeValue( namespaceUri[i], out ); + writeAttributeValue(namespaceUri[i], out); - out.write( attributeUseApostrophe ? '\'' : '"' ); + out.write(attributeUseApostrophe ? '\'' : '"'); } } @Override - public XmlSerializer endTag( String namespace, String name ) - throws IOException - { + public XmlSerializer endTag(String namespace, String name) throws IOException { // check that level is valid //// assert namespace != null; // if(namespace != null) { // namespace = namespace.intern(); // } seenBracket = seenBracketBracket = false; - if ( namespace != null ) - { - if ( !namesInterned ) - { + if (namespace != null) { + if (!namesInterned) { namespace = namespace.intern(); - } - else if ( checkNamesInterned ) - { - checkInterning( namespace ); + } else if (checkNamesInterned) { + checkInterning(namespace); } } - if ( namespace != elNamespace[depth] ) - { - throw new IllegalArgumentException( "expected namespace " + printable( elNamespace[depth] ) + " and not " - + printable( namespace ) + getLocation() ); + if (namespace != elNamespace[depth]) { + throw new IllegalArgumentException("expected namespace " + printable(elNamespace[depth]) + " and not " + + printable(namespace) + getLocation()); } - if ( name == null ) - { - throw new IllegalArgumentException( "end tag name can not be null" + getLocation() ); + if (name == null) { + throw new IllegalArgumentException("end tag name can not be null" + getLocation()); } - if ( checkNamesInterned && namesInterned ) - { - checkInterning( name ); + if (checkNamesInterned && namesInterned) { + checkInterning(name); } - if ( ( !namesInterned && !name.equals( elName[depth] ) ) || ( namesInterned && name != elName[depth] ) ) - { - throw new IllegalArgumentException( "expected element name " + printable( elName[depth] ) + " and not " - + printable( name ) + getLocation() ); + if ((!namesInterned && !name.equals(elName[depth])) || (namesInterned && name != elName[depth])) { + throw new IllegalArgumentException("expected element name " + printable(elName[depth]) + " and not " + + printable(name) + getLocation()); } - if ( startTagIncomplete ) - { + if (startTagIncomplete) { writeNamespaceDeclarations(); - out.write( " />" ); // space is added to make it easier to work in XHTML!!! + out.write(" />"); // space is added to make it easier to work in XHTML!!! --depth; - } - else - { + } else { --depth; // assert startTagIncomplete == false; - if ( doIndent && seenTag ) - { + if (doIndent && seenTag) { writeIndent(); } - out.write( " 0 ) - { + out.write(" 0) { // TODO prefix should be already known from matching start tag ... - final String prefix = lookupOrDeclarePrefix( namespace ); + final String prefix = lookupOrDeclarePrefix(namespace); // assert( prefix != null); - if ( prefix.length() > 0 ) - { - out.write( prefix ); - out.write( ':' ); + if (prefix.length() > 0) { + out.write(prefix); + out.write(':'); } } - out.write( name ); - out.write( '>' ); - + out.write(name); + out.write('>'); } namespaceEnd = elNamespaceCount[depth]; startTagIncomplete = false; @@ -964,171 +773,118 @@ else if ( checkNamesInterned ) } @Override - public XmlSerializer text( String text ) - throws IOException - { + public XmlSerializer text(String text) throws IOException { // assert text != null; - if ( startTagIncomplete || setPrefixCalled ) - closeStartTag(); - if ( doIndent && seenTag ) - seenTag = false; - writeElementContent( text, out ); + if (startTagIncomplete || setPrefixCalled) closeStartTag(); + if (doIndent && seenTag) seenTag = false; + writeElementContent(text, out); return this; } @Override - public XmlSerializer text( char[] buf, int start, int len ) - throws IOException - { - if ( startTagIncomplete || setPrefixCalled ) - closeStartTag(); - if ( doIndent && seenTag ) - seenTag = false; - writeElementContent( buf, start, len, out ); + public XmlSerializer text(char[] buf, int start, int len) throws IOException { + if (startTagIncomplete || setPrefixCalled) closeStartTag(); + if (doIndent && seenTag) seenTag = false; + writeElementContent(buf, start, len, out); return this; } @Override - public void cdsect( String text ) - throws IOException - { - if ( startTagIncomplete || setPrefixCalled || seenBracket ) - closeStartTag(); - if ( doIndent && seenTag ) - seenTag = false; - out.write( "" ); + public void cdsect(String text) throws IOException { + if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); + if (doIndent && seenTag) seenTag = false; + out.write(""); } @Override - public void entityRef( String text ) - throws IOException - { - if ( startTagIncomplete || setPrefixCalled || seenBracket ) - closeStartTag(); - if ( doIndent && seenTag ) - seenTag = false; - out.write( '&' ); - out.write( text ); // escape? - out.write( ';' ); + public void entityRef(String text) throws IOException { + if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); + if (doIndent && seenTag) seenTag = false; + out.write('&'); + out.write(text); // escape? + out.write(';'); } @Override - public void processingInstruction( String text ) - throws IOException - { - if ( startTagIncomplete || setPrefixCalled || seenBracket ) - closeStartTag(); - if ( doIndent && seenTag ) - seenTag = false; - out.write( "" ); + public void processingInstruction(String text) throws IOException { + if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); + if (doIndent && seenTag) seenTag = false; + out.write(""); } @Override - public void comment( String text ) - throws IOException - { - if ( startTagIncomplete || setPrefixCalled || seenBracket ) - closeStartTag(); - if ( doIndent && seenTag ) - seenTag = false; - out.write( "" ); + public void comment(String text) throws IOException { + if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); + if (doIndent && seenTag) seenTag = false; + out.write(""); } @Override - public void docdecl( String text ) - throws IOException - { - if ( startTagIncomplete || setPrefixCalled || seenBracket ) - closeStartTag(); - if ( doIndent && seenTag ) - seenTag = false; - out.write( "" ); + public void docdecl(String text) throws IOException { + if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); + if (doIndent && seenTag) seenTag = false; + out.write(""); } @Override - public void ignorableWhitespace( String text ) - throws IOException - { - if ( startTagIncomplete || setPrefixCalled || seenBracket ) - closeStartTag(); - if ( doIndent && seenTag ) - seenTag = false; - if ( text.length() == 0 ) - { - throw new IllegalArgumentException( "empty string is not allowed for ignorable whitespace" - + getLocation() ); + public void ignorableWhitespace(String text) throws IOException { + if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); + if (doIndent && seenTag) seenTag = false; + if (text.length() == 0) { + throw new IllegalArgumentException("empty string is not allowed for ignorable whitespace" + getLocation()); } - out.write( text ); // no escape? + out.write(text); // no escape? } @Override - public void flush() - throws IOException - { - if ( !finished && startTagIncomplete ) - closeStartTag(); + public void flush() throws IOException { + if (!finished && startTagIncomplete) closeStartTag(); out.flush(); } // --- utility methods - protected void writeAttributeValue( String value, Writer out ) - throws IOException - { + protected void writeAttributeValue(String value, Writer out) throws IOException { // .[apostrophe and <, & escaped], final char quot = attributeUseApostrophe ? '\'' : '"'; final String quotEntity = attributeUseApostrophe ? "'" : """; int pos = 0; - for ( int i = 0; i < value.length(); i++ ) - { - char ch = value.charAt( i ); - if ( ch == '&' ) - { - if ( i > pos ) - out.write( value.substring( pos, i ) ); - out.write( "&" ); + for (int i = 0; i < value.length(); i++) { + char ch = value.charAt(i); + if (ch == '&') { + if (i > pos) out.write(value.substring(pos, i)); + out.write("&"); pos = i + 1; } - if ( ch == '<' ) - { - if ( i > pos ) - out.write( value.substring( pos, i ) ); - out.write( "<" ); + if (ch == '<') { + if (i > pos) out.write(value.substring(pos, i)); + out.write("<"); pos = i + 1; - } - else if ( ch == quot ) - { - if ( i > pos ) - out.write( value.substring( pos, i ) ); - out.write( quotEntity ); + } else if (ch == quot) { + if (i > pos) out.write(value.substring(pos, i)); + out.write(quotEntity); pos = i + 1; - } - else if ( ch < 32 ) - { + } else if (ch < 32) { // in XML 1.0 only legal character are #x9 | #xA | #xD // and they must be escaped otherwise in attribute value they are normalized to spaces - if ( ch == 13 || ch == 10 || ch == 9 ) - { - if ( i > pos ) - out.write( value.substring( pos, i ) ); - out.write( "&#" ); - out.write( Integer.toString( ch ) ); - out.write( ';' ); + if (ch == 13 || ch == 10 || ch == 9) { + if (i > pos) out.write(value.substring(pos, i)); + out.write("&#"); + out.write(Integer.toString(ch)); + out.write(';'); pos = i + 1; - } - else - { - throw new IllegalStateException( "character " + Integer.toString( ch ) + " is not allowed in output" - + getLocation() ); + } else { + throw new IllegalStateException( + "character " + Integer.toString(ch) + " is not allowed in output" + getLocation()); // in XML 1.1 legal are [#x1-#xD7FF] // if(ch > 0) { // if(i > pos) out.write(text.substring(pos, i)); @@ -1143,65 +899,41 @@ else if ( ch < 32 ) } } } - if ( pos > 0 ) - { - out.write( value.substring( pos ) ); - } - else - { - out.write( value ); // this is shortcut to the most common case + if (pos > 0) { + out.write(value.substring(pos)); + } else { + out.write(value); // this is shortcut to the most common case } - } - protected void writeElementContent( String text, Writer out ) - throws IOException - { + protected void writeElementContent(String text, Writer out) throws IOException { // escape '<', '&', ']]>', <32 if necessary int pos = 0; - for ( int i = 0; i < text.length(); i++ ) - { + for (int i = 0; i < text.length(); i++) { // TODO: check if doing char[] text.getChars() would be faster than getCharAt(i) ... - char ch = text.charAt( i ); - if ( ch == ']' ) - { - if ( seenBracket ) - { + char ch = text.charAt(i); + if (ch == ']') { + if (seenBracket) { seenBracketBracket = true; - } - else - { + } else { seenBracket = true; } - } - else - { - if ( ch == '&' ) - { - if ( i > pos ) - out.write( text.substring( pos, i ) ); - out.write( "&" ); + } else { + if (ch == '&') { + if (i > pos) out.write(text.substring(pos, i)); + out.write("&"); pos = i + 1; - } - else if ( ch == '<' ) - { - if ( i > pos ) - out.write( text.substring( pos, i ) ); - out.write( "<" ); + } else if (ch == '<') { + if (i > pos) out.write(text.substring(pos, i)); + out.write("<"); pos = i + 1; - } - else if ( seenBracketBracket && ch == '>' ) - { - if ( i > pos ) - out.write( text.substring( pos, i ) ); - out.write( ">" ); + } else if (seenBracketBracket && ch == '>') { + if (i > pos) out.write(text.substring(pos, i)); + out.write(">"); pos = i + 1; - } - else if ( ch < 32 ) - { + } else if (ch < 32) { // in XML 1.0 only legal character are #x9 | #xA | #xD - if ( ch == 9 || ch == 10 || ch == 13 ) - { + if (ch == 9 || ch == 10 || ch == 13) { // pass through // } else if(ch == 13) { //escape @@ -1210,11 +942,9 @@ else if ( ch < 32 ) // out.write(Integer.toString(ch)); // out.write(';'); // pos = i + 1; - } - else - { - throw new IllegalStateException( "character " + Integer.toString( ch ) - + " is not allowed in output" + getLocation() ); + } else { + throw new IllegalStateException( + "character " + Integer.toString(ch) + " is not allowed in output" + getLocation()); // in XML 1.1 legal are [#x1-#xD7FF] // if(ch > 0) { // if(i > pos) out.write(text.substring(pos, i)); @@ -1228,79 +958,53 @@ else if ( ch < 32 ) // } } } - if ( seenBracket ) - { + if (seenBracket) { seenBracketBracket = seenBracket = false; } - } } - if ( pos > 0 ) - { - out.write( text.substring( pos ) ); - } - else - { - out.write( text ); // this is shortcut to the most common case + if (pos > 0) { + out.write(text.substring(pos)); + } else { + out.write(text); // this is shortcut to the most common case } - } - protected void writeElementContent( char[] buf, int off, int len, Writer out ) - throws IOException - { + protected void writeElementContent(char[] buf, int off, int len, Writer out) throws IOException { // escape '<', '&', ']]>' final int end = off + len; int pos = off; - for ( int i = off; i < end; i++ ) - { + for (int i = off; i < end; i++) { final char ch = buf[i]; - if ( ch == ']' ) - { - if ( seenBracket ) - { + if (ch == ']') { + if (seenBracket) { seenBracketBracket = true; - } - else - { + } else { seenBracket = true; } - } - else - { - if ( ch == '&' ) - { - if ( i > pos ) - { - out.write( buf, pos, i - pos ); + } else { + if (ch == '&') { + if (i > pos) { + out.write(buf, pos, i - pos); } - out.write( "&" ); + out.write("&"); pos = i + 1; - } - else if ( ch == '<' ) - { - if ( i > pos ) - { - out.write( buf, pos, i - pos ); + } else if (ch == '<') { + if (i > pos) { + out.write(buf, pos, i - pos); } - out.write( "<" ); + out.write("<"); pos = i + 1; - } - else if ( seenBracketBracket && ch == '>' ) - { - if ( i > pos ) - { - out.write( buf, pos, i - pos ); + } else if (seenBracketBracket && ch == '>') { + if (i > pos) { + out.write(buf, pos, i - pos); } - out.write( ">" ); + out.write(">"); pos = i + 1; - } - else if ( ch < 32 ) - { + } else if (ch < 32) { // in XML 1.0 only legal character are #x9 | #xA | #xD - if ( ch == 9 || ch == 10 || ch == 13 ) - { + if (ch == 9 || ch == 10 || ch == 13) { // pass through // } else if(ch == 13 ) { //if(ch == '\r') { @@ -1311,11 +1015,9 @@ else if ( ch < 32 ) // out.write(Integer.toString(ch)); // out.write(';'); // pos = i + 1; - } - else - { - throw new IllegalStateException( "character " + Integer.toString( ch ) - + " is not allowed in output" + getLocation() ); + } else { + throw new IllegalStateException( + "character " + Integer.toString(ch) + " is not allowed in output" + getLocation()); // in XML 1.1 legal are [#x1-#xD7FF] // if(ch > 0) { // if(i > pos) out.write(text.substring(pos, i)); @@ -1329,81 +1031,69 @@ else if ( ch < 32 ) // } } } - if ( seenBracket ) - { + if (seenBracket) { seenBracketBracket = seenBracket = false; } // assert seenBracketBracket == seenBracket == false; } } - if ( end > pos ) - { - out.write( buf, pos, end - pos ); + if (end > pos) { + out.write(buf, pos, end - pos); } } // simple utility method -- good for debugging - protected static final String printable( String s ) - { - if ( s == null ) - return "null"; - StringBuilder retval = new StringBuilder( s.length() + 16 ); - retval.append( "'" ); + protected static final String printable(String s) { + if (s == null) return "null"; + StringBuilder retval = new StringBuilder(s.length() + 16); + retval.append("'"); char ch; - for ( int i = 0; i < s.length(); i++ ) - { - addPrintable( retval, s.charAt( i ) ); + for (int i = 0; i < s.length(); i++) { + addPrintable(retval, s.charAt(i)); } - retval.append( "'" ); + retval.append("'"); return retval.toString(); } - protected static final String printable( char ch ) - { + protected static final String printable(char ch) { StringBuilder retval = new StringBuilder(); - addPrintable( retval, ch ); + addPrintable(retval, ch); return retval.toString(); } - private static void addPrintable( StringBuilder retval, char ch ) - { - switch ( ch ) - { + private static void addPrintable(StringBuilder retval, char ch) { + switch (ch) { case '\b': - retval.append( "\\b" ); + retval.append("\\b"); break; case '\t': - retval.append( "\\t" ); + retval.append("\\t"); break; case '\n': - retval.append( "\\n" ); + retval.append("\\n"); break; case '\f': - retval.append( "\\f" ); + retval.append("\\f"); break; case '\r': - retval.append( "\\r" ); + retval.append("\\r"); break; case '\"': - retval.append( "\\\"" ); + retval.append("\\\""); break; case '\'': - retval.append( "\\\'" ); + retval.append("\\\'"); break; case '\\': - retval.append( "\\\\" ); + retval.append("\\\\"); break; default: - if ( ch < 0x20 || ch > 0x7e ) - { - final String ss = "0000" + Integer.toString( ch, 16 ); - retval.append( "\\u" ).append( ss, ss.length() - 4, ss.length() ); - } - else - { - retval.append( ch ); + if (ch < 0x20 || ch > 0x7e) { + final String ss = "0000" + Integer.toString(ch, 16); + retval.append("\\u").append(ss, ss.length() - 4, ss.length()); + } else { + retval.append(ch); } } } - } 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 a5f06c14..1e574485 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 @@ -3,8 +3,8 @@ package org.codehaus.plexus.util.xml.pull; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.io.Reader; /** @@ -60,7 +60,7 @@ * and it was not declared in XMLDecl * * A minimal example for using this API may look as follows: - * + * *
      * import java.io.IOException;
      * import java.io.StringReader;
    @@ -100,14 +100,14 @@
      * 
    *

    * The above example will generate the following output: - * + * *

      * Start document
      * Start tag foo
      * Text Hello World!
      * End tag foo
      * 
    - * + * * For more details on API usage, please refer to the quick Introduction available at * http://www.xmlpull.org * @@ -128,9 +128,7 @@ * @author Stefan Haustein * @author Aleksander Slominski */ - -public interface XmlPullParser -{ +public interface XmlPullParser { /** This constant represents the default namespace (empty string "") */ String NO_NAMESPACE = ""; @@ -252,7 +250,7 @@ public interface XmlPullParser * An XML processing instruction declaration was just read. This event type is available only via * nextToken(). getText() will return text that is inside the processing instruction. * Calls to next() will skip processing instructions automatically. - * + * * @see #nextToken * @see #getText */ @@ -284,8 +282,19 @@ public interface XmlPullParser * only. Relying on the contents of the array may be dangerous since malicious applications may alter the array, * although it is final, due to limitations of the Java language. */ - String[] TYPES = { "START_DOCUMENT", "END_DOCUMENT", "START_TAG", "END_TAG", "TEXT", "CDSECT", "ENTITY_REF", - "IGNORABLE_WHITESPACE", "PROCESSING_INSTRUCTION", "COMMENT", "DOCDECL" }; + String[] TYPES = { + "START_DOCUMENT", + "END_DOCUMENT", + "START_TAG", + "END_TAG", + "TEXT", + "CDSECT", + "ENTITY_REF", + "IGNORABLE_WHITESPACE", + "PROCESSING_INSTRUCTION", + "COMMENT", + "DOCDECL" + }; // ---------------------------------------------------------------------------- // namespace related features @@ -348,8 +357,7 @@ public interface XmlPullParser * @exception XmlPullParserException If the feature is not supported or can not be set * @exception IllegalArgumentException If string with the feature name is null */ - void setFeature( String name, boolean state ) - throws XmlPullParserException; + void setFeature(String name, boolean state) throws XmlPullParserException; /** * Returns the current value of the given feature. @@ -360,7 +368,7 @@ void setFeature( String name, boolean state ) * @return The value of the feature. * @exception IllegalArgumentException if string the feature name is null */ - boolean getFeature( String name ); + boolean getFeature(String name); /** * Set the value of a property. The property name is any fully-qualified URI. @@ -370,8 +378,7 @@ void setFeature( String name, boolean state ) * @exception IllegalArgumentException If string with the property name is null * @throws XmlPullParserException parsing issue */ - void setProperty( String name, Object value ) - throws XmlPullParserException; + void setProperty(String name, Object value) throws XmlPullParserException; /** * Look up the value of a property. The property name is any fully-qualified URI. @@ -381,7 +388,7 @@ void setProperty( String name, Object value ) * @param name The name of property to be retrieved. * @return The value of named property. */ - Object getProperty( String name ); + Object getProperty(String name); /** * Set the input source for parser to the given reader and resets the parser. The event type is set to the initial @@ -390,8 +397,7 @@ void setProperty( String name, Object value ) * @param in the Reader * @throws XmlPullParserException parsing issue */ - void setInput( Reader in ) - throws XmlPullParserException; + void setInput(Reader in) throws XmlPullParserException; /** * Sets the input stream the parser is going to process. This call resets the parser state and sets the event type @@ -407,8 +413,7 @@ void setInput( Reader in ) * @param inputEncoding if not null it MUST be used as encoding for inputStream * @throws XmlPullParserException parsing issue */ - void setInput( InputStream inputStream, String inputEncoding ) - throws XmlPullParserException; + void setInput(InputStream inputStream, String inputEncoding) throws XmlPullParserException; /** * @return the input encoding if known, null otherwise. If setInput(InputStream, inputEncoding) was called with an @@ -448,8 +453,7 @@ void setInput( InputStream inputStream, String inputEncoding ) * @see #FEATURE_VALIDATION * @throws XmlPullParserException parsing issue */ - void defineEntityReplacementText( String entityName, String replacementText ) - throws XmlPullParserException; + void defineEntityReplacementText(String entityName, String replacementText) throws XmlPullParserException; /** * @return the numbers of elements in the namespace stack for the given depth. If namespaces are not enabled, 0 is @@ -459,7 +463,7 @@ void defineEntityReplacementText( String entityName, String replacementText ) * retrieve position of namespace prefixes and URIs that were declared on corresponding START_TAG. *

    * NOTE: to retrieve lsit of namespaces declared in current element: - * + * *

          *       XmlPullParser pp = ...
          *       int nsStart = pp.getNamespaceCount(pp.getDepth()-1);
    @@ -478,8 +482,7 @@ void defineEntityReplacementText( String entityName, String replacementText )
          * @param depth depth
          * @throws XmlPullParserException parsing issue
          */
    -    int getNamespaceCount( int depth )
    -        throws XmlPullParserException;
    +    int getNamespaceCount(int depth) throws XmlPullParserException;
     
         /**
          * @return Returns the namespace prefix for the given position in the namespace stack. Default namespace declaration
    @@ -491,8 +494,7 @@ int getNamespaceCount( int depth )
          * @param pos namespace stack position
          * @throws XmlPullParserException parsing issue
          */
    -    String getNamespacePrefix( int pos )
    -        throws XmlPullParserException;
    +    String getNamespacePrefix(int pos) throws XmlPullParserException;
     
         /**
          * @return Returns the namespace URI for the given position in the namespace stack If the position is out of range, an
    @@ -503,8 +505,7 @@ String getNamespacePrefix( int pos )
          * @throws XmlPullParserException parsing issue
          * @param pos namespace stack position
          */
    -    String getNamespaceUri( int pos )
    -        throws XmlPullParserException;
    +    String getNamespaceUri(int pos) throws XmlPullParserException;
     
         /**
          * @return the URI corresponding to the given prefix, depending on current state of the parser.
    @@ -534,7 +535,7 @@ String getNamespaceUri( int pos )
          * @see #getNamespacePrefix
          * @see #getNamespaceUri
          */
    -    String getNamespace( String prefix );
    +    String getNamespace(String prefix);
     
         // --------------------------------------------------------------------------
         // miscellaneous reporting methods
    @@ -591,8 +592,7 @@ String getNamespaceUri( int pos )
          * exposed via nextToken only.
          * @throws XmlPullParserException parsing issue
          */
    -    boolean isWhitespace()
    -        throws XmlPullParserException;
    +    boolean isWhitespace() throws XmlPullParserException;
     
         /**
          * @return  the text content of the current event as String. The value returned depends on current event type, for
    @@ -626,7 +626,7 @@ boolean isWhitespace()
          * @return char buffer that contains the text of the current event (null if the current event has no text
          *         associated).
          */
    -    char[] getTextCharacters( int[] holderForStartAndLength );
    +    char[] getTextCharacters(int[] holderForStartAndLength);
     
         // --------------------------------------------------------------------------
         // START_TAG / END_TAG shared methods
    @@ -660,8 +660,7 @@ boolean isWhitespace()
          * NOTE: if the parser is not on START_TAG, an exception will be thrown.
          * @throws XmlPullParserException parsing issue
          */
    -    boolean isEmptyElementTag()
    -        throws XmlPullParserException;
    +    boolean isEmptyElementTag() throws XmlPullParserException;
     
         // --------------------------------------------------------------------------
         // START_TAG Attributes retrieval methods
    @@ -693,7 +692,7 @@ boolean isEmptyElementTag()
          * @return attribute namespace, empty string ("") is returned if namespaces processing is not enabled or namespaces
          *         processing is enabled but attribute has no namespace (it has no prefix).
          */
    -    String getAttributeNamespace( int index );
    +    String getAttributeNamespace(int index);
     
         /**
          * Returns the local name of the specified attribute if namespaces are enabled or just attribute name if namespaces
    @@ -703,7 +702,7 @@ boolean isEmptyElementTag()
          * @param index zero based index of attribute
          * @return attribute name (null is never returned)
          */
    -    String getAttributeName( int index );
    +    String getAttributeName(int index);
     
         /**
          * Returns the prefix of the specified attribute Returns null if the element has no prefix. If namespaces are
    @@ -713,7 +712,7 @@ boolean isEmptyElementTag()
          * @param index zero based index of attribute
          * @return attribute prefix or null if namespaces processing is not enabled.
          */
    -    String getAttributePrefix( int index );
    +    String getAttributePrefix(int index);
     
         /**
          * Returns the type of the specified attribute If parser is non-validating it MUST return CDATA.
    @@ -721,7 +720,7 @@ boolean isEmptyElementTag()
          * @param index zero based index of attribute
          * @return attribute type (null is never returned)
          */
    -    String getAttributeType( int index );
    +    String getAttributeType(int index);
     
         /**
          * Returns if the specified attribute was not in input was declared in XML. If parser is non-validating it MUST
    @@ -730,7 +729,7 @@ boolean isEmptyElementTag()
          * @param index zero based index of attribute
          * @return false if attribute was in input
          */
    -    boolean isAttributeDefault( int index );
    +    boolean isAttributeDefault(int index);
     
         /**
          * Returns the given attributes value. Throws an IndexOutOfBoundsException if the index is out of range or current
    @@ -744,7 +743,7 @@ boolean isEmptyElementTag()
          * @param index zero based index of attribute
          * @return value of attribute (null is never returned)
          */
    -    String getAttributeValue( int index );
    +    String getAttributeValue(int index);
     
         /**
          * Returns the attributes value identified by namespace URI and namespace localName. If namespaces are disabled
    @@ -759,7 +758,7 @@ boolean isEmptyElementTag()
          * @param name If namespaces enabled local name of attribute otherwise just attribute name
          * @return value of attribute or null if attribute with given name does not exist
          */
    -    String getAttributeValue( String namespace, String name );
    +    String getAttributeValue(String namespace, String name);
     
         // --------------------------------------------------------------------------
         // actual parsing methods
    @@ -771,8 +770,7 @@ boolean isEmptyElementTag()
          * @see #nextToken()
          * @throws XmlPullParserException parsing issue
          */
    -    int getEventType()
    -        throws XmlPullParserException;
    +    int getEventType() throws XmlPullParserException;
     
         /**
          * @return Get next parsing event - element content wil be coalesced and only one TEXT event must be returned for whole
    @@ -791,8 +789,7 @@ int getEventType()
          * @throws XmlPullParserException parsing issue
          * @throws IOException io issue
          */
    -    int next()
    -        throws XmlPullParserException, IOException;
    +    int next() throws XmlPullParserException, IOException;
     
         /**
          * This method works similarly to next() but will expose additional event types (COMMENT, CDSECT, DOCDECL,
    @@ -846,19 +843,19 @@ int next()
          * 
    DOCDECL *
    if FEATURE_XML_ROUNDTRIP is true or PROCESS_DOCDECL is false then return what is inside of DOCDECL for * example it returns: - * + * *
          * " titlepage SYSTEM "http://www.foo.bar/dtds/typo.dtd"
          * [<!ENTITY % active.links "INCLUDE">]"
          * 
    *

    * for input document that contained: - * + * *

          * <!DOCTYPE titlepage SYSTEM "http://www.foo.bar/dtds/typo.dtd"
          * [<!ENTITY % active.links "INCLUDE">]>
          * 
    - * + * * otherwise if FEATURE_XML_ROUNDTRIP is false and PROCESS_DOCDECL is true then what is returned is undefined (it * may be even null)
    * @@ -885,8 +882,7 @@ int next() * @see #ENTITY_REF * @see #IGNORABLE_WHITESPACE */ - int nextToken() - throws XmlPullParserException, IOException; + int nextToken() throws XmlPullParserException, IOException; // ----------------------------------------------------------------------------- // utility methods to mak XML parsing easier ... @@ -897,7 +893,7 @@ int nextToken() * parser position, the expected event and the current event that is not meeting the requirement. *

    * Essentially it does this - * + * *

          * if ( type != getEventType() || ( namespace != null && !namespace.equals( getNamespace() ) )
          *     || ( name != null && !name.equals( getName() ) ) )
    @@ -909,8 +905,7 @@ int nextToken()
          * @throws XmlPullParserException parsing issue
          * @throws IOException io issue
          */
    -    void require( int type, String namespace, String name )
    -        throws XmlPullParserException, IOException;
    +    void require(int type, String namespace, String name) throws XmlPullParserException, IOException;
     
         /**
          * If current event is START_TAG then if next element is TEXT then element content is returned or if next event is
    @@ -922,18 +917,18 @@ void require( int type, String namespace, String name )
          * 
      *
    1. <tag>foo</tag> *
    2. <tag></tag> (which is equivalent to <tag/> both input can be parsed with the same code: - * + * *
            *   p.nextTag()
            *   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. *

    * Essentially it does this - * + * *

          * if ( getEventType() != START_TAG )
          * {
    @@ -963,15 +958,14 @@ void require( int type, String namespace, String name )
          * @throws XmlPullParserException parsing issue
          * @throws IOException io issue
          */
    -    String nextText()
    -        throws XmlPullParserException, IOException;
    +    String nextText() throws XmlPullParserException, IOException;
     
         /**
          * Call next() and return event if it is START_TAG or END_TAG otherwise throw an exception. It will skip whitespace
          * TEXT before actual tag if any.
          * 

    * essentially it does this - * + * *

          * int eventType = next();
          * if ( eventType == TEXT && isWhitespace() )
    @@ -989,7 +983,5 @@ String nextText()
          * @throws
          * IOException io issue
          */
    -    int nextTag()
    -        throws XmlPullParserException, IOException;
    -
    +    int nextTag() throws XmlPullParserException, IOException;
     }
    diff --git a/src/main/java/org/codehaus/plexus/util/xml/pull/XmlPullParserException.java b/src/main/java/org/codehaus/plexus/util/xml/pull/XmlPullParserException.java
    index ff23754f..198977c5 100644
    --- a/src/main/java/org/codehaus/plexus/util/xml/pull/XmlPullParserException.java
    +++ b/src/main/java/org/codehaus/plexus/util/xml/pull/XmlPullParserException.java
    @@ -8,9 +8,7 @@
      *
      * @author Aleksander Slominski
      */
    -public class XmlPullParserException
    -    extends Exception
    -{
    +public class XmlPullParserException extends Exception {
         /**
          * @deprecated use generic getCause() method
          */
    @@ -25,9 +23,8 @@ public class XmlPullParserException
          * public XmlPullParserException() { }
          */
     
    -    public XmlPullParserException( String s )
    -    {
    -        super( s );
    +    public XmlPullParserException(String s) {
    +        super(s);
         }
     
         /*
    @@ -35,14 +32,14 @@ public XmlPullParserException( String s )
          * XmlPullParserException(String s, int row, int column) { super(s); this.row = row; this.column = column; }
          */
     
    -    public XmlPullParserException( String msg, XmlPullParser parser, Throwable chain )
    -    {
    -        super( ( msg == null ? "" : msg + " " )
    -            + ( parser == null ? "" : "(position:" + parser.getPositionDescription() + ") " )
    -            + ( chain == null ? "" : "caused by: " + chain ), chain );
    +    public XmlPullParserException(String msg, XmlPullParser parser, Throwable chain) {
    +        super(
    +                (msg == null ? "" : msg + " ")
    +                        + (parser == null ? "" : "(position:" + parser.getPositionDescription() + ") ")
    +                        + (chain == null ? "" : "caused by: " + chain),
    +                chain);
     
    -        if ( parser != null )
    -        {
    +        if (parser != null) {
                 this.row = parser.getLineNumber();
                 this.column = parser.getColumnNumber();
             }
    @@ -54,19 +51,16 @@ public XmlPullParserException( String msg, XmlPullParser parser, Throwable chain
          * @return the cause
          */
         @Deprecated
    -    public Throwable getDetail()
    -    {
    +    public Throwable getDetail() {
             return getCause();
         }
     
         // public void setDetail(Throwable cause) { this.detail = cause; }
    -    public int getLineNumber()
    -    {
    +    public int getLineNumber() {
             return row;
         }
     
    -    public int getColumnNumber()
    -    {
    +    public int getColumnNumber() {
             return column;
         }
     
    @@ -77,20 +71,14 @@ public int getColumnNumber()
     
         // NOTE: code that prints this and detail is difficult in J2ME
         @Override
    -    public void printStackTrace()
    -    {
    -        if ( getCause() == null )
    -        {
    +    public void printStackTrace() {
    +        if (getCause() == null) {
                 super.printStackTrace();
    -        }
    -        else
    -        {
    -            synchronized ( System.err )
    -            {
    -                System.err.println( super.getMessage() + "; nested exception is:" );
    +        } else {
    +            synchronized (System.err) {
    +                System.err.println(super.getMessage() + "; nested exception is:");
                     getCause().printStackTrace();
                 }
             }
         }
    -
     }
    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 46ef492f..6d5ec139 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
    @@ -28,9 +28,7 @@
      * be thrown and it is recommended to use an optional feature to signal that implementation is not supporting this kind
      * of output.
      */
    -
    -public interface XmlSerializer
    -{
    +public interface XmlSerializer {
     
         /**
          * Set feature identified by name (recommended to be URI for uniqueness). Some well known optional features are
    @@ -41,8 +39,7 @@ public interface XmlSerializer
          * @param state feature state
          * @exception IllegalStateException If the feature is not supported or can not be set
          */
    -    void setFeature( String name, boolean state )
    -        throws IllegalArgumentException, IllegalStateException;
    +    void setFeature(String name, boolean state) throws IllegalArgumentException, IllegalStateException;
     
         /**
          * Return the current value of the feature with given name.
    @@ -53,7 +50,7 @@ void setFeature( String name, boolean state )
          * @return The value of named feature.
          * @exception IllegalArgumentException if feature string is null
          */
    -    boolean getFeature( String name );
    +    boolean getFeature(String name);
     
         /**
          * Set the value of a property. (the property name is recommended to be URI for uniqueness). Some well known
    @@ -64,8 +61,7 @@ void setFeature( String name, boolean state )
          * @param value property value
          * @exception IllegalStateException if the property is not supported or can not be set
          */
    -    void setProperty( String name, Object value )
    -        throws IllegalArgumentException, IllegalStateException;
    +    void setProperty(String name, Object value) throws IllegalArgumentException, IllegalStateException;
     
         /**
          * Look up the value of a property. The property name is any fully-qualified URI. I
    @@ -75,7 +71,7 @@ void setProperty( String name, Object value )
          * @param name The name of property to be retrieved.
          * @return The value of named property.
          */
    -    Object getProperty( String name );
    +    Object getProperty(String name);
     
         /**
          * Set to use binary output stream with given encoding.
    @@ -85,8 +81,8 @@ void setProperty( String name, Object value )
          * @throws IllegalArgumentException if null
          * @throws IllegalStateException illegal use
          */
    -    void setOutput( OutputStream os, String encoding )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    void setOutput(OutputStream os, String encoding)
    +            throws IOException, IllegalArgumentException, IllegalStateException;
     
         /**
          * @param writer Set the output to the given writer.
    @@ -96,8 +92,7 @@ void setOutput( OutputStream os, String encoding )
          * @throws IllegalArgumentException if null
          * @throws IllegalStateException illegal use
          */
    -    void setOutput( Writer writer )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    void setOutput(Writer writer) throws IOException, IllegalArgumentException, IllegalStateException;
     
         /**
          * Write <?xml declaration with encoding (if encoding not null) and standalone flag (if standalone not null)
    @@ -108,8 +103,8 @@ void setOutput( Writer writer )
          * @throws IllegalArgumentException if null
          * @throws IllegalStateException illegal use
          */
    -    void startDocument( String encoding, Boolean standalone )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    void startDocument(String encoding, Boolean standalone)
    +            throws IOException, IllegalArgumentException, IllegalStateException;
     
         /**
          * Finish writing. All unclosed start tags will be closed and output will be flushed. After calling this method no
    @@ -118,8 +113,7 @@ void startDocument( String encoding, Boolean standalone )
          * @throws IllegalArgumentException if null
          * @throws IllegalStateException illegal use
          */
    -    void endDocument()
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    void endDocument() throws IOException, IllegalArgumentException, IllegalStateException;
     
         /**
          * Binds the given prefix to the given namespace. This call is valid for the next element including child elements.
    @@ -141,8 +135,7 @@ void endDocument()
          * @throws IllegalArgumentException if null
          * @throws IllegalStateException illegal use
          */
    -    void setPrefix( String prefix, String namespace )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    void setPrefix(String prefix, String namespace) throws IOException, IllegalArgumentException, IllegalStateException;
     
         /**
          * @return namespace that corresponds to given prefix If there is no prefix bound to this namespace return null but
    @@ -157,8 +150,7 @@ void setPrefix( String prefix, String namespace )
          * @param generatePrefix to generate the missing prefix
          * @throws IllegalArgumentException if null
          */
    -    String getPrefix( String namespace, boolean generatePrefix )
    -        throws IllegalArgumentException;
    +    String getPrefix(String namespace, boolean generatePrefix) throws IllegalArgumentException;
     
         /**
          * @return the current depth of the element. Outside the root element, the depth is 0. The depth is incremented by 1
    @@ -210,8 +202,8 @@ String getPrefix( String namespace, boolean generatePrefix )
          * @throws IllegalArgumentException if null
          * @throws IllegalStateException illegal use
          */
    -    XmlSerializer startTag( String namespace, String name )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    XmlSerializer startTag(String namespace, String name)
    +            throws IOException, IllegalArgumentException, IllegalStateException;
     
         /**
          * Write an attribute. Calls to attribute() MUST follow a call to startTag() immediately. If there is no prefix
    @@ -225,8 +217,8 @@ XmlSerializer startTag( String namespace, String name )
          * @throws IllegalArgumentException if null
          * @throws IllegalStateException illegal use
          */
    -    XmlSerializer attribute( String namespace, String name, String value )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    XmlSerializer attribute(String namespace, String name, String value)
    +            throws IOException, IllegalArgumentException, IllegalStateException;
     
         /**
          * Write end tag. Repetition of namespace and name is just for avoiding errors.
    @@ -240,8 +232,8 @@ XmlSerializer attribute( String namespace, String name, String value )
          * @throws IllegalArgumentException if null
          * @throws IllegalStateException illegal use
          */
    -    XmlSerializer endTag( String namespace, String name )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    XmlSerializer endTag(String namespace, String name)
    +            throws IOException, IllegalArgumentException, IllegalStateException;
     
         // /**
         // * Writes a start tag with the given namespace and name.
    @@ -303,8 +295,7 @@ XmlSerializer endTag( String namespace, String name )
          * @throws IllegalArgumentException if null
          * @throws IllegalStateException illegal use
          */
    -    XmlSerializer text( String text )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    XmlSerializer text(String text) throws IOException, IllegalArgumentException, IllegalStateException;
     
         /**
          * Writes text, where special XML chars are escaped automatically
    @@ -316,26 +307,20 @@ XmlSerializer text( String text )
          * @throws IllegalArgumentException if null
          * @throws IllegalStateException illegal use
          */
    -    XmlSerializer text( char[] buf, int start, int len )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    XmlSerializer text(char[] buf, int start, int len)
    +            throws IOException, IllegalArgumentException, IllegalStateException;
     
    -    void cdsect( String text )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    void cdsect(String text) throws IOException, IllegalArgumentException, IllegalStateException;
     
    -    void entityRef( String text )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    void entityRef(String text) throws IOException, IllegalArgumentException, IllegalStateException;
     
    -    void processingInstruction( String text )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    void processingInstruction(String text) throws IOException, IllegalArgumentException, IllegalStateException;
     
    -    void comment( String text )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    void comment(String text) throws IOException, IllegalArgumentException, IllegalStateException;
     
    -    void docdecl( String text )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    void docdecl(String text) throws IOException, IllegalArgumentException, IllegalStateException;
     
    -    void ignorableWhitespace( String text )
    -        throws IOException, IllegalArgumentException, IllegalStateException;
    +    void ignorableWhitespace(String text) throws IOException, IllegalArgumentException, IllegalStateException;
     
         /**
          * Write all pending output to the stream. If method startTag() or attribute() was called then start tag is closed
    @@ -345,7 +330,5 @@ void ignorableWhitespace( String text )
          * output call method text() with empty string (text("")).
          * @throws IOException io
          */
    -    void flush()
    -        throws IOException;
    -
    +    void flush() throws IOException;
     }
    diff --git a/src/test/java/org/codehaus/plexus/util/AbstractTestThread.java b/src/test/java/org/codehaus/plexus/util/AbstractTestThread.java
    index ca5ba4ed..1a67c001 100644
    --- a/src/test/java/org/codehaus/plexus/util/AbstractTestThread.java
    +++ b/src/test/java/org/codehaus/plexus/util/AbstractTestThread.java
    @@ -27,9 +27,7 @@
      * @version $Id: $Id
      * @since 3.4.0
      */
    -public abstract class AbstractTestThread
    -    implements Runnable
    -{
    +public abstract class AbstractTestThread implements Runnable {
         // ~ Instance fields ----------------------------------------------------------------------------
         private String name;
     
    @@ -65,8 +63,7 @@ public abstract class AbstractTestThread
          * 

    * Remember to call setThreadRegistry(ThreadRegistry) */ - public AbstractTestThread() - { + public AbstractTestThread() { super(); } @@ -75,10 +72,9 @@ public AbstractTestThread() * * @param registry a {@link org.codehaus.plexus.util.TestThreadManager} object. */ - public AbstractTestThread( TestThreadManager registry ) - { + public AbstractTestThread(TestThreadManager registry) { super(); - setThreadRegistry( registry ); + setThreadRegistry(registry); } // ~ Methods ------------------------------------------------------------------------------------ @@ -88,8 +84,7 @@ public AbstractTestThread( TestThreadManager registry ) * * @return a {@link java.lang.Throwable} object. */ - public Throwable getError() - { + public Throwable getError() { return error; } @@ -97,19 +92,13 @@ public Throwable getError() * Resets the test back to it's state before starting. If the test is currently running this method will block until * the test has finished running. Subclasses should call this method if overriding it. */ - public void reset() - { + public void reset() { // shouldn't reset until the test has finished running - synchronized ( this ) - { - while ( isRunning ) - { - try - { + synchronized (this) { + while (isRunning) { + try { wait(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { } } @@ -123,15 +112,12 @@ public void reset() /** * Start this TestThread running. If the test is currently running then this method does nothing. */ - public final void start() - { + public final void start() { // shouldn't have multiple threads running this test at the same time - synchronized ( this ) - { - if ( isRunning == false ) - { + synchronized (this) { + if (isRunning == false) { isRunning = true; - Thread t = new Thread( this ); + Thread t = new Thread(this); t.start(); } } @@ -142,8 +128,7 @@ public final void start() * * @return a {@link java.lang.String} object. */ - public String getErrorMsg() - { + public String getErrorMsg() { return errorMsg; } @@ -152,8 +137,7 @@ public String getErrorMsg() * * @return a boolean. */ - public boolean hasFailed() - { + public boolean hasFailed() { return !passed; } @@ -162,8 +146,7 @@ public boolean hasFailed() * * @return DOCUMENT ME! */ - public boolean hasPassed() - { + public boolean hasPassed() { return passed; } @@ -172,29 +155,24 @@ public boolean hasPassed() * * @see java.lang.Runnable#run() */ - public final void run() - { - if ( registry == null ) - { - throw new IllegalArgumentException( "The ThreadRegistry is null. Ensure this is set before running this thread" ); + public final void run() { + if (registry == null) { + throw new IllegalArgumentException( + "The ThreadRegistry is null. Ensure this is set before running this thread"); } passed = false; - try - { + try { doRun(); - } - catch ( Throwable t ) - { + } catch (Throwable t) { error = t; } - registry.completed( this ); + registry.completed(this); hasRun = true; isRunning = false; // notify objects with blocked methods which are waiting // on this test to complete running - synchronized ( this ) - { + synchronized (this) { notifyAll(); } } @@ -204,17 +182,15 @@ public final void run() * * @throws java.lang.Throwable */ - public abstract void doRun() - throws Throwable; + public abstract void doRun() throws Throwable; /** * Set the registry this thread should notify when it has completed running * * @param registry a {@link org.codehaus.plexus.util.TestThreadManager} object. */ - public void setThreadRegistry( TestThreadManager registry ) + public void setThreadRegistry(TestThreadManager registry) { - { this.registry = registry; } @@ -223,8 +199,7 @@ public void setThreadRegistry( TestThreadManager registry ) * * @return a boolean. */ - public boolean hasRun() - { + public boolean hasRun() { return hasRun; } @@ -233,8 +208,7 @@ public boolean hasRun() * * @param throwable a {@link java.lang.Throwable} object. */ - public void setError( Throwable throwable ) - { + public void setError(Throwable throwable) { error = throwable; } @@ -243,8 +217,7 @@ public void setError( Throwable throwable ) * * @param string a {@link java.lang.String} object. */ - public void setErrorMsg( String string ) - { + public void setErrorMsg(String string) { errorMsg = string; } @@ -253,8 +226,7 @@ public void setErrorMsg( String string ) * * @param b a boolean. */ - public void setPassed( boolean b ) - { + public void setPassed(boolean b) { passed = b; } @@ -263,8 +235,7 @@ public void setPassed( boolean b ) * * @return a {@link java.lang.String} object. */ - public String getName() - { + public String getName() { return name; } @@ -273,16 +244,13 @@ public String getName() * * @param string a {@link java.lang.String} object. */ - public void setName( String string ) - { + public void setName(String string) { name = string; } - private final void debug( String msg ) - { - if ( DEBUG ) - { - System.out.println( this + ":" + msg ); + private final void debug(String msg) { + if (DEBUG) { + System.out.println(this + ":" + msg); } } } diff --git a/src/test/java/org/codehaus/plexus/util/CollectionUtilsTest.java b/src/test/java/org/codehaus/plexus/util/CollectionUtilsTest.java index 70add088..12a4e25d 100644 --- a/src/test/java/org/codehaus/plexus/util/CollectionUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/CollectionUtilsTest.java @@ -16,10 +16,6 @@ * 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; @@ -28,6 +24,10 @@ import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + /** *

    CollectionUtilsTest class.

    * @@ -35,109 +35,105 @@ * @version $Id: $Id * @since 3.4.0 */ -public class CollectionUtilsTest -{ +public class CollectionUtilsTest { /** *

    testMergeMaps.

    */ @Test - public void testMergeMaps() - { + public void testMergeMaps() { Map dominantMap = new HashMap(); - dominantMap.put( "a", "a" ); - dominantMap.put( "b", "b" ); - dominantMap.put( "c", "c" ); - dominantMap.put( "d", "d" ); - dominantMap.put( "e", "e" ); - dominantMap.put( "f", "f" ); + dominantMap.put("a", "a"); + dominantMap.put("b", "b"); + dominantMap.put("c", "c"); + dominantMap.put("d", "d"); + dominantMap.put("e", "e"); + dominantMap.put("f", "f"); Map recessiveMap = new HashMap(); - recessiveMap.put( "a", "invalid" ); - recessiveMap.put( "b", "invalid" ); - recessiveMap.put( "c", "invalid" ); - recessiveMap.put( "x", "x" ); - recessiveMap.put( "y", "y" ); - recessiveMap.put( "z", "z" ); + recessiveMap.put("a", "invalid"); + recessiveMap.put("b", "invalid"); + recessiveMap.put("c", "invalid"); + recessiveMap.put("x", "x"); + recessiveMap.put("y", "y"); + recessiveMap.put("z", "z"); - Map result = CollectionUtils.mergeMaps( dominantMap, recessiveMap ); + Map result = CollectionUtils.mergeMaps(dominantMap, recessiveMap); // We should have 9 elements - assertEquals( 9, result.keySet().size() ); + assertEquals(9, result.keySet().size()); // Check the elements. - assertEquals( "a", result.get( "a" ) ); - assertEquals( "b", result.get( "b" ) ); - assertEquals( "c", result.get( "c" ) ); - assertEquals( "d", result.get( "d" ) ); - assertEquals( "e", result.get( "e" ) ); - assertEquals( "f", result.get( "f" ) ); - assertEquals( "x", result.get( "x" ) ); - assertEquals( "y", result.get( "y" ) ); - assertEquals( "z", result.get( "z" ) ); + assertEquals("a", result.get("a")); + assertEquals("b", result.get("b")); + assertEquals("c", result.get("c")); + assertEquals("d", result.get("d")); + assertEquals("e", result.get("e")); + assertEquals("f", result.get("f")); + assertEquals("x", result.get("x")); + assertEquals("y", result.get("y")); + assertEquals("z", result.get("z")); } /** *

    testMergeMapArray.

    */ - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") @Test - public void testMergeMapArray() - { + public void testMergeMapArray() { // Test empty array of Maps - Map result0 = CollectionUtils.mergeMaps( new Map[] {} ); + Map result0 = CollectionUtils.mergeMaps(new Map[] {}); - assertNull( result0 ); + assertNull(result0); // Test with an array with a single element. Map map1 = new HashMap(); - map1.put( "a", "a" ); + map1.put("a", "a"); - Map result1 = CollectionUtils.mergeMaps( new Map[] { map1 } ); + Map result1 = CollectionUtils.mergeMaps(new Map[] {map1}); - assertEquals( "a", result1.get( "a" ) ); + assertEquals("a", result1.get("a")); // Test with an array with two elements. Map map2 = new HashMap(); - map2.put( "a", "aa" ); - map2.put( "b", "bb" ); + map2.put("a", "aa"); + map2.put("b", "bb"); - Map result2 = CollectionUtils.mergeMaps( new Map[] { map1, map2 } ); + Map result2 = CollectionUtils.mergeMaps(new Map[] {map1, map2}); - assertEquals( "a", result2.get( "a" ) ); - assertEquals( "bb", result2.get( "b" ) ); + assertEquals("a", result2.get("a")); + assertEquals("bb", result2.get("b")); // Now swap the dominant order. - Map result3 = CollectionUtils.mergeMaps( new Map[] { map2, map1 } ); + Map result3 = CollectionUtils.mergeMaps(new Map[] {map2, map1}); - assertEquals( "aa", result3.get( "a" ) ); - assertEquals( "bb", result3.get( "b" ) ); + assertEquals("aa", result3.get("a")); + assertEquals("bb", result3.get("b")); // Test with an array with three elements. Map map3 = new HashMap(); - map3.put( "a", "aaa" ); - map3.put( "b", "bbb" ); - map3.put( "c", "ccc" ); + map3.put("a", "aaa"); + map3.put("b", "bbb"); + map3.put("c", "ccc"); - Map result4 = CollectionUtils.mergeMaps( new Map[] { map1, map2, map3 } ); + Map result4 = CollectionUtils.mergeMaps(new Map[] {map1, map2, map3}); - assertEquals( "a", result4.get( "a" ) ); - assertEquals( "bb", result4.get( "b" ) ); - assertEquals( "ccc", result4.get( "c" ) ); + assertEquals("a", result4.get("a")); + assertEquals("bb", result4.get("b")); + assertEquals("ccc", result4.get("c")); // Now swap the dominant order. - Map result5 = CollectionUtils.mergeMaps( new Map[] { map3, map2, map1 } ); + Map result5 = CollectionUtils.mergeMaps(new Map[] {map3, map2, map1}); - assertEquals( "aaa", result5.get( "a" ) ); - assertEquals( "bbb", result5.get( "b" ) ); - assertEquals( "ccc", result5.get( "c" ) ); + assertEquals("aaa", result5.get("a")); + assertEquals("bbb", result5.get("b")); + assertEquals("ccc", result5.get("c")); } /** *

    testMavenPropertiesLoading.

    */ @Test - public void testMavenPropertiesLoading() - { + public void testMavenPropertiesLoading() { // Mimic MavenSession properties loading. Properties listed // in dominant order. Properties systemProperties = new Properties(); @@ -147,86 +143,85 @@ public void testMavenPropertiesLoading() Properties driverProperties = new Properties(); // System properties - systemProperties.setProperty( "maven.home", "/projects/maven" ); + systemProperties.setProperty("maven.home", "/projects/maven"); // User build properties - userBuildProperties.setProperty( "maven.username", "jvanzyl" ); - userBuildProperties.setProperty( "maven.repo.remote.enabled", "false" ); - userBuildProperties.setProperty( "maven.repo.local", "/opt/maven/artifact" ); + userBuildProperties.setProperty("maven.username", "jvanzyl"); + userBuildProperties.setProperty("maven.repo.remote.enabled", "false"); + userBuildProperties.setProperty("maven.repo.local", "/opt/maven/artifact"); // Project build properties - projectBuildProperties.setProperty( "maven.final.name", "maven" ); + projectBuildProperties.setProperty("maven.final.name", "maven"); String mavenRepoRemote = "http://www.ibiblio.org/maven,http://foo/bar"; // Project properties - projectProperties.setProperty( "maven.repo.remote", mavenRepoRemote ); + projectProperties.setProperty("maven.repo.remote", mavenRepoRemote); String basedir = "/home/jvanzyl/projects/maven"; // Driver properties - driverProperties.setProperty( "basedir", basedir ); - driverProperties.setProperty( "maven.build.src", "${basedir}/src" ); - driverProperties.setProperty( "maven.build.dir", "${basedir}/target" ); - driverProperties.setProperty( "maven.build.dest", "${maven.build.dir}/classes" ); - driverProperties.setProperty( "maven.repo.remote", "http://www.ibiblio.org/maven" ); - driverProperties.setProperty( "maven.final.name", "maven-1.0" ); - driverProperties.setProperty( "maven.repo.remote.enabled", "true" ); - driverProperties.setProperty( "maven.repo.local", "${maven.home}/artifact" ); - - Map result = CollectionUtils.mergeMaps( new Map[] { systemProperties, userBuildProperties, - projectBuildProperties, projectProperties, driverProperties } ); + driverProperties.setProperty("basedir", basedir); + driverProperties.setProperty("maven.build.src", "${basedir}/src"); + driverProperties.setProperty("maven.build.dir", "${basedir}/target"); + driverProperties.setProperty("maven.build.dest", "${maven.build.dir}/classes"); + driverProperties.setProperty("maven.repo.remote", "http://www.ibiblio.org/maven"); + driverProperties.setProperty("maven.final.name", "maven-1.0"); + driverProperties.setProperty("maven.repo.remote.enabled", "true"); + driverProperties.setProperty("maven.repo.local", "${maven.home}/artifact"); + + Map result = CollectionUtils.mergeMaps(new Map[] { + systemProperties, userBuildProperties, projectBuildProperties, projectProperties, driverProperties + }); // Values that should be taken from systemProperties. - assertEquals( "/projects/maven", (String) result.get( "maven.home" ) ); + assertEquals("/projects/maven", (String) result.get("maven.home")); // Values that should be taken from userBuildProperties. - assertEquals( "/opt/maven/artifact", (String) result.get( "maven.repo.local" ) ); - assertEquals( "false", (String) result.get( "maven.repo.remote.enabled" ) ); - assertEquals( "jvanzyl", (String) result.get( "maven.username" ) ); + assertEquals("/opt/maven/artifact", (String) result.get("maven.repo.local")); + assertEquals("false", (String) result.get("maven.repo.remote.enabled")); + assertEquals("jvanzyl", (String) result.get("maven.username")); // Values take from projectBuildProperties. - assertEquals( "maven", (String) result.get( "maven.final.name" ) ); + assertEquals("maven", (String) result.get("maven.final.name")); // Values take from projectProperties. - assertEquals( mavenRepoRemote, (String) result.get( "maven.repo.remote" ) ); + assertEquals(mavenRepoRemote, (String) result.get("maven.repo.remote")); } /** *

    testIteratorToListWithAPopulatedList.

    */ @Test - public void testIteratorToListWithAPopulatedList() - { + public void testIteratorToListWithAPopulatedList() { List original = new ArrayList(); - original.add( "en" ); - original.add( "to" ); - original.add( "tre" ); + original.add("en"); + original.add("to"); + original.add("tre"); - List copy = CollectionUtils.iteratorToList( original.iterator() ); + List copy = CollectionUtils.iteratorToList(original.iterator()); - assertNotNull( copy ); + assertNotNull(copy); - assertEquals( 3, copy.size() ); + assertEquals(3, copy.size()); - assertEquals( "en", copy.get( 0 ) ); - assertEquals( "to", copy.get( 1 ) ); - assertEquals( "tre", copy.get( 2 ) ); + assertEquals("en", copy.get(0)); + assertEquals("to", copy.get(1)); + assertEquals("tre", copy.get(2)); } /** *

    testIteratorToListWithAEmptyList.

    */ @Test - public void testIteratorToListWithAEmptyList() - { + public void testIteratorToListWithAEmptyList() { List original = new ArrayList(); - List copy = CollectionUtils.iteratorToList( original.iterator() ); + List copy = CollectionUtils.iteratorToList(original.iterator()); - assertNotNull( copy ); + assertNotNull(copy); - assertEquals( 0, copy.size() ); + assertEquals(0, copy.size()); } } diff --git a/src/test/java/org/codehaus/plexus/util/DirectoryScannerTest.java b/src/test/java/org/codehaus/plexus/util/DirectoryScannerTest.java index 86c6dd20..afe9a877 100644 --- a/src/test/java/org/codehaus/plexus/util/DirectoryScannerTest.java +++ b/src/test/java/org/codehaus/plexus/util/DirectoryScannerTest.java @@ -16,12 +16,6 @@ * 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; @@ -40,6 +34,12 @@ import org.junit.Test; import org.junit.rules.TestName; +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; + /** * Base class for testcases doing tests with files. * @@ -47,27 +47,21 @@ * @version $Id: $Id * @since 3.4.0 */ -public class DirectoryScannerTest - extends FileBasedTestCase -{ +public class DirectoryScannerTest extends FileBasedTestCase { @Rule public TestName name = new TestName(); - + private static String testDir = getTestDirectory().getPath(); /** *

    setUp.

    */ @Before - public void setUp() - { - try - { - FileUtils.deleteDirectory( testDir ); - } - catch ( IOException e ) - { - fail( "Could not delete directory " + testDir ); + public void setUp() { + try { + FileUtils.deleteDirectory(testDir); + } catch (IOException e) { + fail("Could not delete directory " + testDir); } } @@ -78,28 +72,23 @@ public void setUp() * @throws java.net.URISyntaxException if any. */ @Test - public void testCrossPlatformIncludesString() - throws IOException, URISyntaxException - { + public void testCrossPlatformIncludesString() throws IOException, URISyntaxException { DirectoryScanner ds = new DirectoryScanner(); - ds.setBasedir( new File( getTestResourcesDir() + File.separator + "directory-scanner" ).getCanonicalFile() ); + ds.setBasedir(new File(getTestResourcesDir() + File.separator + "directory-scanner").getCanonicalFile()); String fs; - if ( File.separatorChar == '/' ) - { + if (File.separatorChar == '/') { fs = "\\"; - } - else - { + } else { fs = "/"; } - ds.setIncludes( new String[] { "foo" + fs } ); + ds.setIncludes(new String[] {"foo" + fs}); ds.addDefaultExcludes(); ds.scan(); String[] files = ds.getIncludedFiles(); - assertEquals( 1, files.length ); + assertEquals(1, files.length); } /** @@ -109,94 +98,77 @@ public void testCrossPlatformIncludesString() * @throws java.net.URISyntaxException if any. */ @Test - public void testCrossPlatformExcludesString() - throws IOException, URISyntaxException - { + public void testCrossPlatformExcludesString() throws IOException, URISyntaxException { DirectoryScanner ds = new DirectoryScanner(); - ds.setBasedir( new File( getTestResourcesDir() + File.separator + "directory-scanner" ).getCanonicalFile() ); - ds.setIncludes( new String[] { "**" } ); + ds.setBasedir(new File(getTestResourcesDir() + File.separator + "directory-scanner").getCanonicalFile()); + ds.setIncludes(new String[] {"**"}); String fs; - if ( File.separatorChar == '/' ) - { + if (File.separatorChar == '/') { fs = "\\"; - } - else - { + } else { fs = "/"; } - ds.setExcludes( new String[] { "foo" + fs } ); + ds.setExcludes(new String[] {"foo" + fs}); ds.addDefaultExcludes(); ds.scan(); String[] files = ds.getIncludedFiles(); - assertEquals( 0, files.length ); + assertEquals(0, files.length); } - private String getTestResourcesDir() - throws URISyntaxException - { + private String getTestResourcesDir() throws URISyntaxException { ClassLoader cloader = Thread.currentThread().getContextClassLoader(); - URL resource = cloader.getResource( "test.txt" ); - if ( resource == null ) - { - fail( "Cannot locate test-resources directory containing 'test.txt' in the classloader." ); + URL resource = cloader.getResource("test.txt"); + if (resource == null) { + fail("Cannot locate test-resources directory containing 'test.txt' in the classloader."); } - File file = new File( new URI( resource.toExternalForm() ).normalize().getPath() ); + File file = new File(new URI(resource.toExternalForm()).normalize().getPath()); return file.getParent(); } - private void createTestFiles() - throws IOException - { - FileUtils.mkdir( testDir ); - this.createFile( new File( testDir + "/scanner1.dat" ), 0 ); - this.createFile( new File( testDir + "/scanner2.dat" ), 0 ); - this.createFile( new File( testDir + "/scanner3.dat" ), 0 ); - this.createFile( new File( testDir + "/scanner4.dat" ), 0 ); - this.createFile( new File( testDir + "/scanner5.dat" ), 0 ); + private void createTestFiles() throws IOException { + FileUtils.mkdir(testDir); + this.createFile(new File(testDir + "/scanner1.dat"), 0); + this.createFile(new File(testDir + "/scanner2.dat"), 0); + this.createFile(new File(testDir + "/scanner3.dat"), 0); + 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 - { + 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" ); + 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 ) ); + 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])" ); + } 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; } } @@ -207,21 +179,18 @@ private boolean checkTestFilesSymlinks() * @throws java.io.IOException if any. */ @Test - public void testGeneral() - throws IOException - { + public void testGeneral() throws IOException { this.createTestFiles(); String includes = "scanner1.dat,scanner2.dat,scanner3.dat,scanner4.dat,scanner5.dat"; String excludes = "scanner1.dat,scanner2.dat"; - List fileNames = FileUtils.getFiles( new File( testDir ), includes, excludes, false ); - - assertEquals( "Wrong number of results.", 3, fileNames.size() ); - assertTrue( "3 not found.", fileNames.contains( new File( "scanner3.dat" ) ) ); - assertTrue( "4 not found.", fileNames.contains( new File( "scanner4.dat" ) ) ); - assertTrue( "5 not found.", fileNames.contains( new File( "scanner5.dat" ) ) ); + List fileNames = FileUtils.getFiles(new File(testDir), includes, excludes, false); + assertEquals("Wrong number of results.", 3, fileNames.size()); + assertTrue("3 not found.", fileNames.contains(new File("scanner3.dat"))); + assertTrue("4 not found.", fileNames.contains(new File("scanner4.dat"))); + assertTrue("5 not found.", fileNames.contains(new File("scanner5.dat"))); } /** @@ -230,100 +199,99 @@ public void testGeneral() * @throws java.io.IOException if any. */ @Test - public void testIncludesExcludesWithWhiteSpaces() - throws IOException - { + public void testIncludesExcludesWithWhiteSpaces() throws IOException { this.createTestFiles(); String includes = "scanner1.dat,\n \n,scanner2.dat \n\r, scanner3.dat\n, \tscanner4.dat,scanner5.dat\n,"; String excludes = "scanner1.dat,\n \n,scanner2.dat \n\r,,"; - List fileNames = FileUtils.getFiles( new File( testDir ), includes, excludes, false ); + List fileNames = FileUtils.getFiles(new File(testDir), includes, excludes, false); - assertEquals( "Wrong number of results.", 3, fileNames.size() ); - assertTrue( "3 not found.", fileNames.contains( new File( "scanner3.dat" ) ) ); - assertTrue( "4 not found.", fileNames.contains( new File( "scanner4.dat" ) ) ); - assertTrue( "5 not found.", fileNames.contains( new File( "scanner5.dat" ) ) ); + assertEquals("Wrong number of results.", 3, fileNames.size()); + assertTrue("3 not found.", fileNames.contains(new File("scanner3.dat"))); + assertTrue("4 not found.", fileNames.contains(new File("scanner4.dat"))); + assertTrue("5 not found.", fileNames.contains(new File("scanner5.dat"))); } /** *

    testFollowSymlinksFalse.

    */ @Test - public void testFollowSymlinksFalse() - { - assumeTrue( checkTestFilesSymlinks() ); - + public void testFollowSymlinksFalse() { + assumeTrue(checkTestFilesSymlinks()); + DirectoryScanner ds = new DirectoryScanner(); - ds.setBasedir( new File( "src/test/resources/symlinks/src/" ) ); - ds.setFollowSymlinks( false ); + ds.setBasedir(new File("src/test/resources/symlinks/src/")); + ds.setFollowSymlinks(false); ds.scan(); - List included = Arrays.asList( ds.getIncludedFiles() ); - assertAlwaysIncluded( included ); - assertEquals( 9, included.size() ); - List includedDirs = Arrays.asList( ds.getIncludedDirectories() ); - assertTrue( includedDirs.contains( "" ) ); // w00t ! - assertTrue( includedDirs.contains( "aRegularDir" ) ); - assertTrue( includedDirs.contains( "symDir" ) ); - assertTrue( includedDirs.contains( "symLinkToDirOnTheOutside" ) ); - assertTrue( includedDirs.contains( "targetDir" ) ); - assertEquals( 5, includedDirs.size() ); + List included = Arrays.asList(ds.getIncludedFiles()); + assertAlwaysIncluded(included); + assertEquals(9, included.size()); + List includedDirs = Arrays.asList(ds.getIncludedDirectories()); + assertTrue(includedDirs.contains("")); // w00t ! + assertTrue(includedDirs.contains("aRegularDir")); + assertTrue(includedDirs.contains("symDir")); + assertTrue(includedDirs.contains("symLinkToDirOnTheOutside")); + assertTrue(includedDirs.contains("targetDir")); + assertEquals(5, includedDirs.size()); } - private void assertAlwaysIncluded( List included ) - { - assertTrue( included.contains( "aRegularDir" + File.separator + "aRegularFile.txt" ) ); - assertTrue( included.contains( "targetDir" + File.separator + "targetFile.txt" ) ); - assertTrue( included.contains( "fileR.txt" ) ); - assertTrue( included.contains( "fileW.txt" ) ); - assertTrue( included.contains( "fileX.txt" ) ); - assertTrue( included.contains( "symR" ) ); - assertTrue( included.contains( "symW" ) ); - assertTrue( included.contains( "symX" ) ); - assertTrue( included.contains( "symLinkToFileOnTheOutside" ) ); + private void assertAlwaysIncluded(List included) { + assertTrue(included.contains("aRegularDir" + File.separator + "aRegularFile.txt")); + assertTrue(included.contains("targetDir" + File.separator + "targetFile.txt")); + assertTrue(included.contains("fileR.txt")); + assertTrue(included.contains("fileW.txt")); + assertTrue(included.contains("fileX.txt")); + assertTrue(included.contains("symR")); + assertTrue(included.contains("symW")); + assertTrue(included.contains("symX")); + assertTrue(included.contains("symLinkToFileOnTheOutside")); } /** *

    testFollowSymlinks.

    */ @Test - public void testFollowSymlinks() - { - assumeTrue( checkTestFilesSymlinks() ); - + public void testFollowSymlinks() { + assumeTrue(checkTestFilesSymlinks()); + DirectoryScanner ds = new DirectoryScanner(); - ds.setBasedir( new File( "src/test/resources/symlinks/src/" ) ); - ds.setFollowSymlinks( true ); + ds.setBasedir(new File("src/test/resources/symlinks/src/")); + ds.setFollowSymlinks(true); ds.scan(); - List included = Arrays.asList( ds.getIncludedFiles() ); - assertAlwaysIncluded( included ); - assertTrue( included.contains( "symDir" + File.separator + "targetFile.txt" ) ); - assertTrue( included.contains( "symLinkToDirOnTheOutside" + File.separator + "FileInDirOnTheOutside.txt" ) ); - assertEquals( 11, included.size() ); - - List includedDirs = Arrays.asList( ds.getIncludedDirectories() ); - assertTrue( includedDirs.contains( "" ) ); // w00t ! - assertTrue( includedDirs.contains( "aRegularDir" ) ); - assertTrue( includedDirs.contains( "symDir" ) ); - assertTrue( includedDirs.contains( "symLinkToDirOnTheOutside" ) ); - assertTrue( includedDirs.contains( "targetDir" ) ); - assertEquals( 5, includedDirs.size() ); + List included = Arrays.asList(ds.getIncludedFiles()); + assertAlwaysIncluded(included); + assertTrue(included.contains("symDir" + File.separator + "targetFile.txt")); + assertTrue(included.contains("symLinkToDirOnTheOutside" + File.separator + "FileInDirOnTheOutside.txt")); + assertEquals(11, included.size()); + + List includedDirs = Arrays.asList(ds.getIncludedDirectories()); + assertTrue(includedDirs.contains("")); // w00t ! + assertTrue(includedDirs.contains("aRegularDir")); + assertTrue(includedDirs.contains("symDir")); + assertTrue(includedDirs.contains("symLinkToDirOnTheOutside")); + assertTrue(includedDirs.contains("targetDir")); + assertEquals(5, includedDirs.size()); } - private void createTestDirectories() - throws IOException - { - FileUtils.mkdir( testDir + File.separator + "directoryTest" ); - FileUtils.mkdir( testDir + File.separator + "directoryTest" + File.separator + "testDir123" ); - FileUtils.mkdir( testDir + File.separator + "directoryTest" + File.separator + "test_dir_123" ); - FileUtils.mkdir( testDir + File.separator + "directoryTest" + File.separator + "test-dir-123" ); - this.createFile( new File( testDir + File.separator + "directoryTest" + File.separator + "testDir123" - + File.separator + "file1.dat" ), 0 ); - this.createFile( new File( testDir + File.separator + "directoryTest" + File.separator + "test_dir_123" - + File.separator + "file1.dat" ), 0 ); - this.createFile( new File( testDir + File.separator + "directoryTest" + File.separator + "test-dir-123" - + File.separator + "file1.dat" ), 0 ); + private void createTestDirectories() throws IOException { + FileUtils.mkdir(testDir + File.separator + "directoryTest"); + FileUtils.mkdir(testDir + File.separator + "directoryTest" + File.separator + "testDir123"); + FileUtils.mkdir(testDir + File.separator + "directoryTest" + File.separator + "test_dir_123"); + FileUtils.mkdir(testDir + File.separator + "directoryTest" + File.separator + "test-dir-123"); + this.createFile( + new File(testDir + File.separator + "directoryTest" + File.separator + "testDir123" + File.separator + + "file1.dat"), + 0); + this.createFile( + new File(testDir + File.separator + "directoryTest" + File.separator + "test_dir_123" + File.separator + + "file1.dat"), + 0); + this.createFile( + new File(testDir + File.separator + "directoryTest" + File.separator + "test-dir-123" + File.separator + + "file1.dat"), + 0); } /** @@ -332,22 +300,20 @@ private void createTestDirectories() * @throws java.io.IOException if any. */ @Test - public void testDirectoriesWithHyphens() - throws IOException - { + public void testDirectoriesWithHyphens() throws IOException { this.createTestDirectories(); DirectoryScanner ds = new DirectoryScanner(); - String[] includes = { "**/*.dat" }; - String[] excludes = { "" }; - ds.setIncludes( includes ); - ds.setExcludes( excludes ); - ds.setBasedir( new File( testDir + File.separator + "directoryTest" ) ); - ds.setCaseSensitive( true ); + String[] includes = {"**/*.dat"}; + String[] excludes = {""}; + ds.setIncludes(includes); + ds.setExcludes(excludes); + ds.setBasedir(new File(testDir + File.separator + "directoryTest")); + ds.setCaseSensitive(true); ds.scan(); String[] files = ds.getIncludedFiles(); - assertEquals( "Wrong number of results.", 3, files.length ); + assertEquals("Wrong number of results.", 3, files.length); } /** @@ -356,38 +322,36 @@ public void testDirectoriesWithHyphens() * @throws java.io.IOException if any. */ @Test - public void testAntExcludesOverrideIncludes() - throws IOException - { + public void testAntExcludesOverrideIncludes() throws IOException { printTestHeader(); - File dir = new File( testDir, "regex-dir" ); + File dir = new File(testDir, "regex-dir"); dir.mkdirs(); - String[] excludedPaths = { "target/foo.txt" }; + String[] excludedPaths = {"target/foo.txt"}; - createFiles( dir, excludedPaths ); + createFiles(dir, excludedPaths); - String[] includedPaths = { "src/main/resources/project/target/foo.txt" }; + String[] includedPaths = {"src/main/resources/project/target/foo.txt"}; - createFiles( dir, includedPaths ); + createFiles(dir, includedPaths); DirectoryScanner ds = new DirectoryScanner(); - String[] includes = { "**/target/*" }; - String[] excludes = { "target/*" }; + String[] includes = {"**/target/*"}; + String[] excludes = {"target/*"}; // This doesn't work, since excluded patterns refine included ones, meaning they operate on // the list of paths that passed the included patterns, and can override them. // String[] includes = {"**src/**/target/**/*" }; // String[] excludes = { "**/target/**/*" }; - ds.setIncludes( includes ); - ds.setExcludes( excludes ); - ds.setBasedir( dir ); + ds.setIncludes(includes); + ds.setExcludes(excludes); + ds.setBasedir(dir); ds.scan(); - assertInclusionsAndExclusions( ds.getIncludedFiles(), excludedPaths, includedPaths ); + assertInclusionsAndExclusions(ds.getIncludedFiles(), excludedPaths, includedPaths); } /** @@ -396,39 +360,37 @@ public void testAntExcludesOverrideIncludes() * @throws java.io.IOException if any. */ @Test - public void testAntExcludesOverrideIncludesWithExplicitAntPrefix() - throws IOException - { + public void testAntExcludesOverrideIncludesWithExplicitAntPrefix() throws IOException { printTestHeader(); - File dir = new File( testDir, "regex-dir" ); + File dir = new File(testDir, "regex-dir"); dir.mkdirs(); - String[] excludedPaths = { "target/foo.txt" }; + String[] excludedPaths = {"target/foo.txt"}; - createFiles( dir, excludedPaths ); + createFiles(dir, excludedPaths); - String[] includedPaths = { "src/main/resources/project/target/foo.txt" }; + String[] includedPaths = {"src/main/resources/project/target/foo.txt"}; - createFiles( dir, includedPaths ); + createFiles(dir, includedPaths); DirectoryScanner ds = new DirectoryScanner(); - String[] includes = - { SelectorUtils.ANT_HANDLER_PREFIX + "**/target/**/*" + SelectorUtils.PATTERN_HANDLER_SUFFIX }; - String[] excludes = { SelectorUtils.ANT_HANDLER_PREFIX + "target/**/*" + SelectorUtils.PATTERN_HANDLER_SUFFIX }; + String[] includes = {SelectorUtils.ANT_HANDLER_PREFIX + "**/target/**/*" + SelectorUtils.PATTERN_HANDLER_SUFFIX + }; + String[] excludes = {SelectorUtils.ANT_HANDLER_PREFIX + "target/**/*" + SelectorUtils.PATTERN_HANDLER_SUFFIX}; // This doesn't work, since excluded patterns refine included ones, meaning they operate on // the list of paths that passed the included patterns, and can override them. // String[] includes = {"**src/**/target/**/*" }; // String[] excludes = { "**/target/**/*" }; - ds.setIncludes( includes ); - ds.setExcludes( excludes ); - ds.setBasedir( dir ); + ds.setIncludes(includes); + ds.setExcludes(excludes); + ds.setBasedir(dir); ds.scan(); - assertInclusionsAndExclusions( ds.getIncludedFiles(), excludedPaths, includedPaths ); + assertInclusionsAndExclusions(ds.getIncludedFiles(), excludedPaths, includedPaths); } /** @@ -437,21 +399,19 @@ public void testAntExcludesOverrideIncludesWithExplicitAntPrefix() * @throws java.io.IOException if any. */ @Test - public void testRegexIncludeWithExcludedPrefixDirs() - throws IOException - { + public void testRegexIncludeWithExcludedPrefixDirs() throws IOException { printTestHeader(); - File dir = new File( testDir, "regex-dir" ); + File dir = new File(testDir, "regex-dir"); dir.mkdirs(); - String[] excludedPaths = { "src/main/foo.txt" }; + String[] excludedPaths = {"src/main/foo.txt"}; - createFiles( dir, excludedPaths ); + createFiles(dir, excludedPaths); - String[] includedPaths = { "src/main/resources/project/target/foo.txt" }; + String[] includedPaths = {"src/main/resources/project/target/foo.txt"}; - createFiles( dir, includedPaths ); + createFiles(dir, includedPaths); String regex = ".+/target.*"; @@ -459,12 +419,12 @@ public void testRegexIncludeWithExcludedPrefixDirs() String includeExpr = SelectorUtils.REGEX_HANDLER_PREFIX + regex + SelectorUtils.PATTERN_HANDLER_SUFFIX; - String[] includes = { includeExpr }; - ds.setIncludes( includes ); - ds.setBasedir( dir ); + String[] includes = {includeExpr}; + ds.setIncludes(includes); + ds.setBasedir(dir); ds.scan(); - assertInclusionsAndExclusions( ds.getIncludedFiles(), excludedPaths, includedPaths ); + assertInclusionsAndExclusions(ds.getIncludedFiles(), excludedPaths, includedPaths); } /** @@ -473,29 +433,24 @@ public void testRegexIncludeWithExcludedPrefixDirs() * @throws java.io.IOException if any. */ @Test - public void testRegexExcludeWithNegativeLookahead() - throws IOException - { + public void testRegexExcludeWithNegativeLookahead() throws IOException { printTestHeader(); - File dir = new File( testDir, "regex-dir" ); - try - { - FileUtils.deleteDirectory( dir ); - } - catch ( IOException e ) - { + File dir = new File(testDir, "regex-dir"); + try { + FileUtils.deleteDirectory(dir); + } catch (IOException e) { } dir.mkdirs(); - String[] excludedPaths = { "target/foo.txt" }; + String[] excludedPaths = {"target/foo.txt"}; - createFiles( dir, excludedPaths ); + createFiles(dir, excludedPaths); - String[] includedPaths = { "src/main/resources/project/target/foo.txt" }; + String[] includedPaths = {"src/main/resources/project/target/foo.txt"}; - createFiles( dir, includedPaths ); + createFiles(dir, includedPaths); String regex = "(?!.*src/).*target.*"; @@ -503,12 +458,12 @@ public void testRegexExcludeWithNegativeLookahead() String excludeExpr = SelectorUtils.REGEX_HANDLER_PREFIX + regex + SelectorUtils.PATTERN_HANDLER_SUFFIX; - String[] excludes = { excludeExpr }; - ds.setExcludes( excludes ); - ds.setBasedir( dir ); + String[] excludes = {excludeExpr}; + ds.setExcludes(excludes); + ds.setBasedir(dir); ds.scan(); - assertInclusionsAndExclusions( ds.getIncludedFiles(), excludedPaths, includedPaths ); + assertInclusionsAndExclusions(ds.getIncludedFiles(), excludedPaths, includedPaths); } /** @@ -517,29 +472,24 @@ public void testRegexExcludeWithNegativeLookahead() * @throws java.io.IOException if any. */ @Test - public void testRegexWithSlashInsideCharacterClass() - throws IOException - { + public void testRegexWithSlashInsideCharacterClass() throws IOException { printTestHeader(); - File dir = new File( testDir, "regex-dir" ); - try - { - FileUtils.deleteDirectory( dir ); - } - catch ( IOException e ) - { + File dir = new File(testDir, "regex-dir"); + try { + FileUtils.deleteDirectory(dir); + } catch (IOException e) { } dir.mkdirs(); - String[] excludedPaths = { "target/foo.txt", "target/src/main/target/foo.txt" }; + String[] excludedPaths = {"target/foo.txt", "target/src/main/target/foo.txt"}; - createFiles( dir, excludedPaths ); + createFiles(dir, excludedPaths); - String[] includedPaths = { "module/src/main/target/foo.txt" }; + String[] includedPaths = {"module/src/main/target/foo.txt"}; - createFiles( dir, includedPaths ); + createFiles(dir, includedPaths); // NOTE: The portion "[^/]" is the interesting part of this pattern. String regex = "(?!((?!target/)[^/]+/)*src/).*target.*"; @@ -548,12 +498,12 @@ public void testRegexWithSlashInsideCharacterClass() String excludeExpr = SelectorUtils.REGEX_HANDLER_PREFIX + regex + SelectorUtils.PATTERN_HANDLER_SUFFIX; - String[] excludes = { excludeExpr }; - ds.setExcludes( excludes ); - ds.setBasedir( dir ); + String[] excludes = {excludeExpr}; + ds.setExcludes(excludes); + ds.setBasedir(dir); ds.scan(); - assertInclusionsAndExclusions( ds.getIncludedFiles(), excludedPaths, includedPaths ); + assertInclusionsAndExclusions(ds.getIncludedFiles(), excludedPaths, includedPaths); } /** @@ -563,33 +513,37 @@ public void testRegexWithSlashInsideCharacterClass() * @throws java.io.IOException if occurs an I/O error. */ @Test - public void testDoNotScanUnnecesaryDirectories() - throws IOException - { + public void testDoNotScanUnnecesaryDirectories() throws IOException { createTestDirectories(); // create additional directories 'anotherDir1', 'anotherDir2' and 'anotherDir3' with a 'file1.dat' file - FileUtils.mkdir( testDir + File.separator + "directoryTest" + File.separator + "testDir123" + File.separator - + "anotherDir1" ); - FileUtils.mkdir( testDir + File.separator + "directoryTest" + File.separator + "test_dir_123" + File.separator - + "anotherDir2" ); - FileUtils.mkdir( testDir + File.separator + "directoryTest" + File.separator + "test-dir-123" + File.separator - + "anotherDir3" ); - - this.createFile( new File( testDir + File.separator + "directoryTest" + File.separator + "testDir123" - + File.separator + "anotherDir1" + File.separator + "file1.dat" ), 0 ); - this.createFile( new File( testDir + File.separator + "directoryTest" + File.separator + "test_dir_123" - + File.separator + "anotherDir2" + File.separator + "file1.dat" ), 0 ); - this.createFile( new File( testDir + File.separator + "directoryTest" + File.separator + "test-dir-123" - + File.separator + "anotherDir3" + File.separator + "file1.dat" ), 0 ); + FileUtils.mkdir(testDir + File.separator + "directoryTest" + File.separator + "testDir123" + File.separator + + "anotherDir1"); + FileUtils.mkdir(testDir + File.separator + "directoryTest" + File.separator + "test_dir_123" + File.separator + + "anotherDir2"); + FileUtils.mkdir(testDir + File.separator + "directoryTest" + File.separator + "test-dir-123" + File.separator + + "anotherDir3"); + + this.createFile( + new File(testDir + File.separator + "directoryTest" + File.separator + "testDir123" + File.separator + + "anotherDir1" + File.separator + "file1.dat"), + 0); + this.createFile( + new File(testDir + File.separator + "directoryTest" + File.separator + "test_dir_123" + File.separator + + "anotherDir2" + File.separator + "file1.dat"), + 0); + this.createFile( + new File(testDir + File.separator + "directoryTest" + File.separator + "test-dir-123" + File.separator + + "anotherDir3" + File.separator + "file1.dat"), + 0); String[] excludedPaths = { "directoryTest" + File.separator + "testDir123" + File.separator + "anotherDir1" + File.separator - + "file1.dat", + + "file1.dat", "directoryTest" + File.separator + "test_dir_123" + File.separator + "anotherDir2" + File.separator - + "file1.dat", + + "file1.dat", "directoryTest" + File.separator + "test-dir-123" + File.separator + "anotherDir3" + File.separator - + "file1.dat" + + "file1.dat" }; String[] includedPaths = { @@ -600,29 +554,26 @@ public void testDoNotScanUnnecesaryDirectories() final Set scannedDirSet = new HashSet(); - DirectoryScanner ds = new DirectoryScanner() - { + DirectoryScanner ds = new DirectoryScanner() { @Override - protected void scandir( File dir, String vpath, boolean fast ) - { - scannedDirSet.add( dir.getName() ); - super.scandir( dir, vpath, fast ); + protected void scandir(File dir, String vpath, boolean fast) { + scannedDirSet.add(dir.getName()); + super.scandir(dir, vpath, fast); } - }; // one '*' matches only ONE directory level - String[] includes = { "directoryTest" + File.separator + "*" + File.separator + "file1.dat" }; - ds.setIncludes( includes ); - ds.setBasedir( new File( testDir ) ); + String[] includes = {"directoryTest" + File.separator + "*" + File.separator + "file1.dat"}; + ds.setIncludes(includes); + ds.setBasedir(new File(testDir)); ds.scan(); - assertInclusionsAndExclusions( ds.getIncludedFiles(), excludedPaths, includedPaths ); + assertInclusionsAndExclusions(ds.getIncludedFiles(), excludedPaths, includedPaths); Set expectedScannedDirSet = - new HashSet( Arrays.asList( "io", "directoryTest", "testDir123", "test_dir_123", "test-dir-123" ) ); + new HashSet(Arrays.asList("io", "directoryTest", "testDir123", "test_dir_123", "test-dir-123")); - assertEquals( expectedScannedDirSet, scannedDirSet ); + assertEquals(expectedScannedDirSet, scannedDirSet); } /** @@ -631,17 +582,15 @@ protected void scandir( File dir, String vpath, boolean fast ) * @throws java.io.IOException if any. */ @Test - public void testIsSymbolicLink() - throws IOException - { - assumeTrue( checkTestFilesSymlinks() ); + public void testIsSymbolicLink() throws IOException { + assumeTrue(checkTestFilesSymlinks()); - final File directory = new File( "src/test/resources/symlinks/src" ); + final File directory = new File("src/test/resources/symlinks/src"); DirectoryScanner ds = new DirectoryScanner(); - assertTrue( ds.isSymbolicLink( directory, "symR" ) ); - assertTrue( ds.isSymbolicLink( directory, "symDir" ) ); - assertFalse( ds.isSymbolicLink( directory, "fileR.txt" ) ); - assertFalse( ds.isSymbolicLink( directory, "aRegularDir" ) ); + assertTrue(ds.isSymbolicLink(directory, "symR")); + assertTrue(ds.isSymbolicLink(directory, "symDir")); + assertFalse(ds.isSymbolicLink(directory, "fileR.txt")); + assertFalse(ds.isSymbolicLink(directory, "aRegularDir")); } /** @@ -650,105 +599,83 @@ public void testIsSymbolicLink() * @throws java.io.IOException if any. */ @Test - public void testIsParentSymbolicLink() - throws IOException - { - assumeTrue( checkTestFilesSymlinks() ); + public void testIsParentSymbolicLink() throws IOException { + assumeTrue(checkTestFilesSymlinks()); - final File directory = new File( "src/test/resources/symlinks/src" ); + final File directory = new File("src/test/resources/symlinks/src"); DirectoryScanner ds = new DirectoryScanner(); - assertFalse( ds.isParentSymbolicLink( directory, "symR" ) ); - assertFalse( ds.isParentSymbolicLink( directory, "symDir" ) ); - assertFalse( ds.isParentSymbolicLink( directory, "fileR.txt" ) ); - assertFalse( ds.isParentSymbolicLink( directory, "aRegularDir" ) ); - assertFalse( ds.isParentSymbolicLink( new File( directory, "aRegularDir" ), "aRegulatFile.txt" ) ); - assertTrue( ds.isParentSymbolicLink( new File( directory, "symDir" ), "targetFile.txt" ) ); - assertTrue( ds.isParentSymbolicLink( new File( directory, "symLinkToDirOnTheOutside" ), - "FileInDirOnTheOutside.txt" ) ); + assertFalse(ds.isParentSymbolicLink(directory, "symR")); + assertFalse(ds.isParentSymbolicLink(directory, "symDir")); + assertFalse(ds.isParentSymbolicLink(directory, "fileR.txt")); + assertFalse(ds.isParentSymbolicLink(directory, "aRegularDir")); + assertFalse(ds.isParentSymbolicLink(new File(directory, "aRegularDir"), "aRegulatFile.txt")); + assertTrue(ds.isParentSymbolicLink(new File(directory, "symDir"), "targetFile.txt")); + assertTrue( + ds.isParentSymbolicLink(new File(directory, "symLinkToDirOnTheOutside"), "FileInDirOnTheOutside.txt")); } - private void printTestHeader() - { + private void printTestHeader() { StackTraceElement ste = new Throwable().getStackTrace()[1]; - System.out.println( "Test: " + ste.getMethodName() ); + System.out.println("Test: " + ste.getMethodName()); } - private void assertInclusionsAndExclusions( String[] files, String[] excludedPaths, String... includedPaths ) - { - Arrays.sort( files ); + private void assertInclusionsAndExclusions(String[] files, String[] excludedPaths, String... includedPaths) { + Arrays.sort(files); - System.out.println( "Included files: " ); - for ( String file : files ) - { - System.out.println( file ); + System.out.println("Included files: "); + for (String file : files) { + System.out.println(file); } List failedToExclude = new ArrayList(); - for ( String excludedPath : excludedPaths ) - { - String alt = excludedPath.replace( '/', '\\' ); - System.out.println( "Searching for exclusion as: " + excludedPath + "\nor: " + alt ); - if ( Arrays.binarySearch( files, excludedPath ) > -1 || Arrays.binarySearch( files, alt ) > -1 ) - { - failedToExclude.add( excludedPath ); + for (String excludedPath : excludedPaths) { + String alt = excludedPath.replace('/', '\\'); + System.out.println("Searching for exclusion as: " + excludedPath + "\nor: " + alt); + if (Arrays.binarySearch(files, excludedPath) > -1 || Arrays.binarySearch(files, alt) > -1) { + failedToExclude.add(excludedPath); } } List failedToInclude = new ArrayList(); - for ( String includedPath : includedPaths ) - { - String alt = includedPath.replace( '/', '\\' ); - System.out.println( "Searching for inclusion as: " + includedPath + "\nor: " + alt ); - if ( Arrays.binarySearch( files, includedPath ) < 0 && Arrays.binarySearch( files, alt ) < 0 ) - { - failedToInclude.add( includedPath ); + for (String includedPath : includedPaths) { + String alt = includedPath.replace('/', '\\'); + System.out.println("Searching for inclusion as: " + includedPath + "\nor: " + alt); + if (Arrays.binarySearch(files, includedPath) < 0 && Arrays.binarySearch(files, alt) < 0) { + failedToInclude.add(includedPath); } } StringBuilder buffer = new StringBuilder(); - if ( !failedToExclude.isEmpty() ) - { - buffer.append( "Should NOT have included:\n" ).append( StringUtils.join( failedToExclude.iterator(), - "\n\t- " ) ); + if (!failedToExclude.isEmpty()) { + buffer.append("Should NOT have included:\n").append(StringUtils.join(failedToExclude.iterator(), "\n\t- ")); } - if ( !failedToInclude.isEmpty() ) - { - if ( buffer.length() > 0 ) - { - buffer.append( "\n\n" ); + if (!failedToInclude.isEmpty()) { + if (buffer.length() > 0) { + buffer.append("\n\n"); } - buffer.append( "Should have included:\n" ).append( StringUtils.join( failedToInclude.iterator(), - "\n\t- " ) ); + buffer.append("Should have included:\n").append(StringUtils.join(failedToInclude.iterator(), "\n\t- ")); } - if ( buffer.length() > 0 ) - { - fail( buffer.toString() ); + if (buffer.length() > 0) { + fail(buffer.toString()); } } - private void createFiles( File dir, String... paths ) - throws IOException - { - for ( String path1 : paths ) - { - String path = path1.replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); - File file = new File( dir, path ); + private void createFiles(File dir, String... paths) throws IOException { + for (String path1 : paths) { + String path = path1.replace('/', File.separatorChar).replace('\\', File.separatorChar); + File file = new File(dir, path); - if ( path.endsWith( File.separator ) ) - { + if (path.endsWith(File.separator)) { file.mkdirs(); - } - else - { - if ( file.getParentFile() != null ) - { + } else { + if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } - createFile( file, 0 ); + createFile(file, 0); } } } diff --git a/src/test/java/org/codehaus/plexus/util/DirectoryWalkerTest.java b/src/test/java/org/codehaus/plexus/util/DirectoryWalkerTest.java index 757ce718..97786c51 100644 --- a/src/test/java/org/codehaus/plexus/util/DirectoryWalkerTest.java +++ b/src/test/java/org/codehaus/plexus/util/DirectoryWalkerTest.java @@ -16,14 +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.io.File; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + /** *

    DirectoryWalkerTest class.

    * @@ -31,30 +31,28 @@ * @version $Id: $Id * @since 3.4.0 */ -public class DirectoryWalkerTest -{ +public class DirectoryWalkerTest { /** *

    testDirectoryWalk.

    */ @Test - public void testDirectoryWalk() - { + public void testDirectoryWalk() { DirectoryWalker walker = new DirectoryWalker(); walker.addSCMExcludes(); - walker.setBaseDir( new File( "src/test/resources/directorywalker" ) ); + walker.setBaseDir(new File("src/test/resources/directorywalker")); WalkCollector collector = new WalkCollector(); - walker.addDirectoryWalkListener( collector ); + walker.addDirectoryWalkListener(collector); walker.scan(); - assertEquals( "Walk Collector / Starting Count", 1, collector.startCount ); - assertNotNull( "Walk Collector / Starting Dir", collector.startingDir ); - assertEquals( "Walk Collector / Finish Count", 1, collector.finishCount ); - assertEquals( "Walk Collector / Steps Count", 4, collector.steps.size() ); - assertTrue( "Walk Collector / percentage low >= 0", collector.percentageLow >= 0 ); - assertTrue( "Walk Collector / percentage high <= 100", collector.percentageHigh <= 100 ); + assertEquals("Walk Collector / Starting Count", 1, collector.startCount); + assertNotNull("Walk Collector / Starting Dir", collector.startingDir); + assertEquals("Walk Collector / Finish Count", 1, collector.finishCount); + assertEquals("Walk Collector / Steps Count", 4, collector.steps.size()); + assertTrue("Walk Collector / percentage low >= 0", collector.percentageLow >= 0); + assertTrue("Walk Collector / percentage high <= 100", collector.percentageHigh <= 100); } } diff --git a/src/test/java/org/codehaus/plexus/util/FileBasedTestCase.java b/src/test/java/org/codehaus/plexus/util/FileBasedTestCase.java index 3e111b4e..367eca64 100644 --- a/src/test/java/org/codehaus/plexus/util/FileBasedTestCase.java +++ b/src/test/java/org/codehaus/plexus/util/FileBasedTestCase.java @@ -16,8 +16,6 @@ * limitations under the License. */ -import static org.junit.Assert.assertTrue; - import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -32,6 +30,8 @@ import junit.framework.AssertionFailedError; +import static org.junit.Assert.assertTrue; + /** * Base class for testcases doing tests with files. * @@ -39,8 +39,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public abstract class FileBasedTestCase -{ +public abstract class FileBasedTestCase { private static File testDir; /** @@ -48,11 +47,9 @@ public abstract class FileBasedTestCase * * @return a {@link java.io.File} object. */ - public static File getTestDirectory() - { - if ( testDir == null ) - { - testDir = ( new File( "target/test/io/" ) ).getAbsoluteFile(); + public static File getTestDirectory() { + if (testDir == null) { + testDir = (new File("target/test/io/")).getAbsoluteFile(); } return testDir; } @@ -65,26 +62,20 @@ public static File getTestDirectory() * @return an array of {@link byte} objects. * @throws java.io.IOException if any. */ - protected byte[] createFile( final File file, final long size ) - throws IOException - { - if ( !file.getParentFile().exists() ) - { - throw new IOException( "Cannot create file " + file + " as the parent directory does not exist" ); + protected byte[] createFile(final File file, final long size) throws IOException { + if (!file.getParentFile().exists()) { + throw new IOException("Cannot create file " + file + " as the parent directory does not exist"); } - byte[] data = generateTestData( size ); + byte[] data = generateTestData(size); - final BufferedOutputStream output = new BufferedOutputStream( Files.newOutputStream( file.toPath() ) ); + final BufferedOutputStream output = new BufferedOutputStream(Files.newOutputStream(file.toPath())); - try - { - output.write( data ); + try { + output.write(data); return data; - } - finally - { + } finally { output.close(); } } @@ -96,20 +87,15 @@ protected byte[] createFile( final File file, final long size ) * @param target a {@link java.io.File} object. * @return a boolean. */ - protected boolean createSymlink( final File link, final File target ) - { - try - { - String[] args = { "ln", "-s", target.getAbsolutePath(), link.getAbsolutePath() }; - Process process = Runtime.getRuntime().exec( args ); + protected boolean createSymlink(final File link, final File target) { + try { + String[] args = {"ln", "-s", target.getAbsolutePath(), link.getAbsolutePath()}; + Process process = Runtime.getRuntime().exec(args); process.waitFor(); - if ( 0 != process.exitValue() ) - { + if (0 != process.exitValue()) { return false; } - } - catch ( Exception e ) - { + } catch (Exception e) { // assume platform does not support "ln" command, tests should be skipped return false; } @@ -122,17 +108,13 @@ protected boolean createSymlink( final File link, final File target ) * @param size a long. * @return an array of {@link byte} objects. */ - protected byte[] generateTestData( final long size ) - { - try - { + protected byte[] generateTestData(final long size) { + try { ByteArrayOutputStream baout = new ByteArrayOutputStream(); - generateTestData( baout, size ); + generateTestData(baout, size); return baout.toByteArray(); - } - catch ( IOException ioe ) - { - throw new RuntimeException( "This should never happen: " + ioe.getMessage() ); + } catch (IOException ioe) { + throw new RuntimeException("This should never happen: " + ioe.getMessage()); } } @@ -143,15 +125,12 @@ protected byte[] generateTestData( final long size ) * @param size a long. * @throws java.io.IOException if any. */ - protected void generateTestData( final OutputStream out, final long size ) - throws IOException - { - for ( int i = 0; i < size; i++ ) - { + protected void generateTestData(final OutputStream out, final long size) throws IOException { + for (int i = 0; i < size; i++) { // output.write((byte)'X'); // nice varied byte pattern compatible with Readers and Writers - out.write( (byte) ( ( i % 127 ) + 1 ) ); + out.write((byte) ((i % 127) + 1)); } } @@ -162,16 +141,13 @@ protected void generateTestData( final OutputStream out, final long size ) * @return a {@link java.io.File} object. * @throws java.io.IOException if any. */ - protected File newFile( String filename ) - throws IOException - { - final File destination = new File( getTestDirectory(), filename ); + protected File newFile(String filename) throws IOException { + final File destination = new File(getTestDirectory(), filename); /* * assertTrue( filename + "Test output data file shouldn't previously exist", !destination.exists() ); */ - if ( destination.exists() ) - { - FileUtils.forceDelete( destination ); + if (destination.exists()) { + FileUtils.forceDelete(destination); } return destination; } @@ -183,11 +159,9 @@ protected File newFile( String filename ) * @param referenceFile a {@link java.io.File} object. * @throws java.lang.Exception if any. */ - protected void checkFile( final File file, final File referenceFile ) - throws Exception - { - assertTrue( "Check existence of output file", file.exists() ); - assertEqualContent( referenceFile, file ); + protected void checkFile(final File file, final File referenceFile) throws Exception { + assertTrue("Check existence of output file", file.exists()); + assertEqualContent(referenceFile, file); } /** @@ -196,17 +170,12 @@ protected void checkFile( final File file, final File referenceFile ) * @param output a {@link java.io.OutputStream} object. * @throws java.lang.Exception if any. */ - protected void checkWrite( final OutputStream output ) - throws Exception - { - try - { - new PrintStream( output ).write( 0 ); - } - catch ( final Throwable t ) - { - throw new AssertionFailedError( "The copy() method closed the stream " + "when it shouldn't have. " - + t.getMessage() ); + protected void checkWrite(final OutputStream output) throws Exception { + try { + new PrintStream(output).write(0); + } catch (final Throwable t) { + throw new AssertionFailedError( + "The copy() method closed the stream " + "when it shouldn't have. " + t.getMessage()); } } @@ -216,17 +185,12 @@ protected void checkWrite( final OutputStream output ) * @param output a {@link java.io.Writer} object. * @throws java.lang.Exception if any. */ - protected void checkWrite( final Writer output ) - throws Exception - { - try - { - new PrintWriter( output ).write( 'a' ); - } - catch ( final Throwable t ) - { - throw new AssertionFailedError( "The copy() method closed the stream " + "when it shouldn't have. " - + t.getMessage() ); + protected void checkWrite(final Writer output) throws Exception { + try { + new PrintWriter(output).write('a'); + } catch (final Throwable t) { + throw new AssertionFailedError( + "The copy() method closed the stream " + "when it shouldn't have. " + t.getMessage()); } } @@ -236,12 +200,9 @@ protected void checkWrite( final Writer output ) * @param file a {@link java.io.File} object. * @throws java.lang.Exception if any. */ - protected void deleteFile( final File file ) - throws Exception - { - if ( file.exists() ) - { - assertTrue( "Couldn't delete file: " + file, file.delete() ); + protected void deleteFile(final File file) throws Exception { + if (file.exists()) { + assertTrue("Couldn't delete file: " + file, file.delete()); } } @@ -250,43 +211,35 @@ protected void deleteFile( final File file ) // ---------------------------------------------------------------------- /** Assert that the content of two files is the same. */ - private void assertEqualContent( final File f0, final File f1 ) - throws IOException - { + private void assertEqualContent(final File f0, final File f1) throws IOException { /* * This doesn't work because the filesize isn't updated until the file is closed. assertTrue( "The files " + f0 * + " and " + f1 + " have differing file sizes (" + f0.length() + " vs " + f1.length() + ")", ( f0.length() == * f1.length() ) ); */ - final InputStream is0 = Files.newInputStream( f0.toPath() ); - try - { - final InputStream is1 = Files.newInputStream( f1.toPath() ); - try - { + final InputStream is0 = Files.newInputStream(f0.toPath()); + try { + final InputStream is1 = Files.newInputStream(f1.toPath()); + try { final byte[] buf0 = new byte[1024]; final byte[] buf1 = new byte[1024]; int n0 = 0; int n1 = 0; - while ( -1 != n0 ) - { - n0 = is0.read( buf0 ); - n1 = is1.read( buf1 ); - assertTrue( "The files " + f0 + " and " + f1 + " have differing number of bytes available (" + n0 - + " vs " + n1 + ")", ( n0 == n1 ) ); + while (-1 != n0) { + n0 = is0.read(buf0); + n1 = is1.read(buf1); + assertTrue( + "The files " + f0 + " and " + f1 + " have differing number of bytes available (" + n0 + + " vs " + n1 + ")", + (n0 == n1)); - assertTrue( "The files " + f0 + " and " + f1 + " have different content", - Arrays.equals( buf0, buf1 ) ); + assertTrue("The files " + f0 + " and " + f1 + " have different content", Arrays.equals(buf0, buf1)); } - } - finally - { + } finally { is1.close(); } - } - finally - { + } finally { is0.close(); } } @@ -298,21 +251,17 @@ private void assertEqualContent( final File f0, final File f1 ) * @param file a {@link java.io.File} object. * @throws java.io.IOException if any. */ - protected void assertEqualContent( final byte[] b0, final File file ) - throws IOException - { - final InputStream is = Files.newInputStream( file.toPath() ); - try - { + protected void assertEqualContent(final byte[] b0, final File file) throws IOException { + final InputStream is = Files.newInputStream(file.toPath()); + try { byte[] b1 = new byte[b0.length]; - int numRead = is.read( b1 ); - assertTrue( "Different number of bytes", numRead == b0.length && is.available() == 0 ); - for ( int i = 0; i < numRead; assertTrue( "Byte " + i + " differs (" + b0[i] + " != " + b1[i] + ")", - b0[i] == b1[i] ), i++ ) + int numRead = is.read(b1); + assertTrue("Different number of bytes", numRead == b0.length && is.available() == 0); + for (int i = 0; + i < numRead; + assertTrue("Byte " + i + " differs (" + b0[i] + " != " + b1[i] + ")", b0[i] == b1[i]), i++) ; - } - finally - { + } finally { is.close(); } } @@ -322,11 +271,10 @@ protected void assertEqualContent( final byte[] b0, final File file ) * * @param file a {@link java.io.File} object. */ - protected void assertIsDirectory( File file ) - { - assertTrue( "The File doesn't exists: " + file.getAbsolutePath(), file.exists() ); + protected void assertIsDirectory(File file) { + assertTrue("The File doesn't exists: " + file.getAbsolutePath(), file.exists()); - assertTrue( "The File isn't a directory: " + file.getAbsolutePath(), file.isDirectory() ); + assertTrue("The File isn't a directory: " + file.getAbsolutePath(), file.isDirectory()); } /** @@ -334,10 +282,9 @@ protected void assertIsDirectory( File file ) * * @param file a {@link java.io.File} object. */ - protected void assertIsFile( File file ) - { - assertTrue( "The File doesn't exists: " + file.getAbsolutePath(), file.exists() ); + protected void assertIsFile(File file) { + assertTrue("The File doesn't exists: " + file.getAbsolutePath(), file.exists()); - assertTrue( "The File isn't a file: " + file.getAbsolutePath(), file.isFile() ); + assertTrue("The File isn't a file: " + file.getAbsolutePath(), file.isFile()); } } diff --git a/src/test/java/org/codehaus/plexus/util/FileUtilsTest.java b/src/test/java/org/codehaus/plexus/util/FileUtilsTest.java index 4d63957c..dcfe8e4d 100644 --- a/src/test/java/org/codehaus/plexus/util/FileUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/FileUtilsTest.java @@ -16,13 +16,6 @@ * 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.IOException; @@ -41,6 +34,13 @@ import org.junit.Test; import org.junit.rules.TestName; +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; + /** * This is used to test FileUtils for correctness. * @@ -50,9 +50,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public final class FileUtilsTest - extends FileBasedTestCase -{ +public final class FileUtilsTest extends FileBasedTestCase { @Rule public TestName name = new TestName(); @@ -76,11 +74,9 @@ public final class FileUtilsTest * * @throws java.lang.Exception if any. */ - public FileUtilsTest() - throws Exception - { - testFile1 = new File( getTestDirectory(), "file1-test.txt" ); - testFile2 = new File( getTestDirectory(), "file1a-test.txt" ); + public FileUtilsTest() throws Exception { + testFile1 = new File(getTestDirectory(), "file1-test.txt"); + testFile2 = new File(getTestDirectory(), "file1a-test.txt"); testFile1Size = (int) testFile1.length(); testFile2Size = (int) testFile2.length(); @@ -92,16 +88,14 @@ public FileUtilsTest() * @throws java.lang.Exception if any. */ @Before - public void setUp() - throws Exception - { + public void setUp() throws Exception { getTestDirectory().mkdirs(); - createFile( testFile1, testFile1Size ); - createFile( testFile2, testFile2Size ); - FileUtils.deleteDirectory( getTestDirectory() ); + createFile(testFile1, testFile1Size); + createFile(testFile2, testFile2Size); + FileUtils.deleteDirectory(getTestDirectory()); getTestDirectory().mkdirs(); - createFile( testFile1, testFile1Size ); - createFile( testFile2, testFile2Size ); + createFile(testFile1, testFile1Size); + createFile(testFile2, testFile2Size); } // byteCountToDisplaySize @@ -110,12 +104,11 @@ public void setUp() *

    testByteCountToDisplaySize.

    */ @Test - public void testByteCountToDisplaySize() - { - assertEquals( FileUtils.byteCountToDisplaySize( 0 ), "0 bytes" ); - assertEquals( FileUtils.byteCountToDisplaySize( 1024 ), "1 KB" ); - assertEquals( FileUtils.byteCountToDisplaySize( 1024 * 1024 ), "1 MB" ); - assertEquals( FileUtils.byteCountToDisplaySize( 1024 * 1024 * 1024 ), "1 GB" ); + public void testByteCountToDisplaySize() { + assertEquals(FileUtils.byteCountToDisplaySize(0), "0 bytes"); + assertEquals(FileUtils.byteCountToDisplaySize(1024), "1 KB"); + assertEquals(FileUtils.byteCountToDisplaySize(1024 * 1024), "1 MB"); + assertEquals(FileUtils.byteCountToDisplaySize(1024 * 1024 * 1024), "1 GB"); } // waitFor @@ -124,11 +117,10 @@ public void testByteCountToDisplaySize() *

    testWaitFor.

    */ @Test - public void testWaitFor() - { - FileUtils.waitFor( "", -1 ); + public void testWaitFor() { + FileUtils.waitFor("", -1); - FileUtils.waitFor( "", 2 ); + FileUtils.waitFor("", 2); } /** @@ -137,13 +129,11 @@ public void testWaitFor() * @throws java.lang.Exception if any. */ @Test - public void testToFile() - throws Exception - { - URL url = getClass().getResource( "/test.txt" ); - url = new URL( url.toString() + "/name%20%23%2520%3F%7B%7D%5B%5D%3C%3E.txt" ); - File file = FileUtils.toFile( url ); - assertEquals( "name #%20?{}[]<>.txt", file.getName() ); + public void testToFile() throws Exception { + URL url = getClass().getResource("/test.txt"); + url = new URL(url.toString() + "/name%20%23%2520%3F%7B%7D%5B%5D%3C%3E.txt"); + File file = FileUtils.toFile(url); + assertEquals("name #%20?{}[]<>.txt", file.getName()); } /** @@ -152,12 +142,10 @@ public void testToFile() * @throws java.lang.Exception if any. */ @Test - public void testToFileBadProtocol() - throws Exception - { - URL url = new URL( "http://maven.apache.org/" ); - File file = FileUtils.toFile( url ); - assertNull( file ); + public void testToFileBadProtocol() throws Exception { + URL url = new URL("http://maven.apache.org/"); + File file = FileUtils.toFile(url); + assertNull(file); } /** @@ -166,11 +154,9 @@ public void testToFileBadProtocol() * @throws java.lang.Exception if any. */ @Test - public void testToFileNull() - throws Exception - { - File file = FileUtils.toFile( null ); - assertNull( file ); + public void testToFileNull() throws Exception { + File file = FileUtils.toFile(null); + assertNull(file); } // Hacked to sanity by Trygve @@ -180,19 +166,21 @@ public void testToFileNull() * @throws java.lang.Exception if any. */ @Test - public void testToURLs() - throws Exception - { - File[] files = new File[] { new File( "file1" ), new File( "file2" ), }; + public void testToURLs() throws Exception { + File[] files = new File[] { + new File("file1"), new File("file2"), + }; - URL[] urls = FileUtils.toURLs( files ); + URL[] urls = FileUtils.toURLs(files); - assertEquals( "The length of the generated URL's is not equals to the length of files. " + "Was " + files.length - + ", expected " + urls.length, files.length, urls.length ); + assertEquals( + "The length of the generated URL's is not equals to the length of files. " + "Was " + files.length + + ", expected " + urls.length, + files.length, + urls.length); - for ( int i = 0; i < urls.length; i++ ) - { - assertEquals( files[i].toURI().toURL(), urls[i] ); + for (int i = 0; i < urls.length; i++) { + assertEquals(files[i].toURI().toURL(), urls[i]); } } @@ -200,15 +188,14 @@ public void testToURLs() *

    testGetFilesFromExtension.

    */ @Test - public void testGetFilesFromExtension() - { + public void testGetFilesFromExtension() { // TODO I'm not sure what is supposed to happen here - FileUtils.getFilesFromExtension( "dir", null ); + FileUtils.getFilesFromExtension("dir", null); // Non-existent files final String[] emptyFileNames = - FileUtils.getFilesFromExtension( getTestDirectory().getAbsolutePath(), new String[] { "java" } ); - assertTrue( emptyFileNames.length == 0 ); + FileUtils.getFilesFromExtension(getTestDirectory().getAbsolutePath(), new String[] {"java"}); + assertTrue(emptyFileNames.length == 0); // Existing files // TODO Figure out how to test this @@ -224,24 +211,19 @@ public void testGetFilesFromExtension() *

    testMkdir.

    */ @Test - public void testMkdir() - { - final File dir = new File( getTestDirectory(), "testdir" ); - FileUtils.mkdir( dir.getAbsolutePath() ); + public void testMkdir() { + final File dir = new File(getTestDirectory(), "testdir"); + FileUtils.mkdir(dir.getAbsolutePath()); dir.deleteOnExit(); - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - try - { - File winFile = new File( getTestDirectory(), "bla*bla" ); + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + try { + File winFile = new File(getTestDirectory(), "bla*bla"); winFile.deleteOnExit(); - FileUtils.mkdir( winFile.getAbsolutePath() ); - assertTrue( false ); - } - catch ( IllegalArgumentException e ) - { - assertTrue( true ); + FileUtils.mkdir(winFile.getAbsolutePath()); + assertTrue(false); + } catch (IllegalArgumentException e) { + assertTrue(true); } } } @@ -254,31 +236,29 @@ public void testMkdir() * @throws java.lang.Exception if any. */ @Test - public void testContentEquals() - throws Exception - { + public void testContentEquals() throws Exception { // Non-existent files - final File file = new File( getTestDirectory(), name.getMethodName() ); - assertTrue( FileUtils.contentEquals( file, file ) ); + 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? // Directories - assertTrue( !FileUtils.contentEquals( getTestDirectory(), getTestDirectory() ) ); + assertTrue(!FileUtils.contentEquals(getTestDirectory(), getTestDirectory())); // Different files - final File objFile1 = new File( getTestDirectory(), name.getMethodName() + ".object" ); + final File objFile1 = new File(getTestDirectory(), name.getMethodName() + ".object"); objFile1.deleteOnExit(); - FileUtils.copyURLToFile( getClass().getResource( "/java/lang/Object.class" ), objFile1 ); + FileUtils.copyURLToFile(getClass().getResource("/java/lang/Object.class"), objFile1); - final File objFile2 = new File( getTestDirectory(), name.getMethodName() + ".collection" ); + final File objFile2 = new File(getTestDirectory(), name.getMethodName() + ".collection"); objFile2.deleteOnExit(); - FileUtils.copyURLToFile( getClass().getResource( "/java/util/Collection.class" ), objFile2 ); + FileUtils.copyURLToFile(getClass().getResource("/java/util/Collection.class"), objFile2); - assertTrue( "Files should not be equal.", !FileUtils.contentEquals( objFile1, objFile2 ) ); + assertTrue("Files should not be equal.", !FileUtils.contentEquals(objFile1, objFile2)); // Equal files file.createNewFile(); - assertTrue( FileUtils.contentEquals( file, file ) ); + assertTrue(FileUtils.contentEquals(file, file)); } // removePath @@ -287,11 +267,10 @@ public void testContentEquals() *

    testRemovePath.

    */ @Test - public void testRemovePath() - { + public void testRemovePath() { final String fileName = - FileUtils.removePath( new File( getTestDirectory(), name.getMethodName() ).getAbsolutePath() ); - assertEquals( name.getMethodName(), fileName ); + FileUtils.removePath(new File(getTestDirectory(), name.getMethodName()).getAbsolutePath()); + assertEquals(name.getMethodName(), fileName); } // getPath @@ -300,11 +279,9 @@ public void testRemovePath() *

    testGetPath.

    */ @Test - public void testGetPath() - { - final String fileName = - FileUtils.getPath( new File( getTestDirectory(), name.getMethodName() ).getAbsolutePath() ); - assertEquals( getTestDirectory().getAbsolutePath(), fileName ); + public void testGetPath() { + final String fileName = FileUtils.getPath(new File(getTestDirectory(), name.getMethodName()).getAbsolutePath()); + assertEquals(getTestDirectory().getAbsolutePath(), fileName); } // copyURLToFile @@ -315,26 +292,21 @@ public void testGetPath() * @throws java.lang.Exception if any. */ @Test - public void testCopyURLToFile() - throws Exception - { + public void testCopyURLToFile() throws Exception { // Creates file - final File file = new File( getTestDirectory(), name.getMethodName() ); + final File file = new File(getTestDirectory(), name.getMethodName()); file.deleteOnExit(); // Loads resource final String resourceName = "/java/lang/Object.class"; - FileUtils.copyURLToFile( getClass().getResource( resourceName ), file ); + FileUtils.copyURLToFile(getClass().getResource(resourceName), file); // Tests that resource was copied correctly - final InputStream fis = Files.newInputStream( file.toPath() ); - try - { - assertTrue( "Content is not equal.", - IOUtil.contentEquals( getClass().getResourceAsStream( resourceName ), fis ) ); - } - finally - { + final InputStream fis = Files.newInputStream(file.toPath()); + try { + assertTrue( + "Content is not equal.", IOUtil.contentEquals(getClass().getResourceAsStream(resourceName), fis)); + } finally { fis.close(); } } @@ -345,14 +317,13 @@ public void testCopyURLToFile() *

    testCatPath.

    */ @Test - public void testCatPath() - { + public void testCatPath() { // TODO StringIndexOutOfBoundsException thrown if file doesn't contain slash. // Is this acceptable? // assertEquals("", FileUtils.catPath("a", "b")); - assertEquals( "/a/c", FileUtils.catPath( "/a/b", "c" ) ); - assertEquals( "/a/d", FileUtils.catPath( "/a/b/c", "../d" ) ); + assertEquals("/a/c", FileUtils.catPath("/a/b", "c")); + assertEquals("/a/d", FileUtils.catPath("/a/b/c", "../d")); } // forceMkdir @@ -363,46 +334,37 @@ public void testCatPath() * @throws java.lang.Exception if any. */ @Test - public void testForceMkdir() - throws Exception - { + public void testForceMkdir() throws Exception { // Tests with existing directory - FileUtils.forceMkdir( getTestDirectory() ); + FileUtils.forceMkdir(getTestDirectory()); // Creates test file - final File testFile = new File( getTestDirectory(), name.getMethodName() ); + final File testFile = new File(getTestDirectory(), name.getMethodName()); testFile.deleteOnExit(); testFile.createNewFile(); - assertTrue( "Test file does not exist.", testFile.exists() ); + assertTrue("Test file does not exist.", testFile.exists()); // Tests with existing file - try - { - FileUtils.forceMkdir( testFile ); - fail( "Exception expected." ); - } - catch ( IOException ex ) - { + try { + FileUtils.forceMkdir(testFile); + fail("Exception expected."); + } catch (IOException ex) { } testFile.delete(); // Tests with non-existent directory - FileUtils.forceMkdir( testFile ); - assertTrue( "Directory was not created.", testFile.exists() ); + FileUtils.forceMkdir(testFile); + assertTrue("Directory was not created.", testFile.exists()); - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - try - { - File winFile = new File( getTestDirectory(), "bla*bla" ); + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + try { + File winFile = new File(getTestDirectory(), "bla*bla"); winFile.deleteOnExit(); - FileUtils.forceMkdir( winFile ); - assertTrue( false ); - } - catch ( IllegalArgumentException e ) - { - assertTrue( true ); + FileUtils.forceMkdir(winFile); + assertTrue(false); + } catch (IllegalArgumentException e) { + assertTrue(true); } } } @@ -415,19 +377,14 @@ public void testForceMkdir() * @throws java.lang.Exception if any. */ @Test - public void testSizeOfDirectory() - throws Exception - { - final File file = new File( getTestDirectory(), name.getMethodName() ); + public void testSizeOfDirectory() throws Exception { + final File file = new File(getTestDirectory(), name.getMethodName()); // Non-existent file - try - { - FileUtils.sizeOfDirectory( file ); - fail( "Exception expected." ); - } - catch ( IllegalArgumentException ex ) - { + try { + FileUtils.sizeOfDirectory(file); + fail("Exception expected."); + } catch (IllegalArgumentException ex) { } // Creates file @@ -435,20 +392,17 @@ public void testSizeOfDirectory() file.deleteOnExit(); // Existing file - try - { - FileUtils.sizeOfDirectory( file ); - fail( "Exception expected." ); - } - catch ( IllegalArgumentException ex ) - { + try { + FileUtils.sizeOfDirectory(file); + fail("Exception expected."); + } catch (IllegalArgumentException ex) { } // Existing directory file.delete(); file.mkdir(); - assertEquals( "Unexpected directory size", TEST_DIRECTORY_SIZE, FileUtils.sizeOfDirectory( file ) ); + assertEquals("Unexpected directory size", TEST_DIRECTORY_SIZE, FileUtils.sizeOfDirectory(file)); } // isFileNewer @@ -458,9 +412,7 @@ public void testSizeOfDirectory() /** *

    XtestIsFileNewer.

    */ - public void XtestIsFileNewer() - { - } + public void XtestIsFileNewer() {} // copyFile /** @@ -469,13 +421,11 @@ public void XtestIsFileNewer() * @throws java.lang.Exception if any. */ @Test - public void testCopyFile1() - throws Exception - { - final File destination = new File( getTestDirectory(), "copy1.txt" ); - FileUtils.copyFile( testFile1, destination ); - assertTrue( "Check Exist", destination.exists() ); - assertTrue( "Check Full copy", destination.length() == testFile1Size ); + public void testCopyFile1() throws Exception { + final File destination = new File(getTestDirectory(), "copy1.txt"); + FileUtils.copyFile(testFile1, destination); + assertTrue("Check Exist", destination.exists()); + assertTrue("Check Full copy", destination.length() == testFile1Size); } /** @@ -484,13 +434,11 @@ public void testCopyFile1() * @throws java.lang.Exception if any. */ @Test - public void testCopyFile2() - throws Exception - { - final File destination = new File( getTestDirectory(), "copy2.txt" ); - FileUtils.copyFile( testFile1, destination ); - assertTrue( "Check Exist", destination.exists() ); - assertTrue( "Check Full copy", destination.length() == testFile2Size ); + public void testCopyFile2() throws Exception { + final File destination = new File(getTestDirectory(), "copy2.txt"); + FileUtils.copyFile(testFile1, destination); + assertTrue("Check Exist", destination.exists()); + assertTrue("Check Full copy", destination.length() == testFile2Size); } /** @@ -499,18 +447,15 @@ public void testCopyFile2() * @throws java.lang.Exception */ @Test - public void testCopyFile3() - throws Exception - { - File destDirectory = new File( getTestDirectory(), "foo/bar/testcopy" ); - if ( destDirectory.exists() ) - { + public void testCopyFile3() throws Exception { + File destDirectory = new File(getTestDirectory(), "foo/bar/testcopy"); + if (destDirectory.exists()) { destDirectory.delete(); } - final File destination = new File( destDirectory, "copy2.txt" ); - FileUtils.copyFile( testFile1, destination ); - assertTrue( "Check Exist", destination.exists() ); - assertTrue( "Check Full copy", destination.length() == testFile2Size ); + final File destination = new File(destDirectory, "copy2.txt"); + FileUtils.copyFile(testFile1, destination); + assertTrue("Check Exist", destination.exists()); + assertTrue("Check Full copy", destination.length() == testFile2Size); } // linkFile @@ -520,14 +465,12 @@ public void testCopyFile3() * @throws java.lang.Exception if any. */ @Test - public void testLinkFile1() - throws Exception - { - final File destination = new File( getTestDirectory(), "link1.txt" ); - FileUtils.linkFile( testFile1, destination ); - assertTrue( "Check Exist", destination.exists() ); - assertTrue( "Check File length", destination.length() == testFile1Size ); - assertTrue( "Check is link", Files.isSymbolicLink(destination.toPath())); + public void testLinkFile1() throws Exception { + final File destination = new File(getTestDirectory(), "link1.txt"); + FileUtils.linkFile(testFile1, destination); + assertTrue("Check Exist", destination.exists()); + assertTrue("Check File length", destination.length() == testFile1Size); + assertTrue("Check is link", Files.isSymbolicLink(destination.toPath())); } /** @@ -536,14 +479,12 @@ public void testLinkFile1() * @throws java.lang.Exception if any. */ @Test - public void testLinkFile2() - throws Exception - { - final File destination = new File( getTestDirectory(), "link2.txt" ); - FileUtils.linkFile( testFile1, destination ); - assertTrue( "Check Exist", destination.exists() ); - assertTrue( "Check File length", destination.length() == testFile2Size ); - assertTrue( "Check is link", Files.isSymbolicLink(destination.toPath())); + public void testLinkFile2() throws Exception { + final File destination = new File(getTestDirectory(), "link2.txt"); + FileUtils.linkFile(testFile1, destination); + assertTrue("Check Exist", destination.exists()); + assertTrue("Check File length", destination.length() == testFile2Size); + assertTrue("Check is link", Files.isSymbolicLink(destination.toPath())); } /** @@ -552,19 +493,16 @@ public void testLinkFile2() * @throws java.lang.Exception */ @Test - public void testLinkFile3() - throws Exception - { - File destDirectory = new File( getTestDirectory(), "foo/bar/testlink" ); - if ( destDirectory.exists() ) - { + public void testLinkFile3() throws Exception { + File destDirectory = new File(getTestDirectory(), "foo/bar/testlink"); + if (destDirectory.exists()) { destDirectory.delete(); } - final File destination = new File( destDirectory, "link2.txt" ); - FileUtils.linkFile( testFile1, destination ); - assertTrue( "Check Exist", destination.exists() ); - assertTrue( "Check File length", destination.length() == testFile2Size ); - assertTrue( "Check is link", Files.isSymbolicLink(destination.toPath())); + final File destination = new File(destDirectory, "link2.txt"); + FileUtils.linkFile(testFile1, destination); + assertTrue("Check Exist", destination.exists()); + assertTrue("Check File length", destination.length() == testFile2Size); + assertTrue("Check is link", Files.isSymbolicLink(destination.toPath())); } // copyFileIfModified @@ -575,26 +513,25 @@ public void testLinkFile3() * @throws java.lang.Exception if any. */ @Test - public void testCopyIfModifiedWhenSourceIsNewer() - throws Exception - { - FileUtils.forceMkdir( new File( getTestDirectory() + "/temp" ) ); + public void testCopyIfModifiedWhenSourceIsNewer() throws Exception { + FileUtils.forceMkdir(new File(getTestDirectory() + "/temp")); // Place destination - File destination = new File( getTestDirectory() + "/temp/copy1.txt" ); - FileUtils.copyFile( testFile1, destination ); + File destination = new File(getTestDirectory() + "/temp/copy1.txt"); + FileUtils.copyFile(testFile1, destination); // Make sure source is newer - reallySleep( 1000 ); + reallySleep(1000); // Place source - File source = new File( getTestDirectory(), "copy1.txt" ); - FileUtils.copyFile( testFile1, source ); - source.setLastModified( System.currentTimeMillis() ); + File source = new File(getTestDirectory(), "copy1.txt"); + FileUtils.copyFile(testFile1, source); + source.setLastModified(System.currentTimeMillis()); // Copy will occur when source is newer - assertTrue( "Failed copy. Target file should have been updated.", - FileUtils.copyFileIfModified( source, destination ) ); + assertTrue( + "Failed copy. Target file should have been updated.", + FileUtils.copyFileIfModified(source, destination)); } /** @@ -603,24 +540,22 @@ public void testCopyIfModifiedWhenSourceIsNewer() * @throws java.lang.Exception if any. */ @Test - public void testCopyIfModifiedWhenSourceIsOlder() - throws Exception - { - FileUtils.forceMkdir( new File( getTestDirectory() + "/temp" ) ); + public void testCopyIfModifiedWhenSourceIsOlder() throws Exception { + FileUtils.forceMkdir(new File(getTestDirectory() + "/temp")); // Place source - File source = new File( getTestDirectory() + "copy1.txt" ); - FileUtils.copyFile( testFile1, source ); + File source = new File(getTestDirectory() + "copy1.txt"); + FileUtils.copyFile(testFile1, source); // Make sure destination is newer - reallySleep( 1000 ); + reallySleep(1000); // Place destination - File destination = new File( getTestDirectory(), "/temp/copy1.txt" ); - FileUtils.copyFile( testFile1, destination ); + File destination = new File(getTestDirectory(), "/temp/copy1.txt"); + FileUtils.copyFile(testFile1, destination); // Copy will occur when destination is newer - assertFalse( "Source file should not have been copied.", FileUtils.copyFileIfModified( source, destination ) ); + assertFalse("Source file should not have been copied.", FileUtils.copyFileIfModified(source, destination)); } /** @@ -629,21 +564,19 @@ public void testCopyIfModifiedWhenSourceIsOlder() * @throws java.lang.Exception if any. */ @Test - public void testCopyIfModifiedWhenSourceHasZeroDate() - throws Exception - { - FileUtils.forceMkdir( new File( getTestDirectory(), "temp" ) ); + public void testCopyIfModifiedWhenSourceHasZeroDate() throws Exception { + FileUtils.forceMkdir(new File(getTestDirectory(), "temp")); // Source modified on 1970-01-01T00:00Z - File source = new File( getTestDirectory(), "copy1.txt" ); - FileUtils.copyFile( testFile1, source ); - source.setLastModified( 0L ); + File source = new File(getTestDirectory(), "copy1.txt"); + FileUtils.copyFile(testFile1, source); + source.setLastModified(0L); // A non existing destination - File destination = new File( getTestDirectory(), "temp/copy1.txt" ); + File destination = new File(getTestDirectory(), "temp/copy1.txt"); // Should copy the source to the non existing destination. - assertTrue( "Source file should have been copied.", FileUtils.copyFileIfModified( source, destination ) ); + assertTrue("Source file should have been copied.", FileUtils.copyFileIfModified(source, destination)); } // forceDelete @@ -654,14 +587,12 @@ public void testCopyIfModifiedWhenSourceHasZeroDate() * @throws java.lang.Exception if any. */ @Test - public void testForceDeleteAFile1() - throws Exception - { - final File destination = new File( getTestDirectory(), "copy1.txt" ); + public void testForceDeleteAFile1() throws Exception { + final File destination = new File(getTestDirectory(), "copy1.txt"); destination.createNewFile(); - assertTrue( "Copy1.txt doesn't exist to delete", destination.exists() ); - FileUtils.forceDelete( destination ); - assertTrue( "Check No Exist", !destination.exists() ); + assertTrue("Copy1.txt doesn't exist to delete", destination.exists()); + FileUtils.forceDelete(destination); + assertTrue("Check No Exist", !destination.exists()); } /** @@ -670,14 +601,12 @@ public void testForceDeleteAFile1() * @throws java.lang.Exception if any. */ @Test - public void testForceDeleteAFile2() - throws Exception - { - final File destination = new File( getTestDirectory(), "copy2.txt" ); + public void testForceDeleteAFile2() throws Exception { + final File destination = new File(getTestDirectory(), "copy2.txt"); destination.createNewFile(); - assertTrue( "Copy2.txt doesn't exist to delete", destination.exists() ); - FileUtils.forceDelete( destination ); - assertTrue( "Check No Exist", !destination.exists() ); + assertTrue("Copy2.txt doesn't exist to delete", destination.exists()); + FileUtils.forceDelete(destination); + assertTrue("Check No Exist", !destination.exists()); } // copyFileToDirectory @@ -688,18 +617,15 @@ public void testForceDeleteAFile2() * @throws java.lang.Exception if any. */ @Test - public void testCopyFile1ToDir() - throws Exception - { - final File directory = new File( getTestDirectory(), "subdir" ); - if ( !directory.exists() ) - { + public void testCopyFile1ToDir() throws Exception { + final File directory = new File(getTestDirectory(), "subdir"); + if (!directory.exists()) { directory.mkdirs(); } - final File destination = new File( directory, testFile1.getName() ); - FileUtils.copyFileToDirectory( testFile1, directory ); - assertTrue( "Check Exist", destination.exists() ); - assertTrue( "Check Full copy", destination.length() == testFile1Size ); + final File destination = new File(directory, testFile1.getName()); + FileUtils.copyFileToDirectory(testFile1, directory); + assertTrue("Check Exist", destination.exists()); + assertTrue("Check Full copy", destination.length() == testFile1Size); } /** @@ -708,18 +634,15 @@ public void testCopyFile1ToDir() * @throws java.lang.Exception if any. */ @Test - public void testCopyFile2ToDir() - throws Exception - { - final File directory = new File( getTestDirectory(), "subdir" ); - if ( !directory.exists() ) - { + public void testCopyFile2ToDir() throws Exception { + final File directory = new File(getTestDirectory(), "subdir"); + if (!directory.exists()) { directory.mkdirs(); } - final File destination = new File( directory, testFile1.getName() ); - FileUtils.copyFileToDirectory( testFile1, directory ); - assertTrue( "Check Exist", destination.exists() ); - assertTrue( "Check Full copy", destination.length() == testFile2Size ); + final File destination = new File(directory, testFile1.getName()); + FileUtils.copyFileToDirectory(testFile1, directory); + assertTrue("Check Exist", destination.exists()); + assertTrue("Check Full copy", destination.length() == testFile2Size); } // copyFileToDirectoryIfModified @@ -730,29 +653,26 @@ public void testCopyFile2ToDir() * @throws java.lang.Exception if any. */ @Test - public void testCopyFile1ToDirIfModified() - throws Exception - { - final File directory = new File( getTestDirectory(), "subdir" ); - if ( directory.exists() ) - { - FileUtils.forceDelete( directory ); + public void testCopyFile1ToDirIfModified() throws Exception { + final File directory = new File(getTestDirectory(), "subdir"); + if (directory.exists()) { + FileUtils.forceDelete(directory); } directory.mkdirs(); - final File destination = new File( directory, testFile1.getName() ); + final File destination = new File(directory, testFile1.getName()); - FileUtils.copyFileToDirectoryIfModified( testFile1, directory ); + FileUtils.copyFileToDirectoryIfModified(testFile1, directory); - final File target = new File( getTestDirectory() + "/subdir", testFile1.getName() ); + final File target = new File(getTestDirectory() + "/subdir", testFile1.getName()); long timestamp = target.lastModified(); - assertTrue( "Check Exist", destination.exists() ); - assertTrue( "Check Full copy", destination.length() == testFile1Size ); + assertTrue("Check Exist", destination.exists()); + assertTrue("Check Full copy", destination.length() == testFile1Size); - FileUtils.copyFileToDirectoryIfModified( testFile1, directory ); + FileUtils.copyFileToDirectoryIfModified(testFile1, directory); - assertTrue( "Timestamp was changed", timestamp == target.lastModified() ); + assertTrue("Timestamp was changed", timestamp == target.lastModified()); } /** @@ -761,29 +681,26 @@ public void testCopyFile1ToDirIfModified() * @throws java.lang.Exception if any. */ @Test - public void testCopyFile2ToDirIfModified() - throws Exception - { - final File directory = new File( getTestDirectory(), "subdir" ); - if ( directory.exists() ) - { - FileUtils.forceDelete( directory ); + public void testCopyFile2ToDirIfModified() throws Exception { + final File directory = new File(getTestDirectory(), "subdir"); + if (directory.exists()) { + FileUtils.forceDelete(directory); } directory.mkdirs(); - final File destination = new File( directory, testFile2.getName() ); + final File destination = new File(directory, testFile2.getName()); - FileUtils.copyFileToDirectoryIfModified( testFile2, directory ); + FileUtils.copyFileToDirectoryIfModified(testFile2, directory); - final File target = new File( getTestDirectory() + "/subdir", testFile2.getName() ); + final File target = new File(getTestDirectory() + "/subdir", testFile2.getName()); long timestamp = target.lastModified(); - assertTrue( "Check Exist", destination.exists() ); - assertTrue( "Check Full copy", destination.length() == testFile2Size ); + assertTrue("Check Exist", destination.exists()); + assertTrue("Check Full copy", destination.length() == testFile2Size); - FileUtils.copyFileToDirectoryIfModified( testFile2, directory ); + FileUtils.copyFileToDirectoryIfModified(testFile2, directory); - assertTrue( "Timestamp was changed", timestamp == target.lastModified() ); + assertTrue("Timestamp was changed", timestamp == target.lastModified()); } // forceDelete @@ -794,11 +711,9 @@ public void testCopyFile2ToDirIfModified() * @throws java.lang.Exception if any. */ @Test - public void testForceDeleteDir() - throws Exception - { - FileUtils.forceDelete( getTestDirectory().getParentFile() ); - assertTrue( "Check No Exist", !getTestDirectory().getParentFile().exists() ); + public void testForceDeleteDir() throws Exception { + FileUtils.forceDelete(getTestDirectory().getParentFile()); + assertTrue("Check No Exist", !getTestDirectory().getParentFile().exists()); } // resolveFile @@ -809,11 +724,9 @@ public void testForceDeleteDir() * @throws java.lang.Exception if any. */ @Test - public void testResolveFileDotDot() - throws Exception - { - final File file = FileUtils.resolveFile( getTestDirectory(), ".." ); - assertEquals( "Check .. operator", file, getTestDirectory().getParentFile() ); + public void testResolveFileDotDot() throws Exception { + final File file = FileUtils.resolveFile(getTestDirectory(), ".."); + assertEquals("Check .. operator", file, getTestDirectory().getParentFile()); } /** @@ -822,11 +735,9 @@ public void testResolveFileDotDot() * @throws java.lang.Exception if any. */ @Test - public void testResolveFileDot() - throws Exception - { - final File file = FileUtils.resolveFile( getTestDirectory(), "." ); - assertEquals( "Check . operator", file, getTestDirectory() ); + public void testResolveFileDot() throws Exception { + final File file = FileUtils.resolveFile(getTestDirectory(), "."); + assertEquals("Check . operator", file, getTestDirectory()); } // normalize @@ -837,36 +748,63 @@ public void testResolveFileDot() * @throws java.lang.Exception if any. */ @Test - public void testNormalize() - throws Exception - { - final String[] src = { "", "/", "///", "/foo", "/foo//", "/./", "/foo/./", "/foo/./bar", "/foo/../bar", - "/foo/../bar/../baz", "/foo/bar/../../baz", "/././", "/foo/./../bar", "/foo/.././bar/", "//foo//./bar", - "/../", "/foo/../../" }; - - final String[] dest = { "", "/", "/", "/foo", "/foo/", "/", "/foo/", "/foo/bar", "/bar", "/baz", "/baz", "/", - "/bar", "/bar/", "/foo/bar", null, null }; - - assertEquals( "Oops, test writer goofed", src.length, dest.length ); - - for ( int i = 0; i < src.length; i++ ) - { - assertEquals( "Check if '" + src[i] + "' normalized to '" + dest[i] + "'", dest[i], - FileUtils.normalize( src[i] ) ); + public void testNormalize() throws Exception { + final String[] src = { + "", + "/", + "///", + "/foo", + "/foo//", + "/./", + "/foo/./", + "/foo/./bar", + "/foo/../bar", + "/foo/../bar/../baz", + "/foo/bar/../../baz", + "/././", + "/foo/./../bar", + "/foo/.././bar/", + "//foo//./bar", + "/../", + "/foo/../../" + }; + + final String[] dest = { + "", + "/", + "/", + "/foo", + "/foo/", + "/", + "/foo/", + "/foo/bar", + "/bar", + "/baz", + "/baz", + "/", + "/bar", + "/bar/", + "/foo/bar", + null, + null + }; + + assertEquals("Oops, test writer goofed", src.length, dest.length); + + for (int i = 0; i < src.length; i++) { + assertEquals( + "Check if '" + src[i] + "' normalized to '" + dest[i] + "'", dest[i], FileUtils.normalize(src[i])); } } - private String replaceAll( String text, String lookFor, String replaceWith ) - { - StringBuilder sb = new StringBuilder( text ); - while ( true ) - { - int idx = sb.indexOf( lookFor ); - if ( idx < 0 ) - { + private String replaceAll(String text, String lookFor, String replaceWith) { + StringBuilder sb = new StringBuilder(text); + while (true) { + int idx = sb.indexOf(lookFor); + if (idx < 0) { break; } - sb.replace( idx, idx + lookFor.length(), replaceWith ); + sb.replace(idx, idx + lookFor.length(), replaceWith); } return sb.toString(); } @@ -878,54 +816,57 @@ private String replaceAll( String text, String lookFor, String replaceWith ) */ // Used to exist as IOTestCase class @Test - public void testFileUtils() - throws Exception - { + public void testFileUtils() throws Exception { // Loads file from classpath final String path = "/test.txt"; - final URL url = this.getClass().getResource( path ); - assertNotNull( path + " was not found.", url ); + final URL url = this.getClass().getResource(path); + assertNotNull(path + " was not found.", url); final String filename = Paths.get(url.toURI()).toString(); final String filename2 = "test2.txt"; - assertTrue( "test.txt extension == \"txt\"", FileUtils.getExtension( filename ).equals( "txt" ) ); + assertTrue( + "test.txt extension == \"txt\"", + FileUtils.getExtension(filename).equals("txt")); - assertTrue( "Test file does exist: " + filename, FileUtils.fileExists( filename ) ); + assertTrue("Test file does exist: " + filename, FileUtils.fileExists(filename)); - assertTrue( "Second test file does not exist", !FileUtils.fileExists( filename2 ) ); + assertTrue("Second test file does not exist", !FileUtils.fileExists(filename2)); - FileUtils.fileWrite( filename2, filename ); - assertTrue( "Second file was written", FileUtils.fileExists( filename2 ) ); + FileUtils.fileWrite(filename2, filename); + assertTrue("Second file was written", FileUtils.fileExists(filename2)); - final String file2contents = FileUtils.fileRead( filename2 ); - assertTrue( "Second file's contents correct", FileUtils.fileRead( filename2 ).equals( file2contents ) ); + final String file2contents = FileUtils.fileRead(filename2); + assertTrue( + "Second file's contents correct", FileUtils.fileRead(filename2).equals(file2contents)); - FileUtils.fileAppend( filename2, filename ); - assertTrue( "Second file's contents correct", - FileUtils.fileRead( filename2 ).equals( file2contents + file2contents ) ); + FileUtils.fileAppend(filename2, filename); + assertTrue( + "Second file's contents correct", FileUtils.fileRead(filename2).equals(file2contents + file2contents)); - FileUtils.fileDelete( filename2 ); - assertTrue( "Second test file does not exist", !FileUtils.fileExists( filename2 ) ); - - final String contents = FileUtils.fileRead( filename ); - assertTrue( "FileUtils.fileRead()", contents.equals( "This is a test" ) ); + FileUtils.fileDelete(filename2); + assertTrue("Second test file does not exist", !FileUtils.fileExists(filename2)); + final String contents = FileUtils.fileRead(filename); + assertTrue("FileUtils.fileRead()", contents.equals("This is a test")); } /** *

    testGetExtension.

    */ @Test - public void testGetExtension() - { - final String[][] tests = - { { "filename.ext", "ext" }, { "README", "" }, { "domain.dot.com", "com" }, { "image.jpeg", "jpeg" }, - { "folder" + File.separator + "image.jpeg", "jpeg" }, { "folder" + File.separator + "README", "" } }; - - for ( String[] test : tests ) - { - assertEquals( test[1], FileUtils.getExtension( test[0] ) ); + public void testGetExtension() { + final String[][] tests = { + {"filename.ext", "ext"}, + {"README", ""}, + {"domain.dot.com", "com"}, + {"image.jpeg", "jpeg"}, + {"folder" + File.separator + "image.jpeg", "jpeg"}, + {"folder" + File.separator + "README", ""} + }; + + for (String[] test : tests) { + assertEquals(test[1], FileUtils.getExtension(test[0])); // assertEquals(tests[i][1], FileUtils.extension(tests[i][0])); } } @@ -934,21 +875,22 @@ public void testGetExtension() *

    testGetExtensionWithPaths.

    */ @Test - public void testGetExtensionWithPaths() - { + public void testGetExtensionWithPaths() { // Since the utilities are based on the separator for the platform // running the test, ensure we are using the right separator final String sep = File.separator; - final String[][] testsWithPaths = { { sep + "tmp" + sep + "foo" + sep + "filename.ext", "ext" }, - { "C:" + sep + "temp" + sep + "foo" + sep + "filename.ext", "ext" }, - { "" + sep + "tmp" + sep + "foo.bar" + sep + "filename.ext", "ext" }, - { "C:" + sep + "temp" + sep + "foo.bar" + sep + "filename.ext", "ext" }, - { "" + sep + "tmp" + sep + "foo.bar" + sep + "README", "" }, - { "C:" + sep + "temp" + sep + "foo.bar" + sep + "README", "" }, { ".." + sep + "filename.ext", "ext" }, - { "blabla", "" } }; - for ( String[] testsWithPath : testsWithPaths ) - { - assertEquals( testsWithPath[1], FileUtils.getExtension( testsWithPath[0] ) ); + final String[][] testsWithPaths = { + {sep + "tmp" + sep + "foo" + sep + "filename.ext", "ext"}, + {"C:" + sep + "temp" + sep + "foo" + sep + "filename.ext", "ext"}, + {"" + sep + "tmp" + sep + "foo.bar" + sep + "filename.ext", "ext"}, + {"C:" + sep + "temp" + sep + "foo.bar" + sep + "filename.ext", "ext"}, + {"" + sep + "tmp" + sep + "foo.bar" + sep + "README", ""}, + {"C:" + sep + "temp" + sep + "foo.bar" + sep + "README", ""}, + {".." + sep + "filename.ext", "ext"}, + {"blabla", ""} + }; + for (String[] testsWithPath : testsWithPaths) { + assertEquals(testsWithPath[1], FileUtils.getExtension(testsWithPath[0])); // assertEquals(testsWithPaths[i][1], FileUtils.extension(testsWithPaths[i][0])); } } @@ -957,14 +899,17 @@ public void testGetExtensionWithPaths() *

    testRemoveExtension.

    */ @Test - public void testRemoveExtension() - { - final String[][] tests = { { "filename.ext", "filename" }, { "first.second.third.ext", "first.second.third" }, - { "README", "README" }, { "domain.dot.com", "domain.dot" }, { "image.jpeg", "image" } }; - - for ( String[] test : tests ) - { - assertEquals( test[1], FileUtils.removeExtension( test[0] ) ); + public void testRemoveExtension() { + final String[][] tests = { + {"filename.ext", "filename"}, + {"first.second.third.ext", "first.second.third"}, + {"README", "README"}, + {"domain.dot.com", "domain.dot"}, + {"image.jpeg", "image"} + }; + + for (String[] test : tests) { + assertEquals(test[1], FileUtils.removeExtension(test[0])); // assertEquals(tests[i][1], FileUtils.basename(tests[i][0])); } } @@ -974,26 +919,31 @@ public void testRemoveExtension() *

    testRemoveExtensionWithPaths.

    */ @Test - public void testRemoveExtensionWithPaths() - { + public void testRemoveExtensionWithPaths() { // Since the utilities are based on the separator for the platform // running the test, ensure we are using the right separator final String sep = File.separator; final String[][] testsWithPaths = { - { sep + "tmp" + sep + "foo" + sep + "filename.ext", sep + "tmp" + sep + "foo" + sep + "filename" }, - { "C:" + sep + "temp" + sep + "foo" + sep + "filename.ext", - "C:" + sep + "temp" + sep + "foo" + sep + "filename" }, - { sep + "tmp" + sep + "foo.bar" + sep + "filename.ext", sep + "tmp" + sep + "foo.bar" + sep + "filename" }, - { "C:" + sep + "temp" + sep + "foo.bar" + sep + "filename.ext", - "C:" + sep + "temp" + sep + "foo.bar" + sep + "filename" }, - { sep + "tmp" + sep + "foo.bar" + sep + "README", sep + "tmp" + sep + "foo.bar" + sep + "README" }, - { "C:" + sep + "temp" + sep + "foo.bar" + sep + "README", - "C:" + sep + "temp" + sep + "foo.bar" + sep + "README" }, - { ".." + sep + "filename.ext", ".." + sep + "filename" } }; - - for ( String[] testsWithPath : testsWithPaths ) - { - assertEquals( testsWithPath[1], FileUtils.removeExtension( testsWithPath[0] ) ); + {sep + "tmp" + sep + "foo" + sep + "filename.ext", sep + "tmp" + sep + "foo" + sep + "filename"}, + { + "C:" + sep + "temp" + sep + "foo" + sep + "filename.ext", + "C:" + sep + "temp" + sep + "foo" + sep + "filename" + }, + {sep + "tmp" + sep + "foo.bar" + sep + "filename.ext", sep + "tmp" + sep + "foo.bar" + sep + "filename"}, + { + "C:" + sep + "temp" + sep + "foo.bar" + sep + "filename.ext", + "C:" + sep + "temp" + sep + "foo.bar" + sep + "filename" + }, + {sep + "tmp" + sep + "foo.bar" + sep + "README", sep + "tmp" + sep + "foo.bar" + sep + "README"}, + { + "C:" + sep + "temp" + sep + "foo.bar" + sep + "README", + "C:" + sep + "temp" + sep + "foo.bar" + sep + "README" + }, + {".." + sep + "filename.ext", ".." + sep + "filename"} + }; + + for (String[] testsWithPath : testsWithPaths) { + assertEquals(testsWithPath[1], FileUtils.removeExtension(testsWithPath[0])); // assertEquals(testsWithPaths[i][1], FileUtils.basename(testsWithPaths[i][0])); } } @@ -1004,20 +954,18 @@ public void testRemoveExtensionWithPaths() * @throws java.lang.Exception if any. */ @Test - public void testCopyDirectoryStructureWithAEmptyDirectoryStructure() - throws Exception - { - File from = new File( getTestDirectory(), "from" ); + public void testCopyDirectoryStructureWithAEmptyDirectoryStructure() throws Exception { + File from = new File(getTestDirectory(), "from"); - FileUtils.deleteDirectory( from ); + FileUtils.deleteDirectory(from); - assertTrue( from.mkdirs() ); + assertTrue(from.mkdirs()); - File to = new File( getTestDirectory(), "to" ); + File to = new File(getTestDirectory(), "to"); - assertTrue( to.mkdirs() ); + assertTrue(to.mkdirs()); - FileUtils.copyDirectoryStructure( from, to ); + FileUtils.copyDirectoryStructure(from, to); } /** @@ -1026,63 +974,61 @@ public void testCopyDirectoryStructureWithAEmptyDirectoryStructure() * @throws java.lang.Exception if any. */ @Test - public void testCopyDirectoryStructureWithAPopulatedStructure() - throws Exception - { + public void testCopyDirectoryStructureWithAPopulatedStructure() throws Exception { // Make a structure to copy - File from = new File( getTestDirectory(), "from" ); + File from = new File(getTestDirectory(), "from"); - FileUtils.deleteDirectory( from ); + FileUtils.deleteDirectory(from); - File fRoot = new File( from, "root.txt" ); + File fRoot = new File(from, "root.txt"); - File d1 = new File( from, "1" ); + File d1 = new File(from, "1"); - File d1_1 = new File( d1, "1_1" ); + File d1_1 = new File(d1, "1_1"); - File d2 = new File( from, "2" ); + File d2 = new File(from, "2"); - File f2 = new File( d2, "2.txt" ); + File f2 = new File(d2, "2.txt"); - File d2_1 = new File( d2, "2_1" ); + File d2_1 = new File(d2, "2_1"); - File f2_1 = new File( d2_1, "2_1.txt" ); + File f2_1 = new File(d2_1, "2_1.txt"); - assertTrue( from.mkdir() ); + assertTrue(from.mkdir()); - assertTrue( d1.mkdir() ); + assertTrue(d1.mkdir()); - assertTrue( d1_1.mkdir() ); + assertTrue(d1_1.mkdir()); - assertTrue( d2.mkdir() ); + assertTrue(d2.mkdir()); - assertTrue( d2_1.mkdir() ); + assertTrue(d2_1.mkdir()); - createFile( fRoot, 100 ); + createFile(fRoot, 100); - createFile( f2, 100 ); + createFile(f2, 100); - createFile( f2_1, 100 ); + createFile(f2_1, 100); - File to = new File( getTestDirectory(), "to" ); + File to = new File(getTestDirectory(), "to"); - assertTrue( to.mkdirs() ); + assertTrue(to.mkdirs()); - FileUtils.copyDirectoryStructure( from, to ); + FileUtils.copyDirectoryStructure(from, to); - checkFile( fRoot, new File( to, "root.txt" ) ); + checkFile(fRoot, new File(to, "root.txt")); - assertIsDirectory( new File( to, "1" ) ); + assertIsDirectory(new File(to, "1")); - assertIsDirectory( new File( to, "1/1_1" ) ); + assertIsDirectory(new File(to, "1/1_1")); - assertIsDirectory( new File( to, "2" ) ); + assertIsDirectory(new File(to, "2")); - assertIsDirectory( new File( to, "2/2_1" ) ); + assertIsDirectory(new File(to, "2/2_1")); - checkFile( f2, new File( to, "2/2.txt" ) ); + checkFile(f2, new File(to, "2/2.txt")); - checkFile( f2_1, new File( to, "2/2_1/2_1.txt" ) ); + checkFile(f2_1, new File(to, "2/2_1/2_1.txt")); } /** @@ -1091,83 +1037,80 @@ public void testCopyDirectoryStructureWithAPopulatedStructure() * @throws java.lang.Exception if any. */ @Test - public void testCopyDirectoryStructureIfModified() - throws Exception - { + public void testCopyDirectoryStructureIfModified() throws Exception { // Make a structure to copy - File from = new File( getTestDirectory(), "from" ); + File from = new File(getTestDirectory(), "from"); - FileUtils.deleteDirectory( from ); + FileUtils.deleteDirectory(from); - File fRoot = new File( from, "root.txt" ); + File fRoot = new File(from, "root.txt"); - File d1 = new File( from, "1" ); + File d1 = new File(from, "1"); - File d1_1 = new File( d1, "1_1" ); + File d1_1 = new File(d1, "1_1"); - File d2 = new File( from, "2" ); + File d2 = new File(from, "2"); - File f2 = new File( d2, "2.txt" ); + File f2 = new File(d2, "2.txt"); - File d2_1 = new File( d2, "2_1" ); + File d2_1 = new File(d2, "2_1"); - File f2_1 = new File( d2_1, "2_1.txt" ); + File f2_1 = new File(d2_1, "2_1.txt"); - assertTrue( from.mkdir() ); + assertTrue(from.mkdir()); - assertTrue( d1.mkdir() ); + assertTrue(d1.mkdir()); - assertTrue( d1_1.mkdir() ); + assertTrue(d1_1.mkdir()); - assertTrue( d2.mkdir() ); + assertTrue(d2.mkdir()); - assertTrue( d2_1.mkdir() ); + assertTrue(d2_1.mkdir()); - createFile( fRoot, 100 ); + createFile(fRoot, 100); - createFile( f2, 100 ); + createFile(f2, 100); - createFile( f2_1, 100 ); + createFile(f2_1, 100); - File to = new File( getTestDirectory(), "to" ); + File to = new File(getTestDirectory(), "to"); - assertTrue( to.mkdirs() ); + assertTrue(to.mkdirs()); - FileUtils.copyDirectoryStructureIfModified( from, to ); + FileUtils.copyDirectoryStructureIfModified(from, to); - File files[] = { new File( to, "root.txt" ), new File( to, "2/2.txt" ), new File( to, "2/2_1/2_1.txt" ) }; + File files[] = {new File(to, "root.txt"), new File(to, "2/2.txt"), new File(to, "2/2_1/2_1.txt")}; - long timestamps[] = { files[0].lastModified(), files[1].lastModified(), files[2].lastModified() }; + long timestamps[] = {files[0].lastModified(), files[1].lastModified(), files[2].lastModified()}; - checkFile( fRoot, files[0] ); + checkFile(fRoot, files[0]); - assertIsDirectory( new File( to, "1" ) ); + assertIsDirectory(new File(to, "1")); - assertIsDirectory( new File( to, "1/1_1" ) ); + assertIsDirectory(new File(to, "1/1_1")); - assertIsDirectory( new File( to, "2" ) ); + assertIsDirectory(new File(to, "2")); - assertIsDirectory( new File( to, "2/2_1" ) ); + assertIsDirectory(new File(to, "2/2_1")); - checkFile( f2, files[1] ); + checkFile(f2, files[1]); - checkFile( f2_1, files[2] ); + checkFile(f2_1, files[2]); - FileUtils.copyDirectoryStructureIfModified( from, to ); + FileUtils.copyDirectoryStructureIfModified(from, to); - assertTrue( "Unmodified file was overwritten", timestamps[0] == files[0].lastModified() ); - assertTrue( "Unmodified file was overwritten", timestamps[1] == files[1].lastModified() ); - assertTrue( "Unmodified file was overwritten", timestamps[2] == files[2].lastModified() ); + assertTrue("Unmodified file was overwritten", timestamps[0] == files[0].lastModified()); + assertTrue("Unmodified file was overwritten", timestamps[1] == files[1].lastModified()); + assertTrue("Unmodified file was overwritten", timestamps[2] == files[2].lastModified()); - files[1].setLastModified( f2.lastModified() - 5000L ); + files[1].setLastModified(f2.lastModified() - 5000L); timestamps[1] = files[1].lastModified(); - FileUtils.copyDirectoryStructureIfModified( from, to ); - - assertTrue( "Unmodified file was overwritten", timestamps[0] == files[0].lastModified() ); - assertTrue( "Outdated file was not overwritten", timestamps[1] < files[1].lastModified() ); - assertTrue( "Unmodified file was overwritten", timestamps[2] == files[2].lastModified() ); + FileUtils.copyDirectoryStructureIfModified(from, to); + assertTrue("Unmodified file was overwritten", timestamps[0] == files[0].lastModified()); + assertTrue("Outdated file was not overwritten", timestamps[1] < files[1].lastModified()); + assertTrue("Unmodified file was overwritten", timestamps[2] == files[2].lastModified()); } /** @@ -1176,43 +1119,38 @@ public void testCopyDirectoryStructureIfModified() * @throws java.lang.Exception if any. */ @Test - public void testCopyDirectoryStructureToSelf() - throws Exception - { + public void testCopyDirectoryStructureToSelf() throws Exception { // Make a structure to copy - File toFrom = new File( getTestDirectory(), "tofrom" ); + File toFrom = new File(getTestDirectory(), "tofrom"); - FileUtils.deleteDirectory( toFrom ); + FileUtils.deleteDirectory(toFrom); - File fRoot = new File( toFrom, "root.txt" ); + File fRoot = new File(toFrom, "root.txt"); - File dSub = new File( toFrom, "subdir" ); + File dSub = new File(toFrom, "subdir"); - File f1 = new File( dSub, "notempty.txt" ); + File f1 = new File(dSub, "notempty.txt"); - File dSubSub = new File( dSub, "subsubdir" ); + File dSubSub = new File(dSub, "subsubdir"); - File f2 = new File( dSubSub, "notemptytoo.txt" ); + File f2 = new File(dSubSub, "notemptytoo.txt"); - assertTrue( toFrom.mkdir() ); + assertTrue(toFrom.mkdir()); - assertTrue( dSub.mkdir() ); + assertTrue(dSub.mkdir()); - assertTrue( dSubSub.mkdir() ); + assertTrue(dSubSub.mkdir()); - createFile( fRoot, 100 ); + createFile(fRoot, 100); - createFile( f1, 100 ); + createFile(f1, 100); - createFile( f2, 100 ); + createFile(f2, 100); - try - { - FileUtils.copyDirectoryStructure( toFrom, toFrom ); - fail( "An exception must be thrown." ); - } - catch ( IOException e ) - { + try { + FileUtils.copyDirectoryStructure(toFrom, toFrom); + fail("An exception must be thrown."); + } catch (IOException e) { // expected } } @@ -1223,31 +1161,29 @@ public void testCopyDirectoryStructureToSelf() * @throws java.lang.Exception if any. */ @Test - public void testFilteredFileCopy() - throws Exception - { - File compareFile = new File( getTestDirectory(), "compare.txt" ); - FileUtils.fileWrite( compareFile.getAbsolutePath(), "UTF-8", "This is a test. Test sample text\n" ); + public void testFilteredFileCopy() throws Exception { + File compareFile = new File(getTestDirectory(), "compare.txt"); + FileUtils.fileWrite(compareFile.getAbsolutePath(), "UTF-8", "This is a test. Test sample text\n"); - File destFile = new File( getTestDirectory(), "target.txt" ); + File destFile = new File(getTestDirectory(), "target.txt"); final Properties filterProperties = new Properties(); - filterProperties.setProperty( "s", "sample text" ); + filterProperties.setProperty("s", "sample text"); // test ${token} - FileUtils.FilterWrapper[] wrappers1 = new FileUtils.FilterWrapper[] { new FileUtils.FilterWrapper() - { - public Reader getReader( Reader reader ) - { - return new InterpolationFilterReader( reader, filterProperties, "${", "}" ); + FileUtils.FilterWrapper[] wrappers1 = new FileUtils.FilterWrapper[] { + new FileUtils.FilterWrapper() { + public Reader getReader(Reader reader) { + return new InterpolationFilterReader(reader, filterProperties, "${", "}"); + } } - } }; + }; - File srcFile = new File( getTestDirectory(), "root.txt" ); - FileUtils.fileWrite( srcFile.getAbsolutePath(), "UTF-8", "This is a test. Test ${s}\n" ); + File srcFile = new File(getTestDirectory(), "root.txt"); + FileUtils.fileWrite(srcFile.getAbsolutePath(), "UTF-8", "This is a test. Test ${s}\n"); - FileUtils.copyFile( srcFile, destFile, "UTF-8", wrappers1 ); - assertTrue( "Files should be equal.", FileUtils.contentEquals( compareFile, destFile ) ); + FileUtils.copyFile(srcFile, destFile, "UTF-8", wrappers1); + assertTrue("Files should be equal.", FileUtils.contentEquals(compareFile, destFile)); srcFile.delete(); destFile.delete(); @@ -1260,33 +1196,29 @@ public Reader getReader( Reader reader ) * @throws java.lang.Exception if any. */ @Test - public void testFilteredWithoutFilterAndOlderFile() - throws Exception - { + public void testFilteredWithoutFilterAndOlderFile() throws Exception { String content = "This is a test."; - File sourceFile = new File( getTestDirectory(), "source.txt" ); - FileUtils.fileWrite( sourceFile.getAbsolutePath(), "UTF-8", content ); + File sourceFile = new File(getTestDirectory(), "source.txt"); + FileUtils.fileWrite(sourceFile.getAbsolutePath(), "UTF-8", content); - File destFile = new File( getTestDirectory(), "target.txt" ); - if ( destFile.exists() ) - { + File destFile = new File(getTestDirectory(), "target.txt"); + if (destFile.exists()) { destFile.delete(); } - FileUtils.copyFile( sourceFile, destFile, null, null ); - assertEqualContent( content.getBytes( "UTF-8" ), destFile ); + FileUtils.copyFile(sourceFile, destFile, null, null); + assertEqualContent(content.getBytes("UTF-8"), destFile); String newercontent = "oldercontent"; - File olderFile = new File( getTestDirectory(), "oldersource.txt" ); + File olderFile = new File(getTestDirectory(), "oldersource.txt"); - FileUtils.fileWrite( olderFile.getAbsolutePath(), "UTF-8", newercontent ); + FileUtils.fileWrite(olderFile.getAbsolutePath(), "UTF-8", newercontent); // very old file ;-) - olderFile.setLastModified( 1 ); - destFile = new File( getTestDirectory(), "target.txt" ); - FileUtils.copyFile( olderFile, destFile, null, null ); - String destFileContent = FileUtils.fileRead( destFile, "UTF-8" ); - assertEquals( content, destFileContent ); - + olderFile.setLastModified(1); + destFile = new File(getTestDirectory(), "target.txt"); + FileUtils.copyFile(olderFile, destFile, null, null); + String destFileContent = FileUtils.fileRead(destFile, "UTF-8"); + assertEquals(content, destFileContent); } /** @@ -1295,33 +1227,29 @@ public void testFilteredWithoutFilterAndOlderFile() * @throws java.lang.Exception if any. */ @Test - public void testFilteredWithoutFilterAndOlderFileAndOverwrite() - throws Exception - { + public void testFilteredWithoutFilterAndOlderFileAndOverwrite() throws Exception { String content = "This is a test."; - File sourceFile = new File( getTestDirectory(), "source.txt" ); - FileUtils.fileWrite( sourceFile.getAbsolutePath(), "UTF-8", content ); + File sourceFile = new File(getTestDirectory(), "source.txt"); + FileUtils.fileWrite(sourceFile.getAbsolutePath(), "UTF-8", content); - File destFile = new File( getTestDirectory(), "target.txt" ); - if ( destFile.exists() ) - { + File destFile = new File(getTestDirectory(), "target.txt"); + if (destFile.exists()) { destFile.delete(); } - FileUtils.copyFile( sourceFile, destFile, null, null ); - assertEqualContent( content.getBytes( "UTF-8" ), destFile ); + FileUtils.copyFile(sourceFile, destFile, null, null); + assertEqualContent(content.getBytes("UTF-8"), destFile); String newercontent = "oldercontent"; - File olderFile = new File( getTestDirectory(), "oldersource.txt" ); + File olderFile = new File(getTestDirectory(), "oldersource.txt"); - FileUtils.fileWrite( olderFile.getAbsolutePath(), "UTF-8", newercontent ); + FileUtils.fileWrite(olderFile.getAbsolutePath(), "UTF-8", newercontent); // very old file ;-) - olderFile.setLastModified( 1 ); - destFile = new File( getTestDirectory(), "target.txt" ); - FileUtils.copyFile( olderFile, destFile, null, null, true ); - String destFileContent = FileUtils.fileRead( destFile, "UTF-8" ); - assertEquals( newercontent, destFileContent ); - + olderFile.setLastModified(1); + destFile = new File(getTestDirectory(), "target.txt"); + FileUtils.copyFile(olderFile, destFile, null, null, true); + String destFileContent = FileUtils.fileRead(destFile, "UTF-8"); + assertEquals(newercontent, destFileContent); } /** @@ -1330,10 +1258,8 @@ public void testFilteredWithoutFilterAndOlderFileAndOverwrite() * @throws java.io.IOException if any. */ @Test - public void testFileRead() - throws IOException - { - File testFile = new File( getTestDirectory(), "testFileRead.txt" ); + public void testFileRead() throws IOException { + File testFile = new File(getTestDirectory(), "testFileRead.txt"); String testFileName = testFile.getAbsolutePath(); /* * NOTE: The method under test uses the JVM's default encoding which by its nature varies from machine to @@ -1343,18 +1269,15 @@ public void testFileRead() */ String testString = "Only US-ASCII characters here, see comment above!"; Writer writer = null; - try - { - writer = new OutputStreamWriter( Files.newOutputStream( testFile.toPath() ) ); - writer.write( testString ); + try { + writer = new OutputStreamWriter(Files.newOutputStream(testFile.toPath())); + writer.write(testString); writer.flush(); + } finally { + IOUtil.close(writer); } - finally - { - IOUtil.close( writer ); - } - assertEquals( "testString should be equal", testString, FileUtils.fileRead( testFile ) ); - assertEquals( "testString should be equal", testString, FileUtils.fileRead( testFileName ) ); + assertEquals("testString should be equal", testString, FileUtils.fileRead(testFile)); + assertEquals("testString should be equal", testString, FileUtils.fileRead(testFileName)); testFile.delete(); } @@ -1364,27 +1287,22 @@ public void testFileRead() * @throws java.io.IOException if any. */ @Test - public void testFileReadWithEncoding() - throws IOException - { + public void testFileReadWithEncoding() throws IOException { String encoding = "UTF-8"; - File testFile = new File( getTestDirectory(), "testFileRead.txt" ); + File testFile = new File(getTestDirectory(), "testFileRead.txt"); String testFileName = testFile.getAbsolutePath(); // unicode escaped Japanese hiragana, "aiueo" + Umlaut a String testString = "\u3042\u3044\u3046\u3048\u304a\u00e4"; Writer writer = null; - try - { - writer = new OutputStreamWriter( Files.newOutputStream( testFile.toPath() ), encoding ); - writer.write( testString ); + try { + writer = new OutputStreamWriter(Files.newOutputStream(testFile.toPath()), encoding); + writer.write(testString); writer.flush(); + } finally { + IOUtil.close(writer); } - finally - { - IOUtil.close( writer ); - } - assertEquals( "testString should be equal", testString, FileUtils.fileRead( testFile, "UTF-8" ) ); - assertEquals( "testString should be equal", testString, FileUtils.fileRead( testFileName, "UTF-8" ) ); + assertEquals("testString should be equal", testString, FileUtils.fileRead(testFile, "UTF-8")); + assertEquals("testString should be equal", testString, FileUtils.fileRead(testFileName, "UTF-8")); testFile.delete(); } @@ -1394,27 +1312,22 @@ public void testFileReadWithEncoding() * @throws java.io.IOException if any. */ @Test - public void testFileAppend() - throws IOException - { + public void testFileAppend() throws IOException { String baseString = "abc"; - File testFile = new File( getTestDirectory(), "testFileAppend.txt" ); + File testFile = new File(getTestDirectory(), "testFileAppend.txt"); String testFileName = testFile.getAbsolutePath(); Writer writer = null; - try - { - writer = new OutputStreamWriter( Files.newOutputStream( testFile.toPath() ) ); - writer.write( baseString ); + try { + writer = new OutputStreamWriter(Files.newOutputStream(testFile.toPath())); + writer.write(baseString); writer.flush(); - } - finally - { - IOUtil.close( writer ); + } finally { + IOUtil.close(writer); } // unicode escaped Japanese hiragana, "aiueo" + Umlaut a String testString = "\u3042\u3044\u3046\u3048\u304a\u00e4"; - FileUtils.fileAppend( testFileName, testString ); - assertEqualContent( ( baseString + testString ).getBytes(), testFile ); + FileUtils.fileAppend(testFileName, testString); + assertEqualContent((baseString + testString).getBytes(), testFile); testFile.delete(); } @@ -1424,28 +1337,23 @@ public void testFileAppend() * @throws java.io.IOException if any. */ @Test - public void testFileAppendWithEncoding() - throws IOException - { + public void testFileAppendWithEncoding() throws IOException { String baseString = "abc"; String encoding = "UTF-8"; - File testFile = new File( getTestDirectory(), "testFileAppend.txt" ); + File testFile = new File(getTestDirectory(), "testFileAppend.txt"); String testFileName = testFile.getAbsolutePath(); Writer writer = null; - try - { - writer = new OutputStreamWriter( Files.newOutputStream( testFile.toPath() ), encoding ); - writer.write( baseString ); + try { + writer = new OutputStreamWriter(Files.newOutputStream(testFile.toPath()), encoding); + writer.write(baseString); writer.flush(); - } - finally - { - IOUtil.close( writer ); + } finally { + IOUtil.close(writer); } // unicode escaped Japanese hiragana, "aiueo" + Umlaut a String testString = "\u3042\u3044\u3046\u3048\u304a\u00e4"; - FileUtils.fileAppend( testFileName, encoding, testString ); - assertEqualContent( ( baseString + testString ).getBytes( encoding ), testFile ); + FileUtils.fileAppend(testFileName, encoding, testString); + assertEqualContent((baseString + testString).getBytes(encoding), testFile); testFile.delete(); } @@ -1455,15 +1363,13 @@ public void testFileAppendWithEncoding() * @throws java.io.IOException if any. */ @Test - public void testFileWrite() - throws IOException - { - File testFile = new File( getTestDirectory(), "testFileWrite.txt" ); + public void testFileWrite() throws IOException { + File testFile = new File(getTestDirectory(), "testFileWrite.txt"); String testFileName = testFile.getAbsolutePath(); // unicode escaped Japanese hiragana, "aiueo" + Umlaut a String testString = "\u3042\u3044\u3046\u3048\u304a\u00e4"; - FileUtils.fileWrite( testFileName, testString ); - assertEqualContent( testString.getBytes(), testFile ); + FileUtils.fileWrite(testFileName, testString); + assertEqualContent(testString.getBytes(), testFile); testFile.delete(); } @@ -1473,16 +1379,14 @@ public void testFileWrite() * @throws java.io.IOException if any. */ @Test - public void testFileWriteWithEncoding() - throws IOException - { + public void testFileWriteWithEncoding() throws IOException { String encoding = "UTF-8"; - File testFile = new File( getTestDirectory(), "testFileWrite.txt" ); + File testFile = new File(getTestDirectory(), "testFileWrite.txt"); String testFileName = testFile.getAbsolutePath(); // unicode escaped Japanese hiragana, "aiueo" + Umlaut a String testString = "\u3042\u3044\u3046\u3048\u304a\u00e4"; - FileUtils.fileWrite( testFileName, encoding, testString ); - assertEqualContent( testString.getBytes( encoding ), testFile ); + FileUtils.fileWrite(testFileName, encoding, testString); + assertEqualContent(testString.getBytes(encoding), testFile); testFile.delete(); } @@ -1495,39 +1399,34 @@ public void testFileWriteWithEncoding() * @see Sun bug id=6481955 */ @Test - public void testDeleteLongPathOnWindows() - throws Exception - { - if ( !Os.isFamily( Os.FAMILY_WINDOWS ) ) - { + public void testDeleteLongPathOnWindows() throws Exception { + if (!Os.isFamily(Os.FAMILY_WINDOWS)) { return; } - File a = new File( getTestDirectory(), "longpath" ); + File a = new File(getTestDirectory(), "longpath"); a.mkdir(); - File a1 = new File( a, "a" ); + File a1 = new File(a, "a"); a1.mkdir(); - StringBuilder path = new StringBuilder( "" ); - for ( int i = 0; i < 100; i++ ) - { - path.append( "../a/" ); + StringBuilder path = new StringBuilder(""); + for (int i = 0; i < 100; i++) { + path.append("../a/"); } - File f = new File( a1, path.toString() + "test.txt" ); + File f = new File(a1, path.toString() + "test.txt"); - InputStream is = new ByteArrayInputStream( "Blabla".getBytes( "UTF-8" ) ); - OutputStream os = Files.newOutputStream( f.getCanonicalFile().toPath() ); - IOUtil.copy( is, os ); - IOUtil.close( is ); - IOUtil.close( os ); + InputStream is = new ByteArrayInputStream("Blabla".getBytes("UTF-8")); + OutputStream os = Files.newOutputStream(f.getCanonicalFile().toPath()); + IOUtil.copy(is, os); + IOUtil.close(is); + IOUtil.close(os); - FileUtils.forceDelete( f ); + FileUtils.forceDelete(f); - File f1 = new File( a1, "test.txt" ); - if ( f1.exists() ) - { - throw new Exception( "Unable to delete the file :" + f1.getAbsolutePath() ); + File f1 = new File(a1, "test.txt"); + if (f1.exists()) { + throw new Exception("Unable to delete the file :" + f1.getAbsolutePath()); } } @@ -1538,20 +1437,18 @@ public void testDeleteLongPathOnWindows() * @throws java.io.IOException if any. */ @Test - public void testCopyFileOnSameFile() - throws IOException - { + public void testCopyFileOnSameFile() throws IOException { String content = "ggrgreeeeeeeeeeeeeeeeeeeeeeeoierjgioejrgiojregioejrgufcdxivbsdibgfizgerfyaezgv!zeez"; - final File theFile = File.createTempFile( "test", ".txt" ); + final File theFile = File.createTempFile("test", ".txt"); theFile.deleteOnExit(); - FileUtils.fileAppend( theFile.getAbsolutePath(), content ); + FileUtils.fileAppend(theFile.getAbsolutePath(), content); - assertTrue( theFile.length() > 0 ); + assertTrue(theFile.length() > 0); // Now copy file over itself - FileUtils.copyFile( theFile, theFile ); + FileUtils.copyFile(theFile, theFile); // This should not fail - assertTrue( theFile.length() > 0 ); + assertTrue(theFile.length() > 0); } /** @@ -1560,22 +1457,26 @@ public void testCopyFileOnSameFile() * @throws java.lang.Exception if any. */ @Test - public void testExtensions() - throws Exception - { - - String[][] values = - { { "fry.frozen", "frozen" }, { "fry", "" }, { "fry.", "" }, { "/turanga/leela/meets.fry", "fry" }, - { "/3000/turanga.leela.fry/zoidberg.helps", "helps" }, { "/3000/turanga.leela.fry/zoidberg.", "" }, - { "/3000/turanga.leela.fry/zoidberg", "" }, { "/3000/leela.fry.bender/", "" }, - { "/3000/leela.fry.bdner/.", "" }, { "/3000/leela.fry.bdner/foo.bar.txt", "txt" } }; - - for ( int i = 0; i < values.length; i++ ) - { - String fileName = values[i][0].replace( '/', File.separatorChar ); + public void testExtensions() throws Exception { + + String[][] values = { + {"fry.frozen", "frozen"}, + {"fry", ""}, + {"fry.", ""}, + {"/turanga/leela/meets.fry", "fry"}, + {"/3000/turanga.leela.fry/zoidberg.helps", "helps"}, + {"/3000/turanga.leela.fry/zoidberg.", ""}, + {"/3000/turanga.leela.fry/zoidberg", ""}, + {"/3000/leela.fry.bender/", ""}, + {"/3000/leela.fry.bdner/.", ""}, + {"/3000/leela.fry.bdner/foo.bar.txt", "txt"} + }; + + for (int i = 0; i < values.length; i++) { + String fileName = values[i][0].replace('/', File.separatorChar); String ext = values[i][1]; - String computed = FileUtils.extension( fileName ); - assertEquals( "case [" + i + "]:" + fileName + " -> " + ext + ", computed : " + computed, ext, computed ); + String computed = FileUtils.extension(fileName); + assertEquals("case [" + i + "]:" + fileName + " -> " + ext + ", computed : " + computed, ext, computed); } } @@ -1585,28 +1486,25 @@ public void testExtensions() * @throws java.lang.Exception if any. */ @Test - public void testIsValidWindowsFileName() - throws Exception - { - File f = new File( "c:\test" ); - assertTrue( FileUtils.isValidWindowsFileName( f ) ); - - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - f = new File( "c:\test\bla:bla" ); - assertFalse( FileUtils.isValidWindowsFileName( f ) ); - f = new File( "c:\test\bla*bla" ); - assertFalse( FileUtils.isValidWindowsFileName( f ) ); - f = new File( "c:\test\bla\"bla" ); - assertFalse( FileUtils.isValidWindowsFileName( f ) ); - f = new File( "c:\test\blabla" ); - assertFalse( FileUtils.isValidWindowsFileName( f ) ); - f = new File( "c:\test\bla|bla" ); - assertFalse( FileUtils.isValidWindowsFileName( f ) ); - f = new File( "c:\test\bla*bla" ); - assertFalse( FileUtils.isValidWindowsFileName( f ) ); + public void testIsValidWindowsFileName() throws Exception { + File f = new File("c:\test"); + assertTrue(FileUtils.isValidWindowsFileName(f)); + + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + f = new File("c:\test\bla:bla"); + assertFalse(FileUtils.isValidWindowsFileName(f)); + f = new File("c:\test\bla*bla"); + assertFalse(FileUtils.isValidWindowsFileName(f)); + f = new File("c:\test\bla\"bla"); + assertFalse(FileUtils.isValidWindowsFileName(f)); + f = new File("c:\test\blabla"); + assertFalse(FileUtils.isValidWindowsFileName(f)); + f = new File("c:\test\bla|bla"); + assertFalse(FileUtils.isValidWindowsFileName(f)); + f = new File("c:\test\bla*bla"); + assertFalse(FileUtils.isValidWindowsFileName(f)); } } @@ -1616,25 +1514,20 @@ public void testIsValidWindowsFileName() * @throws java.lang.Exception if any. */ @Test - public void testDeleteDirectoryWithValidFileSymlink() - throws Exception - { - File symlinkTarget = new File( getTestDirectory(), "fileSymlinkTarget" ); - createFile( symlinkTarget, 1 ); - File symlink = new File( getTestDirectory(), "fileSymlink" ); - createSymlink( symlink, symlinkTarget ); - try - { - FileUtils.deleteDirectory( getTestDirectory() ); - } - finally - { + public void testDeleteDirectoryWithValidFileSymlink() throws Exception { + File symlinkTarget = new File(getTestDirectory(), "fileSymlinkTarget"); + createFile(symlinkTarget, 1); + File symlink = new File(getTestDirectory(), "fileSymlink"); + createSymlink(symlink, symlinkTarget); + try { + FileUtils.deleteDirectory(getTestDirectory()); + } finally { /* * Ensure to cleanup problematic symlink or "mvn clean" will fail */ symlink.delete(); } - assertTrue( "Failed to delete test directory", !getTestDirectory().exists() ); + assertTrue("Failed to delete test directory", !getTestDirectory().exists()); } /** @@ -1643,25 +1536,20 @@ public void testDeleteDirectoryWithValidFileSymlink() * @throws java.lang.Exception if any. */ @Test - public void testDeleteDirectoryWithValidDirSymlink() - throws Exception - { - File symlinkTarget = new File( getTestDirectory(), "dirSymlinkTarget" ); + public void testDeleteDirectoryWithValidDirSymlink() throws Exception { + File symlinkTarget = new File(getTestDirectory(), "dirSymlinkTarget"); symlinkTarget.mkdir(); - File symlink = new File( getTestDirectory(), "dirSymlink" ); - createSymlink( symlink, symlinkTarget ); - try - { - FileUtils.deleteDirectory( getTestDirectory() ); - } - finally - { + File symlink = new File(getTestDirectory(), "dirSymlink"); + createSymlink(symlink, symlinkTarget); + try { + FileUtils.deleteDirectory(getTestDirectory()); + } finally { /* * Ensure to cleanup problematic symlink or "mvn clean" will fail */ symlink.delete(); } - assertTrue( "Failed to delete test directory", !getTestDirectory().exists() ); + assertTrue("Failed to delete test directory", !getTestDirectory().exists()); } /** @@ -1670,24 +1558,19 @@ public void testDeleteDirectoryWithValidDirSymlink() * @throws java.lang.Exception if any. */ @Test - public void testDeleteDirectoryWithDanglingSymlink() - throws Exception - { - File symlinkTarget = new File( getTestDirectory(), "missingSymlinkTarget" ); - File symlink = new File( getTestDirectory(), "danglingSymlink" ); - createSymlink( symlink, symlinkTarget ); - try - { - FileUtils.deleteDirectory( getTestDirectory() ); - } - finally - { + public void testDeleteDirectoryWithDanglingSymlink() throws Exception { + File symlinkTarget = new File(getTestDirectory(), "missingSymlinkTarget"); + File symlink = new File(getTestDirectory(), "danglingSymlink"); + createSymlink(symlink, symlinkTarget); + try { + FileUtils.deleteDirectory(getTestDirectory()); + } finally { /* * Ensure to cleanup problematic symlink or "mvn clean" will fail */ symlink.delete(); } - assertTrue( "Failed to delete test directory", !getTestDirectory().exists() ); + assertTrue("Failed to delete test directory", !getTestDirectory().exists()); } /** @@ -1696,38 +1579,30 @@ public void testDeleteDirectoryWithDanglingSymlink() * @throws java.lang.Exception if any. */ @Test - public void testcopyDirectoryLayoutWithExcludesIncludes() - throws Exception - { - File destination = new File( "target", "copyDirectoryStructureWithExcludesIncludes" ); - if ( !destination.exists() ) - { + public void testcopyDirectoryLayoutWithExcludesIncludes() throws Exception { + File destination = new File("target", "copyDirectoryStructureWithExcludesIncludes"); + if (!destination.exists()) { destination.mkdirs(); } - FileUtils.cleanDirectory( destination ); + FileUtils.cleanDirectory(destination); - File source = new File( "src/test/resources/dir-layout-copy" ); + File source = new File("src/test/resources/dir-layout-copy"); - FileUtils.copyDirectoryLayout( source, destination, null, null ); + FileUtils.copyDirectoryLayout(source, destination, null, null); - assertTrue( destination.exists() ); + assertTrue(destination.exists()); File[] childs = destination.listFiles(); - assertEquals( 2, childs.length ); + assertEquals(2, childs.length); - for ( File current : childs ) - { - if ( current.getName().endsWith( "empty-dir" ) || current.getName().endsWith( "dir1" ) ) - { - if ( current.getName().endsWith( "dir1" ) ) - { - assertEquals( 1, current.listFiles().length ); - assertTrue( current.listFiles()[0].getName().endsWith( "dir2" ) ); + for (File current : childs) { + if (current.getName().endsWith("empty-dir") || current.getName().endsWith("dir1")) { + if (current.getName().endsWith("dir1")) { + assertEquals(1, current.listFiles().length); + assertTrue(current.listFiles()[0].getName().endsWith("dir2")); } - } - else - { - fail( "not empty-dir or dir1" ); + } else { + fail("not empty-dir or dir1"); } } } @@ -1738,14 +1613,12 @@ public void testcopyDirectoryLayoutWithExcludesIncludes() * @throws java.lang.Exception if any */ @Test - public void testCreateTempFile() - throws Exception - { - File last = FileUtils.createTempFile( "unique", ".tmp", null ); - for ( int i = 0; i < 10; i++ ) - { - File current = FileUtils.createTempFile( "unique", ".tmp", null ); - assertTrue( "No unique name: " + current.getName(), !current.getName().equals( last.getName() ) ); + public void testCreateTempFile() throws Exception { + File last = FileUtils.createTempFile("unique", ".tmp", null); + for (int i = 0; i < 10; i++) { + File current = FileUtils.createTempFile("unique", ".tmp", null); + assertTrue( + "No unique name: " + current.getName(), !current.getName().equals(last.getName())); last = current; } } @@ -1756,14 +1629,11 @@ public void testCreateTempFile() * @param time The amount of time to sleep * @throws InterruptedException */ - private void reallySleep( int time ) - throws InterruptedException - { + private void reallySleep(int time) throws InterruptedException { long until = System.currentTimeMillis() + time; - Thread.sleep( time ); - while ( System.currentTimeMillis() < until ) - { - Thread.sleep( time / 10 ); + Thread.sleep(time); + while (System.currentTimeMillis() < until) { + Thread.sleep(time / 10); Thread.yield(); } } diff --git a/src/test/java/org/codehaus/plexus/util/IOUtilTest.java b/src/test/java/org/codehaus/plexus/util/IOUtilTest.java index 4179a20e..f235c495 100644 --- a/src/test/java/org/codehaus/plexus/util/IOUtilTest.java +++ b/src/test/java/org/codehaus/plexus/util/IOUtilTest.java @@ -16,10 +16,6 @@ * 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.IOException; @@ -35,6 +31,10 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** * This is used to test IOUtil for correctness. The following checks are performed: *
      @@ -50,8 +50,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public final class IOUtilTest -{ +public final class IOUtilTest { /* * Note: this is not particularly beautiful code. A better way to check for flush and close status would be to * implement "trojan horse" wrapper implementations of the various stream classes, which set a flag when relevant @@ -68,94 +67,79 @@ public final class IOUtilTest *

      setUp.

      */ @Before - public void setUp() - { - try - { - testDirectory = ( new File( "target/test/io/" ) ).getAbsoluteFile(); - if ( !testDirectory.exists() ) - { + public void setUp() { + try { + testDirectory = (new File("target/test/io/")).getAbsoluteFile(); + if (!testDirectory.exists()) { testDirectory.mkdirs(); } - testFile = new File( testDirectory, "file2-test.txt" ); + testFile = new File(testDirectory, "file2-test.txt"); - createFile( testFile, FILE_SIZE ); - } - catch ( IOException ioe ) - { - throw new RuntimeException( "Can't run this test because environment could not be built" ); + createFile(testFile, FILE_SIZE); + } catch (IOException ioe) { + throw new RuntimeException("Can't run this test because environment could not be built"); } } /** *

      tearDown.

      */ - public void tearDown() - { + public void tearDown() { testFile.delete(); testDirectory.delete(); } - private void createFile( File file, long size ) - throws IOException - { - BufferedOutputStream output = new BufferedOutputStream( Files.newOutputStream( file.toPath() ) ); + private void createFile(File file, long size) throws IOException { + BufferedOutputStream output = new BufferedOutputStream(Files.newOutputStream(file.toPath())); - for ( int i = 0; i < size; i++ ) - { - output.write( (byte) ( i % 128 ) ); // nice varied byte pattern compatible with Readers and Writers + for (int i = 0; i < size; i++) { + output.write((byte) (i % 128)); // nice varied byte pattern compatible with Readers and Writers } output.close(); } /** Assert that the contents of two byte arrays are the same. */ - private void assertEqualContent( byte[] b0, byte[] b1 ) - { - assertTrue( "Content not equal according to java.util.Arrays#equals()", Arrays.equals( b0, b1 ) ); + private void assertEqualContent(byte[] b0, byte[] b1) { + assertTrue("Content not equal according to java.util.Arrays#equals()", Arrays.equals(b0, b1)); } /** Assert that the content of two files is the same. */ - private void assertEqualContent( File f0, File f1 ) - throws IOException - { - InputStream is0 = Files.newInputStream( f0.toPath() ); - InputStream is1 = Files.newInputStream( f1.toPath() ); + private void assertEqualContent(File f0, File f1) throws IOException { + InputStream is0 = Files.newInputStream(f0.toPath()); + InputStream is1 = Files.newInputStream(f1.toPath()); byte[] buf0 = new byte[FILE_SIZE]; byte[] buf1 = new byte[FILE_SIZE]; int n0 = 0; int n1 = 0; - try - { - while ( 0 <= n0 ) - { - n0 = is0.read( buf0 ); - n1 = is1.read( buf1 ); - assertTrue( "The files " + f0 + " and " + f1 + " have differing number of bytes available (" + n0 - + " vs " + n1 + ")", ( n0 == n1 ) ); + try { + while (0 <= n0) { + n0 = is0.read(buf0); + n1 = is1.read(buf1); + assertTrue( + "The files " + f0 + " and " + f1 + " have differing number of bytes available (" + n0 + " vs " + + n1 + ")", + (n0 == n1)); - assertTrue( "The files " + f0 + " and " + f1 + " have different content", Arrays.equals( buf0, buf1 ) ); + assertTrue("The files " + f0 + " and " + f1 + " have different content", Arrays.equals(buf0, buf1)); } - } - finally - { + } finally { is0.close(); is1.close(); } } /** Assert that the content of a file is equal to that in a byte[]. */ - private void assertEqualContent( byte[] b0, File file ) - throws IOException - { - InputStream is = Files.newInputStream( file.toPath() ); + private void assertEqualContent(byte[] b0, File file) throws IOException { + InputStream is = Files.newInputStream(file.toPath()); byte[] b1 = new byte[b0.length]; - int numRead = is.read( b1 ); - assertTrue( "Different number of bytes", numRead == b0.length && is.available() == 0 ); - for ( int i = 0; i < numRead; assertTrue( "Byte " + i + " differs (" + b0[i] + " != " + b1[i] + ")", - b0[i] == b1[i] ), i++ ) + int numRead = is.read(b1); + assertTrue("Different number of bytes", numRead == b0.length && is.available() == 0); + for (int i = 0; + i < numRead; + assertTrue("Byte " + i + " differs (" + b0[i] + " != " + b1[i] + ")", b0[i] == b1[i]), i++) ; is.close(); } @@ -166,22 +150,20 @@ private void assertEqualContent( byte[] b0, File file ) * @throws java.lang.Exception if any. */ @Test - public void testInputStreamToOutputStream() - throws Exception - { - File destination = newFile( "copy1.txt" ); - InputStream fin = Files.newInputStream( testFile.toPath() ); - OutputStream fout = Files.newOutputStream( destination.toPath() ); - - IOUtil.copy( fin, fout ); - assertTrue( "Not all bytes were read", fin.available() == 0 ); + public void testInputStreamToOutputStream() throws Exception { + File destination = newFile("copy1.txt"); + InputStream fin = Files.newInputStream(testFile.toPath()); + OutputStream fout = Files.newOutputStream(destination.toPath()); + + IOUtil.copy(fin, fout); + assertTrue("Not all bytes were read", fin.available() == 0); fout.flush(); - checkFile( destination ); - checkWrite( fout ); + checkFile(destination); + checkWrite(fout); fout.close(); fin.close(); - deleteFile( destination ); + deleteFile(destination); } /** @@ -190,23 +172,21 @@ public void testInputStreamToOutputStream() * @throws java.lang.Exception if any. */ @Test - public void testInputStreamToWriter() - throws Exception - { - File destination = newFile( "copy2.txt" ); - InputStream fin = Files.newInputStream( testFile.toPath() ); - Writer fout = Files.newBufferedWriter( destination.toPath() ); + public void testInputStreamToWriter() throws Exception { + File destination = newFile("copy2.txt"); + InputStream fin = Files.newInputStream(testFile.toPath()); + Writer fout = Files.newBufferedWriter(destination.toPath()); - IOUtil.copy( fin, fout ); + IOUtil.copy(fin, fout); - assertTrue( "Not all bytes were read", fin.available() == 0 ); + assertTrue("Not all bytes were read", fin.available() == 0); fout.flush(); - checkFile( destination ); - checkWrite( fout ); + checkFile(destination); + checkWrite(fout); fout.close(); fin.close(); - deleteFile( destination ); + deleteFile(destination); } /** @@ -215,14 +195,12 @@ public void testInputStreamToWriter() * @throws java.lang.Exception if any. */ @Test - public void testInputStreamToString() - throws Exception - { - InputStream fin = Files.newInputStream( testFile.toPath() ); - String out = IOUtil.toString( fin ); - assertNotNull( out ); - assertTrue( "Not all bytes were read", fin.available() == 0 ); - assertTrue( "Wrong output size: out.length()=" + out.length() + "!=" + FILE_SIZE, out.length() == FILE_SIZE ); + public void testInputStreamToString() throws Exception { + InputStream fin = Files.newInputStream(testFile.toPath()); + String out = IOUtil.toString(fin); + assertNotNull(out); + assertTrue("Not all bytes were read", fin.available() == 0); + assertTrue("Wrong output size: out.length()=" + out.length() + "!=" + FILE_SIZE, out.length() == FILE_SIZE); fin.close(); } @@ -232,13 +210,11 @@ public void testInputStreamToString() * @throws java.lang.Exception if any. */ @Test - public void testReaderToOutputStream() - throws Exception - { - File destination = newFile( "copy3.txt" ); - Reader fin = Files.newBufferedReader( testFile.toPath() ); - OutputStream fout = Files.newOutputStream( destination.toPath() ); - IOUtil.copy( fin, fout ); + public void testReaderToOutputStream() throws Exception { + File destination = newFile("copy3.txt"); + Reader fin = Files.newBufferedReader(testFile.toPath()); + OutputStream fout = Files.newOutputStream(destination.toPath()); + IOUtil.copy(fin, fout); // Note: this method *does* flush. It is equivalent to: // OutputStreamWriter _out = new OutputStreamWriter(fout); // IOUtil.copy( fin, _out, 4096 ); // copy( Reader, Writer, int ); @@ -246,11 +222,11 @@ public void testReaderToOutputStream() // out = fout; // Note: rely on the method to flush - checkFile( destination ); - checkWrite( fout ); + checkFile(destination); + checkWrite(fout); fout.close(); fin.close(); - deleteFile( destination ); + deleteFile(destination); } /** @@ -259,20 +235,18 @@ public void testReaderToOutputStream() * @throws java.lang.Exception if any. */ @Test - public void testReaderToWriter() - throws Exception - { - File destination = newFile( "copy4.txt" ); - Reader fin = Files.newBufferedReader( testFile.toPath() ); - Writer fout = Files.newBufferedWriter( destination.toPath() ); - IOUtil.copy( fin, fout ); + public void testReaderToWriter() throws Exception { + File destination = newFile("copy4.txt"); + Reader fin = Files.newBufferedReader(testFile.toPath()); + Writer fout = Files.newBufferedWriter(destination.toPath()); + IOUtil.copy(fin, fout); fout.flush(); - checkFile( destination ); - checkWrite( fout ); + checkFile(destination); + checkWrite(fout); fout.close(); fin.close(); - deleteFile( destination ); + deleteFile(destination); } /** @@ -281,13 +255,11 @@ public void testReaderToWriter() * @throws java.lang.Exception if any. */ @Test - public void testReaderToString() - throws Exception - { - Reader fin = Files.newBufferedReader( testFile.toPath() ); - String out = IOUtil.toString( fin ); - assertNotNull( out ); - assertTrue( "Wrong output size: out.length()=" + out.length() + "!=" + FILE_SIZE, out.length() == FILE_SIZE ); + public void testReaderToString() throws Exception { + Reader fin = Files.newBufferedReader(testFile.toPath()); + String out = IOUtil.toString(fin); + assertNotNull(out); + assertTrue("Wrong output size: out.length()=" + out.length() + "!=" + FILE_SIZE, out.length() == FILE_SIZE); fin.close(); } @@ -297,15 +269,13 @@ public void testReaderToString() * @throws java.lang.Exception if any. */ @Test - public void testStringToOutputStream() - throws Exception - { - File destination = newFile( "copy5.txt" ); - Reader fin = Files.newBufferedReader( testFile.toPath() ); + public void testStringToOutputStream() throws Exception { + File destination = newFile("copy5.txt"); + Reader fin = Files.newBufferedReader(testFile.toPath()); // Create our String. Rely on testReaderToString() to make sure this is valid. - String str = IOUtil.toString( fin ); - OutputStream fout = Files.newOutputStream( destination.toPath() ); - IOUtil.copy( str, fout ); + String str = IOUtil.toString(fin); + OutputStream fout = Files.newOutputStream(destination.toPath()); + IOUtil.copy(str, fout); // Note: this method *does* flush. It is equivalent to: // OutputStreamWriter _out = new OutputStreamWriter(fout); // IOUtil.copy( str, _out, 4096 ); // copy( Reader, Writer, int ); @@ -313,11 +283,11 @@ public void testStringToOutputStream() // out = fout; // note: we don't flush here; this IOUtils method does it for us - checkFile( destination ); - checkWrite( fout ); + checkFile(destination); + checkWrite(fout); fout.close(); fin.close(); - deleteFile( destination ); + deleteFile(destination); } /** @@ -326,23 +296,21 @@ public void testStringToOutputStream() * @throws java.lang.Exception if any. */ @Test - public void testStringToWriter() - throws Exception - { - File destination = newFile( "copy6.txt" ); - Reader fin = Files.newBufferedReader( testFile.toPath() ); + public void testStringToWriter() throws Exception { + File destination = newFile("copy6.txt"); + Reader fin = Files.newBufferedReader(testFile.toPath()); // Create our String. Rely on testReaderToString() to make sure this is valid. - String str = IOUtil.toString( fin ); - Writer fout = Files.newBufferedWriter( destination.toPath() ); - IOUtil.copy( str, fout ); + String str = IOUtil.toString(fin); + Writer fout = Files.newBufferedWriter(destination.toPath()); + IOUtil.copy(str, fout); fout.flush(); - checkFile( destination ); - checkWrite( fout ); + checkFile(destination); + checkWrite(fout); fout.close(); fin.close(); - deleteFile( destination ); + deleteFile(destination); } /** @@ -351,15 +319,13 @@ public void testStringToWriter() * @throws java.lang.Exception if any. */ @Test - public void testInputStreamToByteArray() - throws Exception - { - InputStream fin = Files.newInputStream( testFile.toPath() ); - byte[] out = IOUtil.toByteArray( fin ); - assertNotNull( out ); - assertTrue( "Not all bytes were read", fin.available() == 0 ); - assertTrue( "Wrong output size: out.length=" + out.length + "!=" + FILE_SIZE, out.length == FILE_SIZE ); - assertEqualContent( out, testFile ); + public void testInputStreamToByteArray() throws Exception { + InputStream fin = Files.newInputStream(testFile.toPath()); + byte[] out = IOUtil.toByteArray(fin); + assertNotNull(out); + assertTrue("Not all bytes were read", fin.available() == 0); + assertTrue("Wrong output size: out.length=" + out.length + "!=" + FILE_SIZE, out.length == FILE_SIZE); + assertEqualContent(out, testFile); fin.close(); } @@ -369,16 +335,14 @@ public void testInputStreamToByteArray() * @throws java.lang.Exception if any. */ @Test - public void testStringToByteArray() - throws Exception - { - Reader fin = Files.newBufferedReader( testFile.toPath() ); + public void testStringToByteArray() throws Exception { + Reader fin = Files.newBufferedReader(testFile.toPath()); // Create our String. Rely on testReaderToString() to make sure this is valid. - String str = IOUtil.toString( fin ); + String str = IOUtil.toString(fin); - byte[] out = IOUtil.toByteArray( str ); - assertEqualContent( str.getBytes(), out ); + byte[] out = IOUtil.toByteArray(str); + assertEqualContent(str.getBytes(), out); fin.close(); } @@ -388,22 +352,20 @@ public void testStringToByteArray() * @throws java.lang.Exception if any. */ @Test - public void testByteArrayToWriter() - throws Exception - { - File destination = newFile( "copy7.txt" ); - Writer fout = Files.newBufferedWriter( destination.toPath() ); - InputStream fin = Files.newInputStream( testFile.toPath() ); + public void testByteArrayToWriter() throws Exception { + File destination = newFile("copy7.txt"); + Writer fout = Files.newBufferedWriter(destination.toPath()); + InputStream fin = Files.newInputStream(testFile.toPath()); // Create our byte[]. Rely on testInputStreamToByteArray() to make sure this is valid. - byte[] in = IOUtil.toByteArray( fin ); - IOUtil.copy( in, fout ); + byte[] in = IOUtil.toByteArray(fin); + IOUtil.copy(in, fout); fout.flush(); - checkFile( destination ); - checkWrite( fout ); + checkFile(destination); + checkWrite(fout); fout.close(); fin.close(); - deleteFile( destination ); + deleteFile(destination); } /** @@ -412,14 +374,12 @@ public void testByteArrayToWriter() * @throws java.lang.Exception if any. */ @Test - public void testByteArrayToString() - throws Exception - { - InputStream fin = Files.newInputStream( testFile.toPath() ); - byte[] in = IOUtil.toByteArray( fin ); + public void testByteArrayToString() throws Exception { + InputStream fin = Files.newInputStream(testFile.toPath()); + byte[] in = IOUtil.toByteArray(fin); // Create our byte[]. Rely on testInputStreamToByteArray() to make sure this is valid. - String str = IOUtil.toString( in ); - assertEqualContent( in, str.getBytes() ); + String str = IOUtil.toString(in); + assertEqualContent(in, str.getBytes()); fin.close(); } @@ -429,25 +389,23 @@ public void testByteArrayToString() * @throws java.lang.Exception if any. */ @Test - public void testByteArrayToOutputStream() - throws Exception - { - File destination = newFile( "copy8.txt" ); - OutputStream fout = Files.newOutputStream( destination.toPath() ); - InputStream fin = Files.newInputStream( testFile.toPath() ); + public void testByteArrayToOutputStream() throws Exception { + File destination = newFile("copy8.txt"); + OutputStream fout = Files.newOutputStream(destination.toPath()); + InputStream fin = Files.newInputStream(testFile.toPath()); // Create our byte[]. Rely on testInputStreamToByteArray() to make sure this is valid. - byte[] in = IOUtil.toByteArray( fin ); + byte[] in = IOUtil.toByteArray(fin); - IOUtil.copy( in, fout ); + IOUtil.copy(in, fout); fout.flush(); - checkFile( destination ); - checkWrite( fout ); + checkFile(destination); + checkWrite(fout); fout.close(); fin.close(); - deleteFile( destination ); + deleteFile(destination); } // ---------------------------------------------------------------------- @@ -460,16 +418,14 @@ public void testByteArrayToOutputStream() * @throws java.lang.Exception if any. */ @Test - public void testCloseInputStream() - throws Exception - { - IOUtil.close( (InputStream) null ); + public void testCloseInputStream() throws Exception { + IOUtil.close((InputStream) null); TestInputStream inputStream = new TestInputStream(); - IOUtil.close( inputStream ); + IOUtil.close(inputStream); - assertTrue( inputStream.closed ); + assertTrue(inputStream.closed); } /** @@ -478,16 +434,14 @@ public void testCloseInputStream() * @throws java.lang.Exception if any. */ @Test - public void testCloseOutputStream() - throws Exception - { - IOUtil.close( (OutputStream) null ); + public void testCloseOutputStream() throws Exception { + IOUtil.close((OutputStream) null); TestOutputStream outputStream = new TestOutputStream(); - IOUtil.close( outputStream ); + IOUtil.close(outputStream); - assertTrue( outputStream.closed ); + assertTrue(outputStream.closed); } /** @@ -496,16 +450,14 @@ public void testCloseOutputStream() * @throws java.lang.Exception if any. */ @Test - public void testCloseReader() - throws Exception - { - IOUtil.close( (Reader) null ); + public void testCloseReader() throws Exception { + IOUtil.close((Reader) null); TestReader reader = new TestReader(); - IOUtil.close( reader ); + IOUtil.close(reader); - assertTrue( reader.closed ); + assertTrue(reader.closed); } /** @@ -514,88 +466,69 @@ public void testCloseReader() * @throws java.lang.Exception if any. */ @Test - public void testCloseWriter() - throws Exception - { - IOUtil.close( (Writer) null ); + public void testCloseWriter() throws Exception { + IOUtil.close((Writer) null); TestWriter writer = new TestWriter(); - IOUtil.close( writer ); + IOUtil.close(writer); - assertTrue( writer.closed ); + assertTrue(writer.closed); } - private class TestInputStream - extends InputStream - { + private class TestInputStream extends InputStream { boolean closed; - public void close() - { + public void close() { closed = true; } - public int read() - { - fail( "This method shouldn't be called" ); + public int read() { + fail("This method shouldn't be called"); return 0; } } - private class TestOutputStream - extends OutputStream - { + private class TestOutputStream extends OutputStream { boolean closed; - public void close() - { + public void close() { closed = true; } - public void write( int value ) - { - fail( "This method shouldn't be called" ); + public void write(int value) { + fail("This method shouldn't be called"); } } - private class TestReader - extends Reader - { + private class TestReader extends Reader { boolean closed; - public void close() - { + public void close() { closed = true; } - public int read( char cbuf[], int off, int len ) - { - fail( "This method shouldn't be called" ); + public int read(char cbuf[], int off, int len) { + fail("This method shouldn't be called"); return 0; } } - private class TestWriter - extends Writer - { + private class TestWriter extends Writer { boolean closed; - public void close() - { + public void close() { closed = true; } - public void write( char cbuf[], int off, int len ) - { - fail( "This method shouldn't be called" ); + public void write(char cbuf[], int off, int len) { + fail("This method shouldn't be called"); } - public void flush() - { - fail( "This method shouldn't be called" ); + public void flush() { + fail("This method shouldn't be called"); } } @@ -603,56 +536,39 @@ public void flush() // Utility methods // ---------------------------------------------------------------------- - private File newFile( String filename ) - throws Exception - { - File destination = new File( testDirectory, filename ); - assertTrue( filename + "Test output data file shouldn't previously exist", !destination.exists() ); + private File newFile(String filename) throws Exception { + File destination = new File(testDirectory, filename); + assertTrue(filename + "Test output data file shouldn't previously exist", !destination.exists()); return destination; } - private void checkFile( File file ) - throws Exception - { - assertTrue( "Check existence of output file", file.exists() ); - assertEqualContent( testFile, file ); + private void checkFile(File file) throws Exception { + assertTrue("Check existence of output file", file.exists()); + assertEqualContent(testFile, file); } - private void checkWrite( OutputStream output ) - throws Exception - { - try - { - new PrintStream( output ).write( 0 ); - } - catch ( Throwable t ) - { - throw new Exception( "The copy() method closed the stream " + "when it shouldn't have. " - + t.getMessage() ); + private void checkWrite(OutputStream output) throws Exception { + try { + new PrintStream(output).write(0); + } catch (Throwable t) { + throw new Exception("The copy() method closed the stream " + "when it shouldn't have. " + t.getMessage()); } } - private void checkWrite( Writer output ) - throws Exception - { - try - { - new PrintWriter( output ).write( 'a' ); - } - catch ( Throwable t ) - { - throw new Exception( "The copy() method closed the stream " + "when it shouldn't have. " - + t.getMessage() ); + private void checkWrite(Writer output) throws Exception { + try { + new PrintWriter(output).write('a'); + } catch (Throwable t) { + throw new Exception("The copy() method closed the stream " + "when it shouldn't have. " + t.getMessage()); } } - private void deleteFile( File file ) - throws Exception - { - assertTrue( "Wrong output size: file.length()=" + file.length() + "!=" + FILE_SIZE + 1, - file.length() == FILE_SIZE + 1 ); + private void deleteFile(File file) throws Exception { + assertTrue( + "Wrong output size: file.length()=" + file.length() + "!=" + FILE_SIZE + 1, + file.length() == FILE_SIZE + 1); - assertTrue( "File would not delete", ( file.delete() || ( !file.exists() ) ) ); + assertTrue("File would not delete", (file.delete() || (!file.exists()))); } } diff --git a/src/test/java/org/codehaus/plexus/util/InterpolationFilterReaderTest.java b/src/test/java/org/codehaus/plexus/util/InterpolationFilterReaderTest.java index 1d190b4d..66cec400 100644 --- a/src/test/java/org/codehaus/plexus/util/InterpolationFilterReaderTest.java +++ b/src/test/java/org/codehaus/plexus/util/InterpolationFilterReaderTest.java @@ -16,14 +16,14 @@ * limitations under the License. */ -import static org.junit.Assert.assertEquals; - import java.io.StringReader; import java.util.HashMap; import java.util.Map; import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** *

      InterpolationFilterReaderTest class.

      * @@ -31,8 +31,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class InterpolationFilterReaderTest -{ +public class InterpolationFilterReaderTest { /* * Added and commented by jdcasey@03-Feb-2005 because it is a bug in the InterpolationFilterReader. * kenneyw@15-04-2005 fixed the bug. @@ -43,15 +42,13 @@ public class InterpolationFilterReaderTest * @throws java.lang.Exception if any. */ @Test - public void testShouldNotInterpolateExpressionAtEndOfDataWithInvalidEndToken() - throws Exception - { + public void testShouldNotInterpolateExpressionAtEndOfDataWithInvalidEndToken() throws Exception { Map m = new HashMap(); - m.put( "test", "TestValue" ); + m.put("test", "TestValue"); String testStr = "This is a ${test"; - assertEquals( "This is a ${test", interpolate( testStr, m ) ); + assertEquals("This is a ${test", interpolate(testStr, m)); } /* @@ -63,15 +60,13 @@ public void testShouldNotInterpolateExpressionAtEndOfDataWithInvalidEndToken() * @throws java.lang.Exception if any. */ @Test - public void testShouldNotInterpolateExpressionWithMissingEndToken() - throws Exception - { + public void testShouldNotInterpolateExpressionWithMissingEndToken() throws Exception { Map m = new HashMap(); - m.put( "test", "TestValue" ); + m.put("test", "TestValue"); String testStr = "This is a ${test, really"; - assertEquals( "This is a ${test, really", interpolate( testStr, m ) ); + assertEquals("This is a ${test, really", interpolate(testStr, m)); } /** @@ -80,15 +75,13 @@ public void testShouldNotInterpolateExpressionWithMissingEndToken() * @throws java.lang.Exception if any. */ @Test - public void testShouldNotInterpolateWithMalformedStartToken() - throws Exception - { + public void testShouldNotInterpolateWithMalformedStartToken() throws Exception { Map m = new HashMap(); - m.put( "test", "testValue" ); + m.put("test", "testValue"); String foo = "This is a $!test} again"; - assertEquals( "This is a $!test} again", interpolate( foo, m ) ); + assertEquals("This is a $!test} again", interpolate(foo, m)); } /** @@ -97,15 +90,13 @@ public void testShouldNotInterpolateWithMalformedStartToken() * @throws java.lang.Exception if any. */ @Test - public void testShouldNotInterpolateWithMalformedEndToken() - throws Exception - { + public void testShouldNotInterpolateWithMalformedEndToken() throws Exception { Map m = new HashMap(); - m.put( "test", "testValue" ); + m.put("test", "testValue"); String foo = "This is a ${test!} again"; - assertEquals( "This is a ${test!} again", interpolate( foo, m, "${", "$}" ) ); + assertEquals("This is a ${test!} again", interpolate(foo, m, "${", "$}")); } /** @@ -114,15 +105,13 @@ public void testShouldNotInterpolateWithMalformedEndToken() * @throws java.lang.Exception if any. */ @Test - public void testInterpolationWithMulticharDelimiters() - throws Exception - { + public void testInterpolationWithMulticharDelimiters() throws Exception { Map m = new HashMap(); - m.put( "test", "testValue" ); + m.put("test", "testValue"); String foo = "This is a ${test$} again"; - assertEquals( "This is a testValue again", interpolate( foo, m, "${", "$}" ) ); + assertEquals("This is a testValue again", interpolate(foo, m, "${", "$}")); } /** @@ -131,16 +120,14 @@ public void testInterpolationWithMulticharDelimiters() * @throws java.lang.Exception if any. */ @Test - public void testDefaultInterpolationWithNonInterpolatedValueAtEnd() - throws Exception - { + public void testDefaultInterpolationWithNonInterpolatedValueAtEnd() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "${name} is an ${noun}. ${not.interpolated}"; - assertEquals( "jason is an asshole. ${not.interpolated}", interpolate( foo, m ) ); + assertEquals("jason is an asshole. ${not.interpolated}", interpolate(foo, m)); } /** @@ -149,16 +136,14 @@ public void testDefaultInterpolationWithNonInterpolatedValueAtEnd() * @throws java.lang.Exception if any. */ @Test - public void testDefaultInterpolationWithInterpolatedValueAtEnd() - throws Exception - { + public void testDefaultInterpolationWithInterpolatedValueAtEnd() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "${name} is an ${noun}"; - assertEquals( "jason is an asshole", interpolate( foo, m ) ); + assertEquals("jason is an asshole", interpolate(foo, m)); } /** @@ -167,16 +152,14 @@ public void testDefaultInterpolationWithInterpolatedValueAtEnd() * @throws java.lang.Exception if any. */ @Test - public void testInterpolationWithSpecifiedBoundaryTokens() - throws Exception - { + public void testInterpolationWithSpecifiedBoundaryTokens() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "@name@ is an @noun@. @not.interpolated@ baby @foo@. @bar@"; - assertEquals( "jason is an asshole. @not.interpolated@ baby @foo@. @bar@", interpolate( foo, m, "@", "@" ) ); + assertEquals("jason is an asshole. @not.interpolated@ baby @foo@. @bar@", interpolate(foo, m, "@", "@")); } /** @@ -185,16 +168,14 @@ public void testInterpolationWithSpecifiedBoundaryTokens() * @throws java.lang.Exception if any. */ @Test - public void testInterpolationWithSpecifiedBoundaryTokensWithNonInterpolatedValueAtEnd() - throws Exception - { + public void testInterpolationWithSpecifiedBoundaryTokensWithNonInterpolatedValueAtEnd() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "@name@ is an @foobarred@"; - assertEquals( "jason is an @foobarred@", interpolate( foo, m, "@", "@" ) ); + assertEquals("jason is an @foobarred@", interpolate(foo, m, "@", "@")); } /** @@ -203,16 +184,14 @@ public void testInterpolationWithSpecifiedBoundaryTokensWithNonInterpolatedValue * @throws java.lang.Exception if any. */ @Test - public void testInterpolationWithSpecifiedBoundaryTokensWithInterpolatedValueAtEnd() - throws Exception - { + public void testInterpolationWithSpecifiedBoundaryTokensWithInterpolatedValueAtEnd() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "@name@ is an @noun@"; - assertEquals( "jason is an asshole", interpolate( foo, m, "@", "@" ) ); + assertEquals("jason is an asshole", interpolate(foo, m, "@", "@")); } /** @@ -221,32 +200,25 @@ public void testInterpolationWithSpecifiedBoundaryTokensWithInterpolatedValueAtE * @throws java.lang.Exception if any. */ @Test - public void testInterpolationWithSpecifiedBoundaryTokensAndAdditionalTokenCharacter() - throws Exception - { + public void testInterpolationWithSpecifiedBoundaryTokensAndAdditionalTokenCharacter() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "@name@ (known as jason@somewhere) is an @noun@"; - assertEquals( "jason (known as jason@somewhere) is an asshole", interpolate( foo, m, "@", "@" ) ); + assertEquals("jason (known as jason@somewhere) is an asshole", interpolate(foo, m, "@", "@")); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - private String interpolate( String input, Map context ) - throws Exception - { - return IOUtil.toString( new InterpolationFilterReader( new StringReader( input ), context ) ); + private String interpolate(String input, Map context) throws Exception { + return IOUtil.toString(new InterpolationFilterReader(new StringReader(input), context)); } - private String interpolate( String input, Map context, String startToken, String endToken ) - throws Exception - { - return IOUtil.toString( new InterpolationFilterReader( new StringReader( input ), context, startToken, - endToken ) ); + private String interpolate(String input, Map context, String startToken, String endToken) throws Exception { + return IOUtil.toString(new InterpolationFilterReader(new StringReader(input), context, startToken, endToken)); } } diff --git a/src/test/java/org/codehaus/plexus/util/LineOrientedInterpolatingReaderTest.java b/src/test/java/org/codehaus/plexus/util/LineOrientedInterpolatingReaderTest.java index 6ff112db..77f82fcc 100644 --- a/src/test/java/org/codehaus/plexus/util/LineOrientedInterpolatingReaderTest.java +++ b/src/test/java/org/codehaus/plexus/util/LineOrientedInterpolatingReaderTest.java @@ -16,8 +16,6 @@ * limitations under the License. */ -import static org.junit.Assert.assertEquals; - import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; @@ -28,6 +26,8 @@ import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** * 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. @@ -36,8 +36,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class LineOrientedInterpolatingReaderTest -{ +public class LineOrientedInterpolatingReaderTest { /* * Added and commented by jdcasey@03-Feb-2005 because it is a bug in the InterpolationFilterReader. */ @@ -47,18 +46,15 @@ public class LineOrientedInterpolatingReaderTest * @throws java.io.IOException if any. */ @Test - public void testShouldInterpolateExpressionAtEndOfDataWithInvalidEndToken() - throws IOException - { + public void testShouldInterpolateExpressionAtEndOfDataWithInvalidEndToken() throws IOException { String testStr = "This is a ${test"; - LineOrientedInterpolatingReader iReader = - new LineOrientedInterpolatingReader( new StringReader( testStr ), - Collections.singletonMap( "test", "TestValue" ) ); - BufferedReader reader = new BufferedReader( iReader ); + LineOrientedInterpolatingReader iReader = new LineOrientedInterpolatingReader( + new StringReader(testStr), Collections.singletonMap("test", "TestValue")); + BufferedReader reader = new BufferedReader(iReader); String result = reader.readLine(); - assertEquals( "This is a ${test", result ); + assertEquals("This is a ${test", result); } /** @@ -67,27 +63,24 @@ public void testShouldInterpolateExpressionAtEndOfDataWithInvalidEndToken() * @throws java.lang.Exception if any. */ @Test - public void testDefaultInterpolationWithNonInterpolatedValueAtEnd() - throws Exception - { + public void testDefaultInterpolationWithNonInterpolatedValueAtEnd() throws Exception { Map m = getStandardMap(); String foo = "${name} is an ${noun}. ${not.interpolated}"; - LineOrientedInterpolatingReader reader = new LineOrientedInterpolatingReader( new StringReader( foo ), m ); + LineOrientedInterpolatingReader reader = new LineOrientedInterpolatingReader(new StringReader(foo), m); StringWriter writer = new StringWriter(); - IOUtil.copy( reader, writer ); + IOUtil.copy(reader, writer); String bar = writer.toString(); - assertEquals( "jason is an asshole. ${not.interpolated}", bar ); + assertEquals("jason is an asshole. ${not.interpolated}", bar); } - private Map getStandardMap() - { + private Map getStandardMap() { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); return m; } @@ -97,20 +90,18 @@ private Map getStandardMap() * @throws java.lang.Exception if any. */ @Test - public void testDefaultInterpolationWithEscapedExpression() - throws Exception - { + public void testDefaultInterpolationWithEscapedExpression() throws Exception { Map m = getStandardMap(); String foo = "${name} is an ${noun}. \\${noun} value"; - LineOrientedInterpolatingReader reader = new LineOrientedInterpolatingReader( new StringReader( foo ), m ); + LineOrientedInterpolatingReader reader = new LineOrientedInterpolatingReader(new StringReader(foo), m); StringWriter writer = new StringWriter(); - IOUtil.copy( reader, writer ); + IOUtil.copy(reader, writer); String bar = writer.toString(); - assertEquals( "jason is an asshole. ${noun} value", bar ); + assertEquals("jason is an asshole. ${noun} value", bar); } /** @@ -119,20 +110,18 @@ public void testDefaultInterpolationWithEscapedExpression() * @throws java.lang.Exception if any. */ @Test - public void testDefaultInterpolationWithInterpolatedValueAtEnd() - throws Exception - { + public void testDefaultInterpolationWithInterpolatedValueAtEnd() throws Exception { Map m = getStandardMap(); String foo = "${name} is an ${noun}"; - LineOrientedInterpolatingReader reader = new LineOrientedInterpolatingReader( new StringReader( foo ), m ); + LineOrientedInterpolatingReader reader = new LineOrientedInterpolatingReader(new StringReader(foo), m); StringWriter writer = new StringWriter(); - IOUtil.copy( reader, writer ); + IOUtil.copy(reader, writer); String bar = writer.toString(); - assertEquals( "jason is an asshole", bar ); + assertEquals("jason is an asshole", bar); } /** @@ -141,21 +130,19 @@ public void testDefaultInterpolationWithInterpolatedValueAtEnd() * @throws java.lang.Exception if any. */ @Test - public void testInterpolationWithSpecifiedBoundaryTokens() - throws Exception - { + public void testInterpolationWithSpecifiedBoundaryTokens() throws Exception { Map m = getStandardMap(); String foo = "@name@ is an @noun@. @not.interpolated@ baby @foo@. @bar@"; LineOrientedInterpolatingReader reader = - new LineOrientedInterpolatingReader( new StringReader( foo ), m, "@", "@" ); + new LineOrientedInterpolatingReader(new StringReader(foo), m, "@", "@"); StringWriter writer = new StringWriter(); - IOUtil.copy( reader, writer ); + IOUtil.copy(reader, writer); String bar = writer.toString(); - assertEquals( "jason is an asshole. @not.interpolated@ baby @foo@. @bar@", bar ); + assertEquals("jason is an asshole. @not.interpolated@ baby @foo@. @bar@", bar); } /** @@ -164,21 +151,19 @@ public void testInterpolationWithSpecifiedBoundaryTokens() * @throws java.lang.Exception if any. */ @Test - public void testInterpolationWithSpecifiedBoundaryTokensWithNonInterpolatedValueAtEnd() - throws Exception - { + public void testInterpolationWithSpecifiedBoundaryTokensWithNonInterpolatedValueAtEnd() throws Exception { Map m = getStandardMap(); String foo = "@name@ is an @foobarred@"; LineOrientedInterpolatingReader reader = - new LineOrientedInterpolatingReader( new StringReader( foo ), m, "@", "@" ); + new LineOrientedInterpolatingReader(new StringReader(foo), m, "@", "@"); StringWriter writer = new StringWriter(); - IOUtil.copy( reader, writer ); + IOUtil.copy(reader, writer); String bar = writer.toString(); - assertEquals( "jason is an @foobarred@", bar ); + assertEquals("jason is an @foobarred@", bar); } /** @@ -187,20 +172,18 @@ public void testInterpolationWithSpecifiedBoundaryTokensWithNonInterpolatedValue * @throws java.lang.Exception if any. */ @Test - public void testInterpolationWithSpecifiedBoundaryTokensWithInterpolatedValueAtEnd() - throws Exception - { + public void testInterpolationWithSpecifiedBoundaryTokensWithInterpolatedValueAtEnd() throws Exception { Map m = getStandardMap(); String foo = "@name@ is an @noun@"; LineOrientedInterpolatingReader reader = - new LineOrientedInterpolatingReader( new StringReader( foo ), m, "@", "@" ); + new LineOrientedInterpolatingReader(new StringReader(foo), m, "@", "@"); StringWriter writer = new StringWriter(); - IOUtil.copy( reader, writer ); + IOUtil.copy(reader, writer); String bar = writer.toString(); - assertEquals( "jason is an asshole", bar ); + assertEquals("jason is an asshole", bar); } } diff --git a/src/test/java/org/codehaus/plexus/util/MatchPatternTest.java b/src/test/java/org/codehaus/plexus/util/MatchPatternTest.java index bd523457..d832378e 100644 --- a/src/test/java/org/codehaus/plexus/util/MatchPatternTest.java +++ b/src/test/java/org/codehaus/plexus/util/MatchPatternTest.java @@ -16,11 +16,11 @@ * limitations under the License. */ +import org.junit.Test; + import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.junit.Test; - /** *

      MatchPatternTest class.

      * @@ -28,19 +28,16 @@ * @version $Id: $Id * @since 3.4.0 */ -public class MatchPatternTest -{ +public class MatchPatternTest { /** *

      testMatchPath.

      * * @throws java.lang.Exception if any. */ @Test - public void testMatchPath() - throws Exception - { - MatchPattern mp = MatchPattern.fromString( "ABC*" ); - assertTrue( mp.matchPath( "ABCD", true ) ); + public void testMatchPath() throws Exception { + MatchPattern mp = MatchPattern.fromString("ABC*"); + assertTrue(mp.matchPath("ABCD", true)); } /** @@ -49,18 +46,16 @@ public void testMatchPath() * @see Issue #63 */ @Test - public void testMatchPatternStart() - { - MatchPattern mp = MatchPattern.fromString( "ABC*" ); + public void testMatchPatternStart() { + MatchPattern mp = MatchPattern.fromString("ABC*"); - assertTrue( mp.matchPatternStart( "ABCD", true ) ); - assertFalse( mp.matchPatternStart( "AbCD", true ) ); + assertTrue(mp.matchPatternStart("ABCD", true)); + assertFalse(mp.matchPatternStart("AbCD", true)); - assertTrue( mp.matchPatternStart( "ABCD", false ) ); - assertTrue( mp.matchPatternStart( "AbCD", false ) ); + assertTrue(mp.matchPatternStart("ABCD", false)); + assertTrue(mp.matchPatternStart("AbCD", false)); - assertFalse( mp.matchPatternStart( "XXXX", true ) ); - assertFalse( mp.matchPatternStart( "XXXX", false ) ); + assertFalse(mp.matchPatternStart("XXXX", true)); + assertFalse(mp.matchPatternStart("XXXX", false)); } - } diff --git a/src/test/java/org/codehaus/plexus/util/MatchPatternsTest.java b/src/test/java/org/codehaus/plexus/util/MatchPatternsTest.java index a10e340e..af49e99a 100644 --- a/src/test/java/org/codehaus/plexus/util/MatchPatternsTest.java +++ b/src/test/java/org/codehaus/plexus/util/MatchPatternsTest.java @@ -16,11 +16,11 @@ * limitations under the License. */ +import org.junit.Test; + import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.junit.Test; - /** *

      MatchPatternsTest class.

      * @@ -28,20 +28,17 @@ * @version $Id: $Id * @since 3.4.0 */ -public class MatchPatternsTest -{ +public class MatchPatternsTest { /** *

      testMatches.

      * * @throws java.lang.Exception if any. */ @Test - public void testMatches() - throws Exception - { - MatchPatterns from = MatchPatterns.from( "ABC**", "CDE**" ); - assertTrue( from.matches( "ABCDE", true ) ); - assertTrue( from.matches( "CDEF", true ) ); - assertFalse( from.matches( "XYZ", true ) ); + public void testMatches() throws Exception { + MatchPatterns from = MatchPatterns.from("ABC**", "CDE**"); + 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 572d4a56..ae049d3d 100644 --- a/src/test/java/org/codehaus/plexus/util/OsTest.java +++ b/src/test/java/org/codehaus/plexus/util/OsTest.java @@ -16,14 +16,14 @@ * 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 org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + /** * Test Case for Os * @@ -31,74 +31,66 @@ * @version $Id: $Id * @since 3.4.0 */ -public class OsTest -{ +public class OsTest { /** *

      testUndefinedFamily.

      */ @Test - public void testUndefinedFamily() - { - assertFalse( Os.isFamily( "bogus family" ) ); + public void testUndefinedFamily() { + assertFalse(Os.isFamily("bogus family")); } /** *

      testOs.

      */ @Test - public void testOs() - { + public void testOs() { Iterator iter = Os.getValidFamilies().iterator(); String currentFamily = null; String notCurrentFamily = null; - while ( iter.hasNext() && ( currentFamily == null || notCurrentFamily == null ) ) - { + while (iter.hasNext() && (currentFamily == null || notCurrentFamily == null)) { String fam = iter.next(); - if ( Os.isFamily( fam ) ) - { + if (Os.isFamily(fam)) { currentFamily = fam; - } - else - { + } else { notCurrentFamily = fam; } } // make sure the OS_FAMILY is set right. - assertEquals( currentFamily, Os.OS_FAMILY ); + assertEquals(currentFamily, Os.OS_FAMILY); // check the current family and one of the others - assertTrue( Os.isOs( currentFamily, null, null, null ) ); - assertFalse( Os.isOs( notCurrentFamily, null, null, null ) ); + assertTrue(Os.isOs(currentFamily, null, null, null)); + assertFalse(Os.isOs(notCurrentFamily, null, null, null)); // check for junk - assertFalse( Os.isOs( "junk", null, null, null ) ); + assertFalse(Os.isOs("junk", null, null, null)); // check the current name - assertTrue( Os.isOs( currentFamily, Os.OS_NAME, null, null ) ); + assertTrue(Os.isOs(currentFamily, Os.OS_NAME, null, null)); // check some other name - assertFalse( Os.isOs( currentFamily, "myos", null, null ) ); + assertFalse(Os.isOs(currentFamily, "myos", null, null)); // check the arch - assertTrue( Os.isOs( currentFamily, Os.OS_NAME, Os.OS_ARCH, null ) ); - assertFalse( Os.isOs( currentFamily, Os.OS_NAME, "myarch", null ) ); + assertTrue(Os.isOs(currentFamily, Os.OS_NAME, Os.OS_ARCH, null)); + assertFalse(Os.isOs(currentFamily, Os.OS_NAME, "myarch", null)); // check the version - assertTrue( Os.isOs( currentFamily, Os.OS_NAME, Os.OS_ARCH, Os.OS_VERSION ) ); - assertFalse( Os.isOs( currentFamily, Os.OS_NAME, Os.OS_ARCH, "myversion" ) ); + assertTrue(Os.isOs(currentFamily, Os.OS_NAME, Os.OS_ARCH, Os.OS_VERSION)); + assertFalse(Os.isOs(currentFamily, Os.OS_NAME, Os.OS_ARCH, "myversion")); } /** *

      testValidList.

      */ @Test - public void testValidList() - { - assertTrue( Os.isValidFamily( "dos" ) ); + public void testValidList() { + assertTrue(Os.isValidFamily("dos")); - assertFalse( Os.isValidFamily( "" ) ); - assertFalse( Os.isValidFamily( null ) ); - assertFalse( Os.isValidFamily( "something" ) ); + assertFalse(Os.isValidFamily("")); + assertFalse(Os.isValidFamily(null)); + assertFalse(Os.isValidFamily("something")); } } diff --git a/src/test/java/org/codehaus/plexus/util/PathToolTest.java b/src/test/java/org/codehaus/plexus/util/PathToolTest.java index 0a6d011e..c8f41080 100644 --- a/src/test/java/org/codehaus/plexus/util/PathToolTest.java +++ b/src/test/java/org/codehaus/plexus/util/PathToolTest.java @@ -16,10 +16,10 @@ * limitations under the License. */ -import static org.junit.Assert.assertEquals; - import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** *

      PathToolTest class.

      * @@ -27,23 +27,20 @@ * @version $Id: $Id * @since 3.4.0 */ -public class PathToolTest -{ +public class PathToolTest { /** *

      testGetRelativePath.

      * * @throws java.lang.Exception */ @Test - public void testGetRelativePath() - throws Exception - { - assertEquals( PathTool.getRelativePath( null, null ), "" ); - assertEquals( PathTool.getRelativePath( null, "/usr/local/java/bin" ), "" ); - assertEquals( PathTool.getRelativePath( "/usr/local/", null ), "" ); - assertEquals( PathTool.getRelativePath( "/usr/local/", "/usr/local/java/bin" ), ".." ); - assertEquals( PathTool.getRelativePath( "/usr/local/", "/usr/local/java/bin/java.sh" ), "../.." ); - assertEquals( PathTool.getRelativePath( "/usr/local/java/bin/java.sh", "/usr/local/" ), "" ); + public void testGetRelativePath() throws Exception { + assertEquals(PathTool.getRelativePath(null, null), ""); + assertEquals(PathTool.getRelativePath(null, "/usr/local/java/bin"), ""); + assertEquals(PathTool.getRelativePath("/usr/local/", null), ""); + assertEquals(PathTool.getRelativePath("/usr/local/", "/usr/local/java/bin"), ".."); + assertEquals(PathTool.getRelativePath("/usr/local/", "/usr/local/java/bin/java.sh"), "../.."); + assertEquals(PathTool.getRelativePath("/usr/local/java/bin/java.sh", "/usr/local/"), ""); } /** @@ -52,13 +49,11 @@ public void testGetRelativePath() * @throws java.lang.Exception */ @Test - public void testGetDirectoryComponent() - throws Exception - { - assertEquals( PathTool.getDirectoryComponent( null ), "" ); - assertEquals( PathTool.getDirectoryComponent( "/usr/local/java/bin" ), "/usr/local/java" ); - assertEquals( PathTool.getDirectoryComponent( "/usr/local/java/bin/" ), "/usr/local/java/bin" ); - assertEquals( PathTool.getDirectoryComponent( "/usr/local/java/bin/java.sh" ), "/usr/local/java/bin" ); + public void testGetDirectoryComponent() throws Exception { + assertEquals(PathTool.getDirectoryComponent(null), ""); + assertEquals(PathTool.getDirectoryComponent("/usr/local/java/bin"), "/usr/local/java"); + assertEquals(PathTool.getDirectoryComponent("/usr/local/java/bin/"), "/usr/local/java/bin"); + assertEquals(PathTool.getDirectoryComponent("/usr/local/java/bin/java.sh"), "/usr/local/java/bin"); } /** @@ -67,18 +62,18 @@ public void testGetDirectoryComponent() * @throws java.lang.Exception */ @Test - public void testCalculateLink() - throws Exception - { - assertEquals( PathTool.calculateLink( "/index.html", "../.." ), "../../index.html" ); - assertEquals( PathTool.calculateLink( "http://plexus.codehaus.org/plexus-utils/index.html", "../.." ), - "http://plexus.codehaus.org/plexus-utils/index.html" ); - assertEquals( PathTool.calculateLink( "/usr/local/java/bin/java.sh", "../.." ), - "../../usr/local/java/bin/java.sh" ); - assertEquals( PathTool.calculateLink( "../index.html", "/usr/local/java/bin" ), - "/usr/local/java/bin/../index.html" ); - assertEquals( PathTool.calculateLink( "../index.html", "http://plexus.codehaus.org/plexus-utils" ), - "http://plexus.codehaus.org/plexus-utils/../index.html" ); + public void testCalculateLink() throws Exception { + assertEquals(PathTool.calculateLink("/index.html", "../.."), "../../index.html"); + assertEquals( + PathTool.calculateLink("http://plexus.codehaus.org/plexus-utils/index.html", "../.."), + "http://plexus.codehaus.org/plexus-utils/index.html"); + assertEquals( + PathTool.calculateLink("/usr/local/java/bin/java.sh", "../.."), "../../usr/local/java/bin/java.sh"); + assertEquals( + PathTool.calculateLink("../index.html", "/usr/local/java/bin"), "/usr/local/java/bin/../index.html"); + assertEquals( + PathTool.calculateLink("../index.html", "http://plexus.codehaus.org/plexus-utils"), + "http://plexus.codehaus.org/plexus-utils/../index.html"); } /** @@ -87,18 +82,18 @@ public void testCalculateLink() * @throws java.lang.Exception */ @Test - public void testGetRelativeWebPath() - throws Exception - { - assertEquals( PathTool.getRelativeWebPath( null, null ), "" ); - assertEquals( PathTool.getRelativeWebPath( null, "http://plexus.codehaus.org/" ), "" ); - assertEquals( PathTool.getRelativeWebPath( "http://plexus.codehaus.org/", null ), "" ); - assertEquals( PathTool.getRelativeWebPath( "http://plexus.codehaus.org/", - "http://plexus.codehaus.org/plexus-utils/index.html" ), - "plexus-utils/index.html" ); - assertEquals( PathTool.getRelativeWebPath( "http://plexus.codehaus.org/plexus-utils/index.html", - "http://plexus.codehaus.org/" ), - "../../" ); + public void testGetRelativeWebPath() throws Exception { + assertEquals(PathTool.getRelativeWebPath(null, null), ""); + assertEquals(PathTool.getRelativeWebPath(null, "http://plexus.codehaus.org/"), ""); + assertEquals(PathTool.getRelativeWebPath("http://plexus.codehaus.org/", null), ""); + assertEquals( + PathTool.getRelativeWebPath( + "http://plexus.codehaus.org/", "http://plexus.codehaus.org/plexus-utils/index.html"), + "plexus-utils/index.html"); + assertEquals( + PathTool.getRelativeWebPath( + "http://plexus.codehaus.org/plexus-utils/index.html", "http://plexus.codehaus.org/"), + "../../"); } /** @@ -107,38 +102,34 @@ public void testGetRelativeWebPath() * @throws java.lang.Exception */ @Test - public void testGetRelativeFilePath() - throws Exception - { - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - assertEquals( PathTool.getRelativeFilePath( null, null ), "" ); - assertEquals( PathTool.getRelativeFilePath( null, "c:\\tools\\java\\bin" ), "" ); - assertEquals( PathTool.getRelativeFilePath( "c:\\tools\\java", null ), "" ); - assertEquals( PathTool.getRelativeFilePath( "c:\\tools", "c:\\tools\\java\\bin" ), "java\\bin" ); - assertEquals( PathTool.getRelativeFilePath( "c:\\tools", "c:\\tools\\java\\bin\\" ), "java\\bin\\" ); - assertEquals( PathTool.getRelativeFilePath( "c:\\tools\\java\\bin", "c:\\tools" ), "..\\.." ); - assertEquals( PathTool.getRelativeFilePath( "c:\\tools\\", "c:\\tools\\java\\bin\\java.exe" ), - "java\\bin\\java.exe" ); - assertEquals( PathTool.getRelativeFilePath( "c:\\tools\\java\\bin\\java.sh", "c:\\tools" ), "..\\..\\.." ); - assertEquals( PathTool.getRelativeFilePath( "c:\\tools", "c:\\bin" ), "..\\bin" ); - assertEquals( PathTool.getRelativeFilePath( "c:\\bin", "c:\\tools" ), "..\\tools" ); - assertEquals( PathTool.getRelativeFilePath( "c:\\bin", "c:\\bin" ), "" ); - } - else - { - assertEquals( PathTool.getRelativeFilePath( null, null ), "" ); - assertEquals( PathTool.getRelativeFilePath( null, "/usr/local/java/bin" ), "" ); - assertEquals( PathTool.getRelativeFilePath( "/usr/local", null ), "" ); - assertEquals( PathTool.getRelativeFilePath( "/usr/local", "/usr/local/java/bin" ), "java/bin" ); - assertEquals( PathTool.getRelativeFilePath( "/usr/local", "/usr/local/java/bin/" ), "java/bin/" ); - assertEquals( PathTool.getRelativeFilePath( "/usr/local/java/bin", "/usr/local/" ), "../../" ); - assertEquals( PathTool.getRelativeFilePath( "/usr/local/", "/usr/local/java/bin/java.sh" ), - "java/bin/java.sh" ); - assertEquals( PathTool.getRelativeFilePath( "/usr/local/java/bin/java.sh", "/usr/local/" ), "../../../" ); - assertEquals( PathTool.getRelativeFilePath( "/usr/local/", "/bin" ), "../../bin" ); - assertEquals( PathTool.getRelativeFilePath( "/bin", "/usr/local" ), "../usr/local" ); - assertEquals( PathTool.getRelativeFilePath( "/bin", "/bin" ), "" ); + public void testGetRelativeFilePath() throws Exception { + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + assertEquals(PathTool.getRelativeFilePath(null, null), ""); + assertEquals(PathTool.getRelativeFilePath(null, "c:\\tools\\java\\bin"), ""); + assertEquals(PathTool.getRelativeFilePath("c:\\tools\\java", null), ""); + assertEquals(PathTool.getRelativeFilePath("c:\\tools", "c:\\tools\\java\\bin"), "java\\bin"); + assertEquals(PathTool.getRelativeFilePath("c:\\tools", "c:\\tools\\java\\bin\\"), "java\\bin\\"); + assertEquals(PathTool.getRelativeFilePath("c:\\tools\\java\\bin", "c:\\tools"), "..\\.."); + assertEquals( + PathTool.getRelativeFilePath("c:\\tools\\", "c:\\tools\\java\\bin\\java.exe"), + "java\\bin\\java.exe"); + assertEquals(PathTool.getRelativeFilePath("c:\\tools\\java\\bin\\java.sh", "c:\\tools"), "..\\..\\.."); + assertEquals(PathTool.getRelativeFilePath("c:\\tools", "c:\\bin"), "..\\bin"); + assertEquals(PathTool.getRelativeFilePath("c:\\bin", "c:\\tools"), "..\\tools"); + assertEquals(PathTool.getRelativeFilePath("c:\\bin", "c:\\bin"), ""); + } else { + assertEquals(PathTool.getRelativeFilePath(null, null), ""); + assertEquals(PathTool.getRelativeFilePath(null, "/usr/local/java/bin"), ""); + assertEquals(PathTool.getRelativeFilePath("/usr/local", null), ""); + assertEquals(PathTool.getRelativeFilePath("/usr/local", "/usr/local/java/bin"), "java/bin"); + assertEquals(PathTool.getRelativeFilePath("/usr/local", "/usr/local/java/bin/"), "java/bin/"); + assertEquals(PathTool.getRelativeFilePath("/usr/local/java/bin", "/usr/local/"), "../../"); + assertEquals( + PathTool.getRelativeFilePath("/usr/local/", "/usr/local/java/bin/java.sh"), "java/bin/java.sh"); + assertEquals(PathTool.getRelativeFilePath("/usr/local/java/bin/java.sh", "/usr/local/"), "../../../"); + assertEquals(PathTool.getRelativeFilePath("/usr/local/", "/bin"), "../../bin"); + assertEquals(PathTool.getRelativeFilePath("/bin", "/usr/local"), "../usr/local"); + assertEquals(PathTool.getRelativeFilePath("/bin", "/bin"), ""); } } } diff --git a/src/test/java/org/codehaus/plexus/util/PerfTest.java b/src/test/java/org/codehaus/plexus/util/PerfTest.java index 595c7272..e7542e1d 100644 --- a/src/test/java/org/codehaus/plexus/util/PerfTest.java +++ b/src/test/java/org/codehaus/plexus/util/PerfTest.java @@ -25,8 +25,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class PerfTest -{ +public class PerfTest { String src = "012345578901234556789012345678901234456789012345678901234567890"; private final int oops = 100; @@ -35,37 +34,31 @@ public class PerfTest *

      testSubString.

      */ @Test - public void testSubString() - { + public void testSubString() { StringBuilder res = new StringBuilder(); int len = src.length(); - for ( int cnt = 0; cnt < oops; cnt++ ) - { - for ( int i = 0; i < len - 5; i++ ) - { - res.append( src.substring( i, i + 4 ) ); + for (int cnt = 0; cnt < oops; cnt++) { + for (int i = 0; i < len - 5; i++) { + res.append(src.substring(i, i + 4)); } } int i = res.length(); - System.out.println( "i = " + i ); + System.out.println("i = " + i); } /** *

      testResDir.

      */ @Test - public void testResDir() - { + public void testResDir() { StringBuilder res = new StringBuilder(); int len = src.length(); - for ( int cnt = 0; cnt < oops; cnt++ ) - { - for ( int i = 0; i < len - 5; i++ ) - { - res.append( src, i, i + 4 ); + for (int cnt = 0; cnt < oops; cnt++) { + for (int i = 0; i < len - 5; i++) { + res.append(src, i, i + 4); } } int i = res.length(); - System.out.println( "i = " + i ); + System.out.println("i = " + i); } } diff --git a/src/test/java/org/codehaus/plexus/util/ReflectionUtilsTest.java b/src/test/java/org/codehaus/plexus/util/ReflectionUtilsTest.java index 32699154..c9e982a1 100644 --- a/src/test/java/org/codehaus/plexus/util/ReflectionUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/ReflectionUtilsTest.java @@ -16,13 +16,12 @@ * limitations under the License. */ -import static org.junit.Assert.assertEquals; - +import java.util.HashMap; import java.util.Map; import org.junit.Test; -import java.util.HashMap; +import static org.junit.Assert.assertEquals; /** * This is used to test ReflectionUtils for correctness. @@ -32,8 +31,7 @@ * @see org.codehaus.plexus.util.ReflectionUtils * @since 3.4.0 */ -public final class ReflectionUtilsTest -{ +public final class ReflectionUtilsTest { public ReflectionUtilsTestClass testClass = new ReflectionUtilsTestClass(); /** @@ -42,10 +40,8 @@ public final class ReflectionUtilsTest * @throws java.lang.IllegalAccessException if any. */ @Test - public void testSimpleVariableAccess() - throws IllegalAccessException - { - assertEquals( "woohoo", (String) ReflectionUtils.getValueIncludingSuperclasses( "myString", testClass ) ); + public void testSimpleVariableAccess() throws IllegalAccessException { + assertEquals("woohoo", (String) ReflectionUtils.getValueIncludingSuperclasses("myString", testClass)); } /** @@ -54,16 +50,13 @@ public void testSimpleVariableAccess() * @throws java.lang.IllegalAccessException if any. */ @Test - public void testComplexVariableAccess() - throws IllegalAccessException - { - Map map = ReflectionUtils.getVariablesAndValuesIncludingSuperclasses( testClass ); - - Map myMap = (Map) map.get( "myMap" ); + public void testComplexVariableAccess() throws IllegalAccessException { + Map map = ReflectionUtils.getVariablesAndValuesIncludingSuperclasses(testClass); - assertEquals( "myValue", (String) myMap.get( "myKey" ) ); - assertEquals( "myOtherValue", (String) myMap.get( "myOtherKey" ) ); + Map myMap = (Map) map.get("myMap"); + assertEquals("myValue", (String) myMap.get("myKey")); + assertEquals("myOtherValue", (String) myMap.get("myOtherKey")); } /** @@ -72,11 +65,8 @@ public void testComplexVariableAccess() * @throws java.lang.IllegalAccessException if any. */ @Test - public void testSuperClassVariableAccess() - throws IllegalAccessException - { - assertEquals( "super-duper", - (String) ReflectionUtils.getValueIncludingSuperclasses( "mySuperString", testClass ) ); + public void testSuperClassVariableAccess() throws IllegalAccessException { + assertEquals("super-duper", (String) ReflectionUtils.getValueIncludingSuperclasses("mySuperString", testClass)); } /** @@ -85,39 +75,33 @@ public void testSuperClassVariableAccess() * @throws java.lang.IllegalAccessException if any. */ @Test - public void testSettingVariableValue() - throws IllegalAccessException - { - ReflectionUtils.setVariableValueInObject( testClass, "mySettableString", "mySetString" ); + public void testSettingVariableValue() throws IllegalAccessException { + ReflectionUtils.setVariableValueInObject(testClass, "mySettableString", "mySetString"); - assertEquals( "mySetString", - (String) ReflectionUtils.getValueIncludingSuperclasses( "mySettableString", testClass ) ); + assertEquals( + "mySetString", (String) ReflectionUtils.getValueIncludingSuperclasses("mySettableString", testClass)); - ReflectionUtils.setVariableValueInObject( testClass, "myParentsSettableString", "myParentsSetString" ); + ReflectionUtils.setVariableValueInObject(testClass, "myParentsSettableString", "myParentsSetString"); - assertEquals( "myParentsSetString", - (String) ReflectionUtils.getValueIncludingSuperclasses( "myParentsSettableString", testClass ) ); + assertEquals("myParentsSetString", (String) + ReflectionUtils.getValueIncludingSuperclasses("myParentsSettableString", testClass)); } - private class ReflectionUtilsTestClass - extends AbstractReflectionUtilsTestClass + private class ReflectionUtilsTestClass extends AbstractReflectionUtilsTestClass { - { private String myString = "woohoo"; private String mySettableString; private Map myMap = new HashMap(); - public ReflectionUtilsTestClass() - { - myMap.put( "myKey", "myValue" ); - myMap.put( "myOtherKey", "myOtherValue" ); + public ReflectionUtilsTestClass() { + myMap.put("myKey", "myValue"); + myMap.put("myOtherKey", "myOtherValue"); } } - private class AbstractReflectionUtilsTestClass - { + private class AbstractReflectionUtilsTestClass { private String mySuperString = "super-duper"; private String myParentsSettableString; diff --git a/src/test/java/org/codehaus/plexus/util/SelectorUtilsTest.java b/src/test/java/org/codehaus/plexus/util/SelectorUtilsTest.java index 160aa16d..6232d459 100644 --- a/src/test/java/org/codehaus/plexus/util/SelectorUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/SelectorUtilsTest.java @@ -16,130 +16,104 @@ * limitations under the License. */ -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.File; import org.junit.Test; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + /** *

      SelectorUtilsTest class.

      * * @author herve * @since 3.4.0 */ -public class SelectorUtilsTest -{ +public class SelectorUtilsTest { /** *

      testMatchPath_DefaultFileSeparator.

      */ @Test - public void testMatchPath_DefaultFileSeparator() - { + public void testMatchPath_DefaultFileSeparator() { String separator = File.separator; // Pattern and target start with file separator - assertTrue( SelectorUtils.matchPath( separator + "*" + separator + "a.txt", - separator + "b" + separator + "a.txt" ) ); + assertTrue( + SelectorUtils.matchPath(separator + "*" + separator + "a.txt", separator + "b" + separator + "a.txt")); // Pattern starts with file separator, target doesn't - assertFalse( SelectorUtils.matchPath( separator + "*" + separator + "a.txt", "b" + separator + "a.txt" ) ); + assertFalse(SelectorUtils.matchPath(separator + "*" + separator + "a.txt", "b" + separator + "a.txt")); // Pattern doesn't start with file separator, target does - assertFalse( SelectorUtils.matchPath( "*" + separator + "a.txt", separator + "b" + separator + "a.txt" ) ); + assertFalse(SelectorUtils.matchPath("*" + separator + "a.txt", separator + "b" + separator + "a.txt")); // Pattern and target don't start with file separator - assertTrue( SelectorUtils.matchPath( "*" + separator + "a.txt", "b" + separator + "a.txt" ) ); + assertTrue(SelectorUtils.matchPath("*" + separator + "a.txt", "b" + separator + "a.txt")); } /** *

      testMatchPath_UnixFileSeparator.

      */ @Test - public void testMatchPath_UnixFileSeparator() - { + public void testMatchPath_UnixFileSeparator() { String separator = "/"; // Pattern and target start with file separator - assertTrue( SelectorUtils.matchPath( separator + "*" + separator + "a.txt", - separator + "b" + separator + "a.txt", separator, false ) ); + assertTrue(SelectorUtils.matchPath( + separator + "*" + separator + "a.txt", separator + "b" + separator + "a.txt", separator, false)); // Pattern starts with file separator, target doesn't - assertFalse( SelectorUtils.matchPath( separator + "*" + separator + "a.txt", "b" + separator + "a.txt", - separator, false ) ); + assertFalse(SelectorUtils.matchPath( + separator + "*" + separator + "a.txt", "b" + separator + "a.txt", separator, false)); // Pattern doesn't start with file separator, target does - assertFalse( SelectorUtils.matchPath( "*" + separator + "a.txt", separator + "b" + separator + "a.txt", - separator, false ) ); + assertFalse(SelectorUtils.matchPath( + "*" + separator + "a.txt", separator + "b" + separator + "a.txt", separator, false)); // Pattern and target don't start with file separator - assertTrue( SelectorUtils.matchPath( "*" + separator + "a.txt", "b" + separator + "a.txt", separator, false ) ); + assertTrue(SelectorUtils.matchPath("*" + separator + "a.txt", "b" + separator + "a.txt", separator, false)); } /** *

      testMatchPath_WindowsFileSeparator.

      */ @Test - public void testMatchPath_WindowsFileSeparator() - { + public void testMatchPath_WindowsFileSeparator() { String separator = "\\"; // Pattern and target start with file separator - assertTrue( SelectorUtils.matchPath( separator + "*" + separator + "a.txt", - separator + "b" + separator + "a.txt", separator, false ) ); + assertTrue(SelectorUtils.matchPath( + separator + "*" + separator + "a.txt", separator + "b" + separator + "a.txt", separator, false)); // Pattern starts with file separator, target doesn't - assertFalse( SelectorUtils.matchPath( separator + "*" + separator + "a.txt", "b" + separator + "a.txt", - separator, false ) ); + assertFalse(SelectorUtils.matchPath( + separator + "*" + separator + "a.txt", "b" + separator + "a.txt", separator, false)); // Pattern doesn't start with file separator, target does - assertFalse( SelectorUtils.matchPath( "*" + separator + "a.txt", separator + "b" + separator + "a.txt", - separator, false ) ); + assertFalse(SelectorUtils.matchPath( + "*" + separator + "a.txt", separator + "b" + separator + "a.txt", separator, false)); // Pattern and target don't start with file separator - assertTrue( SelectorUtils.matchPath( "*" + separator + "a.txt", "b" + separator + "a.txt", separator, false ) ); + assertTrue(SelectorUtils.matchPath("*" + separator + "a.txt", "b" + separator + "a.txt", separator, false)); } @Test - public void testPatternMatchSingleWildcardPosix() - { - assertFalse(SelectorUtils.matchPath( - "/com/test/*", - "/com/test/test/hallo")); + public void testPatternMatchSingleWildcardPosix() { + assertFalse(SelectorUtils.matchPath("/com/test/*", "/com/test/test/hallo")); } - @Test - public void testPatternMatchDoubleWildcardCaseInsensitivePosix() - { - assertTrue(SelectorUtils.matchPath( - "/com/test/**", - "/com/test/test/hallo")); + public void testPatternMatchDoubleWildcardCaseInsensitivePosix() { + assertTrue(SelectorUtils.matchPath("/com/test/**", "/com/test/test/hallo")); } - @Test - public void testPatternMatchDoubleWildcardPosix() - { - assertTrue(SelectorUtils.matchPath( - "/com/test/**", - "/com/test/test/hallo")); + public void testPatternMatchDoubleWildcardPosix() { + assertTrue(SelectorUtils.matchPath("/com/test/**", "/com/test/test/hallo")); } - @Test - public void testPatternMatchSingleWildcardWindows() - { - assertFalse(SelectorUtils.matchPath( - "D:\\com\\test\\*", - "D:\\com\\test\\test\\hallo")); + public void testPatternMatchSingleWildcardWindows() { + assertFalse(SelectorUtils.matchPath("D:\\com\\test\\*", "D:\\com\\test\\test\\hallo")); - assertFalse(SelectorUtils.matchPath( - "D:/com/test/*", - "D:/com/test/test/hallo")); + assertFalse(SelectorUtils.matchPath("D:/com/test/*", "D:/com/test/test/hallo")); } @Test - public void testPatternMatchDoubleWildcardWindows() - { - assertTrue(SelectorUtils.matchPath( - "D:\\com\\test\\**", - "D:\\com\\test\\test\\hallo")); + public void testPatternMatchDoubleWildcardWindows() { + assertTrue(SelectorUtils.matchPath("D:\\com\\test\\**", "D:\\com\\test\\test\\hallo")); - assertTrue(SelectorUtils.matchPath( - "D:\\com\\test\\**", - "D:/com/test/test/hallo")); + assertTrue(SelectorUtils.matchPath("D:\\com\\test\\**", "D:/com/test/test/hallo")); } } diff --git a/src/test/java/org/codehaus/plexus/util/StringInputStreamTest.java b/src/test/java/org/codehaus/plexus/util/StringInputStreamTest.java index 0127c741..0a76f8c8 100644 --- a/src/test/java/org/codehaus/plexus/util/StringInputStreamTest.java +++ b/src/test/java/org/codehaus/plexus/util/StringInputStreamTest.java @@ -25,13 +25,9 @@ * @version $Id: $Id * @since 3.4.0 */ -public class StringInputStreamTest - extends TestCase -{ +public class StringInputStreamTest extends TestCase { /** *

      testFoo.

      */ - public void testFoo() - { - } + public void testFoo() {} } diff --git a/src/test/java/org/codehaus/plexus/util/StringUtilsTest.java b/src/test/java/org/codehaus/plexus/util/StringUtilsTest.java index b7bd6d72..d4ad8856 100644 --- a/src/test/java/org/codehaus/plexus/util/StringUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/StringUtilsTest.java @@ -16,15 +16,15 @@ * 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 org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + /** * Test string utils. * @@ -32,287 +32,266 @@ * @version $Id: $Id * @since 3.4.0 */ -public class StringUtilsTest -{ +public class StringUtilsTest { /** *

      testIsEmpty.

      */ @Test - public void testIsEmpty() - { - assertEquals( true, StringUtils.isEmpty( null ) ); - assertEquals( true, StringUtils.isEmpty( "" ) ); - assertEquals( false, StringUtils.isEmpty( " " ) ); - assertEquals( false, StringUtils.isEmpty( "foo" ) ); - assertEquals( false, StringUtils.isEmpty( " foo " ) ); + public void testIsEmpty() { + assertEquals(true, StringUtils.isEmpty(null)); + assertEquals(true, StringUtils.isEmpty("")); + assertEquals(false, StringUtils.isEmpty(" ")); + assertEquals(false, StringUtils.isEmpty("foo")); + assertEquals(false, StringUtils.isEmpty(" foo ")); } /** *

      testIsNotEmpty.

      */ @Test - public void testIsNotEmpty() - { - assertEquals( false, StringUtils.isNotEmpty( null ) ); - assertEquals( false, StringUtils.isNotEmpty( "" ) ); - assertEquals( true, StringUtils.isNotEmpty( " " ) ); - assertEquals( true, StringUtils.isNotEmpty( "foo" ) ); - assertEquals( true, StringUtils.isNotEmpty( " foo " ) ); + public void testIsNotEmpty() { + assertEquals(false, StringUtils.isNotEmpty(null)); + assertEquals(false, StringUtils.isNotEmpty("")); + assertEquals(true, StringUtils.isNotEmpty(" ")); + assertEquals(true, StringUtils.isNotEmpty("foo")); + assertEquals(true, StringUtils.isNotEmpty(" foo ")); } @Test - public void testIsNotEmptyNegatesIsEmpty() - { - assertEquals( !StringUtils.isEmpty( null ), StringUtils.isNotEmpty( null ) ); - assertEquals( !StringUtils.isEmpty( "" ), StringUtils.isNotEmpty( "" ) ); - assertEquals( !StringUtils.isEmpty( " " ), StringUtils.isNotEmpty( " " ) ); - assertEquals( !StringUtils.isEmpty( "foo" ), StringUtils.isNotEmpty( "foo" ) ); - assertEquals( !StringUtils.isEmpty( " foo " ), StringUtils.isNotEmpty( " foo " ) ); + public void testIsNotEmptyNegatesIsEmpty() { + assertEquals(!StringUtils.isEmpty(null), StringUtils.isNotEmpty(null)); + assertEquals(!StringUtils.isEmpty(""), StringUtils.isNotEmpty("")); + assertEquals(!StringUtils.isEmpty(" "), StringUtils.isNotEmpty(" ")); + assertEquals(!StringUtils.isEmpty("foo"), StringUtils.isNotEmpty("foo")); + assertEquals(!StringUtils.isEmpty(" foo "), StringUtils.isNotEmpty(" foo ")); } /** *

      testIsBlank.

      */ @Test - public void testIsBlank() - { - assertEquals( true, StringUtils.isBlank( null ) ); - assertEquals( true, StringUtils.isBlank( "" ) ); - assertEquals( true, StringUtils.isBlank( " \t\r\n" ) ); - assertEquals( false, StringUtils.isBlank( "foo" ) ); - assertEquals( false, StringUtils.isBlank( " foo " ) ); + public void testIsBlank() { + assertEquals(true, StringUtils.isBlank(null)); + assertEquals(true, StringUtils.isBlank("")); + assertEquals(true, StringUtils.isBlank(" \t\r\n")); + assertEquals(false, StringUtils.isBlank("foo")); + assertEquals(false, StringUtils.isBlank(" foo ")); } /** *

      testIsNotBlank.

      */ @Test - public void testIsNotBlank() - { - assertEquals( false, StringUtils.isNotBlank( null ) ); - assertEquals( false, StringUtils.isNotBlank( "" ) ); - assertEquals( false, StringUtils.isNotBlank( " \t\r\n" ) ); - assertEquals( true, StringUtils.isNotBlank( "foo" ) ); - assertEquals( true, StringUtils.isNotBlank( " foo " ) ); + public void testIsNotBlank() { + assertEquals(false, StringUtils.isNotBlank(null)); + assertEquals(false, StringUtils.isNotBlank("")); + assertEquals(false, StringUtils.isNotBlank(" \t\r\n")); + assertEquals(true, StringUtils.isNotBlank("foo")); + assertEquals(true, StringUtils.isNotBlank(" foo ")); } /** *

      testCapitalizeFirstLetter.

      */ @Test - public void testCapitalizeFirstLetter() - { - assertEquals( "Id", StringUtils.capitalizeFirstLetter( "id" ) ); - assertEquals( "Id", StringUtils.capitalizeFirstLetter( "Id" ) ); + public void testCapitalizeFirstLetter() { + assertEquals("Id", StringUtils.capitalizeFirstLetter("id")); + assertEquals("Id", StringUtils.capitalizeFirstLetter("Id")); } /** *

      testCapitalizeFirstLetterTurkish.

      */ @Test - public void testCapitalizeFirstLetterTurkish() - { + public void testCapitalizeFirstLetterTurkish() { Locale l = Locale.getDefault(); - Locale.setDefault( new Locale( "tr" ) ); - assertEquals( "Id", StringUtils.capitalizeFirstLetter( "id" ) ); - assertEquals( "Id", StringUtils.capitalizeFirstLetter( "Id" ) ); - Locale.setDefault( l ); + Locale.setDefault(new Locale("tr")); + assertEquals("Id", StringUtils.capitalizeFirstLetter("id")); + assertEquals("Id", StringUtils.capitalizeFirstLetter("Id")); + Locale.setDefault(l); } /** *

      testLowerCaseFirstLetter.

      */ @Test - public void testLowerCaseFirstLetter() - { - assertEquals( "id", StringUtils.lowercaseFirstLetter( "id" ) ); - assertEquals( "id", StringUtils.lowercaseFirstLetter( "Id" ) ); + public void testLowerCaseFirstLetter() { + assertEquals("id", StringUtils.lowercaseFirstLetter("id")); + assertEquals("id", StringUtils.lowercaseFirstLetter("Id")); } /** *

      testLowerCaseFirstLetterTurkish.

      */ @Test - public void testLowerCaseFirstLetterTurkish() - { + public void testLowerCaseFirstLetterTurkish() { Locale l = Locale.getDefault(); - Locale.setDefault( new Locale( "tr" ) ); - assertEquals( "id", StringUtils.lowercaseFirstLetter( "id" ) ); - assertEquals( "id", StringUtils.lowercaseFirstLetter( "Id" ) ); - Locale.setDefault( l ); + Locale.setDefault(new Locale("tr")); + assertEquals("id", StringUtils.lowercaseFirstLetter("id")); + assertEquals("id", StringUtils.lowercaseFirstLetter("Id")); + Locale.setDefault(l); } /** *

      testRemoveAndHump.

      */ @Test - public void testRemoveAndHump() - { - assertEquals( "Id", StringUtils.removeAndHump( "id", "-" ) ); - assertEquals( "SomeId", StringUtils.removeAndHump( "some-id", "-" ) ); + public void testRemoveAndHump() { + assertEquals("Id", StringUtils.removeAndHump("id", "-")); + assertEquals("SomeId", StringUtils.removeAndHump("some-id", "-")); } /** *

      testRemoveAndHumpTurkish.

      */ @Test - public void testRemoveAndHumpTurkish() - { + public void testRemoveAndHumpTurkish() { Locale l = Locale.getDefault(); - Locale.setDefault( new Locale( "tr" ) ); - assertEquals( "Id", StringUtils.removeAndHump( "id", "-" ) ); - assertEquals( "SomeId", StringUtils.removeAndHump( "some-id", "-" ) ); - Locale.setDefault( l ); + Locale.setDefault(new Locale("tr")); + assertEquals("Id", StringUtils.removeAndHump("id", "-")); + assertEquals("SomeId", StringUtils.removeAndHump("some-id", "-")); + Locale.setDefault(l); } /** *

      testQuote_EscapeEmbeddedSingleQuotes.

      */ @Test - public void testQuote_EscapeEmbeddedSingleQuotes() - { + public void testQuote_EscapeEmbeddedSingleQuotes() { String src = "This \'is a\' test"; String check = "\'This \\\'is a\\\' test\'"; - char[] escaped = { '\'', '\"' }; - String result = StringUtils.quoteAndEscape( src, '\'', escaped, '\\', false ); + char[] escaped = {'\'', '\"'}; + String result = StringUtils.quoteAndEscape(src, '\'', escaped, '\\', false); - assertEquals( check, result ); + assertEquals(check, result); } /** *

      testQuote_EscapeEmbeddedSingleQuotesWithPattern.

      */ @Test - public void testQuote_EscapeEmbeddedSingleQuotesWithPattern() - { + public void testQuote_EscapeEmbeddedSingleQuotesWithPattern() { String src = "This \'is a\' test"; String check = "\'This pre'postis apre'post test\'"; - char[] escaped = { '\'', '\"' }; - String result = StringUtils.quoteAndEscape( src, '\'', escaped, new char[] { ' ' }, "pre%spost", false ); + char[] escaped = {'\'', '\"'}; + String result = StringUtils.quoteAndEscape(src, '\'', escaped, new char[] {' '}, "pre%spost", false); - assertEquals( check, result ); + assertEquals(check, result); } /** *

      testQuote_EscapeEmbeddedDoubleQuotesAndSpaces.

      */ @Test - public void testQuote_EscapeEmbeddedDoubleQuotesAndSpaces() - { + public void testQuote_EscapeEmbeddedDoubleQuotesAndSpaces() { String src = "This \"is a\" test"; String check = "\'This\\ \\\"is\\ a\\\"\\ test\'"; - char[] escaped = { '\'', '\"', ' ' }; - String result = StringUtils.quoteAndEscape( src, '\'', escaped, '\\', false ); + char[] escaped = {'\'', '\"', ' '}; + String result = StringUtils.quoteAndEscape(src, '\'', escaped, '\\', false); - assertEquals( check, result ); + assertEquals(check, result); } /** *

      testQuote_DontQuoteIfUnneeded.

      */ @Test - public void testQuote_DontQuoteIfUnneeded() - { + public void testQuote_DontQuoteIfUnneeded() { String src = "ThisIsATest"; - char[] escaped = { '\'', '\"' }; - String result = StringUtils.quoteAndEscape( src, '\'', escaped, '\\', false ); + char[] escaped = {'\'', '\"'}; + String result = StringUtils.quoteAndEscape(src, '\'', escaped, '\\', false); - assertEquals( src, result ); + assertEquals(src, result); } /** *

      testQuote_WrapWithSingleQuotes.

      */ @Test - public void testQuote_WrapWithSingleQuotes() - { + public void testQuote_WrapWithSingleQuotes() { String src = "This is a test"; String check = "\'This is a test\'"; - char[] escaped = { '\'', '\"' }; - String result = StringUtils.quoteAndEscape( src, '\'', escaped, '\\', false ); + char[] escaped = {'\'', '\"'}; + String result = StringUtils.quoteAndEscape(src, '\'', escaped, '\\', false); - assertEquals( check, result ); + assertEquals(check, result); } /** *

      testQuote_PreserveExistingQuotes.

      */ @Test - public void testQuote_PreserveExistingQuotes() - { + public void testQuote_PreserveExistingQuotes() { String src = "\'This is a test\'"; - char[] escaped = { '\'', '\"' }; - String result = StringUtils.quoteAndEscape( src, '\'', escaped, '\\', false ); + char[] escaped = {'\'', '\"'}; + String result = StringUtils.quoteAndEscape(src, '\'', escaped, '\\', false); - assertEquals( src, result ); + assertEquals(src, result); } /** *

      testQuote_WrapExistingQuotesWhenForceIsTrue.

      */ @Test - public void testQuote_WrapExistingQuotesWhenForceIsTrue() - { + public void testQuote_WrapExistingQuotesWhenForceIsTrue() { String src = "\'This is a test\'"; String check = "\'\\\'This is a test\\\'\'"; - char[] escaped = { '\'', '\"' }; - String result = StringUtils.quoteAndEscape( src, '\'', escaped, '\\', true ); + char[] escaped = {'\'', '\"'}; + String result = StringUtils.quoteAndEscape(src, '\'', escaped, '\\', true); - assertEquals( check, result ); + assertEquals(check, result); } /** *

      testQuote_ShortVersion_SingleQuotesPreserved.

      */ @Test - public void testQuote_ShortVersion_SingleQuotesPreserved() - { + public void testQuote_ShortVersion_SingleQuotesPreserved() { String src = "\'This is a test\'"; - String result = StringUtils.quoteAndEscape( src, '\'' ); + String result = StringUtils.quoteAndEscape(src, '\''); - assertEquals( src, result ); + assertEquals(src, result); } /** *

      testSplit.

      */ @Test - public void testSplit() - { + public void testSplit() { String[] tokens; - tokens = StringUtils.split( "", ", " ); - assertNotNull( tokens ); - assertEquals( Arrays.asList( new String[0] ), Arrays.asList( tokens ) ); + tokens = StringUtils.split("", ", "); + assertNotNull(tokens); + assertEquals(Arrays.asList(new String[0]), Arrays.asList(tokens)); - tokens = StringUtils.split( ", ,,, ,", ", " ); - assertNotNull( tokens ); - assertEquals( Arrays.asList( new String[0] ), Arrays.asList( tokens ) ); + tokens = StringUtils.split(", ,,, ,", ", "); + assertNotNull(tokens); + assertEquals(Arrays.asList(new String[0]), Arrays.asList(tokens)); - tokens = StringUtils.split( "this", ", " ); - assertNotNull( tokens ); - assertEquals( Arrays.asList( new String[] { "this" } ), Arrays.asList( tokens ) ); + tokens = StringUtils.split("this", ", "); + assertNotNull(tokens); + assertEquals(Arrays.asList(new String[] {"this"}), Arrays.asList(tokens)); - tokens = StringUtils.split( "this is a test", ", " ); - assertNotNull( tokens ); - assertEquals( Arrays.asList( new String[] { "this", "is", "a", "test" } ), Arrays.asList( tokens ) ); + tokens = StringUtils.split("this is a test", ", "); + assertNotNull(tokens); + assertEquals(Arrays.asList(new String[] {"this", "is", "a", "test"}), Arrays.asList(tokens)); - tokens = StringUtils.split( " this is a test ", ", " ); - assertNotNull( tokens ); - assertEquals( Arrays.asList( new String[] { "this", "is", "a", "test" } ), Arrays.asList( tokens ) ); + tokens = StringUtils.split(" this is a test ", ", "); + assertNotNull(tokens); + assertEquals(Arrays.asList(new String[] {"this", "is", "a", "test"}), Arrays.asList(tokens)); - tokens = StringUtils.split( "this is a test, really", ", " ); - assertNotNull( tokens ); - assertEquals( Arrays.asList( new String[] { "this", "is", "a", "test", "really" } ), Arrays.asList( tokens ) ); + tokens = StringUtils.split("this is a test, really", ", "); + assertNotNull(tokens); + assertEquals(Arrays.asList(new String[] {"this", "is", "a", "test", "really"}), Arrays.asList(tokens)); } /** @@ -321,18 +300,15 @@ public void testSplit() * @throws java.lang.Exception if any. */ @Test - public void testRemoveDuplicateWhitespace() - throws Exception - { + public void testRemoveDuplicateWhitespace() throws Exception { String s = "this is test "; - assertEquals( "this is test ", StringUtils.removeDuplicateWhitespace( s ) ); + assertEquals("this is test ", StringUtils.removeDuplicateWhitespace(s)); s = "this \r\n is \n \r test "; - assertEquals( "this is test ", StringUtils.removeDuplicateWhitespace( s ) ); + assertEquals("this is test ", StringUtils.removeDuplicateWhitespace(s)); s = " this \r\n is \n \r test"; - assertEquals( " this is test", StringUtils.removeDuplicateWhitespace( s ) ); + assertEquals(" this is test", StringUtils.removeDuplicateWhitespace(s)); s = "this \r\n is \n \r test \n "; - assertEquals( "this is test ", StringUtils.removeDuplicateWhitespace( s ) ); - + assertEquals("this is test ", StringUtils.removeDuplicateWhitespace(s)); } /** @@ -341,22 +317,17 @@ public void testRemoveDuplicateWhitespace() * @throws java.lang.Exception if any. */ @Test - public void testUnifyLineSeparators() - throws Exception - { + public void testUnifyLineSeparators() throws Exception { String s = "this\r\nis\na\r\ntest"; - try - { - StringUtils.unifyLineSeparators( s, "abs" ); - assertTrue( "Exception NOT catched", false ); - } - catch ( IllegalArgumentException e ) - { - assertTrue( "Exception catched", true ); + try { + StringUtils.unifyLineSeparators(s, "abs"); + assertTrue("Exception NOT catched", false); + } catch (IllegalArgumentException e) { + assertTrue("Exception catched", true); } - assertEquals( "this\nis\na\ntest", StringUtils.unifyLineSeparators( s, "\n" ) ); - assertEquals( "this\r\nis\r\na\r\ntest", StringUtils.unifyLineSeparators( s, "\r\n" ) ); + assertEquals("this\nis\na\ntest", StringUtils.unifyLineSeparators(s, "\n")); + assertEquals("this\r\nis\r\na\r\ntest", StringUtils.unifyLineSeparators(s, "\r\n")); } } diff --git a/src/test/java/org/codehaus/plexus/util/SweeperPoolTest.java b/src/test/java/org/codehaus/plexus/util/SweeperPoolTest.java index a642b5a2..2ca71500 100644 --- a/src/test/java/org/codehaus/plexus/util/SweeperPoolTest.java +++ b/src/test/java/org/codehaus/plexus/util/SweeperPoolTest.java @@ -16,6 +16,12 @@ * limitations under the License. */ +import java.util.Vector; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; @@ -23,12 +29,6 @@ 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 * @@ -36,8 +36,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class SweeperPoolTest -{ +public class SweeperPoolTest { /** The pool under test */ TestObjectPool pool; @@ -58,44 +57,44 @@ public class SweeperPoolTest * Test the pool limits it's size, and disposes unneeded objects correctly */ @Test - public void testMaxSize() - { + public void testMaxSize() { int sweepInterval = 0; int initialCapacity = 5; int maxSize = 2; int minSize = 1; int triggerSize = 2; - pool = new TestObjectPool( maxSize, minSize, initialCapacity, sweepInterval, triggerSize ); + pool = new TestObjectPool(maxSize, minSize, initialCapacity, sweepInterval, triggerSize); Object tmp = pool.get(); - assertNull( "Expected object from pool to be null", tmp ); - pool.put( o1 ); - assertEquals( "Expected pool to contain 1 object", 1, pool.getSize() ); + assertNull("Expected object from pool to be null", tmp); + pool.put(o1); + assertEquals("Expected pool to contain 1 object", 1, pool.getSize()); tmp = pool.get(); - assertSame( "Expected returned pool object to be the same as the one put in", tmp, o1 ); - pool.put( o1 ); - pool.put( o2 ); - assertEquals( "Expected pool to contain 2 objects", 2, pool.getSize() ); - pool.put( o3 ); - assertEquals( "Expected pool to contain only a maximum of 2 objects.", 2, pool.getSize() ); - assertEquals( "Expected 1 disposed pool object", 1, pool.testGetDisposedObjects().size() ); + assertSame("Expected returned pool object to be the same as the one put in", tmp, o1); + pool.put(o1); + pool.put(o2); + assertEquals("Expected pool to contain 2 objects", 2, pool.getSize()); + pool.put(o3); + assertEquals("Expected pool to contain only a maximum of 2 objects.", 2, pool.getSize()); + assertEquals( + "Expected 1 disposed pool object", + 1, + pool.testGetDisposedObjects().size()); tmp = pool.testGetDisposedObjects().iterator().next(); tmp = pool.get(); - assertEquals( "Expected pool size to be 1 after removing one object", 1, pool.getSize() ); + assertEquals("Expected pool size to be 1 after removing one object", 1, pool.getSize()); Object tmp2 = pool.get(); - assertEquals( "Expected pool size to be 0 after removing 2 objects", 0, pool.getSize() ); - assertNotSame( "Expected returned objects to be different", tmp, tmp2 ); - + assertEquals("Expected pool size to be 0 after removing 2 objects", 0, pool.getSize()); + assertNotSame("Expected returned objects to be different", tmp, tmp2); } /** *

      testSweepAndTrim1.

      */ @Test - public void testSweepAndTrim1() - { + public void testSweepAndTrim1() { // test trigger int sweepInterval = 1; int initialCapacity = 5; @@ -103,26 +102,22 @@ public void testSweepAndTrim1() int minSize = 1; int triggerSize = 2; - pool = new TestObjectPool( maxSize, minSize, initialCapacity, sweepInterval, triggerSize ); - pool.put( o1 ); - pool.put( o2 ); - pool.put( o3 ); - pool.put( o4 ); + pool = new TestObjectPool(maxSize, minSize, initialCapacity, sweepInterval, triggerSize); + pool.put(o1); + pool.put(o2); + pool.put(o3); + pool.put(o4); // give the sweeper some time to run - synchronized ( this ) - { - try - { - wait( 2 * 1000 ); - } - catch ( InterruptedException e ) - { - fail( "Unexpected exception thrown. e=" + Tracer.traceToString( e ) ); + synchronized (this) { + try { + wait(2 * 1000); + } catch (InterruptedException e) { + fail("Unexpected exception thrown. e=" + Tracer.traceToString(e)); } } - assertEquals( "Expected pool to only contain 1 object", 1, pool.getSize() ); - assertEquals( "Expected 3 disposed objects", 3, pool.testGetDisposedObjects().size() ); - + assertEquals("Expected pool to only contain 1 object", 1, pool.getSize()); + assertEquals( + "Expected 3 disposed objects", 3, pool.testGetDisposedObjects().size()); } /** @@ -131,9 +126,7 @@ public void testSweepAndTrim1() * @throws java.lang.Exception if any. */ @Before - public void setUp() - throws Exception - { + public void setUp() throws Exception { o1 = new Object(); o2 = new Object(); o3 = new Object(); @@ -148,43 +141,32 @@ public void setUp() * @throws java.lang.Exception if any. */ @After - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { pool.dispose(); - assertTrue( pool.isDisposed() ); + assertTrue(pool.isDisposed()); pool = null; - } - class TestObjectPool - extends SweeperPool - { + class TestObjectPool extends SweeperPool { private Vector disposedObjects = new Vector(); - public TestObjectPool( int maxSize, int minSize, int intialCapacity, int sweepInterval, int triggerSize ) - { - super( maxSize, minSize, intialCapacity, sweepInterval, triggerSize ); + public TestObjectPool(int maxSize, int minSize, int intialCapacity, int sweepInterval, int triggerSize) { + super(maxSize, minSize, intialCapacity, sweepInterval, triggerSize); } - public void reset() - { + public void reset() { disposedObjects.clear(); } /** * @see nz.co.bonzo.beans.castor.pool.ObjectPool#objectDisposed(java.lang.Object) */ - public void objectDisposed( Object obj ) - { - disposedObjects.add( obj ); + public void objectDisposed(Object obj) { + disposedObjects.add(obj); } - public Vector testGetDisposedObjects() - { + public Vector testGetDisposedObjects() { return disposedObjects; } - } - } diff --git a/src/test/java/org/codehaus/plexus/util/TestThreadManager.java b/src/test/java/org/codehaus/plexus/util/TestThreadManager.java index 1ee704b2..dda5b3b6 100644 --- a/src/test/java/org/codehaus/plexus/util/TestThreadManager.java +++ b/src/test/java/org/codehaus/plexus/util/TestThreadManager.java @@ -17,7 +17,6 @@ */ import java.util.Collection; -import java.util.Iterator; import java.util.Vector; import java.util.logging.Logger; @@ -32,8 +31,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class TestThreadManager -{ +public class TestThreadManager { // ~ Instance fields ---------------------------------------------------------------------------- /** Test threads which have completed running */ @@ -60,8 +58,7 @@ public class TestThreadManager * * @param notify a {@link java.lang.Object} object. */ - public TestThreadManager( Object notify ) - { + public TestThreadManager(Object notify) { super(); this.notify = notify; } @@ -73,23 +70,20 @@ public TestThreadManager( Object notify ) * * @return a {@link java.util.Collection} object. */ - public Collection getRunThreads() - { + public Collection getRunThreads() { return runThreads; } /** *

      runTestThreads.

      */ - public void runTestThreads() - { + public void runTestThreads() { failedThreads.clear(); // use an array as the tests may run very quickly // and modify the toRunThreads vector and hence // cause a Concurrent ModificationException on an // iterator - for ( AbstractTestThread toRunThread : toRunThreads ) - { + for (AbstractTestThread toRunThread : toRunThreads) { toRunThread.start(); } } @@ -99,8 +93,7 @@ public void runTestThreads() * * @return a {@link java.util.Collection} object. */ - public Collection getFailedTests() - { + public Collection getFailedTests() { return failedThreads; } @@ -109,8 +102,7 @@ public Collection getFailedTests() * * @return a {@link java.lang.Object} object. */ - public Object getNotifyObject() - { + public Object getNotifyObject() { return notify; } @@ -119,8 +111,7 @@ public Object getNotifyObject() * * @return a boolean. */ - public boolean hasFailedThreads() - { + public boolean hasFailedThreads() { return !failedThreads.isEmpty(); } @@ -129,8 +120,7 @@ public boolean hasFailedThreads() * * @return DOCUMENT ME! */ - public boolean isStillRunningThreads() - { + public boolean isStillRunningThreads() { return !toRunThreads.isEmpty(); } @@ -139,16 +129,14 @@ public boolean isStillRunningThreads() * * @return a {@link java.util.Collection} object. */ - public Collection getToRunThreads() - { + public Collection getToRunThreads() { return toRunThreads; } /** * DOCUMENT ME! */ - public void clear() - { + public void clear() { toRunThreads.clear(); runThreads.clear(); failedThreads.clear(); @@ -163,20 +151,16 @@ public void clear() * * @param thread a {@link org.codehaus.plexus.util.AbstractTestThread} object. */ - public synchronized void completed( AbstractTestThread thread ) - { - toRunThreads.remove( thread ); - runThreads.add( thread ); - if ( thread.hasFailed() ) - { - failedThreads.add( thread ); + public synchronized void completed(AbstractTestThread thread) { + toRunThreads.remove(thread); + runThreads.add(thread); + if (thread.hasFailed()) { + failedThreads.add(thread); } // wakeup thread which is waiting for the threads to complete // execution - if ( toRunThreads.isEmpty() ) - { - synchronized ( notify ) - { + if (toRunThreads.isEmpty()) { + synchronized (notify) { notify.notify(); } } @@ -187,37 +171,30 @@ public synchronized void completed( AbstractTestThread thread ) * * @param thread DOCUMENT ME! */ - public void doRegisterThread( AbstractTestThread thread ) - { - } + public void doRegisterThread(AbstractTestThread thread) {} /** *

      registerThread.

      * * @param thread a {@link org.codehaus.plexus.util.AbstractTestThread} object. */ - public final void registerThread( AbstractTestThread thread ) - { - thread.setThreadRegistry( this ); - if ( toRunThreads.contains( thread ) == false ) - { - toRunThreads.add( thread ); - doRegisterThread( thread ); + public final void registerThread(AbstractTestThread thread) { + thread.setThreadRegistry(this); + if (toRunThreads.contains(thread) == false) { + toRunThreads.add(thread); + doRegisterThread(thread); } - } /** * Put all the runThreads back in the que to be run again and clear the failedTest collection */ - public void reset() - { + public void reset() { toRunThreads.clear(); - for ( Object runThread : runThreads ) - { + for (Object runThread : runThreads) { AbstractTestThread test = (AbstractTestThread) runThread; test.reset(); - registerThread( test ); + registerThread(test); } runThreads.clear(); diff --git a/src/test/java/org/codehaus/plexus/util/Tracer.java b/src/test/java/org/codehaus/plexus/util/Tracer.java index 5bf4f84d..d5ff964d 100644 --- a/src/test/java/org/codehaus/plexus/util/Tracer.java +++ b/src/test/java/org/codehaus/plexus/util/Tracer.java @@ -29,14 +29,12 @@ * @version $Id: $Id * @since 3.4.0 */ -public class Tracer -{ +public class Tracer { /** * Constructor */ - private Tracer() - { + private Tracer() { super(); } @@ -46,15 +44,12 @@ private Tracer() * @param t a {@link java.lang.Throwable} object. * @return a {@link java.lang.String} object. */ - public static String traceToString( Throwable t ) - { - if ( t == null ) - { + public static String traceToString(Throwable t) { + if (t == null) { return null; } StringWriter sw = new StringWriter(); - t.printStackTrace( new PrintWriter( sw ) ); + t.printStackTrace(new PrintWriter(sw)); return sw.toString(); } - } diff --git a/src/test/java/org/codehaus/plexus/util/WalkCollector.java b/src/test/java/org/codehaus/plexus/util/WalkCollector.java index c5c4e018..183e7f94 100644 --- a/src/test/java/org/codehaus/plexus/util/WalkCollector.java +++ b/src/test/java/org/codehaus/plexus/util/WalkCollector.java @@ -20,9 +20,7 @@ import java.util.ArrayList; import java.util.List; -class WalkCollector - implements DirectoryWalkListener -{ +class WalkCollector implements DirectoryWalkListener { public List steps; public File startingDir; @@ -38,8 +36,7 @@ class WalkCollector /** *

      Constructor for WalkCollector.

      */ - public WalkCollector() - { + public WalkCollector() { steps = new ArrayList(); startCount = 0; finishCount = 0; @@ -48,34 +45,30 @@ public WalkCollector() } /** {@inheritDoc} */ - public void directoryWalkStarting( File basedir ) - { - debug( "Walk Starting: " + basedir ); + public void directoryWalkStarting(File basedir) { + debug("Walk Starting: " + basedir); startCount++; startingDir = basedir; } /** {@inheritDoc} */ - public void directoryWalkStep( int percentage, File file ) - { - percentageLow = Math.min( percentageLow, percentage ); - percentageHigh = Math.max( percentageHigh, percentage ); - debug( "Walk Step: [" + percentage + "%] " + file ); - steps.add( file ); + public void directoryWalkStep(int percentage, File file) { + percentageLow = Math.min(percentageLow, percentage); + percentageHigh = Math.max(percentageHigh, percentage); + debug("Walk Step: [" + percentage + "%] " + file); + steps.add(file); } /** *

      directoryWalkFinished.

      */ - public void directoryWalkFinished() - { - debug( "Walk Finished." ); + public void directoryWalkFinished() { + debug("Walk Finished."); finishCount++; } /** {@inheritDoc} */ - public void debug( String message ) - { - System.out.println( message ); + public void debug(String message) { + System.out.println(message); } } 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 92cdaa2d..976551c7 100644 --- a/src/test/java/org/codehaus/plexus/util/cli/CommandLineUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/cli/CommandLineUtilsTest.java @@ -16,10 +16,6 @@ * limitations under the License. */ -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; @@ -27,6 +23,10 @@ import org.codehaus.plexus.util.Os; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + /** *

      CommandLineUtilsTest class.

      * @@ -34,39 +34,31 @@ * @version $Id: $Id * @since 3.4.0 */ -@SuppressWarnings( { "JavaDoc", "deprecation" } ) -public class CommandLineUtilsTest -{ +@SuppressWarnings({"JavaDoc", "deprecation"}) +public class CommandLineUtilsTest { /** *

      testQuoteArguments.

      */ @Test - public void testQuoteArguments() - { - try - { - String result = CommandLineUtils.quote( "Hello" ); - System.out.println( result ); - assertEquals( "Hello", result ); - result = CommandLineUtils.quote( "Hello World" ); - System.out.println( result ); - assertEquals( "\"Hello World\"", result ); - result = CommandLineUtils.quote( "\"Hello World\"" ); - System.out.println( result ); - assertEquals( "\'\"Hello World\"\'", result ); - } - catch ( Exception e ) - { - fail( e.getMessage() ); + public void testQuoteArguments() { + try { + String result = CommandLineUtils.quote("Hello"); + System.out.println(result); + assertEquals("Hello", result); + result = CommandLineUtils.quote("Hello World"); + System.out.println(result); + assertEquals("\"Hello World\"", result); + result = CommandLineUtils.quote("\"Hello World\""); + System.out.println(result); + assertEquals("\'\"Hello World\"\'", result); + } catch (Exception e) { + fail(e.getMessage()); } - try - { - CommandLineUtils.quote( "\"Hello \'World\'\'" ); + try { + CommandLineUtils.quote("\"Hello \'World\'\'"); fail(); - } - catch ( Exception e ) - { + } catch (Exception e) { } } @@ -76,14 +68,11 @@ public void testQuoteArguments() * @throws java.lang.Exception if any. */ @Test - public void testGetSystemEnvVarsCaseInsensitive() - throws Exception - { - Properties vars = CommandLineUtils.getSystemEnvVars( false ); - for ( Object o : vars.keySet() ) - { + public void testGetSystemEnvVarsCaseInsensitive() throws Exception { + Properties vars = CommandLineUtils.getSystemEnvVars(false); + for (Object o : vars.keySet()) { String variable = (String) o; - assertEquals( variable.toUpperCase( Locale.ENGLISH ), variable ); + assertEquals(variable.toUpperCase(Locale.ENGLISH), variable); } } @@ -93,18 +82,14 @@ public void testGetSystemEnvVarsCaseInsensitive() * @throws java.lang.Exception if any. */ @Test - public void testGetSystemEnvVarsWindows() - throws Exception - { - if ( !Os.isFamily( Os.FAMILY_WINDOWS ) ) - { + public void testGetSystemEnvVarsWindows() throws Exception { + if (!Os.isFamily(Os.FAMILY_WINDOWS)) { return; } Properties vars = CommandLineUtils.getSystemEnvVars(); - for ( Object o : vars.keySet() ) - { + for (Object o : vars.keySet()) { String variable = (String) o; - assertEquals( variable.toUpperCase( Locale.ENGLISH ), variable ); + assertEquals(variable.toUpperCase(Locale.ENGLISH), variable); } } @@ -114,29 +99,24 @@ public void testGetSystemEnvVarsWindows() * @throws java.lang.Exception if any. */ @Test - public void testTranslateCommandline() - throws Exception - { - assertCmdLineArgs( new String[] {}, null ); - assertCmdLineArgs( new String[] {}, "" ); + public void testTranslateCommandline() throws Exception { + assertCmdLineArgs(new String[] {}, null); + assertCmdLineArgs(new String[] {}, ""); - assertCmdLineArgs( new String[] { "foo", "bar" }, "foo bar" ); - assertCmdLineArgs( new String[] { "foo", "bar" }, " foo bar " ); + assertCmdLineArgs(new String[] {"foo", "bar"}, "foo bar"); + assertCmdLineArgs(new String[] {"foo", "bar"}, " foo bar "); - assertCmdLineArgs( new String[] { "foo", " double quotes ", "bar" }, "foo \" double quotes \" bar" ); - assertCmdLineArgs( new String[] { "foo", " single quotes ", "bar" }, "foo ' single quotes ' bar" ); + assertCmdLineArgs(new String[] {"foo", " double quotes ", "bar"}, "foo \" double quotes \" bar"); + assertCmdLineArgs(new String[] {"foo", " single quotes ", "bar"}, "foo ' single quotes ' bar"); - assertCmdLineArgs( new String[] { "foo", " \" ", "bar" }, "foo ' \" ' bar" ); - assertCmdLineArgs( new String[] { "foo", " ' ", "bar" }, "foo \" ' \" bar" ); + assertCmdLineArgs(new String[] {"foo", " \" ", "bar"}, "foo ' \" ' bar"); + assertCmdLineArgs(new String[] {"foo", " ' ", "bar"}, "foo \" ' \" bar"); } - private void assertCmdLineArgs( String[] expected, String cmdLine ) - throws Exception - { - String[] actual = CommandLineUtils.translateCommandline( cmdLine ); - assertNotNull( actual ); - assertEquals( expected.length, actual.length ); - assertEquals( Arrays.asList( expected ), Arrays.asList( actual ) ); + private void assertCmdLineArgs(String[] expected, String cmdLine) throws Exception { + String[] actual = CommandLineUtils.translateCommandline(cmdLine); + assertNotNull(actual); + assertEquals(expected.length, actual.length); + assertEquals(Arrays.asList(expected), Arrays.asList(actual)); } - } 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 15cb9744..bdcf5556 100644 --- a/src/test/java/org/codehaus/plexus/util/cli/CommandlineTest.java +++ b/src/test/java/org/codehaus/plexus/util/cli/CommandlineTest.java @@ -16,15 +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.IOException; import java.io.Writer; import java.nio.file.Files; -import java.nio.file.Paths; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.Os; @@ -35,6 +30,10 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** *

      CommandlineTest class.

      * @@ -42,8 +41,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class CommandlineTest -{ +public class CommandlineTest { private String baseDir; /** @@ -52,14 +50,11 @@ public class CommandlineTest * @throws java.lang.Exception if any. */ @Before - public void setUp() - throws Exception - { - baseDir = System.getProperty( "basedir" ); - - if ( baseDir == null ) - { - baseDir = new File( "." ).getCanonicalPath(); + public void setUp() throws Exception { + baseDir = System.getProperty("basedir"); + + if (baseDir == null) { + baseDir = new File(".").getCanonicalPath(); } } @@ -67,28 +62,26 @@ public void setUp() *

      testCommandlineWithoutCommandInConstructor.

      */ @Test - public void testCommandlineWithoutCommandInConstructor() - { - Commandline cmd = new Commandline( new Shell() ); - cmd.setWorkingDirectory( baseDir ); - cmd.createArgument().setValue( "cd" ); - cmd.createArgument().setValue( "." ); + public void testCommandlineWithoutCommandInConstructor() { + 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() ); + assertEquals("cd .", cmd.toString()); } /** *

      testCommandlineWithCommandInConstructor.

      */ @Test - public void testCommandlineWithCommandInConstructor() - { - Commandline cmd = new Commandline( "cd .", new Shell() ); - cmd.setWorkingDirectory( baseDir ); + public void testCommandlineWithCommandInConstructor() { + 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() ); + assertEquals("cd .", cmd.toString()); } /** @@ -97,20 +90,18 @@ public void testCommandlineWithCommandInConstructor() * @throws java.lang.Exception if any. */ @Test - public void testExecuteBinaryOnPath() - throws Exception - { + public void testExecuteBinaryOnPath() throws Exception { // 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" ); + 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:" ) ); + String out = IOUtil.toString(process.getInputStream()); + assertTrue(out.contains("Apache Maven")); + assertTrue(out.contains("Maven home:")); + assertTrue(out.contains("Java version:")); } /** @@ -119,70 +110,64 @@ public void testExecuteBinaryOnPath() * @throws java.lang.Exception if any. */ @Test - public void testExecute() - throws Exception - { + public void testExecute() throws Exception { // 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" ); + 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() ); + assertEquals("Hello", IOUtil.toString(process.getInputStream()).trim()); } /** *

      testSetLine.

      */ @Test - public void testSetLine() - { - Commandline cmd = new Commandline( new Shell() ); - cmd.setWorkingDirectory( baseDir ); - cmd.setExecutable( "echo" ); - cmd.createArgument().setLine( null ); - cmd.createArgument().setLine( "Hello" ); + public void testSetLine() { + 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() ); + assertEquals("echo Hello", cmd.toString()); } /** *

      testCreateCommandInReverseOrder.

      */ @Test - public void testCreateCommandInReverseOrder() - { - Commandline cmd = new Commandline( new Shell() ); - cmd.setWorkingDirectory( baseDir ); - cmd.createArgument().setValue( "." ); - cmd.createArgument( true ).setValue( "cd" ); + public void testCreateCommandInReverseOrder() { + 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() ); + assertEquals("cd .", cmd.toString()); } /** *

      testSetFile.

      */ @Test - public void testSetFile() - { - Commandline cmd = new Commandline( new Shell() ); - cmd.setWorkingDirectory( baseDir ); - cmd.createArgument().setValue( "more" ); - File f = new File( "test.txt" ); - cmd.createArgument().setFile( f ); + public void testSetFile() { + 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( " " ) ) - { + if (fileName.contains(" ")) { fileName = "\"" + fileName + "\""; } // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. - assertEquals( "more " + fileName, cmd.toString() ); + assertEquals("more " + fileName, cmd.toString()); } /** @@ -191,22 +176,20 @@ public void testSetFile() * @throws java.lang.Exception if any. */ @Test - public void testGetShellCommandLineWindows() - throws Exception - { - Commandline cmd = new Commandline( new CmdShell() ); - cmd.setExecutable( "c:\\Program Files\\xxx" ); - cmd.addArguments( new String[] { "a", "b" } ); + public void testGetShellCommandLineWindows() throws Exception { + Commandline cmd = new Commandline(new CmdShell()); + cmd.setExecutable("c:\\Program Files\\xxx"); + cmd.addArguments(new String[] {"a", "b"}); String[] shellCommandline = cmd.getShellCommandline(); - assertEquals( "Command line size", 4, shellCommandline.length ); + assertEquals("Command line size", 4, shellCommandline.length); - assertEquals( "cmd.exe", shellCommandline[0] ); - assertEquals( "/X", shellCommandline[1] ); - assertEquals( "/C", shellCommandline[2] ); + assertEquals("cmd.exe", shellCommandline[0]); + assertEquals("/X", shellCommandline[1]); + assertEquals("/C", shellCommandline[2]); String expectedShellCmd = "\"c:" + File.separator + "Program Files" + File.separator + "xxx\" a b"; expectedShellCmd = "\"" + expectedShellCmd + "\""; - assertEquals( expectedShellCmd, shellCommandline[3] ); + assertEquals(expectedShellCmd, shellCommandline[3]); } /** @@ -215,23 +198,21 @@ public void testGetShellCommandLineWindows() * @throws java.lang.Exception if any. */ @Test - public void testGetShellCommandLineWindowsWithSeveralQuotes() - throws Exception - { - Commandline cmd = new Commandline( new CmdShell() ); - cmd.setExecutable( "c:\\Program Files\\xxx" ); - cmd.addArguments( new String[] { "c:\\Documents and Settings\\whatever", "b" } ); + public void testGetShellCommandLineWindowsWithSeveralQuotes() throws Exception { + Commandline cmd = new Commandline(new CmdShell()); + cmd.setExecutable("c:\\Program Files\\xxx"); + cmd.addArguments(new String[] {"c:\\Documents and Settings\\whatever", "b"}); String[] shellCommandline = cmd.getShellCommandline(); - assertEquals( "Command line size", 4, shellCommandline.length ); + assertEquals("Command line size", 4, shellCommandline.length); - assertEquals( "cmd.exe", shellCommandline[0] ); - assertEquals( "/X", shellCommandline[1] ); - assertEquals( "/C", shellCommandline[2] ); + assertEquals("cmd.exe", shellCommandline[0]); + assertEquals("/X", shellCommandline[1]); + assertEquals("/C", shellCommandline[2]); String expectedShellCmd = "\"c:" + File.separator + "Program Files" + File.separator - + "xxx\" \"c:\\Documents and Settings\\whatever\" b"; + + "xxx\" \"c:\\Documents and Settings\\whatever\" b"; expectedShellCmd = "\"" + expectedShellCmd + "\""; - assertEquals( expectedShellCmd, shellCommandline[3] ); + assertEquals(expectedShellCmd, shellCommandline[3]); } /** @@ -240,25 +221,22 @@ public void testGetShellCommandLineWindowsWithSeveralQuotes() * @throws java.lang.Exception */ @Test - public void testGetShellCommandLineBash() - throws Exception - { - Commandline cmd = new Commandline( new BourneShell() ); - cmd.setExecutable( "/bin/echo" ); - cmd.addArguments( new String[] { "hello world" } ); + public void testGetShellCommandLineBash() throws Exception { + Commandline cmd = new Commandline(new BourneShell()); + cmd.setExecutable("/bin/echo"); + cmd.addArguments(new String[] {"hello world"}); String[] shellCommandline = cmd.getShellCommandline(); - assertEquals( "Command line size", 3, shellCommandline.length ); + assertEquals("Command line size", 3, shellCommandline.length); - assertEquals( "/bin/sh", shellCommandline[0] ); - assertEquals( "-c", shellCommandline[1] ); + assertEquals("/bin/sh", shellCommandline[0]); + assertEquals("-c", shellCommandline[1]); String expectedShellCmd = "'/bin/echo' 'hello world'"; - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { + if (Os.isFamily(Os.FAMILY_WINDOWS)) { expectedShellCmd = "'\\bin\\echo' \'hello world\'"; } - assertEquals( expectedShellCmd, shellCommandline[2] ); + assertEquals(expectedShellCmd, shellCommandline[2]); } /** @@ -267,28 +245,25 @@ public void testGetShellCommandLineBash() * @throws java.lang.Exception */ @Test - public void testGetShellCommandLineBash_WithWorkingDirectory() - throws Exception - { - Commandline cmd = new Commandline( new BourneShell() ); - cmd.setExecutable( "/bin/echo" ); - cmd.addArguments( new String[] { "hello world" } ); + public void testGetShellCommandLineBash_WithWorkingDirectory() throws Exception { + Commandline cmd = new Commandline(new BourneShell()); + cmd.setExecutable("/bin/echo"); + cmd.addArguments(new String[] {"hello world"}); File root = File.listRoots()[0]; - File workingDirectory = new File( root, "path with spaces" ); - cmd.setWorkingDirectory( workingDirectory ); + File workingDirectory = new File(root, "path with spaces"); + cmd.setWorkingDirectory(workingDirectory); String[] shellCommandline = cmd.getShellCommandline(); - assertEquals( "Command line size", 3, shellCommandline.length ); + assertEquals("Command line size", 3, shellCommandline.length); - assertEquals( "/bin/sh", shellCommandline[0] ); - assertEquals( "-c", shellCommandline[1] ); + assertEquals("/bin/sh", shellCommandline[0]); + assertEquals("-c", shellCommandline[1]); String expectedShellCmd = "cd '" + root.getAbsolutePath() + "path with spaces' && '/bin/echo' 'hello world'"; - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { + if (Os.isFamily(Os.FAMILY_WINDOWS)) { expectedShellCmd = "cd '" + root.getAbsolutePath() + "path with spaces' && '\\bin\\echo' 'hello world'"; } - assertEquals( expectedShellCmd, shellCommandline[2] ); + assertEquals(expectedShellCmd, shellCommandline[2]); } /** @@ -297,25 +272,22 @@ public void testGetShellCommandLineBash_WithWorkingDirectory() * @throws java.lang.Exception */ @Test - public void testGetShellCommandLineBash_WithSingleQuotedArg() - throws Exception - { - Commandline cmd = new Commandline( new BourneShell() ); - cmd.setExecutable( "/bin/echo" ); - cmd.addArguments( new String[] { "\'hello world\'" } ); + public void testGetShellCommandLineBash_WithSingleQuotedArg() throws Exception { + Commandline cmd = new Commandline(new BourneShell()); + cmd.setExecutable("/bin/echo"); + cmd.addArguments(new String[] {"\'hello world\'"}); String[] shellCommandline = cmd.getShellCommandline(); - assertEquals( "Command line size", 3, shellCommandline.length ); + assertEquals("Command line size", 3, shellCommandline.length); - assertEquals( "/bin/sh", shellCommandline[0] ); - assertEquals( "-c", shellCommandline[1] ); + assertEquals("/bin/sh", shellCommandline[0]); + assertEquals("-c", shellCommandline[1]); String expectedShellCmd = "'/bin/echo' ''\"'\"'hello world'\"'\"''"; - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - expectedShellCmd = expectedShellCmd.replace( "/bin/echo", "\\bin\\echo" ); + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + expectedShellCmd = expectedShellCmd.replace("/bin/echo", "\\bin\\echo"); } - assertEquals( expectedShellCmd, shellCommandline[2] ); + assertEquals(expectedShellCmd, shellCommandline[2]); } /** @@ -324,26 +296,21 @@ public void testGetShellCommandLineBash_WithSingleQuotedArg() * @throws java.lang.Exception if any. */ @Test - public void testGetShellCommandLineNonWindows() - throws Exception - { - Commandline cmd = new Commandline( new BourneShell() ); - cmd.setExecutable( "/usr/bin" ); - cmd.addArguments( new String[] { "a", "b" } ); + public void testGetShellCommandLineNonWindows() throws Exception { + Commandline cmd = new Commandline(new BourneShell()); + cmd.setExecutable("/usr/bin"); + cmd.addArguments(new String[] {"a", "b"}); String[] shellCommandline = cmd.getShellCommandline(); - assertEquals( "Command line size", 3, shellCommandline.length ); + assertEquals("Command line size", 3, shellCommandline.length); - assertEquals( "/bin/sh", shellCommandline[0] ); - assertEquals( "-c", shellCommandline[1] ); + assertEquals("/bin/sh", shellCommandline[0]); + assertEquals("-c", shellCommandline[1]); - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - assertEquals( "'\\usr\\bin' 'a' 'b'", shellCommandline[2] ); - } - else - { - assertEquals( "'/usr/bin' 'a' 'b'", shellCommandline[2] ); + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + assertEquals("'\\usr\\bin' 'a' 'b'", shellCommandline[2]); + } else { + assertEquals("'/usr/bin' 'a' 'b'", shellCommandline[2]); } } @@ -353,12 +320,10 @@ public void testGetShellCommandLineNonWindows() * @throws java.lang.Exception if any. */ @Test - public void testEnvironment() - throws Exception - { + public void testEnvironment() throws Exception { Commandline cmd = new Commandline(); - cmd.addEnvironment( "name", "value" ); - assertEquals( "name=value", cmd.getEnvironmentVariables()[0] ); + cmd.addEnvironment("name", "value"); + assertEquals("name=value", cmd.getEnvironmentVariables()[0]); } /** @@ -367,23 +332,19 @@ public void testEnvironment() * @throws java.lang.Exception if any. */ @Test - public void testEnvironmentWitOverrideSystemEnvironment() - throws Exception - { + public void testEnvironmentWitOverrideSystemEnvironment() throws Exception { Commandline cmd = new Commandline(); cmd.addSystemEnvironment(); - cmd.addEnvironment( "JAVA_HOME", "/usr/jdk1.5" ); + cmd.addEnvironment("JAVA_HOME", "/usr/jdk1.5"); String[] environmentVariables = cmd.getEnvironmentVariables(); - for ( String environmentVariable : environmentVariables ) - { - if ( "JAVA_HOME=/usr/jdk1.5".equals( environmentVariable ) ) - { + for (String environmentVariable : environmentVariables) { + if ("JAVA_HOME=/usr/jdk1.5".equals(environmentVariable)) { return; } } - fail( "can't find JAVA_HOME=/usr/jdk1.5" ); + fail("can't find JAVA_HOME=/usr/jdk1.5"); } /** @@ -392,14 +353,12 @@ public void testEnvironmentWitOverrideSystemEnvironment() * @throws java.lang.Exception */ @Test - public void testQuotedPathWithSingleApostrophe() - throws Exception - { - File dir = new File( System.getProperty( "basedir" ), "target/test/quotedpath'test" ); - createAndCallScript( dir, "echo Quoted" ); - - dir = new File( System.getProperty( "basedir" ), "target/test/quoted path'test" ); - createAndCallScript( dir, "echo Quoted" ); + public void testQuotedPathWithSingleApostrophe() throws Exception { + File dir = new File(System.getProperty("basedir"), "target/test/quotedpath'test"); + createAndCallScript(dir, "echo Quoted"); + + dir = new File(System.getProperty("basedir"), "target/test/quoted path'test"); + createAndCallScript(dir, "echo Quoted"); } /** @@ -408,11 +367,9 @@ public void testQuotedPathWithSingleApostrophe() * @throws java.lang.Exception */ @Test - public void testPathWithShellExpansionStrings() - throws Exception - { - File dir = new File( System.getProperty( "basedir" ), "target/test/dollar$test" ); - createAndCallScript( dir, "echo Quoted" ); + public void testPathWithShellExpansionStrings() throws Exception { + File dir = new File(System.getProperty("basedir"), "target/test/dollar$test"); + createAndCallScript(dir, "echo Quoted"); } /** @@ -421,20 +378,17 @@ public void testPathWithShellExpansionStrings() * @throws java.lang.Exception */ @Test - public void testQuotedPathWithQuotationMark() - throws Exception - { - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - System.out.println( "testQuotedPathWithQuotationMark() skipped on Windows" ); + public void testQuotedPathWithQuotationMark() throws Exception { + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + System.out.println("testQuotedPathWithQuotationMark() skipped on Windows"); return; } - File dir = new File( System.getProperty( "basedir" ), "target/test/quotedpath\"test" ); - createAndCallScript( dir, "echo Quoted" ); + File dir = new File(System.getProperty("basedir"), "target/test/quotedpath\"test"); + createAndCallScript(dir, "echo Quoted"); - dir = new File( System.getProperty( "basedir" ), "target/test/quoted path\"test" ); - createAndCallScript( dir, "echo Quoted" ); + dir = new File(System.getProperty("basedir"), "target/test/quoted path\"test"); + createAndCallScript(dir, "echo Quoted"); } /** @@ -444,20 +398,17 @@ public void testQuotedPathWithQuotationMark() * @throws java.lang.Exception */ @Test - public void testQuotedPathWithQuotationMarkAndApostrophe() - throws Exception - { - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - System.out.println( "testQuotedPathWithQuotationMarkAndApostrophe() skipped on Windows" ); + public void testQuotedPathWithQuotationMarkAndApostrophe() throws Exception { + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + System.out.println("testQuotedPathWithQuotationMarkAndApostrophe() skipped on Windows"); return; } - File dir = new File( System.getProperty( "basedir" ), "target/test/quotedpath\"'test" ); - createAndCallScript( dir, "echo Quoted" ); + File dir = new File(System.getProperty("basedir"), "target/test/quotedpath\"'test"); + createAndCallScript(dir, "echo Quoted"); - dir = new File( System.getProperty( "basedir" ), "target/test/quoted path\"'test" ); - createAndCallScript( dir, "echo Quoted" ); + dir = new File(System.getProperty("basedir"), "target/test/quoted path\"'test"); + createAndCallScript(dir, "echo Quoted"); } /** @@ -466,34 +417,27 @@ public void testQuotedPathWithQuotationMarkAndApostrophe() * @throws java.lang.Exception */ @Test - public void testOnlyQuotedPath() - throws Exception - { - File dir = new File( System.getProperty( "basedir" ), "target/test/quotedpath\'test" ); + public void testOnlyQuotedPath() throws Exception { + File dir = new File(System.getProperty("basedir"), "target/test/quotedpath\'test"); - File javaHome = new File( System.getProperty( "java.home" ) ); + File javaHome = new File(System.getProperty("java.home")); File java; - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - java = new File( javaHome, "/bin/java.exe" ); - } - else - { - java = new File( javaHome, "/bin/java" ); + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + java = new File(javaHome, "/bin/java.exe"); + } else { + java = new File(javaHome, "/bin/java"); } - if ( !java.exists() ) - { - throw new IOException( java.getAbsolutePath() + " doesn't exist" ); + if (!java.exists()) { + throw new IOException(java.getAbsolutePath() + " doesn't exist"); } String javaBinStr = java.getAbsolutePath(); - if ( Os.isFamily( Os.FAMILY_WINDOWS ) && javaBinStr.contains( " " ) ) - { + if (Os.isFamily(Os.FAMILY_WINDOWS) && javaBinStr.contains(" ")) { javaBinStr = "\"" + javaBinStr + "\""; } - createAndCallScript( dir, javaBinStr + " -version" ); + createAndCallScript(dir, javaBinStr + " -version"); } /** @@ -502,38 +446,31 @@ public void testOnlyQuotedPath() * @throws java.lang.Exception if any. */ @Test - public void testDollarSignInArgumentPath() - throws Exception - { - File dir = new File( System.getProperty( "basedir" ), "target/test" ); - if ( !dir.exists() ) - { - assertTrue( "Can't create dir:" + dir.getAbsolutePath(), dir.mkdirs() ); + public void testDollarSignInArgumentPath() throws Exception { + File dir = new File(System.getProperty("basedir"), "target/test"); + if (!dir.exists()) { + assertTrue("Can't create dir:" + dir.getAbsolutePath(), dir.mkdirs()); } Writer writer = null; - try - { - writer = Files.newBufferedWriter( dir.toPath().resolve( "test$1.txt" ) ); - IOUtil.copy( "Success", writer ); - } - finally - { - IOUtil.close( writer ); + try { + writer = Files.newBufferedWriter(dir.toPath().resolve("test$1.txt")); + IOUtil.copy("Success", writer); + } finally { + IOUtil.close(writer); } Commandline cmd = new Commandline(); // cmd.getShell().setShellCommand( "/bin/sh" ); - cmd.getShell().setQuotedArgumentsEnabled( true ); - cmd.setExecutable( "cat" ); - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - cmd.setExecutable( "dir" ); + cmd.getShell().setQuotedArgumentsEnabled(true); + cmd.setExecutable("cat"); + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + cmd.setExecutable("dir"); } - cmd.setWorkingDirectory( dir ); - cmd.createArg().setLine( "test$1.txt" ); + cmd.setWorkingDirectory(dir); + cmd.createArg().setLine("test$1.txt"); - executeCommandLine( cmd ); + executeCommandLine(cmd); } /** @@ -542,39 +479,29 @@ public void testDollarSignInArgumentPath() * @throws java.lang.Exception if any. */ @Test - public void testTimeOutException() - throws Exception - { - File javaHome = new File( System.getProperty( "java.home" ) ); + public void testTimeOutException() throws Exception { + File javaHome = new File(System.getProperty("java.home")); File java; - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - java = new File( javaHome, "/bin/java.exe" ); - } - else - { - java = new File( javaHome, "/bin/java" ); + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + java = new File(javaHome, "/bin/java.exe"); + } else { + java = new File(javaHome, "/bin/java"); } - if ( !java.exists() ) - { - throw new IOException( java.getAbsolutePath() + " doesn't exist" ); + if (!java.exists()) { + throw new IOException(java.getAbsolutePath() + " doesn't exist"); } Commandline cli = new Commandline(); - cli.setExecutable( java.getAbsolutePath() ); - cli.createArg().setLine( "-version" ); + cli.setExecutable(java.getAbsolutePath()); + cli.createArg().setLine("-version"); CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); - try - { + try { // if the os is faster than 1s to execute java -version the unit will fail :-) - CommandLineUtils.executeCommandLine( cli, new DefaultConsumer(), err, 1 ); - } - catch ( CommandLineTimeOutException e ) - { + CommandLineUtils.executeCommandLine(cli, new DefaultConsumer(), err, 1); + } catch (CommandLineTimeOutException e) { // it works } - } /** @@ -583,31 +510,22 @@ public void testTimeOutException() * @param path not null * @throws IOException if any */ - private static void makeExecutable( File path ) - throws IOException - { - if ( path == null ) - { - throw new IllegalArgumentException( "The file is null" ); + private static void makeExecutable(File path) throws IOException { + if (path == null) { + throw new IllegalArgumentException("The file is null"); } - if ( !path.isFile() ) - { - throw new IllegalArgumentException( "The file '" + path.getAbsolutePath() + "' should be a file" ); + if (!path.isFile()) { + throw new IllegalArgumentException("The file '" + path.getAbsolutePath() + "' should be a file"); } - if ( !Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - Process proc = Runtime.getRuntime().exec( new String[] { "chmod", "a+x", path.getAbsolutePath() } ); - while ( true ) - { - try - { + if (!Os.isFamily(Os.FAMILY_WINDOWS)) { + Process proc = Runtime.getRuntime().exec(new String[] {"chmod", "a+x", path.getAbsolutePath()}); + while (true) { + try { proc.waitFor(); break; - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { // ignore } } @@ -622,44 +540,35 @@ private static void makeExecutable( File path ) * @param content the content of the script file * @throws Exception if any */ - private static void createAndCallScript( File dir, String content ) - throws Exception - { - if ( !dir.exists() ) - { - assertTrue( "Can't create dir:" + dir.getAbsolutePath(), dir.mkdirs() ); + private static void createAndCallScript(File dir, String content) throws Exception { + if (!dir.exists()) { + assertTrue("Can't create dir:" + dir.getAbsolutePath(), dir.mkdirs()); } // Create a script file File bat; - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - bat = new File( dir, "echo.bat" ); - } - else - { - bat = new File( dir, "echo" ); + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + bat = new File(dir, "echo.bat"); + } else { + bat = new File(dir, "echo"); } - Writer w = Files.newBufferedWriter( bat.toPath() ); - try - { - IOUtil.copy( content, w ); - } - finally - { - IOUtil.close( w ); + Writer w = Files.newBufferedWriter(bat.toPath()); + try { + IOUtil.copy(content, w); + } finally { + IOUtil.close(w); } // Change permission - makeExecutable( bat ); + makeExecutable(bat); Commandline cmd = new Commandline(); - cmd.setExecutable( bat.getAbsolutePath() ); - cmd.setWorkingDirectory( dir ); + cmd.setExecutable(bat.getAbsolutePath()); + cmd.setWorkingDirectory(dir); // Execute the script file - executeCommandLine( cmd ); + executeCommandLine(cmd); } /** @@ -668,26 +577,20 @@ private static void createAndCallScript( File dir, String content ) * @param cmd not null * @throws Exception if any */ - private static void executeCommandLine( Commandline cmd ) - throws Exception - { + private static void executeCommandLine(Commandline cmd) throws Exception { CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); - try - { - System.out.println( "Command line is: " + StringUtils.join( cmd.getShellCommandline(), " " ) ); + try { + System.out.println("Command line is: " + StringUtils.join(cmd.getShellCommandline(), " ")); - int exitCode = CommandLineUtils.executeCommandLine( cmd, new DefaultConsumer(), err ); + int exitCode = CommandLineUtils.executeCommandLine(cmd, new DefaultConsumer(), err); - if ( exitCode != 0 ) - { + if (exitCode != 0) { String msg = "Exit code: " + exitCode + " - " + err.getOutput(); - throw new Exception( msg.toString() ); + throw new Exception(msg.toString()); } - } - catch ( CommandLineException e ) - { - throw new Exception( "Unable to execute command: " + e.getMessage(), e ); + } catch (CommandLineException e) { + throw new Exception("Unable to execute command: " + e.getMessage(), e); } } } 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 423d30ed..92dd21db 100644 --- a/src/test/java/org/codehaus/plexus/util/cli/DefaultConsumerTest.java +++ b/src/test/java/org/codehaus/plexus/util/cli/DefaultConsumerTest.java @@ -25,19 +25,15 @@ * @version $Id: $Id * @since 3.4.0 */ -public class DefaultConsumerTest -{ +public class DefaultConsumerTest { /** *

      testConsumeLine.

      * * @throws java.lang.Exception if any. */ @Test - public void testConsumeLine() - throws Exception - { + public void testConsumeLine() throws Exception { DefaultConsumer cons = new DefaultConsumer(); - cons.consumeLine( "Test DefaultConsumer consumeLine" ); + 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 05d043f5..8376a2c0 100644 --- a/src/test/java/org/codehaus/plexus/util/cli/EnhancedStringTokenizerTest.java +++ b/src/test/java/org/codehaus/plexus/util/cli/EnhancedStringTokenizerTest.java @@ -16,11 +16,11 @@ * limitations under the License. */ +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; -import org.junit.Test; - /** *

      EnhancedStringTokenizerTest class.

      * @@ -28,91 +28,81 @@ * @version $Id: $Id * @since 3.4.0 */ -public class EnhancedStringTokenizerTest -{ +public class EnhancedStringTokenizerTest { /** *

      test1.

      */ @Test - public void test1() - { - EnhancedStringTokenizer est = new EnhancedStringTokenizer( "this is a test string" ); + public void test1() { + EnhancedStringTokenizer est = new EnhancedStringTokenizer("this is a test string"); StringBuilder sb = new StringBuilder(); - while ( est.hasMoreTokens() ) - { - sb.append( est.nextToken() ); - sb.append( " " ); + while (est.hasMoreTokens()) { + sb.append(est.nextToken()); + sb.append(" "); } - assertEquals( "this is a test string ", sb.toString() ); + assertEquals("this is a test string ", sb.toString()); } /** *

      test2.

      */ @Test - public void test2() - { - EnhancedStringTokenizer est = new EnhancedStringTokenizer( "1,,,3,,4", "," ); - assertEquals( "Token 1", "1", est.nextToken() ); - assertEquals( "Token 2", "", est.nextToken() ); - assertEquals( "Token 3", "", est.nextToken() ); - assertEquals( "Token 4", "3", est.nextToken() ); - assertEquals( "Token 5", "", est.nextToken() ); - assertEquals( "Token 6", "4", est.nextToken() ); + public void test2() { + EnhancedStringTokenizer est = new EnhancedStringTokenizer("1,,,3,,4", ","); + assertEquals("Token 1", "1", est.nextToken()); + assertEquals("Token 2", "", est.nextToken()); + assertEquals("Token 3", "", est.nextToken()); + assertEquals("Token 4", "3", est.nextToken()); + assertEquals("Token 5", "", est.nextToken()); + assertEquals("Token 6", "4", est.nextToken()); } /** *

      test3.

      */ @Test - public void test3() - { - EnhancedStringTokenizer est = new EnhancedStringTokenizer( "1,,,3,,4", ",", true ); - assertEquals( "Token 1", "1", est.nextToken() ); - assertEquals( "Token 2", ",", est.nextToken() ); - assertEquals( "Token 3", "", est.nextToken() ); - assertEquals( "Token 4", ",", est.nextToken() ); - assertEquals( "Token 5", "", est.nextToken() ); - assertEquals( "Token 6", ",", est.nextToken() ); - assertEquals( "Token 7", "3", est.nextToken() ); - assertEquals( "Token 8", ",", est.nextToken() ); - assertEquals( "Token 9", "", est.nextToken() ); - assertEquals( "Token 10", ",", est.nextToken() ); - assertEquals( "Token 11", "4", est.nextToken() ); + public void test3() { + EnhancedStringTokenizer est = new EnhancedStringTokenizer("1,,,3,,4", ",", true); + assertEquals("Token 1", "1", est.nextToken()); + assertEquals("Token 2", ",", est.nextToken()); + assertEquals("Token 3", "", est.nextToken()); + assertEquals("Token 4", ",", est.nextToken()); + assertEquals("Token 5", "", est.nextToken()); + assertEquals("Token 6", ",", est.nextToken()); + assertEquals("Token 7", "3", est.nextToken()); + assertEquals("Token 8", ",", est.nextToken()); + assertEquals("Token 9", "", est.nextToken()); + assertEquals("Token 10", ",", est.nextToken()); + assertEquals("Token 11", "4", est.nextToken()); } /** *

      testMultipleDelim.

      */ @Test - public void testMultipleDelim() - { - EnhancedStringTokenizer est = new EnhancedStringTokenizer( "1 2|3|4", " |", true ); - assertEquals( "Token 1", "1", est.nextToken() ); - assertEquals( "Token 2", " ", est.nextToken() ); - assertEquals( "Token 3", "2", est.nextToken() ); - assertEquals( "Token 4", "|", est.nextToken() ); - assertEquals( "Token 5", "3", est.nextToken() ); - assertEquals( "Token 6", "|", est.nextToken() ); - assertEquals( "Token 7", "4", est.nextToken() ); - assertEquals( "est.hasMoreTokens()", false, est.hasMoreTokens() ); + public void testMultipleDelim() { + EnhancedStringTokenizer est = new EnhancedStringTokenizer("1 2|3|4", " |", true); + assertEquals("Token 1", "1", est.nextToken()); + assertEquals("Token 2", " ", est.nextToken()); + assertEquals("Token 3", "2", est.nextToken()); + assertEquals("Token 4", "|", est.nextToken()); + assertEquals("Token 5", "3", est.nextToken()); + assertEquals("Token 6", "|", est.nextToken()); + assertEquals("Token 7", "4", est.nextToken()); + assertEquals("est.hasMoreTokens()", false, est.hasMoreTokens()); } /** *

      testEmptyString.

      */ @Test - public void testEmptyString() - { - EnhancedStringTokenizer est = new EnhancedStringTokenizer( "" ); - assertEquals( "est.hasMoreTokens()", false, est.hasMoreTokens() ); - try - { + public void testEmptyString() { + EnhancedStringTokenizer est = new EnhancedStringTokenizer(""); + assertEquals("est.hasMoreTokens()", false, est.hasMoreTokens()); + try { est.nextToken(); fail(); - } - catch ( Exception e ) - { + } catch (Exception e) { } } @@ -120,11 +110,10 @@ public void testEmptyString() *

      testSimpleString.

      */ @Test - public void testSimpleString() - { - EnhancedStringTokenizer est = new EnhancedStringTokenizer( "a " ); - assertEquals( "Token 1", "a", est.nextToken() ); - assertEquals( "Token 2", "", est.nextToken() ); - assertEquals( "est.hasMoreTokens()", false, est.hasMoreTokens() ); + public void testSimpleString() { + EnhancedStringTokenizer est = new EnhancedStringTokenizer("a "); + assertEquals("Token 1", "a", est.nextToken()); + assertEquals("Token 2", "", est.nextToken()); + assertEquals("est.hasMoreTokens()", false, est.hasMoreTokens()); } } 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 eec5def5..2a327933 100644 --- a/src/test/java/org/codehaus/plexus/util/cli/StreamPumperTest.java +++ b/src/test/java/org/codehaus/plexus/util/cli/StreamPumperTest.java @@ -52,10 +52,6 @@ * 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.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -66,6 +62,10 @@ import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + /** *

      StreamPumperTest class.

      * @@ -73,45 +73,42 @@ * @version $Id: $Id * @since 3.4.0 */ -public class StreamPumperTest -{ +public class StreamPumperTest { private String lineSeparator = System.lineSeparator(); /** *

      testPumping.

      */ @Test - public void testPumping() - { + public void testPumping() { String line1 = "line1"; String line2 = "line2"; String lines = line1 + "\n" + line2; - ByteArrayInputStream inputStream = new ByteArrayInputStream( lines.getBytes() ); + ByteArrayInputStream inputStream = new ByteArrayInputStream(lines.getBytes()); TestConsumer consumer = new TestConsumer(); - StreamPumper pumper = new StreamPumper( inputStream, consumer ); - new Thread( pumper ).run(); + StreamPumper pumper = new StreamPumper(inputStream, consumer); + new Thread(pumper).run(); // Check the consumer to see if it got both lines. - assertTrue( consumer.wasLineConsumed( line1, 1000 ) ); - assertTrue( consumer.wasLineConsumed( line2, 1000 ) ); + assertTrue(consumer.wasLineConsumed(line1, 1000)); + assertTrue(consumer.wasLineConsumed(line2, 1000)); } /** *

      testPumpingWithPrintWriter.

      */ @Test - public void testPumpingWithPrintWriter() - { + public void testPumpingWithPrintWriter() { String inputString = "This a test string"; - ByteArrayInputStream bais = new ByteArrayInputStream( inputString.getBytes() ); + ByteArrayInputStream bais = new ByteArrayInputStream(inputString.getBytes()); StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter( sw ); - StreamPumper pumper = new StreamPumper( bais, pw ); + PrintWriter pw = new PrintWriter(sw); + StreamPumper pumper = new StreamPumper(bais, pw); pumper.run(); pumper.flush(); - System.out.println( "aaa" + sw.toString() ); - assertEquals( "This a test string" + lineSeparator, sw.toString() ); + System.out.println("aaa" + sw.toString()); + assertEquals("This a test string" + lineSeparator, sw.toString()); pumper.close(); } @@ -119,20 +116,17 @@ public void testPumpingWithPrintWriter() *

      testPumperReadsInputStreamUntilEndEvenIfConsumerFails.

      */ @Test - public void testPumperReadsInputStreamUntilEndEvenIfConsumerFails() - { + public void testPumperReadsInputStreamUntilEndEvenIfConsumerFails() { // the number of bytes generated should surely exceed the read buffer used by the pumper - GeneratorInputStream gis = new GeneratorInputStream( 1024 * 1024 * 4 ); - StreamPumper pumper = new StreamPumper( gis, new FailingConsumer() ); + GeneratorInputStream gis = new GeneratorInputStream(1024 * 1024 * 4); + StreamPumper pumper = new StreamPumper(gis, new FailingConsumer()); pumper.run(); - assertEquals( "input stream was not fully consumed, producer deadlocks", gis.size, gis.read ); - assertTrue( gis.closed ); - assertNotNull( pumper.getException() ); + assertEquals("input stream was not fully consumed, producer deadlocks", gis.size, gis.read); + assertTrue(gis.closed); + assertNotNull(pumper.getException()); } - static class GeneratorInputStream - extends InputStream - { + static class GeneratorInputStream extends InputStream { final int size; @@ -140,50 +134,35 @@ static class GeneratorInputStream boolean closed = false; - public GeneratorInputStream( int size ) - { + public GeneratorInputStream(int size) { this.size = size; } - public int read() - throws IOException - { - if ( read < size ) - { + public int read() throws IOException { + if (read < size) { read++; return '\n'; - } - else - { + } else { return -1; } } - public void close() - throws IOException - { + public void close() throws IOException { closed = true; } - } - static class FailingConsumer - implements StreamConsumer - { + static class FailingConsumer implements StreamConsumer { - public void consumeLine( String line ) - { - throw new NullPointerException( "too bad, the consumer is badly implemented..." ); + public void consumeLine(String line) { + throw new NullPointerException("too bad, the consumer is badly implemented..."); } - } /** * Used by the test to track whether a line actually got consumed or not. */ - static class TestConsumer - implements StreamConsumer - { + static class TestConsumer implements StreamConsumer { private List lines = new ArrayList(); @@ -195,42 +174,34 @@ static class TestConsumer * @param timeout Number of milliseconds to wait for the line. * @return true if the line gets consumed, else false. */ - public boolean wasLineConsumed( String testLine, long timeout ) - { + public boolean wasLineConsumed(String testLine, long timeout) { long start = System.currentTimeMillis(); long trialTime = 0; - do - { - if ( lines.contains( testLine ) ) - { + do { + if (lines.contains(testLine)) { return true; } // Sleep a bit. - try - { - Thread.sleep( 10 ); - } - catch ( InterruptedException e ) - { + try { + Thread.sleep(10); + } catch (InterruptedException e) { // ignoring... } // How long have been waiting for the line? trialTime = System.currentTimeMillis() - start; - } - while ( trialTime < timeout ); + } while (trialTime < timeout); // If we got here, then the line wasn't consumed within the timeout return false; } - public void consumeLine( String line ) - { - lines.add( line ); + public void consumeLine(String line) { + lines.add(line); } } @@ -238,26 +209,24 @@ public void consumeLine( String line ) *

      testEnabled.

      */ @Test - public void testEnabled() - { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( "AB\nCE\nEF".getBytes() ); + public void testEnabled() { + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream("AB\nCE\nEF".getBytes()); TestConsumer streamConsumer = new TestConsumer(); - StreamPumper streamPumper = new StreamPumper( byteArrayInputStream, streamConsumer ); + StreamPumper streamPumper = new StreamPumper(byteArrayInputStream, streamConsumer); streamPumper.run(); - assertEquals( 3, streamConsumer.lines.size() ); + assertEquals(3, streamConsumer.lines.size()); } /** *

      testDisabled.

      */ @Test - public void testDisabled() - { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( "AB\nCE\nEF".getBytes() ); + public void testDisabled() { + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream("AB\nCE\nEF".getBytes()); TestConsumer streamConsumer = new TestConsumer(); - StreamPumper streamPumper = new StreamPumper( byteArrayInputStream, streamConsumer ); + StreamPumper streamPumper = new StreamPumper(byteArrayInputStream, streamConsumer); streamPumper.disable(); streamPumper.run(); - assertEquals( 0, streamConsumer.lines.size() ); + assertEquals(0, streamConsumer.lines.size()); } } 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 1480685f..f20791c7 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,6 +1,5 @@ package org.codehaus.plexus.util.cli.shell; - /* * Copyright The Codehaus Foundation. * @@ -17,9 +16,6 @@ * limitations under the License. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.util.Arrays; import java.util.List; @@ -27,6 +23,9 @@ import org.codehaus.plexus.util.cli.Commandline; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** *

      BourneShellTest class.

      * @@ -34,16 +33,14 @@ * @version $Id: $Id * @since 3.4.0 */ -public class BourneShellTest -{ +public class BourneShellTest { /** *

      newShell.

      * * @return a {@link org.codehaus.plexus.util.cli.shell.Shell} object. */ - protected Shell newShell() - { + protected Shell newShell() { return new BourneShell(); } @@ -51,169 +48,165 @@ protected Shell newShell() *

      testQuoteWorkingDirectoryAndExecutable.

      */ @Test - public void testQuoteWorkingDirectoryAndExecutable() - { + public void testQuoteWorkingDirectoryAndExecutable() { Shell sh = newShell(); - sh.setWorkingDirectory( "/usr/local/bin" ); - sh.setExecutable( "chmod" ); + sh.setWorkingDirectory("/usr/local/bin"); + sh.setExecutable("chmod"); - String executable = StringUtils.join( sh.getShellCommandLine( new String[] {} ).iterator(), " " ); + String executable = + StringUtils.join(sh.getShellCommandLine(new String[] {}).iterator(), " "); - assertEquals( "/bin/sh -c cd '/usr/local/bin' && 'chmod'", executable ); + assertEquals("/bin/sh -c cd '/usr/local/bin' && 'chmod'", executable); } /** *

      testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes.

      */ @Test - public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes() - { + public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes() { Shell sh = newShell(); - sh.setWorkingDirectory( "/usr/local/'something else'" ); - sh.setExecutable( "chmod" ); + sh.setWorkingDirectory("/usr/local/'something else'"); + sh.setExecutable("chmod"); - String executable = StringUtils.join( sh.getShellCommandLine( new String[] {} ).iterator(), " " ); + String executable = + StringUtils.join(sh.getShellCommandLine(new String[] {}).iterator(), " "); - assertEquals( "/bin/sh -c cd '/usr/local/'\"'\"'something else'\"'\"'' && 'chmod'", executable ); + assertEquals("/bin/sh -c cd '/usr/local/'\"'\"'something else'\"'\"'' && 'chmod'", executable); } /** *

      testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep.

      */ @Test - public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep() - { + public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep() { Shell sh = newShell(); - sh.setWorkingDirectory( "\\usr\\local\\'something else'" ); - sh.setExecutable( "chmod" ); + sh.setWorkingDirectory("\\usr\\local\\'something else'"); + sh.setExecutable("chmod"); - String executable = StringUtils.join( sh.getShellCommandLine( new String[] {} ).iterator(), " " ); + String executable = + StringUtils.join(sh.getShellCommandLine(new String[] {}).iterator(), " "); - assertEquals( "/bin/sh -c cd '\\usr\\local\\\'\"'\"'something else'\"'\"'' && 'chmod'", executable ); + assertEquals("/bin/sh -c cd '\\usr\\local\\\'\"'\"'something else'\"'\"'' && 'chmod'", executable); } /** *

      testPreserveSingleQuotesOnArgument.

      */ @Test - public void testPreserveSingleQuotesOnArgument() - { + public void testPreserveSingleQuotesOnArgument() { Shell sh = newShell(); - sh.setWorkingDirectory( "/usr/bin" ); - sh.setExecutable( "chmod" ); + sh.setWorkingDirectory("/usr/bin"); + sh.setExecutable("chmod"); - String[] args = { "\'some arg with spaces\'" }; + String[] args = {"\'some arg with spaces\'"}; - List shellCommandLine = sh.getShellCommandLine( args ); + List shellCommandLine = sh.getShellCommandLine(args); - String cli = StringUtils.join( shellCommandLine.iterator(), " " ); - System.out.println( cli ); - assertTrue( cli.endsWith( "''\"'\"'some arg with spaces'\"'\"''" ) ); + String cli = StringUtils.join(shellCommandLine.iterator(), " "); + System.out.println(cli); + assertTrue(cli.endsWith("''\"'\"'some arg with spaces'\"'\"''")); } /** *

      testAddSingleQuotesOnArgumentWithSpaces.

      */ @Test - public void testAddSingleQuotesOnArgumentWithSpaces() - { + public void testAddSingleQuotesOnArgumentWithSpaces() { Shell sh = newShell(); - sh.setWorkingDirectory( "/usr/bin" ); - sh.setExecutable( "chmod" ); + sh.setWorkingDirectory("/usr/bin"); + sh.setExecutable("chmod"); - String[] args = { "some arg with spaces" }; + String[] args = {"some arg with spaces"}; - List shellCommandLine = sh.getShellCommandLine( args ); + List shellCommandLine = sh.getShellCommandLine(args); - String cli = StringUtils.join( shellCommandLine.iterator(), " " ); - System.out.println( cli ); - assertTrue( cli.endsWith( "\'" + args[0] + "\'" ) ); + String cli = StringUtils.join(shellCommandLine.iterator(), " "); + System.out.println(cli); + assertTrue(cli.endsWith("\'" + args[0] + "\'")); } /** *

      testEscapeSingleQuotesOnArgument.

      */ @Test - public void testEscapeSingleQuotesOnArgument() - { + public void testEscapeSingleQuotesOnArgument() { Shell sh = newShell(); - sh.setWorkingDirectory( "/usr/bin" ); - sh.setExecutable( "chmod" ); + sh.setWorkingDirectory("/usr/bin"); + sh.setExecutable("chmod"); - String[] args = { "arg'withquote" }; + String[] args = {"arg'withquote"}; - List shellCommandLine = sh.getShellCommandLine( args ); + List shellCommandLine = sh.getShellCommandLine(args); - String cli = StringUtils.join( shellCommandLine.iterator(), " " ); - System.out.println( cli ); - assertEquals( "cd '/usr/bin' && 'chmod' 'arg'\"'\"'withquote'", - shellCommandLine.get( shellCommandLine.size() - 1 ) ); + String cli = StringUtils.join(shellCommandLine.iterator(), " "); + System.out.println(cli); + assertEquals( + "cd '/usr/bin' && 'chmod' 'arg'\"'\"'withquote'", shellCommandLine.get(shellCommandLine.size() - 1)); } /** *

      testArgumentsWithsemicolon.

      */ @Test - public void testArgumentsWithsemicolon() - { + public void testArgumentsWithsemicolon() { - System.out.println( "---- semi colon tests ----" ); + System.out.println("---- semi colon tests ----"); Shell sh = newShell(); - sh.setWorkingDirectory( "/usr/bin" ); - sh.setExecutable( "chmod" ); + sh.setWorkingDirectory("/usr/bin"); + sh.setExecutable("chmod"); - String[] args = { ";some&argwithunix$chars" }; + String[] args = {";some&argwithunix$chars"}; - List shellCommandLine = sh.getShellCommandLine( args ); + List shellCommandLine = sh.getShellCommandLine(args); - String cli = StringUtils.join( shellCommandLine.iterator(), " " ); - System.out.println( cli ); - assertTrue( cli.endsWith( "\'" + args[0] + "\'" ) ); + String cli = StringUtils.join(shellCommandLine.iterator(), " "); + System.out.println(cli); + assertTrue(cli.endsWith("\'" + args[0] + "\'")); - Commandline commandline = new Commandline( newShell() ); - commandline.setExecutable( "chmod" ); - commandline.getShell().setQuotedArgumentsEnabled( true ); - commandline.createArg().setValue( "--password" ); - commandline.createArg().setValue( ";password" ); + Commandline commandline = new Commandline(newShell()); + commandline.setExecutable("chmod"); + commandline.getShell().setQuotedArgumentsEnabled(true); + commandline.createArg().setValue("--password"); + commandline.createArg().setValue(";password"); String[] lines = commandline.getShellCommandline(); - System.out.println( Arrays.asList( lines ) ); + System.out.println(Arrays.asList(lines)); - assertEquals( "/bin/sh", lines[0] ); - assertEquals( "-c", lines[1] ); - assertEquals( "'chmod' '--password' ';password'", lines[2] ); + assertEquals("/bin/sh", lines[0]); + assertEquals("-c", lines[1]); + assertEquals("'chmod' '--password' ';password'", lines[2]); - commandline = new Commandline( newShell() ); - commandline.setExecutable( "chmod" ); - commandline.getShell().setQuotedArgumentsEnabled( true ); - commandline.createArg().setValue( "--password" ); - commandline.createArg().setValue( ";password" ); + commandline = new Commandline(newShell()); + commandline.setExecutable("chmod"); + commandline.getShell().setQuotedArgumentsEnabled(true); + commandline.createArg().setValue("--password"); + commandline.createArg().setValue(";password"); lines = commandline.getShellCommandline(); - System.out.println( Arrays.asList( lines ) ); + System.out.println(Arrays.asList(lines)); - assertEquals( "/bin/sh", lines[0] ); - assertEquals( "-c", lines[1] ); - assertEquals( "'chmod' '--password' ';password'", lines[2] ); + assertEquals("/bin/sh", lines[0]); + assertEquals("-c", lines[1]); + assertEquals("'chmod' '--password' ';password'", lines[2]); - commandline = new Commandline( new CmdShell() ); - commandline.getShell().setQuotedArgumentsEnabled( true ); - commandline.createArg().setValue( "--password" ); - commandline.createArg().setValue( ";password" ); + commandline = new Commandline(new CmdShell()); + commandline.getShell().setQuotedArgumentsEnabled(true); + commandline.createArg().setValue("--password"); + commandline.createArg().setValue(";password"); lines = commandline.getShellCommandline(); - System.out.println( Arrays.asList( lines ) ); + System.out.println(Arrays.asList(lines)); - assertEquals( "cmd.exe", lines[0] ); - assertEquals( "/X", lines[1] ); - assertEquals( "/C", lines[2] ); - assertEquals( "\"--password ;password\"", lines[3] ); + assertEquals("cmd.exe", lines[0]); + assertEquals("/X", lines[1]); + assertEquals("/C", lines[2]); + assertEquals("\"--password ;password\"", lines[3]); } /** @@ -222,42 +215,38 @@ public void testArgumentsWithsemicolon() * @throws java.lang.Exception if any. */ @Test - public void testBourneShellQuotingCharacters() - throws Exception - { + public void testBourneShellQuotingCharacters() throws Exception { // { ' ', '$', ';', '&', '|', '<', '>', '*', '?', '(', ')' }; // test with values http://steve-parker.org/sh/bourne.shtml Appendix B - Meta-characters and Reserved Words - Commandline commandline = new Commandline( newShell() ); - commandline.setExecutable( "chmod" ); - commandline.getShell().setQuotedArgumentsEnabled( true ); - commandline.createArg().setValue( " " ); - commandline.createArg().setValue( "|" ); - commandline.createArg().setValue( "&&" ); - commandline.createArg().setValue( "||" ); - commandline.createArg().setValue( ";" ); - commandline.createArg().setValue( ";;" ); - commandline.createArg().setValue( "&" ); - commandline.createArg().setValue( "()" ); - commandline.createArg().setValue( "<" ); - commandline.createArg().setValue( "<<" ); - commandline.createArg().setValue( ">" ); - commandline.createArg().setValue( ">>" ); - commandline.createArg().setValue( "*" ); - commandline.createArg().setValue( "?" ); - commandline.createArg().setValue( "[" ); - commandline.createArg().setValue( "]" ); - commandline.createArg().setValue( "{" ); - commandline.createArg().setValue( "}" ); - commandline.createArg().setValue( "`" ); + Commandline commandline = new Commandline(newShell()); + commandline.setExecutable("chmod"); + commandline.getShell().setQuotedArgumentsEnabled(true); + commandline.createArg().setValue(" "); + commandline.createArg().setValue("|"); + commandline.createArg().setValue("&&"); + commandline.createArg().setValue("||"); + commandline.createArg().setValue(";"); + commandline.createArg().setValue(";;"); + commandline.createArg().setValue("&"); + commandline.createArg().setValue("()"); + commandline.createArg().setValue("<"); + commandline.createArg().setValue("<<"); + commandline.createArg().setValue(">"); + commandline.createArg().setValue(">>"); + commandline.createArg().setValue("*"); + commandline.createArg().setValue("?"); + commandline.createArg().setValue("["); + commandline.createArg().setValue("]"); + commandline.createArg().setValue("{"); + commandline.createArg().setValue("}"); + commandline.createArg().setValue("`"); String[] lines = commandline.getShellCommandline(); - System.out.println( Arrays.asList( lines ) ); - - assertEquals( "/bin/sh", lines[0] ); - assertEquals( "-c", lines[1] ); - assertEquals( "'chmod' ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`'", - lines[2] ); + System.out.println(Arrays.asList(lines)); + assertEquals("/bin/sh", lines[0]); + assertEquals("-c", lines[1]); + assertEquals( + "'chmod' ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`'", lines[2]); } - } 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 5c67eb3f..499fa555 100644 --- a/src/test/java/org/codehaus/plexus/util/dag/CycleDetectedExceptionTest.java +++ b/src/test/java/org/codehaus/plexus/util/dag/CycleDetectedExceptionTest.java @@ -16,13 +16,13 @@ * limitations under the License. */ -import static org.junit.Assert.assertEquals; - import java.util.ArrayList; import java.util.List; import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** *

      CycleDetectedExceptionTest class.

      * @@ -30,24 +30,22 @@ * @version $Id: $Id * @since 3.4.0 */ -public class CycleDetectedExceptionTest -{ +public class CycleDetectedExceptionTest { /** *

      testException.

      */ @Test - public void testException() - { + public void testException() { final List cycle = new ArrayList(); - cycle.add( "a" ); + cycle.add("a"); - cycle.add( "b" ); + cycle.add("b"); - cycle.add( "a" ); + cycle.add("a"); - final CycleDetectedException e = new CycleDetectedException( "Cycle detected", cycle ); + final CycleDetectedException e = new CycleDetectedException("Cycle detected", cycle); - assertEquals( "Cycle detected a --> b --> a", e.getMessage() ); + assertEquals("Cycle detected a --> b --> a", e.getMessage()); } } 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 76a9c1ff..b0320182 100644 --- a/src/test/java/org/codehaus/plexus/util/dag/CycleDetectorTest.java +++ b/src/test/java/org/codehaus/plexus/util/dag/CycleDetectorTest.java @@ -16,16 +16,16 @@ * limitations under the License. */ +import java.util.List; + +import org.junit.Test; + 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; - /** *

      CycleDetectorTest class.

      * @@ -33,32 +33,27 @@ * @version $Id: $Id * @since 3.4.0 */ -public class CycleDetectorTest -{ +public class CycleDetectorTest { /** *

      testCycyleDetection.

      */ @Test - public void testCycyleDetection() - { + public void testCycyleDetection() { // No cycle // // a --> b --->c // - try - { + try { final DAG dag1 = new DAG(); - dag1.addEdge( "a", "b" ); + dag1.addEdge("a", "b"); - dag1.addEdge( "b", "c" ); + dag1.addEdge("b", "c"); - } - catch ( CycleDetectedException e ) - { + } catch (CycleDetectedException e) { - fail( "Cycle should not be detected" ); + fail("Cycle should not be detected"); } // @@ -67,54 +62,47 @@ public void testCycyleDetection() // | | // -----------| - try - { + try { final DAG dag2 = new DAG(); - dag2.addEdge( "a", "b" ); + dag2.addEdge("a", "b"); - dag2.addEdge( "b", "c" ); + dag2.addEdge("b", "c"); - dag2.addEdge( "c", "a" ); + dag2.addEdge("c", "a"); - fail( "Cycle should be detected" ); + fail("Cycle should be detected"); - } - catch ( CycleDetectedException e ) - { + } catch (CycleDetectedException e) { final List cycle = e.getCycle(); - assertNotNull( "Cycle should be not null", cycle ); + assertNotNull("Cycle should be not null", cycle); - assertTrue( "Cycle contains 'a'", cycle.contains( "a" ) ); + assertTrue("Cycle contains 'a'", cycle.contains("a")); - assertTrue( "Cycle contains 'b'", cycle.contains( "b" ) ); - - assertTrue( "Cycle contains 'c'", cycle.contains( "c" ) ); + assertTrue("Cycle contains 'b'", cycle.contains("b")); + assertTrue("Cycle contains 'c'", cycle.contains("c")); } // | --> c // a --> b // | | --> d // ---------> - try - { + try { final DAG dag3 = new DAG(); - dag3.addEdge( "a", "b" ); + dag3.addEdge("a", "b"); - dag3.addEdge( "b", "c" ); + dag3.addEdge("b", "c"); - dag3.addEdge( "b", "d" ); + dag3.addEdge("b", "d"); - dag3.addEdge( "a", "d" ); + dag3.addEdge("a", "d"); - } - catch ( CycleDetectedException e ) - { - fail( "Cycle should not be detected" ); + } catch (CycleDetectedException e) { + fail("Cycle should not be detected"); } // ------------ @@ -123,36 +111,33 @@ public void testCycyleDetection() // a --> b // | | --> d // ---------> - try - { + try { final DAG dag4 = new DAG(); - dag4.addEdge( "a", "b" ); + dag4.addEdge("a", "b"); - dag4.addEdge( "b", "c" ); + dag4.addEdge("b", "c"); - dag4.addEdge( "b", "d" ); + dag4.addEdge("b", "d"); - dag4.addEdge( "a", "d" ); + dag4.addEdge("a", "d"); - dag4.addEdge( "c", "a" ); + dag4.addEdge("c", "a"); - fail( "Cycle should be detected" ); + fail("Cycle should be detected"); - } - catch ( CycleDetectedException e ) - { + } catch (CycleDetectedException e) { final List cycle = e.getCycle(); - assertNotNull( "Cycle should be not null", cycle ); + assertNotNull("Cycle should be not null", cycle); - assertEquals( "Cycle contains 'a'", "a", (String) cycle.get( 0 ) ); + assertEquals("Cycle contains 'a'", "a", (String) cycle.get(0)); - assertEquals( "Cycle contains 'b'", "b", cycle.get( 1 ) ); + assertEquals("Cycle contains 'b'", "b", cycle.get(1)); - assertEquals( "Cycle contains 'c'", "c", cycle.get( 2 ) ); + assertEquals("Cycle contains 'c'", "c", cycle.get(2)); - assertEquals( "Cycle contains 'a'", "a", (String) cycle.get( 3 ) ); + assertEquals("Cycle contains 'a'", "a", (String) cycle.get(3)); } // f --> g --> h @@ -165,63 +150,58 @@ public void testCycyleDetection() final DAG dag5 = new DAG(); - try - { + try { - dag5.addEdge( "a", "b" ); + dag5.addEdge("a", "b"); - dag5.addEdge( "b", "c" ); + dag5.addEdge("b", "c"); - dag5.addEdge( "b", "f" ); + dag5.addEdge("b", "f"); - dag5.addEdge( "f", "g" ); + dag5.addEdge("f", "g"); - dag5.addEdge( "g", "h" ); + dag5.addEdge("g", "h"); - dag5.addEdge( "c", "d" ); + dag5.addEdge("c", "d"); - dag5.addEdge( "d", "e" ); + dag5.addEdge("d", "e"); - dag5.addEdge( "e", "b" ); + dag5.addEdge("e", "b"); - fail( "Cycle should be detected" ); + fail("Cycle should be detected"); - } - catch ( CycleDetectedException e ) - { + } catch (CycleDetectedException e) { final List cycle = e.getCycle(); - assertNotNull( "Cycle should be not null", cycle ); + assertNotNull("Cycle should be not null", cycle); - assertEquals( "Cycle contains 5 elements", 5, cycle.size() ); + assertEquals("Cycle contains 5 elements", 5, cycle.size()); - assertEquals( "Cycle contains 'b'", "b", (String) cycle.get( 0 ) ); + assertEquals("Cycle contains 'b'", "b", (String) cycle.get(0)); - assertEquals( "Cycle contains 'c'", "c", cycle.get( 1 ) ); + assertEquals("Cycle contains 'c'", "c", cycle.get(1)); - assertEquals( "Cycle contains 'd'", "d", cycle.get( 2 ) ); + assertEquals("Cycle contains 'd'", "d", cycle.get(2)); - assertEquals( "Cycle contains 'e'", "e", (String) cycle.get( 3 ) ); + assertEquals("Cycle contains 'e'", "e", (String) cycle.get(3)); - assertEquals( "Cycle contains 'b'", "b", (String) cycle.get( 4 ) ); + assertEquals("Cycle contains 'b'", "b", (String) cycle.get(4)); - assertTrue( "Edge exists", dag5.hasEdge( "a", "b" ) ); + assertTrue("Edge exists", dag5.hasEdge("a", "b")); - assertTrue( "Edge exists", dag5.hasEdge( "b", "c" ) ); + assertTrue("Edge exists", dag5.hasEdge("b", "c")); - assertTrue( "Edge exists", dag5.hasEdge( "b", "f" ) ); + assertTrue("Edge exists", dag5.hasEdge("b", "f")); - assertTrue( "Edge exists", dag5.hasEdge( "f", "g" ) ); + assertTrue("Edge exists", dag5.hasEdge("f", "g")); - assertTrue( "Edge exists", dag5.hasEdge( "g", "h" ) ); + assertTrue("Edge exists", dag5.hasEdge("g", "h")); - assertTrue( "Edge exists", dag5.hasEdge( "c", "d" ) ); + assertTrue("Edge exists", dag5.hasEdge("c", "d")); - assertTrue( "Edge exists", dag5.hasEdge( "d", "e" ) ); + assertTrue("Edge exists", dag5.hasEdge("d", "e")); - assertFalse( dag5.hasEdge( "e", "b" ) ); + assertFalse(dag5.hasEdge("e", "b")); } - } - } 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 bf0063eb..72d1b12e 100644 --- a/src/test/java/org/codehaus/plexus/util/dag/DAGTest.java +++ b/src/test/java/org/codehaus/plexus/util/dag/DAGTest.java @@ -16,16 +16,16 @@ * 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.ArrayList; import java.util.List; import java.util.Set; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + /** *

      DAGTest class.

      * @@ -33,114 +33,111 @@ * @version $Id: $Id * @since 3.4.0 */ -public class DAGTest -{ +public class DAGTest { /** *

      testDAG.

      * * @throws org.codehaus.plexus.util.dag.CycleDetectedException if any. */ @Test - public void testDAG() - throws CycleDetectedException - { + public void testDAG() throws CycleDetectedException { final DAG dag = new DAG(); - dag.addVertex( "a" ); + dag.addVertex("a"); - assertEquals( 1, dag.getVertices().size() ); + assertEquals(1, dag.getVertices().size()); - assertEquals( "a", dag.getVertex( "a" ).getLabel() ); + assertEquals("a", dag.getVertex("a").getLabel()); - dag.addVertex( "a" ); + dag.addVertex("a"); - assertEquals( 1, dag.getVertices().size() ); + assertEquals(1, dag.getVertices().size()); - assertEquals( "a", dag.getVertex( "a" ).getLabel() ); + assertEquals("a", dag.getVertex("a").getLabel()); - dag.addVertex( "b" ); + dag.addVertex("b"); - assertEquals( 2, dag.getVertices().size() ); + assertEquals(2, dag.getVertices().size()); - assertFalse( dag.hasEdge( "a", "b" ) ); + assertFalse(dag.hasEdge("a", "b")); - assertFalse( dag.hasEdge( "b", "a" ) ); + assertFalse(dag.hasEdge("b", "a")); - final Vertex a = dag.getVertex( "a" ); + final Vertex a = dag.getVertex("a"); - final Vertex b = dag.getVertex( "b" ); + final Vertex b = dag.getVertex("b"); - assertEquals( "a", a.getLabel() ); + assertEquals("a", a.getLabel()); - assertEquals( "b", b.getLabel() ); + assertEquals("b", b.getLabel()); - dag.addEdge( "a", "b" ); + dag.addEdge("a", "b"); - assertTrue( a.getChildren().contains( b ) ); + assertTrue(a.getChildren().contains(b)); - assertTrue( b.getParents().contains( a ) ); + assertTrue(b.getParents().contains(a)); - assertTrue( dag.hasEdge( "a", "b" ) ); + assertTrue(dag.hasEdge("a", "b")); - assertFalse( dag.hasEdge( "b", "a" ) ); + assertFalse(dag.hasEdge("b", "a")); - dag.addEdge( "c", "d" ); + dag.addEdge("c", "d"); - assertEquals( 4, dag.getVertices().size() ); + assertEquals(4, dag.getVertices().size()); - final Vertex c = dag.getVertex( "c" ); + final Vertex c = dag.getVertex("c"); - final Vertex d = dag.getVertex( "d" ); + final Vertex d = dag.getVertex("d"); - assertEquals( "a", a.getLabel() ); + assertEquals("a", a.getLabel()); - assertEquals( "b", b.getLabel() ); + assertEquals("b", b.getLabel()); - assertEquals( "c", c.getLabel() ); + assertEquals("c", c.getLabel()); - assertEquals( "d", d.getLabel() ); + assertEquals("d", d.getLabel()); - assertFalse( dag.hasEdge( "b", "a" ) ); + assertFalse(dag.hasEdge("b", "a")); - assertFalse( dag.hasEdge( "a", "c" ) ); + assertFalse(dag.hasEdge("a", "c")); - assertFalse( dag.hasEdge( "a", "d" ) ); + assertFalse(dag.hasEdge("a", "d")); - assertTrue( dag.hasEdge( "c", "d" ) ); + assertTrue(dag.hasEdge("c", "d")); - assertFalse( dag.hasEdge( "d", "c" ) ); + assertFalse(dag.hasEdge("d", "c")); final Set labels = dag.getLabels(); - assertEquals( 4, labels.size() ); + assertEquals(4, labels.size()); - assertTrue( labels.contains( "a" ) ); + assertTrue(labels.contains("a")); - assertTrue( labels.contains( "b" ) ); + assertTrue(labels.contains("b")); - assertTrue( labels.contains( "c" ) ); + assertTrue(labels.contains("c")); - assertTrue( labels.contains( "d" ) ); + assertTrue(labels.contains("d")); - dag.addEdge( "a", "d" ); + dag.addEdge("a", "d"); - assertTrue( a.getChildren().contains( d ) ); + assertTrue(a.getChildren().contains(d)); - assertTrue( d.getParents().contains( a ) ); + assertTrue(d.getParents().contains(a)); // "b" and "d" are children of "a" - assertEquals( 2, a.getChildren().size() ); + assertEquals(2, a.getChildren().size()); - assertTrue( a.getChildLabels().contains( "b" ) ); + assertTrue(a.getChildLabels().contains("b")); - assertTrue( a.getChildLabels().contains( "d" ) ); + assertTrue(a.getChildLabels().contains("d")); // "a" and "c" are parents of "d" - assertEquals( 2, d.getParents().size() ); + assertEquals(2, d.getParents().size()); - assertTrue( d.getParentLabels().contains( "a" ) ); + assertTrue(d.getParentLabels().contains("a")); - assertTrue( d.getParentLabels().contains( "c" ) ); + assertTrue(d.getParentLabels().contains("c")); } /** @@ -149,12 +146,10 @@ public void testDAG() * @throws org.codehaus.plexus.util.dag.CycleDetectedException if any. */ @Test - public void testGetPredecessors() - throws CycleDetectedException - { + public void testGetPredecessors() throws CycleDetectedException { final DAG dag = new DAG(); - dag.addEdge( "a", "b" ); + dag.addEdge("a", "b"); // // a --> b --> c --> e @@ -165,42 +160,42 @@ public void testGetPredecessors() // force order of nodes - dag.addVertex( "c" ); + dag.addVertex("c"); - dag.addVertex( "d" ); + dag.addVertex("d"); - dag.addEdge( "a", "b" ); + dag.addEdge("a", "b"); - dag.addEdge( "b", "c" ); + dag.addEdge("b", "c"); - dag.addEdge( "b", "d" ); + dag.addEdge("b", "d"); - dag.addEdge( "c", "d" ); + dag.addEdge("c", "d"); - dag.addEdge( "c", "e" ); + dag.addEdge("c", "e"); - dag.addEdge( "f", "d" ); + dag.addEdge("f", "d"); - dag.addEdge( "e", "f" ); + dag.addEdge("e", "f"); - dag.addEdge( "f", "g" ); + dag.addEdge("f", "g"); - final List actual = dag.getSuccessorLabels( "b" ); + final List actual = dag.getSuccessorLabels("b"); final List expected = new ArrayList(); - expected.add( "d" ); + expected.add("d"); - expected.add( "g" ); + expected.add("g"); - expected.add( "f" ); + expected.add("f"); - expected.add( "e" ); + expected.add("e"); - expected.add( "c" ); + expected.add("c"); - expected.add( "b" ); + expected.add("b"); - assertEquals( expected, actual ); + assertEquals(expected, actual); } } 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 25ea5b54..87de9142 100644 --- a/src/test/java/org/codehaus/plexus/util/dag/TopologicalSorterTest.java +++ b/src/test/java/org/codehaus/plexus/util/dag/TopologicalSorterTest.java @@ -16,13 +16,13 @@ * limitations under the License. */ -import static org.junit.Assert.assertEquals; - import java.util.ArrayList; import java.util.List; import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** *

      TopologicalSorterTest class.

      * @@ -30,37 +30,34 @@ * @version $Id: $Id * @since 3.4.0 */ -public class TopologicalSorterTest -{ +public class TopologicalSorterTest { /** *

      testDfs.

      * * @throws org.codehaus.plexus.util.dag.CycleDetectedException if any. */ @Test - public void testDfs() - throws CycleDetectedException - { + public void testDfs() throws CycleDetectedException { // a --> b --->c // // result a,b,c final DAG dag1 = new DAG(); - dag1.addEdge( "a", "b" ); + dag1.addEdge("a", "b"); - dag1.addEdge( "b", "c" ); + dag1.addEdge("b", "c"); final List expected1 = new ArrayList(); - expected1.add( "c" ); + expected1.add("c"); - expected1.add( "b" ); + expected1.add("b"); - expected1.add( "a" ); + expected1.add("a"); - final List actual1 = TopologicalSorter.sort( dag1 ); + final List actual1 = TopologicalSorter.sort(dag1); - assertEquals( "Order is different then expected", expected1, actual1 ); + assertEquals("Order is different then expected", expected1, actual1); // // a <-- b <---c @@ -68,27 +65,27 @@ public void testDfs() // result c, b, a final DAG dag2 = new DAG(); - dag2.addVertex( "a" ); + dag2.addVertex("a"); - dag2.addVertex( "b" ); + dag2.addVertex("b"); - dag2.addVertex( "c" ); + dag2.addVertex("c"); - dag2.addEdge( "b", "a" ); + dag2.addEdge("b", "a"); - dag2.addEdge( "c", "b" ); + dag2.addEdge("c", "b"); final List expected2 = new ArrayList(); - expected2.add( "a" ); + expected2.add("a"); - expected2.add( "b" ); + expected2.add("b"); - expected2.add( "c" ); + expected2.add("c"); - final List actual2 = TopologicalSorter.sort( dag2 ); + final List actual2 = TopologicalSorter.sort(dag2); - assertEquals( "Order is different then expected", expected2, actual2 ); + assertEquals("Order is different then expected", expected2, actual2); // // a --> b --> c --> e @@ -99,53 +96,53 @@ public void testDfs() final DAG dag3 = new DAG(); // force order of nodes in the graph - dag3.addVertex( "a" ); + dag3.addVertex("a"); - dag3.addVertex( "b" ); + dag3.addVertex("b"); - dag3.addVertex( "c" ); + dag3.addVertex("c"); - dag3.addVertex( "d" ); + dag3.addVertex("d"); - dag3.addVertex( "e" ); + dag3.addVertex("e"); - dag3.addVertex( "f" ); + dag3.addVertex("f"); - dag3.addEdge( "a", "b" ); + dag3.addEdge("a", "b"); - dag3.addEdge( "b", "c" ); + dag3.addEdge("b", "c"); - dag3.addEdge( "b", "d" ); + dag3.addEdge("b", "d"); - dag3.addEdge( "c", "d" ); + dag3.addEdge("c", "d"); - dag3.addEdge( "c", "e" ); + dag3.addEdge("c", "e"); - dag3.addEdge( "f", "d" ); + dag3.addEdge("f", "d"); - dag3.addEdge( "e", "f" ); + dag3.addEdge("e", "f"); - dag3.addEdge( "f", "g" ); + dag3.addEdge("f", "g"); final List expected3 = new ArrayList(); - expected3.add( "d" ); + expected3.add("d"); - expected3.add( "g" ); + expected3.add("g"); - expected3.add( "f" ); + expected3.add("f"); - expected3.add( "e" ); + expected3.add("e"); - expected3.add( "c" ); + expected3.add("c"); - expected3.add( "b" ); + expected3.add("b"); - expected3.add( "a" ); + expected3.add("a"); - final List actual3 = TopologicalSorter.sort( dag3 ); + final List actual3 = TopologicalSorter.sort(dag3); - assertEquals( "Order is different then expected", expected3, actual3 ); + assertEquals("Order is different then expected", expected3, actual3); // // a --> b --> c --> e @@ -156,48 +153,48 @@ public void testDfs() final DAG dag4 = new DAG(); // force order of nodes in the graph - dag4.addVertex( "f" ); + dag4.addVertex("f"); - dag4.addVertex( "e" ); + dag4.addVertex("e"); - dag4.addVertex( "d" ); + dag4.addVertex("d"); - dag4.addVertex( "c" ); + dag4.addVertex("c"); - dag4.addVertex( "a" ); + dag4.addVertex("a"); - dag4.addVertex( "b" ); + dag4.addVertex("b"); - dag4.addEdge( "a", "b" ); + dag4.addEdge("a", "b"); - dag4.addEdge( "b", "c" ); + dag4.addEdge("b", "c"); - dag4.addEdge( "b", "d" ); + dag4.addEdge("b", "d"); - dag4.addEdge( "c", "d" ); + dag4.addEdge("c", "d"); - dag4.addEdge( "c", "e" ); + dag4.addEdge("c", "e"); - dag4.addEdge( "f", "d" ); + dag4.addEdge("f", "d"); - dag4.addEdge( "e", "f" ); + dag4.addEdge("e", "f"); final List expected4 = new ArrayList(); - expected4.add( "d" ); + expected4.add("d"); - expected4.add( "f" ); + expected4.add("f"); - expected4.add( "e" ); + expected4.add("e"); - expected4.add( "c" ); + expected4.add("c"); - expected4.add( "b" ); + expected4.add("b"); - expected4.add( "a" ); + expected4.add("a"); - final List actual4 = TopologicalSorter.sort( dag4 ); + final List actual4 = TopologicalSorter.sort(dag4); - assertEquals( "Order is different then expected", expected4, actual4 ); + assertEquals("Order is different then expected", expected4, actual4); } } 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 db49acd2..933f972e 100644 --- a/src/test/java/org/codehaus/plexus/util/dag/VertexTest.java +++ b/src/test/java/org/codehaus/plexus/util/dag/VertexTest.java @@ -16,10 +16,10 @@ * limitations under the License. */ -import static org.junit.Assert.assertEquals; - import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** *

      VertexTest class.

      * @@ -27,36 +27,33 @@ * @version $Id: $Id * @since 3.4.0 */ -public class VertexTest -{ +public class VertexTest { /** *

      testVertex.

      */ @Test - public void testVertex() - { - - final Vertex vertex1 = new Vertex( "a" ); + public void testVertex() { - assertEquals( "a", vertex1.getLabel() ); + final Vertex vertex1 = new Vertex("a"); - assertEquals( 0, vertex1.getChildren().size() ); + assertEquals("a", vertex1.getLabel()); - assertEquals( 0, vertex1.getChildLabels().size() ); + assertEquals(0, vertex1.getChildren().size()); - final Vertex vertex2 = new Vertex( "b" ); + assertEquals(0, vertex1.getChildLabels().size()); - assertEquals( "b", vertex2.getLabel() ); + final Vertex vertex2 = new Vertex("b"); - vertex1.addEdgeTo( vertex2 ); + assertEquals("b", vertex2.getLabel()); - assertEquals( 1, vertex1.getChildren().size() ); + vertex1.addEdgeTo(vertex2); - assertEquals( 1, vertex1.getChildLabels().size() ); + assertEquals(1, vertex1.getChildren().size()); - assertEquals( vertex2, vertex1.getChildren().get( 0 ) ); + assertEquals(1, vertex1.getChildLabels().size()); - assertEquals( "b", vertex1.getChildLabels().get( 0 ) ); + assertEquals(vertex2, vertex1.getChildren().get(0)); + assertEquals("b", vertex1.getChildLabels().get(0)); } } 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 44533bfa..2e712149 100644 --- a/src/test/java/org/codehaus/plexus/util/introspection/ReflectionValueExtractorTest.java +++ b/src/test/java/org/codehaus/plexus/util/introspection/ReflectionValueExtractorTest.java @@ -1,6 +1,5 @@ package org.codehaus.plexus.util.introspection; - /* * Copyright The Codehaus Foundation. * @@ -17,11 +16,6 @@ * 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.List; @@ -30,6 +24,11 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + /** *

      ReflectionValueExtractorTest class.

      * @@ -37,8 +36,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class ReflectionValueExtractorTest -{ +public class ReflectionValueExtractorTest { private Project project; /** @@ -47,30 +45,28 @@ public class ReflectionValueExtractorTest * @throws java.lang.Exception if any. */ @Before - public void setUp() - throws Exception - { + public void setUp() throws Exception { Dependency dependency1 = new Dependency(); - dependency1.setArtifactId( "dep1" ); + dependency1.setArtifactId("dep1"); Dependency dependency2 = new Dependency(); - dependency2.setArtifactId( "dep2" ); + dependency2.setArtifactId("dep2"); project = new Project(); - project.setModelVersion( "4.0.0" ); - project.setGroupId( "org.apache.maven" ); - project.setArtifactId( "maven-core" ); - project.setName( "Maven" ); - project.setVersion( "2.0-SNAPSHOT" ); - project.setScm( new Scm() ); - project.getScm().setConnection( "scm-connection" ); - project.addDependency( dependency1 ); - project.addDependency( dependency2 ); - project.setBuild( new Build() ); + project.setModelVersion("4.0.0"); + project.setGroupId("org.apache.maven"); + project.setArtifactId("maven-core"); + project.setName("Maven"); + project.setVersion("2.0-SNAPSHOT"); + project.setScm(new Scm()); + project.getScm().setConnection("scm-connection"); + project.addDependency(dependency1); + project.addDependency(dependency2); + project.setBuild(new Build()); // Build up an artifactMap - project.addArtifact( new Artifact( "g0", "a0", "v0", "e0", "c0" ) ); - project.addArtifact( new Artifact( "g1", "a1", "v1", "e1", "c1" ) ); - project.addArtifact( new Artifact( "g2", "a2", "v2", "e2", "c2" ) ); + project.addArtifact(new Artifact("g0", "a0", "v0", "e0", "c0")); + project.addArtifact(new Artifact("g1", "a1", "v1", "e1", "c1")); + project.addArtifact(new Artifact("g2", "a2", "v2", "e2", "c2")); } /** @@ -79,86 +75,83 @@ public void setUp() * @throws java.lang.Exception if any. */ @Test - public void testValueExtraction() - throws Exception - { + public void testValueExtraction() throws Exception { // ---------------------------------------------------------------------- // Top level values // ---------------------------------------------------------------------- - assertEquals( "4.0.0", ReflectionValueExtractor.evaluate( "project.modelVersion", project ) ); + assertEquals("4.0.0", ReflectionValueExtractor.evaluate("project.modelVersion", project)); - assertEquals( "org.apache.maven", ReflectionValueExtractor.evaluate( "project.groupId", project ) ); + assertEquals("org.apache.maven", ReflectionValueExtractor.evaluate("project.groupId", project)); - assertEquals( "maven-core", ReflectionValueExtractor.evaluate( "project.artifactId", project ) ); + assertEquals("maven-core", ReflectionValueExtractor.evaluate("project.artifactId", project)); - assertEquals( "Maven", ReflectionValueExtractor.evaluate( "project.name", project ) ); + assertEquals("Maven", ReflectionValueExtractor.evaluate("project.name", project)); - assertEquals( "2.0-SNAPSHOT", ReflectionValueExtractor.evaluate( "project.version", project ) ); + assertEquals("2.0-SNAPSHOT", ReflectionValueExtractor.evaluate("project.version", project)); // ---------------------------------------------------------------------- // SCM // ---------------------------------------------------------------------- - assertEquals( "scm-connection", ReflectionValueExtractor.evaluate( "project.scm.connection", project ) ); + assertEquals("scm-connection", ReflectionValueExtractor.evaluate("project.scm.connection", project)); // ---------------------------------------------------------------------- // Dependencies // ---------------------------------------------------------------------- - List dependencies = (List) ReflectionValueExtractor.evaluate( "project.dependencies", project ); + List dependencies = (List) ReflectionValueExtractor.evaluate("project.dependencies", project); - assertNotNull( dependencies ); + assertNotNull(dependencies); - assertEquals( 2, dependencies.size() ); + assertEquals(2, dependencies.size()); // ---------------------------------------------------------------------- // Dependencies - using index notation // ---------------------------------------------------------------------- // List - Dependency dependency = (Dependency) ReflectionValueExtractor.evaluate( "project.dependencies[0]", project ); + Dependency dependency = (Dependency) ReflectionValueExtractor.evaluate("project.dependencies[0]", project); - assertNotNull( dependency ); + assertNotNull(dependency); - assertTrue( "dep1".equals( dependency.getArtifactId() ) ); + assertTrue("dep1".equals(dependency.getArtifactId())); - String artifactId = (String) ReflectionValueExtractor.evaluate( "project.dependencies[1].artifactId", project ); + String artifactId = (String) ReflectionValueExtractor.evaluate("project.dependencies[1].artifactId", project); - assertTrue( "dep2".equals( artifactId ) ); + assertTrue("dep2".equals(artifactId)); // Array - dependency = (Dependency) ReflectionValueExtractor.evaluate( "project.dependenciesAsArray[0]", project ); + dependency = (Dependency) ReflectionValueExtractor.evaluate("project.dependenciesAsArray[0]", project); - assertNotNull( dependency ); + assertNotNull(dependency); - assertTrue( "dep1".equals( dependency.getArtifactId() ) ); + assertTrue("dep1".equals(dependency.getArtifactId())); - artifactId = (String) ReflectionValueExtractor.evaluate( "project.dependenciesAsArray[1].artifactId", project ); + artifactId = (String) ReflectionValueExtractor.evaluate("project.dependenciesAsArray[1].artifactId", project); - assertTrue( "dep2".equals( artifactId ) ); + assertTrue("dep2".equals(artifactId)); // Map - dependency = (Dependency) ReflectionValueExtractor.evaluate( "project.dependenciesAsMap(dep1)", project ); + dependency = (Dependency) ReflectionValueExtractor.evaluate("project.dependenciesAsMap(dep1)", project); - assertNotNull( dependency ); + assertNotNull(dependency); - assertTrue( "dep1".equals( dependency.getArtifactId() ) ); + assertTrue("dep1".equals(dependency.getArtifactId())); - artifactId = - (String) ReflectionValueExtractor.evaluate( "project.dependenciesAsMap(dep2).artifactId", project ); + artifactId = (String) ReflectionValueExtractor.evaluate("project.dependenciesAsMap(dep2).artifactId", project); - assertTrue( "dep2".equals( artifactId ) ); + assertTrue("dep2".equals(artifactId)); // ---------------------------------------------------------------------- // Build // ---------------------------------------------------------------------- - Build build = (Build) ReflectionValueExtractor.evaluate( "project.build", project ); + Build build = (Build) ReflectionValueExtractor.evaluate("project.build", project); - assertNotNull( build ); + assertNotNull(build); } /** @@ -167,12 +160,10 @@ public void testValueExtraction() * @throws java.lang.Exception if any. */ @Test - public void testValueExtractorWithAInvalidExpression() - throws Exception - { - assertNull( ReflectionValueExtractor.evaluate( "project.foo", project ) ); - assertNull( ReflectionValueExtractor.evaluate( "project.dependencies[10]", project ) ); - assertNull( ReflectionValueExtractor.evaluate( "project.dependencies[0].foo", project ) ); + public void testValueExtractorWithAInvalidExpression() throws Exception { + assertNull(ReflectionValueExtractor.evaluate("project.foo", project)); + assertNull(ReflectionValueExtractor.evaluate("project.dependencies[10]", project)); + assertNull(ReflectionValueExtractor.evaluate("project.dependencies[0].foo", project)); } /** @@ -181,13 +172,11 @@ public void testValueExtractorWithAInvalidExpression() * @throws java.lang.Exception if any. */ @Test - public void testMappedDottedKey() - throws Exception - { + public void testMappedDottedKey() throws Exception { Map map = new HashMap(); - map.put( "a.b", "a.b-value" ); + map.put("a.b", "a.b-value"); - 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))); } /** @@ -196,15 +185,13 @@ public void testMappedDottedKey() * @throws java.lang.Exception if any. */ @Test - public void testIndexedMapped() - throws Exception - { + public void testIndexedMapped() throws Exception { Map map = new HashMap(); - map.put( "a", "a-value" ); + map.put("a", "a-value"); List list = new ArrayList(); - list.add( map ); + list.add(map); - assertEquals( "a-value", ReflectionValueExtractor.evaluate( "h.value[0](a)", new ValueHolder( list ) ) ); + assertEquals("a-value", ReflectionValueExtractor.evaluate("h.value[0](a)", new ValueHolder(list))); } /** @@ -213,14 +200,12 @@ public void testIndexedMapped() * @throws java.lang.Exception if any. */ @Test - public void testMappedIndexed() - throws Exception - { + public void testMappedIndexed() throws Exception { List list = new ArrayList(); - list.add( "a-value" ); + list.add("a-value"); Map map = new HashMap(); - map.put( "a", list ); - assertEquals( "a-value", ReflectionValueExtractor.evaluate( "h.value(a)[0]", new ValueHolder( map ) ) ); + map.put("a", list); + assertEquals("a-value", ReflectionValueExtractor.evaluate("h.value(a)[0]", new ValueHolder(map))); } /** @@ -229,12 +214,10 @@ public void testMappedIndexed() * @throws java.lang.Exception if any. */ @Test - public void testMappedMissingDot() - throws Exception - { + public void testMappedMissingDot() throws Exception { Map map = new HashMap(); - map.put( "a", new ValueHolder( "a-value" ) ); - assertNull( ReflectionValueExtractor.evaluate( "h.value(a)value", new ValueHolder( map ) ) ); + map.put("a", new ValueHolder("a-value")); + assertNull(ReflectionValueExtractor.evaluate("h.value(a)value", new ValueHolder(map))); } /** @@ -243,12 +226,10 @@ public void testMappedMissingDot() * @throws java.lang.Exception if any. */ @Test - public void testIndexedMissingDot() - throws Exception - { + public void testIndexedMissingDot() throws Exception { List list = new ArrayList(); - list.add( new ValueHolder( "a-value" ) ); - assertNull( ReflectionValueExtractor.evaluate( "h.value[0]value", new ValueHolder( list ) ) ); + list.add(new ValueHolder("a-value")); + assertNull(ReflectionValueExtractor.evaluate("h.value[0]value", new ValueHolder(list))); } /** @@ -257,10 +238,8 @@ public void testIndexedMissingDot() * @throws java.lang.Exception if any. */ @Test - public void testDotDot() - throws Exception - { - assertNull( ReflectionValueExtractor.evaluate( "h..value", new ValueHolder( "value" ) ) ); + public void testDotDot() throws Exception { + assertNull(ReflectionValueExtractor.evaluate("h..value", new ValueHolder("value"))); } /** @@ -269,19 +248,17 @@ public void testDotDot() * @throws java.lang.Exception if any. */ @Test - public void testBadIndexedSyntax() - throws Exception - { + public void testBadIndexedSyntax() throws Exception { List list = new ArrayList(); - list.add( "a-value" ); - Object value = new ValueHolder( list ); - - 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 ) ); + list.add("a-value"); + Object value = new ValueHolder(list); + + 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)); } /** @@ -290,17 +267,15 @@ public void testBadIndexedSyntax() * @throws java.lang.Exception if any. */ @Test - public void testBadMappedSyntax() - throws Exception - { + public void testBadMappedSyntax() throws Exception { Map map = new HashMap(); - map.put( "a", "a-value" ); - Object value = new ValueHolder( map ); + map.put("a", "a-value"); + Object value = new ValueHolder(map); - 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 ) ); + 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)); } /** @@ -309,15 +284,10 @@ public void testBadMappedSyntax() * @throws java.lang.Exception if any. */ @Test - public void testIllegalIndexedType() - throws Exception - { - try - { - ReflectionValueExtractor.evaluate( "h.value[1]", new ValueHolder( "string" ) ); - } - catch ( Exception e ) - { + public void testIllegalIndexedType() throws Exception { + try { + ReflectionValueExtractor.evaluate("h.value[1]", new ValueHolder("string")); + } catch (Exception e) { // TODO assert exception message } } @@ -328,15 +298,10 @@ public void testIllegalIndexedType() * @throws java.lang.Exception if any. */ @Test - public void testIllegalMappedType() - throws Exception - { - try - { - ReflectionValueExtractor.evaluate( "h.value(key)", new ValueHolder( "string" ) ); - } - catch ( Exception e ) - { + public void testIllegalMappedType() throws Exception { + try { + ReflectionValueExtractor.evaluate("h.value(key)", new ValueHolder("string")); + } catch (Exception e) { // TODO assert exception message } } @@ -347,10 +312,8 @@ public void testIllegalMappedType() * @throws java.lang.Exception if any. */ @Test - public void testTrimRootToken() - throws Exception - { - assertNull( ReflectionValueExtractor.evaluate( "project", project, true ) ); + public void testTrimRootToken() throws Exception { + assertNull(ReflectionValueExtractor.evaluate("project", project, true)); } /** @@ -359,19 +322,21 @@ public void testTrimRootToken() * @throws java.lang.Exception if any. */ @Test - public void testArtifactMap() - throws Exception - { - assertEquals( "g0", ( (Artifact) ReflectionValueExtractor.evaluate( "project.artifactMap(g0:a0:c0)", - project ) ).getGroupId() ); - assertEquals( "a1", ( (Artifact) ReflectionValueExtractor.evaluate( "project.artifactMap(g1:a1:c1)", - project ) ).getArtifactId() ); - assertEquals( "c2", ( (Artifact) ReflectionValueExtractor.evaluate( "project.artifactMap(g2:a2:c2)", - project ) ).getClassifier() ); + public void testArtifactMap() throws Exception { + assertEquals( + "g0", + ((Artifact) ReflectionValueExtractor.evaluate("project.artifactMap(g0:a0:c0)", project)).getGroupId()); + assertEquals( + "a1", + ((Artifact) ReflectionValueExtractor.evaluate("project.artifactMap(g1:a1:c1)", project)) + .getArtifactId()); + assertEquals( + "c2", + ((Artifact) ReflectionValueExtractor.evaluate("project.artifactMap(g2:a2:c2)", project)) + .getClassifier()); } - public static class Artifact - { + public static class Artifact { private String groupId; private String artifactId; @@ -382,8 +347,7 @@ public static class Artifact private String classifier; - public Artifact( String groupId, String artifactId, String version, String extension, String classifier ) - { + public Artifact(String groupId, String artifactId, String version, String extension, String classifier) { this.groupId = groupId; this.artifactId = artifactId; this.version = version; @@ -391,59 +355,48 @@ public Artifact( String groupId, String artifactId, String version, String exten this.classifier = classifier; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public void setGroupId( String groupId ) - { + public void setGroupId(String groupId) { this.groupId = groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public void setArtifactId( String artifactId ) - { + public void setArtifactId(String artifactId) { this.artifactId = artifactId; } - public String getVersion() - { + public String getVersion() { return version; } - public void setVersion( String version ) - { + public void setVersion(String version) { this.version = version; } - public String getExtension() - { + public String getExtension() { return extension; } - public void setExtension( String extension ) - { + public void setExtension(String extension) { this.extension = extension; } - public String getClassifier() - { + public String getClassifier() { return classifier; } - public void setClassifier( String classifier ) - { + public void setClassifier(String classifier) { this.classifier = classifier; } } - public static class Project - { + public static class Project { private String modelVersion; private String groupId; @@ -463,170 +416,135 @@ public static class Project private Map artifactMap = new HashMap(); private String description; - public void setModelVersion( String modelVersion ) - { + public void setModelVersion(String modelVersion) { this.modelVersion = modelVersion; } - public void setGroupId( String groupId ) - { + public void setGroupId(String groupId) { this.groupId = groupId; } - public void setScm( Scm scm ) - { + public void setScm(Scm scm) { this.scm = scm; } - public void addDependency( Dependency dependency ) - { - this.dependencies.add( dependency ); + public void addDependency(Dependency dependency) { + this.dependencies.add(dependency); } - public void setBuild( Build build ) - { + public void setBuild(Build build) { this.build = build; } - public void setArtifactId( String artifactId ) - { + public void setArtifactId(String artifactId) { this.artifactId = artifactId; } - public void setName( String name ) - { + public void setName(String name) { this.name = name; } - public void setVersion( String version ) - { + public void setVersion(String version) { this.version = version; } - public Scm getScm() - { + public Scm getScm() { return scm; } - public String getModelVersion() - { + public String getModelVersion() { return modelVersion; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public List getDependencies() - { + public List getDependencies() { return dependencies; } - public Build getBuild() - { + public Build getBuild() { return build; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public String getName() - { + public String getName() { return name; } - public String getVersion() - { + public String getVersion() { return version; } - public Dependency[] getDependenciesAsArray() - { - return (Dependency[]) getDependencies().toArray( new Dependency[0] ); + public Dependency[] getDependenciesAsArray() { + return (Dependency[]) getDependencies().toArray(new Dependency[0]); } - public Map getDependenciesAsMap() - { + public Map getDependenciesAsMap() { Map ret = new HashMap(); - for ( Object o : getDependencies() ) - { + for (Object o : getDependencies()) { Dependency dep = (Dependency) o; - ret.put( dep.getArtifactId(), dep ); + ret.put(dep.getArtifactId(), dep); } return ret; } // ${project.artifactMap(g:a:v)} - public void addArtifact( Artifact a ) - { - artifactMap.put( a.getGroupId() + ":" + a.getArtifactId() + ":" + a.getClassifier(), a ); + public void addArtifact(Artifact a) { + artifactMap.put(a.getGroupId() + ":" + a.getArtifactId() + ":" + a.getClassifier(), a); } - public Map getArtifactMap() - { + public Map getArtifactMap() { return artifactMap; } - public void setDescription( String description ) - { + public void setDescription(String description) { this.description = description; } - public String getDescription() - { + public String getDescription() { return description; } } - public static class Build - { - - } + public static class Build {} - public static class Dependency - { + public static class Dependency { private String artifactId; - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public void setArtifactId( String id ) - { + public void setArtifactId(String id) { artifactId = id; } } - public static class Scm - { + public static class Scm { private String connection; - public void setConnection( String connection ) - { + public void setConnection(String connection) { this.connection = connection; } - public String getConnection() - { + public String getConnection() { return connection; } } - public static class ValueHolder - { + public static class ValueHolder { private final Object value; - public ValueHolder( Object value ) - { + public ValueHolder(Object value) { this.value = value; } - public Object getValue() - { + public Object getValue() { return value; } } @@ -637,12 +555,10 @@ public Object getValue() * @throws java.lang.Exception if any. */ @Test - public void testRootPropertyRegression() - throws Exception - { + public void testRootPropertyRegression() throws Exception { Project project = new Project(); - project.setDescription( "c:\\\\org\\apache\\test" ); - Object evalued = ReflectionValueExtractor.evaluate( "description", project ); - assertNotNull( evalued ); + project.setDescription("c:\\\\org\\apache\\test"); + Object evalued = ReflectionValueExtractor.evaluate("description", project); + assertNotNull(evalued); } } diff --git a/src/test/java/org/codehaus/plexus/util/io/CachingOutputStreamTest.java b/src/test/java/org/codehaus/plexus/util/io/CachingOutputStreamTest.java index e7888ad4..1a53155a 100644 --- a/src/test/java/org/codehaus/plexus/util/io/CachingOutputStreamTest.java +++ b/src/test/java/org/codehaus/plexus/util/io/CachingOutputStreamTest.java @@ -33,110 +33,98 @@ import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; -public class CachingOutputStreamTest -{ +public class CachingOutputStreamTest { Path tempDir; Path checkLastModified; @Before - public void setup() throws IOException - { - Path dir = Paths.get( "target/io" ); - Files.createDirectories( dir ); - tempDir = Files.createTempDirectory( dir, "temp-" ); - checkLastModified = tempDir.resolve( ".check" ); + public void setup() throws IOException { + Path dir = Paths.get("target/io"); + Files.createDirectories(dir); + tempDir = Files.createTempDirectory(dir, "temp-"); + checkLastModified = tempDir.resolve(".check"); } - private void waitLastModified() throws IOException, InterruptedException - { - Files.newOutputStream( checkLastModified ).close(); - FileTime lm = Files.getLastModifiedTime( checkLastModified ); - while ( true ) - { - Files.newOutputStream( checkLastModified ).close(); - FileTime nlm = Files.getLastModifiedTime( checkLastModified ); - if ( !Objects.equals( nlm, lm ) ) - { + private void waitLastModified() throws IOException, InterruptedException { + Files.newOutputStream(checkLastModified).close(); + FileTime lm = Files.getLastModifiedTime(checkLastModified); + while (true) { + Files.newOutputStream(checkLastModified).close(); + FileTime nlm = Files.getLastModifiedTime(checkLastModified); + if (!Objects.equals(nlm, lm)) { break; } - Thread.sleep( 10 ); + Thread.sleep(10); } } @Test - public void testWriteNoExistingFile() throws IOException, InterruptedException - { - byte[] data = "Hello world!".getBytes( StandardCharsets.UTF_8 ); - Path path = tempDir.resolve( "file.txt" ); - assertFalse( Files.exists( path ) ); - - try ( CachingOutputStream cos = new CachingOutputStream( path, 4 ) ) - { - cos.write( data ); + public void testWriteNoExistingFile() throws IOException, InterruptedException { + byte[] data = "Hello world!".getBytes(StandardCharsets.UTF_8); + Path path = tempDir.resolve("file.txt"); + assertFalse(Files.exists(path)); + + try (CachingOutputStream cos = new CachingOutputStream(path, 4)) { + cos.write(data); } - assertTrue( Files.exists( path ) ); - byte[] read = Files.readAllBytes( path ); - assertArrayEquals( data, read ); - FileTime modified = Files.getLastModifiedTime( path ); + assertTrue(Files.exists(path)); + byte[] read = Files.readAllBytes(path); + assertArrayEquals(data, read); + FileTime modified = Files.getLastModifiedTime(path); waitLastModified(); - try ( CachingOutputStream cos = new CachingOutputStream( path, 4 ) ) - { - cos.write( data ); + try (CachingOutputStream cos = new CachingOutputStream(path, 4)) { + cos.write(data); } - assertTrue( Files.exists( path ) ); - read = Files.readAllBytes( path ); - assertArrayEquals( data, read ); - FileTime newModified = Files.getLastModifiedTime( path ); - assertEquals( modified, newModified ); + assertTrue(Files.exists(path)); + read = Files.readAllBytes(path); + assertArrayEquals(data, read); + FileTime newModified = Files.getLastModifiedTime(path); + assertEquals(modified, newModified); modified = newModified; waitLastModified(); // write longer data - data = "Good morning!".getBytes( StandardCharsets.UTF_8 ); - try ( CachingOutputStream cos = new CachingOutputStream( path, 4 ) ) - { - cos.write( data ); + data = "Good morning!".getBytes(StandardCharsets.UTF_8); + try (CachingOutputStream cos = new CachingOutputStream(path, 4)) { + cos.write(data); } - assertTrue( Files.exists( path ) ); - read = Files.readAllBytes( path ); - assertArrayEquals( data, read ); - newModified = Files.getLastModifiedTime( path ); - assertNotEquals( modified, newModified ); + assertTrue(Files.exists(path)); + read = Files.readAllBytes(path); + assertArrayEquals(data, read); + newModified = Files.getLastModifiedTime(path); + assertNotEquals(modified, newModified); modified = newModified; waitLastModified(); // different data same size - data = "Good mornong!".getBytes( StandardCharsets.UTF_8 ); - try ( CachingOutputStream cos = new CachingOutputStream( path, 4 ) ) - { - cos.write( data ); + data = "Good mornong!".getBytes(StandardCharsets.UTF_8); + try (CachingOutputStream cos = new CachingOutputStream(path, 4)) { + cos.write(data); } - assertTrue( Files.exists( path ) ); - read = Files.readAllBytes( path ); - assertArrayEquals( data, read ); - newModified = Files.getLastModifiedTime( path ); - assertNotEquals( modified, newModified ); + assertTrue(Files.exists(path)); + read = Files.readAllBytes(path); + assertArrayEquals(data, read); + newModified = Files.getLastModifiedTime(path); + assertNotEquals(modified, newModified); modified = newModified; waitLastModified(); // same data but shorter - data = "Good mornon".getBytes( StandardCharsets.UTF_8 ); - try ( CachingOutputStream cos = new CachingOutputStream( path, 4 ) ) - { - cos.write( data ); + data = "Good mornon".getBytes(StandardCharsets.UTF_8); + try (CachingOutputStream cos = new CachingOutputStream(path, 4)) { + cos.write(data); } - assertTrue( Files.exists( path ) ); - read = Files.readAllBytes( path ); - assertArrayEquals( data, read ); - newModified = Files.getLastModifiedTime( path ); - assertNotEquals( modified, newModified ); + assertTrue(Files.exists(path)); + read = Files.readAllBytes(path); + assertArrayEquals(data, read); + newModified = Files.getLastModifiedTime(path); + assertNotEquals(modified, newModified); modified = newModified; } - } diff --git a/src/test/java/org/codehaus/plexus/util/io/CachingWriterTest.java b/src/test/java/org/codehaus/plexus/util/io/CachingWriterTest.java index 69156a8e..6c3dc9f6 100644 --- a/src/test/java/org/codehaus/plexus/util/io/CachingWriterTest.java +++ b/src/test/java/org/codehaus/plexus/util/io/CachingWriterTest.java @@ -33,43 +33,37 @@ import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; -public class CachingWriterTest -{ +public class CachingWriterTest { Path tempDir; Path checkLastModified; @Before - public void setup() throws IOException - { - Path dir = Paths.get( "target/io" ); - Files.createDirectories( dir ); - tempDir = Files.createTempDirectory( dir, "temp-" ); - checkLastModified = tempDir.resolve( ".check" ); + public void setup() throws IOException { + Path dir = Paths.get("target/io"); + Files.createDirectories(dir); + tempDir = Files.createTempDirectory(dir, "temp-"); + checkLastModified = tempDir.resolve(".check"); } - private void waitLastModified() throws IOException, InterruptedException - { - Files.newOutputStream( checkLastModified ).close(); - FileTime lm = Files.getLastModifiedTime( checkLastModified ); - while ( true ) - { - Files.newOutputStream( checkLastModified ).close(); - FileTime nlm = Files.getLastModifiedTime( checkLastModified ); - if ( !Objects.equals( nlm, lm ) ) - { + private void waitLastModified() throws IOException, InterruptedException { + Files.newOutputStream(checkLastModified).close(); + FileTime lm = Files.getLastModifiedTime(checkLastModified); + while (true) { + Files.newOutputStream(checkLastModified).close(); + FileTime nlm = Files.getLastModifiedTime(checkLastModified); + if (!Objects.equals(nlm, lm)) { break; } - Thread.sleep( 10 ); + Thread.sleep(10); } } @Test - public void testNoOverwriteWithFlush() throws IOException, InterruptedException - { + public void testNoOverwriteWithFlush() throws IOException, InterruptedException { String data = "Hello world!"; Path path = tempDir.resolve("file-bigger.txt"); - assertFalse( Files.exists(path)); + assertFalse(Files.exists(path)); try (Writer w = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { for (int i = 0; i < 10; i++) { @@ -91,77 +85,71 @@ public void testNoOverwriteWithFlush() throws IOException, InterruptedException } @Test - public void testWriteNoExistingFile() throws IOException, InterruptedException - { + public void testWriteNoExistingFile() throws IOException, InterruptedException { String data = "Hello world!"; - Path path = tempDir.resolve( "file.txt" ); - assertFalse( Files.exists( path ) ); + Path path = tempDir.resolve("file.txt"); + assertFalse(Files.exists(path)); - try ( CachingWriter cos = new CachingWriter( path, StandardCharsets.UTF_8, 4 ) ) - { - cos.write( data ); + try (CachingWriter cos = new CachingWriter(path, StandardCharsets.UTF_8, 4)) { + cos.write(data); } - assertTrue( Files.exists( path ) ); - String read = new String( Files.readAllBytes( path ), StandardCharsets.UTF_8 ); - assertEquals( data, read ); - FileTime modified = Files.getLastModifiedTime( path ); + assertTrue(Files.exists(path)); + String read = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + assertEquals(data, read); + FileTime modified = Files.getLastModifiedTime(path); waitLastModified(); - try ( CachingWriter cos = new CachingWriter( path, StandardCharsets.UTF_8, 4 ) ) - { - cos.write( data ); + try (CachingWriter cos = new CachingWriter(path, StandardCharsets.UTF_8, 4)) { + cos.write(data); } - assertTrue( Files.exists( path ) ); - read = new String( Files.readAllBytes( path ), StandardCharsets.UTF_8 ); - assertEquals( data, read ); - FileTime newModified = Files.getLastModifiedTime( path ); - assertEquals( modified, newModified ); + assertTrue(Files.exists(path)); + read = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + assertEquals(data, read); + FileTime newModified = Files.getLastModifiedTime(path); + assertEquals(modified, newModified); modified = newModified; waitLastModified(); // write longer data data = "Good morning!"; - try ( CachingWriter cos = new CachingWriter( path, StandardCharsets.UTF_8, 4 ) ) - { - cos.write( data ); + try (CachingWriter cos = new CachingWriter(path, StandardCharsets.UTF_8, 4)) { + cos.write(data); } - assertTrue( Files.exists( path ) ); - read = new String( Files.readAllBytes( path ), StandardCharsets.UTF_8 ); - assertEquals( data, read ); - newModified = Files.getLastModifiedTime( path ); - assertNotEquals( modified, newModified ); + assertTrue(Files.exists(path)); + read = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + assertEquals(data, read); + newModified = Files.getLastModifiedTime(path); + assertNotEquals(modified, newModified); modified = newModified; waitLastModified(); // different data same size data = "Good mornong!"; - try ( CachingWriter cos = new CachingWriter( path, StandardCharsets.UTF_8, 4 ) ) - { - cos.write( data ); + try (CachingWriter cos = new CachingWriter(path, StandardCharsets.UTF_8, 4)) { + cos.write(data); } - assertTrue( Files.exists( path ) ); - read = new String( Files.readAllBytes( path ), StandardCharsets.UTF_8 ); - assertEquals( data, read ); - newModified = Files.getLastModifiedTime( path ); - assertNotEquals( modified, newModified ); + assertTrue(Files.exists(path)); + read = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + assertEquals(data, read); + newModified = Files.getLastModifiedTime(path); + assertNotEquals(modified, newModified); modified = newModified; waitLastModified(); // same data but shorter data = "Good mornon"; - try ( CachingWriter cos = new CachingWriter( path, StandardCharsets.UTF_8, 4 ) ) - { - cos.write( data ); + try (CachingWriter cos = new CachingWriter(path, StandardCharsets.UTF_8, 4)) { + cos.write(data); } - assertTrue( Files.exists( path ) ); - read = new String( Files.readAllBytes( path ), StandardCharsets.UTF_8 ); - assertEquals( data, read ); - newModified = Files.getLastModifiedTime( path ); - assertNotEquals( modified, newModified ); + assertTrue(Files.exists(path)); + read = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + assertEquals(data, read); + newModified = Files.getLastModifiedTime(path); + assertNotEquals(modified, newModified); modified = newModified; } } 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 d3c0db8c..d08d1415 100644 --- a/src/test/java/org/codehaus/plexus/util/reflection/ReflectorTest.java +++ b/src/test/java/org/codehaus/plexus/util/reflection/ReflectorTest.java @@ -16,11 +16,11 @@ * limitations under the License. */ -import static org.junit.Assert.assertEquals; - import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** *

      ReflectorTest class.

      * @@ -28,8 +28,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class ReflectorTest -{ +public class ReflectorTest { private Project project; private Reflector reflector; @@ -40,12 +39,10 @@ public class ReflectorTest * @throws java.lang.Exception if any. */ @Before - public void setUp() - throws Exception - { + public void setUp() throws Exception { project = new Project(); - project.setModelVersion( "1.0.0" ); - project.setVersion( "42" ); + project.setModelVersion("1.0.0"); + project.setVersion("42"); reflector = new Reflector(); } @@ -56,10 +53,8 @@ public void setUp() * @throws java.lang.Exception if any. */ @Test - public void testObjectPropertyFromName() - throws Exception - { - assertEquals( "1.0.0", reflector.getObjectProperty( project, "modelVersion" ) ); + public void testObjectPropertyFromName() throws Exception { + assertEquals("1.0.0", reflector.getObjectProperty(project, "modelVersion")); } /** @@ -68,10 +63,8 @@ public void testObjectPropertyFromName() * @throws java.lang.Exception if any. */ @Test - public void testObjectPropertyFromBean() - throws Exception - { - assertEquals( "Foo", reflector.getObjectProperty( project, "name" ) ); + public void testObjectPropertyFromBean() throws Exception { + assertEquals("Foo", reflector.getObjectProperty(project, "name")); } /** @@ -80,37 +73,30 @@ public void testObjectPropertyFromBean() * @throws java.lang.Exception if any. */ @Test - public void testObjectPropertyFromField() - throws Exception - { - assertEquals( "42", reflector.getObjectProperty( project, "version" ) ); + public void testObjectPropertyFromField() throws Exception { + assertEquals("42", reflector.getObjectProperty(project, "version")); } - public static class Project - { + public static class Project { private String model; private String name; private String version; - public void setModelVersion( String modelVersion ) - { + public void setModelVersion(String modelVersion) { this.model = modelVersion; } - public void setVersion( String version ) - { + public void setVersion(String version) { this.version = version; } - public String modelVersion() - { + public String modelVersion() { return model; } - public String getName() - { + public String getName() { return "Foo"; } } 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 76125f95..b03e8313 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/PrettyPrintXMLWriterTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/PrettyPrintXMLWriterTest.java @@ -16,9 +16,7 @@ * limitations under the License. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import javax.swing.text.html.HTML.Tag; import java.io.File; import java.io.IOException; @@ -27,13 +25,15 @@ import java.nio.file.Files; import java.util.NoSuchElementException; -import javax.swing.text.html.HTML.Tag; - import org.codehaus.plexus.util.StringUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** * Test of {@link org.codehaus.plexus.util.xml.PrettyPrintXMLWriter} * @@ -42,8 +42,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class PrettyPrintXMLWriterTest -{ +public class PrettyPrintXMLWriterTest { StringWriter w; PrettyPrintXMLWriter writer; @@ -52,8 +51,7 @@ public class PrettyPrintXMLWriterTest *

      setUp.

      */ @Before - public void setUp() - { + public void setUp() { initWriter(); } @@ -61,117 +59,107 @@ public void setUp() *

      tearDown.

      */ @After - public void tearDown() - { + public void tearDown() { writer = null; w = null; } - private void initWriter() - { + private void initWriter() { w = new StringWriter(); - writer = new PrettyPrintXMLWriter( w ); + writer = new PrettyPrintXMLWriter(w); } /** *

      testDefaultPrettyPrintXMLWriter.

      */ @Test - public void testDefaultPrettyPrintXMLWriter() - { - writer.startElement( Tag.HTML.toString() ); + public void testDefaultPrettyPrintXMLWriter() { + writer.startElement(Tag.HTML.toString()); - writeXhtmlHead( writer ); + writeXhtmlHead(writer); - writeXhtmlBody( writer ); + writeXhtmlBody(writer); writer.endElement(); // Tag.HTML - assertEquals( expectedResult( PrettyPrintXMLWriter.LS ), w.toString() ); + assertEquals(expectedResult(PrettyPrintXMLWriter.LS), w.toString()); } /** *

      testPrettyPrintXMLWriterWithGivenLineSeparator.

      */ @Test - public void testPrettyPrintXMLWriterWithGivenLineSeparator() - { - writer.setLineSeparator( "\n" ); + public void testPrettyPrintXMLWriterWithGivenLineSeparator() { + writer.setLineSeparator("\n"); - writer.startElement( Tag.HTML.toString() ); + writer.startElement(Tag.HTML.toString()); - writeXhtmlHead( writer ); + writeXhtmlHead(writer); - writeXhtmlBody( writer ); + writeXhtmlBody(writer); writer.endElement(); // Tag.HTML - assertEquals( expectedResult( "\n" ), w.toString() ); + assertEquals(expectedResult("\n"), w.toString()); } /** *

      testPrettyPrintXMLWriterWithGivenLineIndenter.

      */ @Test - public void testPrettyPrintXMLWriterWithGivenLineIndenter() - { - writer.setLineIndenter( " " ); + public void testPrettyPrintXMLWriterWithGivenLineIndenter() { + writer.setLineIndenter(" "); - writer.startElement( Tag.HTML.toString() ); + writer.startElement(Tag.HTML.toString()); - writeXhtmlHead( writer ); + writeXhtmlHead(writer); - writeXhtmlBody( writer ); + writeXhtmlBody(writer); writer.endElement(); // Tag.HTML - assertEquals( expectedResult( " ", PrettyPrintXMLWriter.LS ), w.toString() ); + assertEquals(expectedResult(" ", PrettyPrintXMLWriter.LS), w.toString()); } /** *

      testEscapeXmlAttribute.

      */ @Test - public void testEscapeXmlAttribute() - { + public void testEscapeXmlAttribute() { // Windows - writer.startElement( Tag.DIV.toString() ); - writer.addAttribute( "class", "sect\r\nion" ); + writer.startElement(Tag.DIV.toString()); + writer.addAttribute("class", "sect\r\nion"); writer.endElement(); // Tag.DIV - assertEquals( "
      ", w.toString() ); + assertEquals("
      ", w.toString()); // Mac initWriter(); - writer.startElement( Tag.DIV.toString() ); - writer.addAttribute( "class", "sect\rion" ); + writer.startElement(Tag.DIV.toString()); + writer.addAttribute("class", "sect\rion"); writer.endElement(); // Tag.DIV - assertEquals( "
      ", w.toString() ); + assertEquals("
      ", w.toString()); // Unix initWriter(); - writer.startElement( Tag.DIV.toString() ); - writer.addAttribute( "class", "sect\nion" ); + writer.startElement(Tag.DIV.toString()); + writer.addAttribute("class", "sect\nion"); writer.endElement(); // Tag.DIV - assertEquals( "
      ", w.toString() ); + assertEquals("
      ", w.toString()); } /** *

      testendElementAlreadyClosed.

      */ @Test - public void testendElementAlreadyClosed() - { - try - { - writer.startElement( Tag.DIV.toString() ); - writer.addAttribute( "class", "someattribute" ); + public void testendElementAlreadyClosed() { + try { + writer.startElement(Tag.DIV.toString()); + writer.addAttribute("class", "someattribute"); writer.endElement(); // Tag.DIV closed writer.endElement(); // Tag.DIV already closed, and there is no other outer tag! - fail( "Should throw a NoSuchElementException" ); - } - catch ( NoSuchElementException e ) - { - assert ( true ); + fail("Should throw a NoSuchElementException"); + } catch (NoSuchElementException e) { + assert (true); } } @@ -184,105 +172,96 @@ public void testendElementAlreadyClosed() * @throws java.io.IOException if an I/O error occurs */ @Test - public void testIssue51DetectJava7ConcatenationBug() - throws IOException - { - File dir = new File( "target/test-xml" ); - if ( !dir.exists() ) - { - assertTrue( "cannot create directory test-xml", dir.mkdir() ); + public void testIssue51DetectJava7ConcatenationBug() throws IOException { + File dir = new File("target/test-xml"); + if (!dir.exists()) { + assertTrue("cannot create directory test-xml", dir.mkdir()); } - File xmlFile = new File( dir, "test-issue-51.xml" ); - OutputStreamWriter osw = new OutputStreamWriter( Files.newOutputStream( xmlFile.toPath() ), "UTF-8" ); - writer = new PrettyPrintXMLWriter( osw ); + File xmlFile = new File(dir, "test-issue-51.xml"); + OutputStreamWriter osw = new OutputStreamWriter(Files.newOutputStream(xmlFile.toPath()), "UTF-8"); + writer = new PrettyPrintXMLWriter(osw); int iterations = 20000; - try - { - for ( int i = 0; i < iterations; ++i ) - { - writer.startElement( Tag.DIV.toString() + i ); - writer.addAttribute( "class", "someattribute" ); + try { + for (int i = 0; i < iterations; ++i) { + writer.startElement(Tag.DIV.toString() + i); + writer.addAttribute("class", "someattribute"); } - for ( int i = 0; i < iterations; ++i ) - { + for (int i = 0; i < iterations; ++i) { writer.endElement(); // closes Tag.DIV + i } - } - catch ( NoSuchElementException e ) - { - fail( "Should not throw a NoSuchElementException" ); - } - finally - { - if ( osw != null ) - { + } catch (NoSuchElementException e) { + fail("Should not throw a NoSuchElementException"); + } finally { + if (osw != null) { osw.close(); } } } - private void writeXhtmlHead( XMLWriter writer ) - { - writer.startElement( Tag.HEAD.toString() ); - writer.startElement( Tag.TITLE.toString() ); - writer.writeText( "title" ); + private void writeXhtmlHead(XMLWriter writer) { + writer.startElement(Tag.HEAD.toString()); + writer.startElement(Tag.TITLE.toString()); + writer.writeText("title"); writer.endElement(); // Tag.TITLE - writer.startElement( Tag.META.toString() ); - writer.addAttribute( "name", "author" ); - writer.addAttribute( "content", "Author" ); + writer.startElement(Tag.META.toString()); + writer.addAttribute("name", "author"); + writer.addAttribute("content", "Author"); writer.endElement(); // Tag.META - writer.startElement( Tag.META.toString() ); - writer.addAttribute( "name", "date" ); - writer.addAttribute( "content", "Date" ); + writer.startElement(Tag.META.toString()); + writer.addAttribute("name", "date"); + writer.addAttribute("content", "Date"); writer.endElement(); // Tag.META writer.endElement(); // Tag.HEAD } - private void writeXhtmlBody( XMLWriter writer ) - { - writer.startElement( Tag.BODY.toString() ); - writer.startElement( Tag.P.toString() ); - writer.writeText( "Paragraph 1, line 1. Paragraph 1, line 2." ); + private void writeXhtmlBody(XMLWriter writer) { + writer.startElement(Tag.BODY.toString()); + writer.startElement(Tag.P.toString()); + writer.writeText("Paragraph 1, line 1. Paragraph 1, line 2."); writer.endElement(); // Tag.P - writer.startElement( Tag.DIV.toString() ); - writer.addAttribute( "class", "section" ); - writer.startElement( Tag.H2.toString() ); - writer.writeText( "Section title" ); + writer.startElement(Tag.DIV.toString()); + writer.addAttribute("class", "section"); + writer.startElement(Tag.H2.toString()); + writer.writeText("Section title"); writer.endElement(); // Tag.H2 writer.endElement(); // Tag.DIV writer.endElement(); // Tag.BODY } - private String expectedResult( String lineSeparator ) - { - return expectedResult( " ", lineSeparator ); + private String expectedResult(String lineSeparator) { + return expectedResult(" ", lineSeparator); } - private String expectedResult( String lineIndenter, String lineSeparator ) - { + private String expectedResult(String lineIndenter, String lineSeparator) { StringBuilder expected = new StringBuilder(); - expected.append( "" ).append( lineSeparator ); - expected.append( StringUtils.repeat( lineIndenter, 1 ) ).append( "" ).append( lineSeparator ); - expected.append( StringUtils.repeat( lineIndenter, - 2 ) ).append( "title" ).append( lineSeparator ); - expected.append( StringUtils.repeat( lineIndenter, - 2 ) ).append( "" ).append( lineSeparator ); - expected.append( StringUtils.repeat( lineIndenter, - 2 ) ).append( "" ).append( lineSeparator ); - expected.append( StringUtils.repeat( lineIndenter, 1 ) ).append( "" ).append( lineSeparator ); - expected.append( StringUtils.repeat( lineIndenter, 1 ) ).append( "" ).append( lineSeparator ); - expected.append( StringUtils.repeat( lineIndenter, - 2 ) ).append( "

      Paragraph 1, line 1. Paragraph 1, line 2.

      " ).append( lineSeparator ); - expected.append( StringUtils.repeat( lineIndenter, - 2 ) ).append( "
      " ).append( lineSeparator ); - expected.append( StringUtils.repeat( lineIndenter, - 3 ) ).append( "

      Section title

      " ).append( lineSeparator ); - expected.append( StringUtils.repeat( lineIndenter, 2 ) ).append( "
      " ).append( lineSeparator ); - expected.append( StringUtils.repeat( lineIndenter, 1 ) ).append( "" ).append( lineSeparator ); - expected.append( "" ); + expected.append("").append(lineSeparator); + expected.append(StringUtils.repeat(lineIndenter, 1)).append("").append(lineSeparator); + expected.append(StringUtils.repeat(lineIndenter, 2)) + .append("title") + .append(lineSeparator); + expected.append(StringUtils.repeat(lineIndenter, 2)) + .append("") + .append(lineSeparator); + expected.append(StringUtils.repeat(lineIndenter, 2)) + .append("") + .append(lineSeparator); + expected.append(StringUtils.repeat(lineIndenter, 1)).append("").append(lineSeparator); + expected.append(StringUtils.repeat(lineIndenter, 1)).append("").append(lineSeparator); + expected.append(StringUtils.repeat(lineIndenter, 2)) + .append("

      Paragraph 1, line 1. Paragraph 1, line 2.

      ") + .append(lineSeparator); + expected.append(StringUtils.repeat(lineIndenter, 2)) + .append("
      ") + .append(lineSeparator); + expected.append(StringUtils.repeat(lineIndenter, 3)) + .append("

      Section title

      ") + .append(lineSeparator); + expected.append(StringUtils.repeat(lineIndenter, 2)).append("
      ").append(lineSeparator); + expected.append(StringUtils.repeat(lineIndenter, 1)).append("").append(lineSeparator); + expected.append(""); return expected.toString(); } diff --git a/src/test/java/org/codehaus/plexus/util/xml/XmlStreamReaderTest.java b/src/test/java/org/codehaus/plexus/util/xml/XmlStreamReaderTest.java index 7ca8cc48..93f4eacf 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/XmlStreamReaderTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/XmlStreamReaderTest.java @@ -21,10 +21,9 @@ import java.io.InputStream; import java.io.SequenceInputStream; -import org.codehaus.plexus.util.IOUtil; - import junit.framework.ComparisonFailure; import junit.framework.TestCase; +import org.codehaus.plexus.util.IOUtil; /** *

      XmlStreamReaderTest class.

      @@ -33,9 +32,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class XmlStreamReaderTest - extends TestCase -{ +public class XmlStreamReaderTest extends TestCase { /** french */ private static final String TEXT_LATIN1 = "eacute: \u00E9"; @@ -50,76 +47,63 @@ public class XmlStreamReaderTest /** Unicode: support everything */ private static final String TEXT_UNICODE = - TEXT_LATIN1 + ", " + TEXT_LATIN7 + ", " + TEXT_LATIN15 + ", " + TEXT_EUC_JP; + TEXT_LATIN1 + ", " + TEXT_LATIN7 + ", " + TEXT_LATIN15 + ", " + TEXT_EUC_JP; /** see http://unicode.org/faq/utf_bom.html#BOM */ - private static final byte[] BOM_UTF8 = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }; + private static final byte[] BOM_UTF8 = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}; - private static final byte[] BOM_UTF16BE = { (byte) 0xFE, (byte) 0xFF }; + private static final byte[] BOM_UTF16BE = {(byte) 0xFE, (byte) 0xFF}; - private static final byte[] BOM_UTF16LE = { (byte) 0xFF, (byte) 0xFE }; + private static final byte[] BOM_UTF16LE = {(byte) 0xFF, (byte) 0xFE}; - private static final byte[] BOM_UTF32BE = { (byte) 0x00, (byte) 0x00, (byte) 0xFF, (byte) 0xFE }; + private static final byte[] BOM_UTF32BE = {(byte) 0x00, (byte) 0x00, (byte) 0xFF, (byte) 0xFE}; - private static final byte[] BOM_UTF32LE = { (byte) 0xFF, (byte) 0xFE, (byte) 0x00, (byte) 0x00 }; + private static final byte[] BOM_UTF32LE = {(byte) 0xFF, (byte) 0xFE, (byte) 0x00, (byte) 0x00}; - private static String createXmlContent( String text, String encoding ) - { + private static String createXmlContent(String text, String encoding) { String xmlDecl = ""; - if ( encoding != null ) - { + if (encoding != null) { xmlDecl = ""; } String xml = xmlDecl + "\n" + text + ""; return xml; } - private static void checkXmlContent( String xml, String encoding ) - throws IOException - { - checkXmlContent( xml, encoding, null ); + private static void checkXmlContent(String xml, String encoding) throws IOException { + checkXmlContent(xml, encoding, null); } - private static void checkXmlContent( String xml, String encoding, byte... bom ) - throws IOException - { - byte[] xmlContent = xml.getBytes( encoding ); - InputStream in = new ByteArrayInputStream( xmlContent ); + private static void checkXmlContent(String xml, String encoding, byte... bom) throws IOException { + byte[] xmlContent = xml.getBytes(encoding); + InputStream in = new ByteArrayInputStream(xmlContent); - if ( bom != null ) - { - in = new SequenceInputStream( new ByteArrayInputStream( bom ), in ); + if (bom != null) { + in = new SequenceInputStream(new ByteArrayInputStream(bom), in); } - XmlStreamReader reader = new XmlStreamReader( in ); - assertEquals( encoding, reader.getEncoding() ); - String result = IOUtil.toString( reader ); - assertEquals( xml, result ); + XmlStreamReader reader = new XmlStreamReader(in); + assertEquals(encoding, reader.getEncoding()); + String result = IOUtil.toString(reader); + assertEquals(xml, result); } - private static void checkXmlStreamReader( String text, String encoding, String effectiveEncoding ) - throws IOException - { - checkXmlStreamReader( text, encoding, effectiveEncoding, null ); + private static void checkXmlStreamReader(String text, String encoding, String effectiveEncoding) + throws IOException { + checkXmlStreamReader(text, encoding, effectiveEncoding, null); } - private static void checkXmlStreamReader( String text, String encoding ) - throws IOException - { - checkXmlStreamReader( text, encoding, encoding, null ); + private static void checkXmlStreamReader(String text, String encoding) throws IOException { + checkXmlStreamReader(text, encoding, encoding, null); } - private static void checkXmlStreamReader( String text, String encoding, byte... bom ) - throws IOException - { - checkXmlStreamReader( text, encoding, encoding, bom ); + private static void checkXmlStreamReader(String text, String encoding, byte... bom) throws IOException { + checkXmlStreamReader(text, encoding, encoding, bom); } - private static void checkXmlStreamReader( String text, String encoding, String effectiveEncoding, byte... bom ) - throws IOException - { - String xml = createXmlContent( text, encoding ); - checkXmlContent( xml, effectiveEncoding, bom ); + private static void checkXmlStreamReader(String text, String encoding, String effectiveEncoding, byte... bom) + throws IOException { + String xml = createXmlContent(text, encoding); + checkXmlContent(xml, effectiveEncoding, bom); } /** @@ -127,12 +111,10 @@ private static void checkXmlStreamReader( String text, String encoding, String e * * @throws java.io.IOException if any. */ - public void testNoXmlHeader() - throws IOException - { + public void testNoXmlHeader() throws IOException { String xml = "text with no XML header"; - checkXmlContent( xml, "UTF-8" ); - checkXmlContent( xml, "UTF-8", BOM_UTF8 ); + checkXmlContent(xml, "UTF-8"); + checkXmlContent(xml, "UTF-8", BOM_UTF8); } /** @@ -140,11 +122,9 @@ public void testNoXmlHeader() * * @throws java.io.IOException if any. */ - public void testDefaultEncoding() - throws IOException - { - checkXmlStreamReader( TEXT_UNICODE, null, "UTF-8" ); - checkXmlStreamReader( TEXT_UNICODE, null, "UTF-8", BOM_UTF8 ); + public void testDefaultEncoding() throws IOException { + checkXmlStreamReader(TEXT_UNICODE, null, "UTF-8"); + checkXmlStreamReader(TEXT_UNICODE, null, "UTF-8", BOM_UTF8); } /** @@ -152,11 +132,9 @@ public void testDefaultEncoding() * * @throws java.io.IOException if any. */ - public void testUTF8Encoding() - throws IOException - { - checkXmlStreamReader( TEXT_UNICODE, "UTF-8" ); - checkXmlStreamReader( TEXT_UNICODE, "UTF-8", BOM_UTF8 ); + public void testUTF8Encoding() throws IOException { + checkXmlStreamReader(TEXT_UNICODE, "UTF-8"); + checkXmlStreamReader(TEXT_UNICODE, "UTF-8", BOM_UTF8); } /** @@ -164,12 +142,10 @@ public void testUTF8Encoding() * * @throws java.io.IOException if any. */ - public void testUTF16Encoding() - throws IOException - { - checkXmlStreamReader( TEXT_UNICODE, "UTF-16", "UTF-16BE", null ); - checkXmlStreamReader( TEXT_UNICODE, "UTF-16", "UTF-16LE", BOM_UTF16LE ); - checkXmlStreamReader( TEXT_UNICODE, "UTF-16", "UTF-16BE", BOM_UTF16BE ); + public void testUTF16Encoding() throws IOException { + checkXmlStreamReader(TEXT_UNICODE, "UTF-16", "UTF-16BE", null); + checkXmlStreamReader(TEXT_UNICODE, "UTF-16", "UTF-16LE", BOM_UTF16LE); + checkXmlStreamReader(TEXT_UNICODE, "UTF-16", "UTF-16BE", BOM_UTF16BE); } /** @@ -177,10 +153,8 @@ public void testUTF16Encoding() * * @throws java.io.IOException if any. */ - public void testUTF16BEEncoding() - throws IOException - { - checkXmlStreamReader( TEXT_UNICODE, "UTF-16BE" ); + public void testUTF16BEEncoding() throws IOException { + checkXmlStreamReader(TEXT_UNICODE, "UTF-16BE"); } /** @@ -188,10 +162,8 @@ public void testUTF16BEEncoding() * * @throws java.io.IOException if any. */ - public void testUTF16LEEncoding() - throws IOException - { - checkXmlStreamReader( TEXT_UNICODE, "UTF-16LE" ); + public void testUTF16LEEncoding() throws IOException { + checkXmlStreamReader(TEXT_UNICODE, "UTF-16LE"); } /** @@ -199,10 +171,8 @@ public void testUTF16LEEncoding() * * @throws java.io.IOException if any. */ - public void testLatin1Encoding() - throws IOException - { - checkXmlStreamReader( TEXT_LATIN1, "ISO-8859-1" ); + public void testLatin1Encoding() throws IOException { + checkXmlStreamReader(TEXT_LATIN1, "ISO-8859-1"); } /** @@ -210,10 +180,8 @@ public void testLatin1Encoding() * * @throws java.io.IOException if any. */ - public void testLatin7Encoding() - throws IOException - { - checkXmlStreamReader( TEXT_LATIN7, "ISO-8859-7" ); + public void testLatin7Encoding() throws IOException { + checkXmlStreamReader(TEXT_LATIN7, "ISO-8859-7"); } /** @@ -221,10 +189,8 @@ public void testLatin7Encoding() * * @throws java.io.IOException if any. */ - public void testLatin15Encoding() - throws IOException - { - checkXmlStreamReader( TEXT_LATIN15, "ISO-8859-15" ); + public void testLatin15Encoding() throws IOException { + checkXmlStreamReader(TEXT_LATIN15, "ISO-8859-15"); } /** @@ -232,10 +198,8 @@ public void testLatin15Encoding() * * @throws java.io.IOException if any. */ - public void testEUC_JPEncoding() - throws IOException - { - checkXmlStreamReader( TEXT_EUC_JP, "EUC-JP" ); + public void testEUC_JPEncoding() throws IOException { + checkXmlStreamReader(TEXT_EUC_JP, "EUC-JP"); } /** @@ -243,10 +207,8 @@ public void testEUC_JPEncoding() * * @throws java.io.IOException if any. */ - public void testEBCDICEncoding() - throws IOException - { - checkXmlStreamReader( "simple text in EBCDIC", "CP1047" ); + public void testEBCDICEncoding() throws IOException { + checkXmlStreamReader("simple text in EBCDIC", "CP1047"); } /** @@ -254,16 +216,11 @@ public void testEBCDICEncoding() * * @throws java.io.IOException if any. */ - public void testInappropriateEncoding() - throws IOException - { - try - { - checkXmlStreamReader( TEXT_UNICODE, "ISO-8859-2" ); - fail( "Check should have failed, since some characters are not available in the specified encoding" ); - } - catch ( ComparisonFailure cf ) - { + public void testInappropriateEncoding() throws IOException { + try { + checkXmlStreamReader(TEXT_UNICODE, "ISO-8859-2"); + fail("Check should have failed, since some characters are not available in the specified encoding"); + } catch (ComparisonFailure cf) { // expected failure, since the encoding does not contain some characters } } @@ -273,25 +230,23 @@ public void testInappropriateEncoding() * * @throws java.io.IOException if any. */ - public void testEncodingAttribute() - throws IOException - { + public void testEncodingAttribute() throws IOException { String xml = ""; - checkXmlContent( xml, "US-ASCII" ); + checkXmlContent(xml, "US-ASCII"); xml = ""; - checkXmlContent( xml, "US-ASCII" ); + checkXmlContent(xml, "US-ASCII"); xml = ""; - checkXmlContent( xml, "UTF-8" ); + checkXmlContent(xml, "UTF-8"); xml = "\n"; - checkXmlContent( xml, "US-ASCII" ); + checkXmlContent(xml, "US-ASCII"); xml = "\n"; - checkXmlContent( xml, "UTF-8" ); + checkXmlContent(xml, "UTF-8"); xml = ""; - checkXmlContent( xml, "UTF-8" ); + checkXmlContent(xml, "UTF-8"); } } 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 fa13aaa0..2930665e 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/XmlStreamWriterTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/XmlStreamWriterTest.java @@ -1,7 +1,5 @@ package org.codehaus.plexus.util.xml; -import static org.junit.Assert.assertEquals; - /* * Copyright The Codehaus Foundation. * @@ -17,12 +15,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** *

      XmlStreamWriterTest class.

      * @@ -30,8 +29,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class XmlStreamWriterTest -{ +public class XmlStreamWriterTest { /** french */ private static final String TEXT_LATIN1 = "eacute: \u00E9"; @@ -46,37 +44,31 @@ public class XmlStreamWriterTest /** Unicode: support everything */ private static final String TEXT_UNICODE = - TEXT_LATIN1 + ", " + TEXT_LATIN7 + ", " + TEXT_LATIN15 + ", " + TEXT_EUC_JP; + TEXT_LATIN1 + ", " + TEXT_LATIN7 + ", " + TEXT_LATIN15 + ", " + TEXT_EUC_JP; - private static String createXmlContent( String text, String encoding ) - { + private static String createXmlContent(String text, String encoding) { String xmlDecl = ""; - if ( encoding != null ) - { + if (encoding != null) { xmlDecl = ""; } String xml = xmlDecl + "\n" + text + ""; return xml; } - private static void checkXmlContent( String xml, String encoding ) - throws IOException - { + private static void checkXmlContent(String xml, String encoding) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); - XmlStreamWriter writer = new XmlStreamWriter( out ); - writer.write( xml ); + XmlStreamWriter writer = new XmlStreamWriter(out); + writer.write(xml); writer.close(); byte[] xmlContent = out.toByteArray(); - String result = new String( xmlContent, encoding ); - assertEquals( xml, result ); + String result = new String(xmlContent, encoding); + assertEquals(xml, result); } - private static void checkXmlWriter( String text, String encoding ) - throws IOException - { - String xml = createXmlContent( text, encoding ); - String effectiveEncoding = ( encoding == null ) ? "UTF-8" : encoding; - checkXmlContent( xml, effectiveEncoding ); + private static void checkXmlWriter(String text, String encoding) throws IOException { + String xml = createXmlContent(text, encoding); + String effectiveEncoding = (encoding == null) ? "UTF-8" : encoding; + checkXmlContent(xml, effectiveEncoding); } /** @@ -85,11 +77,9 @@ private static void checkXmlWriter( String text, String encoding ) * @throws java.io.IOException if any. */ @Test - public void testNoXmlHeader() - throws IOException - { + public void testNoXmlHeader() throws IOException { String xml = "text with no XML header"; - checkXmlContent( xml, "UTF-8" ); + checkXmlContent(xml, "UTF-8"); } /** @@ -98,15 +88,13 @@ public void testNoXmlHeader() * @throws java.io.IOException if any. */ @Test - public void testEmpty() - throws IOException - { + public void testEmpty() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); - XmlStreamWriter writer = new XmlStreamWriter( out ); + XmlStreamWriter writer = new XmlStreamWriter(out); writer.flush(); - writer.write( "" ); + writer.write(""); writer.flush(); - writer.write( "." ); + writer.write("."); writer.flush(); writer.close(); } @@ -117,10 +105,8 @@ public void testEmpty() * @throws java.io.IOException if any. */ @Test - public void testDefaultEncoding() - throws IOException - { - checkXmlWriter( TEXT_UNICODE, null ); + public void testDefaultEncoding() throws IOException { + checkXmlWriter(TEXT_UNICODE, null); } /** @@ -129,10 +115,8 @@ public void testDefaultEncoding() * @throws java.io.IOException if any. */ @Test - public void testUTF8Encoding() - throws IOException - { - checkXmlWriter( TEXT_UNICODE, "UTF-8" ); + public void testUTF8Encoding() throws IOException { + checkXmlWriter(TEXT_UNICODE, "UTF-8"); } /** @@ -141,10 +125,8 @@ public void testUTF8Encoding() * @throws java.io.IOException if any. */ @Test - public void testUTF16Encoding() - throws IOException - { - checkXmlWriter( TEXT_UNICODE, "UTF-16" ); + public void testUTF16Encoding() throws IOException { + checkXmlWriter(TEXT_UNICODE, "UTF-16"); } /** @@ -153,10 +135,8 @@ public void testUTF16Encoding() * @throws java.io.IOException if any. */ @Test - public void testUTF16BEEncoding() - throws IOException - { - checkXmlWriter( TEXT_UNICODE, "UTF-16BE" ); + public void testUTF16BEEncoding() throws IOException { + checkXmlWriter(TEXT_UNICODE, "UTF-16BE"); } /** @@ -165,10 +145,8 @@ public void testUTF16BEEncoding() * @throws java.io.IOException if any. */ @Test - public void testUTF16LEEncoding() - throws IOException - { - checkXmlWriter( TEXT_UNICODE, "UTF-16LE" ); + public void testUTF16LEEncoding() throws IOException { + checkXmlWriter(TEXT_UNICODE, "UTF-16LE"); } /** @@ -177,10 +155,8 @@ public void testUTF16LEEncoding() * @throws java.io.IOException if any. */ @Test - public void testLatin1Encoding() - throws IOException - { - checkXmlWriter( TEXT_LATIN1, "ISO-8859-1" ); + public void testLatin1Encoding() throws IOException { + checkXmlWriter(TEXT_LATIN1, "ISO-8859-1"); } /** @@ -189,10 +165,8 @@ public void testLatin1Encoding() * @throws java.io.IOException if any. */ @Test - public void testLatin7Encoding() - throws IOException - { - checkXmlWriter( TEXT_LATIN7, "ISO-8859-7" ); + public void testLatin7Encoding() throws IOException { + checkXmlWriter(TEXT_LATIN7, "ISO-8859-7"); } /** @@ -201,10 +175,8 @@ public void testLatin7Encoding() * @throws java.io.IOException if any. */ @Test - public void testLatin15Encoding() - throws IOException - { - checkXmlWriter( TEXT_LATIN15, "ISO-8859-15" ); + public void testLatin15Encoding() throws IOException { + checkXmlWriter(TEXT_LATIN15, "ISO-8859-15"); } /** @@ -213,10 +185,8 @@ public void testLatin15Encoding() * @throws java.io.IOException if any. */ @Test - public void testEUC_JPEncoding() - throws IOException - { - checkXmlWriter( TEXT_EUC_JP, "EUC-JP" ); + public void testEUC_JPEncoding() throws IOException { + checkXmlWriter(TEXT_EUC_JP, "EUC-JP"); } /** @@ -225,9 +195,7 @@ public void testEUC_JPEncoding() * @throws java.io.IOException if any. */ @Test - public void testEBCDICEncoding() - throws IOException - { - checkXmlWriter( "simple text in EBCDIC", "CP1047" ); + public void testEBCDICEncoding() throws IOException { + checkXmlWriter("simple text in EBCDIC", "CP1047"); } } 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 4d4a083f..f11cb29e 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/XmlUtilTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/XmlUtilTest.java @@ -16,9 +16,6 @@ * limitations under the License. */ -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -34,6 +31,9 @@ import org.codehaus.plexus.util.WriterFactory; import org.junit.Test; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + /** * Test the {@link org.codehaus.plexus.util.xml.XmlUtil} class. * @@ -41,8 +41,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class XmlUtilTest -{ +public class XmlUtilTest { private String basedir; /** @@ -50,23 +49,18 @@ public class XmlUtilTest * * @return a {@link java.lang.String} object. */ - public final String getBasedir() - { - if ( null == basedir ) - { - basedir = System.getProperty( "basedir", new File( "" ).getAbsolutePath() ); + public final String getBasedir() { + if (null == basedir) { + basedir = System.getProperty("basedir", new File("").getAbsolutePath()); } return basedir; } - private File getTestOutputFile( String relPath ) - throws IOException - { - final File file = new File( getBasedir(), relPath ); + private File getTestOutputFile(String relPath) throws IOException { + final File file = new File(getBasedir(), relPath); final File parentFile = file.getParentFile(); - if ( !parentFile.isDirectory() && !parentFile.mkdirs() ) - { - throw new IOException( "Could not create test directory " + parentFile ); + if (!parentFile.isDirectory() && !parentFile.mkdirs()) { + throw new IOException("Could not create test directory " + parentFile); } return file; } @@ -77,28 +71,24 @@ private File getTestOutputFile( String relPath ) * @throws java.lang.Exception if any. */ @Test - public void testPrettyFormatInputStreamOutputStream() - throws Exception - { - File testDocument = new File( getBasedir(), "src/test/resources/testDocument.xhtml" ); - assertTrue( testDocument.exists() ); + public void testPrettyFormatInputStreamOutputStream() throws Exception { + File testDocument = new File(getBasedir(), "src/test/resources/testDocument.xhtml"); + assertTrue(testDocument.exists()); InputStream is = null; OutputStream os = null; - try - { - is = Files.newInputStream( testDocument.toPath() ); - os = Files.newOutputStream( getTestOutputFile( "target/test/prettyFormatTestDocumentOutputStream.xml" ).toPath() ); - - assertNotNull( is ); - assertNotNull( os ); - - XmlUtil.prettyFormat( is, os ); - } - finally - { - IOUtil.close( is ); - IOUtil.close( os ); + try { + is = Files.newInputStream(testDocument.toPath()); + os = Files.newOutputStream(getTestOutputFile("target/test/prettyFormatTestDocumentOutputStream.xml") + .toPath()); + + assertNotNull(is); + assertNotNull(os); + + XmlUtil.prettyFormat(is, os); + } finally { + IOUtil.close(is); + IOUtil.close(os); } } @@ -108,29 +98,23 @@ public void testPrettyFormatInputStreamOutputStream() * @throws java.lang.Exception if any. */ @Test - public void testPrettyFormatReaderWriter() - throws Exception - { - File testDocument = new File( getBasedir(), "src/test/resources/testDocument.xhtml" ); - assertTrue( testDocument.exists() ); + public void testPrettyFormatReaderWriter() throws Exception { + File testDocument = new File(getBasedir(), "src/test/resources/testDocument.xhtml"); + assertTrue(testDocument.exists()); Reader reader = null; Writer writer = null; - try - { - reader = ReaderFactory.newXmlReader( testDocument ); - writer = - WriterFactory.newXmlWriter( getTestOutputFile( "target/test/prettyFormatTestDocumentWriter.xml" ) ); + try { + reader = ReaderFactory.newXmlReader(testDocument); + writer = WriterFactory.newXmlWriter(getTestOutputFile("target/test/prettyFormatTestDocumentWriter.xml")); - assertNotNull( reader ); - assertNotNull( writer ); + assertNotNull(reader); + assertNotNull(writer); - XmlUtil.prettyFormat( reader, writer ); - } - finally - { - IOUtil.close( reader ); - IOUtil.close( writer ); + XmlUtil.prettyFormat(reader, writer); + } finally { + IOUtil.close(reader); + IOUtil.close(writer); } } @@ -140,34 +124,29 @@ public void testPrettyFormatReaderWriter() * @throws java.lang.Exception if any. */ @Test - public void testPrettyFormatString() - throws Exception - { - File testDocument = new File( getBasedir(), "src/test/resources/testDocument.xhtml" ); - assertTrue( testDocument.exists() ); + public void testPrettyFormatString() throws Exception { + File testDocument = new File(getBasedir(), "src/test/resources/testDocument.xhtml"); + assertTrue(testDocument.exists()); Reader reader = null; Writer writer = null; String content; - try - { - reader = ReaderFactory.newXmlReader( testDocument ); - content = IOUtil.toString( reader ); + try { + reader = ReaderFactory.newXmlReader(testDocument); + content = IOUtil.toString(reader); - reader = ReaderFactory.newXmlReader( testDocument ); + reader = ReaderFactory.newXmlReader(testDocument); writer = new StringWriter(); - XmlUtil.prettyFormat( reader, writer ); - } - finally - { - IOUtil.close( reader ); - IOUtil.close( writer ); + XmlUtil.prettyFormat(reader, writer); + } finally { + IOUtil.close(reader); + IOUtil.close(writer); } - assertNotNull( content ); + assertNotNull(content); - int countEOL = StringUtils.countMatches( content, XmlUtil.DEFAULT_LINE_SEPARATOR ); - assertTrue( countEOL < StringUtils.countMatches( writer.toString(), XmlUtil.DEFAULT_LINE_SEPARATOR ) ); + int countEOL = StringUtils.countMatches(content, XmlUtil.DEFAULT_LINE_SEPARATOR); + assertTrue(countEOL < StringUtils.countMatches(writer.toString(), XmlUtil.DEFAULT_LINE_SEPARATOR)); } /** @@ -176,28 +155,23 @@ public void testPrettyFormatString() * @throws java.lang.Exception if any. */ @Test - public void testPrettyFormatReaderWriter2() - throws Exception - { - File testDocument = new File( getBasedir(), "src/test/resources/test.xdoc.xhtml" ); - assertTrue( testDocument.exists() ); + public void testPrettyFormatReaderWriter2() throws Exception { + File testDocument = new File(getBasedir(), "src/test/resources/test.xdoc.xhtml"); + assertTrue(testDocument.exists()); Reader reader = null; Writer writer = null; - try - { - reader = ReaderFactory.newXmlReader( testDocument ); - writer = WriterFactory.newXmlWriter( getTestOutputFile( "target/test/prettyFormatTestXdocWriter.xml" ) ); + try { + reader = ReaderFactory.newXmlReader(testDocument); + writer = WriterFactory.newXmlWriter(getTestOutputFile("target/test/prettyFormatTestXdocWriter.xml")); - assertNotNull( reader ); - assertNotNull( writer ); + assertNotNull(reader); + assertNotNull(writer); - XmlUtil.prettyFormat( reader, writer ); - } - finally - { - IOUtil.close( reader ); - IOUtil.close( writer ); + XmlUtil.prettyFormat(reader, writer); + } finally { + IOUtil.close(reader); + IOUtil.close(writer); } } } 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 4c1f6954..23ce4263 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/XmlWriterUtilTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/XmlWriterUtilTest.java @@ -16,9 +16,6 @@ * 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; @@ -29,6 +26,9 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** *

      XmlWriterUtilTest class.

      * @@ -36,8 +36,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class XmlWriterUtilTest -{ +public class XmlWriterUtilTest { private OutputStream output; private Writer writer; @@ -50,12 +49,10 @@ public class XmlWriterUtilTest * @throws java.lang.Exception if any. */ @Before - public void setUp() - throws Exception - { + public void setUp() throws Exception { output = new ByteArrayOutputStream(); - writer = WriterFactory.newXmlWriter( output ); - xmlWriter = new PrettyPrintXMLWriter( writer ); + writer = WriterFactory.newXmlWriter(output); + xmlWriter = new PrettyPrintXMLWriter(writer); } /** @@ -64,9 +61,7 @@ public void setUp() * @throws java.lang.Exception if any. */ @After - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { xmlWriter = null; writer = null; output = null; @@ -79,12 +74,10 @@ public void tearDown() * @throws java.lang.Exception if any */ @Test - public void testWriteLineBreakXMLWriter() - throws Exception - { - XmlWriterUtil.writeLineBreak( xmlWriter ); + public void testWriteLineBreakXMLWriter() throws Exception { + XmlWriterUtil.writeLineBreak(xmlWriter); writer.close(); - assertTrue( StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) == 1 ); + assertTrue(StringUtils.countMatches(output.toString(), XmlWriterUtil.LS) == 1); } /** @@ -94,12 +87,10 @@ public void testWriteLineBreakXMLWriter() * @throws java.lang.Exception if any */ @Test - public void testWriteLineBreakXMLWriterInt() - throws Exception - { - XmlWriterUtil.writeLineBreak( xmlWriter, 10 ); + public void testWriteLineBreakXMLWriterInt() throws Exception { + XmlWriterUtil.writeLineBreak(xmlWriter, 10); writer.close(); - assertTrue( StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) == 10 ); + assertTrue(StringUtils.countMatches(output.toString(), XmlWriterUtil.LS) == 10); } /** @@ -109,15 +100,13 @@ public void testWriteLineBreakXMLWriterInt() * @throws java.lang.Exception if any */ @Test - public void testWriteLineBreakXMLWriterIntInt() - throws Exception - { - XmlWriterUtil.writeLineBreak( xmlWriter, 10, 2 ); + public void testWriteLineBreakXMLWriterIntInt() throws Exception { + XmlWriterUtil.writeLineBreak(xmlWriter, 10, 2); writer.close(); - assertTrue( StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) == 10 ); - assertTrue( StringUtils.countMatches( output.toString(), - StringUtils.repeat( " ", - 2 * XmlWriterUtil.DEFAULT_INDENTATION_SIZE ) ) == 1 ); + assertTrue(StringUtils.countMatches(output.toString(), XmlWriterUtil.LS) == 10); + assertTrue(StringUtils.countMatches( + output.toString(), StringUtils.repeat(" ", 2 * XmlWriterUtil.DEFAULT_INDENTATION_SIZE)) + == 1); } /** @@ -127,13 +116,11 @@ public void testWriteLineBreakXMLWriterIntInt() * @throws java.lang.Exception if any */ @Test - public void testWriteLineBreakXMLWriterIntIntInt() - throws Exception - { - XmlWriterUtil.writeLineBreak( xmlWriter, 10, 2, 4 ); + public void testWriteLineBreakXMLWriterIntIntInt() throws Exception { + XmlWriterUtil.writeLineBreak(xmlWriter, 10, 2, 4); writer.close(); - assertTrue( StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) == 10 ); - assertTrue( StringUtils.countMatches( output.toString(), StringUtils.repeat( " ", 2 * 4 ) ) == 1 ); + assertTrue(StringUtils.countMatches(output.toString(), XmlWriterUtil.LS) == 10); + assertTrue(StringUtils.countMatches(output.toString(), StringUtils.repeat(" ", 2 * 4)) == 1); } /** @@ -143,15 +130,14 @@ public void testWriteLineBreakXMLWriterIntIntInt() * @throws java.lang.Exception if any */ @Test - public void testWriteCommentLineBreakXMLWriter() - throws Exception - { - XmlWriterUtil.writeCommentLineBreak( xmlWriter ); + public void testWriteCommentLineBreakXMLWriter() throws Exception { + XmlWriterUtil.writeCommentLineBreak(xmlWriter); writer.close(); StringBuilder sb = new StringBuilder(); - sb.append( "" ).append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ); + sb.append("") + .append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); + assertTrue(output.toString().length() == XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length()); } /** @@ -161,19 +147,17 @@ public void testWriteCommentLineBreakXMLWriter() * @throws java.lang.Exception if any */ @Test - public void testWriteCommentLineBreakXMLWriterInt() - throws Exception - { - XmlWriterUtil.writeCommentLineBreak( xmlWriter, 20 ); + public void testWriteCommentLineBreakXMLWriterInt() throws Exception { + XmlWriterUtil.writeCommentLineBreak(xmlWriter, 20); writer.close(); - assertEquals( output.toString(), "" + XmlWriterUtil.LS ); + assertEquals(output.toString(), "" + XmlWriterUtil.LS); tearDown(); setUp(); - XmlWriterUtil.writeCommentLineBreak( xmlWriter, 10 ); + XmlWriterUtil.writeCommentLineBreak(xmlWriter, 10); writer.close(); - assertEquals( output.toString(), output.toString(), "" + XmlWriterUtil.LS ); + assertEquals(output.toString(), output.toString(), "" + XmlWriterUtil.LS); } /** @@ -183,38 +167,40 @@ public void testWriteCommentLineBreakXMLWriterInt() * @throws java.lang.Exception if any */ @Test - public void testWriteCommentXMLWriterString() - throws Exception - { - XmlWriterUtil.writeComment( xmlWriter, "hello" ); + public void testWriteCommentXMLWriterString() throws Exception { + XmlWriterUtil.writeComment(xmlWriter, "hello"); writer.close(); StringBuffer sb = new StringBuffer(); - sb.append( "" ).append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ); + sb.append("") + .append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); + assertTrue(output.toString().length() == XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length()); tearDown(); setUp(); - XmlWriterUtil.writeComment( xmlWriter, - "hellooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" ); + XmlWriterUtil.writeComment( + xmlWriter, "hellooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"); writer.close(); sb = new StringBuffer(); - sb.append( "" ).append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() >= XmlWriterUtil.DEFAULT_COLUMN_LINE ); + sb.append("") + .append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); + assertTrue(output.toString().length() >= XmlWriterUtil.DEFAULT_COLUMN_LINE); tearDown(); setUp(); - XmlWriterUtil.writeComment( xmlWriter, "hello\nworld" ); + XmlWriterUtil.writeComment(xmlWriter, "hello\nworld"); writer.close(); sb = new StringBuffer(); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 2 - * ( XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ) ); + sb.append("") + .append(XmlWriterUtil.LS); + sb.append("") + .append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); + assertTrue( + output.toString().length() == 2 * (XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length())); } /** @@ -224,33 +210,37 @@ public void testWriteCommentXMLWriterString() * @throws java.lang.Exception if any */ @Test - public void testWriteCommentXMLWriterStringInt() - throws Exception - { - String indent = StringUtils.repeat( " ", 2 * XmlWriterUtil.DEFAULT_INDENTATION_SIZE ); + public void testWriteCommentXMLWriterStringInt() throws Exception { + String indent = StringUtils.repeat(" ", 2 * XmlWriterUtil.DEFAULT_INDENTATION_SIZE); - XmlWriterUtil.writeComment( xmlWriter, "hello", 2 ); + XmlWriterUtil.writeComment(xmlWriter, "hello", 2); writer.close(); StringBuffer sb = new StringBuffer(); - sb.append( indent ); - sb.append( "" ).append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() - + 2 * XmlWriterUtil.DEFAULT_INDENTATION_SIZE ); + sb.append(indent); + sb.append("") + .append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); + assertTrue(output.toString().length() + == XmlWriterUtil.DEFAULT_COLUMN_LINE + - 1 + + XmlWriterUtil.LS.length() + + 2 * XmlWriterUtil.DEFAULT_INDENTATION_SIZE); tearDown(); setUp(); - XmlWriterUtil.writeComment( xmlWriter, "hello\nworld", 2 ); + XmlWriterUtil.writeComment(xmlWriter, "hello\nworld", 2); writer.close(); sb = new StringBuffer(); - sb.append( indent ); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( indent ); - sb.append( "" ).append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 2 - * ( XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ) + 2 * indent.length() ); + sb.append(indent); + sb.append("") + .append(XmlWriterUtil.LS); + sb.append(indent); + sb.append("") + .append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); + assertTrue(output.toString().length() + == 2 * (XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length()) + 2 * indent.length()); } /** @@ -260,33 +250,34 @@ public void testWriteCommentXMLWriterStringInt() * @throws java.lang.Exception if any */ @Test - public void testWriteCommentXMLWriterStringIntInt() - throws Exception - { - String repeat = StringUtils.repeat( " ", 2 * 4 ); + public void testWriteCommentXMLWriterStringIntInt() throws Exception { + String repeat = StringUtils.repeat(" ", 2 * 4); - XmlWriterUtil.writeComment( xmlWriter, "hello", 2, 4 ); + XmlWriterUtil.writeComment(xmlWriter, "hello", 2, 4); writer.close(); StringBuffer sb = new StringBuffer(); - sb.append( repeat ); - sb.append( "" ).append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() - + 2 * 4 ); + sb.append(repeat); + sb.append("") + .append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); + assertTrue(output.toString().length() + == XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() + 2 * 4); tearDown(); setUp(); - XmlWriterUtil.writeComment( xmlWriter, "hello\nworld", 2, 4 ); + XmlWriterUtil.writeComment(xmlWriter, "hello\nworld", 2, 4); writer.close(); sb = new StringBuffer(); - sb.append( repeat ); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( repeat ); - sb.append( "" ).append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 2 - * ( XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ) + 2 * repeat.length() ); + sb.append(repeat); + sb.append("") + .append(XmlWriterUtil.LS); + sb.append(repeat); + sb.append("") + .append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); + assertTrue(output.toString().length() + == 2 * (XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length()) + 2 * repeat.length()); } /** @@ -296,29 +287,27 @@ public void testWriteCommentXMLWriterStringIntInt() * @throws java.lang.Exception if any */ @Test - public void testWriteCommentXMLWriterStringIntIntInt() - throws Exception - { - String indent = StringUtils.repeat( " ", 2 * 4 ); + public void testWriteCommentXMLWriterStringIntIntInt() throws Exception { + String indent = StringUtils.repeat(" ", 2 * 4); - XmlWriterUtil.writeComment( xmlWriter, "hello", 2, 4, 50 ); + XmlWriterUtil.writeComment(xmlWriter, "hello", 2, 4, 50); writer.close(); StringBuffer sb = new StringBuffer(); - sb.append( indent ); - sb.append( "" ).append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 50 - 1 + XmlWriterUtil.LS.length() + 2 * 4 ); + sb.append(indent); + sb.append("").append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); + assertTrue(output.toString().length() == 50 - 1 + XmlWriterUtil.LS.length() + 2 * 4); tearDown(); setUp(); - XmlWriterUtil.writeComment( xmlWriter, "hello", 2, 4, 10 ); + XmlWriterUtil.writeComment(xmlWriter, "hello", 2, 4, 10); writer.close(); sb = new StringBuffer(); - sb.append( indent ); - sb.append( "" ).append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() >= 10 + 2 * 4 ); + sb.append(indent); + sb.append("").append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); + assertTrue(output.toString().length() >= 10 + 2 * 4); } /** @@ -328,40 +317,56 @@ public void testWriteCommentXMLWriterStringIntIntInt() * @throws java.lang.Exception if any */ @Test - public void testWriteCommentTextXMLWriterStringInt() - throws Exception - { - XmlWriterUtil.writeCommentText( xmlWriter, "hello", 0 ); + public void testWriteCommentTextXMLWriterStringInt() throws Exception { + XmlWriterUtil.writeCommentText(xmlWriter, "hello", 0); writer.close(); StringBuffer sb = new StringBuffer(); - sb.append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 3 * ( 80 - 1 + XmlWriterUtil.LS.length() ) - + 2 * XmlWriterUtil.LS.length() ); + sb.append(XmlWriterUtil.LS); + sb.append("") + .append(XmlWriterUtil.LS); + sb.append("") + .append(XmlWriterUtil.LS); + sb.append("") + .append(XmlWriterUtil.LS); + sb.append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); + assertTrue( + output.toString().length() == 3 * (80 - 1 + XmlWriterUtil.LS.length()) + 2 * XmlWriterUtil.LS.length()); tearDown(); setUp(); - String indent = StringUtils.repeat( " ", 2 * 2 ); + String indent = StringUtils.repeat(" ", 2 * 2); - XmlWriterUtil.writeCommentText( xmlWriter, "hello world with end of line\n and " - + "loooooooooooooooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnong line", 2 ); + XmlWriterUtil.writeCommentText( + xmlWriter, + "hello world with end of line\n and " + + "loooooooooooooooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnong line", + 2); writer.close(); sb = new StringBuffer(); - sb.append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( XmlWriterUtil.LS ); - sb.append( indent ); - assertEquals( output.toString(), sb.toString() ); + sb.append(XmlWriterUtil.LS); + sb.append(indent) + .append("") + .append(XmlWriterUtil.LS); + sb.append(indent) + .append("") + .append(XmlWriterUtil.LS); + sb.append(indent) + .append("") + .append(XmlWriterUtil.LS); + sb.append(indent) + .append("") + .append(XmlWriterUtil.LS); + sb.append(indent) + .append("") + .append(XmlWriterUtil.LS); + sb.append(indent) + .append("") + .append(XmlWriterUtil.LS); + sb.append(XmlWriterUtil.LS); + sb.append(indent); + assertEquals(output.toString(), sb.toString()); } /** @@ -371,23 +376,27 @@ public void testWriteCommentTextXMLWriterStringInt() * @throws java.lang.Exception if any */ @Test - public void testWriteCommentTextXMLWriterStringIntInt() - throws Exception - { - String indent = StringUtils.repeat( " ", 2 * 4 ); + public void testWriteCommentTextXMLWriterStringIntInt() throws Exception { + String indent = StringUtils.repeat(" ", 2 * 4); - XmlWriterUtil.writeCommentText( xmlWriter, "hello", 2, 4 ); + XmlWriterUtil.writeCommentText(xmlWriter, "hello", 2, 4); writer.close(); StringBuilder sb = new StringBuilder(); - sb.append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( XmlWriterUtil.LS ); - sb.append( indent ); - assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 3 * ( 80 - 1 + XmlWriterUtil.LS.length() ) + 4 * 2 * 4 - + 2 * XmlWriterUtil.LS.length() ); + sb.append(XmlWriterUtil.LS); + sb.append(indent) + .append("") + .append(XmlWriterUtil.LS); + sb.append(indent) + .append("") + .append(XmlWriterUtil.LS); + sb.append(indent) + .append("") + .append(XmlWriterUtil.LS); + sb.append(XmlWriterUtil.LS); + sb.append(indent); + assertEquals(output.toString(), sb.toString()); + assertTrue(output.toString().length() + == 3 * (80 - 1 + XmlWriterUtil.LS.length()) + 4 * 2 * 4 + 2 * XmlWriterUtil.LS.length()); } /** @@ -397,23 +406,27 @@ public void testWriteCommentTextXMLWriterStringIntInt() * @throws java.lang.Exception if any */ @Test - public void testWriteCommentTextXMLWriterStringIntIntInt() - throws Exception - { - String indent = StringUtils.repeat( " ", 2 * 4 ); + public void testWriteCommentTextXMLWriterStringIntIntInt() throws Exception { + String indent = StringUtils.repeat(" ", 2 * 4); - XmlWriterUtil.writeCommentText( xmlWriter, "hello", 2, 4, 50 ); + XmlWriterUtil.writeCommentText(xmlWriter, "hello", 2, 4, 50); writer.close(); StringBuilder sb = new StringBuilder(); - sb.append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( XmlWriterUtil.LS ); - sb.append( indent ); - assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 3 * ( 50 - 1 + XmlWriterUtil.LS.length() ) + 4 * 2 * 4 - + 2 * XmlWriterUtil.LS.length() ); + sb.append(XmlWriterUtil.LS); + sb.append(indent) + .append("") + .append(XmlWriterUtil.LS); + sb.append(indent) + .append("") + .append(XmlWriterUtil.LS); + sb.append(indent) + .append("") + .append(XmlWriterUtil.LS); + sb.append(XmlWriterUtil.LS); + sb.append(indent); + assertEquals(output.toString(), sb.toString()); + assertTrue(output.toString().length() + == 3 * (50 - 1 + XmlWriterUtil.LS.length()) + 4 * 2 * 4 + 2 * XmlWriterUtil.LS.length()); } /** @@ -423,14 +436,13 @@ public void testWriteCommentTextXMLWriterStringIntIntInt() * @throws java.lang.Exception if any */ @Test - public void testWriteCommentNull() - throws Exception - { - XmlWriterUtil.writeComment( xmlWriter, null ); + public void testWriteCommentNull() throws Exception { + XmlWriterUtil.writeComment(xmlWriter, null); writer.close(); StringBuilder sb = new StringBuilder(); - sb.append( "" ).append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); + sb.append("") + .append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); } /** @@ -440,14 +452,13 @@ public void testWriteCommentNull() * @throws java.lang.Exception if any */ @Test - public void testWriteCommentShort() - throws Exception - { - XmlWriterUtil.writeComment( xmlWriter, "This is a short text" ); + public void testWriteCommentShort() throws Exception { + XmlWriterUtil.writeComment(xmlWriter, "This is a short text"); writer.close(); StringBuilder sb = new StringBuilder(); - sb.append( "" ).append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); + sb.append("") + .append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); } /** @@ -457,18 +468,22 @@ public void testWriteCommentShort() * @throws java.lang.Exception if any */ @Test - public void testWriteCommentLong() - throws Exception - { - XmlWriterUtil.writeComment( xmlWriter, "Maven is a software project management and comprehension tool. " - + "Based on the concept of a project object model (POM), Maven can manage a project's build, reporting " - + "and documentation from a central piece of information." ); + public void testWriteCommentLong() throws Exception { + XmlWriterUtil.writeComment( + xmlWriter, + "Maven is a software project management and comprehension tool. " + + "Based on the concept of a project object model (POM), Maven can manage a project's build, reporting " + + "and documentation from a central piece of information."); writer.close(); StringBuilder sb = new StringBuilder(); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); - assertEquals( output.toString(), sb.toString() ); + sb.append("") + .append(XmlWriterUtil.LS); + sb.append("") + .append(XmlWriterUtil.LS); + sb.append("") + .append(XmlWriterUtil.LS); + sb.append("") + .append(XmlWriterUtil.LS); + assertEquals(output.toString(), sb.toString()); } } 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 3d3cb5ec..f9faac45 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomBuilderTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomBuilderTest.java @@ -16,10 +16,6 @@ * limitations under the License. */ -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; @@ -29,6 +25,10 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + /** * Test the Xpp3DomBuilder. * @@ -36,8 +36,7 @@ * @version $Id: $Id * @since 3.4.0 */ -public class Xpp3DomBuilderTest -{ +public class Xpp3DomBuilderTest { private static final String LS = System.lineSeparator(); /** @@ -46,16 +45,14 @@ public class Xpp3DomBuilderTest * @throws java.lang.Exception if any. */ @Test - public void testBuildFromReader() - throws Exception - { + public void testBuildFromReader() throws Exception { String domString = createDomString(); - Xpp3Dom dom = Xpp3DomBuilder.build( new StringReader( domString ) ); + Xpp3Dom dom = Xpp3DomBuilder.build(new StringReader(domString)); Xpp3Dom expectedDom = createExpectedDom(); - assertEquals( "check DOMs match", expectedDom, dom ); + assertEquals("check DOMs match", expectedDom, dom); } /** @@ -64,18 +61,17 @@ public void testBuildFromReader() * @throws java.lang.Exception if any. */ @Test - public void testBuildTrimming() - throws Exception - { + public void testBuildTrimming() throws Exception { String domString = createDomString(); - Xpp3Dom dom = Xpp3DomBuilder.build( new StringReader( domString ), true ); + Xpp3Dom dom = Xpp3DomBuilder.build(new StringReader(domString), true); - assertEquals( "test with trimming on", "element1", dom.getChild( "el1" ).getValue() ); + assertEquals("test with trimming on", "element1", dom.getChild("el1").getValue()); - dom = Xpp3DomBuilder.build( new StringReader( domString ), false ); + dom = Xpp3DomBuilder.build(new StringReader(domString), false); - assertEquals( "test with trimming off", " element1\n ", dom.getChild( "el1" ).getValue() ); + assertEquals( + "test with trimming off", " element1\n ", dom.getChild("el1").getValue()); } /** @@ -84,16 +80,14 @@ public void testBuildTrimming() * @throws java.lang.Exception if any. */ @Test - public void testBuildFromXpp3Dom() - throws Exception - { + public void testBuildFromXpp3Dom() throws Exception { Xpp3Dom expectedDom = createExpectedDom(); Xpp3Dom dom = null; XmlPullParser parser = new MXParser(); String domString = "" + createDomString() + ""; - parser.setInput( new StringReader( domString ) ); + parser.setInput(new StringReader(domString)); int eventType = parser.getEventType(); @@ -101,63 +95,47 @@ public void testBuildFromXpp3Dom() boolean newRootClosed = false; boolean rootClosed = false; - while ( eventType != XmlPullParser.END_DOCUMENT ) - { - if ( eventType == XmlPullParser.START_TAG ) - { + while (eventType != XmlPullParser.END_DOCUMENT) { + if (eventType == XmlPullParser.START_TAG) { String rawName = parser.getName(); - if ( "root".equals( rawName ) ) - { - dom = Xpp3DomBuilder.build( parser ); + if ("root".equals(rawName)) { + dom = Xpp3DomBuilder.build(parser); } - } - else if ( eventType == XmlPullParser.END_TAG ) - { + } else if (eventType == XmlPullParser.END_TAG) { String rawName = parser.getName(); - if ( "configuration".equals( rawName ) ) - { + if ("configuration".equals(rawName)) { configurationClosed = true; - } - else if ( "newRoot".equals( rawName ) ) - { + } else if ("newRoot".equals(rawName)) { newRootClosed = true; - } - else if ( "root".equals( rawName ) ) - { + } else if ("root".equals(rawName)) { rootClosed = true; } } eventType = parser.next(); } - assertEquals( "Check DOM matches", expectedDom, dom ); - assertFalse( "Check closing root was consumed", rootClosed ); - assertTrue( "Check continued to parse configuration", configurationClosed ); - assertTrue( "Check continued to parse newRoot", newRootClosed ); + assertEquals("Check DOM matches", expectedDom, dom); + assertFalse("Check closing root was consumed", rootClosed); + assertTrue("Check continued to parse configuration", configurationClosed); + assertTrue("Check continued to parse newRoot", newRootClosed); } /** * Test we get an error from the parser, and don't hit the IllegalStateException. */ @Test - public void testUnclosedXml() - { + public void testUnclosedXml() { String domString = "" + createDomString(); - try - { - Xpp3DomBuilder.build( new StringReader( domString ) ); - } - catch ( XmlPullParserException expected ) - { + try { + Xpp3DomBuilder.build(new StringReader(domString)); + } catch (XmlPullParserException expected) { // correct - assertTrue( true ); - } - catch ( IOException expected ) - { + assertTrue(true); + } catch (IOException expected) { // this will do too - assertTrue( true ); + assertTrue(true); } } @@ -168,18 +146,18 @@ public void testUnclosedXml() * @throws org.codehaus.plexus.util.xml.pull.XmlPullParserException if any. */ @Test - public void testEscapingInContent() - throws IOException, XmlPullParserException - { - Xpp3Dom dom = Xpp3DomBuilder.build( new StringReader( getEncodedString() ) ); + public void testEscapingInContent() throws IOException, XmlPullParserException { + Xpp3Dom dom = Xpp3DomBuilder.build(new StringReader(getEncodedString())); - assertEquals( "Check content value", "\"text\"", dom.getChild( "el" ).getValue() ); - assertEquals( "Check content value", "\"text\"", dom.getChild( "ela" ).getValue() ); - assertEquals( "Check content value", "\"text\"", dom.getChild( "elb" ).getValue() ); + assertEquals("Check content value", "\"text\"", dom.getChild("el").getValue()); + assertEquals( + "Check content value", "\"text\"", dom.getChild("ela").getValue()); + assertEquals( + "Check content value", "\"text\"", dom.getChild("elb").getValue()); StringWriter w = new StringWriter(); - Xpp3DomWriter.write( w, dom ); - assertEquals( "Compare stringified DOMs", getExpectedString(), w.toString() ); + Xpp3DomWriter.write(w, dom); + assertEquals("Compare stringified DOMs", getExpectedString(), w.toString()); } /** @@ -189,18 +167,16 @@ public void testEscapingInContent() * @throws org.codehaus.plexus.util.xml.pull.XmlPullParserException if any. */ @Test - public void testEscapingInAttributes() - throws IOException, XmlPullParserException - { + public void testEscapingInAttributes() throws IOException, XmlPullParserException { String s = getAttributeEncodedString(); - Xpp3Dom dom = Xpp3DomBuilder.build( new StringReader( s ) ); + Xpp3Dom dom = Xpp3DomBuilder.build(new StringReader(s)); - assertEquals( "Check attribute value", "", dom.getChild( "el" ).getAttribute( "att" ) ); + assertEquals("Check attribute value", "", dom.getChild("el").getAttribute("att")); StringWriter w = new StringWriter(); - Xpp3DomWriter.write( w, dom ); + Xpp3DomWriter.write(w, dom); String newString = w.toString(); - assertEquals( "Compare stringified DOMs", newString, s ); + assertEquals("Compare stringified DOMs", newString, s); } /** @@ -210,70 +186,61 @@ public void testEscapingInAttributes() * @throws org.codehaus.plexus.util.xml.pull.XmlPullParserException if any. */ @Test - public void testInputLocationTracking() - throws IOException, XmlPullParserException - { + public void testInputLocationTracking() throws IOException, XmlPullParserException { Xpp3DomBuilder.InputLocationBuilder ilb = new Xpp3DomBuilder.InputLocationBuilder() { - public Object toInputLocation( XmlPullParser parser ) - { + 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 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() ); + 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() - { + private static String getAttributeEncodedString() { StringBuilder domString = new StringBuilder(); - domString.append( "" ); - domString.append( LS ); - domString.append( " bar" ); - domString.append( LS ); - domString.append( "" ); + domString.append(""); + domString.append(LS); + domString.append(" bar"); + domString.append(LS); + domString.append(""); return domString.toString(); } - private static String getEncodedString() - { + private static String getEncodedString() { StringBuilder domString = new StringBuilder(); - domString.append( "\n" ); - domString.append( " \"text\"\n" ); - domString.append( " \"text\"]]>\n" ); - domString.append( " <b>"text"</b>\n" ); - domString.append( "" ); + domString.append("\n"); + domString.append(" \"text\"\n"); + domString.append(" \"text\"]]>\n"); + domString.append(" <b>"text"</b>\n"); + domString.append(""); return domString.toString(); } - private static String getExpectedString() - { + private static String getExpectedString() { StringBuilder domString = new StringBuilder(); - domString.append( "" ); - domString.append( LS ); - domString.append( " "text"" ); - domString.append( LS ); - domString.append( " <b>"text"</b>" ); - domString.append( LS ); - domString.append( " <b>"text"</b>" ); - domString.append( LS ); - domString.append( "" ); + domString.append(""); + domString.append(LS); + domString.append(" "text""); + domString.append(LS); + domString.append(" <b>"text"</b>"); + domString.append(LS); + domString.append(" <b>"text"</b>"); + domString.append(LS); + domString.append(""); return domString.toString(); } @@ -282,54 +249,52 @@ private static String getExpectedString() // HELPER METHODS // - private static String createDomString() - { + private static String createDomString() { StringBuilder buf = new StringBuilder(); - buf.append( "\n" ); - buf.append( " element1\n \n" ); - buf.append( " \n" ); - buf.append( " element3\n" ); - buf.append( " \n" ); - buf.append( " \n" ); - buf.append( " \n" ); - buf.append( " do not trim \n" ); - buf.append( "\n" ); + buf.append("\n"); + buf.append(" element1\n \n"); + buf.append(" \n"); + buf.append(" element3\n"); + buf.append(" \n"); + buf.append(" \n"); + buf.append(" \n"); + buf.append(" do not trim \n"); + buf.append("\n"); return buf.toString(); } - private static Xpp3Dom createExpectedDom() - { + 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 ); + 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 ); + 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 ); + 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); return expectedDom; } } diff --git a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomPerfTest.java b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomPerfTest.java index 22bba428..31636955 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomPerfTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomPerfTest.java @@ -46,22 +46,21 @@ @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Warmup(iterations = 3, time = 3, timeUnit = TimeUnit.SECONDS) -public class Xpp3DomPerfTest -{ +public class Xpp3DomPerfTest { @State(Scope.Benchmark) - static public class AdditionState { + public static class AdditionState { Xpp3Dom dom1; Xpp3Dom dom2; @Setup(Level.Iteration) public void setUp() throws IOException, XmlPullParserException { - String testDom = "onetwo"; - dom1 = Xpp3DomBuilder.build( new StringReader( testDom ) ); - dom2 = new Xpp3Dom( dom1 ); + String testDom = + "onetwo"; + dom1 = Xpp3DomBuilder.build(new StringReader(testDom)); + dom2 = new Xpp3Dom(dom1); } } - /** *

      benchmarkClone.

      * @@ -69,9 +68,8 @@ public void setUp() throws IOException, XmlPullParserException { * @return a {@link org.codehaus.plexus.util.xml.Xpp3Dom} object. */ @Benchmark - public Xpp3Dom benchmarkClone(AdditionState state) - { - return new Xpp3Dom( state.dom1 ); + public Xpp3Dom benchmarkClone(AdditionState state) { + return new Xpp3Dom(state.dom1); } /** @@ -80,9 +78,8 @@ public Xpp3Dom benchmarkClone(AdditionState state) * @param state a {@link org.codehaus.plexus.util.xml.Xpp3DomPerfTest.AdditionState} object. */ @Benchmark - public void benchmarkMerge(AdditionState state) - { - Xpp3Dom.mergeXpp3Dom( state.dom1, state.dom2 ); + public void benchmarkMerge(AdditionState state) { + Xpp3Dom.mergeXpp3Dom(state.dom1, state.dom2); } /** @@ -91,14 +88,12 @@ public void benchmarkMerge(AdditionState state) * @param args a {@link java.lang.String} object. * @throws org.openjdk.jmh.runner.RunnerException if any. */ - public static void main( String... args ) - throws RunnerException - { + public static void main(String... args) throws RunnerException { Options opts = new OptionsBuilder() - .measurementIterations( 3 ) - .measurementTime( TimeValue.milliseconds( 3000 ) ) - .forks( 1 ) + .measurementIterations(3) + .measurementTime(TimeValue.milliseconds(3000)) + .forks(1) .build(); - new Runner( opts ).run(); + new Runner(opts).run(); } } 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 6a1b7078..c4f21029 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomTest.java @@ -16,13 +16,6 @@ * 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.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; @@ -31,6 +24,13 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.junit.Test; +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; + /** *

      Xpp3DomTest class.

      * @@ -38,185 +38,172 @@ * @version $Id: $Id * @since 3.4.0 */ -public class Xpp3DomTest -{ +public class Xpp3DomTest { /** *

      testShouldPerformAppendAtFirstSubElementLevel.

      */ @Test - public void testShouldPerformAppendAtFirstSubElementLevel() - { + 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 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" ); + Xpp3Dom t1s1 = new Xpp3Dom("topsub1"); + t1s1.setValue("t1s1Value"); + t1s1.setInputLocation("t1s1"); - t1.addChild( t1s1 ); + t1.addChild(t1s1); // create the recessive DOM - Xpp3Dom t2 = new Xpp3Dom( "top" ); - t2.setInputLocation( "t2top" ); + Xpp3Dom t2 = new Xpp3Dom("top"); + t2.setInputLocation("t2top"); - Xpp3Dom t2s1 = new Xpp3Dom( "topsub1" ); - t2s1.setValue( "t2s1Value" ); - t2s1.setInputLocation( "t2s1" ); + Xpp3Dom t2s1 = new Xpp3Dom("topsub1"); + t2s1.setValue("t2s1Value"); + t2s1.setInputLocation("t2s1"); - t2.addChild( t2s1 ); + t2.addChild(t2s1); // merge and check results. - Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( t1, t2 ); + 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(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() ); + assertEquals("t1top", result.getInputLocation()); + assertEquals("t2s1", result.getChildren("topsub1")[0].getInputLocation()); + assertEquals("t1s1", result.getChildren("topsub1")[1].getInputLocation()); } /** *

      testShouldOverrideAppendAndDeepMerge.

      */ @Test - public void testShouldOverrideAppendAndDeepMerge() - { + 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 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" ); + Xpp3Dom t1s1 = new Xpp3Dom("topsub1"); + t1s1.setValue("t1s1Value"); + t1s1.setInputLocation("t1s1"); - t1.addChild( t1s1 ); + t1.addChild(t1s1); // create the recessive DOM - Xpp3Dom t2 = new Xpp3Dom( "top" ); - t2.setInputLocation( "t2top" ); + Xpp3Dom t2 = new Xpp3Dom("top"); + t2.setInputLocation("t2top"); - Xpp3Dom t2s1 = new Xpp3Dom( "topsub1" ); - t2s1.setValue( "t2s1Value" ); - t2s1.setInputLocation( "t2s1" ); + Xpp3Dom t2s1 = new Xpp3Dom("topsub1"); + t2s1.setValue("t2s1Value"); + t2s1.setInputLocation("t2s1"); - t2.addChild( t2s1 ); + t2.addChild(t2s1); // merge and check results. - Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( t1, t2, Boolean.TRUE ); + Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(t1, t2, Boolean.TRUE); - assertEquals( 1, result.getChildren( "topsub1" ).length ); - assertEquals( "t1s1Value", result.getChildren( "topsub1" )[0].getValue() ); + assertEquals(1, result.getChildren("topsub1").length); + assertEquals("t1s1Value", result.getChildren("topsub1")[0].getValue()); - assertEquals( "t1top", result.getInputLocation() ); - assertEquals( "t1s1", result.getChildren( "topsub1" )[0].getInputLocation() ); + assertEquals("t1top", result.getInputLocation()); + assertEquals("t1s1", result.getChildren("topsub1")[0].getInputLocation()); } /** *

      testShouldPerformSelfOverrideAtTopLevel.

      */ @Test - public void testShouldPerformSelfOverrideAtTopLevel() - { + public void testShouldPerformSelfOverrideAtTopLevel() { // create the dominant DOM - Xpp3Dom t1 = new Xpp3Dom( "top" ); - t1.setAttribute( "attr", "value" ); - t1.setInputLocation( "t1top" ); + Xpp3Dom t1 = new Xpp3Dom("top"); + t1.setAttribute("attr", "value"); + t1.setInputLocation("t1top"); - t1.setAttribute( Xpp3Dom.SELF_COMBINATION_MODE_ATTRIBUTE, Xpp3Dom.SELF_COMBINATION_OVERRIDE ); + t1.setAttribute(Xpp3Dom.SELF_COMBINATION_MODE_ATTRIBUTE, Xpp3Dom.SELF_COMBINATION_OVERRIDE); // create the recessive DOM - Xpp3Dom t2 = new Xpp3Dom( "top" ); - t2.setAttribute( "attr2", "value2" ); - t2.setValue( "t2Value" ); - t2.setInputLocation( "t2top" ); + 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 ); + Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(t1, t2); - assertEquals( 2, result.getAttributeNames().length ); - assertNull( result.getValue() ); - assertEquals( "t1top", result.getInputLocation() ); + assertEquals(2, result.getAttributeNames().length); + assertNull(result.getValue()); + assertEquals("t1top", result.getInputLocation()); } /** *

      testShouldMergeValuesAtTopLevelByDefault.

      */ @Test - public void testShouldMergeValuesAtTopLevelByDefault() - { + public void testShouldMergeValuesAtTopLevelByDefault() { // create the dominant DOM - Xpp3Dom t1 = new Xpp3Dom( "top" ); - t1.setAttribute( "attr", "value" ); - t1.setInputLocation( "t1top" ); + 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" ); + 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 ); + Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(t1, t2); // this is still 2, since we're not using the merge-control attribute. - assertEquals( 2, result.getAttributeNames().length ); + assertEquals(2, result.getAttributeNames().length); - assertEquals( result.getValue(), t2.getValue() ); - assertEquals( "t2top", result.getInputLocation() ); + assertEquals(result.getValue(), t2.getValue()); + assertEquals("t2top", result.getInputLocation()); } /** *

      testShouldMergeValuesAtTopLevel.

      */ @Test - public void testShouldMergeValuesAtTopLevel() - { + public void testShouldMergeValuesAtTopLevel() { // create the dominant DOM - Xpp3Dom t1 = new Xpp3Dom( "top" ); - t1.setAttribute( "attr", "value" ); + Xpp3Dom t1 = new Xpp3Dom("top"); + t1.setAttribute("attr", "value"); - t1.setAttribute( Xpp3Dom.SELF_COMBINATION_MODE_ATTRIBUTE, Xpp3Dom.SELF_COMBINATION_MERGE ); + t1.setAttribute(Xpp3Dom.SELF_COMBINATION_MODE_ATTRIBUTE, Xpp3Dom.SELF_COMBINATION_MERGE); // create the recessive DOM - Xpp3Dom t2 = new Xpp3Dom( "top" ); - t2.setAttribute( "attr2", "value2" ); - t2.setValue( "t2Value" ); + Xpp3Dom t2 = new Xpp3Dom("top"); + t2.setAttribute("attr2", "value2"); + t2.setValue("t2Value"); // merge and check results. - Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( t1, t2 ); + Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(t1, t2); - assertEquals( 3, result.getAttributeNames().length ); - assertEquals( result.getValue(), t2.getValue() ); + assertEquals(3, result.getAttributeNames().length); + assertEquals(result.getValue(), t2.getValue()); } /** *

      testNullAttributeNameOrValue.

      */ @Test - public void testNullAttributeNameOrValue() - { - Xpp3Dom t1 = new Xpp3Dom( "top" ); - try - { - t1.setAttribute( "attr", null ); - fail( "null attribute values shouldn't be allowed" ); - } - catch ( NullPointerException e ) - { + public void testNullAttributeNameOrValue() { + Xpp3Dom t1 = new Xpp3Dom("top"); + try { + t1.setAttribute("attr", null); + fail("null attribute values shouldn't be allowed"); + } catch (NullPointerException e) { } t1.toString(); - try - { - t1.setAttribute( null, "value" ); - fail( "null attribute names shouldn't be allowed" ); - } - catch ( NullPointerException e ) - { + try { + t1.setAttribute(null, "value"); + fail("null attribute names shouldn't be allowed"); + } catch (NullPointerException e) { } t1.toString(); } @@ -225,13 +212,12 @@ public void testNullAttributeNameOrValue() *

      testEquals.

      */ @Test - public void testEquals() - { - Xpp3Dom dom = new Xpp3Dom( "top" ); + public void testEquals() { + Xpp3Dom dom = new Xpp3Dom("top"); - assertEquals( dom, dom ); - assertFalse( dom.equals( null ) ); - assertFalse( dom.equals( new Xpp3Dom( (String) null ) ) ); + assertEquals(dom, dom); + assertFalse(dom.equals(null)); + assertFalse(dom.equals(new Xpp3Dom((String) null))); } /** @@ -241,29 +227,24 @@ public void testEquals() * @throws java.io.IOException if any. */ @Test - public void testEqualsIsNullSafe() - throws XmlPullParserException, IOException - { + public void testEqualsIsNullSafe() throws XmlPullParserException, IOException { String testDom = "onetwo"; - Xpp3Dom dom = Xpp3DomBuilder.build( new StringReader( testDom ) ); - Xpp3Dom dom2 = Xpp3DomBuilder.build( new StringReader( testDom ) ); + Xpp3Dom dom = Xpp3DomBuilder.build(new StringReader(testDom)); + Xpp3Dom dom2 = Xpp3DomBuilder.build(new StringReader(testDom)); - try - { + try { dom2.attributes = new HashMap(); - dom2.attributes.put( "nullValue", null ); - dom2.attributes.put( null, "nullKey" ); + dom2.attributes.put("nullValue", null); + dom2.attributes.put(null, "nullKey"); dom2.childList.clear(); - dom2.childList.add( null ); + dom2.childList.add(null); - assertFalse( dom.equals( dom2 ) ); - assertFalse( dom2.equals( dom ) ); + assertFalse(dom.equals(dom2)); + assertFalse(dom2.equals(dom)); - } - catch ( NullPointerException ex ) - { + } catch (NullPointerException ex) { ex.printStackTrace(); - fail( "\nNullPointerExceptions should not be thrown." ); + fail("\nNullPointerExceptions should not be thrown."); } } @@ -274,25 +255,23 @@ public void testEqualsIsNullSafe() * @throws java.io.IOException if any. */ @Test - public void testShouldOverwritePluginConfigurationSubItemsByDefault() - throws XmlPullParserException, IOException - { + public void testShouldOverwritePluginConfigurationSubItemsByDefault() throws XmlPullParserException, IOException { String parentConfigStr = "onetwo"; Xpp3Dom parentConfig = - Xpp3DomBuilder.build( new StringReader( parentConfigStr ), new FixedInputLocationBuilder( "parent" ) ); + Xpp3DomBuilder.build(new StringReader(parentConfigStr), new FixedInputLocationBuilder("parent")); String childConfigStr = "three"; Xpp3Dom childConfig = - Xpp3DomBuilder.build( new StringReader( childConfigStr ), new FixedInputLocationBuilder( "child" ) ); + Xpp3DomBuilder.build(new StringReader(childConfigStr), new FixedInputLocationBuilder("child")); - Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( childConfig, parentConfig ); - Xpp3Dom items = result.getChild( "items" ); + Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(childConfig, parentConfig); + Xpp3Dom items = result.getChild("items"); - assertEquals( 1, items.getChildCount() ); + assertEquals(1, items.getChildCount()); - Xpp3Dom item = items.getChild( 0 ); - assertEquals( "three", item.getValue() ); - assertEquals( "child", item.getInputLocation() ); + Xpp3Dom item = items.getChild(0); + assertEquals("three", item.getValue()); + assertEquals("child", item.getInputLocation()); } /** @@ -303,30 +282,29 @@ public void testShouldOverwritePluginConfigurationSubItemsByDefault() */ @Test public void testShouldMergePluginConfigurationSubItemsWithMergeAttributeSet() - throws XmlPullParserException, IOException - { + throws XmlPullParserException, IOException { String parentConfigStr = "onetwo"; Xpp3Dom parentConfig = - Xpp3DomBuilder.build( new StringReader( parentConfigStr ), new FixedInputLocationBuilder( "parent" ) ); + Xpp3DomBuilder.build(new StringReader(parentConfigStr), new FixedInputLocationBuilder("parent")); String childConfigStr = - "three"; + "three"; Xpp3Dom childConfig = - Xpp3DomBuilder.build( new StringReader( childConfigStr ), new FixedInputLocationBuilder( "child" ) ); + Xpp3DomBuilder.build(new StringReader(childConfigStr), new FixedInputLocationBuilder("child")); - Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( childConfig, parentConfig ); - Xpp3Dom items = result.getChild( "items" ); + Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(childConfig, parentConfig); + Xpp3Dom items = result.getChild("items"); - assertEquals( 3, items.getChildCount() ); + assertEquals(3, items.getChildCount()); 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() ); + 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()); } /** @@ -335,21 +313,19 @@ public void testShouldMergePluginConfigurationSubItemsWithMergeAttributeSet() * @throws java.lang.Exception if any. */ @Test - public void testShouldNotChangeUponMergeWithItselfWhenFirstOrLastSubItemIsEmpty() - throws Exception - { + public void testShouldNotChangeUponMergeWithItselfWhenFirstOrLastSubItemIsEmpty() throws Exception { String configStr = "test"; - Xpp3Dom dominantConfig = Xpp3DomBuilder.build( new StringReader( configStr ) ); - Xpp3Dom recessiveConfig = Xpp3DomBuilder.build( new StringReader( configStr ) ); + Xpp3Dom dominantConfig = Xpp3DomBuilder.build(new StringReader(configStr)); + Xpp3Dom recessiveConfig = Xpp3DomBuilder.build(new StringReader(configStr)); - Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( dominantConfig, recessiveConfig ); - Xpp3Dom items = result.getChild( "items" ); + Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(dominantConfig, recessiveConfig); + Xpp3Dom items = result.getChild("items"); - assertEquals( 3, items.getChildCount() ); + assertEquals(3, items.getChildCount()); - assertEquals( null, items.getChild( 0 ).getValue() ); - assertEquals( "test", items.getChild( 1 ).getValue() ); - assertEquals( null, items.getChild( 2 ).getValue() ); + assertEquals(null, items.getChild(0).getValue()); + assertEquals("test", items.getChild(1).getValue()); + assertEquals(null, items.getChild(2).getValue()); } /** @@ -358,21 +334,19 @@ public void testShouldNotChangeUponMergeWithItselfWhenFirstOrLastSubItemIsEmpty( * @throws java.lang.Exception if any. */ @Test - public void testShouldCopyRecessiveChildrenNotPresentInTarget() - throws Exception - { + public void testShouldCopyRecessiveChildrenNotPresentInTarget() throws Exception { String dominantStr = "x"; String recessiveStr = "y"; - Xpp3Dom dominantConfig = Xpp3DomBuilder.build( new StringReader( dominantStr ) ); - Xpp3Dom recessiveConfig = Xpp3DomBuilder.build( new StringReader( recessiveStr ) ); + Xpp3Dom dominantConfig = Xpp3DomBuilder.build(new StringReader(dominantStr)); + Xpp3Dom recessiveConfig = Xpp3DomBuilder.build(new StringReader(recessiveStr)); - Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( dominantConfig, recessiveConfig ); + Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(dominantConfig, recessiveConfig); - assertEquals( 2, result.getChildCount() ); + assertEquals(2, result.getChildCount()); - assertEquals( "x", result.getChild( "foo" ).getValue() ); - assertEquals( "y", result.getChild( "bar" ).getValue() ); - assertNotSame( result.getChild( "bar" ), recessiveConfig.getChild( "bar" ) ); + assertEquals("x", result.getChild("foo").getValue()); + assertEquals("y", result.getChild("bar").getValue()); + assertNotSame(result.getChild("bar"), recessiveConfig.getChild("bar")); } /** @@ -382,13 +356,11 @@ public void testShouldCopyRecessiveChildrenNotPresentInTarget() * @throws org.codehaus.plexus.util.xml.pull.XmlPullParserException if any. */ @Test - public void testDupeChildren() - throws IOException, XmlPullParserException - { + public void testDupeChildren() throws IOException, XmlPullParserException { String dupes = "xy"; - Xpp3Dom dom = Xpp3DomBuilder.build( new StringReader( dupes ) ); - assertNotNull( dom ); - assertEquals( "y", dom.getChild( "foo" ).getValue() ); + Xpp3Dom dom = Xpp3DomBuilder.build(new StringReader(dupes)); + assertNotNull(dom); + assertEquals("y", dom.getChild("foo").getValue()); } /** @@ -397,18 +369,16 @@ public void testDupeChildren() * @throws java.lang.Exception if any. */ @Test - public void testShouldRemoveEntireElementWithAttributesAndChildren() - throws Exception - { + public void testShouldRemoveEntireElementWithAttributesAndChildren() throws Exception { String dominantStr = ""; String recessiveStr = "parameter"; - Xpp3Dom dominantConfig = Xpp3DomBuilder.build( new StringReader( dominantStr ) ); - Xpp3Dom recessiveConfig = Xpp3DomBuilder.build( new StringReader( recessiveStr ) ); + Xpp3Dom dominantConfig = Xpp3DomBuilder.build(new StringReader(dominantStr)); + Xpp3Dom recessiveConfig = Xpp3DomBuilder.build(new StringReader(recessiveStr)); - Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( dominantConfig, recessiveConfig ); + Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(dominantConfig, recessiveConfig); - assertEquals( 0, result.getChildCount() ); - assertEquals( "config", result.getName() ); + assertEquals(0, result.getChildCount()); + assertEquals("config", result.getName()); } /** @@ -417,32 +387,26 @@ public void testShouldRemoveEntireElementWithAttributesAndChildren() * @throws java.lang.Exception if any. */ @Test - public void testShouldRemoveDoNotRemoveTagWhenSwappedInputDOMs() - throws Exception - { + public void testShouldRemoveDoNotRemoveTagWhenSwappedInputDOMs() throws Exception { String dominantStr = ""; String recessiveStr = "parameter"; - Xpp3Dom dominantConfig = Xpp3DomBuilder.build( new StringReader( dominantStr ) ); - Xpp3Dom recessiveConfig = Xpp3DomBuilder.build( new StringReader( recessiveStr ) ); + Xpp3Dom dominantConfig = Xpp3DomBuilder.build(new StringReader(dominantStr)); + Xpp3Dom recessiveConfig = Xpp3DomBuilder.build(new StringReader(recessiveStr)); // same DOMs as testShouldRemoveEntireElementWithAttributesAndChildren(), swapping dominant <--> recessive - Xpp3Dom result = Xpp3Dom.mergeXpp3Dom( recessiveConfig, dominantConfig ); + Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(recessiveConfig, dominantConfig); - assertEquals( recessiveConfig.toString(), result.toString() ); + assertEquals(recessiveConfig.toString(), result.toString()); } - private static class FixedInputLocationBuilder - implements Xpp3DomBuilder.InputLocationBuilder - { + private static class FixedInputLocationBuilder implements Xpp3DomBuilder.InputLocationBuilder { private final Object location; - public FixedInputLocationBuilder( Object location ) - { + public FixedInputLocationBuilder(Object location) { this.location = location; } - public Object toInputLocation( XmlPullParser parser ) - { + 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 9e244f19..ea21509a 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomUtilsTest.java @@ -16,8 +16,6 @@ * limitations under the License. */ -import static org.junit.Assert.assertEquals; - import java.io.IOException; import java.io.StringReader; @@ -25,6 +23,8 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** *

      Xpp3DomUtilsTest class.

      * @@ -32,46 +32,51 @@ * @version $Id: $Id * @since 3.4.0 */ -public class Xpp3DomUtilsTest -{ +public class Xpp3DomUtilsTest { /** *

      testCombineId.

      * * @throws java.lang.Exception if any. */ @Test - public void testCombineId() - throws Exception - { + public void testCombineId() throws Exception { String lhs = "" + "LHS-ONLYLHS" - + "TOOVERWRITELHS" + ""; + + "TOOVERWRITELHS" + + ""; String rhs = "" + "RHS-ONLYRHS" - + "TOOVERWRITERHS" + ""; - - 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 ); - - 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() ); + + "TOOVERWRITERHS" + + ""; + + 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); + + 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()); } /** @@ -80,38 +85,44 @@ public void testCombineId() * @throws java.lang.Exception if any. */ @Test - public void testCombineKeys() - throws Exception - { - String lhs = "" + "LHS-ONLYLHS" - + "TOOVERWRITELHS" + ""; - - String rhs = "" + "RHS-ONLYRHS" - + "TOOVERWRITERHS" + ""; - - 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 ); - - 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() ); + public void testCombineKeys() throws Exception { + String lhs = "" + + "LHS-ONLYLHS" + + "TOOVERWRITELHS" + ""; + + String rhs = "" + + "RHS-ONLYRHS" + + "TOOVERWRITERHS" + ""; + + 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); + + 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()); } @Test @@ -120,48 +131,42 @@ public void testPreserveDominantBlankValue() throws XmlPullParserException, IOEx String rhs = "recessive"; - Xpp3Dom leftDom = Xpp3DomBuilder.build( new StringReader( lhs ), new FixedInputLocationBuilder( "left" ) ); - Xpp3Dom rightDom = Xpp3DomBuilder.build( new StringReader( rhs ), new FixedInputLocationBuilder( "right" ) ); + 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( " ", mergeResult.getValue() ); + Xpp3Dom mergeResult = Xpp3DomUtils.mergeXpp3Dom(leftDom, rightDom, true); + assertEquals(" ", mergeResult.getValue()); } @Test - public void testPreserveDominantEmptyNode() throws XmlPullParserException, IOException - { + public void testPreserveDominantEmptyNode() throws XmlPullParserException, IOException { String lhs = ""; String rhs = "recessive"; - Xpp3Dom leftDom = Xpp3DomBuilder.build( new StringReader( lhs ), new FixedInputLocationBuilder( "left" ) ); - Xpp3Dom rightDom = Xpp3DomBuilder.build( new StringReader( rhs ), new FixedInputLocationBuilder( "right" ) ); + 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( "", mergeResult.getValue() ); + Xpp3Dom mergeResult = Xpp3DomUtils.mergeXpp3Dom(leftDom, rightDom, true); + assertEquals("", mergeResult.getValue()); } @Test - public void testIsNotEmptyNegatesIsEmpty() - { - assertEquals( !Xpp3DomUtils.isEmpty( null ), Xpp3DomUtils.isNotEmpty( null ) ); - assertEquals( !Xpp3DomUtils.isEmpty( "" ), Xpp3DomUtils.isNotEmpty( "" ) ); - assertEquals( !Xpp3DomUtils.isEmpty( " " ), Xpp3DomUtils.isNotEmpty( " " ) ); - assertEquals( !Xpp3DomUtils.isEmpty( "someValue" ), Xpp3DomUtils.isNotEmpty( "someValue" ) ); + public void testIsNotEmptyNegatesIsEmpty() { + assertEquals(!Xpp3DomUtils.isEmpty(null), Xpp3DomUtils.isNotEmpty(null)); + assertEquals(!Xpp3DomUtils.isEmpty(""), Xpp3DomUtils.isNotEmpty("")); + assertEquals(!Xpp3DomUtils.isEmpty(" "), Xpp3DomUtils.isNotEmpty(" ")); + assertEquals(!Xpp3DomUtils.isEmpty("someValue"), Xpp3DomUtils.isNotEmpty("someValue")); } - private static class FixedInputLocationBuilder - implements Xpp3DomBuilder.InputLocationBuilder - { + private static class FixedInputLocationBuilder implements Xpp3DomBuilder.InputLocationBuilder { private final Object location; - public FixedInputLocationBuilder( Object location ) - { + public FixedInputLocationBuilder(Object location) { this.location = location; } - public Object toInputLocation( XmlPullParser parser ) - { + 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 93c00a7d..55853d0b 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomWriterTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/Xpp3DomWriterTest.java @@ -16,12 +16,12 @@ * limitations under the License. */ -import static org.junit.Assert.assertEquals; - import java.io.StringWriter; import org.junit.Test; +import static org.junit.Assert.assertEquals; + /** *

      Xpp3DomWriterTest class.

      * @@ -29,103 +29,95 @@ * @version $Id: $Id * @since 3.4.0 */ -public class Xpp3DomWriterTest -{ - private static final String LS = System.getProperty( "line.separator" ); +public class Xpp3DomWriterTest { + private static final String LS = System.getProperty("line.separator"); /** *

      testWriter.

      */ @Test - public void testWriter() - { + public void testWriter() { StringWriter writer = new StringWriter(); - Xpp3DomWriter.write( writer, createXpp3Dom() ); + Xpp3DomWriter.write(writer, createXpp3Dom()); - assertEquals( "Check if output matches", createExpectedXML( true ), writer.toString() ); + assertEquals("Check if output matches", createExpectedXML(true), writer.toString()); } /** *

      testWriterNoEscape.

      */ @Test - public void testWriterNoEscape() - { + public void testWriterNoEscape() { StringWriter writer = new StringWriter(); - Xpp3DomWriter.write( new PrettyPrintXMLWriter( writer ), createXpp3Dom(), false ); + Xpp3DomWriter.write(new PrettyPrintXMLWriter(writer), createXpp3Dom(), false); - assertEquals( "Check if output matches", createExpectedXML( false ), writer.toString() ); + assertEquals("Check if output matches", createExpectedXML(false), writer.toString()); } - private String createExpectedXML( boolean escape ) - { + private String createExpectedXML(boolean escape) { StringBuilder buf = new StringBuilder(); - buf.append( "" ); - buf.append( LS ); - buf.append( " element1" ); - buf.append( LS ); - buf.append( " " ); - buf.append( LS ); - buf.append( " element3" ); - buf.append( LS ); - buf.append( " " ); - buf.append( LS ); - buf.append( " " ); - buf.append( LS ); - buf.append( " " ); - buf.append( LS ); - buf.append( " " ); - buf.append( LS ); - if ( escape ) - { - buf.append( " element7" ).append( LS ).append( "&"'<>" ); - } - else - { - buf.append( " element7" ).append( LS ).append( "&\"\'<>" ); + buf.append(""); + buf.append(LS); + buf.append(" element1"); + buf.append(LS); + buf.append(" "); + buf.append(LS); + buf.append(" element3"); + buf.append(LS); + buf.append(" "); + buf.append(LS); + buf.append(" "); + buf.append(LS); + buf.append(" "); + buf.append(LS); + buf.append(" "); + buf.append(LS); + if (escape) { + buf.append(" element7").append(LS).append("&"'<>"); + } else { + buf.append(" element7").append(LS).append("&\"\'<>"); } - buf.append( LS ); - buf.append( " " ); - buf.append( LS ); - buf.append( "" ); + buf.append(LS); + buf.append(" "); + buf.append(LS); + buf.append(""); return buf.toString(); } - private Xpp3Dom createXpp3Dom() - { - Xpp3Dom dom = new Xpp3Dom( "root" ); + private Xpp3Dom createXpp3Dom() { + Xpp3Dom dom = new Xpp3Dom("root"); - Xpp3Dom el1 = new Xpp3Dom( "el1" ); - el1.setValue( "element1" ); - dom.addChild( el1 ); + Xpp3Dom el1 = new Xpp3Dom("el1"); + el1.setValue("element1"); + dom.addChild(el1); - Xpp3Dom el2 = new Xpp3Dom( "el2" ); - el2.setAttribute( "att2", "attribute2\nnextline" ); - dom.addChild( el2 ); + Xpp3Dom el2 = new Xpp3Dom("el2"); + el2.setAttribute("att2", "attribute2\nnextline"); + dom.addChild(el2); - Xpp3Dom el3 = new Xpp3Dom( "el3" ); - el3.setAttribute( "att3", "attribute3" ); - el3.setValue( "element3" ); - el2.addChild( el3 ); + Xpp3Dom el3 = new Xpp3Dom("el3"); + el3.setAttribute("att3", "attribute3"); + el3.setValue("element3"); + el2.addChild(el3); - Xpp3Dom el4 = new Xpp3Dom( "el4" ); - el4.setValue( "" ); - dom.addChild( el4 ); + Xpp3Dom el4 = new Xpp3Dom("el4"); + el4.setValue(""); + dom.addChild(el4); - Xpp3Dom el5 = new Xpp3Dom( "el5" ); - dom.addChild( el5 ); + Xpp3Dom el5 = new Xpp3Dom("el5"); + dom.addChild(el5); // test escaping - Xpp3Dom el6 = new Xpp3Dom( "el6" ); - el6.setAttribute( "att6", "attribute6\n&\"'<>" ); - dom.addChild( el6 ); + Xpp3Dom el6 = new Xpp3Dom("el6"); + el6.setAttribute("att6", "attribute6\n&\"'<>"); + dom.addChild(el6); - Xpp3Dom el7 = new Xpp3Dom( "el7" ); - el7.setValue( "element7\n&\"\'<>" ); - el6.addChild( el7 ); + Xpp3Dom el7 = new Xpp3Dom("el7"); + el7.setValue("element7\n&\"\'<>"); + el6.addChild(el7); return dom; } diff --git a/src/test/java/org/codehaus/plexus/util/xml/pull/IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production24_Test.java b/src/test/java/org/codehaus/plexus/util/xml/pull/IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production24_Test.java index 4b1f5eb5..becde36c 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/pull/IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production24_Test.java +++ b/src/test/java/org/codehaus/plexus/util/xml/pull/IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production24_Test.java @@ -1,10 +1,6 @@ package org.codehaus.plexus.util.xml.pull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.File; -import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; @@ -12,6 +8,9 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** * Test class that execute a particular set of tests associated to a TESCASES tag from the XML W3C Conformance Tests. * TESCASES PROFILE:
      IBM XML Conformance Test Suite - Production 24
      @@ -21,10 +20,10 @@ * @version $Id: $Id * @since 3.4.0 */ -public class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production24_Test -{ +public +class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production24_Test { - final static File testResourcesDir = new File( "src/test/resources/", "xmlconf/ibm/" ); + static final File testResourcesDir = new File("src/test/resources/", "xmlconf/ibm/"); MXParser parser; @@ -32,8 +31,7 @@ public class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMX *

      setUp.

      */ @Before - public void setUp() - { + public void setUp() { parser = new MXParser(); } @@ -47,228 +45,190 @@ public void setUp() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P24_ibm24n01xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P24/ibm24n01.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P24_ibm24n01xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P24/ibm24n01.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests VersionInfo with a required field missing. The VersionNum is missing in the VersionInfo in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected apostrophe (') or quotation mark (\") after version and not ?" ) ); + fail( + "Tests VersionInfo with a required field missing. The VersionNum is missing in the VersionInfo in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue( + e.getMessage().contains("expected apostrophe (') or quotation mark (\") after version and not ?")); } } - /** - * Test ID:
      ibm-not-wf-P24-ibm24n02.xml
      - * Test URI:
      not-wf/P24/ibm24n02.xml
      - * Comment:
      Tests VersionInfo with a required field missing. The white space is     missing between the key word "xml" and the VersionInfo in the XMLDecl.
      - * Sections:
      2.8
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P24_ibm24n02xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P24/ibm24n02.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests VersionInfo with a required field missing. The white space is missing between the key word \"xml\" and the VersionInfo in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected v in version and not ?" ) ); - } - } - - /** - * Test ID:
      ibm-not-wf-P24-ibm24n03.xml
      - * Test URI:
      not-wf/P24/ibm24n03.xml
      - * Comment:
      Tests VersionInfo with a required field missing. The "="      (equal sign) is missing between the key word "version" and the VersionNum.
      - * Sections:
      2.8
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P24_ibm24n03xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P24/ibm24n03.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests VersionInfo with a required field missing. The \"=\" (equal sign) is missing between the key word \"version\" and the VersionNum." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected equals sign (=) after version and not \\'" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P24-ibm24n02.xml
      + * Test URI:
      not-wf/P24/ibm24n02.xml
      + * Comment:
      Tests VersionInfo with a required field missing. The white space is     missing between the key word "xml" and the VersionInfo in the XMLDecl.
      + * Sections:
      2.8
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P24_ibm24n02xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P24/ibm24n02.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests VersionInfo with a required field missing. The white space is missing between the key word \"xml\" and the VersionInfo in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected v in version and not ?")); + } + } - /** - * Test ID:
      ibm-not-wf-P24-ibm24n04.xml
      - * Test URI:
      not-wf/P24/ibm24n04.xml
      - * Comment:
      Tests VersionInfo with wrong field ordering. The VersionNum     occurs before "=" and "version".
      - * Sections:
      2.8
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P24_ibm24n04xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P24/ibm24n04.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests VersionInfo with wrong field ordering. The VersionNum occurs before \"=\" and \"version\"." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected v in version and not \\'" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P24-ibm24n03.xml
      + * Test URI:
      not-wf/P24/ibm24n03.xml
      + * Comment:
      Tests VersionInfo with a required field missing. The "="      (equal sign) is missing between the key word "version" and the VersionNum.
      + * Sections:
      2.8
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P24_ibm24n03xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P24/ibm24n03.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests VersionInfo with a required field missing. The \"=\" (equal sign) is missing between the key word \"version\" and the VersionNum."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected equals sign (=) after version and not \\'")); + } + } - /** - * Test ID:
      ibm-not-wf-P24-ibm24n05.xml
      - * Test URI:
      not-wf/P24/ibm24n05.xml
      - * Comment:
      Tests VersionInfo with wrong field ordering. The "=" occurs     after "version" and the VersionNum.
      - * Sections:
      2.8
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P24_ibm24n05xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P24/ibm24n05.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests VersionInfo with wrong field ordering. The \"=\" occurs after \"version\" and the VersionNum." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected equals sign (=) after version and not \\'" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P24-ibm24n04.xml
      + * Test URI:
      not-wf/P24/ibm24n04.xml
      + * Comment:
      Tests VersionInfo with wrong field ordering. The VersionNum     occurs before "=" and "version".
      + * Sections:
      2.8
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P24_ibm24n04xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P24/ibm24n04.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests VersionInfo with wrong field ordering. The VersionNum occurs before \"=\" and \"version\"."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected v in version and not \\'")); + } + } - /** - * Test ID:
      ibm-not-wf-P24-ibm24n06.xml
      - * Test URI:
      not-wf/P24/ibm24n06.xml
      - * Comment:
      Tests VersionInfo with the wrong key word "Version".
      - * Sections:
      2.8
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P24_ibm24n06xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P24/ibm24n06.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests VersionInfo with the wrong key word \"Version\"." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected v in version and not V" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P24-ibm24n05.xml
      + * Test URI:
      not-wf/P24/ibm24n05.xml
      + * Comment:
      Tests VersionInfo with wrong field ordering. The "=" occurs     after "version" and the VersionNum.
      + * Sections:
      2.8
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P24_ibm24n05xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P24/ibm24n05.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests VersionInfo with wrong field ordering. The \"=\" occurs after \"version\" and the VersionNum."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected equals sign (=) after version and not \\'")); + } + } - /** - * Test ID:
      ibm-not-wf-P24-ibm24n07.xml
      - * Test URI:
      not-wf/P24/ibm24n07.xml
      - * Comment:
      Tests VersionInfo with the wrong key word "versioN".
      - * Sections:
      2.8
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P24_ibm24n07xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P24/ibm24n07.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests VersionInfo with the wrong key word \"versioN\"." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected n in version and not N" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P24-ibm24n06.xml
      + * Test URI:
      not-wf/P24/ibm24n06.xml
      + * Comment:
      Tests VersionInfo with the wrong key word "Version".
      + * Sections:
      2.8
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P24_ibm24n06xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P24/ibm24n06.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail("Tests VersionInfo with the wrong key word \"Version\"."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected v in version and not V")); + } + } - /** - * Test ID:
      ibm-not-wf-P24-ibm24n08.xml
      - * Test URI:
      not-wf/P24/ibm24n08.xml
      - * Comment:
      Tests VersionInfo with mismatched quotes around the VersionNum.      version = '1.0" is used as the VersionInfo.
      - * Sections:
      2.8
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P24_ibm24n08xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P24/ibm24n08.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests VersionInfo with mismatched quotes around the VersionNum. version = '1.0\" is used as the VersionInfo." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "ibm-not-wf-P24-ibm24n07.xml + * Test URI:
      not-wf/P24/ibm24n07.xml
      + * Comment:
      Tests VersionInfo with the wrong key word "versioN".
      + * Sections:
      2.8
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P24_ibm24n07xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P24/ibm24n07.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail("Tests VersionInfo with the wrong key word \"versioN\"."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected n in version and not N")); + } + } - /** - * Test ID:
      ibm-not-wf-P24-ibm24n09.xml
      - * Test URI:
      not-wf/P24/ibm24n09.xml
      - * Comment:
      Tests VersionInfo with mismatched quotes around the VersionNum.      The closing bracket for the VersionNum is missing.
      - * Sections:
      2.8
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P24_ibm24n09xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P24/ibm24n09.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests VersionInfo with mismatched quotes around the VersionNum. The closing bracket for the VersionNum is missing." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "ibm-not-wf-P24-ibm24n08.xml + * Test URI:
      not-wf/P24/ibm24n08.xml
      + * Comment:
      Tests VersionInfo with mismatched quotes around the VersionNum.      version = '1.0" is used as the VersionInfo.
      + * Sections:
      2.8
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P24_ibm24n08xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P24/ibm24n08.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests VersionInfo with mismatched quotes around the VersionNum. version = '1.0\" is used as the VersionInfo."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("ibm-not-wf-P24-ibm24n09.xml + * Test URI:
      not-wf/P24/ibm24n09.xml
      + * Comment:
      Tests VersionInfo with mismatched quotes around the VersionNum.      The closing bracket for the VersionNum is missing.
      + * Sections:
      2.8
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P24_ibm24n09xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P24/ibm24n09.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests VersionInfo with mismatched quotes around the VersionNum. The closing bracket for the VersionNum is missing."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("IBM XML Conformance Test Suite - Production 2 @@ -27,9 +27,10 @@ * @version $Id: $Id * @since 3.4.0 */ -public class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production2_Test { +public +class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production2_Test { - final static File testResourcesDir = new File("src/test/resources/", "xmlconf/ibm/"); + static final File testResourcesDir = new File("src/test/resources/", "xmlconf/ibm/"); MXParser parser; @@ -51,23 +52,17 @@ public void setUp() { * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n01xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n01.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n01xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n01.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x00" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x0 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x00"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x0 found in comment")); } } - /** * Test ID:
      ibm-not-wf-P02-ibm02n02.xml
      * Test URI:
      not-wf/P02/ibm02n02.xml
      @@ -78,19 +73,14 @@ public void testibm_not_wf_P02_ibm02n01xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n02xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n02.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n02xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n02.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x01" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x1 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x01"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x1 found in comment")); } } @@ -104,19 +94,14 @@ public void testibm_not_wf_P02_ibm02n02xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n03xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n03.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n03xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n03.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x02" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x2 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x02"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x2 found in comment")); } } @@ -130,19 +115,14 @@ public void testibm_not_wf_P02_ibm02n03xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n04xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n04.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n04xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n04.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x03" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x3 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x03"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x3 found in comment")); } } @@ -156,19 +136,14 @@ public void testibm_not_wf_P02_ibm02n04xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n05xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n05.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n05xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n05.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x04" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x4 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x04"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x4 found in comment")); } } @@ -182,19 +157,14 @@ public void testibm_not_wf_P02_ibm02n05xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n06xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n06.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n06xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n06.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x05" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x5 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x05"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x5 found in comment")); } } @@ -209,18 +179,16 @@ public void testibm_not_wf_P02_ibm02n06xml() */ @Test public void testibm_not_wf_P02_ibm02n07xml() throws IOException { - try(Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n07.xml"))) { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n07.xml"))) { parser.setInput(reader); - while (parser.nextToken() != XmlPullParser.END_DOCUMENT); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; fail("Tests a comment which contains an illegal Char: #x06"); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x6 found in comment" ) ); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x6 found in comment")); } } - /** * Test ID:
      ibm-not-wf-P02-ibm02n08.xml
      * Test URI:
      not-wf/P02/ibm02n08.xml
      @@ -231,19 +199,14 @@ public void testibm_not_wf_P02_ibm02n07xml() throws IOException { * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n08xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n08.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n08xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n08.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x07" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x7 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x07"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x7 found in comment")); } } @@ -257,19 +220,14 @@ public void testibm_not_wf_P02_ibm02n08xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n09xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n09.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n09xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n09.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x08" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x8 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x08"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x8 found in comment")); } } @@ -283,19 +241,14 @@ public void testibm_not_wf_P02_ibm02n09xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n10xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n10.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n10xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n10.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x0B" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0xb found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x0B"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0xb found in comment")); } } @@ -309,19 +262,14 @@ public void testibm_not_wf_P02_ibm02n10xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n11xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n11.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n11xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n11.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x0C" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0xc found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x0C"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0xc found in comment")); } } @@ -335,19 +283,14 @@ public void testibm_not_wf_P02_ibm02n11xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n12xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n12.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n12xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n12.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x0E" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0xe found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x0E"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0xe found in comment")); } } @@ -361,19 +304,14 @@ public void testibm_not_wf_P02_ibm02n12xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n13xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n13.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n13xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n13.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x0F" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0xf found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x0F"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0xf found in comment")); } } @@ -387,19 +325,14 @@ public void testibm_not_wf_P02_ibm02n13xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n14xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n14.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n14xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n14.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x10" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x10 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x10"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x10 found in comment")); } } @@ -413,19 +346,14 @@ public void testibm_not_wf_P02_ibm02n14xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n15xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n15.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n15xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n15.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x11" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x11 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x11"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x11 found in comment")); } } @@ -439,19 +367,14 @@ public void testibm_not_wf_P02_ibm02n15xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n16xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n16.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n16xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n16.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x12" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x12 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x12"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x12 found in comment")); } } @@ -465,19 +388,14 @@ public void testibm_not_wf_P02_ibm02n16xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n17xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n17.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n17xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n17.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x13" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x13 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x13"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x13 found in comment")); } } @@ -491,19 +409,14 @@ public void testibm_not_wf_P02_ibm02n17xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n18xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n18.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n18xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n18.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x14" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x14 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x14"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x14 found in comment")); } } @@ -517,19 +430,14 @@ public void testibm_not_wf_P02_ibm02n18xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n19xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n19.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n19xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n19.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x15" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x15 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x15"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x15 found in comment")); } } @@ -543,19 +451,14 @@ public void testibm_not_wf_P02_ibm02n19xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n20xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n20.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n20xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n20.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x16" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x16 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x16"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x16 found in comment")); } } @@ -569,19 +472,14 @@ public void testibm_not_wf_P02_ibm02n20xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n21xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n21.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n21xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n21.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x17" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x17 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x17"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x17 found in comment")); } } @@ -595,19 +493,14 @@ public void testibm_not_wf_P02_ibm02n21xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n22xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n22.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n22xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n22.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x18" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x18 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x18"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x18 found in comment")); } } @@ -621,19 +514,14 @@ public void testibm_not_wf_P02_ibm02n22xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n23xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n23.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n23xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n23.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x19" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x19 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x19"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x19 found in comment")); } } @@ -647,19 +535,14 @@ public void testibm_not_wf_P02_ibm02n23xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n24xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n24.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n24xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n24.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x1A" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x1a found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x1A"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x1a found in comment")); } } @@ -673,19 +556,14 @@ public void testibm_not_wf_P02_ibm02n24xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n25xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n25.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n25xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n25.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x1B" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x1b found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x1B"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x1b found in comment")); } } @@ -699,19 +577,14 @@ public void testibm_not_wf_P02_ibm02n25xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n26xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n26.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n26xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n26.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x1C" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x1c found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x1C"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x1c found in comment")); } } @@ -725,19 +598,14 @@ public void testibm_not_wf_P02_ibm02n26xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n27xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n27.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n27xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n27.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x1D" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x1d found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x1D"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x1d found in comment")); } } @@ -751,19 +619,14 @@ public void testibm_not_wf_P02_ibm02n27xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n28xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n28.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n28xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n28.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x1E" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x1e found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x1E"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x1e found in comment")); } } @@ -777,19 +640,14 @@ public void testibm_not_wf_P02_ibm02n28xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n29xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P02/ibm02n29.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n29xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P02/ibm02n29.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #x1F" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0x1f found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #x1F"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0x1f found in comment")); } } @@ -804,22 +662,17 @@ public void testibm_not_wf_P02_ibm02n29xml() * * NOTE: This test file is malformed into the original test suite, so I skip it. */ - //@Test - public void testibm_not_wf_P02_ibm02n30xml() - throws IOException - { - try ( BufferedReader reader = - Files.newBufferedReader( Paths.get( testResourcesDir.getCanonicalPath(), "not-wf/P02/ibm02n30.xml" ), - Charset.forName( "ISO-8859-15" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + // @Test + public void testibm_not_wf_P02_ibm02n30xml() throws IOException { + try (BufferedReader reader = Files.newBufferedReader( + Paths.get(testResourcesDir.getCanonicalPath(), "not-wf/P02/ibm02n30.xml"), + Charset.forName("ISO-8859-15"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #xD800" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0xd800 found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #xD800"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0xd800 found in comment")); } } @@ -834,21 +687,16 @@ public void testibm_not_wf_P02_ibm02n30xml() * * NOTE: This test file is malformed into the original test suite, so I skip it. */ - //@Test - public void testibm_not_wf_P02_ibm02n31xml() - throws IOException - { - try ( FileInputStream is = new FileInputStream( new File( testResourcesDir, "not-wf/P02/ibm02n31.xml" ) ); - InputStreamReader reader = new InputStreamReader( is, "ISO-8859-15" ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + // @Test + public void testibm_not_wf_P02_ibm02n31xml() throws IOException { + try (FileInputStream is = new FileInputStream(new File(testResourcesDir, "not-wf/P02/ibm02n31.xml")); + InputStreamReader reader = new InputStreamReader(is, "ISO-8859-15")) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #xDFFF" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0xdfff found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #xDFFF"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0xdfff found in comment")); } } @@ -862,20 +710,15 @@ public void testibm_not_wf_P02_ibm02n31xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n32xml() - throws IOException - { - try ( FileInputStream is = new FileInputStream( new File( testResourcesDir, "not-wf/P02/ibm02n32.xml" ) ); - InputStreamReader reader = new InputStreamReader( is, StandardCharsets.UTF_8 ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n32xml() throws IOException { + try (FileInputStream is = new FileInputStream(new File(testResourcesDir, "not-wf/P02/ibm02n32.xml")); + InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #xFFFE" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0xfffe found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #xFFFE"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0xfffe found in comment")); } } @@ -889,21 +732,15 @@ public void testibm_not_wf_P02_ibm02n32xml() * @throws java.io.IOException if there is an I/O error */ @Test - public void testibm_not_wf_P02_ibm02n33xml() - throws IOException - { - try ( FileInputStream is = new FileInputStream( new File( testResourcesDir, "not-wf/P02/ibm02n33.xml" ) ); - InputStreamReader reader = new InputStreamReader( is, StandardCharsets.UTF_8 ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testibm_not_wf_P02_ibm02n33xml() throws IOException { + try (FileInputStream is = new FileInputStream(new File(testResourcesDir, "not-wf/P02/ibm02n33.xml")); + InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "Tests a comment which contains an illegal Char: #xFFFF" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "Illegal character 0xffff found in comment" ) ); + fail("Tests a comment which contains an illegal Char: #xFFFF"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("Illegal character 0xffff found in comment")); } } - } diff --git a/src/test/java/org/codehaus/plexus/util/xml/pull/IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production32_Test.java b/src/test/java/org/codehaus/plexus/util/xml/pull/IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production32_Test.java index a6a80030..91effa9d 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/pull/IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production32_Test.java +++ b/src/test/java/org/codehaus/plexus/util/xml/pull/IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production32_Test.java @@ -1,8 +1,5 @@ package org.codehaus.plexus.util.xml.pull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -11,6 +8,9 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** * Test class that execute a particular set of tests associated to a TESCASES tag from the XML W3C Conformance Tests. * TESCASES PROFILE:
      IBM XML Conformance Test Suite - Production 32
      @@ -20,10 +20,10 @@ * @version $Id: $Id * @since 3.4.0 */ -public class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production32_Test -{ +public +class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production32_Test { - final static File testResourcesDir = new File( "src/test/resources/", "xmlconf/ibm/" ); + static final File testResourcesDir = new File("src/test/resources/", "xmlconf/ibm/"); MXParser parser; @@ -31,246 +31,203 @@ public class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMX *

      setUp.

      */ @Before - public void setUp() - { + public void setUp() { parser = new MXParser(); } - /** - * Test ID:
      ibm-not-wf-P32-ibm32n01.xml
      - * Test URI:
      not-wf/P32/ibm32n01.xml
      - * Comment:
      Tests SDDecl with a required field missing. The leading white space     is missing with the SDDecl in the XMLDecl.
      - * Sections:
      2.9
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P32_ibm32n01xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P32/ibm32n01.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests SDDecl with a required field missing. The leading white space is missing with the SDDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected a space after version and not s" ) ); - } - } - - /** - * Test ID:
      ibm-not-wf-P32-ibm32n02.xml
      - * Test URI:
      not-wf/P32/ibm32n02.xml
      - * Comment:
      Tests SDDecl with a required field missing. The "=" sign is missing     in the SDDecl in the XMLDecl.
      - * Sections:
      2.9
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P32_ibm32n02xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P32/ibm32n02.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests SDDecl with a required field missing. The \"=\" sign is missing in the SDDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected equals sign (=) after standalone and not \"" ) ); - } - } - - /** - * Test ID:
      ibm-not-wf-P32-ibm32n03.xml
      - * Test URI:
      not-wf/P32/ibm32n03.xml
      - * Comment:
      Tests SDDecl with wrong key word. The word "Standalone" occurs in      the SDDecl in the XMLDecl.
      - * Sections:
      2.9
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P32_ibm32n03xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P32/ibm32n03.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests SDDecl with wrong key word. The word \"Standalone\" occurs in the SDDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "unexpected character S" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P32-ibm32n01.xml
      + * Test URI:
      not-wf/P32/ibm32n01.xml
      + * Comment:
      Tests SDDecl with a required field missing. The leading white space     is missing with the SDDecl in the XMLDecl.
      + * Sections:
      2.9
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P32_ibm32n01xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P32/ibm32n01.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests SDDecl with a required field missing. The leading white space is missing with the SDDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected a space after version and not s")); + } + } - /** - * Test ID:
      ibm-not-wf-P32-ibm32n04.xml
      - * Test URI:
      not-wf/P32/ibm32n04.xml
      - * Comment:
      Tests SDDecl with wrong key word. The word "Yes" occurs in the     SDDecl in the XMLDecl.
      - * Sections:
      2.9
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P32_ibm32n04xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P32/ibm32n04.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests SDDecl with wrong key word. The word \"Yes\" occurs in the SDDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected 'yes' or 'no' after standalone and not Y" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P32-ibm32n02.xml
      + * Test URI:
      not-wf/P32/ibm32n02.xml
      + * Comment:
      Tests SDDecl with a required field missing. The "=" sign is missing     in the SDDecl in the XMLDecl.
      + * Sections:
      2.9
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P32_ibm32n02xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P32/ibm32n02.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests SDDecl with a required field missing. The \"=\" sign is missing in the SDDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected equals sign (=) after standalone and not \"")); + } + } - /** - * Test ID:
      ibm-not-wf-P32-ibm32n05.xml
      - * Test URI:
      not-wf/P32/ibm32n05.xml
      - * Comment:
      Tests SDDecl with wrong key word. The word "YES" occurs in the     SDDecl in the XMLDecl.
      - * Sections:
      2.9
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P32_ibm32n05xml() - throws IOException - { + /** + * Test ID:
      ibm-not-wf-P32-ibm32n03.xml
      + * Test URI:
      not-wf/P32/ibm32n03.xml
      + * Comment:
      Tests SDDecl with wrong key word. The word "Standalone" occurs in      the SDDecl in the XMLDecl.
      + * Sections:
      2.9
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P32_ibm32n03xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P32/ibm32n03.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail("Tests SDDecl with wrong key word. The word \"Standalone\" occurs in the SDDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("unexpected character S")); + } + } - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P32/ibm32n05.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests SDDecl with wrong key word. The word \"YES\" occurs in the SDDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected 'yes' or 'no' after standalone and not Y" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P32-ibm32n04.xml
      + * Test URI:
      not-wf/P32/ibm32n04.xml
      + * Comment:
      Tests SDDecl with wrong key word. The word "Yes" occurs in the     SDDecl in the XMLDecl.
      + * Sections:
      2.9
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P32_ibm32n04xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P32/ibm32n04.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail("Tests SDDecl with wrong key word. The word \"Yes\" occurs in the SDDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected 'yes' or 'no' after standalone and not Y")); + } + } - /** - * Test ID:
      ibm-not-wf-P32-ibm32n06.xml
      - * Test URI:
      not-wf/P32/ibm32n06.xml
      - * Comment:
      Tests SDDecl with wrong key word. The word "No" occurs in the     SDDecl in the XMLDecl.
      - * Sections:
      2.9
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P32_ibm32n06xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P32/ibm32n06.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests SDDecl with wrong key word. The word \"No\" occurs in the SDDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected 'yes' or 'no' after standalone and not N" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P32-ibm32n05.xml
      + * Test URI:
      not-wf/P32/ibm32n05.xml
      + * Comment:
      Tests SDDecl with wrong key word. The word "YES" occurs in the     SDDecl in the XMLDecl.
      + * Sections:
      2.9
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P32_ibm32n05xml() throws IOException { + + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P32/ibm32n05.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail("Tests SDDecl with wrong key word. The word \"YES\" occurs in the SDDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected 'yes' or 'no' after standalone and not Y")); + } + } - /** - * Test ID:
      ibm-not-wf-P32-ibm32n07.xml
      - * Test URI:
      not-wf/P32/ibm32n07.xml
      - * Comment:
      Tests SDDecl with wrong key word. The word "NO" occurs in the     SDDecl in the XMLDecl.
      - * Sections:
      2.9
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P32_ibm32n07xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P32/ibm32n07.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests SDDecl with wrong key word. The word \"NO\" occurs in the SDDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected 'yes' or 'no' after standalone and not N" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P32-ibm32n06.xml
      + * Test URI:
      not-wf/P32/ibm32n06.xml
      + * Comment:
      Tests SDDecl with wrong key word. The word "No" occurs in the     SDDecl in the XMLDecl.
      + * Sections:
      2.9
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P32_ibm32n06xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P32/ibm32n06.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail("Tests SDDecl with wrong key word. The word \"No\" occurs in the SDDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected 'yes' or 'no' after standalone and not N")); + } + } - /** - * Test ID:
      ibm-not-wf-P32-ibm32n08.xml
      - * Test URI:
      not-wf/P32/ibm32n08.xml
      - * Comment:
      Tests SDDecl with wrong field ordering. The "=" sign occurs      after the key word "yes" in the SDDecl in the XMLDecl.
      - * Sections:
      2.9
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P32_ibm32n08xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P32/ibm32n08.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests SDDecl with wrong field ordering. The \"=\" sign occurs after the key word \"yes\" in the SDDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected equals sign (=) after standalone and not \"" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P32-ibm32n07.xml
      + * Test URI:
      not-wf/P32/ibm32n07.xml
      + * Comment:
      Tests SDDecl with wrong key word. The word "NO" occurs in the     SDDecl in the XMLDecl.
      + * Sections:
      2.9
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P32_ibm32n07xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P32/ibm32n07.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail("Tests SDDecl with wrong key word. The word \"NO\" occurs in the SDDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected 'yes' or 'no' after standalone and not N")); + } + } - /** - * Test ID:
      ibm-not-wf-P32-ibm32n09.xml
      - * Test URI:
      not-wf/P32/ibm32n09.xml
      - * Comment:
      This is test violates WFC: Entity Declared in P68.     The standalone document declaration has the value yes, BUT there is an      external markup declaration of an entity (other than amp, lt, gt, apos,     quot), and references to this entity appear in the document.
      - * Sections:
      2.9
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - * - * NOTE: This test is SKIPPED as MXParser does not support parsing inside DOCTYPEDECL. - */ - // @Test - public void testibm_not_wf_P32_ibm32n09xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P32/ibm32n09.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "This is test violates WFC: Entity Declared in P68. The standalone document declaration has the value yes, BUT there is an external markup declaration of an entity (other than amp, lt, gt, apos, quot), and references to this entity appear in the document." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected ?> as last part of ibm-not-wf-P32-ibm32n08.xml + * Test URI:
      not-wf/P32/ibm32n08.xml
      + * Comment:
      Tests SDDecl with wrong field ordering. The "=" sign occurs      after the key word "yes" in the SDDecl in the XMLDecl.
      + * Sections:
      2.9
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P32_ibm32n08xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P32/ibm32n08.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests SDDecl with wrong field ordering. The \"=\" sign occurs after the key word \"yes\" in the SDDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected equals sign (=) after standalone and not \"")); + } + } + /** + * Test ID:
      ibm-not-wf-P32-ibm32n09.xml
      + * Test URI:
      not-wf/P32/ibm32n09.xml
      + * Comment:
      This is test violates WFC: Entity Declared in P68.     The standalone document declaration has the value yes, BUT there is an      external markup declaration of an entity (other than amp, lt, gt, apos,     quot), and references to this entity appear in the document.
      + * Sections:
      2.9
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + * + * NOTE: This test is SKIPPED as MXParser does not support parsing inside DOCTYPEDECL. + */ + // @Test + public void testibm_not_wf_P32_ibm32n09xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P32/ibm32n09.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "This is test violates WFC: Entity Declared in P68. The standalone document declaration has the value yes, BUT there is an external markup declaration of an entity (other than amp, lt, gt, apos, quot), and references to this entity appear in the document."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected ?> as last part of IBM XML Conformance Test Suite - Production 66 @@ -22,10 +21,10 @@ * @version $Id: $Id * @since 3.4.0 */ -public class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production66_Test -{ +public +class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production66_Test { - final static File testResourcesDir = new File( "src/test/resources/", "xmlconf/ibm/" ); + static final File testResourcesDir = new File("src/test/resources/", "xmlconf/ibm/"); MXParser parser; @@ -33,401 +32,339 @@ public class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMX *

      setUp.

      */ @Before - public void setUp() - { + public void setUp() { parser = new MXParser(); } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n01.xml
      - * Test URI:
      not-wf/P66/ibm66n01.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "#002f" is      used as the referred character in the CharRef in the EntityDecl in the DTD.
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n01xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n01.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"#002f\" is used as the referred character in the CharRef in the EntityDecl in the DTD." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with decimal value) may not contain f" ) ); - } - } - - /** - * Test ID:
      ibm-not-wf-P66-ibm66n02.xml
      - * Test URI:
      not-wf/P66/ibm66n02.xml
      - * Comment:
      Tests CharRef with the semicolon character missing. The semicolon      character is missing at the end of the CharRef in the attribute value in     the STag of element "root".
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n02xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n02.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with the semicolon character missing. The semicolon character is missing at the end of the CharRef in the attribute value in the STag of element \"root\"." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with hex value) may not contain \"" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n01.xml
      + * Test URI:
      not-wf/P66/ibm66n01.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "#002f" is      used as the referred character in the CharRef in the EntityDecl in the DTD.
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n01xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n01.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"#002f\" is used as the referred character in the CharRef in the EntityDecl in the DTD."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with decimal value) may not contain f")); + } + } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n03.xml
      - * Test URI:
      not-wf/P66/ibm66n03.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "49" is      used as the referred character in the CharRef in the EntityDecl in the DTD.
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n03xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n03.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"49\" is used as the referred character in the CharRef in the EntityDecl in the DTD." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "entity reference names can not start with character '4'" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n02.xml
      + * Test URI:
      not-wf/P66/ibm66n02.xml
      + * Comment:
      Tests CharRef with the semicolon character missing. The semicolon      character is missing at the end of the CharRef in the attribute value in     the STag of element "root".
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n02xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n02.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with the semicolon character missing. The semicolon character is missing at the end of the CharRef in the attribute value in the STag of element \"root\"."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with hex value) may not contain \"")); + } + } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n04.xml
      - * Test URI:
      not-wf/P66/ibm66n04.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "#5~0" is      used as the referred character in the attribute value in the EmptyElemTag     of the element "root".
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n04xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n04.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"#5~0\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with decimal value) may not contain ~" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n03.xml
      + * Test URI:
      not-wf/P66/ibm66n03.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "49" is      used as the referred character in the CharRef in the EntityDecl in the DTD.
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n03xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n03.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"49\" is used as the referred character in the CharRef in the EntityDecl in the DTD."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("entity reference names can not start with character '4'")); + } + } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n05.xml
      - * Test URI:
      not-wf/P66/ibm66n05.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "#x002g" is     used as the referred character in the CharRef in the EntityDecl in the DTD.
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - * @throws java.io.FileNotFoundException if any. - * @throws org.codehaus.plexus.util.xml.pull.XmlPullParserException if any. - */ - @Test - public void testibm_not_wf_P66_ibm66n05xml() - throws FileNotFoundException, IOException, XmlPullParserException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n05.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"#x002g\" is used as the referred character in the CharRef in the EntityDecl in the DTD." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with hex value) may not contain g" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n04.xml
      + * Test URI:
      not-wf/P66/ibm66n04.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "#5~0" is      used as the referred character in the attribute value in the EmptyElemTag     of the element "root".
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n04xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n04.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"#5~0\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with decimal value) may not contain ~")); + } + } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n06.xml
      - * Test URI:
      not-wf/P66/ibm66n06.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "#x006G" is     used as the referred character in the attribute value in the EmptyElemTag      of the element "root".
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n06xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n06.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"#x006G\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with hex value) may not contain G" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n05.xml
      + * Test URI:
      not-wf/P66/ibm66n05.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "#x002g" is     used as the referred character in the CharRef in the EntityDecl in the DTD.
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + * @throws java.io.FileNotFoundException if any. + * @throws org.codehaus.plexus.util.xml.pull.XmlPullParserException if any. + */ + @Test + public void testibm_not_wf_P66_ibm66n05xml() throws FileNotFoundException, IOException, XmlPullParserException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n05.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"#x002g\" is used as the referred character in the CharRef in the EntityDecl in the DTD."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with hex value) may not contain g")); + } + } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n07.xml
      - * Test URI:
      not-wf/P66/ibm66n07.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "#0=2f" is      used as the referred character in the CharRef in the EntityDecl in the DTD.
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n07xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n07.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"#0=2f\" is used as the referred character in the CharRef in the EntityDecl in the DTD." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with hex value) may not contain =" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n06.xml
      + * Test URI:
      not-wf/P66/ibm66n06.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "#x006G" is     used as the referred character in the attribute value in the EmptyElemTag      of the element "root".
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n06xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n06.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"#x006G\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with hex value) may not contain G")); + } + } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n08.xml
      - * Test URI:
      not-wf/P66/ibm66n08.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "#56.0" is      used as the referred character in the attribute value in the EmptyElemTag      of the element "root".
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n08xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n08.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"#56.0\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with decimal value) may not contain ." ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n07.xml
      + * Test URI:
      not-wf/P66/ibm66n07.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "#0=2f" is      used as the referred character in the CharRef in the EntityDecl in the DTD.
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n07xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n07.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"#0=2f\" is used as the referred character in the CharRef in the EntityDecl in the DTD."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with hex value) may not contain =")); + } + } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n09.xml
      - * Test URI:
      not-wf/P66/ibm66n09.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "#x00/2f"      is used as the referred character in the CharRef in the EntityDecl in the      DTD.
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n09xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n09.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"#x00/2f\" is used as the referred character in the CharRef in the EntityDecl in the DTD." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with hex value) may not contain /" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n08.xml
      + * Test URI:
      not-wf/P66/ibm66n08.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "#56.0" is      used as the referred character in the attribute value in the EmptyElemTag      of the element "root".
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n08xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n08.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"#56.0\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with decimal value) may not contain .")); + } + } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n10.xml
      - * Test URI:
      not-wf/P66/ibm66n10.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "#51)" is      used as the referred character in the attribute value in the EmptyElemTag      of the element "root".
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n10xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n10.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"#51)\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with decimal value) may not contain )" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n09.xml
      + * Test URI:
      not-wf/P66/ibm66n09.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "#x00/2f"      is used as the referred character in the CharRef in the EntityDecl in the      DTD.
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n09xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n09.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"#x00/2f\" is used as the referred character in the CharRef in the EntityDecl in the DTD."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with hex value) may not contain /")); + } + } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n11.xml
      - * Test URI:
      not-wf/P66/ibm66n11.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "#00 2f"     is used as the referred character in the CharRef in the EntityDecl in the      DTD.
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n11xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n11.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"#00 2f\" is used as the referred character in the CharRef in the EntityDecl in the DTD." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with hex value) may not contain " ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n10.xml
      + * Test URI:
      not-wf/P66/ibm66n10.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "#51)" is      used as the referred character in the attribute value in the EmptyElemTag      of the element "root".
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n10xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n10.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"#51)\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with decimal value) may not contain )")); + } + } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n12.xml
      - * Test URI:
      not-wf/P66/ibm66n12.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "#x0000"      is used as the referred character in the attribute value in the EmptyElemTag     of the element "root".
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n12xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n12.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"#x0000\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with hex value 0000) is invalid" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n11.xml
      + * Test URI:
      not-wf/P66/ibm66n11.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "#00 2f"     is used as the referred character in the CharRef in the EntityDecl in the      DTD.
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n11xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n11.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"#00 2f\" is used as the referred character in the CharRef in the EntityDecl in the DTD."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with hex value) may not contain ")); + } + } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n13.xml
      - * Test URI:
      not-wf/P66/ibm66n13.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "#x001f"      is used as the referred character in the attribute value in the EmptyElemTag     of the element "root".
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n13xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n13.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"#x001f\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with hex value 001f) is invalid" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n12.xml
      + * Test URI:
      not-wf/P66/ibm66n12.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "#x0000"      is used as the referred character in the attribute value in the EmptyElemTag     of the element "root".
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n12xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n12.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"#x0000\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with hex value 0000) is invalid")); + } + } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n14.xml
      - * Test URI:
      not-wf/P66/ibm66n14.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "#xfffe"      is used as the referred character in the attribute value in the EmptyElemTag     of the element "root".
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n14xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n14.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"#xfffe\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with hex value fffe) is invalid" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n13.xml
      + * Test URI:
      not-wf/P66/ibm66n13.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "#x001f"      is used as the referred character in the attribute value in the EmptyElemTag     of the element "root".
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n13xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n13.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"#x001f\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with hex value 001f) is invalid")); + } + } - /** - * Test ID:
      ibm-not-wf-P66-ibm66n15.xml
      - * Test URI:
      not-wf/P66/ibm66n15.xml
      - * Comment:
      Tests CharRef with an illegal character referred to. The "#xffff"      is used as the referred character in the attribute value in the EmptyElemTag     of the element "root".
      - * Sections:
      4.1
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P66_ibm66n15xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P66/ibm66n15.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests CharRef with an illegal character referred to. The \"#xffff\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with hex value ffff) is invalid" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n14.xml
      + * Test URI:
      not-wf/P66/ibm66n14.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "#xfffe"      is used as the referred character in the attribute value in the EmptyElemTag     of the element "root".
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n14xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n14.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"#xfffe\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with hex value fffe) is invalid")); + } + } + /** + * Test ID:
      ibm-not-wf-P66-ibm66n15.xml
      + * Test URI:
      not-wf/P66/ibm66n15.xml
      + * Comment:
      Tests CharRef with an illegal character referred to. The "#xffff"      is used as the referred character in the attribute value in the EmptyElemTag     of the element "root".
      + * Sections:
      4.1
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P66_ibm66n15xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P66/ibm66n15.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests CharRef with an illegal character referred to. The \"#xffff\" is used as the referred character in the attribute value in the EmptyElemTag of the element \"root\"."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with hex value ffff) is invalid")); + } + } } diff --git a/src/test/java/org/codehaus/plexus/util/xml/pull/IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production80_Test.java b/src/test/java/org/codehaus/plexus/util/xml/pull/IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production80_Test.java index e5510bb5..9b109a67 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/pull/IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production80_Test.java +++ b/src/test/java/org/codehaus/plexus/util/xml/pull/IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production80_Test.java @@ -1,8 +1,5 @@ package org.codehaus.plexus.util.xml.pull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -11,6 +8,9 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** * Test class that execute a particular set of tests associated to a TESCASES tag from the XML W3C Conformance Tests. * TESCASES PROFILE:
      IBM XML Conformance Test Suite - Production 80
      @@ -20,10 +20,10 @@ * @version $Id: $Id * @since 3.4.0 */ -public class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production80_Test -{ +public +class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMXMLConformanceTestSuite_Production80_Test { - final static File testResourcesDir = new File( "src/test/resources/", "xmlconf/ibm/" ); + static final File testResourcesDir = new File("src/test/resources/", "xmlconf/ibm/"); MXParser parser; @@ -31,165 +31,140 @@ public class IBMXML10Tests_Test_IBMXMLConformanceTestSuite_not_wftests_Test_IBMX *

      setUp.

      */ @Before - public void setUp() - { + public void setUp() { parser = new MXParser(); } - /** - * Test ID:
      ibm-not-wf-P80-ibm80n01.xml
      - * Test URI:
      not-wf/P80/ibm80n01.xml
      - * Comment:
      Tests EncodingDecl with a required field missing. The leading white      space is missing in the EncodingDecl in the XMLDecl.
      - * Sections:
      4.3.3
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P80_ibm80n01xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P80/ibm80n01.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests EncodingDecl with a required field missing. The leading white space is missing in the EncodingDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected a space after version and not e" ) ); - } - } - - /** - * Test ID:
      ibm-not-wf-P80-ibm80n02.xml
      - * Test URI:
      not-wf/P80/ibm80n02.xml
      - * Comment:
      Tests EncodingDecl with a required field missing. The "=" sign is      missing in the EncodingDecl in the XMLDecl.
      - * Sections:
      4.3.3
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P80_ibm80n02xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P80/ibm80n02.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests EncodingDecl with a required field missing. The \"=\" sign is missing in the EncodingDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected equals sign (=) after encoding and not \"" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P80-ibm80n01.xml
      + * Test URI:
      not-wf/P80/ibm80n01.xml
      + * Comment:
      Tests EncodingDecl with a required field missing. The leading white      space is missing in the EncodingDecl in the XMLDecl.
      + * Sections:
      4.3.3
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P80_ibm80n01xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P80/ibm80n01.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests EncodingDecl with a required field missing. The leading white space is missing in the EncodingDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected a space after version and not e")); + } + } - /** - * Test ID:
      ibm-not-wf-P80-ibm80n03.xml
      - * Test URI:
      not-wf/P80/ibm80n03.xml
      - * Comment:
      Tests EncodingDecl with a required field missing. The double quoted      EncName are missing in the EncodingDecl in the XMLDecl.
      - * Sections:
      4.3.3
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P80_ibm80n03xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P80/ibm80n03.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests EncodingDecl with a required field missing. The double quoted EncName are missing in the EncodingDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "expected apostrophe (') or quotation mark (\") after encoding and not ?" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P80-ibm80n02.xml
      + * Test URI:
      not-wf/P80/ibm80n02.xml
      + * Comment:
      Tests EncodingDecl with a required field missing. The "=" sign is      missing in the EncodingDecl in the XMLDecl.
      + * Sections:
      4.3.3
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P80_ibm80n02xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P80/ibm80n02.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests EncodingDecl with a required field missing. The \"=\" sign is missing in the EncodingDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("expected equals sign (=) after encoding and not \"")); + } + } - /** - * Test ID:
      ibm-not-wf-P80-ibm80n04.xml
      - * Test URI:
      not-wf/P80/ibm80n04.xml
      - * Comment:
      Tests EncodingDecl with wrong field ordering. The string "encoding="    occurs after the double quoted EncName in the EncodingDecl in the XMLDecl.
      - * Sections:
      4.3.3
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P80_ibm80n04xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P80/ibm80n04.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests EncodingDecl with wrong field ordering. The string \"encoding=\" occurs after the double quoted EncName in the EncodingDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "unexpected character \"" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P80-ibm80n03.xml
      + * Test URI:
      not-wf/P80/ibm80n03.xml
      + * Comment:
      Tests EncodingDecl with a required field missing. The double quoted      EncName are missing in the EncodingDecl in the XMLDecl.
      + * Sections:
      4.3.3
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P80_ibm80n03xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P80/ibm80n03.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests EncodingDecl with a required field missing. The double quoted EncName are missing in the EncodingDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue( + e.getMessage().contains("expected apostrophe (') or quotation mark (\") after encoding and not ?")); + } + } - /** - * Test ID:
      ibm-not-wf-P80-ibm80n05.xml
      - * Test URI:
      not-wf/P80/ibm80n05.xml
      - * Comment:
      Tests EncodingDecl with wrong field ordering. The "encoding" occurs     after the double quoted EncName in the EncodingDecl in the XMLDecl.
      - * Sections:
      4.3.3
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P80_ibm80n05xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P80/ibm80n05.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests EncodingDecl with wrong field ordering. The \"encoding\" occurs after the double quoted EncName in the EncodingDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "unexpected character \"" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P80-ibm80n04.xml
      + * Test URI:
      not-wf/P80/ibm80n04.xml
      + * Comment:
      Tests EncodingDecl with wrong field ordering. The string "encoding="    occurs after the double quoted EncName in the EncodingDecl in the XMLDecl.
      + * Sections:
      4.3.3
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P80_ibm80n04xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P80/ibm80n04.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests EncodingDecl with wrong field ordering. The string \"encoding=\" occurs after the double quoted EncName in the EncodingDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("unexpected character \"")); + } + } - /** - * Test ID:
      ibm-not-wf-P80-ibm80n06.xml
      - * Test URI:
      not-wf/P80/ibm80n06.xml
      - * Comment:
      Tests EncodingDecl with wrong key word. The string "Encoding" is      used as the key word in the EncodingDecl in the XMLDecl.
      - * Sections:
      4.3.3
      - * Version: - * - * @throws java.io.IOException if there is an I/O error - */ - @Test - public void testibm_not_wf_P80_ibm80n06xml() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "not-wf/P80/ibm80n06.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) - ; - fail( "Tests EncodingDecl with wrong key word. The string \"Encoding\" is used as the key word in the EncodingDecl in the XMLDecl." ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "unexpected character E" ) ); - } - } + /** + * Test ID:
      ibm-not-wf-P80-ibm80n05.xml
      + * Test URI:
      not-wf/P80/ibm80n05.xml
      + * Comment:
      Tests EncodingDecl with wrong field ordering. The "encoding" occurs     after the double quoted EncName in the EncodingDecl in the XMLDecl.
      + * Sections:
      4.3.3
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P80_ibm80n05xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P80/ibm80n05.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests EncodingDecl with wrong field ordering. The \"encoding\" occurs after the double quoted EncName in the EncodingDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("unexpected character \"")); + } + } + /** + * Test ID:
      ibm-not-wf-P80-ibm80n06.xml
      + * Test URI:
      not-wf/P80/ibm80n06.xml
      + * Comment:
      Tests EncodingDecl with wrong key word. The string "Encoding" is      used as the key word in the EncodingDecl in the XMLDecl.
      + * Sections:
      4.3.3
      + * Version: + * + * @throws java.io.IOException if there is an I/O error + */ + @Test + public void testibm_not_wf_P80_ibm80n06xml() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "not-wf/P80/ibm80n06.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) + ; + fail( + "Tests EncodingDecl with wrong key word. The string \"Encoding\" is used as the key word in the EncodingDecl in the XMLDecl."); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("unexpected character E")); + } + } } diff --git a/src/test/java/org/codehaus/plexus/util/xml/pull/MXParserPerfTest.java b/src/test/java/org/codehaus/plexus/util/xml/pull/MXParserPerfTest.java index c4d1a74f..ef6e30a2 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/pull/MXParserPerfTest.java +++ b/src/test/java/org/codehaus/plexus/util/xml/pull/MXParserPerfTest.java @@ -51,21 +51,19 @@ public class MXParserPerfTest { @State(Scope.Benchmark) - static public class AdditionState { + public static class AdditionState { byte[] data; @Setup(Level.Iteration) public void setUp() throws IOException, XmlPullParserException { - try (InputStream buf = getClass().getResourceAsStream( "/xml/pom.xml" ) ) - { - data = new byte[ buf.available() ]; - buf.read( data, 0, data.length ); + try (InputStream buf = getClass().getResourceAsStream("/xml/pom.xml")) { + data = new byte[buf.available()]; + buf.read(data, 0, data.length); } } } - /** *

      benchmarkBuild.

      * @@ -75,9 +73,8 @@ public void setUp() throws IOException, XmlPullParserException { * @throws org.codehaus.plexus.util.xml.pull.XmlPullParserException if any. */ @Benchmark - public Xpp3Dom benchmarkBuild( AdditionState state ) throws IOException, XmlPullParserException - { - return Xpp3DomBuilder.build( new ByteArrayInputStream( state.data ), null ); + public Xpp3Dom benchmarkBuild(AdditionState state) throws IOException, XmlPullParserException { + return Xpp3DomBuilder.build(new ByteArrayInputStream(state.data), null); } /** @@ -86,15 +83,13 @@ public Xpp3Dom benchmarkBuild( AdditionState state ) throws IOException, XmlPull * @param args a {@link java.lang.String} object. * @throws org.openjdk.jmh.runner.RunnerException if any. */ - public static void main( String... args ) - throws RunnerException - { + public static void main(String... args) throws RunnerException { Options opts = new OptionsBuilder() - .measurementIterations( 3 ) - .measurementTime( TimeValue.milliseconds( 3000 ) ) - .forks( 1 ) - .include( "org.codehaus.plexus.util.xml.pull.MXParserPerfTest" ) + .measurementIterations(3) + .measurementTime(TimeValue.milliseconds(3000)) + .forks(1) + .include("org.codehaus.plexus.util.xml.pull.MXParserPerfTest") .build(); - new Runner( opts ).run(); + new Runner(opts).run(); } } 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 cba42b32..f0f748fb 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,11 +16,6 @@ * limitations under the License. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.EOFException; import java.io.File; import java.io.IOException; @@ -34,6 +29,11 @@ import org.codehaus.plexus.util.ReaderFactory; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** *

      MXParserTest class.

      * @@ -41,32 +41,29 @@ * @version $Id: $Id * @since 3.4.0 */ -public class MXParserTest -{ +public class MXParserTest { /** *

      testHexadecimalEntities.

      * * @throws java.lang.Exception if any. */ @Test - public void testHexadecimalEntities() - throws Exception - { + public void testHexadecimalEntities() throws Exception { MXParser parser = new MXParser(); - parser.defineEntityReplacementText( "test", "replacement" ); + parser.defineEntityReplacementText("test", "replacement"); String input = "A"; - parser.setInput( new StringReader( input ) ); + parser.setInput(new StringReader(input)); - assertEquals( XmlPullParser.START_TAG, parser.next() ); + assertEquals(XmlPullParser.START_TAG, parser.next()); - assertEquals( XmlPullParser.TEXT, parser.next() ); + assertEquals(XmlPullParser.TEXT, parser.next()); - assertEquals( "A", parser.getText() ); + assertEquals("A", parser.getText()); - assertEquals( XmlPullParser.END_TAG, parser.next() ); + assertEquals(XmlPullParser.END_TAG, parser.next()); } /** @@ -75,24 +72,22 @@ public void testHexadecimalEntities() * @throws java.lang.Exception if any. */ @Test - public void testDecimalEntities() - throws Exception - { + public void testDecimalEntities() throws Exception { MXParser parser = new MXParser(); - parser.defineEntityReplacementText( "test", "replacement" ); + parser.defineEntityReplacementText("test", "replacement"); String input = "A"; - parser.setInput( new StringReader( input ) ); + parser.setInput(new StringReader(input)); - assertEquals( XmlPullParser.START_TAG, parser.next() ); + assertEquals(XmlPullParser.START_TAG, parser.next()); - assertEquals( XmlPullParser.TEXT, parser.next() ); + assertEquals(XmlPullParser.TEXT, parser.next()); - assertEquals( "A", parser.getText() ); + assertEquals("A", parser.getText()); - assertEquals( XmlPullParser.END_TAG, parser.next() ); + assertEquals(XmlPullParser.END_TAG, parser.next()); } /** @@ -101,24 +96,22 @@ public void testDecimalEntities() * @throws java.lang.Exception if any. */ @Test - public void testPredefinedEntities() - throws Exception - { + public void testPredefinedEntities() throws Exception { MXParser parser = new MXParser(); - parser.defineEntityReplacementText( "test", "replacement" ); + parser.defineEntityReplacementText("test", "replacement"); String input = "<>&'""; - parser.setInput( new StringReader( input ) ); + parser.setInput(new StringReader(input)); - assertEquals( XmlPullParser.START_TAG, parser.next() ); + assertEquals(XmlPullParser.START_TAG, parser.next()); - assertEquals( XmlPullParser.TEXT, parser.next() ); + assertEquals(XmlPullParser.TEXT, parser.next()); - assertEquals( "<>&'\"", parser.getText() ); + assertEquals("<>&'\"", parser.getText()); - assertEquals( XmlPullParser.END_TAG, parser.next() ); + assertEquals(XmlPullParser.END_TAG, parser.next()); } /** @@ -128,19 +121,17 @@ public void testPredefinedEntities() * @throws java.io.IOException if any. */ @Test - public void testEntityReplacementMap() - throws XmlPullParserException, IOException - { - EntityReplacementMap erm = new EntityReplacementMap( new String[][] { { "abc", "CDE" }, { "EFG", "HIJ" } } ); - MXParser parser = new MXParser( erm ); + public void testEntityReplacementMap() throws XmlPullParserException, IOException { + EntityReplacementMap erm = new EntityReplacementMap(new String[][] {{"abc", "CDE"}, {"EFG", "HIJ"}}); + MXParser parser = new MXParser(erm); String input = "&EFG;"; - parser.setInput( new StringReader( input ) ); + parser.setInput(new StringReader(input)); - assertEquals( XmlPullParser.START_TAG, parser.next() ); - assertEquals( XmlPullParser.TEXT, parser.next() ); - assertEquals( "HIJ", parser.getText() ); - assertEquals( XmlPullParser.END_TAG, parser.next() ); + assertEquals(XmlPullParser.START_TAG, parser.next()); + assertEquals(XmlPullParser.TEXT, parser.next()); + assertEquals("HIJ", parser.getText()); + assertEquals(XmlPullParser.END_TAG, parser.next()); } /** @@ -149,28 +140,26 @@ public void testEntityReplacementMap() * @throws java.lang.Exception if any. */ @Test - public void testCustomEntities() - throws Exception - { + public void testCustomEntities() throws Exception { MXParser parser = new MXParser(); String input = "&myentity;"; - parser.setInput( new StringReader( input ) ); - parser.defineEntityReplacementText( "myentity", "replacement" ); - assertEquals( XmlPullParser.START_TAG, parser.next() ); - assertEquals( XmlPullParser.TEXT, parser.next() ); - assertEquals( "replacement", parser.getText() ); - assertEquals( XmlPullParser.END_TAG, parser.next() ); + parser.setInput(new StringReader(input)); + parser.defineEntityReplacementText("myentity", "replacement"); + assertEquals(XmlPullParser.START_TAG, parser.next()); + assertEquals(XmlPullParser.TEXT, parser.next()); + assertEquals("replacement", parser.getText()); + assertEquals(XmlPullParser.END_TAG, parser.next()); parser = new MXParser(); input = "&myCustom;"; - parser.setInput( new StringReader( input ) ); - parser.defineEntityReplacementText( "fo", "A" ); - parser.defineEntityReplacementText( "myCustom", "&fo;" ); - assertEquals( XmlPullParser.START_TAG, parser.next() ); - assertEquals( XmlPullParser.TEXT, parser.next() ); - assertEquals( "A", parser.getText() ); - assertEquals( XmlPullParser.END_TAG, parser.next() ); + parser.setInput(new StringReader(input)); + parser.defineEntityReplacementText("fo", "A"); + parser.defineEntityReplacementText("myCustom", "&fo;"); + assertEquals(XmlPullParser.START_TAG, parser.next()); + assertEquals(XmlPullParser.TEXT, parser.next()); + assertEquals("A", parser.getText()); + assertEquals(XmlPullParser.END_TAG, parser.next()); } /** @@ -179,26 +168,24 @@ public void testCustomEntities() * @throws java.lang.Exception if any. */ @Test - public void testUnicodeEntities() - throws Exception - { + public void testUnicodeEntities() throws Exception { MXParser parser = new MXParser(); String input = "𝟭"; - parser.setInput( new StringReader( input ) ); + parser.setInput(new StringReader(input)); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( "\uD835\uDFED", parser.getText() ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals("\uD835\uDFED", parser.getText()); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); parser = new MXParser(); input = "ř"; - parser.setInput( new StringReader( input ) ); + parser.setInput(new StringReader(input)); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( "\u0159", parser.getText() ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals("\u0159", parser.getText()); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); } /** @@ -207,22 +194,17 @@ public void testUnicodeEntities() * @throws java.lang.Exception if any. */ @Test - public void testInvalidCharacterReferenceHexa() - throws Exception - { + public void testInvalidCharacterReferenceHexa() throws Exception { MXParser parser = new MXParser(); String input = ""; - parser.setInput( new StringReader( input ) ); + parser.setInput(new StringReader(input)); - try - { - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - fail( "Should fail since � is an illegal character reference" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with hex value 110000) is invalid" ) ); + try { + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + fail("Should fail since � is an illegal character reference"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with hex value 110000) is invalid")); } } @@ -232,45 +214,41 @@ public void testInvalidCharacterReferenceHexa() * @throws java.lang.Exception if any. */ @Test - public void testValidCharacterReferenceHexa() - throws Exception - { + public void testValidCharacterReferenceHexa() throws Exception { MXParser parser = new MXParser(); - String input = " Ȁ퟿ᄁ�𐀀􏿽􏿿"; - parser.setInput( new StringReader( input ) ); - - try - { - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 0x9, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 0xA, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 0xD, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 0x20, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 0x200, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 0xD7FF, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 0xE000, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 0xFFA2, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 0xFFFD, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 0x10000, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 0x10FFFD, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 0x10FFFF, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); - } - catch ( XmlPullParserException e ) - { - fail( "Should success since the input represents all legal character references" ); + String input = + " Ȁ퟿ᄁ�𐀀􏿽􏿿"; + parser.setInput(new StringReader(input)); + + try { + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(0x9, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(0xA, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(0xD, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(0x20, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(0x200, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(0xD7FF, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(0xE000, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(0xFFA2, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(0xFFFD, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(0x10000, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(0x10FFFD, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(0x10FFFF, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); + } catch (XmlPullParserException e) { + fail("Should success since the input represents all legal character references"); } } @@ -280,22 +258,17 @@ public void testValidCharacterReferenceHexa() * @throws java.lang.Exception if any. */ @Test - public void testInvalidCharacterReferenceDecimal() - throws Exception - { + public void testInvalidCharacterReferenceDecimal() throws Exception { MXParser parser = new MXParser(); String input = ""; - parser.setInput( new StringReader( input ) ); + parser.setInput(new StringReader(input)); - try - { - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - fail( "Should fail since � is an illegal character reference" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with decimal value 1114112) is invalid" ) ); + try { + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + fail("Should fail since � is an illegal character reference"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with decimal value 1114112) is invalid")); } } @@ -305,46 +278,41 @@ public void testInvalidCharacterReferenceDecimal() * @throws java.lang.Exception if any. */ @Test - public void testValidCharacterReferenceDecimal() - throws Exception - { + public void testValidCharacterReferenceDecimal() throws Exception { MXParser parser = new MXParser(); String input = - " Ȁ퟿ᄁ�𐀀􏿽􏿿"; - parser.setInput( new StringReader( input ) ); - - try - { - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 9, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 10, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 13, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 32, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 512, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 55295, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 57344, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 65442, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 65533, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 65536, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 1114109, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( 1114111, parser.getText().codePointAt( 0 ) ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); - } - catch ( XmlPullParserException e ) - { - fail( "Should success since the input represents all legal character references" ); + " Ȁ퟿ᄁ�𐀀􏿽􏿿"; + parser.setInput(new StringReader(input)); + + try { + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(9, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(10, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(13, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(32, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(512, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(55295, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(57344, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(65442, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(65533, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(65536, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(1114109, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(1114111, parser.getText().codePointAt(0)); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); + } catch (XmlPullParserException e) { + fail("Should success since the input represents all legal character references"); } } @@ -354,47 +322,44 @@ public void testValidCharacterReferenceDecimal() * @throws java.lang.Exception if any. */ @Test - public void testParserPosition() - throws Exception - { - String input = " \n \tnnn\n"; + public void testParserPosition() throws Exception { + String input = + " \n \tnnn\n"; MXParser parser = new MXParser(); - parser.setInput( new StringReader( input ) ); - - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken() ); - assertPosition( 1, 39, parser ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertPosition( 1, 49, parser ); - assertEquals( XmlPullParser.IGNORABLE_WHITESPACE, parser.nextToken() ); - assertPosition( 2, 3, parser ); // end when next token starts - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertPosition( 2, 12, parser ); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertPosition( 2, 18, parser ); - assertEquals( XmlPullParser.TEXT, parser.nextToken() ); - assertPosition( 2, 23, parser ); // end when next token starts - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); - assertPosition( 2, 29, parser ); - assertEquals( XmlPullParser.IGNORABLE_WHITESPACE, parser.nextToken() ); - assertPosition( 3, 2, parser ); // end when next token starts - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertPosition( 4, 6, parser ); + parser.setInput(new StringReader(input)); + + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken()); + assertPosition(1, 39, parser); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertPosition(1, 49, parser); + assertEquals(XmlPullParser.IGNORABLE_WHITESPACE, parser.nextToken()); + assertPosition(2, 3, parser); // end when next token starts + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertPosition(2, 12, parser); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertPosition(2, 18, parser); + assertEquals(XmlPullParser.TEXT, parser.nextToken()); + assertPosition(2, 23, parser); // end when next token starts + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); + assertPosition(2, 29, parser); + assertEquals(XmlPullParser.IGNORABLE_WHITESPACE, parser.nextToken()); + assertPosition(3, 2, parser); // end when next token starts + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertPosition(4, 6, parser); } @Test - public void testProcessingInstruction() - throws Exception - { + public void testProcessingInstruction() throws Exception { String input = "nnn"; MXParser parser = new MXParser(); - parser.setInput( new StringReader( input ) ); + parser.setInput(new StringReader(input)); - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken() ); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.TEXT, parser.nextToken() ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken()); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals(XmlPullParser.TEXT, parser.nextToken()); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); } /** @@ -403,28 +368,26 @@ public void testProcessingInstruction() * @throws java.lang.Exception if any. */ @Test - public void testProcessingInstructionsContainingXml() - throws Exception - { + public void testProcessingInstructionsContainingXml() throws Exception { StringBuffer sb = new StringBuffer(); - sb.append( "" ); - sb.append( "\n" ); - sb.append( " \n" ); - sb.append( " \n" ); - sb.append( " ?>\n" ); - sb.append( "" ); + sb.append(""); + sb.append("\n"); + sb.append(" \n"); + sb.append(" \n"); + sb.append(" ?>\n"); + sb.append(""); MXParser parser = new MXParser(); - parser.setInput( new StringReader( sb.toString() ) ); - - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken() ); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.TEXT, parser.nextToken() ); // whitespace - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken() ); - assertEquals( XmlPullParser.TEXT, parser.nextToken() ); // whitespace - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); + parser.setInput(new StringReader(sb.toString())); + + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken()); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals(XmlPullParser.TEXT, parser.nextToken()); // whitespace + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken()); + assertEquals(XmlPullParser.TEXT, parser.nextToken()); // whitespace + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); } /** @@ -433,56 +396,50 @@ public void testProcessingInstructionsContainingXml() * @throws java.lang.Exception if any. */ @Test - public void testMalformedProcessingInstructionsContainingXmlNoClosingQuestionMark() - throws Exception - { + public void testMalformedProcessingInstructionsContainingXmlNoClosingQuestionMark() throws Exception { StringBuffer sb = new StringBuffer(); - sb.append( "\n" ); - sb.append( "\n" ); - sb.append( "\n" ); - sb.append( " >\n" ); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append(" >\n"); MXParser parser = new MXParser(); - parser.setInput( new StringReader( sb.toString() ) ); - - try - { - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken() ); - assertEquals( XmlPullParser.IGNORABLE_WHITESPACE, parser.nextToken() ); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.IGNORABLE_WHITESPACE, parser.nextToken() ); - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken() ); - - fail( "Should fail since it has invalid PI" ); - } - catch ( XmlPullParserException ex ) - { - assertTrue( ex.getMessage().contains( "processing instruction started on line 3 and column 1 was not closed" ) ); + parser.setInput(new StringReader(sb.toString())); + + try { + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken()); + assertEquals(XmlPullParser.IGNORABLE_WHITESPACE, parser.nextToken()); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); + assertEquals(XmlPullParser.IGNORABLE_WHITESPACE, parser.nextToken()); + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken()); + + fail("Should fail since it has invalid PI"); + } catch (XmlPullParserException ex) { + assertTrue( + ex.getMessage().contains("processing instruction started on line 3 and column 1 was not closed")); } } @Test - public void testSubsequentProcessingInstructionShort() - throws Exception - { + public void testSubsequentProcessingInstructionShort() throws Exception { StringBuffer sb = new StringBuffer(); - sb.append( "" ); - sb.append( "" ); - sb.append( "" ); - sb.append( "" ); - sb.append( "" ); + sb.append(""); + sb.append(""); + sb.append(""); + sb.append(""); + sb.append(""); MXParser parser = new MXParser(); - parser.setInput( new StringReader( sb.toString() ) ); + parser.setInput(new StringReader(sb.toString())); - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken() ); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken() ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken()); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken()); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); } /** @@ -491,46 +448,42 @@ public void testSubsequentProcessingInstructionShort() * @throws java.lang.Exception if any. */ @Test - public void testSubsequentProcessingInstructionMoreThan8k() - throws Exception - { + public void testSubsequentProcessingInstructionMoreThan8k() throws Exception { StringBuffer sb = new StringBuffer(); - sb.append( "" ); - sb.append( "" ); + sb.append(""); + sb.append(""); // add ten times 1000 chars as comment - for ( int j = 0; j < 10; j++ ) - { + for (int j = 0; j < 10; j++) { - sb.append( "" ); + sb.append(" -->"); } - sb.append( "" ); - sb.append( "" ); + sb.append(""); + sb.append(""); MXParser parser = new MXParser(); - parser.setInput( new StringReader( sb.toString() ) ); - - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken() ); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken() ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); + parser.setInput(new StringReader(sb.toString())); + + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken()); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken()); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); } /** @@ -539,25 +492,23 @@ public void testSubsequentProcessingInstructionMoreThan8k() * @throws java.lang.Exception if any. */ @Test - public void testLargeText_NoOverflow() - throws Exception - { + public void testLargeText_NoOverflow() throws Exception { StringBuffer sb = new StringBuffer(); - sb.append( "" ); - sb.append( "" ); + sb.append(""); + sb.append(""); // Anything above 33,554,431 would fail without a fix for // https://web.archive.org/web/20070831191548/http://www.extreme.indiana.edu/bugzilla/show_bug.cgi?id=228 // with java.io.IOException: error reading input, returned 0 - sb.append( new String( new char[33554432] ) ); - sb.append( "" ); + sb.append(new String(new char[33554432])); + sb.append(""); MXParser parser = new MXParser(); - parser.setInput( new StringReader( sb.toString() ) ); + parser.setInput(new StringReader(sb.toString())); - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken() ); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.TEXT, parser.nextToken() ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken()); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals(XmlPullParser.TEXT, parser.nextToken()); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); } /** @@ -566,28 +517,23 @@ public void testLargeText_NoOverflow() * @throws java.lang.Exception if any. */ @Test - public void testMalformedProcessingInstructionAfterTag() - throws Exception - { + public void testMalformedProcessingInstructionAfterTag() throws Exception { MXParser parser = new MXParser(); String input = ""; - parser.setInput( new StringReader( input ) ); + parser.setInput(new StringReader(input)); - try - { - assertEquals( XmlPullParser.START_TAG, parser.next() ); + try { + assertEquals(XmlPullParser.START_TAG, parser.next()); - assertEquals( XmlPullParser.END_TAG, parser.next() ); + assertEquals(XmlPullParser.END_TAG, parser.next()); - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, 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" ) ); + fail("Should fail since it has an invalid Processing Instruction"); + } catch (XmlPullParserException ex) { + assertTrue(ex.getMessage().contains("processing instruction PITarget name not found")); } } @@ -597,28 +543,23 @@ public void testMalformedProcessingInstructionAfterTag() * @throws java.lang.Exception if any. */ @Test - public void testMalformedProcessingInstructionBeforeTag() - throws Exception - { + public void testMalformedProcessingInstructionBeforeTag() throws Exception { MXParser parser = new MXParser(); String input = ""; - parser.setInput( new StringReader( input ) ); + parser.setInput(new StringReader(input)); - try - { - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.next() ); + try { + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.next()); - assertEquals( XmlPullParser.START_TAG, parser.next() ); + assertEquals(XmlPullParser.START_TAG, parser.next()); - assertEquals( XmlPullParser.END_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" ) ); + fail("Should fail since it has invalid PI"); + } catch (XmlPullParserException ex) { + assertTrue(ex.getMessage().contains("processing instruction PITarget name not found")); } } @@ -628,30 +569,27 @@ public void testMalformedProcessingInstructionBeforeTag() * @throws java.lang.Exception if any. */ @Test - public void testMalformedProcessingInstructionSpaceBeforeName() - throws Exception - { + public void testMalformedProcessingInstructionSpaceBeforeName() throws Exception { MXParser parser = new MXParser(); StringBuilder sb = new StringBuilder(); - sb.append( "" ); - sb.append( "" ); + sb.append(""); + sb.append(""); - parser.setInput( new StringReader( sb.toString() ) ); + parser.setInput(new StringReader(sb.toString())); - try - { - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.next() ); + try { + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.next()); - assertEquals( XmlPullParser.START_TAG, parser.next() ); + assertEquals(XmlPullParser.START_TAG, parser.next()); - assertEquals( XmlPullParser.END_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( "" ); + sb.append(""); + sb.append(""); - parser.setInput( new StringReader( sb.toString() ) ); + parser.setInput(new StringReader(sb.toString())); - try - { - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, parser.next() ); + try { + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.next()); - assertEquals( XmlPullParser.START_TAG, parser.next() ); + assertEquals(XmlPullParser.START_TAG, parser.next()); - assertEquals( XmlPullParser.END_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 1 was not closed" ) ); + fail("Should fail since it has invalid PI"); + } catch (XmlPullParserException ex) { + assertTrue( + ex.getMessage().contains("processing instruction started on line 1 and column 1 was not closed")); } } @@ -694,30 +628,26 @@ public void testMalformedProcessingInstructionNoClosingQuestionMark() * @throws java.lang.Exception if any. */ @Test - public void testSubsequentMalformedProcessingInstructionNoClosingQuestionMark() - throws Exception - { + public void testSubsequentMalformedProcessingInstructionNoClosingQuestionMark() throws Exception { MXParser parser = new MXParser(); StringBuilder sb = new StringBuilder(); - sb.append( "" ); - sb.append( "" ); + sb.append(""); + sb.append(""); - parser.setInput( new StringReader( sb.toString() ) ); + parser.setInput(new StringReader(sb.toString())); - try - { - assertEquals( XmlPullParser.START_TAG, parser.next() ); + try { + assertEquals(XmlPullParser.START_TAG, parser.next()); - assertEquals( XmlPullParser.END_TAG, parser.next() ); + assertEquals(XmlPullParser.END_TAG, parser.next()); - assertEquals( XmlPullParser.PROCESSING_INSTRUCTION, 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 12 was not closed" ) ); + fail("Should fail since it has invalid PI"); + } catch (XmlPullParserException ex) { + assertTrue( + ex.getMessage().contains("processing instruction started on line 1 and column 12 was not closed")); } } @@ -727,75 +657,61 @@ public void testSubsequentMalformedProcessingInstructionNoClosingQuestionMark() * @throws java.lang.Exception if any. */ @Test - public void testSubsequentAbortedProcessingInstruction() - throws Exception - { + public void testSubsequentAbortedProcessingInstruction() throws Exception { MXParser parser = new MXParser(); StringBuilder sb = new StringBuilder(); - sb.append( "" ); - sb.append( ""); + sb.append("" ); - sb.append( "\n" - + " \n" - + " \n" - + "\n" - + "\n" - + "]", parser.getText() ); - assertEquals( XmlPullParser.IGNORABLE_WHITESPACE, parser.nextToken() ); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( "document", parser.getName() ); - assertEquals( 1, parser.getAttributeCount() ); - assertEquals( "name", parser.getAttributeName( 0 ) ); - assertEquals( "section name with entities: '&' 'Α' '<' ' ' '>' '𝟭' ''' 'ř' '\"'", - parser.getAttributeValue( 0 ) ); - - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( "myCustomEntity", parser.getName() ); - assertEquals( "ř", parser.getText() ); - - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); - assertEquals( XmlPullParser.END_DOCUMENT, parser.nextToken() ); - } - catch ( XmlPullParserException e ) - { - fail( "should not raise exception: " + e ); + parser.setInput(reader); + parser.defineEntityReplacementText("nbsp", " "); + parser.defineEntityReplacementText("Alpha", "Α"); + parser.defineEntityReplacementText("tritPos", "𝟭"); + parser.defineEntityReplacementText("flo", "ř"); + parser.defineEntityReplacementText("myCustomEntity", "&flo;"); + assertEquals(XmlPullParser.PROCESSING_INSTRUCTION, parser.nextToken()); + assertEquals(XmlPullParser.IGNORABLE_WHITESPACE, parser.nextToken()); + assertEquals(XmlPullParser.DOCDECL, parser.nextToken()); + assertEquals( + " document [\n" + + " \n" + + " \n" + + " \n" + + "\n" + + "\n" + + "]", + parser.getText()); + assertEquals(XmlPullParser.IGNORABLE_WHITESPACE, parser.nextToken()); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals("document", parser.getName()); + assertEquals(1, parser.getAttributeCount()); + assertEquals("name", parser.getAttributeName(0)); + assertEquals( + "section name with entities: '&' 'Α' '<' ' ' '>' '𝟭' ''' 'ř' '\"'", + parser.getAttributeValue(0)); + + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals("myCustomEntity", parser.getName()); + assertEquals("ř", parser.getText()); + + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); + assertEquals(XmlPullParser.END_DOCUMENT, parser.nextToken()); + } catch (XmlPullParserException e) { + fail("should not raise exception: " + e); } } @@ -1336,10 +1181,8 @@ private void testDocdeclTextWithEntitiesInAttributes( String filename ) * @since 3.4.2 */ @Test - public void testEntityRefTextUnix() - throws IOException - { - testEntityRefText( "\n" ); + public void testEntityRefTextUnix() throws IOException { + testEntityRefText("\n"); } /** @@ -1352,63 +1195,58 @@ public void testEntityRefTextUnix() * @since 3.4.2 */ @Test - public void testEntityRefTextDOS() - throws IOException - { - testEntityRefText( "\r\n" ); + public void testEntityRefTextDOS() throws IOException { + testEntityRefText("\r\n"); } - private void testEntityRefText( String newLine ) - throws IOException - { + private void testEntityRefText(String newLine) throws IOException { StringBuilder sb = new StringBuilder(); - sb.append( "" ).append( newLine ); - sb.append( "" ).append( newLine ); - sb.append( "" ).append( newLine ); - sb.append( "" ).append( newLine ); - sb.append( "]>" ).append( newLine ); - sb.append( "&foo;&foo1;&foo2;&tritPos;" ); - - try - { + sb.append("").append(newLine); + sb.append("").append(newLine); + sb.append("").append(newLine); + sb.append("").append(newLine); + sb.append("]>").append(newLine); + sb.append("&foo;&foo1;&foo2;&tritPos;"); + + try { MXParser parser = new MXParser(); - parser.setInput( new StringReader( sb.toString() ) ); - parser.defineEntityReplacementText( "foo", "ř" ); - parser.defineEntityReplacementText( "nbsp", " " ); - parser.defineEntityReplacementText( "foo1", " " ); - parser.defineEntityReplacementText( "foo2", "š" ); - parser.defineEntityReplacementText( "tritPos", "𝟭" ); - - assertEquals( XmlPullParser.DOCDECL, parser.nextToken() ); - assertEquals( " test [\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "]", parser.getText() ); - assertEquals( XmlPullParser.IGNORABLE_WHITESPACE, parser.nextToken() ); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( "b", parser.getName() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( "ř", parser.getText() ); - assertEquals( "foo", parser.getName() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( " ", parser.getText() ); - assertEquals( "foo1", parser.getName() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( "š", parser.getText() ); - assertEquals( "foo2", parser.getName() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( "𝟭", parser.getText() ); - assertEquals( "tritPos", parser.getName() ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); - assertEquals( "b", parser.getName() ); - assertEquals( XmlPullParser.END_DOCUMENT, parser.nextToken() ); - } - catch ( XmlPullParserException e ) - { - fail( "should not raise exception: " + e ); + parser.setInput(new StringReader(sb.toString())); + parser.defineEntityReplacementText("foo", "ř"); + parser.defineEntityReplacementText("nbsp", " "); + parser.defineEntityReplacementText("foo1", " "); + parser.defineEntityReplacementText("foo2", "š"); + parser.defineEntityReplacementText("tritPos", "𝟭"); + + assertEquals(XmlPullParser.DOCDECL, parser.nextToken()); + assertEquals( + " test [\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "]", + parser.getText()); + assertEquals(XmlPullParser.IGNORABLE_WHITESPACE, parser.nextToken()); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals("b", parser.getName()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals("ř", parser.getText()); + assertEquals("foo", parser.getName()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(" ", parser.getText()); + assertEquals("foo1", parser.getName()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals("š", parser.getText()); + assertEquals("foo2", parser.getName()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals("𝟭", parser.getText()); + assertEquals("tritPos", parser.getName()); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); + assertEquals("b", parser.getName()); + assertEquals(XmlPullParser.END_DOCUMENT, parser.nextToken()); + } catch (XmlPullParserException e) { + fail("should not raise exception: " + e); } } @@ -1425,35 +1263,32 @@ private void testEntityRefText( String newLine ) public void testEntityReplacement() throws IOException { String input = "

        

      "; - try - { + try { MXParser parser = new MXParser(); - parser.setInput( new StringReader( input ) ); - parser.defineEntityReplacementText( "nbsp", " " ); - - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( "p", parser.getName() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( " a pagebreak: ", parser.getText() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( " PB ", parser.getText() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( "\u00A0", parser.getText() ); - assertEquals( "#160", parser.getName() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( " ", parser.getText() ); - assertEquals( "nbsp", parser.getName() ); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( "unknown", parser.getName() ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); - assertEquals( "unknown", parser.getName() ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); - assertEquals( "p", parser.getName() ); - assertEquals( XmlPullParser.END_DOCUMENT, parser.nextToken() ); - } - catch ( XmlPullParserException e ) - { - fail( "should not raise exception: " + e ); + parser.setInput(new StringReader(input)); + parser.defineEntityReplacementText("nbsp", " "); + + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals("p", parser.getName()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals(" a pagebreak: ", parser.getText()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals(" PB ", parser.getText()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals("\u00A0", parser.getText()); + assertEquals("#160", parser.getName()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals(" ", parser.getText()); + assertEquals("nbsp", parser.getName()); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals("unknown", parser.getName()); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); + assertEquals("unknown", parser.getName()); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); + assertEquals("p", parser.getName()); + assertEquals(XmlPullParser.END_DOCUMENT, parser.nextToken()); + } catch (XmlPullParserException e) { + fail("should not raise exception: " + e); } } @@ -1468,47 +1303,42 @@ public void testEntityReplacement() throws IOException { * @since 3.4.2 */ @Test - public void testReplacementInPCArrayWithShorterCharArray() - throws IOException - { + public void testReplacementInPCArrayWithShorterCharArray() throws IOException { String input = "]>" - + "

      &&foo;&tritPos;

      "; + + "

      &&foo;&tritPos;

      "; - try - { + try { MXParser parser = new MXParser(); - parser.setInput( new StringReader( new String(input.getBytes(), "ISO-8859-1" ) ) ); - parser.defineEntityReplacementText( "foo", "ř" ); - parser.defineEntityReplacementText( "tritPos", "𝟭" ); - - assertEquals( XmlPullParser.DOCDECL, parser.nextToken() ); - assertEquals( " test []", parser.getText() ); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( "section", parser.getName() ); - assertEquals( 1, parser.getAttributeCount() ); - assertEquals( "name" , parser.getAttributeName( 0 ) ); - assertEquals( "&ř𝟭" , parser.getAttributeValue( 0 ) ); - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( "

      ", parser.getText() ); - assertEquals( "p", parser.getName() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( "&", parser.getText() ); - assertEquals( "amp", parser.getName() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( "ř", parser.getText() ); - assertEquals( "foo", parser.getName() ); - assertEquals( XmlPullParser.ENTITY_REF, parser.nextToken() ); - assertEquals( "𝟭", parser.getText() ); - assertEquals( "tritPos", parser.getName() ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); - assertEquals( "p", parser.getName() ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); - assertEquals( "section", parser.getName() ); - assertEquals( XmlPullParser.END_DOCUMENT, parser.nextToken() ); - } - catch ( XmlPullParserException e ) - { - fail( "should not raise exception: " + e ); + parser.setInput(new StringReader(new String(input.getBytes(), "ISO-8859-1"))); + parser.defineEntityReplacementText("foo", "ř"); + parser.defineEntityReplacementText("tritPos", "𝟭"); + + assertEquals(XmlPullParser.DOCDECL, parser.nextToken()); + assertEquals(" test []", parser.getText()); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals("section", parser.getName()); + assertEquals(1, parser.getAttributeCount()); + assertEquals("name", parser.getAttributeName(0)); + assertEquals("&ř𝟭", parser.getAttributeValue(0)); + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals("

      ", parser.getText()); + assertEquals("p", parser.getName()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals("&", parser.getText()); + assertEquals("amp", parser.getName()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals("ř", parser.getText()); + assertEquals("foo", parser.getName()); + assertEquals(XmlPullParser.ENTITY_REF, parser.nextToken()); + assertEquals("𝟭", parser.getText()); + assertEquals("tritPos", parser.getName()); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); + assertEquals("p", parser.getName()); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); + assertEquals("section", parser.getName()); + assertEquals(XmlPullParser.END_DOCUMENT, parser.nextToken()); + } catch (XmlPullParserException e) { + fail("should not raise exception: " + e); } } @@ -1519,22 +1349,19 @@ public void testReplacementInPCArrayWithShorterCharArray() public void testUnicode() throws IOException { String input = ""; - try - { + try { MXParser parser = new MXParser(); - parser.setInput( new StringReader( input ) ); - - assertEquals( XmlPullParser.START_TAG, parser.nextToken() ); - assertEquals( "project", parser.getName() ); - assertEquals( XmlPullParser.COMMENT, parser.nextToken() ); - assertEquals( "ALL TEH BOMS! \uD83D\uDCA3 ", parser.getText() ); - assertEquals( XmlPullParser.END_TAG, parser.nextToken() ); - assertEquals( "project", parser.getName() ); - } - catch ( XmlPullParserException e ) - { + parser.setInput(new StringReader(input)); + + assertEquals(XmlPullParser.START_TAG, parser.nextToken()); + assertEquals("project", parser.getName()); + assertEquals(XmlPullParser.COMMENT, parser.nextToken()); + assertEquals("ALL TEH BOMS! \uD83D\uDCA3 ", parser.getText()); + assertEquals(XmlPullParser.END_TAG, parser.nextToken()); + assertEquals("project", parser.getName()); + } catch (XmlPullParserException e) { e.printStackTrace(); - fail( "should not raise exception: " + e ); + fail("should not raise exception: " + e); } } } diff --git a/src/test/java/org/codehaus/plexus/util/xml/pull/eduni_misc_Test_BjoernHoehrmannviaHST2013_09_18_Test.java b/src/test/java/org/codehaus/plexus/util/xml/pull/eduni_misc_Test_BjoernHoehrmannviaHST2013_09_18_Test.java index 854fb494..2ae6de39 100644 --- a/src/test/java/org/codehaus/plexus/util/xml/pull/eduni_misc_Test_BjoernHoehrmannviaHST2013_09_18_Test.java +++ b/src/test/java/org/codehaus/plexus/util/xml/pull/eduni_misc_Test_BjoernHoehrmannviaHST2013_09_18_Test.java @@ -1,8 +1,5 @@ package org.codehaus.plexus.util.xml.pull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.File; import java.io.FileInputStream; import java.io.FileReader; @@ -14,6 +11,9 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** * Test class that execute a particular set of tests associated to a TESCASES tag from the XML W3C Conformance Tests. * TESCASES PROFILE:

      Bjoern Hoehrmann via HST 2013-09-18
      @@ -23,10 +23,9 @@ * @version $Id: $Id * @since 3.4.0 */ -public class eduni_misc_Test_BjoernHoehrmannviaHST2013_09_18_Test -{ +public class eduni_misc_Test_BjoernHoehrmannviaHST2013_09_18_Test { - final static File testResourcesDir = new File("src/test/resources/", "xmlconf/eduni/misc/"); + static final File testResourcesDir = new File("src/test/resources/", "xmlconf/eduni/misc/"); MXParser parser; @@ -34,8 +33,7 @@ public class eduni_misc_Test_BjoernHoehrmannviaHST2013_09_18_Test *

      setUp.

      */ @Before - public void setUp() - { + public void setUp() { parser = new MXParser(); } @@ -49,19 +47,14 @@ public void setUp() * @throws java.io.IOException if there is an I/O error */ @Test - public void testhst_bh_001() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "001.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testhst_bh_001() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "001.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "decimal charref > 10FFFF, indeed > max 32 bit integer, checking for recovery from possible overflow" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with hex value FF000000F6) is invalid" ) ); + fail("decimal charref > 10FFFF, indeed > max 32 bit integer, checking for recovery from possible overflow"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with hex value FF000000F6) is invalid")); } } @@ -75,19 +68,14 @@ public void testhst_bh_001() * @throws java.io.IOException if there is an I/O error */ @Test - public void testhst_bh_002() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "002.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testhst_bh_002() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "002.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "hex charref > 10FFFF, indeed > max 32 bit integer, checking for recovery from possible overflow" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with decimal value 4294967542) is invalid" ) ); + fail("hex charref > 10FFFF, indeed > max 32 bit integer, checking for recovery from possible overflow"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with decimal value 4294967542) is invalid")); } } @@ -101,19 +89,14 @@ public void testhst_bh_002() * @throws java.io.IOException if there is an I/O error */ @Test - public void testhst_bh_003() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "003.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testhst_bh_003() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "003.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "decimal charref > 10FFFF, indeed > max 64 bit integer, checking for recovery from possible overflow" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with hex value FFFFFFFF000000F6) is invalid" ) ); + fail("decimal charref > 10FFFF, indeed > max 64 bit integer, checking for recovery from possible overflow"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("character reference (with hex value FFFFFFFF000000F6) is invalid")); } } @@ -127,19 +110,15 @@ public void testhst_bh_003() * @throws java.io.IOException if there is an I/O error */ @Test - public void testhst_bh_004() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "004.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testhst_bh_004() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "004.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "hex charref > 10FFFF, indeed > max 64 bit integer, checking for recovery from possible overflow" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "character reference (with decimal value 18446744073709551862) is invalid" ) ); + fail("hex charref > 10FFFF, indeed > max 64 bit integer, checking for recovery from possible overflow"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage() + .contains("character reference (with decimal value 18446744073709551862) is invalid")); } } @@ -155,19 +134,14 @@ public void testhst_bh_004() * NOTE: This test is SKIPPED as MXParser do not supports DOCDECL parsing. */ // @Test - public void testhst_bh_005() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "005.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testhst_bh_005() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "005.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "xmlns:xml is an attribute as far as validation is concerned and must be declared" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( true ); + fail("xmlns:xml is an attribute as far as validation is concerned and must be declared"); + } catch (XmlPullParserException e) { + assertTrue(true); } } @@ -183,19 +157,14 @@ public void testhst_bh_005() * NOTE: This test is SKIPPED as MXParser do not supports DOCDECL parsing. */ // @Test - public void testhst_bh_006() - throws IOException - { - try ( Reader reader = new FileReader( new File( testResourcesDir, "006.xml" ) ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testhst_bh_006() throws IOException { + try (Reader reader = new FileReader(new File(testResourcesDir, "006.xml"))) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "xmlns:foo is an attribute as far as validation is concerned and must be declared" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( true ); + fail("xmlns:foo is an attribute as far as validation is concerned and must be declared"); + } catch (XmlPullParserException e) { + assertTrue(true); } } @@ -209,20 +178,15 @@ public void testhst_bh_006() * @throws java.io.IOException if there is an I/O error */ @Test - public void testhst_lhs_007() - throws IOException - { - try ( FileInputStream is = new FileInputStream( new File( testResourcesDir, "007.xml" ) ); - InputStreamReader reader = new InputStreamReader( is, StandardCharsets.UTF_8 ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testhst_lhs_007() throws IOException { + try (FileInputStream is = new FileInputStream(new File(testResourcesDir, "007.xml")); + InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "UTF-8 BOM plus xml decl of iso-8859-1 incompatible" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "UTF-8 BOM plus xml decl of iso-8859-1 is incompatible" ) ); + fail("UTF-8 BOM plus xml decl of iso-8859-1 incompatible"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("UTF-8 BOM plus xml decl of iso-8859-1 is incompatible")); } } @@ -236,20 +200,15 @@ public void testhst_lhs_007() * @throws java.io.IOException if there is an I/O error */ @Test - public void testhst_lhs_008() - throws IOException - { - try ( FileInputStream is = new FileInputStream( new File( testResourcesDir, "008.xml" ) ); - InputStreamReader reader = new InputStreamReader( is, StandardCharsets.UTF_16 ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testhst_lhs_008() throws IOException { + try (FileInputStream is = new FileInputStream(new File(testResourcesDir, "008.xml")); + InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_16)) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "UTF-16 BOM plus xml decl of utf-8 (using UTF-16 coding) incompatible" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "UTF-16 BOM plus xml decl of utf-8 is incompatible" ) ); + fail("UTF-16 BOM plus xml decl of utf-8 (using UTF-16 coding) incompatible"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("UTF-16 BOM plus xml decl of utf-8 is incompatible")); } } @@ -263,21 +222,15 @@ public void testhst_lhs_008() * @throws java.io.IOException if there is an I/O error */ @Test - public void testhst_lhs_009() - throws IOException - { - try ( FileInputStream is = new FileInputStream( new File( testResourcesDir, "009.xml" ) ); - InputStreamReader reader = new InputStreamReader( is, StandardCharsets.UTF_8 ) ) - { - parser.setInput( reader ); - while ( parser.nextToken() != XmlPullParser.END_DOCUMENT ) + public void testhst_lhs_009() throws IOException { + try (FileInputStream is = new FileInputStream(new File(testResourcesDir, "009.xml")); + InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) { + parser.setInput(reader); + while (parser.nextToken() != XmlPullParser.END_DOCUMENT) ; - fail( "UTF-16 BOM plus xml decl of utf-8 (using UTF-8 coding) incompatible" ); - } - catch ( XmlPullParserException e ) - { - assertTrue( e.getMessage().contains( "UTF-16 BOM in a UTF-8 encoded file is incompatible" ) ); + fail("UTF-16 BOM plus xml decl of utf-8 (using UTF-8 coding) incompatible"); + } catch (XmlPullParserException e) { + assertTrue(e.getMessage().contains("UTF-16 BOM in a UTF-8 encoded file is incompatible")); } } - }