diff --git a/pom.xml b/pom.xml
index a84e1cc1..ef9ce4bc 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,5 +1,4 @@
-
-
* This class is public domain (not copyrighted).
* 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 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 When a name path segment is matched against a pattern path segment, the following special characters can be used: Case sensitivity may be turned off if necessary. By default, it is turned on. This will scan a directory called test for .class files, but excludes all files in all proper subdirectories of a
* directory called "modules" 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. Returns the names of the files which were selected out and therefore not ultimately included. The names are relative to the base directory. This involves performing a slow scan if one has not already been
* completed. Returns the names of the 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. 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.
* 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.
@@ -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
* This class is public domain (not copyrighted).
* This class provides basic facilities for manipulating files and file paths. Methods exist to retrieve the components of a typical file path. For example
* There are also methods to {@link #catPath concatenate two paths}, {@link #resolveFile resolve a path relative to a
* File} and {@link #normalize} a path. There are 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. 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" Will concatenate 2 paths. Paths with Thieved from Tomcat sources... Copies a entire directory layout : no files will be copied only directories Copies a entire directory structure. Copies an entire directory structure but only source files with timestamp later than the destinations'. Renames a file, even if that involves crossing file system boundaries. This will remove 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. 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. Describes a match target for SelectorUtils. Significantly more efficient than using strings, since re-evaluation and re-tokenizing is avoided. Checks these MatchPatterns against a specified string. Uses far less string tokenization than any of the alternatives. 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 This method is thread-safe.
@@ -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
*/
- 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 )
* 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 Listnull
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 Listnull
.
* @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( Comparatortrue
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 @@
* 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 null
indicates that the element does not appear in the given {@link Collection}.
- *
+ *
* @param col The collection to count cardinalities for
* @param 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.File.separator
s 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.
* '*' matches zero or more characters
* '?' matches one character.
*
- *
+ *
*
@@ -122,7 +122,7 @@
* System.out.println( files[i] );
* }
*
- *
+ *
* 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 ArrayListfalse
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);
}
/**
* ExceptionUtils
. Protected to discourage instantiation.
*/
- protected ExceptionUtils()
- {
- }
+ protected ExceptionUtils() {}
/**
* 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) {
ListfromIndex
argument is negative or not less than the count
* of Throwable
s 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;
ArrayListThrowable
.
* @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);
List256
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 )
- {
- EntryImplnull
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 extends K, ? extends V> map )
- {
- for ( Entry extends K, ? extends V> entry : map.entrySet() )
- {
- addEntry( entry.getKey(), entry.getValue() );
+ public void putAll(Map extends K, ? extends V> map) {
+ for (Entry extends K, ? extends V> entry : map.entrySet()) {
+ addEntry(entry.getKey(), entry.getValue());
}
}
@@ -307,15 +282,12 @@ public void putAll( Map extends K, ? extends V> map )
* @throws NullPointerException if the key is null
.
*/
@Override
- public V remove( Object key )
- {
- EntryImpltrue
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 EntryImpltrue
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;
+
/**
*
/www/hosted/mysite/index.html
, can be broken into:
*
@@ -94,15 +94,15 @@
*
* File
manager.
*/
- public static File getFile( String fileName )
- {
- return new File( fileName );
+ public static File getFile(String fileName) {
+ return new File(fileName);
}
/**
* 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
* 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 be properly handled.
* /a/b/c + d = /a/b/d
* /a/b/c + ../d = /a/d
*
-
+ *
* 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
*
- *
+ *
* @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
*
- *
+ *
*
*
- *
+ *
* @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, Object> variables, String beginToken, String endToken )
- {
- super( in );
+ public InterpolationFilterReader(Reader in, Map, Object> variables, String beginToken, String endToken) {
+ super(in);
this.variables = variables;
this.beginToken = beginToken;
@@ -133,13 +130,12 @@ public InterpolationFilterReader( Reader in, Map, Object> 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, Mapto
(if it exists), ensure that to
's parent directory exists and move
* from
, which involves deleting from
as well.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.");
}
}
}
/**
* -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 ListString
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 @@
*
* Possible values:
*
@@ -172,39 +167,35 @@ private static Set
*/
- 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$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).
* 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 thefilename
. 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 fromoldPath
. */ - 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 fromoldPath
. */ - 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 withinfilename
. 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 210cb3a6..848ac158 100644 --- a/src/main/java/org/codehaus/plexus/util/PropertyUtils.java +++ b/src/main/java/org/codehaus/plexus/util/PropertyUtils.java @@ -16,13 +16,13 @@ * limitations under the License. */ -import java.util.Objects; -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. @@ -30,36 +30,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 067d41d5..06d7a2d5 100644 --- a/src/main/java/org/codehaus/plexus/util/ReaderFactory.java +++ b/src/main/java/org/codehaus/plexus/util/ReaderFactory.java @@ -16,8 +16,6 @@ * limitations under the License. */ -import org.codehaus.plexus.util.xml.XmlStreamReader; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -28,6 +26,8 @@ import java.nio.charset.Charset; import java.nio.file.Files; +import org.codehaus.plexus.util.xml.XmlStreamReader; + /** * Utility to create Readers from streams, with explicit encoding choice: platform default, XML, or specified. * @@ -43,12 +43,11 @@ * @since 1.4.3 */ @Deprecated -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"; @@ -56,7 +55,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"; @@ -65,7 +64,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"; @@ -73,7 +72,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"; @@ -81,7 +80,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"; @@ -89,7 +88,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"; @@ -97,7 +96,7 @@ public class ReaderFactory /** * Thefile.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. @@ -107,10 +106,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); } /** @@ -121,10 +118,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); } /** @@ -135,10 +130,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); } /** @@ -148,9 +141,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); } /** @@ -161,10 +153,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()); } /** @@ -175,10 +165,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()); } /** @@ -190,10 +178,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); } /** @@ -206,10 +192,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); } /** @@ -221,9 +205,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 ListgetFieldsIncludingSuperclasses( 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 benull
, 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( ComparatorfilenameComparator ); + 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, *
* @@ -110,14 +106,13 @@ public static SelectorUtils getInstance() * @param str The path to match, as a String. Must not bepattern=**\a
andstr=b
will yieldtrue
.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, *
* @@ -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 bepattern=**\a
andstr=b
will yieldtrue
.null
. * @returntrue
if the pattern matches against the string, orfalse
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. * @returntrue
if the pattern matches against the string, orfalse
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 benull
. * @returntrue
if the string matches against the pattern, orfalse
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. * @returntrue
if the string matches against the pattern, orfalse
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) { Listret = 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 { /** **
*/ - public StringUtils() - { - } + public StringUtils() {} // Empty // -------------------------------------------------------------------------- @@ -110,9 +107,8 @@ public StringUtils() * @param str the String to check * @return the trimmed text (neverStringUtils
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. *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 (ornull
) */ - 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 * @returntrue
if the String isnull
, 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 ) * @returntrue
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 ) * @returntrue
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 * @returntrue
if the Strings are equal, case insensitive, or bothnull
*/ - 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] isnull
*/ - 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] isnull
*/ - 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. Ifnull
, 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 isnull
*/ - 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 isnull
*/ - 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 isnull
* @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 isnull
*/ - 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 isnull
*/ - 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 isnull
*/ - 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 isnull
*/ - 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 isnull
*/ - 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 isnull
*/ - 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 isnull
*/ - 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 isnull
*/ - 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 isnull
*/ - 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 isnull
*/ - 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 ifrepeat < 0
* @throws NullPointerException if str isnull
*/ - 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 isnull
*/ - 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 isnull
* @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 isnull
*/ - 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, ornull
* @throws NullPointerException if tag isnull
*/ - 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, ornull
* @throws NullPointerException if open or close isnull
*/ - 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 isnull
* @throws NullPointerException if sub isnull
*/ - 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 * @returntrue
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 * @returntrue
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 * @returntrue
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 * @returntrue
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 * @returntrue
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 * @returntrue
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 * @returntrue
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 ornull
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 ornull
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 atsweepInterval
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 specializedjava.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 correspondingboolean
. */ - 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 parsableshort
. * @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 correspondingshort
. * @throws NumberFormatException if the specified character sequence does not contain a parsableshort
. */ - 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 parsableint
. * @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 correspondingint
. * @throws NumberFormatException if the specified character sequence does not contain a parsableint
. */ - 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 parsablelong
. * @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 correspondinglong
. * @throws NumberFormatException if the specified character sequence does not contain a parsablelong
. */ - 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 parsablefloat
. */ - 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 parsabledouble
. */ - 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 specifiedStringBuffer
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 specifiedStringBuffer
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 specifiedStringBuffer
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 specifiedStringBuffer
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 specifiedStringBuffer
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 specifiedStringBuffer
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 specifiedStringBuffer
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 ) * @returnformat(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 specifiedStringBuffer
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 ) * @returnformat(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 specifiedStringBuffer
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 specifiedStringBuffer
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 theStringBuffer
to append. * @return the specifiedStringBuffer
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 with10
raised at the specified power exponent. @@ -904,33 +754,23 @@ else if ( dotPos > 0 ) * @param E the exponent. * @returnvalue * 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 bd592e38..09d8ca64 100644 --- a/src/main/java/org/codehaus/plexus/util/WriterFactory.java +++ b/src/main/java/org/codehaus/plexus/util/WriterFactory.java @@ -16,8 +16,6 @@ * limitations under the License. */ -import org.codehaus.plexus.util.xml.XmlStreamWriter; - import java.io.File; import java.io.IOException; import java.io.OutputStream; @@ -27,6 +25,8 @@ import java.nio.charset.Charset; import java.nio.file.Files; +import org.codehaus.plexus.util.xml.XmlStreamWriter; + /** * Utility to create Writers, with explicit encoding choice: platform default, XML, or specified. * @@ -40,12 +40,11 @@ * @since 1.4.4 */ @Deprecated -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"; @@ -53,7 +52,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"; @@ -62,7 +61,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"; @@ -70,7 +69,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"; @@ -78,7 +77,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"; @@ -86,7 +85,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"; @@ -94,7 +93,7 @@ public class WriterFactory /** * Thefile.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. @@ -104,10 +103,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); } /** @@ -118,10 +115,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); } /** @@ -131,9 +126,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); } /** @@ -144,10 +138,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()); } /** @@ -159,10 +151,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); } /** @@ -174,9 +164,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
* * @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 Mapsomeelement
must provide a methodcreateAcommandline
which returns an instance * of this class.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 *
* @@ -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); } /** *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 *
* * @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. - * + * *this.createArgument(false)
.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 byaddLine
,addValue
or the argument object. */ - public String[] getArguments() - { - Vectorresult = 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 ListgetSuccessorLabels( 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() * * @returntrue
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() * * @returntrue
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 ornull
* @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(); - Listl = 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.
- * + * **
- * + * * @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); } /** *- 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"The implementation supports indexed, nested and mapped properties.
- * + * **
- * + * * @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- 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"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/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 edd76231..765e536a 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.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -28,6 +24,10 @@ import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.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() { MapdominantMap = 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 - Mapresult0 = 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.
*/ @org.junit.jupiter.api.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.
*/ @org.junit.jupiter.api.Test - public void testIteratorToListWithAPopulatedList() - { + public void testIteratorToListWithAPopulatedList() { Listoriginal = new ArrayList (); - original.add( "en" ); - original.add( "to" ); - original.add( "tre" ); + original.add("en"); + original.add("to"); + original.add("tre"); - List