From 130e5bc69f3f9b293b0ff026fd000d45766f7ff6 Mon Sep 17 00:00:00 2001
From: Tibor Digana File
object, or null
if the URL's protocol
* is not file
*/
- public @Nullable static File toFile( final @Nullable URL url )
+ @Nullable public static File toFile( final @Nullable URL url )
{
if ( url == null || !url.getProtocol().equalsIgnoreCase( "file" ) )
{
@@ -942,7 +942,7 @@ public static void copyURLToFile( @Nonnull final URL source, @Nonnull final File
* null
if too many ..'s.
*/
- public static @Nonnull String normalize( @Nonnull final String path )
+ @Nonnull public static String normalize( @Nonnull final String path )
{
String normalized = path;
// Resolve occurrences of "//" in the normalized path
@@ -1046,7 +1046,7 @@ private static void copyStreamToFile( @Nonnull final @WillClose InputStream sour
* @param filename Absolute or relative file path to resolve.
* @return The canonical File
of filename
.
*/
- public static @Nonnull File resolveFile( final File baseFile, @Nonnull String filename )
+ @Nonnull public static File resolveFile( final File baseFile, @Nonnull String filename )
{
String filenm = filename;
if ( '/' != File.separatorChar )
@@ -2014,7 +2014,7 @@ private static boolean isValidWindowsFileName( @Nonnull File f )
* @param file the file to check
*
*/
- public static boolean isSymbolicLink( final @Nonnull File file )
+ public static boolean isSymbolicLink( @Nonnull final File file )
throws IOException
{
if ( Java7Support.isAtLeastJava7() )
@@ -2032,7 +2032,7 @@ public static boolean isSymbolicLink( final @Nonnull File file )
* always return false for java versions prior to 1.7.
*
*/
- public static boolean isSymbolicLinkForSure( final @Nonnull File file )
+ public static boolean isSymbolicLinkForSure( @Nonnull final File file )
throws IOException
{
return Java7Support.isAtLeastJava7() && Java7Support.isSymLink( file );
@@ -2056,7 +2056,7 @@ public static boolean isSymbolicLinkForSure( final @Nonnull File file )
* @return true if the file is a symbolic link or if we're on some crappy os.
* false if the file is not a symlink or we're not able to detect it.
*/
- static boolean isSymbolicLinkLegacy( final @Nonnull File file )
+ static boolean isSymbolicLinkLegacy( @Nonnull final File file )
throws IOException
{
final File canonical = new File( file.getCanonicalPath() );
diff --git a/src/main/java/org/apache/maven/shared/utils/io/IOUtil.java b/src/main/java/org/apache/maven/shared/utils/io/IOUtil.java
index 04801702..f7ec295f 100644
--- a/src/main/java/org/apache/maven/shared/utils/io/IOUtil.java
+++ b/src/main/java/org/apache/maven/shared/utils/io/IOUtil.java
@@ -133,6 +133,7 @@ private IOUtil()
/**
* Copy bytes from an InputStream
to an OutputStream
.
+ * @throws IOException
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final OutputStream output )
throws IOException
@@ -144,6 +145,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Output
* Copy bytes from an InputStream
to an OutputStream
.
*
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final OutputStream output,
final int bufferSize )
@@ -159,6 +161,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Output
/**
* Copy chars from a Reader
to a Writer
.
+ * @throws IOException
*/
public static void copy( @Nonnull final Reader input, @Nonnull final Writer output )
throws IOException
@@ -170,6 +173,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final Writer outp
* Copy chars from a Reader
to a Writer
.
*
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
public static void copy( @Nonnull final Reader input, @Nonnull final Writer output, final int bufferSize )
throws IOException
@@ -195,6 +199,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final Writer outp
* Copy and convert bytes from an InputStream
to chars on a
* Writer
.
* The platform's default encoding is used for the byte-to-char conversion.
+ * @throws IOException
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final Writer output )
throws IOException
@@ -208,6 +213,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* The platform's default encoding is used for the byte-to-char conversion.
*
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final Writer output, final int bufferSize )
throws IOException
@@ -223,6 +229,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
+ * @throws IOException
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final Writer output,
@Nonnull final String encoding )
@@ -240,6 +247,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* IANA
* Charset Registry for a list of valid encoding types.
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final Writer output,
@Nonnull final String encoding, final int bufferSize )
@@ -255,6 +263,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a String.
* The platform's default encoding is used for the byte-to-char conversion.
+ * @throws IOException
*/
@Nonnull public static String toString( @Nonnull final InputStream input )
throws IOException
@@ -267,6 +276,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* The platform's default encoding is used for the byte-to-char conversion.
*
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
@Nonnull public static String toString( @Nonnull final InputStream input, final int bufferSize )
throws IOException
@@ -282,6 +292,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
+ * @throws IOException
*/
@Nonnull public static String toString( @Nonnull final InputStream input, @Nonnull final String encoding )
throws IOException
@@ -296,6 +307,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* IANA
* Charset Registry for a list of valid encoding types.
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
@Nonnull public static String toString( @Nonnull final InputStream input, @Nonnull final String encoding,
final int bufferSize )
@@ -311,6 +323,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a byte[]
.
+ * @throws IOException
*/
@Nonnull public static byte[] toByteArray( @Nonnull final InputStream input )
throws IOException
@@ -322,6 +335,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* Get the contents of an InputStream
as a byte[]
.
*
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
@Nonnull public static byte[] toByteArray( @Nonnull final InputStream input, final int bufferSize )
throws IOException
@@ -342,6 +356,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Serialize chars from a Reader
to bytes on an OutputStream
, and
* flush the OutputStream
.
+ * @throws IOException
*/
public static void copy( @Nonnull final Reader input, @Nonnull final OutputStream output )
throws IOException
@@ -354,6 +369,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
* flush the OutputStream
.
*
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
public static void copy( @Nonnull final Reader input, @Nonnull final OutputStream output, final int bufferSize )
throws IOException
@@ -370,6 +386,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Get the contents of a Reader
as a String.
+ * @throws IOException
*/
@Nonnull public static String toString( @Nonnull final Reader input )
throws IOException
@@ -381,6 +398,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
* Get the contents of a Reader
as a String.
*
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
@Nonnull public static String toString( @Nonnull final Reader input, final int bufferSize )
throws IOException
@@ -395,6 +413,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Get the contents of a Reader
as a byte[]
.
+ * @throws IOException
*/
@Nonnull public static byte[] toByteArray( @Nonnull final Reader input )
throws IOException
@@ -406,6 +425,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
* Get the contents of a Reader
as a byte[]
.
*
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
@Nonnull public static byte[] toByteArray( @Nonnull final Reader input, final int bufferSize )
throws IOException
@@ -426,6 +446,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Serialize chars from a String
to bytes on an OutputStream
, and
* flush the OutputStream
.
+ * @throws IOException
*/
public static void copy( @Nonnull final String input, @Nonnull final OutputStream output )
throws IOException
@@ -438,6 +459,7 @@ public static void copy( @Nonnull final String input, @Nonnull final OutputStrea
* flush the OutputStream
.
*
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
public static void copy( @Nonnull final String input, @Nonnull final OutputStream output, final int bufferSize )
throws IOException
@@ -455,6 +477,9 @@ public static void copy( @Nonnull final String input, @Nonnull final OutputStrea
/**
* Copy chars from a String
to a Writer
.
+ * @param input
+ * @param output
+ * @throws IOException
*/
public static void copy( @Nonnull final String input, @Nonnull final Writer output )
throws IOException
@@ -467,6 +492,7 @@ public static void copy( @Nonnull final String input, @Nonnull final Writer outp
/**
* Get the contents of a String
as a byte[]
.
+ * @throws IOException
*/
@Nonnull public static byte[] toByteArray( @Nonnull final String input )
throws IOException
@@ -478,6 +504,7 @@ public static void copy( @Nonnull final String input, @Nonnull final Writer outp
* Get the contents of a String
as a byte[]
.
*
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
@Nonnull public static byte[] toByteArray( @Nonnull final String input, final int bufferSize )
throws IOException
@@ -499,6 +526,7 @@ public static void copy( @Nonnull final String input, @Nonnull final Writer outp
* 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.
+ * @throws IOException
*/
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output )
throws IOException
@@ -512,6 +540,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* The platform's default encoding is used for the byte-to-char conversion.
*
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output, final int bufferSize )
throws IOException
@@ -527,6 +556,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
+ * @throws IOException
*/
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output, final String encoding )
throws IOException
@@ -543,6 +573,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* IANA
* Charset Registry for a list of valid encoding types.
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output, @Nonnull final String encoding,
final int bufferSize )
@@ -558,6 +589,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
/**
* Get the contents of a byte[]
as a String.
* The platform's default encoding is used for the byte-to-char conversion.
+ * @throws IOException
*/
@Nonnull public static String toString( @Nonnull final byte[] input )
throws IOException
@@ -570,6 +602,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* The platform's default encoding is used for the byte-to-char conversion.
*
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
@Nonnull public static String toString( @Nonnull final byte[] input, final int bufferSize )
throws IOException
@@ -585,6 +618,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
+ * @throws IOException
*/
@Nonnull public static String toString( @Nonnull final byte[] input, @Nonnull final String encoding )
throws IOException
@@ -599,6 +633,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* IANA
* Charset Registry for a list of valid encoding types.
* @param bufferSize Size of internal buffer to use.
+ * @throws IOException
*/
@Nonnull public static String toString( @Nonnull final byte[] input, @Nonnull final String encoding,
final int bufferSize )
@@ -614,6 +649,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
/**
* Copy bytes from a byte[]
to an OutputStream
.
+ * @throws IOException
*/
public static void copy( @Nonnull final byte[] input, @Nonnull final OutputStream output )
throws IOException
@@ -627,6 +663,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final OutputStrea
* @param input1 the first stream
* @param input2 the second stream
* @return true if the content of the streams are equal or they both don't exist, false otherwise
+ * @throws IOException
*/
public static boolean contentEquals( @Nonnull final InputStream input1, @Nonnull final InputStream input2 )
throws IOException
diff --git a/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java b/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java
index 6d16aeed..a08ac66d 100644
--- a/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java
+++ b/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java
@@ -105,7 +105,7 @@ public static boolean isSymLink( @Nonnull File file )
}
- public static @Nonnull File readSymbolicLink( @Nonnull File symlink )
+ @Nonnull public static File readSymbolicLink( @Nonnull File symlink )
throws IOException
{
try
@@ -145,7 +145,7 @@ public static boolean exists( @Nonnull File file )
}
- public static @Nonnull File createSymbolicLink( @Nonnull File symlink, @Nonnull File target )
+ @Nonnull public static File createSymbolicLink( @Nonnull File symlink, @Nonnull File target )
throws IOException
{
try
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java
index 78fa4f69..212b6c4c 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java
@@ -46,18 +46,36 @@ public class Xpp3DomBuilder
{
private static final boolean DEFAULT_TRIM = true;
+ /**
+ * @param reader {@link Reader}
+ * @return the built dom.
+ * @throws XmlPullParserException
+ */
public static Xpp3Dom build( @WillClose @Nonnull Reader reader )
throws XmlPullParserException
{
return build( reader, DEFAULT_TRIM );
}
+ /**
+ * @param is {@link InputStream}
+ * @param encoding
+ * @return the built dom.
+ * @throws XmlPullParserException
+ */
public static Xpp3Dom build( @WillClose InputStream is, @Nonnull String encoding )
throws XmlPullParserException
{
return build( is, encoding, DEFAULT_TRIM );
}
+ /**
+ * @param is {@link InputStream}
+ * @param encoding The encoding.
+ * @param trim true/false.
+ * @return the built dom.
+ * @throws XmlPullParserException
+ */
public static Xpp3Dom build( @WillClose InputStream is, @Nonnull String encoding, boolean trim )
throws XmlPullParserException
{
@@ -72,6 +90,12 @@ public static Xpp3Dom build( @WillClose InputStream is, @Nonnull String encoding
}
}
+ /**
+ * @param reader {@link Reader}
+ * @param trim true/false.
+ * @return the built dom.
+ * @throws XmlPullParserException
+ */
public static Xpp3Dom build( @WillClose Reader reader, boolean trim )
throws XmlPullParserException
{
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomUtils.java b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomUtils.java
index 6627a958..1b10dc8c 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomUtils.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomUtils.java
@@ -29,16 +29,33 @@
*/
public class Xpp3DomUtils
{
+ /**
+ * @param dominant {@link Xpp3Dom}
+ * @param recessive {@link Xpp3Dom}
+ * @param childMergeOverride true/false.
+ * @return Merged dom.
+ */
public static Xpp3Dom mergeXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive, Boolean childMergeOverride )
{
return dominant != null ? merge( dominant, recessive, childMergeOverride ) : recessive;
}
+ /**
+ * @param dominant {@link Xpp3Dom}
+ * @param recessive {@link Xpp3Dom}
+ * @return Merged dom.
+ */
public static Xpp3Dom mergeXpp3Dom( Xpp3Dom dominant, Xpp3Dom recessive )
{
return dominant != null ? merge( dominant, recessive, null ) : recessive;
}
+ /**
+ * @param dominant {@link Xpp3Dom}
+ * @param recessive {@link Xpp3Dom}
+ * @param childMergeOverride true/false.
+ * @return Merged dom.
+ */
public static Xpp3Dom merge( Xpp3Dom dominant, Xpp3Dom recessive, Boolean childMergeOverride )
{
if ( recessive == null || isCombineSelfOverride( dominant ) )
@@ -130,6 +147,10 @@ private static boolean isMergeChildren( Xpp3Dom dominant )
dominant.getAttribute( Xpp3Dom.CHILDREN_COMBINATION_MODE_ATTRIBUTE ) );
}
+ /**
+ * @param str The string to be checked.
+ * @return true
in case string is empty false
otherwise.
+ */
public static boolean isEmpty( String str )
{
return str == null || str.trim().length() == 0;
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomWriter.java b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomWriter.java
index 293814a9..9acf23c4 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomWriter.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomWriter.java
@@ -27,21 +27,38 @@
*/
public class Xpp3DomWriter
{
+ /**
+ * @param writer {@link Writer}
+ * @param dom {@link Xpp3Dom}
+ */
public static void write( Writer writer, Xpp3Dom dom )
{
write( new PrettyPrintXMLWriter( writer ), dom );
}
+ /**
+ * @param writer {@link PrintWriter}
+ * @param dom {@link Xpp3Dom}
+ */
public static void write( PrintWriter writer, Xpp3Dom dom )
{
write( new PrettyPrintXMLWriter( writer ), dom );
}
+ /**
+ * @param xmlWriter {@link XMLWriter}
+ * @param dom {@link Xpp3Dom}
+ */
public static void write( XMLWriter xmlWriter, Xpp3Dom dom )
{
write( xmlWriter, dom, true );
}
+ /**
+ * @param xmlWriter {@link XMLWriter}
+ * @param dom {@link Xpp3Dom}
+ * @param escape true/false.
+ */
public static void write( XMLWriter xmlWriter, Xpp3Dom dom, boolean escape )
{
xmlWriter.startElement( dom.getName() );
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/pull/XmlPullParserException.java b/src/main/java/org/apache/maven/shared/utils/xml/pull/XmlPullParserException.java
index 5d6d2c3b..3858a902 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/pull/XmlPullParserException.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/pull/XmlPullParserException.java
@@ -30,16 +30,30 @@ public class XmlPullParserException
extends RuntimeException
{
+ /**
+ *
+ */
+ private static final long serialVersionUID = 117075811816936575L;
+
+ /**
+ * @param e IOException.
+ */
public XmlPullParserException( IOException e )
{
super( e );
}
+ /**
+ * @param e The exception.
+ */
public XmlPullParserException( SAXException e )
{
super( e );
}
+ /**
+ * @param message The message.
+ */
public XmlPullParserException( String message )
{
super( message );
From b281989451fdf81f4f7e9143864182d39047ce6e Mon Sep 17 00:00:00 2001
From: Karl Heinz Marbaise null
*/
- @SuppressWarnings( "ConstantConditions" )
@Nonnull public static String overlayString( @Nonnull String text, @Nonnull String overlay, int start, int end )
{
if ( overlay == null )
@@ -2480,7 +2478,6 @@ else if ( s.charAt( i ) == '\n' )
* false if not or null
string input
*
*/
- @SuppressWarnings( "ConstantConditions" )
public static boolean contains( @Nullable String str, char searchChar )
{
return !isEmpty( str ) && str.indexOf( searchChar ) >= 0;
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/CommandLineTimeOutException.java b/src/main/java/org/apache/maven/shared/utils/cli/CommandLineTimeOutException.java
index 0cd9777a..fa9deeb4 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/CommandLineTimeOutException.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/CommandLineTimeOutException.java
@@ -28,6 +28,11 @@ public class CommandLineTimeOutException
extends CommandLineException
{
+ /**
+ *
+ */
+ private static final long serialVersionUID = 7322428741683224481L;
+
/**
* @param message
* @param cause
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/CommandLineUtils.java b/src/main/java/org/apache/maven/shared/utils/cli/CommandLineUtils.java
index ac5a108f..764d5d2c 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/CommandLineUtils.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/CommandLineUtils.java
@@ -44,7 +44,6 @@ public abstract class CommandLineUtils
/**
*
*/
- @SuppressWarnings( "UnusedDeclaration" )
public static class StringStreamConsumer
implements StreamConsumer
{
@@ -82,14 +81,12 @@ public void run()
}
- @SuppressWarnings( "UnusedDeclaration" )
public static int executeCommandLine( @Nonnull Commandline cl, StreamConsumer systemOut, StreamConsumer systemErr )
throws CommandLineException
{
return executeCommandLine( cl, null, systemOut, systemErr, 0 );
}
- @SuppressWarnings( "UnusedDeclaration" )
public static int executeCommandLine( @Nonnull Commandline cl, StreamConsumer systemOut, StreamConsumer systemErr,
int timeoutInSeconds )
throws CommandLineException
@@ -97,7 +94,6 @@ public static int executeCommandLine( @Nonnull Commandline cl, StreamConsumer sy
return executeCommandLine( cl, null, systemOut, systemErr, timeoutInSeconds );
}
- @SuppressWarnings( "UnusedDeclaration" )
public static int executeCommandLine( @Nonnull Commandline cl, InputStream systemIn, StreamConsumer systemOut,
StreamConsumer systemErr )
throws CommandLineException
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/XMLEncode.java b/src/main/java/org/apache/maven/shared/utils/xml/XMLEncode.java
index 8d8c9f67..0d6ecd16 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/XMLEncode.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/XMLEncode.java
@@ -375,25 +375,4 @@ private static char lookAhead( int la, int offset, String data )
}
}
- // combine multiple checks in one methods for speed
- private static boolean contains( String text, char[] chars )
- {
- if ( text == null || chars == null || chars.length == 0 )
- {
- return false;
- }
- for ( int i = 0; i < text.length(); i++ )
- {
- char c = text.charAt( i );
- for ( char aChar : chars )
- {
- if ( aChar == c )
- {
- return true;
- }
- }
- }
- return false;
- }
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java b/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java
index ecced002..f1bc0c6f 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java
@@ -36,6 +36,11 @@
class XmlReaderException
extends IOException
{
+ /**
+ *
+ */
+ private static final long serialVersionUID = 5044326391409597950L;
+
private final String bomEncoding;
private final String xmlGuessEncoding;
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReader.java b/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReader.java
index f5da0400..a05f17b4 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReader.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReader.java
@@ -36,17 +36,16 @@ public class XmlStreamReader
{
private final org.apache.commons.io.input.XmlStreamReader reader;
- @SuppressWarnings( "checkstyle:staticvariablename" )
- private static String _staticDefaultEncoding = null;
+ private static String staticDefaultEncoding = null;
public static void setDefaultEncoding( String encoding )
{
- _staticDefaultEncoding = encoding;
+ staticDefaultEncoding = encoding;
}
public static String getDefaultEncoding()
{
- return _staticDefaultEncoding;
+ return staticDefaultEncoding;
}
public XmlStreamReader( File file )
@@ -64,7 +63,7 @@ public XmlStreamReader( InputStream is )
public XmlStreamReader( InputStream is, boolean lenient )
throws IOException, XmlStreamReaderException
{
- reader = new org.apache.commons.io.input.XmlStreamReader( is, lenient, _staticDefaultEncoding );
+ reader = new org.apache.commons.io.input.XmlStreamReader( is, lenient, staticDefaultEncoding );
}
public XmlStreamReader( URL url )
@@ -76,7 +75,7 @@ public XmlStreamReader( URL url )
public XmlStreamReader( URLConnection conn )
throws IOException
{
- reader = new org.apache.commons.io.input.XmlStreamReader( conn, _staticDefaultEncoding );
+ reader = new org.apache.commons.io.input.XmlStreamReader( conn, staticDefaultEncoding );
}
public XmlStreamReader( InputStream is, String httpContentType )
@@ -90,7 +89,7 @@ public XmlStreamReader( InputStream is, String httpContentType, boolean lenient,
{
reader = new org.apache.commons.io.input.XmlStreamReader( is, httpContentType, lenient,
( defaultEncoding == null )
- ? _staticDefaultEncoding
+ ? staticDefaultEncoding
: defaultEncoding );
}
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java b/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java
index 65251d5c..f1fbb1a3 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java
@@ -37,6 +37,11 @@
class XmlStreamReaderException
extends XmlReaderException
{
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1007947701939672080L;
+
/**
* Creates an exception instance if the charset encoding could not be determined.
*
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java
index aef182b7..5cb63233 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java
@@ -37,7 +37,6 @@
public class Xpp3Dom
implements Iterable
Quote and escape a String with the given character, handling null
.
addLine
,
* addValue
or the argument object.
+ * @return an array of arguments.
*/
public String[] getArguments()
{
@@ -299,6 +313,7 @@ public String[] getArguments()
* addValue
or the argument object.
*
* @param mask flag to mask any arguments (having his {@code mask} field to {@code true}).
+ * @return an array of arguments.
*/
public String[] getArguments( boolean mask )
{
@@ -328,12 +343,16 @@ public String[] getArguments( boolean mask )
return result.toArray( new String[result.size()] );
}
+ /** {@inheritDoc}
+ */
public String toString()
{
return StringUtils.join( getShellCommandline( true ), " " );
}
+ /** {@inheritDoc}
+ */
public Object clone()
{
throw new RuntimeException( "Do we ever clone a commandline?" );
@@ -343,7 +362,8 @@ public Object clone()
}
/**
- * Sets execution directory.
+ * Sets working directory.
+ * @param path The to be set as working directory.
*/
public void setWorkingDirectory( String path )
{
@@ -352,12 +372,16 @@ public void setWorkingDirectory( String path )
/**
* Sets execution directory.
+ * @param workingDirectory The working directory.
*/
public void setWorkingDirectory( File workingDirectory )
{
shell.setWorkingDirectory( workingDirectory );
}
+ /**
+ * @return The working directory.
+ */
public File getWorkingDirectory()
{
return shell.getWorkingDirectory();
@@ -373,6 +397,8 @@ public void clearArgs()
/**
* Executes the command.
+ * @return The process.
+ * @throws CommandLineException in case of errors.
*/
public Process execute()
throws CommandLineException
@@ -427,6 +453,7 @@ void setShell( Shell shell )
/**
* Get the shell to be used in this command line.
+ * @return the shell.
*/
public Shell getShell()
{
@@ -489,11 +516,17 @@ public void setMask( boolean mask )
this.mask = mask;
}
+ /**
+ * @return The parts.
+ */
private String[] getParts()
{
return parts;
}
+ /**
+ * @return true/false
+ */
public boolean isMask()
{
return mask;
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/DefaultConsumer.java b/src/main/java/org/apache/maven/shared/utils/cli/DefaultConsumer.java
index db75f534..040b8adf 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/DefaultConsumer.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/DefaultConsumer.java
@@ -26,6 +26,7 @@
public class DefaultConsumer
implements StreamConsumer
{
+ /** {@inheritDoc} */
public void consumeLine( String line )
{
System.out.println( line );
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/ShutdownHookUtils.java b/src/main/java/org/apache/maven/shared/utils/cli/ShutdownHookUtils.java
index 9ce64657..d1ea5686 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/ShutdownHookUtils.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/ShutdownHookUtils.java
@@ -32,6 +32,9 @@
public class ShutdownHookUtils
{
+ /**
+ * @param hook The thread hook.
+ */
public static void addShutDownHook( Thread hook )
{
try
@@ -48,6 +51,9 @@ public static void addShutDownHook( Thread hook )
}
}
+ /**
+ * @param hook The hook which should be removed.
+ */
public static void removeShutdownHook( Thread hook )
{
try
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java b/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java
index c460ad9f..dc6802b8 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java
@@ -34,6 +34,7 @@ public interface StreamConsumer
{
/**
* Called when the StreamPumper pumps a line from the Stream.
+ * @param line The line to be consumed.
*/
void consumeLine( String line );
}
diff --git a/src/main/java/org/apache/maven/shared/utils/cli/StreamPumper.java b/src/main/java/org/apache/maven/shared/utils/cli/StreamPumper.java
index 3118a642..5bed568c 100644
--- a/src/main/java/org/apache/maven/shared/utils/cli/StreamPumper.java
+++ b/src/main/java/org/apache/maven/shared/utils/cli/StreamPumper.java
@@ -32,12 +32,10 @@
import org.apache.maven.shared.utils.io.IOUtil;
/**
- * Class to pump the error stream during Process's runtime. Copied from the Ant
- * built-in task.
+ * Class to pump the error stream during Process's runtime. Copied from the Ant built-in task.
*
* @author Florin Vancea
* @author Paul Julius
- *
*/
public class StreamPumper
extends AbstractStreamHandler
@@ -52,16 +50,30 @@ public class StreamPumper
private static final int SIZE = 1024;
+ /**
+ * @param in {@link InputStream}
+ * @param consumer {@link StreamConsumer}
+ */
public StreamPumper( InputStream in, StreamConsumer consumer )
{
this( new InputStreamReader( in ), null, consumer );
}
- public StreamPumper( InputStream in, StreamConsumer consumer, @Nullable Charset charset )
+ /**
+ * @param in {@link InputStream}
+ * @param consumer {@link StreamConsumer}
+ * @param charset {@link Charset}
+ */
+ public StreamPumper( InputStream in, StreamConsumer consumer, @Nullable Charset charset )
{
this( null == charset ? new InputStreamReader( in ) : new InputStreamReader( in, charset ), null, consumer );
}
+ /**
+ * @param in {@link Writer}
+ * @param writer {@link PrintWriter}
+ * @param consumer {@link StreamConsumer}
+ */
private StreamPumper( Reader in, PrintWriter writer, StreamConsumer consumer )
{
this.in = new BufferedReader( in, SIZE );
@@ -69,6 +81,7 @@ private StreamPumper( Reader in, PrintWriter writer, StreamConsumer consumer )
this.consumer = consumer;
}
+ /** run it. */
public void run()
{
try
@@ -113,6 +126,9 @@ public void run()
}
}
+ /**
+ * flush.
+ */
public void flush()
{
if ( out != null )
@@ -121,11 +137,17 @@ public void flush()
}
}
+ /**
+ * Close it.
+ */
public void close()
{
IOUtil.close( out );
}
+ /**
+ * @return {@link Exception}
+ */
public Exception getException()
{
return exception;
diff --git a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java
index 91415bcc..748466e0 100644
--- a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java
+++ b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java
@@ -281,11 +281,11 @@ public File getBasedir()
/**
* Sets whether or not the file system should be regarded as case sensitive.
*
- * @param isCaseSensitive whether or not the file system should be regarded as a case sensitive one
+ * @param isCaseSensitiveParameter whether or not the file system should be regarded as a case sensitive one
*/
- public void setCaseSensitive( final boolean isCaseSensitive )
+ public void setCaseSensitive( final boolean isCaseSensitiveParameter )
{
- this.isCaseSensitive = isCaseSensitive;
+ this.isCaseSensitive = isCaseSensitiveParameter;
}
/**
@@ -360,6 +360,9 @@ public void setExcludes( final String... excludes )
}
}
+ /**
+ * @param scanConductor {@link #scanConductor}
+ */
public void setScanConductor( final ScanConductor scanConductor )
{
this.scanConductor = scanConductor;
@@ -443,6 +446,7 @@ public void scan()
* {@link DirectoryScanResult#getFilesAdded()} and {@link DirectoryScanResult#getFilesRemoved()}
*
* @param oldFiles the list of previously captured files names.
+ * @return the result of the directory scan.
*/
public DirectoryScanResult diffIncludedFiles( String... oldFiles )
{
@@ -455,6 +459,11 @@ public DirectoryScanResult diffIncludedFiles( String... oldFiles )
return diffFiles( oldFiles, filesIncluded.toArray( new String[filesIncluded.size()] ) );
}
+ /**
+ * @param oldFiles array of old files.
+ * @param newFiles array of new files.
+ * @return calculated differerence.
+ */
public static DirectoryScanResult diffFiles( @Nullable String[] oldFiles, @Nullable String[] newFiles )
{
SetFile
object, or null
if the URL's protocol
* is not file
*/
- @Nullable public static File toFile( final @Nullable URL url )
+ @Nullable public static File toFile( @Nullable final URL url )
{
if ( url == null || !url.getProtocol().equalsIgnoreCase( "file" ) )
{
@@ -1179,6 +1182,10 @@ public static void delete( @Nonnull File file )
}
}
+ /**
+ * @param file The file.
+ * @return true / false
+ */
public static boolean deleteLegacyStyle( @Nonnull File file )
{
if ( Java7Support.isAtLeastJava7() )
@@ -1428,7 +1435,7 @@ public static long sizeOfDirectory( @Nonnull final File directory )
* @param includes the includes pattern, comma separated
* @param excludes the excludes pattern, comma separated
* @return a list of File objects
- * @throws IOException
+ * @throws IOException in case of failure.
* @see #getFileNames(File, String, String, boolean)
*/
@Nonnull
@@ -1446,7 +1453,7 @@ public static ListReader
to a Writer
.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final Reader input, @Nonnull final Writer output )
throws IOException
@@ -173,7 +173,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final Writer outp
* Copy chars from a Reader
to a Writer
.
*
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final Reader input, @Nonnull final Writer output, final int bufferSize )
throws IOException
@@ -199,7 +199,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final Writer outp
* Copy and convert bytes from an InputStream
to chars on a
* Writer
.
* The platform's default encoding is used for the byte-to-char conversion.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final Writer output )
throws IOException
@@ -213,7 +213,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* The platform's default encoding is used for the byte-to-char conversion.
*
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final Writer output, final int bufferSize )
throws IOException
@@ -229,7 +229,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final Writer output,
@Nonnull final String encoding )
@@ -247,7 +247,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* IANA
* Charset Registry for a list of valid encoding types.
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final Writer output,
@Nonnull final String encoding, final int bufferSize )
@@ -263,7 +263,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a String.
* The platform's default encoding is used for the byte-to-char conversion.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final InputStream input )
throws IOException
@@ -276,7 +276,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* The platform's default encoding is used for the byte-to-char conversion.
*
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final InputStream input, final int bufferSize )
throws IOException
@@ -292,7 +292,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final InputStream input, @Nonnull final String encoding )
throws IOException
@@ -307,7 +307,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* IANA
* Charset Registry for a list of valid encoding types.
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final InputStream input, @Nonnull final String encoding,
final int bufferSize )
@@ -323,7 +323,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a byte[]
.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static byte[] toByteArray( @Nonnull final InputStream input )
throws IOException
@@ -335,7 +335,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* Get the contents of an InputStream
as a byte[]
.
*
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static byte[] toByteArray( @Nonnull final InputStream input, final int bufferSize )
throws IOException
@@ -356,7 +356,7 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Serialize chars from a Reader
to bytes on an OutputStream
, and
* flush the OutputStream
.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final Reader input, @Nonnull final OutputStream output )
throws IOException
@@ -369,7 +369,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
* flush the OutputStream
.
*
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final Reader input, @Nonnull final OutputStream output, final int bufferSize )
throws IOException
@@ -386,7 +386,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Get the contents of a Reader
as a String.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final Reader input )
throws IOException
@@ -398,7 +398,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
* Get the contents of a Reader
as a String.
*
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final Reader input, final int bufferSize )
throws IOException
@@ -413,7 +413,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Get the contents of a Reader
as a byte[]
.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static byte[] toByteArray( @Nonnull final Reader input )
throws IOException
@@ -425,7 +425,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
* Get the contents of a Reader
as a byte[]
.
*
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static byte[] toByteArray( @Nonnull final Reader input, final int bufferSize )
throws IOException
@@ -446,7 +446,7 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Serialize chars from a String
to bytes on an OutputStream
, and
* flush the OutputStream
.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final String input, @Nonnull final OutputStream output )
throws IOException
@@ -459,7 +459,7 @@ public static void copy( @Nonnull final String input, @Nonnull final OutputStrea
* flush the OutputStream
.
*
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final String input, @Nonnull final OutputStream output, final int bufferSize )
throws IOException
@@ -477,9 +477,9 @@ public static void copy( @Nonnull final String input, @Nonnull final OutputStrea
/**
* Copy chars from a String
to a Writer
.
- * @param input
- * @param output
- * @throws IOException
+ * @param input Input string.
+ * @param output resulting output {@link Writer}
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final String input, @Nonnull final Writer output )
throws IOException
@@ -492,7 +492,7 @@ public static void copy( @Nonnull final String input, @Nonnull final Writer outp
/**
* Get the contents of a String
as a byte[]
.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static byte[] toByteArray( @Nonnull final String input )
throws IOException
@@ -504,7 +504,7 @@ public static void copy( @Nonnull final String input, @Nonnull final Writer outp
* Get the contents of a String
as a byte[]
.
*
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static byte[] toByteArray( @Nonnull final String input, final int bufferSize )
throws IOException
@@ -526,7 +526,7 @@ public static void copy( @Nonnull final String input, @Nonnull final Writer outp
* 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.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output )
throws IOException
@@ -540,7 +540,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* The platform's default encoding is used for the byte-to-char conversion.
*
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output, final int bufferSize )
throws IOException
@@ -556,7 +556,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output, final String encoding )
throws IOException
@@ -573,7 +573,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* IANA
* Charset Registry for a list of valid encoding types.
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output, @Nonnull final String encoding,
final int bufferSize )
@@ -589,7 +589,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
/**
* Get the contents of a byte[]
as a String.
* The platform's default encoding is used for the byte-to-char conversion.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final byte[] input )
throws IOException
@@ -602,7 +602,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* The platform's default encoding is used for the byte-to-char conversion.
*
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final byte[] input, final int bufferSize )
throws IOException
@@ -618,7 +618,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final byte[] input, @Nonnull final String encoding )
throws IOException
@@ -633,7 +633,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* IANA
* Charset Registry for a list of valid encoding types.
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final byte[] input, @Nonnull final String encoding,
final int bufferSize )
@@ -649,7 +649,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
/**
* Copy bytes from a byte[]
to an OutputStream
.
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static void copy( @Nonnull final byte[] input, @Nonnull final OutputStream output )
throws IOException
@@ -663,7 +663,7 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final OutputStrea
* @param input1 the first stream
* @param input2 the second stream
* @return true if the content of the streams are equal or they both don't exist, false otherwise
- * @throws IOException
+ * @throws IOException in case of failure.
*/
public static boolean contentEquals( @Nonnull final InputStream input1, @Nonnull final InputStream input2 )
throws IOException
From df6023b60f6117554b07d82500546c186deb621e Mon Sep 17 00:00:00 2001
From: Karl Heinz Marbaise Note: we kept this protected method for the sake of backward compatibility!
* - * @param srcFile - * @param dest - * @throws Exception + * @param srcFile The source file. + * @param destination The destination. + * @throws Exception In case of failure. */ - void expandFile( File srcFile, File dest ) + void expandFile( File srcFile, File destination ) throws Exception { if ( source == null ) @@ -117,7 +117,7 @@ void expandFile( File srcFile, File dest ) throw new NullPointerException( "Source Archive must not be null!" ); } - File destDir = dest; + File destDir = destination; if ( destDir == null ) { destDir = new File( System.getProperty( "user.dir" ) ); diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java index d26aa0dc..8c1c525a 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java @@ -126,6 +126,9 @@ public JavaToolResult execute( Request request ) return result; } + /** + * @return {@link InputStream} + */ protected InputStream createSystemInputStream() { InputStream systemIn = new InputStream() @@ -143,6 +146,11 @@ public int read() return systemIn; } + /** + * @param cli {@link Commandline} + * @param request {@link Request} + * @return {@link JavaToolRequest} + */ protected JavaToolResult executeCommandLine( Commandline cli, Request request ) { if ( getLogger().isDebugEnabled() ) @@ -174,6 +182,10 @@ protected JavaToolResult executeCommandLine( Commandline cli, Request request ) return result; } + /** + * @param request {@link Request} + * @return {@link StreamConsumer} + */ protected StreamConsumer createSystemErrorStreamConsumer( Request request ) { StreamConsumer systemErr = request.getSystemErrorStreamConsumer(); @@ -196,6 +208,10 @@ public void consumeLine( final String line ) return systemErr; } + /** + * @param request {@link Request} + * @return {@link StreamConsumer} + */ protected StreamConsumer createSystemOutStreamConsumer( Request request ) { StreamConsumer systemOut = request.getSystemOutStreamConsumer(); diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java index 0bb3d760..7c27ac19 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java @@ -33,6 +33,9 @@ public class CmdShell extends Shell { + /** + * Create an instance of CmdShell. + */ public CmdShell() { setShellCommand( "cmd.exe" ); diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java index a26e7dae..dcee0466 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java @@ -31,6 +31,9 @@ public class CommandShell extends Shell { + /** + * Create an instance. + */ public CommandShell() { setShellCommand( "command.com" ); diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java index b2dfe9fc..58096109 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java @@ -116,26 +116,26 @@ String[] getShellArgs() /** * Get the command line for the provided executable and arguments in this shell * - * @param executable executable that the shell has to call - * @param arguments arguments for the executable, not the shell + * @param executableParameter executable that the shell has to call + * @param argumentsParameter arguments for the executable, not the shell * @return List with one String object with executable and arguments quoted as needed */ - ListInputStream
to an OutputStream
.
- * @throws IOException
+ * @param input The input size.
+ * @param output The resulting output.
+ * @throws IOException in case of an error.
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final OutputStream output )
throws IOException
@@ -144,8 +146,10 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Output
/**
* Copy bytes from an InputStream
to an OutputStream
.
*
+ * @param input The input size.
+ * @param output The resulting output.
* @param bufferSize Size of internal buffer to use.
- * @throws IOException
+ * @throws IOException in case of an error.
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final OutputStream output,
final int bufferSize )
@@ -161,6 +165,8 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Output
/**
* Copy chars from a Reader
to a Writer
.
+ * @param input The input size.
+ * @param output The resulting output.
* @throws IOException in case of failure.
*/
public static void copy( @Nonnull final Reader input, @Nonnull final Writer output )
@@ -172,6 +178,8 @@ public static void copy( @Nonnull final Reader input, @Nonnull final Writer outp
/**
* Copy chars from a Reader
to a Writer
.
*
+ * @param input The input size.
+ * @param output The resulting output.
* @param bufferSize Size of internal buffer to use.
* @throws IOException in case of failure.
*/
@@ -199,6 +207,8 @@ public static void copy( @Nonnull final Reader input, @Nonnull final Writer outp
* Copy and convert bytes from an InputStream
to chars on a
* Writer
.
* The platform's default encoding is used for the byte-to-char conversion.
+ * @param input The input size.
+ * @param output The resulting output.
* @throws IOException in case of failure.
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final Writer output )
@@ -212,6 +222,8 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* Writer
.
* The platform's default encoding is used for the byte-to-char conversion.
*
+ * @param input The input size.
+ * @param output The resulting output.
* @param bufferSize Size of internal buffer to use.
* @throws IOException in case of failure.
*/
@@ -226,6 +238,8 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* Copy and convert bytes from an InputStream
to chars on a
* Writer
, using the specified encoding.
*
+ * @param input The input size.
+ * @param output The resulting output.
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
@@ -246,6 +260,8 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
+ * @param input The input size.
+ * @param output The resulting output.
* @param bufferSize Size of internal buffer to use.
* @throws IOException in case of failure.
*/
@@ -263,6 +279,8 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a String.
* The platform's default encoding is used for the byte-to-char conversion.
+ * @param input The input size.
+ * @return The resulting string.
* @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final InputStream input )
@@ -275,7 +293,9 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* Get the contents of an InputStream
as a String.
* The platform's default encoding is used for the byte-to-char conversion.
*
+ * @param input The input size.
* @param bufferSize Size of internal buffer to use.
+ * @return the resulting string.
* @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final InputStream input, final int bufferSize )
@@ -289,9 +309,11 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a String.
*
+ * @param input The input size.
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
+ * @return the converted string.
* @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final InputStream input, @Nonnull final String encoding )
@@ -303,10 +325,12 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a String.
*
+ * @param input The input size.
* @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.
+ * @return The converted string.
* @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final InputStream input, @Nonnull final String encoding,
@@ -323,6 +347,8 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a byte[]
.
+ * @param input The input size.
+ * @return the resulting byte array.
* @throws IOException in case of failure.
*/
@Nonnull public static byte[] toByteArray( @Nonnull final InputStream input )
@@ -334,7 +360,9 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a byte[]
.
*
+ * @param input The input size.
* @param bufferSize Size of internal buffer to use.
+ * @return the resulting byte array.
* @throws IOException in case of failure.
*/
@Nonnull public static byte[] toByteArray( @Nonnull final InputStream input, final int bufferSize )
@@ -356,6 +384,8 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Serialize chars from a Reader
to bytes on an OutputStream
, and
* flush the OutputStream
.
+ * @param input The input size.
+ * @param output The resulting output.
* @throws IOException in case of failure.
*/
public static void copy( @Nonnull final Reader input, @Nonnull final OutputStream output )
@@ -368,6 +398,8 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
* Serialize chars from a Reader
to bytes on an OutputStream
, and
* flush the OutputStream
.
*
+ * @param input The input size.
+ * @param output The resulting output.
* @param bufferSize Size of internal buffer to use.
* @throws IOException in case of failure.
*/
@@ -386,6 +418,8 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Get the contents of a Reader
as a String.
+ * @param input The input size.
+ * @return The converted string.
* @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final Reader input )
@@ -397,7 +431,9 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Get the contents of a Reader
as a String.
*
+ * @param input The input size.
* @param bufferSize Size of internal buffer to use.
+ * @return the resulting byte array.
* @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final Reader input, final int bufferSize )
@@ -413,6 +449,8 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Get the contents of a Reader
as a byte[]
.
+ * @param input The input size.
+ * @return the resulting byte array.
* @throws IOException in case of failure.
*/
@Nonnull public static byte[] toByteArray( @Nonnull final Reader input )
@@ -424,7 +462,9 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Get the contents of a Reader
as a byte[]
.
*
+ * @param input The input size.
* @param bufferSize Size of internal buffer to use.
+ * @return the resulting byte array.
* @throws IOException in case of failure.
*/
@Nonnull public static byte[] toByteArray( @Nonnull final Reader input, final int bufferSize )
@@ -446,6 +486,8 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Serialize chars from a String
to bytes on an OutputStream
, and
* flush the OutputStream
.
+ * @param input The input size.
+ * @param output The resulting output.
* @throws IOException in case of failure.
*/
public static void copy( @Nonnull final String input, @Nonnull final OutputStream output )
@@ -458,6 +500,8 @@ public static void copy( @Nonnull final String input, @Nonnull final OutputStrea
* Serialize chars from a String
to bytes on an OutputStream
, and
* flush the OutputStream
.
*
+ * @param input The input size.
+ * @param output The resulting output.
* @param bufferSize Size of internal buffer to use.
* @throws IOException in case of failure.
*/
@@ -492,6 +536,8 @@ public static void copy( @Nonnull final String input, @Nonnull final Writer outp
/**
* Get the contents of a String
as a byte[]
.
+ * @param input The input size.
+ * @return The resulting byte array.
* @throws IOException in case of failure.
*/
@Nonnull public static byte[] toByteArray( @Nonnull final String input )
@@ -503,7 +549,9 @@ public static void copy( @Nonnull final String input, @Nonnull final Writer outp
/**
* Get the contents of a String
as a byte[]
.
*
+ * @param input The input size.
* @param bufferSize Size of internal buffer to use.
+ * @return The resulting byte array.
* @throws IOException in case of failure.
*/
@Nonnull public static byte[] toByteArray( @Nonnull final String input, final int bufferSize )
@@ -526,6 +574,8 @@ public static void copy( @Nonnull final String input, @Nonnull final Writer outp
* 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 The input size.
+ * @param output The resulting output.
* @throws IOException in case of failure.
*/
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output )
@@ -539,6 +589,8 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* Writer
.
* The platform's default encoding is used for the byte-to-char conversion.
*
+ * @param input The input size.
+ * @param output The resulting output.
* @param bufferSize Size of internal buffer to use.
* @throws IOException in case of failure.
*/
@@ -556,6 +608,8 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
+ * @param input The input size.
+ * @param output The resulting output.
* @throws IOException in case of failure.
*/
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output, final String encoding )
@@ -572,6 +626,8 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
+ * @param input The input bytes.
+ * @param output The output buffer {@link Writer}
* @param bufferSize Size of internal buffer to use.
* @throws IOException in case of failure.
*/
@@ -589,6 +645,8 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
/**
* Get the contents of a byte[]
as a String.
* The platform's default encoding is used for the byte-to-char conversion.
+ * @param input The input bytes.
+ * @return The resulting string.
* @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final byte[] input )
@@ -602,6 +660,8 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* The platform's default encoding is used for the byte-to-char conversion.
*
* @param bufferSize Size of internal buffer to use.
+ * @param input The input bytes.
+ * @return The created string.
* @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final byte[] input, final int bufferSize )
@@ -618,6 +678,8 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* @param encoding The name of a supported character encoding. See the
* IANA
* Charset Registry for a list of valid encoding types.
+ * @param input The input bytes.
+ * @return The resulting string.
* @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final byte[] input, @Nonnull final String encoding )
@@ -633,6 +695,8 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* IANA
* Charset Registry for a list of valid encoding types.
* @param bufferSize Size of internal buffer to use.
+ * @param input Input bytes.
+ * @return The resulting string.
* @throws IOException in case of failure.
*/
@Nonnull public static String toString( @Nonnull final byte[] input, @Nonnull final String encoding,
@@ -649,6 +713,8 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
/**
* Copy bytes from a byte[]
to an OutputStream
.
+ * @param input Input byte array.
+ * @param output output stream {@link OutputStream}
* @throws IOException in case of failure.
*/
public static void copy( @Nonnull final byte[] input, @Nonnull final OutputStream output )
diff --git a/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java b/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java
index a08ac66d..550de2f4 100644
--- a/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java
+++ b/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java
@@ -87,6 +87,10 @@ public class Java7Support
IS_JAVA7 = isJava7x;
}
+ /**
+ * @param file The file to check for being a symbolic link.
+ * @return true if the file is a symlink false otherwise.
+ */
public static boolean isSymLink( @Nonnull File file )
{
try
@@ -105,6 +109,11 @@ public static boolean isSymLink( @Nonnull File file )
}
+ /**
+ * @param symlink The sym link.
+ * @return The file.
+ * @throws IOException in case of error.
+ */
@Nonnull public static File readSymbolicLink( @Nonnull File symlink )
throws IOException
{
@@ -125,6 +134,11 @@ public static boolean isSymLink( @Nonnull File file )
}
+ /**
+ * @param file The file to check.
+ * @return true if exist false otherwise.
+ * @throws IOException in case of failure.
+ */
public static boolean exists( @Nonnull File file )
throws IOException
{
@@ -145,6 +159,12 @@ public static boolean exists( @Nonnull File file )
}
+ /**
+ * @param symlink The link name.
+ * @param target The target.
+ * @return The linked file.
+ * @throws IOException in case of an error.
+ */
@Nonnull public static File createSymbolicLink( @Nonnull File symlink, @Nonnull File target )
throws IOException
{
@@ -185,7 +205,7 @@ else if ( targetException instanceof RuntimeException )
/**
* Performs a nio delete
* @param file the file to delete
- * @throws IOException
+ * @throws IOException in case of error.
*/
public static void delete( @Nonnull File file )
throws IOException
@@ -205,11 +225,17 @@ public static void delete( @Nonnull File file )
}
}
+ /**
+ * @return true in case of Java 7.
+ */
public static boolean isJava7()
{
return IS_JAVA7;
}
+ /**
+ * @return true in case of Java7 or greater.
+ */
public static boolean isAtLeastJava7()
{
return IS_JAVA7;
diff --git a/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java b/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java
index d5c2c21d..15ad1488 100644
--- a/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java
+++ b/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java
@@ -60,6 +60,11 @@ private MatchPattern( @Nonnull String source, @Nonnull String separator )
}
+ /**
+ * @param str The string to match for.
+ * @param isCaseSensitive case sensitive true false otherwise.
+ * @return true if matches false otherwise.
+ */
public boolean matchPath( String str, boolean isCaseSensitive )
{
if ( regexPattern != null )
@@ -84,6 +89,11 @@ boolean matchPath( String str, String[] strDirs, boolean isCaseSensitive )
}
}
+ /**
+ * @param str The string to check.
+ * @param isCaseSensitive Check case sensitive or not.
+ * @return true in case of matching pattern.
+ */
public boolean matchPatternStart( @Nonnull String str, boolean isCaseSensitive )
{
if ( regexPattern != null )
@@ -101,12 +111,19 @@ public boolean matchPatternStart( @Nonnull String str, boolean isCaseSensitive )
}
}
+ /**
+ * @return Tokenized string.
+ */
public String[] getTokenizedPathString()
{
return tokenized;
}
+ /**
+ * @param string The part which will be checked to start with.
+ * @return true in case of starting with the string false otherwise.
+ */
public boolean startsWith( String string )
{
return source.startsWith( string );
@@ -124,6 +141,10 @@ static String[] tokenizePathToString( @Nonnull String path, @Nonnull String sepa
return ret.toArray( new String[ret.size()] );
}
+ /**
+ * @param source The source.
+ * @return The match pattern.
+ */
public static MatchPattern fromString( String source )
{
return new MatchPattern( source, File.separator );
diff --git a/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java b/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java
index 4ebc699c..8e59f48f 100644
--- a/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java
+++ b/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java
@@ -59,6 +59,11 @@ public boolean matches( @Nonnull String name, boolean isCaseSensitive )
return false;
}
+ /**
+ * @param name The name.
+ * @param isCaseSensitive being case sensetive.
+ * @return true if any of the supplied patterns match start.
+ */
public boolean matchesPatternStart( @Nonnull String name, boolean isCaseSensitive )
{
for ( MatchPattern includesPattern : patterns )
@@ -71,6 +76,10 @@ public boolean matchesPatternStart( @Nonnull String name, boolean isCaseSensitiv
return false;
}
+ /**
+ * @param sources The sources
+ * @return Converted match patterns.
+ */
public static MatchPatterns from( @Nonnull String... sources )
{
final int length = sources.length;
diff --git a/src/main/java/org/apache/maven/shared/utils/io/ScanConductor.java b/src/main/java/org/apache/maven/shared/utils/io/ScanConductor.java
index ec3c5c5a..61d74620 100644
--- a/src/main/java/org/apache/maven/shared/utils/io/ScanConductor.java
+++ b/src/main/java/org/apache/maven/shared/utils/io/ScanConductor.java
@@ -71,7 +71,7 @@ public enum ScanAction
* This method will get invoked for every detected directory.
*
* @param name the directory name (contains parent folders up to the pwd)
- * @param directory
+ * @param directory The directory.
* @return the ScanAction to control how to proceed with the scanning
*/
ScanAction visitDirectory( String name, File directory );
@@ -80,7 +80,7 @@ public enum ScanAction
* This method will get invoked for every detected file.
*
* @param name the file name (contains parent folders up to the pwd)
- * @param file
+ * @param file The file.
* @return the ScanAction to control how to proceed with the scanning
*/
ScanAction visitFile( String name, File file );
diff --git a/src/main/java/org/apache/maven/shared/utils/io/SelectorUtils.java b/src/main/java/org/apache/maven/shared/utils/io/SelectorUtils.java
index 2480ebcd..396ef6a3 100644
--- a/src/main/java/org/apache/maven/shared/utils/io/SelectorUtils.java
+++ b/src/main/java/org/apache/maven/shared/utils/io/SelectorUtils.java
@@ -43,12 +43,24 @@
public final class SelectorUtils
{
+ /**
+ * Pattern handler prefix.
+ */
private static final String PATTERN_HANDLER_PREFIX = "[";
+ /**
+ * Pattern handler suffix.
+ */
public static final String PATTERN_HANDLER_SUFFIX = "]";
+ /**
+ * Regex start pattern.
+ */
public static final String REGEX_HANDLER_PREFIX = "%regex" + PATTERN_HANDLER_PREFIX;
+ /**
+ * ANT pattern prefix.
+ */
public static final String ANT_HANDLER_PREFIX = "%ant" + PATTERN_HANDLER_PREFIX;
/**
diff --git a/src/main/java/org/apache/maven/shared/utils/io/WalkCollector.java b/src/main/java/org/apache/maven/shared/utils/io/WalkCollector.java
index d5d35d33..5d48d4ac 100644
--- a/src/main/java/org/apache/maven/shared/utils/io/WalkCollector.java
+++ b/src/main/java/org/apache/maven/shared/utils/io/WalkCollector.java
@@ -41,6 +41,9 @@ public class WalkCollector
int percentageHigh;
+ /**
+ * Create an instance.
+ */
public WalkCollector()
{
steps = new ArrayListoverride
.
+ */
public static final String SELF_COMBINATION_OVERRIDE = "override"; // plexus: public
+ /**
+ * The attribute which identifies merge
+ */
public static final String SELF_COMBINATION_MERGE = "merge";
@SuppressWarnings( "UnusedDeclaration" )
@@ -72,6 +87,9 @@ public class Xpp3Dom
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private static final Xpp3Dom[] EMPTY_DOM_ARRAY = new Xpp3Dom[0];
+ /**
+ * @param name The name of the instance.
+ */
public Xpp3Dom( String name )
{
this.name = name;
@@ -79,11 +97,20 @@ public Xpp3Dom( String name )
childMap = new HashMapnull
.
+ */
public static boolean isNotEmpty( String str )
{
return str != null && str.length() > 0;
}
+ /**
+ * @param str The string to be checked.
+ * @return true if the string is empty or null
.
+ */
public static boolean isEmpty( String str )
{
return str == null || str.trim().length() == 0;
}
+ /** {@inheritDoc} */
public Iterator+ * Messages are built with instances of {@link org.apache.maven.shared.utils.logging.MessageBuffer MessageBuffer} + * which provides a fluent API. + * {@link org.apache.maven.shared.utils.logging.MessageUtils MessageUtils} gives access to these buffers. + *
+ * Plugins can use this API with any Maven version: color + * just won't be activated when run with Maven version older than 3.4.0. + *
+ * Styles are:
debug
, info
, warning
and error
for slf4j level display,success
, failure
, strong
, mojo
and project
for
+ * message contentMAVEN_OPTS
+ * environment variable (eventually in .mavenrc
script):style.<style name>
,bold
, <color>
and
+ * bg<color>
(for background), where <color>
is
+ * an ANSI color: black
,
+ * red
, green
, yellow
, blue
, magenta
,
+ * cyan
or white
, eventually with bright
prefix+ * Internally, Jansi is used to render + * ANSI colors on any platform. */ public class MessageUtils { @@ -47,6 +50,7 @@ public class MessageUtils /** * Install color support. + * This method is called by Maven core, and calling it is not necessary in plugins. */ public static void systemInstall() { @@ -78,7 +82,6 @@ public static void setColor( boolean flag ) /** * Is message color active: requires JAnsi available (through Maven) and the color has not been disabled. - * @return */ public static boolean isColor() { diff --git a/src/main/java/org/apache/maven/shared/utils/logging/package-info.java b/src/main/java/org/apache/maven/shared/utils/logging/package-info.java index cd1a417f..aa0c28eb 100644 --- a/src/main/java/org/apache/maven/shared/utils/logging/package-info.java +++ b/src/main/java/org/apache/maven/shared/utils/logging/package-info.java @@ -33,7 +33,7 @@ *
success
, failure
, strong
, mojo
and project
for
* message contentMAVEN_OPTS
+ * Default styles colors can be overridden through system properties, that can be set in MAVEN_OPTS
* environment variable (eventually in .mavenrc
script):style.<style name>
,bold
, <color>
and
diff --git a/src/site/apt/index.apt.vm b/src/site/apt/index.apt.vm
index 38e007cc..a7bbc885 100644
--- a/src/site/apt/index.apt.vm
+++ b/src/site/apt/index.apt.vm
@@ -30,17 +30,20 @@
${project.name}
This project aims to be a functional replacement for
- {{{http://plexus.codehaus.org/plexus-utils}plexus-utils}} in Maven.
+ {{{http://codehaus-plexus.github.io/plexus-utils/}plexus-utils}} in Maven.
It is not a 100% API compatible replacement though but a replacement * Internally, Jansi is used to render @@ -60,6 +60,11 @@ public static void systemInstall() } } + /** + * Undo a previous {@link #systemInstall()}. If {@link #systemInstall()} was called + * multiple times, {@link #systemUninstall()} must be called call the same number of times before + * it is actually uninstalled. + */ public static void systemUninstall() { if ( JANSI ) @@ -69,10 +74,10 @@ public static void systemUninstall() } /** - * Activates message color (if JAnsi is available). + * Enables message color (if JAnsi is available). * @param flag */ - public static void setColor( boolean flag ) + public static void setColorEnabled( boolean flag ) { if ( JANSI ) { @@ -81,9 +86,9 @@ public static void setColor( boolean flag ) } /** - * Is message color active: requires JAnsi available (through Maven) and the color has not been disabled. + * Is message color enabled: requires JAnsi available (through Maven) and the color has not been disabled. */ - public static boolean isColor() + public static boolean isColorEnabled() { return JANSI ? Ansi.isEnabled() : false; } @@ -116,11 +121,11 @@ public static MessageBuffer buffer( int size ) } /** - * Remove any ANSI code from a message + * Remove any ANSI code from a message (colors or other escape sequences). * @param msg message eventually containing ANSI codes * @return the message with ANSI codes removed */ - public static String stripAnsi( String msg ) + public static String stripAnsiCodes( String msg ) { return msg.replaceAll( "\u001B\\[[;\\d]*[ -/]*[@-~]", "" ); } diff --git a/src/main/java/org/apache/maven/shared/utils/logging/Style.java b/src/main/java/org/apache/maven/shared/utils/logging/Style.java index 81b4d642..41ecc7f8 100644 --- a/src/main/java/org/apache/maven/shared/utils/logging/Style.java +++ b/src/main/java/org/apache/maven/shared/utils/logging/Style.java @@ -144,7 +144,7 @@ public String toString() { return name(); } - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder( name() + '=' ); if ( bold ) { sb.append( "bold" ); @@ -174,7 +174,7 @@ public String toString() } sb.append( bgColor.name() ); } - return name() + '=' + sb; + return sb.toString(); } } diff --git a/src/main/java/org/apache/maven/shared/utils/logging/package-info.java b/src/main/java/org/apache/maven/shared/utils/logging/package-info.java index aa0c28eb..6f1288f4 100644 --- a/src/main/java/org/apache/maven/shared/utils/logging/package-info.java +++ b/src/main/java/org/apache/maven/shared/utils/logging/package-info.java @@ -30,8 +30,8 @@ *
* Styles are:
debug
, info
, warning
and error
for slf4j level display,success
, failure
, strong
, mojo
and project
for
- * message contentsuccess
, warning
, failure
, strong
, mojo
+ * and project
for message contentMAVEN_OPTS
* environment variable (eventually in .mavenrc
script):- * Messages are built with instances of {@link org.apache.maven.shared.utils.logging.MessageBuffer MessageBuffer} + * Messages are built with instances of {@link org.apache.maven.shared.utils.logging.MessageBuilder MessageBuilder} * which provides a fluent API. * {@link org.apache.maven.shared.utils.logging.MessageUtils MessageUtils} gives access to these buffers. *
diff --git a/src/test/java/org/apache/maven/shared/utils/logging/AnsiMessageBufferTest.java b/src/test/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilderTest.java
similarity index 52%
rename from src/test/java/org/apache/maven/shared/utils/logging/AnsiMessageBufferTest.java
rename to src/test/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilderTest.java
index 55a436aa..d1ae7eab 100644
--- a/src/test/java/org/apache/maven/shared/utils/logging/AnsiMessageBufferTest.java
+++ b/src/test/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilderTest.java
@@ -25,87 +25,87 @@
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
-public class AnsiMessageBufferTest
+public class AnsiMessageBuilderTest
{
- private AnsiMessageBuffer ansiMessageBuffer;
+ private AnsiMessageBuilder ansiMessageBuilder;
@Before
public void initializeAnsiMessageBuffer()
{
- this.ansiMessageBuffer = new AnsiMessageBuffer();
+ this.ansiMessageBuilder = new AnsiMessageBuilder();
}
@Test
public void should_color_debug()
{
- ansiMessageBuffer.debug( "a debug message" );
+ ansiMessageBuilder.debug( "a debug message" );
- assertThat( ansiMessageBuffer.toString(), equalTo( "\u001B[1;36ma debug message\u001B[m" ) );
+ assertThat( ansiMessageBuilder.toString(), equalTo( "\u001B[1;36ma debug message\u001B[m" ) );
}
@Test
public void should_color_info()
{
- ansiMessageBuffer.info( "an info message" );
+ ansiMessageBuilder.info( "an info message" );
- assertThat( ansiMessageBuffer.toString(), equalTo( "\u001B[1;34man info message\u001B[m" ) );
+ assertThat( ansiMessageBuilder.toString(), equalTo( "\u001B[1;34man info message\u001B[m" ) );
}
@Test
public void should_color_warning_and_reset()
{
- ansiMessageBuffer.warning( "a warning message" );
+ ansiMessageBuilder.warning( "a warning message" );
- assertThat( ansiMessageBuffer.toString(), equalTo( "\u001B[1;33ma warning message\u001B[m" ) );
+ assertThat( ansiMessageBuilder.toString(), equalTo( "\u001B[1;33ma warning message\u001B[m" ) );
}
@Test
public void should_color_error()
{
- ansiMessageBuffer.error( "an error message" );
+ ansiMessageBuilder.error( "an error message" );
- assertThat( ansiMessageBuffer.toString(), equalTo( "\u001B[1;31man error message\u001B[m" ) );
+ assertThat( ansiMessageBuilder.toString(), equalTo( "\u001B[1;31man error message\u001B[m" ) );
}
@Test
public void should_color_success_with_message()
{
- ansiMessageBuffer.success( "a success message" );
+ ansiMessageBuilder.success( "a success message" );
- assertThat( ansiMessageBuffer.toString(), equalTo( "\u001B[1;32ma success message\u001B[m" ) );
+ assertThat( ansiMessageBuilder.toString(), equalTo( "\u001B[1;32ma success message\u001B[m" ) );
}
@Test
public void should_color_failure_and_reset()
{
- ansiMessageBuffer.failure( "a failure message" );
+ ansiMessageBuilder.failure( "a failure message" );
- assertThat( ansiMessageBuffer.toString(), equalTo( "\u001B[1;31ma failure message\u001B[m" ) );
+ assertThat( ansiMessageBuilder.toString(), equalTo( "\u001B[1;31ma failure message\u001B[m" ) );
}
@Test
public void should_color_strong_and_reset()
{
- ansiMessageBuffer.strong( "a strong message" );
+ ansiMessageBuilder.strong( "a strong message" );
- assertThat( ansiMessageBuffer.toString(), equalTo( "\u001B[1ma strong message\u001B[m" ) );
+ assertThat( ansiMessageBuilder.toString(), equalTo( "\u001B[1ma strong message\u001B[m" ) );
}
@Test
public void should_color_mojo_and_reset()
{
- ansiMessageBuffer.mojo( "a mojo" );
+ ansiMessageBuilder.mojo( "a mojo" );
- assertThat( ansiMessageBuffer.toString(), equalTo( "\u001B[32ma mojo\u001B[m" ) );
+ assertThat( ansiMessageBuilder.toString(), equalTo( "\u001B[32ma mojo\u001B[m" ) );
}
@Test
public void should_color_project_and_reset()
{
- ansiMessageBuffer.project( "a project" );
+ ansiMessageBuilder.project( "a project" );
- assertThat( ansiMessageBuffer.toString(), equalTo( "\u001B[36ma project\u001B[m" ) );
+ assertThat( ansiMessageBuilder.toString(), equalTo( "\u001B[36ma project\u001B[m" ) );
}
}
From 0ec15a61195e42575b5dcbd6a0c451993ba328b9 Mon Sep 17 00:00:00 2001
From: Herve Boutemy
* Internally, Jansi is used to render
* ANSI colors on any platform.
+ * @since 3.1.0
*/
public class MessageUtils
{
@@ -120,6 +121,16 @@ public static MessageBuilder buffer( int size )
return JANSI ? new AnsiMessageBuilder( size ) : new PlainMessageBuilder( size );
}
+ /**
+ * Create a message buffer with an internal buffer of defined size.
+ * @return a new buffer
+ */
+ @SuppressWarnings( "checkstyle:magicnumber" )
+ public static LoggerLevelRenderer logger()
+ {
+ return JANSI ? new AnsiMessageBuilder( 20 ) : new PlainMessageBuilder( 7 );
+ }
+
/**
* Remove any ANSI code from a message (colors or other escape sequences).
* @param msg message eventually containing ANSI codes
diff --git a/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java b/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java
index e60a762c..abee6dd3 100644
--- a/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java
+++ b/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java
@@ -23,7 +23,7 @@
* Message builder implementation that just ignores styling, for Maven version earlier than 3.4.0.
*/
class PlainMessageBuilder
- implements MessageBuilder
+ implements MessageBuilder, LoggerLevelRenderer
{
private StringBuilder buffer;
@@ -42,24 +42,24 @@ class PlainMessageBuilder
buffer = new StringBuilder( size );
}
- public PlainMessageBuilder debug( Object message )
+ public String debug( String level )
{
- return a( message );
+ return a( level ).toString();
}
- public PlainMessageBuilder info( Object message )
+ public String info( String level )
{
- return a( message );
+ return a( level ).toString();
}
- public PlainMessageBuilder warning( Object message )
+ public String warning( String level )
{
- return a( message );
+ return a( level ).toString();
}
- public PlainMessageBuilder error( Object message )
+ public String error( String level )
{
- return a( message );
+ return a( level ).toString();
}
public PlainMessageBuilder success( Object message )
@@ -67,6 +67,11 @@ public PlainMessageBuilder success( Object message )
return a( message );
}
+ public PlainMessageBuilder warning( Object message )
+ {
+ return a( message );
+ }
+
public PlainMessageBuilder failure( Object message )
{
return a( message );
diff --git a/src/main/java/org/apache/maven/shared/utils/logging/Style.java b/src/main/java/org/apache/maven/shared/utils/logging/Style.java
index defc2aa3..756ff141 100644
--- a/src/main/java/org/apache/maven/shared/utils/logging/Style.java
+++ b/src/main/java/org/apache/maven/shared/utils/logging/Style.java
@@ -26,6 +26,7 @@
/**
* Configurable message styles.
+ * @since 3.1.0
*/
enum Style
{
diff --git a/src/main/java/org/apache/maven/shared/utils/logging/package-info.java b/src/main/java/org/apache/maven/shared/utils/logging/package-info.java
index 2ff1c661..5f8e3423 100644
--- a/src/main/java/org/apache/maven/shared/utils/logging/package-info.java
+++ b/src/main/java/org/apache/maven/shared/utils/logging/package-info.java
@@ -42,6 +42,7 @@
* red
, green
, yellow
, blue
, magenta
,
* cyan
or white
, eventually with bright
prefix
* Messages are built with instances of {@link org.apache.maven.shared.utils.logging.MessageBuilder MessageBuilder} - * which provides a fluent API. - * {@link org.apache.maven.shared.utils.logging.MessageUtils MessageUtils} gives access to these buffers. + * which provides a fluent API, while error level are colored by slf4j provider with + * {@link org.apache.maven.shared.utils.logging.LoggerLevelRenderer LoggerLevelRenderer}. + *
+ * {@link org.apache.maven.shared.utils.logging.MessageUtils MessageUtils} gives access to these builders. *
* Plugins can use this API with any Maven version: color * just won't be activated when run with Maven version older than 3.4.0. *
* Styles are:
debug
, info
, warning
and error
for slf4j level display,debug
, info
, warning
and error
for
+ * {@link org.apache.maven.shared.utils.logging.LoggerLevelRenderer logger level rendering},success
, warning
, failure
, strong
, mojo
- * and project
for message contentproject
for {@link org.apache.maven.shared.utils.logging.MessageBuilder message content}
* MAVEN_OPTS
* environment variable (eventually in .mavenrc
script):CRLF
.
*
* @param writer not null writer
+ * @throws IOException if writing fails.
*/
- public static void writeLineBreak( XMLWriter writer )
+ public static void writeLineBreak( XMLWriter writer ) throws IOException
{
writeLineBreak( writer, 1 );
}
@@ -53,8 +55,9 @@ public static void writeLineBreak( XMLWriter writer )
*
* @param writer not null
* @param repeat positive number
+ * @throws IOException if writing fails.
*/
- public static void writeLineBreak( XMLWriter writer, int repeat )
+ public static void writeLineBreak( XMLWriter writer, int repeat ) throws IOException
{
for ( int i = 0; i < repeat; i++ )
{
@@ -70,8 +73,9 @@ public static void writeLineBreak( XMLWriter writer, int repeat )
* @param indent positive number
* @see #DEFAULT_INDENTATION_SIZE
* @see #writeLineBreak(XMLWriter, int, int, int)
+ * @throws IOException if writing fails.
*/
- public static void writeLineBreak( XMLWriter writer, int repeat, int indent )
+ public static void writeLineBreak( XMLWriter writer, int repeat, int indent ) throws IOException
{
writeLineBreak( writer, repeat, indent, DEFAULT_INDENTATION_SIZE );
}
@@ -83,8 +87,9 @@ public static void writeLineBreak( XMLWriter writer, int repeat, int indent )
* @param repeat The number of repetitions of the indent
* @param indent positive number
* @param indentSize positive number
+ * @throws IOException if writing fails.
*/
- public static void writeLineBreak( XMLWriter writer, int repeat, int indent, int indentSize )
+ public static void writeLineBreak( XMLWriter writer, int repeat, int indent, int indentSize ) throws IOException
{
writeLineBreak( writer, repeat );
@@ -107,8 +112,9 @@ public static void writeLineBreak( XMLWriter writer, int repeat, int indent, int
* @param writer not null
* @see #DEFAULT_COLUMN_LINE
* @see #writeCommentLineBreak(XMLWriter, int)
+ * @throws IOException if writing fails.
*/
- public static void writeCommentLineBreak( XMLWriter writer )
+ public static void writeCommentLineBreak( XMLWriter writer ) throws IOException
{
writeCommentLineBreak( writer, DEFAULT_COLUMN_LINE );
}
@@ -118,8 +124,9 @@ public static void writeCommentLineBreak( XMLWriter writer )
*
* @param writer not null
* @param columnSize positive number
+ * @throws IOException if writing fails.
*/
- public static void writeCommentLineBreak( XMLWriter writer, int columnSize )
+ public static void writeCommentLineBreak( XMLWriter writer, int columnSize ) throws IOException
{
if ( columnSize < 10 )
{
@@ -137,8 +144,9 @@ public static void writeCommentLineBreak( XMLWriter writer, int columnSize )
* @param comment The comment to write
* @see #DEFAULT_INDENTATION_SIZE
* @see #writeComment(XMLWriter, String, int, int)
+ * @throws IOException if writing fails.
*/
- public static void writeComment( XMLWriter writer, String comment )
+ public static void writeComment( XMLWriter writer, String comment ) throws IOException
{
writeComment( writer, comment, 0, DEFAULT_INDENTATION_SIZE );
}
@@ -152,8 +160,9 @@ public static void writeComment( XMLWriter writer, String comment )
* @param indent positive number
* @see #DEFAULT_INDENTATION_SIZE
* @see #writeComment(XMLWriter, String, int, int)
+ * @throws IOException if writing fails.
*/
- public static void writeComment( XMLWriter writer, String comment, int indent )
+ public static void writeComment( XMLWriter writer, String comment, int indent ) throws IOException
{
writeComment( writer, comment, indent, DEFAULT_INDENTATION_SIZE );
}
@@ -168,8 +177,9 @@ public static void writeComment( XMLWriter writer, String comment, int indent )
* @param indentSize positive number
* @see #DEFAULT_COLUMN_LINE
* @see #writeComment(XMLWriter, String, int, int, int)
+ * @throws IOException if writing fails.
*/
- public static void writeComment( XMLWriter writer, String comment, int indent, int indentSize )
+ public static void writeComment( XMLWriter writer, String comment, int indent, int indentSize ) throws IOException
{
writeComment( writer, comment, indent, indentSize, DEFAULT_COLUMN_LINE );
}
@@ -183,8 +193,10 @@ public static void writeComment( XMLWriter writer, String comment, int indent, i
* @param indent positive number
* @param indentSize positive number
* @param columnSize positive number
+ * @throws IOException if writing fails.
*/
public static void writeComment( XMLWriter writer, String comment, int indent, int indentSize, int columnSize )
+ throws IOException
{
if ( comment == null )
{
@@ -263,8 +275,9 @@ public static void writeComment( XMLWriter writer, String comment, int indent, i
* @param comment The comment to write
* @see #DEFAULT_INDENTATION_SIZE
* @see #writeCommentText(XMLWriter, String, int, int)
+ * @throws IOException if writing fails.
*/
- public static void writeCommentText( XMLWriter writer, String comment )
+ public static void writeCommentText( XMLWriter writer, String comment ) throws IOException
{
writeCommentText( writer, comment, 0, DEFAULT_INDENTATION_SIZE );
}
@@ -279,8 +292,9 @@ public static void writeCommentText( XMLWriter writer, String comment )
* @param indent positive number
* @see #DEFAULT_INDENTATION_SIZE
* @see #writeCommentText(XMLWriter, String, int, int)
+ * @throws IOException if writing fails.
*/
- public static void writeCommentText( XMLWriter writer, String comment, int indent )
+ public static void writeCommentText( XMLWriter writer, String comment, int indent ) throws IOException
{
writeCommentText( writer, comment, indent, DEFAULT_INDENTATION_SIZE );
}
@@ -295,8 +309,10 @@ public static void writeCommentText( XMLWriter writer, String comment, int inden
* @param indentSize positive number
* @see #DEFAULT_COLUMN_LINE
* @see #writeCommentText(XMLWriter, String, int, int, int)
+ * @throws IOException if writing fails.
*/
public static void writeCommentText( XMLWriter writer, String comment, int indent, int indentSize )
+ throws IOException
{
writeCommentText( writer, comment, indent, indentSize, DEFAULT_COLUMN_LINE );
}
@@ -311,8 +327,10 @@ public static void writeCommentText( XMLWriter writer, String comment, int inden
* @param indent positive number
* @param indentSize positive number
* @param columnSize positive number
+ * @throws IOException if writing fails.
*/
public static void writeCommentText( XMLWriter writer, String comment, int indent, int indentSize, int columnSize )
+ throws IOException
{
if ( indent < 0 )
{
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java
index 94d11c6e..b24d6f7e 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java
@@ -19,6 +19,7 @@
* under the License.
*/
+import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
@@ -375,10 +376,17 @@ public int hashCode()
/** {@inheritDoc} */
public String toString()
{
- StringWriter writer = new StringWriter();
- Xpp3DomWriter.write( getPrettyPrintXMLWriter( writer ), this );
- return writer.toString();
-
+ try
+ {
+ StringWriter writer = new StringWriter();
+ Xpp3DomWriter.write( getPrettyPrintXMLWriter( writer ), this );
+ return writer.toString();
+ }
+ catch ( final IOException e )
+ {
+ // JDK error in StringWriter.
+ throw new AssertionError( "Unexpected IOException from StringWriter." );
+ }
}
/**
@@ -386,9 +394,17 @@ public String toString()
*/
public String toUnescapedString()
{
- StringWriter writer = new StringWriter();
- Xpp3DomWriter.write( getPrettyPrintXMLWriter( writer ), this, false );
- return writer.toString();
+ try
+ {
+ StringWriter writer = new StringWriter();
+ Xpp3DomWriter.write( getPrettyPrintXMLWriter( writer ), this, false );
+ return writer.toString();
+ }
+ catch ( final IOException e )
+ {
+ // JDK error in StringWriter.
+ throw new AssertionError( "Unexpected IOException from StringWriter." );
+ }
}
private PrettyPrintXMLWriter getPrettyPrintXMLWriter( StringWriter writer )
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomWriter.java b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomWriter.java
index 9acf23c4..b390c545 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomWriter.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomWriter.java
@@ -19,6 +19,7 @@
* under the License.
*/
+import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
@@ -30,8 +31,9 @@ public class Xpp3DomWriter
/**
* @param writer {@link Writer}
* @param dom {@link Xpp3Dom}
+ * @throws IOException if writing fails.
*/
- public static void write( Writer writer, Xpp3Dom dom )
+ public static void write( Writer writer, Xpp3Dom dom ) throws IOException
{
write( new PrettyPrintXMLWriter( writer ), dom );
}
@@ -39,8 +41,9 @@ public static void write( Writer writer, Xpp3Dom dom )
/**
* @param writer {@link PrintWriter}
* @param dom {@link Xpp3Dom}
+ * @throws IOException if writing fails.
*/
- public static void write( PrintWriter writer, Xpp3Dom dom )
+ public static void write( PrintWriter writer, Xpp3Dom dom ) throws IOException
{
write( new PrettyPrintXMLWriter( writer ), dom );
}
@@ -48,8 +51,9 @@ public static void write( PrintWriter writer, Xpp3Dom dom )
/**
* @param xmlWriter {@link XMLWriter}
* @param dom {@link Xpp3Dom}
+ * @throws IOException if writing fails.
*/
- public static void write( XMLWriter xmlWriter, Xpp3Dom dom )
+ public static void write( XMLWriter xmlWriter, Xpp3Dom dom ) throws IOException
{
write( xmlWriter, dom, true );
}
@@ -58,8 +62,9 @@ public static void write( XMLWriter xmlWriter, Xpp3Dom dom )
* @param xmlWriter {@link XMLWriter}
* @param dom {@link Xpp3Dom}
* @param escape true/false.
+ * @throws IOException if writing fails.
*/
- public static void write( XMLWriter xmlWriter, Xpp3Dom dom, boolean escape )
+ public static void write( XMLWriter xmlWriter, Xpp3Dom dom, boolean escape ) throws IOException
{
xmlWriter.startElement( dom.getName() );
String[] attributeNames = dom.getAttributeNames();
diff --git a/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java b/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java
index f60dd223..f2723327 100644
--- a/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java
+++ b/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java
@@ -1,5 +1,6 @@
package org.apache.maven.shared.utils.xml;
+import java.io.IOException;
import javax.swing.text.html.HTML;
import java.io.StringWriter;
@@ -60,7 +61,7 @@ public void after()
}
@Test
- public void testDefaultPrettyPrintXMLWriter()
+ public void testDefaultPrettyPrintXMLWriter() throws IOException
{
writer.startElement( HTML.Tag.HTML.toString() );
@@ -74,7 +75,7 @@ public void testDefaultPrettyPrintXMLWriter()
}
@Test
- public void testPrettyPrintXMLWriterWithGivenLineSeparator()
+ public void testPrettyPrintXMLWriterWithGivenLineSeparator() throws IOException
{
writer.setLineSeparator( "\n" );
@@ -90,7 +91,7 @@ public void testPrettyPrintXMLWriterWithGivenLineSeparator()
}
@Test
- public void testPrettyPrintXMLWriterWithGivenLineIndenter()
+ public void testPrettyPrintXMLWriterWithGivenLineIndenter() throws IOException
{
writer.setLineIndenter( " " );
@@ -106,7 +107,7 @@ public void testPrettyPrintXMLWriterWithGivenLineIndenter()
}
@Test
- public void testEscapeXmlAttributeWindows()
+ public void testEscapeXmlAttributeWindows() throws IOException
{
// Windows
writer.startElement( HTML.Tag.DIV.toString() );
@@ -116,7 +117,7 @@ public void testEscapeXmlAttributeWindows()
}
@Test
- public void testEscapeXmlAttributeMac()
+ public void testEscapeXmlAttributeMac() throws IOException
{
// Mac
writer.startElement( HTML.Tag.DIV.toString() );
@@ -126,7 +127,7 @@ public void testEscapeXmlAttributeMac()
}
@Test
- public void testEscapeXmlAttributeTrailingCR()
+ public void testEscapeXmlAttributeTrailingCR() throws IOException
{
// Mac
writer.startElement( HTML.Tag.DIV.toString() );
@@ -136,7 +137,7 @@ public void testEscapeXmlAttributeTrailingCR()
}
@Test
- public void testEscapeXmlAttributeUnix()
+ public void testEscapeXmlAttributeUnix() throws IOException
{
// Unix
writer.startElement( HTML.Tag.DIV.toString() );
@@ -145,7 +146,7 @@ public void testEscapeXmlAttributeUnix()
Assert.assertEquals( "* Internally, Jansi is used to render * ANSI colors on any platform. @@ -39,7 +39,7 @@ public class MessageUtils boolean jansi = true; try { - // JAnsi is provided by Maven core since 3.4.0 + // JAnsi is provided by Maven core since 3.5.0 Class.forName( "org.fusesource.jansi.Ansi" ); } catch ( ClassNotFoundException cnfe ) @@ -51,7 +51,7 @@ public class MessageUtils /** * Install color support. - * This method is called by Maven core, and calling it is not necessary in plugins. + * This method is called by Maven core, and calling it is not necessary in plugins. */ public static void systemInstall() { diff --git a/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java b/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java index abee6dd3..6a7b56e1 100644 --- a/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java +++ b/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java @@ -20,7 +20,7 @@ */ /** - * Message builder implementation that just ignores styling, for Maven version earlier than 3.4.0. + * Message builder implementation that just ignores styling, for Maven version earlier than 3.5.0. */ class PlainMessageBuilder implements MessageBuilder, LoggerLevelRenderer @@ -46,17 +46,17 @@ public String debug( String level ) { return a( level ).toString(); } - + public String info( String level ) { return a( level ).toString(); } - + public String warning( String level ) { return a( level ).toString(); } - + public String error( String level ) { return a( level ).toString(); @@ -71,7 +71,7 @@ public PlainMessageBuilder warning( Object message ) { return a( message ); } - + public PlainMessageBuilder failure( Object message ) { return a( message ); diff --git a/src/main/java/org/apache/maven/shared/utils/logging/package-info.java b/src/main/java/org/apache/maven/shared/utils/logging/package-info.java index e90ab654..dfc5ddee 100644 --- a/src/main/java/org/apache/maven/shared/utils/logging/package-info.java +++ b/src/main/java/org/apache/maven/shared/utils/logging/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -19,7 +19,7 @@ */ /** * An API to write Maven messages to console with styled color content, consistently across whole - * Maven ecosystem (Maven itself or any plugin or extension). + * Maven ecosystem (Maven itself or any plugin or extension). *
* Messages are built with instances of {@link org.apache.maven.shared.utils.logging.MessageBuilder MessageBuilder} * which provides a fluent API, while error level are colored by slf4j provider with @@ -28,10 +28,10 @@ * {@link org.apache.maven.shared.utils.logging.MessageUtils MessageUtils} gives access to these builders. *
* Plugins can use this API with any Maven version: color - * just won't be activated when run with Maven version older than 3.4.0. + * just won't be activated when run with Maven version older than 3.5.0. *
* Styles are:
debug
, info
, warning
and error
for
+ * debug
, info
, warning
and error
for
* {@link org.apache.maven.shared.utils.logging.LoggerLevelRenderer logger level rendering},success
, warning
, failure
, strong
, mojo
* and project
for {@link org.apache.maven.shared.utils.logging.MessageBuilder message content}.mavenrc
script):style.<style name>
,bold
, <color>
and
- * bg<color>
(for background), where <color>
is
+ * bg<color>
(for background), where <color>
is
* an ANSI color: black
,
* red
, green
, yellow
, blue
, magenta
,
* cyan
or white
, eventually with bright
prefixDelegates to {@link #doSystemUninstall()} for the actual uninstall procedure
+ *
+ * @see Runtime#addShutdownHook(Thread)
+ * @see MessageUtils#systemUninstall()
+ * @see #doSystemUninstall()
+ */
+ public static void registerShutdownHook()
+ {
+ if ( JANSI && shutdownHook == null )
+ {
+ // No shutdown hook registered yet.
+ shutdownHook = new Thread()
+ {
+ @Override
+ public void run()
+ {
+ synchronized ( STARTUP_SHUTDOWN_MONITOR )
+ {
+ doSystemUninstall();
+ }
+ }
+ };
+ Runtime.getRuntime().addShutdownHook( shutdownHook );
+ }
+ }
}
diff --git a/src/test/java/org/apache/maven/shared/utils/logging/MessageUtilsTest.java b/src/test/java/org/apache/maven/shared/utils/logging/MessageUtilsTest.java
new file mode 100644
index 00000000..1a6d4b47
--- /dev/null
+++ b/src/test/java/org/apache/maven/shared/utils/logging/MessageUtilsTest.java
@@ -0,0 +1,48 @@
+package org.apache.maven.shared.utils.logging;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.sameInstance;
+import static org.junit.Assert.assertThat;
+
+import java.io.PrintStream;
+
+import org.junit.Test;
+
+public class MessageUtilsTest
+{
+ @Test
+ public void testSystem()
+ {
+ PrintStream currentOut = System.out;
+ try
+ {
+ MessageUtils.systemInstall();
+ assertThat( System.out, not( sameInstance( currentOut ) ) );
+ MessageUtils.systemUninstall();
+ assertThat( System.out, sameInstance( currentOut ) );
+ }
+ finally
+ {
+ System.setOut( currentOut );
+ }
+ }
+}
From 8f12a7280e9f7ef166b611f212da376d207efa88 Mon Sep 17 00:00:00 2001
From: Herve Boutemy
In order to guard against corrupted downloads/installations, it is highly recommended to verify the signature - of the release bundles against the public KEYS used by the Apache Maven + of the release bundles against the public KEYS used by the Apache Maven developers.
${project.name} is distributed under the Apache License, version 2.0.
@@ -108,8 +108,8 @@ under the License.false
we will only overwrite if the local
- * file or directory is older than the one in the archive.
- *
- * @param overwrite
- */
- public void setOverwrite( boolean overwrite )
- {
- this.overwrite = overwrite;
- }
-
- /**
- * Actually perform the unpacking of the source archive
- * into the destination directory.
- *
- * @throws Exception
- */
- public void execute()
- throws Exception
- {
- expandFile( source, dest );
- }
-
- /**
- * It is intended to be overwritten when implementing an own unarchiver
- * - *Note: we kept this protected method for the sake of backward compatibility!
- * - * @param srcFile The source file. - * @param destination The destination. - * @throws Exception In case of failure. - */ - void expandFile( File srcFile, File destination ) - throws Exception - { - if ( source == null ) - { - throw new NullPointerException( "Source Archive must not be null!" ); - } - - File destDir = destination; - if ( destDir == null ) - { - destDir = new File( System.getProperty( "user.dir" ) ); - } - - ZipInputStream in = null; - try - { - in = new ZipInputStream( new FileInputStream( srcFile ) ); - - for ( ZipEntry zipEntry = in.getNextEntry(); zipEntry != null; zipEntry = in.getNextEntry() ) - { - String zipEntryName = zipEntry.getName(); - Date zipEntryDate = new Date( zipEntry.getTime() ); - - extractFile( source, destDir, in, zipEntryName, zipEntryDate, zipEntry.isDirectory() ); - } - - in.close(); - in = null; - } - finally - { - IOUtil.close( in ); - } - } - - /** - * Extract a single ZipEntry. - * - *Note: we kept this protected method for the sake of backward compatibility!
- * - * @param archive the archive to unpack - * @param destDir the destination dirctory - * @param compressedInputStream - * @param entryName - * @param entryDate - * @param isDirectory - * @throws Exception - */ - void extractFile( File archive, File destDir, InputStream compressedInputStream, String entryName, - Date entryDate, boolean isDirectory ) - throws Exception - { - File targetFile = new File( destDir, entryName ); - - if ( !targetFile.getAbsolutePath().startsWith( destDir.getAbsolutePath() ) ) - { - throw new IOException( "Entry '" + entryName + "' outside the target directory." ); - } - - // if overwrite is specified and the file type - // of the existing file does not match, then delete it - if ( overwrite && targetFile.exists() && targetFile.isDirectory() != isDirectory ) - { - deleteFileOrDir( targetFile ); - } - - if ( !targetFile.exists() || overwrite || targetFile.lastModified() <= entryDate.getTime() ) - { - if ( isDirectory ) - { - targetFile.mkdirs(); - } - else - { - byte[] buffer = new byte[BUFFER_SIZE]; - OutputStream out = null; - try - { - out = new FileOutputStream( targetFile ); - - int len; - while ( ( len = compressedInputStream.read( buffer ) ) >= 0 ) - { - out.write( buffer, 0, len ); - } - - out.close(); - out = null; - } - finally - { - IOUtil.close( out ); - } - targetFile.setLastModified( entryDate.getTime() ); - } - } - } - - /** - * small helper method who deletes the given directory or file. - * - * @param targetFile - * @throws IOException - */ - private void deleteFileOrDir( File targetFile ) - throws IOException - { - if ( targetFile.isDirectory() ) - { - FileUtils.deleteDirectory( targetFile ); - } - else - { - FileUtils.delete( targetFile ); - } - - } -} diff --git a/src/test/java/org/apache/maven/shared/utils/ExpandTest.java b/src/test/java/org/apache/maven/shared/utils/ExpandTest.java deleted file mode 100644 index 6718c830..00000000 --- a/src/test/java/org/apache/maven/shared/utils/ExpandTest.java +++ /dev/null @@ -1,336 +0,0 @@ -package org.apache.maven.shared.utils; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.apache.maven.shared.utils.io.FileUtils; -import org.junit.Rule; -import org.junit.Test; -import org.junit.Assert; -import org.junit.rules.TemporaryFolder; - -import java.io.File; -import java.io.FileNotFoundException; -import java.net.URL; - -import static org.hamcrest.CoreMatchers.*; - -/** - * This will test the plexus utility class {@link Expand}. - * - * Most of this stuff will be obsolete because java-1.4.2 - * introduced a java.util.zip package which works like a charm. - * - * We of course need to implement this class due to compatibility - * reasons. - * - * @author Mark Struberg - */ -public class ExpandTest - extends Assert -{ - - private static final String TEST_ZIP_LOCATION = "/expand/expand_test.zip"; - private static final String TEST_ZIP_TARGET_FOLDER = "expand_test_target/"; - - private static final String TEST_UNZIPPED_FILE = "expand_test/test_file.txt"; - private static final String TEST_UNZIPPED_CONTENT = "TestContent"; - - - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - private File getSourceFile() - { - URL zipFileUrl = getClass().getResource( TEST_ZIP_LOCATION ); - - assertNotNull( zipFileUrl ); - - return new File( zipFileUrl.getFile() ); - } - - /** - * Create a clean target directory for unzipping. - * If it did exist, then clean it first. - * - * @return The target folder. - */ - private File getTestTargetDir() - throws Exception - { - return tempFolder.newFolder( TEST_ZIP_TARGET_FOLDER ); - } - - @Test - public void testSetDest_No_NPE() - { - Expand expand = new Expand(); - expand.setDest( null ); - } - - @Test - public void testSetSrc_No_NPE() - { - Expand expand = new Expand(); - expand.setSrc( null ); - } - - @Test - public void testExecute() - throws Exception - { - Expand expand = new Expand(); - - File source = getSourceFile(); - expand.setSrc( source ); - - File targetDir = getTestTargetDir(); - expand.setDest( targetDir ); - - expand.execute(); - - verifyExpandedFileAndContent( targetDir, TEST_UNZIPPED_CONTENT ); - } - - @Test - public void testExecuteIntoNonexistingDirectory() - throws Exception - { - Expand expand = new Expand(); - - File source = getSourceFile(); - expand.setSrc( source ); - - File nonexisingDir = new File( getTestTargetDir(), "nonexisting_dir" ); - - if ( nonexisingDir.exists() ) - { - FileUtils.deleteDirectory( nonexisingDir ); - } - - expand.setDest( nonexisingDir ); - - expand.execute(); - - verifyExpandedFileAndContent( nonexisingDir, TEST_UNZIPPED_CONTENT ); - } - - @Test - public void testExecuteNonexistingSource() - throws Exception - { - Expand expand = new Expand(); - - File nonexistingSource = new File( "target/expand_test_target/nonexisting_source_file.nixda" ); - expand.setSrc( nonexistingSource ); - - File targetDir = getTestTargetDir(); - expand.setDest( targetDir ); - - try - { - expand.execute(); - fail( "expand with notexiting source must throw Exception!" ); - } - catch ( Exception e ) - { - Throwable cause = ExceptionUtils.getRootCause( e ); - if ( cause == null ) - { - cause = e; - } - - assertTrue( "cause must be a FileNotFoundException", cause instanceof FileNotFoundException ); - } - - } - - @Test( expected = NullPointerException.class ) - public void testExecute_NullSource() - throws Exception - { - Expand expand = new Expand(); - expand.setSrc( null ); - - File targetDir = getTestTargetDir(); - expand.setDest( targetDir ); - - expand.execute(); - } - - @Test - public void testExecute_NullDest() - throws Exception - { - Expand expand = new Expand(); - expand.setSrc( getSourceFile() ); - - // execute without a dest directory seems to - // expand all the archive into the current working directory - expand.setDest( null ); - - String oldWorkingDirectory = System.getProperty( "user.dir" ); - - try - { - File targetDir = getTestTargetDir(); - System.setProperty( "user.dir", targetDir.getAbsolutePath() ); - - expand.execute(); - - verifyExpandedFileAndContent( targetDir, TEST_UNZIPPED_CONTENT ); - } - finally - { - System.setProperty( "user.dir", oldWorkingDirectory ); - } - } - - @Test - public void testExecute_Overwrite() - throws Exception - { - File targetDir = getTestTargetDir(); - File expandedFile = null; - - { - // part1: expand - - Expand expand = new Expand(); - - File source = getSourceFile(); - expand.setSrc( source ); - - expand.setDest( targetDir ); - - expand.execute(); - - expandedFile = verifyExpandedFile( targetDir ); - } - - // turn the clock back 10 seconds - long time = System.currentTimeMillis() - 10000L; - - // round down to 1s; - time = time - time % 1000L; - - expandedFile.setLastModified( time ); - assertEquals( time, expandedFile.lastModified() ); - - { - // part2: expand in non-overwrite mode - - Expand expand = new Expand(); - - File source = getSourceFile(); - expand.setSrc( source ); - expand.setDest( targetDir ); - - expand.setOverwrite( false ); - - expand.execute(); - - expandedFile = verifyExpandedFile( targetDir ); - - assertEquals( "file must still have the old lastModified timestamp" - , time, expandedFile.lastModified() ); - - } - - { - // part3: expand in overwrite mode but local file is still newer than the one in the archive - - Expand expand = new Expand(); - - File source = getSourceFile(); - expand.setSrc( source ); - expand.setDest( targetDir ); - - expand.setOverwrite( true ); - - expand.execute(); - - expandedFile = verifyExpandedFile( targetDir ); - - // obviously the file will be overwritten anyway - assertTrue( "file must now have the original old lastModified timestamp, but was: time=" + time - + " expandedFile.lastModified()= " + expandedFile.lastModified() - , time > expandedFile.lastModified() ); - } - - // turn the clock back a loooong time! - time = 100000000L; - - expandedFile.setLastModified( time ); - assertEquals( time, expandedFile.lastModified() ); - - { - // part3: expand in overwrite mode but local file is now older than the one in the archive - - Expand expand = new Expand(); - - File source = getSourceFile(); - expand.setSrc( source ); - expand.setDest( targetDir ); - - expand.setOverwrite( true ); - - expand.execute(); - - expandedFile = verifyExpandedFile( targetDir ); - - assertTrue( "file must now have newer lastModified timestamp, but was: time=" + time - + " expandedFile.lastModified()= " + expandedFile.lastModified() - , time < expandedFile.lastModified() ); - - } - } - - - private File verifyExpandedFile( File targetDir ) - { - assertThat( "target directory must exist" - , targetDir.exists() - , is( true ) ); - - File expandedFile = new File( targetDir, TEST_UNZIPPED_FILE ); - - assertThat( "expanded file must exist: " + expandedFile.getAbsolutePath() - , expandedFile.exists() - , is( true ) ); - - return expandedFile; - } - - private void verifyExpandedFileAndContent( File targetDir, String expectedContent ) - throws FileNotFoundException - { - File expandedFile = verifyExpandedFile( targetDir ); - - assertNotNull( expandedFile ); - - java.util.Scanner scanner = new java.util.Scanner( expandedFile ).useDelimiter( "\n" ); - String text = scanner.next(); - - assertThat( "expanded file content must match" - , text - , is( expectedContent ) ); - } -} From 7d4ea36ee5b4541586d6fba395fcccc906d67053 Mon Sep 17 00:00:00 2001 From: Elliotte Rusty Harold- * Implementation to call the CMD Shell present on Windows NT, 2000 and XP - *
+ * Implementation to call the CMD Shell present on Windows NT, 2000, XP, 7, 8, and 10. * * @author Carlos Sanchez * diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java index dcee0466..ba85633b 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java @@ -21,13 +21,12 @@ /** - ** Implementation to call the Command.com Shell present on Windows 95, 98 and Me - *
* * @author Carlos Sanchez - * + * @deprecated Windows ME is long dead. Update to Windows 10 and use {@link CmdShell}. */ +@Deprecated public class CommandShell extends Shell { diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java index 58096109..bec555e0 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java @@ -27,14 +27,13 @@ import org.apache.maven.shared.utils.StringUtils; /** - ** Class that abstracts the Shell functionality, - * with subclases for shells that behave particularly, like + * with subclasses for shells that behave particularly, like
+ * *
command.com
cmd.exe
- * If the given {@code URL} is not {@code null}, it is asserted to represent a valid and loadable properties - * resource. + * If the given {@code URL} is {@code null} or the properties can't be read, an empty properties object is returned. *
* - * @param url The {@code URL} of the properties resource to load or {@code null}. - * - * @return The loaded properties or an empty {@code Properties} instance if {@code url} is {@code null}. - * + * @param url the {@code URL} of the properties resource to load or {@code null} + * @return the loaded properties or an empty {@code Properties} instance if properties fail to load * @since 3.1.0 */ - @Nonnull public static Properties loadOptionalProperties( final @Nullable URL url ) + @Nonnull + public static Properties loadOptionalProperties( final @Nullable URL url ) { - InputStream in = null; - try - { - final Properties properties = new Properties(); - if ( url != null ) + Properties properties = new Properties(); + if ( url != null ) + { + try ( InputStream in = url.openStream() ) { - in = url.openStream(); properties.load( in ); - in.close(); - in = null; } - - return properties; - } - catch ( final IOException e ) - { - throw new AssertionError( e ); - } - finally - { - IOUtil.close( in ); + catch ( IllegalArgumentException | IOException ex ) + { + // ignore and return empty properties + } } + return properties; } /** * Loads {@code Properties} from a given {@code File}. *- * If the given {@code File} is not {@code null}, it is asserted to represent a valid and loadable properties - * resource. + * If the given {@code File} is {@code null} or the properties file can't be read, an empty properties object is + * returned. *
* - * @param file The {@code File} of the properties resource to load or {@code null}. - * - * @return The loaded properties or an empty {@code Properties} instance if {@code file} is {@code null}. - * + * @param file the {@code File} of the properties resource to load or {@code null} + * @return the loaded properties or an empty {@code Properties} instance if properties fail to load * @since 3.1.0 */ - @Nonnull public static Properties loadOptionalProperties( final @Nullable File file ) + @Nonnull + public static Properties loadOptionalProperties( final @Nullable File file ) { - InputStream in = null; - try + Properties properties = new Properties(); + if ( file != null ) { - final Properties properties = new Properties(); - - if ( file != null ) + try ( InputStream in = new FileInputStream( file ) ) { - in = new FileInputStream( file ); properties.load( in ); - in.close(); - in = null; } - - return properties; - } - catch ( final IOException e ) - { - throw new AssertionError( e ); - } - finally - { - IOUtil.close( in ); + catch ( IllegalArgumentException | IOException ex ) + { + // ignore and return empty properties + } } + + return properties; + } /** * Loads {@code Properties} from a given {@code InputStream}. *- * If the given {@code InputStream} is not {@code null}, it is asserted to represent a valid and loadable properties - * resource. + * If the given {@code InputStream} is {@code null} or the properties can't be read, an empty properties object is + * returned. *
* - * @param inputStream The {@code InputStream} of the properties resource to load or {@code null}. - * - * @return The loaded properties or an empty {@code Properties} instance if {@code inputStream} is {@code null}. - * + * @param inputStream the properties resource to load or {@code null} + * @return the loaded properties or an empty {@code Properties} instance if properties fail to load * @since 3.1.0 */ - @Nonnull public static Properties loadOptionalProperties( final @Nullable InputStream inputStream ) + @Nonnull + public static Properties loadOptionalProperties( final @Nullable InputStream inputStream ) { - InputStream in = null; - try - { - final Properties properties = new Properties(); - if ( inputStream != null ) - { - in = inputStream; - properties.load( in ); - in.close(); - in = null; - } + Properties properties = new Properties(); - return properties; - } - catch ( final IOException e ) + if ( inputStream != null ) { - throw new AssertionError( e ); - } - finally - { - IOUtil.close( in ); + try + { + properties.load( inputStream ); + } + catch ( IllegalArgumentException | IOException ex ) + { + // ignore and return empty properties + } + finally + { + IOUtil.close( inputStream ); + } } + + return properties; + } } diff --git a/src/test/java/org/apache/maven/shared/utils/PropertyUtilsTest.java b/src/test/java/org/apache/maven/shared/utils/PropertyUtilsTest.java index b7c5ba6d..41067a40 100644 --- a/src/test/java/org/apache/maven/shared/utils/PropertyUtilsTest.java +++ b/src/test/java/org/apache/maven/shared/utils/PropertyUtilsTest.java @@ -22,8 +22,10 @@ import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.io.UnsupportedEncodingException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -38,7 +40,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class PropertyUtilsTest { @@ -67,6 +69,15 @@ public void loadOptionalNullInputStream() { assertThat( PropertyUtils.loadOptionalProperties( (InputStream) null ), is( new Properties() ) ); } + + + @Test + public void loadOptionalProperties_ioException() + throws Exception + { + URL url = new URL( "https://nonesuch12344.foo.bar.com/" ); + assertThat( PropertyUtils.loadOptionalProperties( url ), is( new Properties() ) ); + } @Test @SuppressWarnings( "deprecation" ) @@ -137,8 +148,7 @@ public void loadEmptyURL() @Test @SuppressWarnings( "deprecation" ) - public void loadValidInputStream() - throws Exception + public void loadValidInputStream() throws UnsupportedEncodingException { Properties value = new Properties(); value.setProperty( "a", "b" ); @@ -154,8 +164,7 @@ public void loadValidInputStream() @Test @NeedsTemporaryFolder @SuppressWarnings( "deprecation" ) - public void loadValidFile() - throws Exception + public void loadValidFile() throws IOException { OutputStream out = null; try @@ -179,8 +188,7 @@ public void loadValidFile() @Test @NeedsTemporaryFolder @SuppressWarnings( "deprecation" ) - public void loadValidURL() - throws Exception + public void loadValidURL() throws IOException { OutputStream out = null; try From c26ac49709a53b3685f466c779129fbd73487105 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Herv=C3=A9=20Boutemy?=URL
to a File
.
*
- * @param url File URL.
- * @return The equivalent File
object, or null
if the URL's protocol
- * is not file
+ * @param url file URL
+ * @return the equivalent File
object, or null
if the URL's protocol
+ * is not file
*/
@Nullable public static File toFile( @Nullable final URL url )
{
@@ -707,8 +707,7 @@ public static boolean contentEquals( @Nonnull final File file1, @Nonnull final F
}
/**
- * Remove extension from filename.
- * ie
+ * Remove extension from filename. E.g.
* * foo.txt --> foo * a\b\c.jpg --> a\b\c @@ -732,8 +731,8 @@ public static boolean contentEquals( @Nonnull final File file1, @Nonnull final F } /** - * Get extension from filename. - * ie + * Get extension from filename. E.g. + * ** foo.txt --> "txt" * a\b\c.jpg --> "jpg" @@ -753,10 +752,10 @@ public static boolean contentEquals( @Nonnull final File file1, @Nonnull final F * (and any parent directories) will be created. If a filesource
in *destinationDirectory
exists, it will be overwritten. * - * @param source An existingFile
to copy. - * @param destinationDirectory A directory to copysource
into. - * @throws java.io.FileNotFoundException ifsource
isn't a normal file. - * @throws IllegalArgumentException ifdestinationDirectory
isn't a directory. + * @param source an existingFile
to copy + * @param destinationDirectory a directory to copysource
into + * @throws java.io.FileNotFoundException ifsource
isn't a normal file + * @throws IllegalArgumentException ifdestinationDirectory
isn't a directory * @throws IOException ifsource
does not exist, the file in *destinationDirectory
cannot be written to, or an IO error * occurs during copying. @@ -775,16 +774,16 @@ public static void copyFileToDirectory( @Nonnull final File source, @Nonnull fin /** * Copy file from source to destination only if source is newer than the target file. * IfdestinationDirectory
does not exist, it - * (and any parent directories) will be created. If a filesource
in - *destinationDirectory
exists, it will be overwritten. + * (and any parent directories) is created. If a filesource
in + *destinationDirectory
exists, it is overwritten. * - * @param source An existingFile
to copy. - * @param destinationDirectory A directory to copysource
into. - * @throws java.io.FileNotFoundException ifsource
isn't a normal file. - * @throws IllegalArgumentException ifdestinationDirectory
isn't a directory. + * @param source an existingFile
to copy + * @param destinationDirectory a directory to copysource
into + * @throws java.io.FileNotFoundException ifsource
isn't a normal file + * @throws IllegalArgumentException ifdestinationDirectory
isn't a directory * @throws IOException ifsource
does not exist, the file in *destinationDirectory
cannot be written to, or an IO error - * occurs during copying. + * occurs during copying */ private static void copyFileToDirectoryIfModified( @Nonnull final File source, @Nonnull final File destinationDirectory ) @@ -804,11 +803,11 @@ private static void copyFileToDirectoryIfModified( @Nonnull final File source, * created if they don't already exist.destination
will be overwritten if it * already exists. * - * @param source An existing non-directoryFile
to copy bytes from. - * @param destination A non-directoryFile
to write bytes to (possibly - * overwriting). - * @throws IOException ifsource
does not exist,destination
cannot be - * written to, or an IO error occurs during copying. + * @param source an existing non-directoryFile
to copy bytes from + * @param destination a non-directoryFile
to write bytes to (possibly + * overwriting) + * @throws IOException ifsource
does not exist,destination
cannot be + * written to, or an IO error occurs during copying. * @throws java.io.FileNotFoundException ifdestination
is a directory */ public static void copyFile( @Nonnull final File source, @Nonnull final File destination ) From ff23ef7d872bd5a2aa6488cc1a2a0fc9befe30a5 Mon Sep 17 00:00:00 2001 From: Elliotte Rusty HaroldDate: Mon, 13 Apr 2020 13:52:48 -0400 Subject: [PATCH 133/265] [MSHARED-881] use try with resources (#27) * use try with resources * format --- .../maven/shared/utils/io/FileUtils.java | 235 +++++------------- .../shared/utils/xml/Xpp3DomBuilder.java | 6 +- .../maven/shared/utils/io/FileUtilsTest.java | 2 +- 3 files changed, 68 insertions(+), 175 deletions(-) diff --git a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java index c1303853..36e6fd97 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java +++ b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java @@ -31,7 +31,6 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; -import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -41,6 +40,7 @@ import java.io.Writer; import java.net.URL; import java.nio.channels.FileChannel; +import java.nio.charset.Charset; import java.security.SecureRandom; import java.text.DecimalFormat; import java.util.ArrayList; @@ -270,32 +270,20 @@ public static boolean fileExists( @Nonnull String fileName ) @Nonnull public static String fileRead( @Nonnull File file, @Nullable String encoding ) throws IOException { - StringBuilder buf = new StringBuilder(); - - Reader reader = null; + StringBuilder buf = new StringBuilder(); + if ( encoding == null ) + { + encoding = Charset.defaultCharset().name(); + } - try + try ( Reader reader = new InputStreamReader( new FileInputStream( file ), encoding ) ) { - if ( encoding != null ) - { - reader = new InputStreamReader( new FileInputStream( file ), encoding ); - } - else - { - reader = new InputStreamReader( new FileInputStream( file ) ); - } int count; char[] b = new char[512]; while ( ( count = reader.read( b ) ) >= 0 ) // blocking read { buf.append( b, 0, count ); } - reader.close(); - reader = null; - } - finally - { - IOUtil.close( reader ); } return buf.toString(); @@ -340,24 +328,15 @@ public static void fileAppend( @Nonnull String fileName, @Nonnull String data ) public static void fileAppend( @Nonnull String fileName, @Nullable String encoding, @Nonnull String data ) throws IOException { - FileOutputStream out = null; - try + + if ( encoding == null ) { - out = new FileOutputStream( fileName, true ); - if ( encoding != null ) - { - out.write( data.getBytes( encoding ) ); - } - else - { - out.write( data.getBytes() ); - } - out.close(); - out = null; + encoding = Charset.defaultCharset().name(); } - finally + + try ( OutputStream out = new FileOutputStream( fileName, true ) ) { - IOUtil.close( out ); + out.write( data.getBytes( encoding ) ); } } @@ -401,24 +380,15 @@ public static void fileWrite( @Nonnull String fileName, @Nullable String encodin public static void fileWrite( @Nonnull File file, @Nullable String encoding, @Nonnull String data ) throws IOException { - Writer writer = null; - try + + if ( encoding == null ) { - if ( encoding != null ) - { - writer = new OutputStreamWriter( new FileOutputStream( file ), encoding ); - } - else - { - writer = new OutputStreamWriter( new FileOutputStream( file ) ); - } - writer.write( data ); - writer.close(); - writer = null; + encoding = Charset.defaultCharset().name(); } - finally + + try ( Writer writer = new OutputStreamWriter( new FileOutputStream( file ), encoding ) ) { - IOUtil.close( writer ); + writer.write( data ); } } @@ -447,18 +417,14 @@ public static void fileWriteArray( @Nonnull File file, @Nullable String... data public static void fileWriteArray( @Nonnull File file, @Nullable String encoding, @Nullable String... data ) throws IOException { - Writer writer = null; - try + + if ( encoding == null ) { - if ( encoding != null ) - { - writer = new OutputStreamWriter( new FileOutputStream( file ), encoding ); - } - else - { - writer = new OutputStreamWriter( new FileOutputStream( file ) ); - } + encoding = Charset.defaultCharset().name(); + } + try ( Writer writer = new OutputStreamWriter( new FileOutputStream( file ), encoding ) ) + { for ( int i = 0; data != null && i < data.length; i++ ) { writer.write( data[i] ); @@ -467,13 +433,6 @@ public static void fileWriteArray( @Nonnull File file, @Nullable String encoding writer.write( "\n" ); } } - - writer.close(); - writer = null; - } - finally - { - IOUtil.close( writer ); } } @@ -637,25 +596,11 @@ public static boolean contentEquals( @Nonnull final File file1, @Nonnull final F return false; } - InputStream input1 = null; - InputStream input2 = null; - boolean equals = false; - try - { - input1 = new FileInputStream( file1 ); - input2 = new FileInputStream( file2 ); - equals = IOUtil.contentEquals( input1, input2 ); - input1.close(); - input1 = null; - input2.close(); - input2 = null; + try ( InputStream input1 = new FileInputStream( file1 ); + InputStream input2 = new FileInputStream( file2 ) ) + { + return IOUtil.contentEquals( input1, input2 ); } - finally - { - IOUtil.close( input1 ); - IOUtil.close( input2 ); - } - return equals; } /** @@ -857,16 +802,13 @@ private static void mkdirsFor( @Nonnull File destination ) private static void doCopyFile( @Nonnull File source, @Nonnull File destination ) throws IOException { - FileInputStream fis = null; - FileOutputStream fos = null; - FileChannel input = null; - FileChannel output = null; - try + + try ( FileInputStream fis = new FileInputStream( source ); + FileOutputStream fos = new FileOutputStream( destination ); + FileChannel input = fis.getChannel(); + FileChannel output = fos.getChannel() ) { - fis = new FileInputStream( source ); - fos = new FileOutputStream( destination ); - input = fis.getChannel(); - output = fos.getChannel(); + long size = input.size(); long pos = 0; long count; @@ -875,21 +817,6 @@ private static void doCopyFile( @Nonnull File source, @Nonnull File destination count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos; pos += output.transferFrom( input, pos, count ); } - output.close(); - output = null; - fos.close(); - fos = null; - input.close(); - input = null; - fis.close(); - fis = null; - } - finally - { - IOUtil.close( output ); - IOUtil.close( fos ); - IOUtil.close( input ); - IOUtil.close( fis ); } } @@ -959,35 +886,23 @@ private static void copyStreamToFile( @Nonnull @WillClose final InputStream sour @Nonnull final File destination ) throws IOException { - InputStream in = source; - OutputStream out = null; - try + // does destination directory exist ? + if ( destination.getParentFile() != null && !destination.getParentFile().exists() ) { - //does destination directory exist ? - if ( destination.getParentFile() != null && !destination.getParentFile().exists() ) - { - //noinspection ResultOfMethodCallIgnored - destination.getParentFile().mkdirs(); - } - - //make sure we can write to destination - if ( destination.exists() && !destination.canWrite() ) - { - final String message = "Unable to open file " + destination + " for writing."; - throw new IOException( message ); - } + // noinspection ResultOfMethodCallIgnored + destination.getParentFile().mkdirs(); + } - out = new FileOutputStream( destination ); - IOUtil.copy( in, out ); - out.close(); - out = null; - in.close(); - in = null; + // make sure we can write to destination + if ( destination.exists() && !destination.canWrite() ) + { + final String message = "Unable to open file " + destination + " for writing."; + throw new IOException( message ); } - finally + + try ( OutputStream out = new FileOutputStream( destination ); InputStream in = source ) { - IOUtil.close( out ); - IOUtil.close( in ); + IOUtil.copy( in, out ); } } @@ -1179,7 +1094,7 @@ public static void forceDelete( @Nonnull final File file ) * deletes a file. * * @param file The file to delete - * @throws IOException If the file cannot be delted. + * @throws IOException if the file cannot be deleted */ @@ -1913,37 +1828,25 @@ public static void copyFile( @Nonnull File from, @Nonnull File to, @Nullable Str { if ( wrappers != null && wrappers.length > 0 ) { + + if ( encoding == null || encoding.isEmpty() ) + { + encoding = Charset.defaultCharset().name(); + } + // buffer so it isn't reading a byte at a time! - Reader fileReader = null; - Writer fileWriter = null; - try + try ( Reader fileReader = + new BufferedReader( new InputStreamReader( new FileInputStream( from ), encoding ) ); + Writer fileWriter = new OutputStreamWriter( new FileOutputStream( to ), encoding ) ) { - if ( encoding == null || encoding.length() < 1 ) - { - fileReader = new BufferedReader( new FileReader( from ) ); - fileWriter = new FileWriter( to ); - } - else - { - fileReader = new BufferedReader( new InputStreamReader( new FileInputStream( from ), encoding ) ); - fileWriter = new OutputStreamWriter( new FileOutputStream( to ), encoding ); - } + Reader wrapped = fileReader; for ( FilterWrapper wrapper : wrappers ) { - fileReader = wrapper.getReader( fileReader ); + wrapped = wrapper.getReader( wrapped ); } - IOUtil.copy( fileReader, fileWriter ); - fileWriter.close(); - fileWriter = null; - fileReader.close(); - fileReader = null; - } - finally - { - IOUtil.close( fileReader ); - IOUtil.close( fileWriter ); + IOUtil.copy( wrapped, fileWriter ); } } else @@ -1956,7 +1859,7 @@ public static void copyFile( @Nonnull File from, @Nonnull File to, @Nullable Str } /** - * Note: the file content is read with platform encoding + * Note: the file content is read with platform encoding. * * @param file the file * @return a List containing every every line not starting with # and not empty @@ -1969,31 +1872,21 @@ public static void copyFile( @Nonnull File from, @Nonnull File to, @Nullable Str if ( file.exists() ) { - BufferedReader reader = null; - try + try ( BufferedReader reader = new BufferedReader( new FileReader( file ) ) ) { - reader = new BufferedReader( new FileReader( file ) ); - for ( String line = reader.readLine(); line != null; line = reader.readLine() ) { line = line.trim(); - if ( !line.startsWith( "#" ) && line.length() != 0 ) { lines.add( line ); } } - - reader.close(); - reader = null; - } - finally - { - IOUtil.close( reader ); } } return lines; + } /** diff --git a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java index 0798e4f4..596e127d 100644 --- a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java +++ b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java @@ -92,9 +92,9 @@ public static Xpp3Dom build( @WillClose InputStream is, @Nonnull String encoding /** * @param reader {@link Reader} - * @param trim true/false. - * @return the built dom. - * @throws XmlPullParserException in case of an error. + * @param trim true/false + * @return the built dom + * @throws XmlPullParserException in case of an error */ public static Xpp3Dom build( @WillClose Reader reader, boolean trim ) throws XmlPullParserException diff --git a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java index 73717b7c..e6ef175e 100644 --- a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java +++ b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java @@ -4,8 +4,8 @@ import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; From 75ea857c12d1e1d072f223841c769ff07fa360c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Herv=C3=A9=20Boutemy?= Date: Mon, 13 Apr 2020 22:25:15 +0200 Subject: [PATCH 134/265] README improvement --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index adf4e28b..6ddc421d 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Contributing to [Apache Maven Shared Utils](https://maven.apache.org/shared/mave [][jira] [][license] -[](https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.apache.maven.shared%22%20AND%20a%3A%22maven-shared-utils%22) +[](https://search.maven.org/artifact/org.apache.maven.shared/maven-shared-utils) [][build] [][test-results] From bb2f85e98c3c651ae50b7f642500cb74f50abb0d Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" <27856297+dependabot-preview[bot]@users.noreply.github.com> Date: Mon, 9 Mar 2020 04:19:41 +0000 Subject: [PATCH 135/265] Bump hamcrest-core from 1.3 to 2.2 Bumps [hamcrest-core](https://github.com/hamcrest/JavaHamcrest) from 1.3 to 2.2. - [Release notes](https://github.com/hamcrest/JavaHamcrest/releases) - [Changelog](https://github.com/hamcrest/JavaHamcrest/blob/master/CHANGES.md) - [Commits](https://github.com/hamcrest/JavaHamcrest/compare/hamcrest-java-1.3...v2.2) Signed-off-by: dependabot-preview[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 21a01e03..681089d4 100644 --- a/pom.xml +++ b/pom.xml @@ -83,7 +83,7 @@ org.hamcrest hamcrest-core -1.3 +2.2 test From 32942621ff5df2f8779e0f55276c902a1fcb42b9 Mon Sep 17 00:00:00 2001 From: Rob Oxspring Date: Sun, 17 May 2020 00:23:04 +0100 Subject: [PATCH 136/265] [MSHARED-860] Deprecate unnecessary Java7Support (#30) * [MSHARED-860] Call java.nio.file.Files utility methods directly rather than via reflection * [MSHARED-860] Move createSymbolicLink() utility to FileUtils * [MSHARED-860] Deprecate Java7Support and call java.nio.file.Files methods directly --- .../shared/utils/io/DirectoryScanner.java | 9 +- .../maven/shared/utils/io/FileUtils.java | 59 +++---- .../maven/shared/utils/io/Java7Support.java | 162 ++---------------- .../shared/utils/io/DirectoryScannerTest.java | 2 - .../maven/shared/utils/io/FileUtilsTest.java | 20 ++- .../shared/utils/io/Java7SupportTest.java | 23 +-- .../shared/utils/io/SymlinkTestSetup.java | 14 +- 7 files changed, 66 insertions(+), 223 deletions(-) diff --git a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java index 721d7a92..c22cfe33 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java +++ b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java @@ -21,6 +21,7 @@ import java.io.File; import java.io.IOException; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -902,13 +903,7 @@ public void addDefaultExcludes() boolean isSymbolicLink( final File parent, final String name ) throws IOException { - if ( Java7Support.isAtLeastJava7() ) - { - return Java7Support.isSymLink( parent ); - } - final File resolvedParent = new File( parent.getCanonicalPath() ); - final File toTest = new File( resolvedParent, name ); - return !toTest.getAbsolutePath().equals( toTest.getCanonicalPath() ); + return Files.isSymbolicLink( parent.toPath() ); } private void setupDefaultFilters() diff --git a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java index 36e6fd97..f7de64c7 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java +++ b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java @@ -41,6 +41,7 @@ import java.net.URL; import java.nio.channels.FileChannel; import java.nio.charset.Charset; +import java.nio.file.Files; import java.security.SecureRandom; import java.text.DecimalFormat; import java.util.ArrayList; @@ -764,10 +765,10 @@ public static void copyFile( @Nonnull final File source, @Nonnull final File des final String message = "File " + source + " does not exist"; throw new IOException( message ); } - if ( Java7Support.isAtLeastJava7() && Java7Support.isSymLink( source ) ) + if ( Files.isSymbolicLink( source.toPath() ) ) { - File target = Java7Support.readSymbolicLink( source ); - Java7Support.createSymbolicLink( destination, target ); + File target = Files.readSymbolicLink( source.toPath() ).toFile(); + createSymbolicLink( destination, target ); return; } @@ -1101,17 +1102,7 @@ public static void forceDelete( @Nonnull final File file ) public static void delete( @Nonnull File file ) throws IOException { - if ( Java7Support.isAtLeastJava7() ) - { - Java7Support.delete( file ); - } - else - { - if ( !file.delete() ) - { - throw new IOException( "Could not delete " + file.getName() ); - } - } + Files.delete( file.toPath() ); } /** @@ -1120,21 +1111,14 @@ public static void delete( @Nonnull File file ) */ public static boolean deleteLegacyStyle( @Nonnull File file ) { - if ( Java7Support.isAtLeastJava7() ) + try { - try - { - Java7Support.delete( file ); - return true; - } - catch ( IOException e ) - { - return false; - } + Files.delete( file.toPath() ); + return true; } - else + catch ( IOException e ) { - return file.delete(); + return false; } } @@ -1934,11 +1918,7 @@ private static boolean isValidWindowsFileName( @Nonnull File f ) public static boolean isSymbolicLink( @Nonnull final File file ) throws IOException { - if ( Java7Support.isAtLeastJava7() ) - { - return Java7Support.isSymLink( file ); - } - return isSymbolicLinkLegacy( file ); + return Files.isSymbolicLink( file.toPath() ); } /** @@ -1953,7 +1933,7 @@ public static boolean isSymbolicLink( @Nonnull final File file ) public static boolean isSymbolicLinkForSure( @Nonnull final File file ) throws IOException { - return Java7Support.isAtLeastJava7() && Java7Support.isSymLink( file ); + return Files.isSymbolicLink( file.toPath() ); } /** @@ -1981,4 +1961,19 @@ static boolean isSymbolicLinkLegacy( @Nonnull final File file ) return !file.getAbsolutePath().equals( canonical.getPath() ); } + /** + * @param symlink The link name. + * @param target The target. + * @return The linked file. + * @throws IOException in case of an error. + */ + @Nonnull public static File createSymbolicLink( @Nonnull File symlink, @Nonnull File target ) + throws IOException + { + if ( !Files.exists( symlink.toPath() ) ) + { + return Files.createSymbolicLink( symlink.toPath(), target.toPath() ).toFile(); + } + return symlink; + } } diff --git a/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java b/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java index 550de2f4..a51d5022 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java +++ b/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java @@ -22,93 +22,27 @@ import javax.annotation.Nonnull; import java.io.File; import java.io.IOException; -import java.lang.reflect.Array; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; +import java.nio.file.Files; /** * Java7 feature detection * * @author Kristian Rosenvold + * + * @deprecated no longer needed, prefer to use {@link java.nio.file.Files} methods directly. */ +@Deprecated public class Java7Support { - - private static final boolean IS_JAVA7; - - private static Method isSymbolicLink; - - private static Method delete; - - private static Method toPath; - - private static Method exists; - - private static Method toFile; - - private static Method readSymlink; - - private static Method createSymlink; - - private static Object emptyLinkOpts; - - private static Object emptyFileAttributes; - - static - { - boolean isJava7x = true; - try - { - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - Class> files = cl.loadClass( "java.nio.file.Files" ); - Class> path = cl.loadClass( "java.nio.file.Path" ); - Class> fa = cl.loadClass( "java.nio.file.attribute.FileAttribute" ); - Class> linkOption = cl.loadClass( "java.nio.file.LinkOption" ); - isSymbolicLink = files.getMethod( "isSymbolicLink", path ); - delete = files.getMethod( "delete", path ); - readSymlink = files.getMethod( "readSymbolicLink", path ); - - emptyFileAttributes = Array.newInstance( fa, 0 ); - final Object o = emptyFileAttributes; - createSymlink = files.getMethod( "createSymbolicLink", path, path, o.getClass() ); - emptyLinkOpts = Array.newInstance( linkOption, 0 ); - exists = files.getMethod( "exists", path, emptyLinkOpts.getClass() ); - toPath = File.class.getMethod( "toPath" ); - toFile = path.getMethod( "toFile" ); - } - catch ( ClassNotFoundException e ) - { - isJava7x = false; - } - catch ( NoSuchMethodException e ) - { - isJava7x = false; - } - IS_JAVA7 = isJava7x; - } - /** * @param file The file to check for being a symbolic link. * @return true if the file is a symlink false otherwise. */ public static boolean isSymLink( @Nonnull File file ) { - try - { - Object path = toPath.invoke( file ); - return (Boolean) isSymbolicLink.invoke( null, path ); - } - catch ( IllegalAccessException e ) - { - throw new RuntimeException( e ); - } - catch ( InvocationTargetException e ) - { - throw new RuntimeException( e ); - } + return Files.isSymbolicLink( file.toPath() ); } - /** * @param symlink The sym link. * @return The file. @@ -117,23 +51,9 @@ public static boolean isSymLink( @Nonnull File file ) @Nonnull public static File readSymbolicLink( @Nonnull File symlink ) throws IOException { - try - { - Object path = toPath.invoke( symlink ); - Object resultPath = readSymlink.invoke( null, path ); - return (File) toFile.invoke( resultPath ); - } - catch ( IllegalAccessException e ) - { - throw new RuntimeException( e ); - } - catch ( InvocationTargetException e ) - { - throw new RuntimeException( e ); - } + return Files.readSymbolicLink( symlink.toPath() ).toFile(); } - /** * @param file The file to check. * @return true if exist false otherwise. @@ -142,21 +62,7 @@ public static boolean isSymLink( @Nonnull File file ) public static boolean exists( @Nonnull File file ) throws IOException { - try - { - Object path = toPath.invoke( file ); - final Object invoke = exists.invoke( null, path, emptyLinkOpts ); - return (Boolean) invoke; - } - catch ( IllegalAccessException e ) - { - throw new RuntimeException( e ); - } - catch ( InvocationTargetException e ) - { - throw (RuntimeException) e.getTargetException(); - } - + return Files.exists( file.toPath() ); } /** @@ -168,40 +74,9 @@ public static boolean exists( @Nonnull File file ) @Nonnull public static File createSymbolicLink( @Nonnull File symlink, @Nonnull File target ) throws IOException { - try - { - if ( !exists( symlink ) ) - { - Object link = toPath.invoke( symlink ); - Object path = createSymlink.invoke( null, link, toPath.invoke( target ), emptyFileAttributes ); - return (File) toFile.invoke( path ); - } - return symlink; - } - catch ( IllegalAccessException e ) - { - throw new RuntimeException( e ); - } - catch ( InvocationTargetException e ) - { - final Throwable targetException = e.getTargetException(); - if ( targetException instanceof IOException ) - { - throw (IOException) targetException; - } - else if ( targetException instanceof RuntimeException ) - { - // java.lang.UnsupportedOperationException: Symbolic links not supported on this operating system - // java.lang.SecurityException: denies certain permissions see Javadoc - throw ( RuntimeException ) targetException; - } - else - { - throw new IOException( targetException.getClass() + ": " + targetException.getLocalizedMessage() ); - } - } - + return FileUtils.createSymbolicLink( symlink, target ); } + /** * Performs a nio delete * @param file the file to delete @@ -210,19 +85,7 @@ else if ( targetException instanceof RuntimeException ) public static void delete( @Nonnull File file ) throws IOException { - try - { - Object path = toPath.invoke( file ); - delete.invoke( null, path ); - } - catch ( IllegalAccessException e ) - { - throw new RuntimeException( e ); - } - catch ( InvocationTargetException e ) - { - throw (IOException) e.getTargetException(); - } + Files.delete( file.toPath() ); } /** @@ -230,7 +93,7 @@ public static void delete( @Nonnull File file ) */ public static boolean isJava7() { - return IS_JAVA7; + return true; } /** @@ -238,7 +101,6 @@ public static boolean isJava7() */ public static boolean isAtLeastJava7() { - return IS_JAVA7; + return true; } - } diff --git a/src/test/java/org/apache/maven/shared/utils/io/DirectoryScannerTest.java b/src/test/java/org/apache/maven/shared/utils/io/DirectoryScannerTest.java index f19562f0..9ede93a0 100644 --- a/src/test/java/org/apache/maven/shared/utils/io/DirectoryScannerTest.java +++ b/src/test/java/org/apache/maven/shared/utils/io/DirectoryScannerTest.java @@ -153,7 +153,6 @@ public void followSymlinksFalse() throws IOException { assumeFalse( Os.isFamily( Os.FAMILY_WINDOWS ) ); - assumeTrue( Java7Support.isAtLeastJava7() ); File testDir = SymlinkTestSetup.createStandardSymlinkTestDir( new File( "target/test/symlinkTestCase" ) ); @@ -191,7 +190,6 @@ public void followSymlinks() throws IOException { assumeFalse( Os.isFamily( Os.FAMILY_WINDOWS ) ); - assumeTrue( Java7Support.isAtLeastJava7() ); DirectoryScanner ds = new DirectoryScanner(); File testDir = SymlinkTestSetup.createStandardSymlinkTestDir( new File( "target/test/symlinkTestCase" ) ); diff --git a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java index e6ef175e..69e72a9d 100644 --- a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java +++ b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java @@ -4,7 +4,9 @@ import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -21,6 +23,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.URL; +import java.nio.file.Files; import java.util.Arrays; import java.util.HashSet; import java.util.List; @@ -442,7 +445,6 @@ public void copyFile1() public void copyFileThatIsSymlink() throws Exception { - assumeTrue( Java7Support.isAtLeastJava7() ); assumeFalse( Os.isFamily( Os.FAMILY_WINDOWS ) ); File destination = new File( tempFolder.getRoot(), "symCopy.txt" ); @@ -450,7 +452,8 @@ public void copyFileThatIsSymlink() File testDir = SymlinkTestSetup.createStandardSymlinkTestDir( new File( "target/test/symlinkCopy" ) ); FileUtils.copyFile( new File( testDir, "symR" ), destination ); - assertTrue( Java7Support.isSymLink( destination )); + + assertTrue( Files.isSymbolicLink( destination.toPath() ) ); } @@ -1439,6 +1442,19 @@ public void extensionUnixNonRootPathOnUnix() assertThat( FileUtils.extension( "/test/foo.bar.txt" ), is( "txt" ) ); } + @Test + public void createAndReadSymlink() + throws Exception + { + assumeThat( System.getProperty( "os.name" ), not( startsWith( "Windows" ) ) ); + File file = new File( "target/fzz" ); + FileUtils.createSymbolicLink( file, new File("../target") ); + + final File file1 = Files.readSymbolicLink( file.toPath() ).toFile(); + assertEquals( "target", file1.getName() ); + Files.delete( file.toPath() ); + } + //// constants for testing private static final String[] MINIMUM_DEFAULT_EXCLUDES = { diff --git a/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java b/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java index 9652e53f..39c3eb13 100644 --- a/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java +++ b/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java @@ -27,7 +27,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assume.assumeThat; import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.startsWith; public class Java7SupportTest { @@ -35,28 +34,8 @@ public class Java7SupportTest public void testIsSymLink() throws Exception { - File file = new File( "." ); - if ( Java7Support.isAtLeastJava7() ) - { - assertFalse( Java7Support.isSymLink( file ) ); - } - } - - @Test - public void createAndReadSymlink() - throws Exception - { - assumeThat( System.getProperty( "os.name" ), not( startsWith( "Windows" ) ) ); - File file = new File( "target/fzz" ); - if ( Java7Support.isAtLeastJava7() ) - { - Java7Support.createSymbolicLink( file, new File("../target") ); - - final File file1 = Java7Support.readSymbolicLink( file ); - assertEquals( "target", file1.getName()); - Java7Support.delete( file ); - } + assertFalse( Java7Support.isSymLink( file ) ); } } diff --git a/src/test/java/org/apache/maven/shared/utils/io/SymlinkTestSetup.java b/src/test/java/org/apache/maven/shared/utils/io/SymlinkTestSetup.java index 6ae3ba94..9283c970 100644 --- a/src/test/java/org/apache/maven/shared/utils/io/SymlinkTestSetup.java +++ b/src/test/java/org/apache/maven/shared/utils/io/SymlinkTestSetup.java @@ -51,14 +51,12 @@ public static File createStandardSymlinkTestDir( File root ) write( new File( srcDir, "fileX.txt" ), "FileX payload", StandardCharsets.UTF_8 ); // todo: set file attributes (not used here) - Java7Support.createSymbolicLink( new File( srcDir, "symDir" ), new File( "targetDir" ) ); - Java7Support.createSymbolicLink( new File( srcDir, "symLinkToDirOnTheOutside" ), - new File( "../dirOnTheOutside" ) ); - Java7Support.createSymbolicLink( new File( srcDir, "symLinkToFileOnTheOutside" ), - new File( "../onTheOutside.txt" ) ); - Java7Support.createSymbolicLink( new File( srcDir, "symR" ), new File( "fileR.txt" ) ); - Java7Support.createSymbolicLink( new File( srcDir, "symW" ), new File( "fileW.txt" ) ); - Java7Support.createSymbolicLink( new File( srcDir, "symX" ), new File( "fileX.txt" ) ); + FileUtils.createSymbolicLink( new File( srcDir, "symDir" ), new File( "targetDir" ) ); + FileUtils.createSymbolicLink( new File( srcDir, "symLinkToDirOnTheOutside" ), new File( "../dirOnTheOutside" ) ); + FileUtils.createSymbolicLink( new File( srcDir, "symLinkToFileOnTheOutside" ), new File( "../onTheOutside.txt" ) ); + FileUtils.createSymbolicLink( new File( srcDir, "symR" ), new File( "fileR.txt" ) ); + FileUtils.createSymbolicLink( new File( srcDir, "symW" ), new File( "fileW.txt" ) ); + FileUtils.createSymbolicLink( new File( srcDir, "symX" ), new File( "fileX.txt" ) ); return srcDir; } } From 77ff09b0ee9732fe203f4c58b45f6c1e00d92f0d Mon Sep 17 00:00:00 2001 From: Rob Oxspring Date: Sun, 17 May 2020 00:55:09 +0100 Subject: [PATCH 137/265] [MRESOURCES-236] Attempt to copy file permissions when copying files (#29) --- .../maven/shared/utils/io/FileUtils.java | 34 +++++++++++++++++++ .../maven/shared/utils/io/FileUtilsTest.java | 14 ++++++++ 2 files changed, 48 insertions(+) diff --git a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java index f7de64c7..895cf449 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java +++ b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java @@ -819,6 +819,8 @@ private static void doCopyFile( @Nonnull File source, @Nonnull File destination pos += output.transferFrom( input, pos, count ); } } + + copyFilePermissions( source, destination ); } /** @@ -1840,6 +1842,38 @@ public static void copyFile( @Nonnull File from, @Nonnull File to, @Nullable Str copyFile( from, to ); } } + + copyFilePermissions( from, to ); + } + + /** + * Attempts to copy file permissions from the source to the destination file. + * Initially attempts to copy posix file permissions, assuming that the files are both on posix filesystems. + * If the initial attempts fail then a second attempt using less precise permissions model. + * Note that permissions are copied on a best-efforts basis, + * failure to copy permissions will not result in an exception. + * + * @param source the file to copy permissions from. + * @param destination the file to copy permissions to. + */ + private static void copyFilePermissions( @Nonnull File source, @Nonnull File destination ) + throws IOException + { + try + { + // attempt to copy posix file permissions + Files.setPosixFilePermissions( + destination.toPath(), + Files.getPosixFilePermissions( source.toPath() ) + ); + } + catch ( UnsupportedOperationException e ) + { + // fallback to setting partial permissions + destination.setExecutable( source.canExecute() ); + destination.setReadable( source.canRead() ); + destination.setWritable( source.canWrite() ); + } } /** diff --git a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java index 69e72a9d..b5f17e69 100644 --- a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java +++ b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java @@ -493,6 +493,20 @@ public void deleteFileLegacyNofile() assertFalse( FileUtils.deleteLegacyStyle( destination ) ); } + @Test + public void copyFileWithPermissions() + throws Exception + { + File source = new File( "/bin/sh" ); + assumeThat( "Need an executable to copy", source.exists(), is( true ) ); + + File destination = new File( tempFolder.getRoot(), "executable" ); + + FileUtils.copyFile( source, destination ); + + assertThat( "Check executable", destination.canExecute(), is( true ) ); + } + @Test public void copyFile2() throws Exception From cc9d8f3b817e98fc9139c0de9f0865442f7a9029 Mon Sep 17 00:00:00 2001 From: olivier lamy Date: Sun, 17 May 2020 11:03:50 +1000 Subject: [PATCH 138/265] this file is not needed anymore Signed-off-by: olivier lamy --- .../shared/utils/io/Java7SupportTest.java | 41 ------------------- 1 file changed, 41 deletions(-) delete mode 100644 src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java diff --git a/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java b/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java deleted file mode 100644 index 39c3eb13..00000000 --- a/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.apache.maven.shared.utils.io; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assume.assumeThat; -import static org.hamcrest.CoreMatchers.not; - -public class Java7SupportTest -{ - @Test - public void testIsSymLink() - throws Exception - { - File file = new File( "." ); - assertFalse( Java7Support.isSymLink( file ) ); - } - -} From 92a5ba3c431affcabb2cebd11ca17fe02b15748c Mon Sep 17 00:00:00 2001 From: olivier lamy Date: Sun, 17 May 2020 11:03:50 +1000 Subject: [PATCH 139/265] Fix issue with copying file executable test with ASF Jenkins Signed-off-by: olivier lamy --- pom.xml | 1 + .../maven/shared/utils/io/FileUtilsTest.java | 14 +++++-- .../shared/utils/io/Java7SupportTest.java | 41 ------------------- src/test/resources/executable | 1 + 4 files changed, 12 insertions(+), 45 deletions(-) delete mode 100644 src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java create mode 100755 src/test/resources/executable diff --git a/pom.xml b/pom.xml index 681089d4..fa314445 100644 --- a/pom.xml +++ b/pom.xml @@ -142,6 +142,7 @@ diff --git a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java index b5f17e69..46b94ffe 100644 --- a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java +++ b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java @@ -497,14 +497,20 @@ public void deleteFileLegacyNofile() public void copyFileWithPermissions() throws Exception { - File source = new File( "/bin/sh" ); - assumeThat( "Need an executable to copy", source.exists(), is( true ) ); + File source = new File( "src/test/resources/executable" ); + source.setExecutable( true ); + assumeThat( "Need an existing file to copy", source.exists(), is( true ) ); + assumeThat( "Need an executable file to copy", source.canExecute(), is( true ) ); - File destination = new File( tempFolder.getRoot(), "executable" ); + File destination = new File( tempFolder.getRoot(), "executable-copy" ); FileUtils.copyFile( source, destination ); - assertThat( "Check executable", destination.canExecute(), is( true ) ); + assertThat( "destination not exists: " + destination.getAbsolutePath() + + ", directory content: " + Arrays.asList( destination.getParentFile().list() ), + Files.exists( destination.toPath() ), is( true ) ); + + assertThat( "Check copy executable", destination.canExecute(), is( true ) ); } @Test diff --git a/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java b/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java deleted file mode 100644 index 39c3eb13..00000000 --- a/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.apache.maven.shared.utils.io; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assume.assumeThat; -import static org.hamcrest.CoreMatchers.not; - -public class Java7SupportTest -{ - @Test - public void testIsSymLink() - throws Exception - { - File file = new File( "." ); - assertFalse( Java7Support.isSymLink( file ) ); - } - -} diff --git a/src/test/resources/executable b/src/test/resources/executable new file mode 100755 index 00000000..e804f19a --- /dev/null +++ b/src/test/resources/executable @@ -0,0 +1 @@ +noop From 8b35ffcf1b410a0870a22ae37f18d96423d42852 Mon Sep 17 00:00:00 2001 From: Rob Oxspring src/test/resources/directorywalker/**/* src/test/resources/symlinks/**/* +src/test/resources/executable Date: Sun, 17 May 2020 21:57:24 +0100 Subject: [PATCH 140/265] [MSHARED-681] createSymbolicLink() overwrites existing different symlinks Tests explicitly assuming Windows use consistent assumption --- .../maven/shared/utils/io/FileUtils.java | 15 ++++++++-- .../maven/shared/utils/io/FileUtilsTest.java | 29 +++++++++++++++++-- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java index 895cf449..24dcf985 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java +++ b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java @@ -42,6 +42,7 @@ import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.file.Files; +import java.nio.file.Path; import java.security.SecureRandom; import java.text.DecimalFormat; import java.util.ArrayList; @@ -2004,10 +2005,18 @@ static boolean isSymbolicLinkLegacy( @Nonnull final File file ) @Nonnull public static File createSymbolicLink( @Nonnull File symlink, @Nonnull File target ) throws IOException { - if ( !Files.exists( symlink.toPath() ) ) + final Path symlinkPath = symlink.toPath(); + + if ( Files.exists( symlinkPath ) ) { - return Files.createSymbolicLink( symlink.toPath(), target.toPath() ).toFile(); + if ( target.equals( Files.readSymbolicLink( symlinkPath ).toFile() ) ) + { + return symlink; + } + + Files.delete( symlinkPath ); } - return symlink; + + return Files.createSymbolicLink( symlinkPath, target.toPath() ).toFile(); } } diff --git a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java index 46b94ffe..b9fd7c45 100644 --- a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java +++ b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java @@ -1429,7 +1429,7 @@ public void isASymbolicLink() throws IOException { // This testcase will pass when running under java7 or higher - assumeThat( Os.isFamily(Os.FAMILY_WINDOWS), is(false) ); + assumeFalse( Os.isFamily( Os.FAMILY_WINDOWS ) ); File file = new File( "src/test/resources/symlinks/src/symDir" ); assertTrue(FileUtils.isSymbolicLink(file )); @@ -1466,7 +1466,8 @@ public void extensionUnixNonRootPathOnUnix() public void createAndReadSymlink() throws Exception { - assumeThat( System.getProperty( "os.name" ), not( startsWith( "Windows" ) ) ); + assumeFalse( Os.isFamily( Os.FAMILY_WINDOWS ) ); + File file = new File( "target/fzz" ); FileUtils.createSymbolicLink( file, new File("../target") ); @@ -1475,6 +1476,30 @@ public void createAndReadSymlink() Files.delete( file.toPath() ); } + @Test + public void createSymbolicLinkWithDifferentTargetOverwritesSymlink() + throws Exception + { + assumeFalse( Os.isFamily( Os.FAMILY_WINDOWS ) ); + + // Arrange + + final File symlink1 = new File( tempFolder.getRoot(), "symlink" ); + + FileUtils.createSymbolicLink( symlink1, testFile1 ); + + // Act + + final File symlink2 = FileUtils.createSymbolicLink( symlink1, testFile2 ); + + // Assert + + assertThat( + Files.readSymbolicLink( symlink2.toPath() ).toFile(), + CoreMatchers.equalTo( testFile2 ) + ); + } + //// constants for testing private static final String[] MINIMUM_DEFAULT_EXCLUDES = { From 87da81f880be3ad32080e4d2176e280958aff2d7 Mon Sep 17 00:00:00 2001 From: olivier lamy Date: Tue, 26 May 2020 11:10:42 +1000 Subject: [PATCH 141/265] bump version Signed-off-by: olivier lamy --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index fa314445..1800bb9d 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ maven-shared-utils -3.2.2-SNAPSHOT +3.3.0-SNAPSHOT Apache Maven Shared Utils Shared utilities for use by Maven core and plugins From e57180309a64758e161513d80f1185e13dc84826 Mon Sep 17 00:00:00 2001 From: Rob OxspringDate: Fri, 1 May 2020 00:35:56 +0100 Subject: [PATCH 142/265] [MSHARED-884] - Add tests for existing FileUtils.copyFile() method with no filtering. - Add tests for existing FileUtils.copyFile() method with filtering. - Refactor to deal with the simpler no-filters case first - Only overwrite existing file if there's a content change - Avoid conflicts with Java 9 additional Buffer methods - Consistent explicit use of Charset instances - Prefer Files.newBufferedReader/Writer methods - Use TimeUnit rather than constants in millisecond --- .../maven/shared/utils/io/FileUtils.java | 164 ++++++--- .../maven/shared/utils/io/FileUtilsTest.java | 321 +++++++++++++++++- 2 files changed, 426 insertions(+), 59 deletions(-) diff --git a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java index f7de64c7..8929c4d3 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java +++ b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java @@ -30,17 +30,20 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.FileReader; import java.io.IOException; import java.io.InputStream; -import java.io.InputStreamReader; import java.io.OutputStream; -import java.io.OutputStreamWriter; +import java.io.RandomAccessFile; import java.io.Reader; import java.io.Writer; import java.net.URL; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CoderResult; import java.nio.file.Files; import java.security.SecureRandom; import java.text.DecimalFormat; @@ -110,7 +113,7 @@ protected FileUtils() /** * The file copy buffer size (30 MB) */ - private static final long FILE_COPY_BUFFER_SIZE = ONE_MB * 30; + private static final int FILE_COPY_BUFFER_SIZE = ONE_MB * 30; /** * The vm line separator @@ -271,13 +274,12 @@ public static boolean fileExists( @Nonnull String fileName ) @Nonnull public static String fileRead( @Nonnull File file, @Nullable String encoding ) throws IOException { - StringBuilder buf = new StringBuilder(); - if ( encoding == null ) - { - encoding = Charset.defaultCharset().name(); - } + Charset charset = charset( encoding ); + + StringBuilder buf = new StringBuilder(); + - try ( Reader reader = new InputStreamReader( new FileInputStream( file ), encoding ) ) + try ( Reader reader = Files.newBufferedReader( file.toPath(), charset ) ) { int count; char[] b = new char[512]; @@ -329,15 +331,11 @@ public static void fileAppend( @Nonnull String fileName, @Nonnull String data ) public static void fileAppend( @Nonnull String fileName, @Nullable String encoding, @Nonnull String data ) throws IOException { - - if ( encoding == null ) - { - encoding = Charset.defaultCharset().name(); - } - + Charset charset = charset( encoding ); + try ( OutputStream out = new FileOutputStream( fileName, true ) ) { - out.write( data.getBytes( encoding ) ); + out.write( data.getBytes( charset ) ); } } @@ -381,13 +379,9 @@ public static void fileWrite( @Nonnull String fileName, @Nullable String encodin public static void fileWrite( @Nonnull File file, @Nullable String encoding, @Nonnull String data ) throws IOException { - - if ( encoding == null ) - { - encoding = Charset.defaultCharset().name(); - } + Charset charset = charset( encoding ); - try ( Writer writer = new OutputStreamWriter( new FileOutputStream( file ), encoding ) ) + try ( Writer writer = Files.newBufferedWriter( file.toPath(), charset ) ) { writer.write( data ); } @@ -418,13 +412,9 @@ public static void fileWriteArray( @Nonnull File file, @Nullable String... data public static void fileWriteArray( @Nonnull File file, @Nullable String encoding, @Nullable String... data ) throws IOException { - - if ( encoding == null ) - { - encoding = Charset.defaultCharset().name(); - } + Charset charset = charset( encoding ); - try ( Writer writer = new OutputStreamWriter( new FileOutputStream( file ), encoding ) ) + try ( Writer writer = Files.newBufferedWriter( file.toPath(), charset ) ) { for ( int i = 0; data != null && i < data.length; i++ ) { @@ -1810,34 +1800,97 @@ public static void copyFile( @Nonnull File from, @Nonnull File to, @Nullable Str @Nullable FilterWrapper[] wrappers, boolean overwrite ) throws IOException { - if ( wrappers != null && wrappers.length > 0 ) + if ( wrappers == null || wrappers.length == 0 ) { - - if ( encoding == null || encoding.isEmpty() ) + if ( overwrite || to.lastModified() < from.lastModified() ) { - encoding = Charset.defaultCharset().name(); + copyFile( from, to ); } - + } + else + { + Charset charset = charset( encoding ); + // buffer so it isn't reading a byte at a time! - try ( Reader fileReader = - new BufferedReader( new InputStreamReader( new FileInputStream( from ), encoding ) ); - Writer fileWriter = new OutputStreamWriter( new FileOutputStream( to ), encoding ) ) + try ( Reader fileReader = Files.newBufferedReader( from.toPath(), charset ) ) { - Reader wrapped = fileReader; for ( FilterWrapper wrapper : wrappers ) { wrapped = wrapper.getReader( wrapped ); } - IOUtil.copy( wrapped, fileWriter ); - } - } - else - { - if ( to.lastModified() < from.lastModified() || overwrite ) - { - copyFile( from, to ); + if ( overwrite || !to.exists() ) + { + try ( Writer fileWriter = Files.newBufferedWriter( to.toPath(), charset ) ) + { + IOUtil.copy( wrapped, fileWriter ); + } + } + else + { + CharsetEncoder encoder = charset.newEncoder(); + + int totalBufferSize = FILE_COPY_BUFFER_SIZE; + + int charBufferSize = ( int ) Math.floor( totalBufferSize / ( 2 + 2 * encoder.maxBytesPerChar() ) ); + int byteBufferSize = ( int ) Math.ceil( charBufferSize * encoder.maxBytesPerChar() ); + + CharBuffer newChars = CharBuffer.allocate( charBufferSize ); + ByteBuffer newBytes = ByteBuffer.allocate( byteBufferSize ); + ByteBuffer existingBytes = ByteBuffer.allocate( byteBufferSize ); + + CoderResult coderResult; + int existingRead; + boolean writing = false; + + try ( final RandomAccessFile existing = new RandomAccessFile( to, "rw" ) ) + { + int n; + while ( -1 != ( n = wrapped.read( newChars ) ) ) + { + ( ( Buffer ) newChars ).flip(); + + coderResult = encoder.encode( newChars, newBytes, n != 0 ); + if ( coderResult.isError() ) + { + coderResult.throwException(); + } + + ( ( Buffer ) newBytes ).flip(); + + if ( !writing ) + { + existingRead = existing.read( existingBytes.array(), 0, newBytes.remaining() ); + ( ( Buffer ) existingBytes ).position( existingRead ); + ( ( Buffer ) existingBytes ).flip(); + + if ( newBytes.compareTo( existingBytes ) != 0 ) + { + writing = true; + if ( existingRead > 0 ) + { + existing.seek( existing.getFilePointer() - existingRead ); + } + } + } + + if ( writing ) + { + existing.write( newBytes.array(), 0, newBytes.remaining() ); + } + + ( ( Buffer ) newChars ).clear(); + ( ( Buffer ) newBytes ).clear(); + ( ( Buffer ) existingBytes ).clear(); + } + + if ( existing.length() > existing.getFilePointer() ) + { + existing.setLength( existing.getFilePointer() ); + } + } + } } } } @@ -1856,7 +1909,7 @@ public static void copyFile( @Nonnull File from, @Nonnull File to, @Nullable Str if ( file.exists() ) { - try ( BufferedReader reader = new BufferedReader( new FileReader( file ) ) ) + try ( BufferedReader reader = Files.newBufferedReader( file.toPath(), Charset.defaultCharset() ) ) { for ( String line = reader.readLine(); line != null; line = reader.readLine() ) { @@ -1873,6 +1926,23 @@ public static void copyFile( @Nonnull File from, @Nonnull File to, @Nullable Str } + /** + * Returns the named charset or the default charset. + * @param encoding the name or alias of the charset, null or empty + * @return A charset object for the named or default charset. + */ + private static Charset charset( String encoding ) + { + if ( encoding == null || encoding.isEmpty() ) + { + return Charset.defaultCharset(); + } + else + { + return Charset.forName( encoding ); + } + } + /** * For Windows OS, check if the file name contains any of the following characters: * ":", "*", "?", "\"", "<", ">", "|"
diff --git a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java index 69e72a9d..24bf43d3 100644 --- a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java +++ b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java @@ -14,19 +14,38 @@ import static org.junit.Assume.assumeThat; import static org.junit.Assume.assumeTrue; +import org.apache.maven.shared.utils.Os; +import org.apache.maven.shared.utils.testhelpers.FileTestHelper; +import org.codehaus.plexus.util.InterpolationFilterReader; +import org.hamcrest.CoreMatchers; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.rules.TestName; + +import javax.annotation.Nonnull; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; import java.net.URL; import java.nio.file.Files; import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -47,16 +66,6 @@ * under the License. */ -import org.apache.maven.shared.utils.Os; -import org.apache.maven.shared.utils.testhelpers.FileTestHelper; -import org.hamcrest.CoreMatchers; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.rules.TestName; - /** * This is used to test FileUtils for correctness. * @@ -441,9 +450,298 @@ public void copyFile1() testFile1.lastModified() == destination.lastModified());*/ } + /** A time today, rounded down to the previous minute */ + private static long MODIFIED_TODAY = (System.currentTimeMillis() / TimeUnit.MINUTES.toMillis( 1 )) * TimeUnit.MINUTES.toMillis( 1 ); + + /** A time yesterday, rounded down to the previous minute */ + private static long MODIFIED_YESTERDAY = MODIFIED_TODAY - TimeUnit.DAYS.toMillis( 1 ); + + /** A time last week, rounded down to the previous minute */ + private static long MODIFIED_LAST_WEEK = MODIFIED_TODAY - TimeUnit.DAYS.toMillis( 7 ); + @Test - public void copyFileThatIsSymlink() + public void copyFileWithNoFiltersAndNoDestination() throws Exception + { + File from = write( + "from.txt", + MODIFIED_YESTERDAY, + "Hello World!" + ); + File to = new File( + tempFolder.getRoot(), + "to.txt" + ); + + FileUtils.copyFile( from, to, null, ( FileUtils.FilterWrapper[] ) null); + + assertTrue( + "to.txt did not exist so should have been written", + to.lastModified() >= MODIFIED_TODAY + ); + assertFileContent( to, "Hello World!" ); + } + + @Test + public void copyFileWithNoFiltersAndOutdatedDestination() + throws Exception + { + File from = write( + "from.txt", + MODIFIED_YESTERDAY, + "Hello World!" + ); + File to = write( + "to.txt", + MODIFIED_LAST_WEEK, + "Older content" + ); + + FileUtils.copyFile( from, to, null, ( FileUtils.FilterWrapper[] ) null); + + assertTrue( + "to.txt was outdated so should have been overwritten", + to.lastModified() >= MODIFIED_TODAY + ); + assertFileContent( to, "Hello World!" ); + } + + @Test + public void copyFileWithNoFiltersAndNewerDestination() + throws Exception + { + File from = write( + "from.txt", + MODIFIED_LAST_WEEK, + "Hello World!" + ); + File to = write( + "to.txt", + MODIFIED_YESTERDAY, + "Older content" + ); + + FileUtils.copyFile( from, to, null, ( FileUtils.FilterWrapper[] ) null); + + assertTrue( + "to.txt was newer so should have been left alone", + to.lastModified() < MODIFIED_TODAY + ); + assertFileContent( to, "Older content" ); + } + + @Test + public void copyFileWithNoFiltersAndNewerDestinationButForcedOverwrite() + throws Exception + { + File from = write( + "from.txt", + MODIFIED_LAST_WEEK, + "Hello World!" + ); + File to = write( + "to.txt", + MODIFIED_YESTERDAY, + "Older content" + ); + + FileUtils.copyFile( from, to, null, null, true); + + assertTrue( + "to.txt was newer but the overwrite should have been forced", + to.lastModified() >= MODIFIED_TODAY + ); + assertFileContent( to, "Hello World!" ); + } + + @Test + public void copyFileWithFilteringButNoFilters() + throws Exception + { + File from = write( + "from.txt", + MODIFIED_YESTERDAY, + "Hello ${name}!" + ); + File to = write( + "to.txt", + MODIFIED_LAST_WEEK, + "Older content" + ); + + FileUtils.copyFile( from, to, null ); + + assertTrue( + "to.txt was outdated so should have been overwritten", + to.lastModified() >= MODIFIED_TODAY + ); + assertFileContent( to, "Hello ${name}!" ); + } + + @Test + public void copyFileWithFilteringAndNoDestination() + throws Exception + { + File from = write( + "from.txt", + MODIFIED_YESTERDAY, + "Hello ${name}!" + ); + File to = new File( + tempFolder.getRoot(), + "to.txt" + ); + + FileUtils.copyFile( from, to, null, wrappers( "name", "Bob" ) ); + + assertTrue( + "to.txt did not exist so should have been written", + to.lastModified() >= MODIFIED_TODAY + ); + assertFileContent( to, "Hello Bob!" ); + } + + @Test + public void copyFileWithFilteringAndOutdatedDestination() + throws Exception + { + File from = write( + "from.txt", + MODIFIED_YESTERDAY, + "Hello ${name}!" + ); + File to = write( + "to.txt", + MODIFIED_LAST_WEEK, + "Older content" + ); + + FileUtils.copyFile( from, to, null, wrappers( "name", "Bob" ) ); + + assertTrue( + "to.txt was outdated so should have been overwritten", + to.lastModified() >= MODIFIED_TODAY + ); + assertFileContent( to, "Hello Bob!" ); + } + + @Test + public void copyFileWithFilteringAndNewerDestinationButForcedOverwrite() + throws Exception + { + File from = write( + "from.txt", + MODIFIED_LAST_WEEK, + "Hello ${name}!" + ); + File to = write( + "to.txt", + MODIFIED_YESTERDAY, + "Older content" + ); + + FileUtils.copyFile( from, to, null, wrappers( "name", "Bob" ), true ); + + assertTrue( + "to.txt was newer but the overwrite should have been forced", + to.lastModified() >= MODIFIED_TODAY + ); + assertFileContent( to, "Hello Bob!" ); + } + + @Test + public void copyFileWithFilteringAndNewerDestinationButModifiedContent() + throws Exception + { + File from = write( + "from.txt", + MODIFIED_LAST_WEEK, + "Hello ${name}!" + ); + File to = write( + "to.txt", + MODIFIED_YESTERDAY, + "Hello Charlie!" + ); + + FileUtils.copyFile( from, to, null, wrappers( "name", "Bob" ) ); + + assertTrue( + "to.txt was outdated so should have been overwritten", + to.lastModified() >= MODIFIED_TODAY + ); + assertFileContent( to, "Hello Bob!" ); + } + + @Test + public void copyFileWithFilteringAndNewerDestinationAndMatchingContent() + throws Exception + { + File from = write( + "from.txt", + MODIFIED_LAST_WEEK, + "Hello ${name}!" + ); + File to = write( + "to.txt", + MODIFIED_YESTERDAY, + "Hello Bob!" + ); + + String encoding = null; + + FileUtils.copyFile( from, to, null, wrappers( "name", "Bob" ) ); + + assertFileContent( to, "Hello Bob!" ); + assertTrue( + "to.txt content should be unchanged and have been left alone", + to.lastModified() < MODIFIED_TODAY + ); + } + + private FileUtils.FilterWrapper[] wrappers( String key, String value ) + { + final Map map = new HashMap(); + map.put( key, value ); + return new FileUtils.FilterWrapper[] + { + new FileUtils.FilterWrapper() + { + @Override + public Reader getReader( Reader reader ) + { + return new InterpolationFilterReader( reader, map ); + } + } + }; + } + + private File write( @Nonnull String name, long lastModified, @Nonnull String text) throws IOException + { + final File file = new File( tempFolder.getRoot(), name ); + try ( final Writer writer = new FileWriter( file ) ) { + writer.write(text); + } + assertTrue( file.setLastModified( lastModified ) ); + assertEquals( "Failed to set lastModified date on " + file.getPath(), lastModified, file.lastModified() ); + return file; + } + + private static void assertFileContent( @Nonnull File file, @Nonnull String expected ) throws IOException + { + try ( Reader in = new FileReader( file )) + { + assertEquals( + "Expected " + file.getPath() + " to contain: " + expected, + expected, + IOUtil.toString( in ) + ); + } + } + + @Test + public void copyFileThatIsSymlink() + throws Exception { assumeFalse( Os.isFamily( Os.FAMILY_WINDOWS ) ); @@ -457,7 +755,6 @@ public void copyFileThatIsSymlink() } - @Test public void deleteFile() throws Exception From 83d44c98dbc340006a28d2fd0acbf9b1844ac74c Mon Sep 17 00:00:00 2001 From: DomDate: Fri, 22 May 2020 04:31:50 +0200 Subject: [PATCH 143/265] [MSHARED-881] use try-with-resources --- .../maven/shared/utils/io/FileUtilsTest.java | 23 ++++--------------- 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java index 86dc0a2e..66d1844c 100644 --- a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java +++ b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java @@ -156,10 +156,9 @@ void createFile( File file, long size ) void assertEqualContent( byte[] b0, File file ) throws IOException { - InputStream is = new java.io.FileInputStream( file ); int count = 0, numRead = 0; byte[] b1 = new byte[b0.length]; - try + try ( InputStream is = new FileInputStream( file ) ) { while ( count < b0.length && numRead >= 0 ) { @@ -172,10 +171,6 @@ void assertEqualContent( byte[] b0, File file ) assertThat( "byte " + i + " differs", b1[i], is( b0[i] ) ); } } - finally - { - is.close(); - } } void deleteFile( File file ) @@ -345,17 +340,12 @@ public void copyURLToFile() String resourceName = "/java/lang/Object.class"; FileUtils.copyURLToFile( getClass().getResource( resourceName ), file ); - // Tests that resuorce was copied correctly - FileInputStream fis = new FileInputStream( file ); - try + // Tests that resource was copied correctly + try ( FileInputStream fis = new FileInputStream( file ) ) { assertThat( "Content is not equal.", IOUtil.contentEquals( getClass().getResourceAsStream( resourceName ), fis ), is( true ) ); } - finally - { - fis.close(); - } //TODO Maybe test copy to itself like for copyFile() } @@ -1180,15 +1170,10 @@ public void fileUtils() String filename = file1.getAbsolutePath(); //Create test file on-the-fly (used to be in CVS) - OutputStream out = new java.io.FileOutputStream( file1 ); - try + try ( OutputStream out = new java.io.FileOutputStream( file1 ) ) { out.write( "This is a test".getBytes( "UTF-8" ) ); } - finally - { - out.close(); - } File file2 = new File( tempFolder.getRoot(), "test2.txt" ); From 35760122cedc997e28e81b38e194dfa8abf9433a Mon Sep 17 00:00:00 2001 From: Elliotte Rusty Harold Date: Wed, 27 May 2020 08:07:04 -0400 Subject: [PATCH 144/265] update to commons-lang 3.8.1 (#33) --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 1800bb9d..772d7947 100644 --- a/pom.xml +++ b/pom.xml @@ -94,13 +94,13 @@ org.apache.commons commons-lang3 -3.4 +3.8.1 test foo * a\b\c.jpg --> a\b\c @@ -691,7 +695,9 @@ public static boolean contentEquals( @Nonnull final File file1, @Nonnull final F * * @param filename the path of the file * @return the filename minus extension + * @deprecated use {@code org.apache.commons.io.FilenameUtils.removeExtension()} */ + @Deprecated @Nonnull public static String removeExtension( @Nonnull final String filename ) { String ext = extension( filename ); @@ -706,7 +712,7 @@ public static boolean contentEquals( @Nonnull final File file1, @Nonnull final F } /** - * Get extension from filename. E.g. + * Get extension from a path. E.g. * * com.google.code.findbugs jsr305 -3.0.0 +3.0.2 provided * foo.txt --> "txt" @@ -716,7 +722,9 @@ public static boolean contentEquals( @Nonnull final File file1, @Nonnull final F * * @param filename the path of the file * @return the extension of filename or "" if none + * @deprecated use {@code org.apache.commons.io.FilenameUtils.getExtension()} */ + @Deprecated @Nonnull public static String getExtension( @Nonnull final String filename ) { return extension( filename ); @@ -734,7 +742,9 @@ public static boolean contentEquals( @Nonnull final File file1, @Nonnull final F * @throws IOException ifsource
does not exist, the file in *destinationDirectory
cannot be written to, or an IO error * occurs during copying. + * @deprecated use {@code org.apache.commons.io.FileUtils.copyFileToDirectory()} */ + @Deprecated public static void copyFileToDirectory( @Nonnull final File source, @Nonnull final File destinationDirectory ) throws IOException { @@ -784,7 +794,10 @@ private static void copyFileToDirectoryIfModified( @Nonnull final File source, * @throws IOException ifsource
does not exist,destination
cannot be * written to, or an IO error occurs during copying * @throws java.io.FileNotFoundException ifdestination
is a directory + * @deprecated use {@code java.nio.Files.copy(source.toPath(), destination.toPath(), CopyOptions.NOFOLLOW_LINKS, + * CopyOptions.REPLACE_EXISTING)} */ + @Deprecated public static void copyFile( @Nonnull final File source, @Nonnull final File destination ) throws IOException { @@ -891,6 +904,8 @@ private static boolean copyFileIfModified( @Nonnull final File source, @Nonnull *- *
destination
cannot be written to- an IO error occurs during copying
*
source
URL cannot be openedsource
cannot be openeddestination
cannot be written tonull
if too many ..'s.
+ * @deprecated use {@code org.apache.commons.io.FileNameUtils.normalize()}
*/
+ @Deprecated
@Nonnull public static String normalize( @Nonnull final String path )
{
String normalized = path;
@@ -1083,11 +1103,13 @@ private static void copyStreamToFile( @Nonnull @WillClose final InputStream sour
}
/**
- * Delete a file. If file is directory delete it and all sub-directories.
+ * Delete a file. If file is directory, delete it and all sub-directories.
*
* @param file the file path
* @throws IOException if any
+ * @deprecated use {@code org.apache.commons.io.FileUtils.deleteQuietly()}
*/
+ @Deprecated
public static void forceDelete( @Nonnull final String file )
throws IOException
{
@@ -1095,11 +1117,13 @@ public static void forceDelete( @Nonnull final String file )
}
/**
- * Delete a file. If file is directory delete it and all sub-directories.
+ * Delete a file. If file is directory, delete it and all sub-directories.
*
* @param file a file
* @throws IOException if any
+ * @deprecated use {@code org.apache.commons.io.FileUtils.deleteQuietly()}
*/
+ @Deprecated
public static void forceDelete( @Nonnull final File file )
throws IOException
{
@@ -1123,13 +1147,13 @@ public static void forceDelete( @Nonnull final File file )
}
/**
- * deletes a file.
+ * Deletes a file.
*
- * @param file The file to delete
+ * @param file the file to delete
* @throws IOException if the file cannot be deleted
+ * @deprecated use {@code java.nio.files.Files.delete(file.toPath())}
*/
-
-
+ @Deprecated
public static void delete( @Nonnull File file )
throws IOException
{
@@ -1137,9 +1161,11 @@ public static void delete( @Nonnull File file )
}
/**
- * @param file The file.
+ * @param file the file
* @return true / false
+ * @deprecated use {@code java.nio.files.Files.delete(file.toPath())}
*/
+ @Deprecated
public static boolean deleteLegacyStyle( @Nonnull File file )
{
try
@@ -1974,7 +2000,9 @@ private static void copyFilePermissions( @Nonnull File source, @Nonnull File des
* @param file the file
* @return a List containing every every line not starting with # and not empty
* @throws IOException if any
+ * @deprecated assumes the platform default character set
*/
+ @Deprecated
@Nonnull public static ListInputStream
, Reader
, String
and
* byte[]
) and destinations (OutputStream
, Writer
,
* String
and byte[]
).
- *
- *
+ *
* Unless otherwise noted, these copy
methods do not flush or close the
* streams. Often, doing so would require making non-portable assumptions about the streams' origin
* and further use. This means that both streams' close()
methods must be called after
* copying. if one omits this step, then the stream resources (sockets, file descriptors) are
* released when the associated Stream is garbage-collected. It is not a good idea to rely on this
- * mechanism. For a good overview of the distinction between "memory management" and "resource
- * management", see this
- * UnixReview article
For each copy
method, a variant is provided that allows the caller to specify the
* buffer size (the default is 4k). As the buffer size can have a fairly large impact on speed, this
* may be worth tweaking. Often "large buffer -> faster" does not hold, even for large data
* transfers.
For byte-to-char methods, a copy
variant allows the encoding to be selected
* (otherwise the platform default is used).
The copy
methods use an internal buffer when copying. It is therefore advisable
* not to deliberately wrap the stream arguments to the copy
methods in
* Buffered*
streams. For example, don't do the
* following:
* copy( new BufferedInputStream( in ), new BufferedOutputStream( out ) );
- *
The rationale is as follows:
- * + * *Imagine that an InputStream's read() is a very expensive operation, which would usually suggest
* wrapping in a BufferedInputStream. The BufferedInputStream works by issuing infrequent
* {@link java.io.InputStream#read(byte[] b, int off, int len)} requests on the underlying InputStream, to
@@ -133,9 +128,9 @@ private IOUtil()
/**
* Copy bytes from an InputStream
to an OutputStream
.
- * @param input The input size.
- * @param output The resulting output.
- * @throws IOException in case of an error.
+ * @param input the input size
+ * @param output the resulting output
+ * @throws IOException in case of an error
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final OutputStream output )
throws IOException
@@ -146,10 +141,10 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Output
/**
* Copy bytes from an InputStream
to an OutputStream
.
*
- * @param input The input size.
- * @param output The resulting output.
- * @param bufferSize Size of internal buffer to use.
- * @throws IOException in case of an error.
+ * @param input the input size
+ * @param output the resulting output
+ * @param bufferSize size of internal buffer to use
+ * @throws IOException in case of an error
*/
public static void copy( @Nonnull final InputStream input, @Nonnull final OutputStream output,
final int bufferSize )
@@ -759,8 +754,8 @@ public static boolean contentEquals( @Nonnull final InputStream input1, @Nonnull
/**
* Closes a {@code Channel} suppressing any {@code IOException}.
*
- * Note:
The usecase justifying this method is a shortcoming of the Java language up to but not including
- * Java 7. For any code targetting Java 7 or later use of this method is highly discouraged and the
+ * Note: The use case justifying this method is a shortcoming of the Java language up to but not including
+ * Java 7. For any code targeting Java 7 or later use of this method is highly discouraged and the
* {@code try-with-resources} statement should be used instead. Care must be taken to not use this method in a way
* {@code IOException}s get suppressed incorrectly.
* You must close all resources in use inside the {@code try} block to not suppress exceptions in the
@@ -844,7 +839,9 @@ public static boolean contentEquals( @Nonnull final InputStream input1, @Nonnull
*
- * Note:
The usecase justifying this method is a shortcoming of the Java language up to but not including
+ * Note: The use case justifying this method is a shortcoming of the Java language up to but not including
* Java 7. For any code targeting Java 7 or later use of this method is highly discouraged and the
* {@code try-with-resources} statement should be used instead. Care must be taken to not use this method in a way
* {@code IOException}s get suppressed incorrectly.
@@ -948,7 +945,9 @@ public static void close( @Nullable Channel channel )
*
- * Note:
The usecase justifying this method is a shortcoming of the Java language up to but not including
+ * Note: The use case justifying this method is a shortcoming of the Java language up to but not including
* Java 7. For any code targeting Java 7 or later use of this method is highly discouraged and the
* {@code try-with-resources} statement should be used instead. Care must be taken to not use this method in a way
* {@code IOException}s get suppressed incorrectly.
@@ -1052,7 +1051,9 @@ public static void close( @Nullable InputStream inputStream )
*
- * Note:
The usecase justifying this method is a shortcoming of the Java language up to but not including
+ * Note: The use case justifying this method is a shortcoming of the Java language up to but not including
* Java 7. For any code targeting Java 7 or later use of this method is highly discouraged and the
* {@code try-with-resources} statement should be used instead. Care must be taken to not use this method in a way
* {@code IOException}s get suppressed incorrectly.
@@ -1156,7 +1157,9 @@ public static void close( @Nullable OutputStream outputStream )
*
- * Note:
The usecase justifying this method is a shortcoming of the Java language up to but not including
+ * Note: The use case justifying this method is a shortcoming of the Java language up to but not including
* Java 7. For any code targeting Java 7 or later use of this method is highly discouraged and the
* {@code try-with-resources} statement should be used instead. Care must be taken to not use this method in a way
* {@code IOException}s get suppressed incorrectly.
@@ -1260,7 +1263,9 @@ public static void close( @Nullable Reader reader )
*
XmlWriter
class.
*
* @author Vincent Siveton
- * @version $Id$
+ *
*/
public class XmlWriterUtil
{
diff --git a/src/test/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractorTest.java b/src/test/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractorTest.java
index e082617e..1c9a0e26 100644
--- a/src/test/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractorTest.java
+++ b/src/test/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractorTest.java
@@ -30,7 +30,7 @@
/**
* @author Jason van Zyl
- * @version $Id$
+ *
*/
public class ReflectionValueExtractorTest
extends TestCase
diff --git a/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java b/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java
index f2723327..5679512f 100644
--- a/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java
+++ b/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java
@@ -36,7 +36,7 @@
* Test of {@link PrettyPrintXMLWriter}
*
* @author Vincent Siveton
- * @version $Id$
+ *
*/
public class PrettyPrintXmlWriterTest
{
diff --git a/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java b/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java
index 894774a9..a22cece1 100644
--- a/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java
+++ b/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java
@@ -29,7 +29,7 @@
/**
* @author Vincent Siveton
- * @version $Id$
+ *
*/
public class XmlWriterUtilTest
extends TestCase
From da69ad6f1c529834ca103487ce20621701e4765a Mon Sep 17 00:00:00 2001
From: Elliotte Rusty Harold sourceDirectory
must exists.
+ * sourceDirectory
must exist.
* to
may have been deleted already when this happens.
+ * @deprecated use {@code java.nio.Files.move()}
*/
+ @Deprecated
public static void rename( @Nonnull File from, @Nonnull File to )
throws IOException
{
@@ -1774,23 +1788,24 @@ public static void rename( @Nonnull File from, @Nonnull File to )
* 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 + *
This method is different to {@link File#createTempFile(String, String, File)} * 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 + * when the parentDir attribute is null.
+ *To automatically delete the file created by this method, use the * {@link File#deleteOnExit()} method.
* * @param prefix prefix before the random number * @param suffix file extension; include the '.' - * @param parentDir Directory to create the temporary file in-java.io.tmpdir
- * used if not specificed
+ * @param parentDir directory to create the temporary file in -java.io.tmpdir
+ * used if not specified
* @return a File reference to the new temporary file.
+ * @deprecated use {@code java.nio.Files.createTempFile()}
*/
+ @Deprecated
public static File createTempFile( @Nonnull String prefix, @Nonnull String suffix, @Nullable File parentDir )
{
File result;
@@ -1823,7 +1838,7 @@ private static int positiveRandom( Random rand )
}
/**
- * If wrappers is null or empty, the file will be copy only if to.lastModified() < from.lastModified()
+ * If wrappers is null or empty, the file will be copied only if to.lastModified() < from.lastModified()
*
* @param from the file to copy
* @param to the destination file
@@ -1840,13 +1855,12 @@ public static void copyFile( @Nonnull File from, @Nonnull File to, @Nullable Str
/**
* Wrapper class for Filter.
- *
*/
public abstract static class FilterWrapper
{
/**
* @param fileReader {@link Reader}
- * @return The Reader instance.
+ * @return the Reader instance
*/
public abstract Reader getReader( Reader fileReader );
}
@@ -1859,8 +1873,8 @@ public abstract static class FilterWrapper
* @param to the destination file
* @param encoding the file output encoding (only if wrappers is not empty)
* @param wrappers array of {@link FilterWrapper}
- * @param overwrite if true and f wrappers is null or empty, the file will be copy enven if to.lastModified() <
- * from.lastModified()
+ * @param overwrite if true and wrappers is null or empty, the file will be copied even if
+ * to.lastModified() < from.lastModified()
* @throws IOException if an IO error occurs during copying or filtering
*/
public static void copyFile( @Nonnull File from, @Nonnull File to, @Nullable String encoding,
@@ -2103,10 +2117,14 @@ public static boolean isSymbolicLinkForSure( @Nonnull final File file )
}
/**
- * @param symlink The link name.
- * @param target The target.
- * @return The linked file.
- * @throws IOException in case of an error.
+ * Create a new symbolic link, possibly replacing an existing symbolic link.
+ *
+ * @param symlink the link name
+ * @param target the target
+ * @return the linked file
+ * @throws IOException in case of an error
+ * @see {@code java.nio.file.Files.createSymbolicLink(Path)} which creates a new
+ * symbolic link but does not replace exsiting symbolic links
*/
@Nonnull public static File createSymbolicLink( @Nonnull File symlink, @Nonnull File target )
throws IOException
diff --git a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java
index 90d93c60..9fa7c85e 100644
--- a/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java
+++ b/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java
@@ -74,6 +74,7 @@
* @version $Id: FileUtilsTestCase.java 1081025 2011-03-13 00:45:10Z niallp $
* @see FileUtils
*/
+@SuppressWarnings( "deprecation" )
public class FileUtilsTest
{
@@ -90,11 +91,6 @@ public class FileUtilsTest
*/
private static final int TEST_DIRECTORY_SIZE = 0;
- /**
- * Delay in milliseconds to make sure test for "last modified date" are accurate
- */
- //private static final int LAST_MODIFIED_DELAY = 600;
-
private File testFile1;
private File testFile2;
@@ -132,18 +128,10 @@ void createFile( File file, long size )
{
throw new IOException( "Cannot create file " + file + " as the parent directory does not exist" );
}
-
- OutputStream out = null;
- try
+
+ try (OutputStream out = new BufferedOutputStream( new FileOutputStream( file ) ) )
{
- out = new BufferedOutputStream( new FileOutputStream( file ) );
FileTestHelper.generateTestData( out, size );
- out.close();
- out = null;
- }
- finally
- {
- IOUtil.close( out );
}
}
@@ -258,26 +246,6 @@ public void toURLs1()
assertThat( urls[2].toExternalForm(), containsString( "test%20file.txt" ) );
}
-// @Test public void toURLs2() throws Exception {
-// File[] files = new File[] {
-// new File(getTestDirectory(), "file1.txt"),
-// null,
-// };
-// URL[] urls = FileUtils.toURLs(files);
-//
-// assertEquals(files.length, urls.length);
-// assertEquals(true, urls[0].toExternalForm().startsWith("file:"));
-// assertEquals(true, urls[0].toExternalForm().indexOf("file1.txt") > 0);
-// assertEquals(null, urls[1]);
-// }
-//
-// @Test public void toURLs3() throws Exception {
-// File[] files = null;
-// URL[] urls = FileUtils.toURLs(files);
-//
-// assertEquals(0, urls.length);
-// }
-
// contentEquals
@Test
@@ -676,8 +644,6 @@ public void copyFileWithFilteringAndNewerDestinationAndMatchingContent()
"Hello Bob!"
);
- String encoding = null;
-
FileUtils.copyFile( from, to, null, wrappers( "name", "Bob" ) );
assertFileContent( to, "Hello Bob!" );
@@ -689,7 +655,7 @@ public void copyFileWithFilteringAndNewerDestinationAndMatchingContent()
private FileUtils.FilterWrapper[] wrappers( String key, String value )
{
- final Map map = new HashMap();
+ final MapInputStream
to an OutputStream
.
- * @param input the input size
- * @param output the resulting output
+ *
+ * @param input the stream to read from
+ * @param output the stream to write to
* @throws IOException in case of an error
+ * @deprecated use {@code org.apache.commons.io.IOUtils.copy()} or in
+ * Java 9 and later {@code InputStream.transferTo()}.
*/
+ @Deprecated
public static void copy( @Nonnull final InputStream input, @Nonnull final OutputStream output )
throws IOException
{
@@ -141,11 +145,16 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Output
/**
* Copy bytes from an InputStream
to an OutputStream
.
*
- * @param input the input size
- * @param output the resulting output
- * @param bufferSize size of internal buffer to use
+ * In Java 9 and later this is replaced by {@code InputStream.transferTo()}.
+ *
+ * @param input the stream to read from
+ * @param output the stream to write to
+ * @param bufferSize size of internal buffer
* @throws IOException in case of an error
+ * @deprecated use {@code org.apache.commons.io.IOUtils.copy()} or in
+ * Java 9 and later {@code InputStream.transferTo()}.
*/
+ @Deprecated
public static void copy( @Nonnull final InputStream input, @Nonnull final OutputStream output,
final int bufferSize )
throws IOException
@@ -160,10 +169,12 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Output
/**
* Copy chars from a Reader
to a Writer
.
- * @param input The input size.
- * @param output The resulting output.
- * @throws IOException in case of failure.
+ *
+ * @param input the reader to read from
+ * @param output the writer to write to
+ * @throws IOException in case of failure * @deprecated use {@code org.apache.commons.io.IOUtils.copy()}.
*/
+ @Deprecated
public static void copy( @Nonnull final Reader input, @Nonnull final Writer output )
throws IOException
{
@@ -173,11 +184,13 @@ public static void copy( @Nonnull final Reader input, @Nonnull final Writer outp
/**
* Copy chars from a Reader
to a Writer
.
*
- * @param input The input size.
- * @param output The resulting output.
- * @param bufferSize Size of internal buffer to use.
- * @throws IOException in case of failure.
+ * @param input the reader to read from
+ * @param output the writer to write to
+ * @param bufferSize size of internal buffer
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.copy()}.
*/
+ @Deprecated
public static void copy( @Nonnull final Reader input, @Nonnull final Writer output, final int bufferSize )
throws IOException
{
@@ -201,11 +214,15 @@ public static void copy( @Nonnull final Reader input, @Nonnull final Writer outp
/**
* Copy and convert bytes from an InputStream
to chars on a
* Writer
.
+ *
* The platform's default encoding is used for the byte-to-char conversion.
- * @param input The input size.
- * @param output The resulting output.
- * @throws IOException in case of failure.
+ *
+ * @param input the reader to read from
+ * @param output the writer to write to
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.copy()}.
*/
+ @Deprecated
public static void copy( @Nonnull final InputStream input, @Nonnull final Writer output )
throws IOException
{
@@ -217,11 +234,13 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* Writer
.
* The platform's default encoding is used for the byte-to-char conversion.
*
- * @param input The input size.
- * @param output The resulting output.
- * @param bufferSize Size of internal buffer to use.
- * @throws IOException in case of failure.
+ * @param input the input stream to read from
+ * @param output the writer to write to
+ * @param bufferSize size of internal buffer
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.copy()}.
*/
+ @Deprecated
public static void copy( @Nonnull final InputStream input, @Nonnull final Writer output, final int bufferSize )
throws IOException
{
@@ -233,13 +252,15 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* Copy and convert bytes from an InputStream
to chars on a
* Writer
, using the specified encoding.
*
- * @param input The input size.
- * @param output The resulting output.
- * @param encoding The name of a supported character encoding. See the
- * IANA
+ * @param input the input stream to read from
+ * @param output the writer to write to
+ * @param encoding the name of a supported character encoding. See the
+ * IANA
* Charset Registry for a list of valid encoding types.
- * @throws IOException in case of failure.
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.copy()}.
*/
+ @Deprecated
public static void copy( @Nonnull final InputStream input, @Nonnull final Writer output,
@Nonnull final String encoding )
throws IOException
@@ -252,14 +273,16 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* Copy and convert bytes from an InputStream
to chars on a
* Writer
, using the specified encoding.
*
- * @param encoding The name of a supported character encoding. See the
- * IANA
+ * @param encoding the name of a supported character encoding. See the
+ * IANA
* Charset Registry for a list of valid encoding types.
- * @param input The input size.
- * @param output The resulting output.
- * @param bufferSize Size of internal buffer to use.
- * @throws IOException in case of failure.
+ * @param input the input stream to read from
+ * @param output the writer to write to
+ * @param bufferSize size of internal buffer
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.copy()}.
*/
+ @Deprecated
public static void copy( @Nonnull final InputStream input, @Nonnull final Writer output,
@Nonnull final String encoding, final int bufferSize )
throws IOException
@@ -274,10 +297,13 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a String.
* The platform's default encoding is used for the byte-to-char conversion.
- * @param input The input size.
- * @return The resulting string.
- * @throws IOException in case of failure.
+ *
+ * @param input the InputStream to read from
+ * @return the resulting string
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
@Nonnull public static String toString( @Nonnull final InputStream input )
throws IOException
{
@@ -288,11 +314,13 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
* Get the contents of an InputStream
as a String.
* The platform's default encoding is used for the byte-to-char conversion.
*
- * @param input The input size.
- * @param bufferSize Size of internal buffer to use.
- * @return the resulting string.
- * @throws IOException in case of failure.
+ * @param input the InputStream to read from
+ * @param bufferSize size of internal buffer
+ * @return the resulting string
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
@Nonnull public static String toString( @Nonnull final InputStream input, final int bufferSize )
throws IOException
{
@@ -304,13 +332,15 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a String.
*
- * @param input The input size.
- * @param encoding The name of a supported character encoding. See the
- * IANA
+ * @param input the InputStream to read from
+ * @param encoding the name of a supported character encoding. See the
+ * IANA
* Charset Registry for a list of valid encoding types.
- * @return the converted string.
- * @throws IOException in case of failure.
+ * @return the converted string
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.toString()}.
*/
+ @Deprecated
@Nonnull public static String toString( @Nonnull final InputStream input, @Nonnull final String encoding )
throws IOException
{
@@ -320,14 +350,16 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a String.
*
- * @param input The input size.
- * @param encoding The name of a supported character encoding. See the
- * IANA
+ * @param input the InputStream to read from
+ * @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.
+ * @param bufferSize size of internal buffer
* @return The converted string.
- * @throws IOException in case of failure.
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.toString()}.
*/
+ @Deprecated
@Nonnull public static String toString( @Nonnull final InputStream input, @Nonnull final String encoding,
final int bufferSize )
throws IOException
@@ -342,10 +374,13 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a byte[]
.
- * @param input The input size.
+ *
+ * @param input the InputStream to read from
* @return the resulting byte array.
- * @throws IOException in case of failure.
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.readFully()}.
*/
+ @Deprecated
@Nonnull public static byte[] toByteArray( @Nonnull final InputStream input )
throws IOException
{
@@ -355,11 +390,13 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Get the contents of an InputStream
as a byte[]
.
*
- * @param input The input size.
- * @param bufferSize Size of internal buffer to use.
+ * @param input the InputStream to read from
+ * @param bufferSize size of internal buffer
* @return the resulting byte array.
- * @throws IOException in case of failure.
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.readFully()}.
*/
+ @Deprecated
@Nonnull public static byte[] toByteArray( @Nonnull final InputStream input, final int bufferSize )
throws IOException
{
@@ -379,10 +416,13 @@ public static void copy( @Nonnull final InputStream input, @Nonnull final Writer
/**
* Serialize chars from a Reader
to bytes on an OutputStream
, and
* flush the OutputStream
.
- * @param input The input size.
- * @param output The resulting output.
- * @throws IOException in case of failure.
+ *
+ * @param input the InputStream to read from
+ * @param output the output stream to write to
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
public static void copy( @Nonnull final Reader input, @Nonnull final OutputStream output )
throws IOException
{
@@ -393,11 +433,13 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
* Serialize chars from a Reader
to bytes on an OutputStream
, and
* flush the OutputStream
.
*
- * @param input The input size.
- * @param output The resulting output.
- * @param bufferSize Size of internal buffer to use.
- * @throws IOException in case of failure.
+ * @param input the InputStream to read from
+ * @param output the output to write to
+ * @param bufferSize size of internal buffer
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
public static void copy( @Nonnull final Reader input, @Nonnull final OutputStream output, final int bufferSize )
throws IOException
{
@@ -413,10 +455,12 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Get the contents of a Reader
as a String.
- * @param input The input size.
+ * @param input the InputStream to read from
* @return The converted string.
- * @throws IOException in case of failure.
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.toString()}.
*/
+ @Deprecated
@Nonnull public static String toString( @Nonnull final Reader input )
throws IOException
{
@@ -426,11 +470,13 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Get the contents of a Reader
as a String.
*
- * @param input The input size.
- * @param bufferSize Size of internal buffer to use.
+ * @param input the reader to read from
+ * @param bufferSize size of internal buffer
* @return the resulting byte array.
- * @throws IOException in case of failure.
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.toString()}.
*/
+ @Deprecated
@Nonnull public static String toString( @Nonnull final Reader input, final int bufferSize )
throws IOException
{
@@ -444,10 +490,13 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Get the contents of a Reader
as a byte[]
.
- * @param input The input size.
+ *
+ * @param input the InputStream to read from
* @return the resulting byte array.
- * @throws IOException in case of failure.
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
@Nonnull public static byte[] toByteArray( @Nonnull final Reader input )
throws IOException
{
@@ -457,11 +506,13 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Get the contents of a Reader
as a byte[]
.
*
- * @param input The input size.
- * @param bufferSize Size of internal buffer to use.
+ * @param input the InputStream to read from
+ * @param bufferSize size of internal buffer
* @return the resulting byte array.
- * @throws IOException in case of failure.
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
@Nonnull public static byte[] toByteArray( @Nonnull final Reader input, final int bufferSize )
throws IOException
{
@@ -481,10 +532,12 @@ public static void copy( @Nonnull final Reader input, @Nonnull final OutputStrea
/**
* Serialize chars from a String
to bytes on an OutputStream
, and
* flush the OutputStream
.
- * @param input The input size.
- * @param output The resulting output.
- * @throws IOException in case of failure.
+ * @param input the InputStream to read from
+ * @param output the output to write to
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
public static void copy( @Nonnull final String input, @Nonnull final OutputStream output )
throws IOException
{
@@ -495,11 +548,13 @@ public static void copy( @Nonnull final String input, @Nonnull final OutputStrea
* Serialize chars from a String
to bytes on an OutputStream
, and
* flush the OutputStream
.
*
- * @param input The input size.
- * @param output The resulting output.
- * @param bufferSize Size of internal buffer to use.
- * @throws IOException in case of failure.
+ * @param input the InputStream to read from
+ * @param output the output to write to
+ * @param bufferSize size of internal buffer
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
public static void copy( @Nonnull final String input, @Nonnull final OutputStream output, final int bufferSize )
throws IOException
{
@@ -516,10 +571,13 @@ public static void copy( @Nonnull final String input, @Nonnull final OutputStrea
/**
* Copy chars from a String
to a Writer
.
- * @param input Input string.
+ *
+ * @param input the string to write
* @param output resulting output {@link Writer}
- * @throws IOException in case of failure.
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.write()}.
*/
+ @Deprecated
public static void copy( @Nonnull final String input, @Nonnull final Writer output )
throws IOException
{
@@ -531,10 +589,13 @@ public static void copy( @Nonnull final String input, @Nonnull final Writer outp
/**
* Get the contents of a String
as a byte[]
.
- * @param input The input size.
- * @return The resulting byte array.
- * @throws IOException in case of failure.
+ *
+ * @param input the String to read from
+ * @return the resulting byte array
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
@Nonnull public static byte[] toByteArray( @Nonnull final String input )
throws IOException
{
@@ -544,11 +605,13 @@ public static void copy( @Nonnull final String input, @Nonnull final Writer outp
/**
* Get the contents of a String
as a byte[]
.
*
- * @param input The input size.
- * @param bufferSize Size of internal buffer to use.
- * @return The resulting byte array.
- * @throws IOException in case of failure.
+ * @param input the InputStream to read from
+ * @param bufferSize size of internal buffer
+ * @return the resulting byte array
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
@Nonnull public static byte[] toByteArray( @Nonnull final String input, final int bufferSize )
throws IOException
{
@@ -569,10 +632,13 @@ public static void copy( @Nonnull final String input, @Nonnull final Writer outp
* 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 The input size.
- * @param output The resulting output.
- * @throws IOException in case of failure.
+ *
+ * @param input the InputStream to read from
+ * @param output the output to write to
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output )
throws IOException
{
@@ -584,11 +650,13 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* Writer
.
* The platform's default encoding is used for the byte-to-char conversion.
*
- * @param input The input size.
- * @param output The resulting output.
- * @param bufferSize Size of internal buffer to use.
- * @throws IOException in case of failure.
+ * @param input the InputStream to read from
+ * @param output the output to write to
+ * @param bufferSize size of internal buffer
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output, final int bufferSize )
throws IOException
{
@@ -600,13 +668,15 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* Copy and convert bytes from a byte[]
to chars on a
* Writer
, using the specified encoding.
*
- * @param encoding The name of a supported character encoding. See the
- * IANA
+ * @param encoding the name of a supported character encoding. See the
+ * IANA
* Charset Registry for a list of valid encoding types.
- * @param input The input size.
- * @param output The resulting output.
- * @throws IOException in case of failure.
+ * @param input the data to write
+ * @param output the writer to write to
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.write()}.
*/
+ @Deprecated
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output, final String encoding )
throws IOException
{
@@ -618,14 +688,16 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* Copy and convert bytes from a byte[]
to chars on a
* Writer
, using the specified encoding.
*
- * @param encoding The name of a supported character encoding. See the
- * IANA
+ * @param encoding the name of a supported character encoding. See the
+ * IANA
* Charset Registry for a list of valid encoding types.
- * @param input The input bytes.
+ * @param input the input bytes
* @param output The output buffer {@link Writer}
- * @param bufferSize Size of internal buffer to use.
- * @throws IOException in case of failure.
+ * @param bufferSize size of internal buffer
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.write()}.
*/
+ @Deprecated
public static void copy( @Nonnull final byte[] input, @Nonnull final Writer output, @Nonnull final String encoding,
final int bufferSize )
throws IOException
@@ -640,10 +712,12 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
/**
* Get the contents of a byte[]
as a String.
* The platform's default encoding is used for the byte-to-char conversion.
- * @param input The input bytes.
- * @return The resulting string.
- * @throws IOException in case of failure.
+ * @param input the input bytes
+ * @return the resulting string
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
@Nonnull public static String toString( @Nonnull final byte[] input )
throws IOException
{
@@ -654,11 +728,13 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
* Get the contents of a byte[]
as a String.
* The platform's default encoding is used for the byte-to-char conversion.
*
- * @param bufferSize Size of internal buffer to use.
- * @param input The input bytes.
- * @return The created string.
- * @throws IOException in case of failure.
+ * @param bufferSize size of internal buffer
+ * @param input the input bytes
+ * @return the created string
+ * @throws IOException in case of failure
+ * @deprecated always specify a character encoding
*/
+ @Deprecated
@Nonnull public static String toString( @Nonnull final byte[] input, final int bufferSize )
throws IOException
{
@@ -670,13 +746,15 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
/**
* Get the contents of a byte[]
as a String.
*
- * @param encoding The name of a supported character encoding. See the
- * IANA
+ * @param encoding the name of a supported character encoding. See the
+ * IANA
* Charset Registry for a list of valid encoding types.
- * @param input The input bytes.
- * @return The resulting string.
- * @throws IOException in case of failure.
+ * @param input the input bytes
+ * @return the resulting string
+ * @throws IOException in case of failure
+ * @deprecated use {@code new String(input, encoding)}
*/
+ @Deprecated
@Nonnull public static String toString( @Nonnull final byte[] input, @Nonnull final String encoding )
throws IOException
{
@@ -686,14 +764,16 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
/**
* Get the contents of a byte[]
as a String.
*
- * @param encoding The name of a supported character encoding. See the
- * IANA
+ * @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.
- * @param input Input bytes.
- * @return The resulting string.
- * @throws IOException in case of failure.
+ * @param bufferSize size of internal buffer
+ * @param input input bytes
+ * @return the resulting string
+ * @throws IOException in case of failure
+ * @deprecated use {@code new String(input, encoding)}
*/
+ @Deprecated
@Nonnull public static String toString( @Nonnull final byte[] input, @Nonnull final String encoding,
final int bufferSize )
throws IOException
@@ -708,10 +788,13 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final Writer outp
/**
* Copy bytes from a byte[]
to an OutputStream
.
+ *
* @param input Input byte array.
* @param output output stream {@link OutputStream}
- * @throws IOException in case of failure.
+ * @throws IOException in case of failure
+ * @deprecated inline this method
*/
+ @Deprecated
public static void copy( @Nonnull final byte[] input, @Nonnull final OutputStream output )
throws IOException
{
@@ -719,13 +802,15 @@ public static void copy( @Nonnull final byte[] input, @Nonnull final OutputStrea
}
/**
- * Compare the contents of two Streams to determine if they are equal or not.
+ * Compare the contents of two streams to determine if they are equal or not.
*
* @param input1 the first stream
* @param input2 the second stream
* @return true if the content of the streams are equal or they both don't exist, false otherwise
- * @throws IOException in case of failure.
+ * @throws IOException in case of failure
+ * @deprecated use {@code org.apache.commons.io.IOUtils.contentEquals()}
*/
+ @Deprecated
public static boolean contentEquals( @Nonnull final InputStream input1, @Nonnull final InputStream input2 )
throws IOException
{
From d1042e0aff6b4a70ed3620bb95e4767b95f85ad8 Mon Sep 17 00:00:00 2001
From: Elliotte Rusty Harold * If the given {@code File} is {@code null} or the properties file can't be read, an empty properties object is * returned. @@ -185,11 +184,10 @@ public static Properties loadOptionalProperties( final @Nullable File file ) } /** - * Loads {@code Properties} from a given {@code InputStream}. - *
+ * Loads {@code Properties} from an {@code InputStream} and closes the stream. * If the given {@code InputStream} is {@code null} or the properties can't be read, an empty properties object is - * returned. - *
+ * returned. In a future release, this will no longer close the stream, so callers + * should close the stream themselves. * * @param inputStream the properties resource to load or {@code null} * @return the loaded properties or an empty {@code Properties} instance if properties fail to load @@ -203,18 +201,14 @@ public static Properties loadOptionalProperties( final @Nullable InputStream inp if ( inputStream != null ) { - try + try ( InputStream in = inputStream ) // reassign inputStream to autoclose { - properties.load( inputStream ); + properties.load( in ); } catch ( IllegalArgumentException | IOException ex ) { // ignore and return empty properties } - finally - { - IOUtil.close( inputStream ); - } } return properties; diff --git a/src/test/java/org/apache/maven/shared/utils/PropertyUtilsTest.java b/src/test/java/org/apache/maven/shared/utils/PropertyUtilsTest.java index 41067a40..0c696415 100644 --- a/src/test/java/org/apache/maven/shared/utils/PropertyUtilsTest.java +++ b/src/test/java/org/apache/maven/shared/utils/PropertyUtilsTest.java @@ -33,7 +33,6 @@ import java.net.URL; import java.util.Properties; -import org.apache.maven.shared.utils.io.IOUtil; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -166,23 +165,15 @@ public void loadValidInputStream() throws UnsupportedEncodingException @SuppressWarnings( "deprecation" ) public void loadValidFile() throws IOException { - OutputStream out = null; - try + File valid = tempFolder.newFile( "valid" ); + Properties value = new Properties(); + value.setProperty( "a", "b" ); + try ( OutputStream out = new FileOutputStream( valid ) ) { - File valid = tempFolder.newFile( "valid" ); - Properties value = new Properties(); - value.setProperty( "a", "b" ); - out = new FileOutputStream( valid ); value.store( out, "a test" ); - out.close(); - out = null; assertThat( PropertyUtils.loadProperties( valid ), is( value ) ); assertThat( PropertyUtils.loadOptionalProperties( valid ), is( value ) ); } - finally - { - IOUtil.close( out ); - } } @Test @@ -190,22 +181,14 @@ public void loadValidFile() throws IOException @SuppressWarnings( "deprecation" ) public void loadValidURL() throws IOException { - OutputStream out = null; - try - { - File valid = tempFolder.newFile( "valid" ); - Properties value = new Properties(); - value.setProperty( "a", "b" ); - out = new FileOutputStream( valid ); - value.store( out, "a test" ); - out.close(); - out = null; - assertThat( PropertyUtils.loadProperties( valid.toURI().toURL() ), is( value ) ); - assertThat( PropertyUtils.loadOptionalProperties( valid.toURI().toURL() ), is( value ) ); - } - finally + File valid = tempFolder.newFile( "valid" ); + Properties value = new Properties(); + value.setProperty( "a", "b" ); + try ( OutputStream out = new FileOutputStream( valid ) ) { - IOUtil.close( out ); + value.store( out, "a test" ); + assertThat( PropertyUtils.loadProperties( valid.toURI().toURL() ), is( value ) ); + assertThat( PropertyUtils.loadOptionalProperties( valid.toURI().toURL() ), is( value ) ); } } From 7768b895c627ce7df4ef105979c418842963b80b Mon Sep 17 00:00:00 2001 From: Elliotte Rusty HaroldRemoves control characters, including whitespace, from both + *
Removes C0 control characters, including ASCII whitespace, from both
* ends of this String, handling null
by returning
* an empty String.
Removes control characters, including whitespace, from both + *
Removes C0 control characters, including ASCII whitespace, from both
* ends of this String, handling null
by returning
* null
.
Splits the provided text into a array, based on a given separator.
* *The separator is not included in the returned String array. The
- * maximum number of splits to perfom can be controlled. A null
- * separator will cause parsing to be on whitespace.
null
+ * separator causes splitting on whitespace.
*
- * This is useful for quickly splitting a String directly into + *
This is useful for quickly splitting a String into
* an array of tokens, instead of an enumeration of tokens (as
* StringTokenizer
does).
null
+ * @return the number of occurrences, 0 if the String is null
* @throws NullPointerException if sub is null
*/
public static int countMatches( @Nullable String str, @Nonnull String sub )
@@ -1715,7 +1715,7 @@ public static int countMatches( @Nullable String str, @Nonnull String sub )
//--------------------------------------------------------------------------
/**
- * Checks if the String contains only unicode letters.
+ *Checks if the String contains only Unicode letters.
* *null
will return false
.
* An empty String will return true
.
Checks if the String contains only unicode letters and + *
Checks if the String contains only Unicode letters and
* space (' '
).
null
will return false
. An
@@ -1795,7 +1795,7 @@ public static boolean isAlphaSpace( String str )
}
/**
- *
Checks if the String contains only unicode letters or digits.
+ *Checks if the String contains only Unicode letters or digits.
* *null
will return false
. An empty
* String will return true
.
Checks if the String contains only unicode letters, digits + *
Checks if the String contains only Unicode letters, digits
* or space (' '
).
null
will return false
. An empty
@@ -1850,7 +1850,7 @@ public static boolean isAlphanumericSpace( String str )
}
/**
- *
Checks if the String contains only unicode digits.
+ *Checks if the String contains only Unicode digits.
* *null
will return false
.
* An empty String will return true
.
true
if the Strings are equal, case sensitive, or
* both null
* @see java.lang.String#equals(Object)
+ * @deprecated use {@code java.lang.Objects.equals()}
*/
+ @Deprecated
public static boolean equals( @Nullable String str1, @Nullable String str2 )
{
return ( str1 == null ? str2 == null : str1.equals( str2 ) );
@@ -315,7 +317,7 @@ public static int lastIndexOfAny( String str, String... searchStrs )
/**
* Gets a substring from the specified string avoiding exceptions.
- * + * *A negative start position can be used to start n
* characters from the end of the String.
Gets a substring from the specified String avoiding exceptions.
- * + * *A negative start position can be used to start/end n
* characters from the end of the String.
Gets the leftmost n
characters of a String.
If n
characters are not available, or the
* String is null
, the String will be returned without
* an exception.
Gets the rightmost n
characters of a String.
If n
characters are not available, or the String
* is null
, the String will be returned without an
* exception.
Gets n
characters from the middle of a String.
If n
characters are not available, the remainder
* of the String will be returned without an exception. If the
* String is null
, null
will be returned.
Splits the provided text into a array, using whitespace as the * separator.
- * + * *The separator is not included in the returned String array.
* * @param str the String to parse @@ -516,9 +518,9 @@ public static String mid( String str, int pos, int len ) } /** - * @param text The text to be split. - * @param separator The separator at which the text will be split. - * @return The resulting array. + * @param text the text to be split + * @param separator the separator at which the text will be split + * @return the resulting array * @see #split(String, String, int) */ @Nonnull public static String[] split( @Nonnull String text, @Nullable String separator ) @@ -528,19 +530,19 @@ public static String mid( String str, int pos, int len ) /** *Splits the provided text into a array, based on a given separator.
- * + * *The separator is not included in the returned String array. The
* maximum number of splits to perform can be controlled. A null
* separator causes splitting on whitespace.
This is useful for quickly splitting a String into
* an array of tokens, instead of an enumeration of tokens (as
* StringTokenizer
does).
null
, splits on whitespace.
- * @param max The maximum number of elements to include in the
+ * @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
*/
@@ -2375,11 +2377,10 @@ public static String escape( @Nullable String source, @Nonnull final char[] esca
}
/**
- * Remove all duplicate whitespace characters and line terminators are replaced with a single
- * space.
+ * Remove all duplicate whitespace characters and replace line terminators with a single space.
*
* @param s a not null String
- * @return a string with unique whitespace.
+ * @return a string with unique whitespace
*
*/
@Nonnull public static String removeDuplicateWhitespace( @Nonnull String s )
From cd25a3712e54d7d79efb0ad743af32ee61f0f4f6 Mon Sep 17 00:00:00 2001
From: Elliotte Rusty Harold null
+ * @deprecated use {@code java.lang.Objects.toString()}
*/
+ @Deprecated
@Nonnull public static String defaultString( Object obj )
{
return defaultString( obj, "" );
@@ -1904,7 +1906,9 @@ public static boolean isNumeric( String str )
* null
* @return the passed in string, or the default if it was
* null
+ * @deprecated use {@code java.lang.Objects.toString()}
*/
+ @Deprecated
@Nonnull public static String defaultString( Object obj, @Nonnull String defaultString )
{
return ( obj == null ) ? defaultString : obj.toString();
From be2a1a12adaf6b8ff95d0ee375320fec57390d48 Mon Sep 17 00:00:00 2001
From: Elliotte Rusty Harold Common String
manipulation routines.
Originally from * Turbine, the * GenerationJavaCore library and Velocity. @@ -57,7 +57,7 @@ public class StringUtils *
StringUtils
instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* StringUtils.trim(" foo ");
.
This constructor is public to permit tools that require a JavaBean * manager to operate.
*/ @@ -97,13 +97,13 @@ public static String trim( String str ) } /** - *Deletes all whitespaces from a String.
- * + *Deletes all whitespace from a String.
+ * *Whitespace is defined by * {@link Character#isWhitespace(char)}.
* * @param str String target to delete whitespace from - * @return the String without whitespaces + * @return the String without whitespace * @throws NullPointerException */ @Nonnull public static String deleteWhitespace( @Nonnull String str ) @@ -134,7 +134,7 @@ public static boolean isNotEmpty( @Nullable String str ) /** *Checks if a (trimmed) String is null
or empty.
Note: In future releases, this method will no longer trim the input string such that it works * complementary to {@link #isNotEmpty(String)}. Code that wants to test for whitespace-only strings should be * migrated to use {@link #isBlank(String)} instead.
@@ -152,7 +152,7 @@ public static boolean isEmpty( @Nullable String str ) ** Checks if a String is whitespace, empty ("") or null. *
- * + * ** StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true @@ -188,7 +188,7 @@ public static boolean isBlank( @Nullable String str ) ** Checks if a String is not empty (""), not null and not whitespace only. *
- * + * ** StringUtils.isNotBlank(null) = false * StringUtils.isNotBlank("") = false @@ -211,7 +211,7 @@ public static boolean isNotBlank( @Nullable String str ) /** *Compares two Strings, returning
- * + * *true
if they are equal.* @@ -231,7 +231,7 @@ public static boolean equals( @Nullable String str1, @Nullable String str2 ) /** *
null
s are handled without exceptions. Twonull
* references are considered to be equal. The comparison is case sensitive.Compares two Strings, returning
- * + * *true
if they are equal ignoring * the case.* @@ -248,7 +248,7 @@ public static boolean equalsIgnoreCase( String str1, String str2 ) /** *
Nulls
are handled without exceptions. Twonull
* references are considered equal. Comparison is case insensitive.Find the first index of any of a set of potential substrings.
- * + * ** * @param str the String to check @@ -285,7 +285,7 @@ public static int indexOfAny( String str, String... searchStrs ) /** *
null
String will return-1
.Find the latest index of any of a set of potential substrings.
- * + * ** * @param str the String to check @@ -598,7 +598,7 @@ public static String mid( String str, int pos, int len ) /** *
null
string will return-1
.Concatenates elements of an array into a single String.
- * + * *The difference from join is that concatenate has no delimiter.
* * @param array the array of values to concatenate. @@ -612,7 +612,7 @@ public static String mid( String str, int pos, int len ) /** *Joins the elements of the provided array into a single String * containing the provided list of elements.
- * + * *No delimiter is added before or after the list. A *
* @@ -644,7 +644,7 @@ public static String mid( String str, int pos, int len ) /** *null
separator is the same as a blank String.Joins the elements of the provided
- * + * *Iterator
into * a single String containing the provided elements.No delimiter is added before or after the list. A *
* @@ -675,7 +675,7 @@ public static String mid( String str, int pos, int len ) /** *null
separator is the same as a blank String.Replace a char with another char inside a larger String, once.
- * + * *A
* * @param text text to search and replace in @@ -691,7 +691,7 @@ public static String replaceOnce( @Nullable String text, char repl, char with ) /** *null
reference passed to this method is a no-op.Replace all occurances of a char within another char.
- * + * *A
* * @param text text to search and replace in @@ -708,7 +708,7 @@ public static String replace( @Nullable String text, char repl, char with ) /** *null
reference passed to this method is a no-op.Replace a char with another char inside a larger String, * for the first
- * + * *max
values of the search char.A
* * @param text text to search and replace in @@ -724,7 +724,7 @@ public static String replace( @Nullable String text, char repl, char with, int m /** *null
reference passed to this method is a no-op.Replace a String with another String inside a larger String, once.
- * + * *A
* * @param text text to search and replace in @@ -739,8 +739,8 @@ public static String replaceOnce( @Nullable String text, @Nullable String repl, } /** - *null
reference passed to this method is a no-op.Replace all occurances of a String within another String.
- * + *Replace all occurrences of a String within another String.
+ * *A
* * @param text text to search and replace in @@ -757,7 +757,7 @@ public static String replace( @Nullable String text, @Nullable String repl, @Nu /** *null
reference passed to this method is a no-op.Replace a String with another String inside a larger String, * for the first
- * + * *max
values of the search String.A
* * @param text text to search and replace in @@ -794,9 +794,9 @@ public static String replace( @Nullable String text, @Nullable String repl, @Nul * * @param text String to do overlaying in * @param overlay String to overlay - * @param start int to start overlaying at - * @param end int to stop overlaying before - * @return String with overlayed text + * @param start position to start overlaying at + * @param end position to stop overlaying before + * @return String with overlaid text * @throws NullPointerException if text or overlay isnull
reference passed to this method is a no-op.null
*/ @Nonnull public static String overlayString( @Nonnull String text, @Nonnull String overlay, int start, int end ) @@ -817,7 +817,7 @@ public static String replace( @Nullable String text, @Nullable String repl, @Nul /** *Center a String in a larger String of size
n
.- *
+ * *Uses spaces as the value to buffer the String with. * Equivalent to
* @@ -833,7 +833,7 @@ public static String replace( @Nullable String text, @Nullable String repl, @Nul /** *center(str, size, " ")
.Center a String in a larger String of size
- * + * *n
.Uses a supplied String as the value to buffer the String with.
* * @param str String to center @@ -1006,7 +1006,7 @@ else if ( idx != -1 ) /** *Remove the last character from a String.
- * + * *If the String ends in
* @@ -1070,7 +1070,7 @@ else if ( idx != -1 ) /** *\r\n
, then remove both * of them.Escapes any values it finds into their String form.
- * + * *So a tab becomes the characters
* @@ -1189,7 +1189,7 @@ else if ( ch < 32 ) /** *'\\'
and *'t'
.Right pad a String with spaces.
- * + * *The String is padded to the size of
* * @param str String to repeat @@ -1204,7 +1204,7 @@ else if ( ch < 32 ) /** *n
.Right pad a String with a specified string.
- * + * *The String is padded to the size of
* * @param str String to pad out @@ -1226,7 +1226,7 @@ else if ( ch < 32 ) /** *n
.Left pad a String with spaces.
- * + * *The String is padded to the size of
* * @param str String to pad out @@ -1276,7 +1276,7 @@ public static String strip( String str ) /** *n
.Remove a specified String from the front and back of a * String.
- * + * *If whitespace is wanted to be removed, used the * {@link #strip(java.lang.String)} method.
* @@ -1327,7 +1327,7 @@ public static String[] stripAll( String[] strs, @Nullable String delimiter ) /** *Strip any of a supplied String from the end of a String.
- * + * *If the strip String is
* @@ -1362,7 +1362,7 @@ public static String stripEnd( String str, @Nullable String strip ) /** *null
, whitespace is * stripped.Strip any of a supplied String from the start of a String.
- * + * *If the strip String is
* @@ -1435,7 +1435,7 @@ public static String lowerCase( String str ) /** *null
, whitespace is * stripped.Uncapitalise a String.
- * + * *That is, convert the first character into lower-case. *
* @@ -1467,7 +1467,7 @@ public static String uncapitalise( String str ) /** *null
is returned asnull
.Capitalise a String.
- * + * *That is, convert the first character into title-case. *
* @@ -1499,10 +1499,10 @@ public static String capitalise( String str ) /** *null
is returned asnull
.Swaps the case of String.
- * + * *Properly looks after making sure the start of words * are Titlecase and not Uppercase.
- * + * ** * @param str the String to swap the case of @@ -1556,10 +1556,10 @@ else if ( Character.isLowerCase( ch ) ) /** *
null
is returned asnull
.Capitalise all the words in a String.
- * + * *Uses {@link Character#isWhitespace(char)} as a * separator between words.
- * + * ** * @param str the String to capitalise @@ -1597,10 +1597,10 @@ else if ( space ) /** *
null
will returnnull
.Uncapitalise all the words in a string.
- * + * *Uses {@link Character#isWhitespace(char)} as a * separator between words.
- * + * ** * @param str the string to uncapitalise @@ -1642,7 +1642,7 @@ else if ( space ) /** *
null
will returnnull
.Get the String that is nested in between two instances of the * same String.
- * + * *If
* @@ -1685,7 +1685,7 @@ public static String getNestedString( String str, @Nonnull String open, @Nonnull /** *str
isnull
, will * returnnull
.How many times is the substring in the larger String.
- * + * ** * @param str the String to check @@ -1718,7 +1718,7 @@ public static int countMatches( @Nullable String str, @Nonnull String sub ) /** *
null
returns0
.Checks if the String contains only Unicode letters.
- * + * ** @@ -1744,7 +1744,7 @@ public static boolean isAlpha( String str ) /** *
null
will returnfalse
. * An empty String will returntrue
.Checks if the String contains only whitespace.
- * + * ** @@ -1771,7 +1771,7 @@ public static boolean isWhitespace( String str ) /** *
null
will returnfalse
. An * empty String will returntrue
.Checks if the String contains only Unicode letters and * space (
- * + * *' '
).* @@ -1798,7 +1798,7 @@ public static boolean isAlphaSpace( String str ) /** *
null
will returnfalse
. An * empty String will returntrue
.Checks if the String contains only Unicode letters or digits.
- * + * ** @@ -1826,7 +1826,7 @@ public static boolean isAlphanumeric( String str ) /** *
null
will returnfalse
. An empty * String will returntrue
.Checks if the String contains only Unicode letters, digits * or space (
- * + * *' '
).* @@ -1853,7 +1853,7 @@ public static boolean isAlphanumericSpace( String str ) /** *
null
will returnfalse
. An empty * String will returntrue
.Checks if the String contains only Unicode digits.
- * + * ** @@ -1919,7 +1919,7 @@ public static boolean isNumeric( String str ) /** *
null
will returnfalse
. * An empty String will returntrue
.Reverse a String.
- * + * ** * @param str the String to reverse @@ -1936,7 +1936,7 @@ public static String reverse( String str ) /** *
null
String returnsnull
.Reverses a String that is delimited by a specific character.
- * + * *The Strings between the delimiters are not reversed. * Thus java.lang.String becomes String.lang.java (if the delimiter * is
@@ -1956,8 +1956,6 @@ public static String reverse( String str ) /** *'.'
).Reverses an array.
- * - *TAKEN FROM CollectionsUtils.
* * @param array the array to reverse */ @@ -2165,17 +2163,13 @@ public static String interpolate( String text, @Nonnull Map, ?> namespace ) } /** - * Convert the first character of the given String to uppercase. - * This method will not trim of spaces! - * - *- * Attention: this method will currently throw a - *
+ * Converts the first character of the given String to uppercase. + * This method does not trim spaces! * * @param data the String to get capitalized * @return data string with the first character transformed to uppercase * @throws NullPointerException if data isIndexOutOfBoundsException
for empty strings! - *null
+ * @throws IndexOutOfBoundsException if data is empty */ @Nonnull public static String capitalizeFirstLetter( @Nonnull String data ) { @@ -2192,17 +2186,14 @@ public static String interpolate( String text, @Nonnull Map, ?> namespace ) } /** - * Convert the first character of the given String to lowercase. - * This method will not trim of spaces! + * Converts the first character of the given String to lowercase. + * This method does not trim spaces! * - *- * Attention: this method will currently throw a - *
* * @param data the String to get it's first character lower-cased. * @return data string with the first character transformed to lowercase * @throws NullPointerException if data isIndexOutOfBoundsException
for empty strings! - *null
+ * @throws IndexOutOfBoundsException if data is empty */ @Nonnull public static String lowercaseFirstLetter( @Nonnull String data ) { @@ -2218,7 +2209,7 @@ public static String interpolate( String text, @Nonnull Map, ?> namespace ) * * 'ThisIsIt' will become 'this-is-it'. * - * @param view The view. + * @param view the view * @return deHumped String */ @Nonnull public static String addAndDeHump( @Nonnull String view ) @@ -2240,7 +2231,7 @@ public static String interpolate( String text, @Nonnull Map, ?> namespace ) /** *Quote and escape a String with the given character, handling
- * + * *null
.* StringUtils.quoteAndEscape(null, *) = null * StringUtils.quoteAndEscape("", *) = "" @@ -2264,9 +2255,9 @@ public static String quoteAndEscape( @Nullable String source, char quoteChar ) /** *Quote and escape a String with the given character, handling
* - * @param source The source. - * @param quoteChar The quote character. - * @param quotingTriggers The quoting trigger. + * @param source the source + * @param quoteChar the quote character + * @param quotingTriggers the quoting trigger * @return the String quoted and escaped * @see #quoteAndEscape(String, char, char[], char[], char, boolean) * @@ -2277,11 +2268,11 @@ public static String quoteAndEscape( @Nullable String source, char quoteChar, @N } /** - * @param source The source. - * @param quoteChar The quote character. - * @param escapedChars The escaped characters. - * @param escapeChar The escape character. - * @param force true/false. + * @param source the source + * @param quoteChar the quote character + * @param escapedChars the escaped characters + * @param escapeChar the escape character + * @param force true/false * @return the String quoted and escaped * @see #quoteAndEscape(String, char, char[], char[], char, boolean) * @@ -2293,12 +2284,12 @@ public static String quoteAndEscape( @Nullable String source, char quoteChar, } /** - * @param source The source. - * @param quoteChar The quote character. - * @param escapedChars set of characters to escape. - * @param quotingTriggers The quoting trigger. - * @param escapeChar prefix for escaping a character. - * @param force true/false. + * @param source the source + * @param quoteChar the quote character + * @param escapedChars set of characters to escape + * @param quotingTriggers the quoting trigger + * @param escapeChar prefix for escaping a character + * @param force true/false * @return the String quoted and escaped */ public static String quoteAndEscape( @Nullable String source, char quoteChar, @Nonnull final char[] escapedChars, @@ -2347,9 +2338,9 @@ else if ( !escaped.equals( source ) ) } /** - * @param source The source. - * @param escapedChars set of characters to escape. - * @param escapeChar prefix for escaping a character. + * @param source the source + * @param escapedChars set of characters to escape + * @param escapeChar prefix for escaping a character * @return the String escaped */ public static String escape( @Nullable String source, @Nonnull final char[] escapedChars, char escapeChar ) @@ -2410,7 +2401,7 @@ public static String escape( @Nullable String source, @Nonnull final char[] esca * '\n', '\r' and '\r\n' with the system line separator. * * @param s a not null String - * @return a String that contains only System line separators. + * @return a String that contains only System line separators * @see #unifyLineSeparators(String, String) * */ @@ -2425,7 +2416,7 @@ public static String unifyLineSeparators( @Nullable String s ) * * @param s a not null String * @param ls the wanted line separator ("\n" on UNIX), if null using the System line separator. - * @return a String that contains only System line separators. + * @return a String that contains only System line separators * @throws IllegalArgumentException if ls is not '\n', '\r' and '\r\n' characters. * */ @@ -2476,9 +2467,9 @@ else if ( s.charAt( i ) == '\n' ) /** *null
.Checks if String contains a search character, handling
- * + * *null
. * This method uses {@link String#indexOf(int)}.A
- * + * *null
or empty ("") String will returnfalse
.* StringUtils.contains(null, *) = false * StringUtils.contains("", *) = false @@ -2500,9 +2491,9 @@ public static boolean contains( @Nullable String str, char searchChar ) /** *Checks if String contains a search String, handling
- * + * *null
. * This method uses {@link String#indexOf(int)}.A
- * + * *null
String will returnfalse
.* StringUtils.contains(null, *) = false * StringUtils.contains(*, null) = false @@ -2526,7 +2517,7 @@ public static boolean contains( @Nullable String str, @Nullable String searchStr *Checks if String ends with a search String, handling
* *null
.A
- * + * *null
String will returnfalse
.* StringUtils.endsWithIgnoreCase(null, *) = false * StringUtils.endsWithIgnoreCase(*, null) = false From d63328f2b67ed407ab159fda04031792b6a374a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotrek=20=C5=BBygie=C5=82o?=Date: Tue, 9 Jun 2020 11:40:51 +0200 Subject: [PATCH 165/265] Restore space between referenced parameter and its description --- src/main/java/org/apache/maven/shared/utils/StringUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/maven/shared/utils/StringUtils.java b/src/main/java/org/apache/maven/shared/utils/StringUtils.java index 613b1de4..b44a054f 100644 --- a/src/main/java/org/apache/maven/shared/utils/StringUtils.java +++ b/src/main/java/org/apache/maven/shared/utils/StringUtils.java @@ -540,7 +540,7 @@ public static String mid( String str, int pos, int len ) * StringTokenizer
does). * * @param str the string to parse - * @param separatorcCharacters used as the delimiters. If + * @param separator Characters used as the delimiters. If *null
, splits on whitespace. * @param max the maximum number of elements to include in the * array. A zero or negative value implies no limit. From 5a1ece544cf4b10b16f4fe915db33c22b0bd3095 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotrek=20=C5=BBygie=C5=82o?=Date: Wed, 10 Jun 2020 11:26:03 +0200 Subject: [PATCH 166/265] Remove useless check --- .../java/org/apache/maven/shared/utils/cli/shell/Shell.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java index bec555e0..d2573048 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java @@ -102,7 +102,7 @@ void setShellArgs( String[] shellArgs ) */ String[] getShellArgs() { - if ( ( shellArgs == null ) || shellArgs.isEmpty() ) + if ( shellArgs.isEmpty() ) { return null; } From 8159ddbf5fc3317b85609c785011d8032815def6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotrek=20=C5=BBygie=C5=82o?= Date: Wed, 10 Jun 2020 11:14:40 +0200 Subject: [PATCH 167/265] Remove unused containers This closes #55 --- .../shared/utils/xml/Xpp3DomBuilder.java | 30 ------------------- 1 file changed, 30 deletions(-) diff --git a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java index 8242208b..bfa77f37 100644 --- a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java +++ b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java @@ -24,7 +24,6 @@ import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; @@ -193,14 +192,6 @@ private static class DocHandler private final List values = new ArrayList (); - // Todo: Use these for something smart ! - private final List warnings = new ArrayList (); - - private final List errors = new ArrayList (); - - private final List fatals = new ArrayList (); - - Xpp3Dom result = null; private final boolean trim; @@ -250,27 +241,6 @@ private void attachToParent( Xpp3Dom child ) } } - @Override - public void warning( SAXParseException e ) - throws SAXException - { - warnings.add( e ); - } - - @Override - public void error( SAXParseException e ) - throws SAXException - { - errors.add( e ); - } - - @Override - public void fatalError( SAXParseException e ) - throws SAXException - { - fatals.add( e ); - } - private Xpp3Dom pop() { int depth = elemStack.size() - 1; From 76605ac236ee5fb64062581209e8ee941efcea77 Mon Sep 17 00:00:00 2001 From: Rob Oxspring Date: Wed, 27 May 2020 21:49:20 +0100 Subject: [PATCH 168/265] [MSHARED-431] Escape arguments including hash-signs --- .../org/apache/maven/shared/utils/cli/shell/BourneShell.java | 2 +- .../apache/maven/shared/utils/cli/shell/BourneShellTest.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java index 1793cbb7..02586afd 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java @@ -34,7 +34,7 @@ public class BourneShell private static final char DOUBLE_QUOTATION = '"'; private static final char[] BASH_QUOTING_TRIGGER_CHARS = - { ' ', '$', ';', '&', '|', '<', '>', '*', '?', '(', ')', '[', ']', '{', '}', '`' }; + { ' ', '$', ';', '&', '|', '<', '>', '*', '?', '(', ')', '[', ']', '{', '}', '`', '#' }; /** * Create instance of BourneShell. diff --git a/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java b/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java index c83287c2..7d5c4565 100644 --- a/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java +++ b/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java @@ -186,13 +186,14 @@ public void testBourneShellQuotingCharacters() commandline.createArg().setValue( "{" ); commandline.createArg().setValue( "}" ); commandline.createArg().setValue( "`" ); + commandline.createArg().setValue( "#" ); List lines = commandline.getShell().getShellCommandLine( commandline.getArguments() ); System.out.println( lines ); assertEquals( "/bin/sh", lines.get( 0 ) ); assertEquals( "-c", lines.get( 1 ) ); - assertEquals( "chmod \" \" \"|\" \"&&\" \"||\" \";\" \";;\" \"&\" \"()\" \"<\" \"<<\" \">\" \">>\" \"*\" \"?\" \"[\" \"]\" \"{\" \"}\" \"`\"", + assertEquals( "chmod \" \" \"|\" \"&&\" \"||\" \";\" \";;\" \"&\" \"()\" \"<\" \"<<\" \">\" \">>\" \"*\" \"?\" \"[\" \"]\" \"{\" \"}\" \"`\" \"#\"", lines.get( 2 ) ); } From f751e614c09df8de1a080dc1153931f3f68991c9 Mon Sep 17 00:00:00 2001 From: Rob Oxspring Date: Thu, 28 May 2020 23:29:05 +0100 Subject: [PATCH 169/265] [MSHARED-297] - BourneShell unconditionally single quotes executable and arguments Closes #40 --- .../shared/utils/cli/shell/BourneShell.java | 49 +++++++------------ .../maven/shared/utils/cli/shell/Shell.java | 39 ++++++++++----- .../utils/cli/shell/BourneShellTest.java | 32 ++++++++---- 3 files changed, 70 insertions(+), 50 deletions(-) diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java index 02586afd..33177889 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java @@ -23,7 +23,6 @@ import java.util.ArrayList; import java.util.List; import org.apache.maven.shared.utils.Os; -import org.apache.maven.shared.utils.StringUtils; /** * @author Jason van Zyl @@ -31,19 +30,16 @@ public class BourneShell extends Shell { - private static final char DOUBLE_QUOTATION = '"'; - - private static final char[] BASH_QUOTING_TRIGGER_CHARS = - { ' ', '$', ';', '&', '|', '<', '>', '*', '?', '(', ')', '[', ']', '{', '}', '`', '#' }; /** * Create instance of BourneShell. */ public BourneShell() { + setUnconditionalQuoting( true ); setShellCommand( "/bin/sh" ); - setArgumentQuoteDelimiter( DOUBLE_QUOTATION ); - setExecutableQuoteDelimiter( DOUBLE_QUOTATION ); + setArgumentQuoteDelimiter( '\'' ); + setExecutableQuoteDelimiter( '\'' ); setSingleQuotedArgumentEscaped( true ); setSingleQuotedExecutableEscaped( false ); setQuotedExecutableEnabled( true ); @@ -59,7 +55,7 @@ public String getExecutable() return super.getExecutable(); } - return unifyQuotes( super.getExecutable() ); + return quoteOneItem( super.getExecutable(), true ); } /** {@inheritDoc} */ @@ -112,47 +108,40 @@ protected String getExecutionPreamble() StringBuilder sb = new StringBuilder(); sb.append( "cd " ); - sb.append( unifyQuotes( dir ) ); + sb.append( quoteOneItem( dir, false ) ); sb.append( " && " ); return sb.toString(); } - /** {@inheritDoc} */ - protected char[] getQuotingTriggerChars() - { - return BASH_QUOTING_TRIGGER_CHARS; - } - /** * Unify quotes in a path for the Bourne Shell.
* *- * BourneShell.unifyQuotes(null) = null - * BourneShell.unifyQuotes("") = (empty) - * BourneShell.unifyQuotes("/test/quotedpath'abc") = /test/quotedpath\'abc - * BourneShell.unifyQuotes("/test/quoted path'abc") = "/test/quoted path'abc" - * BourneShell.unifyQuotes("/test/quotedpath\"abc") = "/test/quotedpath\"abc" - * BourneShell.unifyQuotes("/test/quoted path\"abc") = "/test/quoted path\"abc" - * BourneShell.unifyQuotes("/test/quotedpath\"'abc") = "/test/quotedpath\"'abc" - * BourneShell.unifyQuotes("/test/quoted path\"'abc") = "/test/quoted path\"'abc" + * BourneShell.quoteOneItem(null) = null + * BourneShell.quoteOneItem("") = '' + * BourneShell.quoteOneItem("/test/quotedpath'abc") = '/test/quotedpath'"'"'abc' + * BourneShell.quoteOneItem("/test/quoted path'abc") = '/test/quoted pat'"'"'habc' + * BourneShell.quoteOneItem("/test/quotedpath\"abc") = '/test/quotedpath"abc' + * BourneShell.quoteOneItem("/test/quoted path\"abc") = '/test/quoted path"abc' + * BourneShell.quoteOneItem("/test/quotedpath\"'abc") = '/test/quotedpath"'"'"'abc' + * BourneShell.quoteOneItem("/test/quoted path\"'abc") = '/test/quoted path"'"'"'abc' ** * @param path not null path. * @return the path unified correctly for the Bourne shell. */ - private static String unifyQuotes( String path ) + protected String quoteOneItem( String path, boolean isExecutable ) { if ( path == null ) { return null; } - if ( path.indexOf( ' ' ) == -1 && path.indexOf( '\'' ) != -1 && path.indexOf( '"' ) == -1 ) - { - return StringUtils.escape( path ); - } - - return StringUtils.quoteAndEscape( path, '\"', BASH_QUOTING_TRIGGER_CHARS ); + StringBuilder sb = new StringBuilder(); + sb.append( "'" ); + sb.append( path.replace( "'", "'\"'\"'" ) ); + sb.append( "'" ); + return sb.toString(); } } diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java index d2573048..c1e5dd0c 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java @@ -49,6 +49,8 @@ public class Shell private boolean quotedArgumentsEnabled = true; + private boolean unconditionalQuoting = false; + private String executable; private String workingDir; @@ -112,6 +114,19 @@ String[] getShellArgs() } } + protected String quoteOneItem( String inputString, boolean isExecutable ) + { + char[] escapeChars = getEscapeChars( isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped() ); + return StringUtils.quoteAndEscape( + inputString, + isExecutable ? getExecutableQuoteDelimiter() : getArgumentQuoteDelimiter(), + escapeChars, + getQuotingTriggerChars(), + '\\', + unconditionalQuoting + ); + } + /** * Get the command line for the provided executable and arguments in this shell * @@ -144,15 +159,11 @@ ListgetRawCommandLine( String executableParameter, String... argumentsP if ( isQuotedExecutableEnabled() ) { - char[] escapeChars = - getEscapeChars( isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped() ); - - sb.append( StringUtils.quoteAndEscape( getExecutable(), getExecutableQuoteDelimiter(), escapeChars, - getQuotingTriggerChars(), '\\', false ) ); + sb.append( quoteOneItem( executableParameter, true ) ); } else { - sb.append( getExecutable() ); + sb.append( executableParameter ); } } for ( String argument : argumentsParameter ) @@ -164,10 +175,7 @@ List getRawCommandLine( String executableParameter, String... argumentsP if ( isQuotedArgumentsEnabled() ) { - char[] escapeChars = getEscapeChars( isSingleQuotedArgumentEscaped(), isDoubleQuotedArgumentEscaped() ); - - sb.append( StringUtils.quoteAndEscape( argument, getArgumentQuoteDelimiter(), escapeChars, - getQuotingTriggerChars(), '\\', false ) ); + sb.append( quoteOneItem( argument, false ) ); } else { @@ -284,7 +292,7 @@ public List getShellCommandLine( String... arguments ) commandLine.addAll( getShellArgsList() ); } - commandLine.addAll( getCommandLine( getExecutable(), arguments ) ); + commandLine.addAll( getCommandLine( executable, arguments ) ); return commandLine; @@ -398,4 +406,13 @@ void setSingleQuotedExecutableEscaped( boolean singleQuotedExecutableEscaped ) this.singleQuotedExecutableEscaped = singleQuotedExecutableEscaped; } + public boolean isUnconditionalQuoting() + { + return unconditionalQuoting; + } + + public void setUnconditionalQuoting( boolean unconditionalQuoting ) + { + this.unconditionalQuoting = unconditionalQuoting; + } } diff --git a/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java b/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java index 7d5c4565..4fbcf841 100644 --- a/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java +++ b/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java @@ -44,7 +44,7 @@ public void testQuoteWorkingDirectoryAndExecutable() String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " ); - assertEquals( "/bin/sh -c cd /usr/local/bin && chmod", executable ); + assertEquals( "/bin/sh -c cd '/usr/local/bin' && 'chmod'", executable ); } public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes() @@ -56,7 +56,7 @@ public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes() String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " ); - assertEquals( "/bin/sh -c cd \"/usr/local/\'something else\'\" && chmod", executable ); + assertEquals( "/bin/sh -c cd '/usr/local/'\"'\"'something else'\"'\"'' && 'chmod'", executable ); } public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep() @@ -68,7 +68,7 @@ public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_Backsl String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " ); - assertEquals( "/bin/sh -c cd \"\\usr\\local\\\'something else\'\" && chmod", executable ); + assertEquals( "/bin/sh -c cd '\\usr\\local\\'\"'\"'something else'\"'\"'' && 'chmod'", executable ); } public void testPreserveSingleQuotesOnArgument() @@ -84,7 +84,7 @@ public void testPreserveSingleQuotesOnArgument() String cli = StringUtils.join( shellCommandLine.iterator(), " " ); System.out.println( cli ); - assertTrue( cli.endsWith( args[0] ) ); + assertTrue( cli.endsWith( "'\"some arg with spaces\"'" ) ); } public void testAddSingleQuotesOnArgumentWithSpaces() @@ -100,7 +100,21 @@ public void testAddSingleQuotesOnArgumentWithSpaces() String cli = StringUtils.join( shellCommandLine.iterator(), " " ); System.out.println( cli ); - assertTrue( cli.endsWith( "\"" + args[0] + "\"" ) ); + assertTrue( cli.endsWith("'some arg with spaces'")); + } + + public void testAddArgumentWithSingleQuote() + { + Shell sh = newShell(); + + sh.setWorkingDirectory( "/usr/bin" ); + sh.setExecutable( "chmod" ); + + String[] args = { "arg'withquote" }; + + List shellCommandLine = sh.getShellCommandLine( args ); + + assertEquals("cd '/usr/bin' && 'chmod' 'arg'\"'\"'withquote'", shellCommandLine.get(shellCommandLine.size() - 1)); } public void testArgumentsWithSemicolon() @@ -119,7 +133,7 @@ public void testArgumentsWithSemicolon() String cli = StringUtils.join( shellCommandLine.iterator(), " " ); System.out.println( cli ); - assertTrue( cli.endsWith( "\"" + args[0] + "\"" ) ); + assertTrue( cli.endsWith( "';some&argwithunix$chars'" ) ); Commandline commandline = new Commandline( newShell() ); commandline.setExecutable( "chmod" ); @@ -132,7 +146,7 @@ public void testArgumentsWithSemicolon() assertEquals( "/bin/sh", lines.get( 0 ) ); assertEquals( "-c", lines.get( 1 ) ); - assertEquals( "chmod --password \";password\"", lines.get( 2 ) ); + assertEquals( "'chmod' '--password' ';password'", lines.get( 2 ) ); commandline = new Commandline( newShell() ); commandline.setExecutable( "chmod" ); @@ -144,7 +158,7 @@ public void testArgumentsWithSemicolon() assertEquals( "/bin/sh", lines.get( 0) ); assertEquals( "-c", lines.get( 1 ) ); - assertEquals( "chmod --password \";password\"", lines.get( 2 ) ); + assertEquals( "'chmod' '--password' ';password'", lines.get( 2 ) ); commandline = new Commandline( new CmdShell() ); commandline.getShell().setQuotedArgumentsEnabled( true ); @@ -193,7 +207,7 @@ public void testBourneShellQuotingCharacters() assertEquals( "/bin/sh", lines.get( 0 ) ); assertEquals( "-c", lines.get( 1 ) ); - assertEquals( "chmod \" \" \"|\" \"&&\" \"||\" \";\" \";;\" \"&\" \"()\" \"<\" \"<<\" \">\" \">>\" \"*\" \"?\" \"[\" \"]\" \"{\" \"}\" \"`\" \"#\"", + assertEquals( "'chmod' ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`' '#'", lines.get( 2 ) ); } From 6798f3033c3c5144e52c5aa8e1be584ea97527d2 Mon Sep 17 00:00:00 2001 From: Rob Oxspring Date: Thu, 28 May 2020 23:50:09 +0100 Subject: [PATCH 170/265] [MSHARED-297] - Minor code cleanup --- .../shared/utils/cli/shell/BourneShell.java | 13 ++--------- .../maven/shared/utils/cli/shell/Shell.java | 6 ++--- .../utils/cli/CommandLineUtilsTest.java | 5 ++--- .../utils/cli/shell/BourneShellTest.java | 22 ++++++------------- 4 files changed, 14 insertions(+), 32 deletions(-) diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java index 33177889..e3af6651 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java @@ -105,13 +105,8 @@ protected String getExecutionPreamble() } String dir = getWorkingDirectoryAsString(); - StringBuilder sb = new StringBuilder(); - sb.append( "cd " ); - sb.append( quoteOneItem( dir, false ) ); - sb.append( " && " ); - - return sb.toString(); + return "cd " + quoteOneItem( dir, false ) + " && "; } /** @@ -138,10 +133,6 @@ protected String quoteOneItem( String path, boolean isExecutable ) return null; } - StringBuilder sb = new StringBuilder(); - sb.append( "'" ); - sb.append( path.replace( "'", "'\"'\"'" ) ); - sb.append( "'" ); - return sb.toString(); + return "'" + path.replace( "'", "'\"'\"'" ) + "'"; } } diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java index c1e5dd0c..02681086 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java @@ -110,7 +110,7 @@ String[] getShellArgs() } else { - return shellArgs.toArray( new String[shellArgs.size()] ); + return shellArgs.toArray( new String[0] ); } } @@ -146,7 +146,7 @@ List getCommandLine( String executableParameter, String... argumentsPara */ List getRawCommandLine( String executableParameter, String... argumentsParameter ) { - List commandLine = new ArrayList (); + List commandLine = new ArrayList<>(); StringBuilder sb = new StringBuilder(); if ( executableParameter != null ) @@ -280,7 +280,7 @@ char getExecutableQuoteDelimiter() public List getShellCommandLine( String... arguments ) { - List commandLine = new ArrayList (); + List commandLine = new ArrayList<>(); if ( getShellCommand() != null ) { diff --git a/src/test/java/org/apache/maven/shared/utils/cli/CommandLineUtilsTest.java b/src/test/java/org/apache/maven/shared/utils/cli/CommandLineUtilsTest.java index 50d9336c..079d0d16 100644 --- a/src/test/java/org/apache/maven/shared/utils/cli/CommandLineUtilsTest.java +++ b/src/test/java/org/apache/maven/shared/utils/cli/CommandLineUtilsTest.java @@ -148,8 +148,8 @@ public void givenAnEscapedDoubleQuoteMarkInArgument_whenTranslatingToCmdLineArgs public void givenAnEscapedSingleQuoteMarkInArgument_whenTranslatingToCmdLineArgs_thenTheQuotationMarkRemainsEscaped() throws Exception { - final String command = "echo \"let\\\'s go\""; - final String[] expected = new String[] { "echo", "let\\\'s go" }; + final String command = "echo \"let\\'s go\""; + final String[] expected = new String[] { "echo", "let\\'s go"}; assertCmdLineArgs( expected, command ); } @@ -168,5 +168,4 @@ private void assertCmdLineArgs( final String[] expected, final String cmdLine ) assertEquals( expected.length, actual.length ); assertEquals( Arrays.asList( expected ), Arrays.asList( actual ) ); } - } diff --git a/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java b/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java index 4fbcf841..199f36e4 100644 --- a/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java +++ b/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java @@ -42,7 +42,7 @@ public void testQuoteWorkingDirectoryAndExecutable() sh.setWorkingDirectory( "/usr/local/bin" ); sh.setExecutable( "chmod" ); - String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " ); + String executable = StringUtils.join( sh.getShellCommandLine().iterator(), " " ); assertEquals( "/bin/sh -c cd '/usr/local/bin' && 'chmod'", executable ); } @@ -54,7 +54,7 @@ public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes() sh.setWorkingDirectory( "/usr/local/'something else'" ); sh.setExecutable( "chmod" ); - String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " ); + String executable = StringUtils.join( sh.getShellCommandLine().iterator(), " " ); assertEquals( "/bin/sh -c cd '/usr/local/'\"'\"'something else'\"'\"'' && 'chmod'", executable ); } @@ -66,7 +66,7 @@ public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_Backsl sh.setWorkingDirectory( "\\usr\\local\\'something else'" ); sh.setExecutable( "chmod" ); - String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " ); + String executable = StringUtils.join( sh.getShellCommandLine().iterator(), " " ); assertEquals( "/bin/sh -c cd '\\usr\\local\\'\"'\"'something else'\"'\"'' && 'chmod'", executable ); } @@ -78,9 +78,7 @@ public void testPreserveSingleQuotesOnArgument() sh.setWorkingDirectory( "/usr/bin" ); sh.setExecutable( "chmod" ); - final String[] args = { "\"some arg with spaces\"" }; - - List shellCommandLine = sh.getShellCommandLine( args ); + List shellCommandLine = sh.getShellCommandLine("\"some arg with spaces\""); String cli = StringUtils.join( shellCommandLine.iterator(), " " ); System.out.println( cli ); @@ -94,9 +92,7 @@ public void testAddSingleQuotesOnArgumentWithSpaces() sh.setWorkingDirectory( "/usr/bin" ); sh.setExecutable( "chmod" ); - String[] args = { "some arg with spaces" }; - - List shellCommandLine = sh.getShellCommandLine( args ); + List shellCommandLine = sh.getShellCommandLine("some arg with spaces"); String cli = StringUtils.join( shellCommandLine.iterator(), " " ); System.out.println( cli ); @@ -110,9 +106,7 @@ public void testAddArgumentWithSingleQuote() sh.setWorkingDirectory( "/usr/bin" ); sh.setExecutable( "chmod" ); - String[] args = { "arg'withquote" }; - - List shellCommandLine = sh.getShellCommandLine( args ); + List shellCommandLine = sh.getShellCommandLine("arg'withquote"); assertEquals("cd '/usr/bin' && 'chmod' 'arg'\"'\"'withquote'", shellCommandLine.get(shellCommandLine.size() - 1)); } @@ -127,9 +121,7 @@ public void testArgumentsWithSemicolon() sh.setWorkingDirectory( "/usr/bin" ); sh.setExecutable( "chmod" ); - String[] args = { ";some&argwithunix$chars" }; - - List shellCommandLine = sh.getShellCommandLine( args ); + List shellCommandLine = sh.getShellCommandLine(";some&argwithunix$chars"); String cli = StringUtils.join( shellCommandLine.iterator(), " " ); System.out.println( cli ); From dda9e1480f4f51120f619dfd302ed0d10807dfa5 Mon Sep 17 00:00:00 2001 From: Elliotte Rusty Harold Date: Fri, 17 Jul 2020 09:44:24 -0400 Subject: [PATCH 171/265] [MSHARED-904] update test dependencies for Maven 3.1 (#57) * update test dependencies * commons-lang not used * declare plexus --- pom.xml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/pom.xml b/pom.xml index 714a5200..c348c54c 100644 --- a/pom.xml +++ b/pom.xml @@ -90,12 +90,6 @@ commons-io 2.6
destinationDirectory
isn't a directory
* @throws IOException if source
does not exist, the file in
* destinationDirectory
cannot be written to, or an IO error
- * occurs during copying.
+ * occurs during copying
* @deprecated use {@code org.apache.commons.io.FileUtils.copyFileToDirectory()}
*/
@Deprecated
@@ -791,11 +791,11 @@ private static void copyFileToDirectoryIfModified( @Nonnull final File source,
* @param source an existing non-directory File
to copy bytes from
* @param destination a non-directory File
to write bytes to (possibly
* overwriting)
- * @throws IOException if source
does not exist, destination
cannot be
- * written to, or an IO error occurs during copying
+ * @throws IOException if source
does not exist, destination
cannot be
+ * written to, or an IO error occurs during copying
* @throws java.io.FileNotFoundException if destination
is a directory
- * @deprecated use {@code java.nio.Files.copy(source.toPath(), destination.toPath(), CopyOptions.NOFOLLOW_LINKS,
- * CopyOptions.REPLACE_EXISTING)}
+ * @deprecated use {@code java.nio.Files.copy(source.toPath(), destination.toPath(), LinkOption.NOFOLLOW_LINKS,
+ * StandardCopyOption.REPLACE_EXISTING)}
*/
@Deprecated
public static void copyFile( @Nonnull final File source, @Nonnull final File destination )
@@ -873,7 +873,7 @@ private static void doCopyFile( @Nonnull File source, @Nonnull File destination
* @param source An existing non-directory File
to copy bytes from.
* @param destination A non-directory File
to write bytes to (possibly
* overwriting).
- * @return true if no problem occured
+ * @return true if no problem occurred
* @throws IOException if source
does not exist, destination
cannot be
* written to, or an IO error occurs during copying.
*/
@@ -895,9 +895,9 @@ private static boolean copyFileIfModified( @Nonnull final File source, @Nonnull
* The directories up to destination
will be created if they don't already exist.
* destination
will be overwritten if it already exists.
*
- * @param source A URL
to copy bytes from.
- * @param destination A non-directory File
to write bytes to (possibly
- * overwriting).
+ * @param source a URL
to copy bytes from
+ * @param destination a non-directory File
to write bytes to (possibly
+ * overwriting)
* @throws IOException if
* source
URL cannot be openeddestination
will be created if they don't already exist.
* destination
will be overwritten if it already exists.
*
- * @param source An {@link InputStream} to copy bytes from. This stream is
+ * @param source an {@link InputStream} to copy bytes from. This stream is
* guaranteed to be closed.
- * @param destination A non-directory File
to write bytes to (possibly
- * overwriting).
+ * @param destination a non-directory File
to write bytes to (possibly
+ * overwriting)
* @throws IOException if
* source
cannot be openednull
if too many ..'s.
+ * @return the normalized String, or null
if too many ..'s
* @deprecated use {@code org.apache.commons.io.FileNameUtils.normalize()}
*/
@Deprecated
@@ -1026,8 +1026,7 @@ private static void copyStreamToFile( @Nonnull @WillClose final InputStream sour
* relative (doesn't start with /
), it will be resolved relative to
* baseFile
, otherwise it is treated as a normal root-relative path.
*
- * @param baseFile Where to resolve filename
from, if filename
is
- * relative.
+ * @param baseFile where to resolve filename
from, if filename
is relative
* @param filename absolute or relative file path to resolve
* @return the canonical File
of filename
*/
From e07ce88105d5f03d597810f9ed08c223a1a07492 Mon Sep 17 00:00:00 2001
From: Elliotte Rusty Harold null
.
- * @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.
+ * @deprecated use System#getenv()
*/
+ @Deprecated
public static Properties getSystemEnvVars()
{
return getSystemEnvVars( !Os.isFamily( Os.FAMILY_WINDOWS ) );
@@ -435,9 +435,9 @@ public static Properties getSystemEnvVars()
*
* @param caseSensitive Whether environment variable keys should be treated case-sensitively.
* @return Properties object of (possibly modified) envar keys mapped to their values.
- * @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.
+ * @deprecated use System#getenv()
*/
+ @Deprecated
public static Properties getSystemEnvVars( boolean caseSensitive )
{
MapSets the shell or command-line interpretor for the detected operating system, + *
Sets the shell or command-line interpreter for the detected operating system, * and the shell arguments.
*/ private void setDefaultShell() @@ -140,13 +139,9 @@ private void setDefaultShell() } /** - * Creates an argument object. - * - *Each commandline object has at most one instance of the
- * argument class. This method calls
- * this.createArgument(false)
.
Each commandline object has at most one instance of the - * argument class.
+ * Creates an argument object and adds it to the list of args. * * @param insertAtStart if true, the argument is inserted at the - * beginning of the list of args, otherwise it is appended. - * @return The arguments. + * beginning of the list of args. Otherwise it is appended. + * @return the argument */ public Arg createArg( boolean insertAtStart ) { @@ -179,7 +171,8 @@ public Arg createArg( boolean insertAtStart ) /** * Sets the executable to run. - * @param executable The executable. + * + * @param executable the executable */ public void setExecutable( String executable ) { @@ -187,7 +180,7 @@ public void setExecutable( String executable ) } /** - * @return The executable. + * @return the executable */ public String getExecutable() { @@ -196,7 +189,7 @@ public String getExecutable() } /** - * @param line The arguments. + * @param line the arguments */ public void addArguments( String... line ) { @@ -207,9 +200,10 @@ public void addArguments( String... line ) } /** - * Add an environment variable - * @param name The name of the environment variable. - * @param value The appropriate value. + * Add an environment variable. + * + * @param name the name of the environment variable + * @param value the appropriate value */ public void addEnvironment( String name, String value ) { @@ -218,7 +212,7 @@ public void addEnvironment( String name, String value ) } /** - * Add system environment variables + * Add system environment variables. */ public void addSystemEnvironment() { @@ -235,8 +229,9 @@ public void addSystemEnvironment() } /** - * Return the list of environment variables - * @return an array of all environment variables. + * Return the list of environment variables. + * + * @return an array of all environment variables */ public String[] getEnvironmentVariables() { @@ -254,7 +249,8 @@ public String[] getEnvironmentVariables() /** * Returns the executable and all defined arguments. - * @return an array of all arguments incl. executable. + * + * @return an array of all arguments including the executable */ public String[] getCommandline() { @@ -272,7 +268,7 @@ public String[] getCommandline() } /** - * @return the shell, executable and all defined arguments without masking any arguments. + * @return the shell, executable and all defined arguments without masking any arguments */ private String[] getShellCommandline() { @@ -280,7 +276,7 @@ private String[] getShellCommandline() } /** - * @param mask flag to mask any arguments (having his {@code mask} field to {@code true}). + * @param mask flag to mask any arguments (having his {@code mask} field to {@code true}) * @return the shell, executable and all defined arguments with masking some arguments if * {@code mask} parameter is on */ @@ -302,10 +298,10 @@ public String[] getArguments() /** * Returns all arguments defined byaddLine
,
- * addValue
or the argument object.
+ * addValue
, or the argument object.
*
- * @param mask flag to mask any arguments (having his {@code mask} field to {@code true}).
- * @return an array of arguments.
+ * @param mask flag to mask any arguments (having his {@code mask} field to {@code true})
+ * @return an array of arguments
*/
public String[] getArguments( boolean mask )
{
@@ -355,7 +351,8 @@ public Object clone()
/**
* Sets working directory.
- * @param path The to be set as working directory.
+ *
+ * @param path the working directory
*/
public void setWorkingDirectory( String path )
{
@@ -363,8 +360,9 @@ public void setWorkingDirectory( String path )
}
/**
- * Sets execution directory.
- * @param workingDirectory The working directory.
+ * Sets working directory.
+ *
+ * @param workingDirectory the working directory
*/
public void setWorkingDirectory( File workingDirectory )
{
@@ -372,7 +370,7 @@ public void setWorkingDirectory( File workingDirectory )
}
/**
- * @return The working directory.
+ * @return the working directory
*/
public File getWorkingDirectory()
{
@@ -388,17 +386,16 @@ public void clearArgs()
}
/**
- * Executes the command.
- * @return The process.
- * @throws CommandLineException in case of errors.
+ * Execute the command.
+ *
+ * @return the process
+ * @throws CommandLineException in case of errors
*/
public Process execute()
throws CommandLineException
{
Process process;
- //addEnvironment( "MAVEN_TEST_ENVAR", "MAVEN_TEST_ENVAR_VALUE" );
-
String[] environment = getEnvironmentVariables();
File workingDir = shell.getWorkingDirectory();
@@ -434,7 +431,7 @@ else if ( !workingDir.isDirectory() )
}
/**
- * Allows to set the shell to be used in this command line.
+ * Set the shell to be used for this command line.
*
* @param shell the shell
*/
@@ -445,7 +442,8 @@ void setShell( Shell shell )
/**
* Get the shell to be used in this command line.
- * @return the shell.
+ *
+ * @return the shell
*/
public Shell getShell()
{
@@ -453,7 +451,7 @@ public Shell getShell()
}
/**
- *
+ * A single command line argument
*/
public static class Argument
implements Arg
@@ -502,7 +500,7 @@ public void setMask( boolean mask )
}
/**
- * @return The parts.
+ * @return the parts
*/
private String[] getParts()
{
From e6249ce6a57590b73e1e666a83593afb04fd1d0a Mon Sep 17 00:00:00 2001
From: Elliotte Rusty Harold Methods exist to retrieve the components of a typical file path. For example
* /www/hosted/mysite/index.html
, can be broken into:
*
filename
to it's canonical form. If filename
is
- * relative (doesn't start with /
), it will be resolved relative to
- * baseFile
, otherwise it is treated as a normal root-relative path.
+ * Resolve a file filename
to its canonical form. If filename
is
+ * relative (doesn't start with /
), it is resolved relative to
+ * baseFile
. Otherwise it is treated as a normal root-relative path.
*
* @param baseFile where to resolve filename
from, if filename
is relative
* @param filename absolute or relative file path to resolve
@@ -1605,14 +1605,30 @@ public static ListsourceDirectory
must exist.
* true
if the document headers have freshly been written.
*/
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/XMLWriter.java b/src/main/java/org/apache/maven/shared/utils/xml/XMLWriter.java
index 0daad8bc..32a56d26 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/XMLWriter.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/XMLWriter.java
@@ -30,7 +30,7 @@ public interface XMLWriter
/**
* Sets the encoding of the document.
- * If not set, UTF-8 is being used
+ * If not set, UTF-8 is used.
*
* @param encoding the encoding
* @throws IllegalStateException if the generation of the document has already started
@@ -38,7 +38,7 @@ public interface XMLWriter
void setEncoding( String encoding );
/**
- * Sets the docType of the document.
+ * Sets the DOCTYPE of the document.
*
* @param docType the docType
* @throws IllegalStateException if the generation of the document has already started
@@ -48,15 +48,17 @@ public interface XMLWriter
/**
* Start an XML Element tag.
- * @param name The name of the tag.
- * @throws IOException if starting the element fails.
+ *
+ * @param name the name of the tag
+ * @throws IOException if starting the element fails
*/
void startElement( String name ) throws IOException;
/**
* Add a XML attribute to the current XML Element.
- * This method must get called immediately after {@link #startElement(String)}
+ * This method must get called immediately after {@link #startElement(String)}.
+ *
* @param key The key of the attribute.
* @param value The value of the attribute.
* @throws IllegalStateException if no element tag is currently in process
@@ -65,8 +67,9 @@ public interface XMLWriter
void addAttribute( String key, String value ) throws IOException;
/**
- * Add a value text to the current element tag
- * This will perform XML escaping to guarantee valid content
+ * Add text to the current element tag.
+ * This performs XML escaping to guarantee well-formed content.
+ *
* @param text The text which should be written.
* @throws IllegalStateException if no element tag got started yet
* @throws IOException if writing the text fails.
@@ -74,10 +77,11 @@ public interface XMLWriter
void writeText( String text ) throws IOException;
/**
- * Add a preformatted markup to the current element tag
- * @param text The text which should be written.
- * @throws IllegalStateException if no element tag got started yet
- * @throws IOException if writing the markup fails.
+ * Add preformatted markup to the current element tag.
+ *
+ * @param text the text which should be written
+ * @throws IllegalStateException if no element tag is started yet
+ * @throws IOException if writing the markup fails
*/
void writeMarkup( String text ) throws IOException;
diff --git a/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java b/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java
index 4830f433..d0611119 100644
--- a/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java
+++ b/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java
@@ -20,9 +20,8 @@
*/
import java.io.IOException;
-
-import javax.swing.text.html.HTML;
import java.io.StringWriter;
+import javax.swing.text.html.HTML;
import org.apache.maven.shared.utils.StringUtils;
import org.junit.Assert;
@@ -32,13 +31,25 @@
* Test of {@link PrettyPrintXMLWriter}
*
* @author Vincent Siveton
- *
*/
public class PrettyPrintXmlWriterTest
{
- private StringWriter w = new StringWriter();
+ private StringWriter w = new StringWriter();;
private PrettyPrintXMLWriter writer = new PrettyPrintXMLWriter( w );
+ @Test
+ public void testNoStartTag() throws IOException
+ {
+
+ try {
+ writer.startElement( "" );
+ Assert.fail( "allowed empty name" );
+ } catch ( IllegalArgumentException ex ) {
+ Assert.assertEquals( "Element name cannot be empty", ex.getMessage() );
+ }
+
+ }
+
@Test
public void testDefaultPrettyPrintXMLWriter() throws IOException
{
From 9f40037bfb04d54dd997a9ab837390045c9a4348 Mon Sep 17 00:00:00 2001
From: Maarten Mulders Condition that tests the OS type.
- * *This class got copied over from Apache ANT.
* Even the version from plexus-utils was
- * only an ANT fork!
+ * only an ANT fork!
* The last time it got copied was on 2011-08-12
When merging changes please take care of the special * OS_FAMILY handling in this version of Os.java!
* diff --git a/src/main/java/org/apache/maven/shared/utils/PathTool.java b/src/main/java/org/apache/maven/shared/utils/PathTool.java index 28bc3083..2a0b0fe5 100644 --- a/src/main/java/org/apache/maven/shared/utils/PathTool.java +++ b/src/main/java/org/apache/maven/shared/utils/PathTool.java @@ -26,12 +26,13 @@ import javax.annotation.Nullable; /** - * Path tool contains static methods to assist in determining path-related - * information such as relative paths. - * + *Path tool contains static methods to assist in determining path-related + * information such as relative paths.
+ ** This class originally got developed at Apache Anakia and later maintained * in maven-utils of Apache Maven-1. * Some external fixes by Apache Committers have been applied later. + *
*/ public class PathTool { @@ -55,9 +56,9 @@ public PathTool() * file separators. The relative path returned is formed using * forward slashes as it is expected this path is to be used as a * link in a web page (again mimicking Anakia's behavior). - * + *
* This method is thread-safe.
- *
+ *
* PathTool.getRelativePath( null, null ) = "" * PathTool.getRelativePath( null, "/usr/local/java/bin" ) = "" @@ -111,8 +112,7 @@ public static String getRelativePath( @Nullable String basedir, @Nullable String } /** - * This method can calculate the relative path between two pathes on a file system. - *
+ *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" ) = "" diff --git a/src/main/java/org/apache/maven/shared/utils/StringUtils.java b/src/main/java/org/apache/maven/shared/utils/StringUtils.java index b70cdae8..de4a1e88 100644 --- a/src/main/java/org/apache/maven/shared/utils/StringUtils.java +++ b/src/main/java/org/apache/maven/shared/utils/StringUtils.java @@ -104,7 +104,6 @@ public static String trim( String str ) * * @param str String target to delete whitespace from * @return the String without whitespace - * @throws NullPointerException */ @Nonnull public static String deleteWhitespace( @Nonnull String str ) { @@ -122,7 +121,7 @@ public static String trim( String str ) /** *Checks if a String is non
+ * not empty (null
and is - * not empty (length > 0
).length > 0
). * * @param str the String to check * @return true if the String is non-null, and not length zero @@ -816,7 +815,7 @@ public static String replace( @Nullable String text, @Nullable String repl, @Nul //-------------------------------------------------------------------------- /** - *Center a String in a larger String of size
n
.+ *
Center a String in a larger String of size
* *n
.Uses spaces as the value to buffer the String with. * Equivalent to
@@ -1174,7 +1173,7 @@ else if ( ch < 32 ) * @param str String to repeat * @param repeat number of times to repeat str * @return String with repeated String - * @throws NegativeArraySizeException ifcenter(str, size, " ")
.repeat < 0
+ * @throws NegativeArraySizeException ifrepeat < 0
* @throws NullPointerException if str isnull
*/ @Nonnull public static String repeat( @Nonnull String str, int repeat ) @@ -1979,14 +1978,12 @@ private static void reverseArray( @Nonnull String... array ) //-------------------------------------------------------------------------- /** - * Turn "Now is the time for all good men" into "Now is the time for..." - * - * Specifically: - * - * If str is less than max characters long, return it. + *Turn "Now is the time for all good men" into "Now is the time for..."
+ *Specifically:
+ *If str is less than max characters long, return it. * Else abbreviate it to (substring(str, 0, max-3) + "..."). * If maxWidth is less than 3, throw an IllegalArgumentException. - * In no case will it return a string of length greater than maxWidth. + * In no case will it return a string of length greater than maxWidth.
* * @param s The string to be abbreviated. * @param maxWidth maximum length of result string @@ -1999,12 +1996,13 @@ private static void reverseArray( @Nonnull String... array ) /** * Turn "Now is the time for all good men" into "...is the time for..." - * + ** Works like abbreviate(String, int), but allows you to specify a "left edge" * offset. Note that this left edge is not necessarily going to be the leftmost * character in the result, or the first * character following the ellipses, but it will appear somewhere in the result. * In no case will it return a string of length greater than maxWidth. + *
* * @param s String to abbreviate. * @param offset left edge of source string @@ -2051,8 +2049,9 @@ private static void reverseArray( @Nonnull String... array ) * Compare two strings, and return the portion where they differ. * (More precisely, return the remainder of the second string, * starting from where it's different from the first.) - * - * E.g. strdiff("i am a machine", "i am a robot") -> "robot" + *+ * E.g. strdiff("i am a machine", "i am a robot") → "robot" + *
* * @param s1 The first string. * @param s2 The second string. @@ -2071,7 +2070,7 @@ public static String difference( @Nonnull String s1, @Nonnull String s2 ) /** * Compare two strings, and return the index at which the strings begin to differ. *- * E.g. strdiff("i am a machine", "i am a robot") -> 7 + * E.g. strdiff("i am a machine", "i am a robot") → 7 *
* * @param s1 The first string. @@ -2188,7 +2187,6 @@ public static String interpolate( String text, @Nonnull Map, ?> namespace ) /** * Converts the first character of the given String to lowercase. * This method does not trim spaces! - * * * @param data the String to get it's first character lower-cased. * @return data string with the first character transformed to lowercase @@ -2205,9 +2203,8 @@ public static String interpolate( String text, @Nonnull Map, ?> namespace ) } /** - * Take the input string and un-camel-case it. - * - * 'ThisIsIt' will become 'this-is-it'. + *Take the input string and un-camel-case it.
+ *'ThisIsIt' will become 'this-is-it'.
* * @param view the view * @return deHumped String @@ -2519,7 +2516,6 @@ public static boolean contains( @Nullable String str, @Nullable String searchStr /** *Checks if String ends with a search String, handling
- * *null
.A
* *null
String will returnfalse
.diff --git a/src/main/java/org/apache/maven/shared/utils/cli/Arg.java b/src/main/java/org/apache/maven/shared/utils/cli/Arg.java index 094cbba6..62f14ea6 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/Arg.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/Arg.java @@ -33,6 +33,7 @@ public interface Arg /** * @param line the line of arguments + * @throws CommandLineException in case of unbalanced quotes. */ void setLine( String line ) throws CommandLineException; diff --git a/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java b/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java index f430332a..e03e905c 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java @@ -37,15 +37,14 @@ import org.apache.maven.shared.utils.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">
@@ -55,8 +54,7 @@ * </acommandline>
* </someelement>
** The element
@@ -89,6 +87,7 @@ public Commandline( Shell shell ) * Shell is autodetected from operating system. * * @param toProcess the command to process + * @throws CommandLineException in case of unbalanced quotes. */ public Commandline( String toProcess ) throws CommandLineException { diff --git a/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java b/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java index 0cde961e..d64fba96 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java @@ -22,12 +22,11 @@ import java.io.IOException; /** - * Works in concert with the StreamPumper class to + *someelement
must provide a method *createAcommandline
which returns an instance of this class. *Works in concert with the StreamPumper class to * allow implementations to gain access to the lines being - * "Pumped". - *
- * Please note that implementations of this interface can be expected to be - * called from arbitrary threads and must therefore be threadsafe. + * "Pumped". + *Please note that implementations of this interface can be expected to be + * called from arbitrary threads and must therefore be threadsafe.
* * @author Florin Vancea * @author Paul Julius diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java index 22826802..738f660d 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java @@ -36,9 +36,9 @@ /** * Abstract implementation of a {@link JavaTool}. * - * @author Tony Chemit+ * @author Tony Chemit * @since 0.5 - * @param + * @param Tool-specific request type */ public abstract class AbstractJavaTool extends AbstractLogEnabled diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaToolRequest.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaToolRequest.java index 6e18178a..597041b4 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaToolRequest.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaToolRequest.java @@ -24,7 +24,7 @@ /** * Abstract implementation of a {@link JavaToolRequest}. * - * @author Tony Chemit + * @author Tony Chemit * @since 0.5 */ public class AbstractJavaToolRequest diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaTool.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaTool.java index b4bc3a9a..78b01701 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaTool.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaTool.java @@ -20,26 +20,23 @@ */ /** - * Describes a java tool, means a executable available in the jdk. - * - * The name of the tool ({@link #getJavaToolName()}) reflects the name of the executable that should exists as an - * executable in the jdk, like {@code jarsigner, keytool, javadoc, ...}. - * - * An abstract implementation of the {@link JavaTool} named {@link AbstractJavaTool} use the command line API to execute - * any user requests of this tool. + * Describes a java tool, means a executable available in the jdk.
+ *The name of the tool ({@link #getJavaToolName()}) reflects the name of the executable that should exists as an + * executable in the jdk, like {@code jarsigner, keytool, javadoc, ...}.
+ *An abstract implementation of the {@link JavaTool} named {@link AbstractJavaTool} use the command line API to + * execute any user requests of this tool.
* - * @author Tony Chemit+ * @author Tony Chemit * @since 0.5 - * @param + * @param Tool-specific request type */ public interface JavaTool { /** - * Return the name of the java tool. This is exactly the name (without his extension) of the executable to - * find in the {@code jdk/bin} directory. - * - * For example: {@code jarsigner, keytool, javadoc, ...} + * Return the name of the java tool. This is exactly the name (without his extension) of the executable to + * find in the {@code jdk/bin} directory.
+ *For example: {@code jarsigner, keytool, javadoc, ...}
* * @return the name of the java tool. */ @@ -55,13 +52,11 @@ public interface JavaToolvoid setToolchain( Object toolchain ); /** - * Execute the input request and then returns the result of the execution. - * - * If could not create the java tool invocation, a {@link JavaToolException} will be thrown. - * - * If execution fails, then the result will have a none-zero {@link JavaToolResult#getExitCode()} and his + * Execute the input request and then returns the result of the execution.
+ *If could not create the java tool invocation, a {@link JavaToolException} will be thrown.
+ *If execution fails, then the result will have a none-zero {@link JavaToolResult#getExitCode()} and his * {@link JavaToolResult#getExecutionException()} will be filled with the error, otherwise the exist code will be - * zero. + * zero.
* * @param request the request to perform * @return the result of the tool execution diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolException.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolException.java index fa10b33b..fb9d6946 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolException.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolException.java @@ -20,13 +20,12 @@ */ /** - * Signals an error during the construction of the command line used to invoke java tool, e.g. illegal invocation - * arguments. - * - * This should not be confused with a failure of the invoked java tool build itself which will be reported by means of a - * non-zero exit code. + *Signals an error during the construction of the command line used to invoke java tool, e.g. illegal invocation + * arguments.
+ *This should not be confused with a failure of the invoked java tool build itself which will be reported by means + * of a non-zero exit code.
* - * @author Tony Chemit+ * @author Tony Chemit * * @see JavaToolResult#getExitCode() * @since 0.5 diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolRequest.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolRequest.java index 7227774c..6ad86b14 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolRequest.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolRequest.java @@ -24,27 +24,25 @@ /** * Specifies the minimum parameters used to control a {@link JavaTool} invocation. * - * @author Tony Chemit + * @author Tony Chemit * @since 0.5 */ public interface JavaToolRequest { /** - * Gets the value of the {@code systemOutStreamConsumer} field. - * - * This option field if filled is used by the commandline tool to consume system ouput stream of the jarsigner - * command. + * Gets the value of the {@code systemOutStreamConsumer} field.
+ *This option field if filled is used by the commandline tool to consume system ouput stream of the jarsigner + * command.
* * @return the value of the {@code systemOutStreamConsumer} field. */ StreamConsumer getSystemOutStreamConsumer(); /** - * Gets the value of the {@code systemErrorStreamConsumer} field. - * - * This option field if filled is used by the commandline tool to consume system error stream of the jarsigner - * command. + *Gets the value of the {@code systemErrorStreamConsumer} field.
+ *This option field if filled is used by the commandline tool to consume system error stream of the jarsigner + * command.
* * @return the value of the {@code systemErrorStreamConsumer} field. */ diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolResult.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolResult.java index f3a6a77e..deb830e8 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolResult.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolResult.java @@ -25,7 +25,7 @@ /** * Describes the result of a {@link JavaTool} invocation. * - * @author Tony Chemit+ * @author Tony Chemit * @since 0.5 */ public class JavaToolResult diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java index e3af6651..f04864ea 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java @@ -111,7 +111,6 @@ protected String getExecutionPreamble() /** * Unify quotes in a path for the Bourne Shell.
- * ** BourneShell.quoteOneItem(null) = null * BourneShell.quoteOneItem("") = '' diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java index 04aa6de1..06b7df73 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java @@ -51,7 +51,6 @@ public CmdShell() ** From cmd.exe /? output: *
- * ** If /C or /K is specified, then the remainder of the command line after * the switch is processed as a command line, where the following logic is @@ -74,7 +73,6 @@ public CmdShell() * remove the last quote character on the command line, preserving * any text after the last quote character. *- * ** Always quoting the entire command line, regardless of these conditions * appears to make Windows processes invoke successfully. diff --git a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java index 02681086..47ec0dab 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java @@ -28,7 +28,7 @@ /** * Class that abstracts the Shell functionality, - * with subclasses for shells that behave particularly, like
+ * with subclasses for shells that behave particularly, like * *
*
- diff --git a/src/main/java/org/apache/maven/shared/utils/introspection/ClassMap.java b/src/main/java/org/apache/maven/shared/utils/introspection/ClassMap.java index 19b17322..357eab45 100644 --- a/src/main/java/org/apache/maven/shared/utils/introspection/ClassMap.java +++ b/src/main/java/org/apache/maven/shared/utils/introspection/ClassMap.java @@ -79,16 +79,13 @@ Class> getCachedClass() } /** - * Find a Method using the methodKey - * provided. - * - * Look in the methodMap for an entry. If found, + *
command.com
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. + * 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 parameters. * @return The found method. diff --git a/src/main/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractor.java b/src/main/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractor.java index 963c9829..cf007cc7 100644 --- a/src/main/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractor.java +++ b/src/main/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractor.java @@ -36,7 +36,6 @@ /** *Using simple dotted expressions to extract the values from an Object instance, * For example we might want to extract a value like:
- * *project.build.sourceDirectory
The implementation supports indexed, nested and mapped properties similar to the JSP way.
* * @author Jason van Zyl @@ -146,14 +145,13 @@ private ReflectionValueExtractor() /** *The implementation supports indexed, nested and mapped properties.
- * **
- nested properties should be defined by a dot, i.e. "user.address.street"
*- indexed properties (java.util.List or array instance) should be contains
*(\\w+)\\[(\\d+)\\]
* pattern, i.e. "user.addresses[1].street"- mapped properties should be contains
- *(\\w+)\\((.+)\\)
pattern, * i.e. "user.addresses(myAddress).street"+ *
* * @param expression not null expression * @param root not null object @@ -170,14 +168,13 @@ public static Object evaluate( @Nonnull String expression, @Nullable Object root ** The implementation supports indexed, nested and mapped properties. *
- * **
- nested properties should be defined by a dot, i.e. "user.address.street"
*- indexed properties (java.util.List or array instance) should be contains
*(\\w+)\\[(\\d+)\\]
* pattern, i.e. "user.addresses[1].street"- mapped properties should be contains
- *(\\w+)\\((.+)\\)
pattern, i.e. * "user.addresses(myAddress).street"+ *
* * @param expression not null expression * @param root not null object diff --git a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java index 5d03525e..bd8bd7d9 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java +++ b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java @@ -32,56 +32,62 @@ import javax.annotation.Nullable; /** - * Class for scanning a directory for files/directories which match certain criteria. - * + *Class for scanning a directory for files/directories which match certain criteria.
+ ** These criteria consist of selectors and patterns which have been specified. With the selectors you can select which * files you want to have included. Files which are not selected are excluded. With patterns you can include or exclude * files based on their filename. - *
+ * + ** The idea is simple. A given directory is recursively scanned for all files and directories. Each file/directory is * matched against a set of selectors, including special support for matching against filenames with include and and * exclude patterns. Only files/directories which match at least one pattern of the include pattern list or other file * selector, and don't match any pattern of the exclude pattern list or fail to match against a required selector will * be placed in the list of files/directories found. - *
+ * + ** When no list of include patterns is supplied, "**" will be used, which means that everything will be matched. When no * list of exclude patterns is supplied, an empty list is used, such that nothing will be excluded. When no selectors * are supplied, none are applied. - *
+ * + ** The filename pattern matching is done as follows: The name to be matched is split up in path segments. A path segment * is the name of a directory or file, which is bounded by
+ * + *File.separator
('/' under UNIX, '\' under * Windows). For example, "abc/def/ghi/xyz.java" is split up in the segments "abc", "def","ghi" and "xyz.java". The same * is done for the pattern against which should be matched. - ** The segments of the name and the pattern are then matched against each other. When '**' is used for a path segment in * the pattern, it matches zero or more path segments of the name. - *
+ * + ** There is a special case regarding the use of
+ * + *File.separator
s at the beginning of the pattern and the * string to match:
* When a pattern starts with aFile.separator
, the string to match must also start with a *File.separator
. When a pattern does not start with aFile.separator
, the string to match * may not start with aFile.separator
. When one of these rules is not obeyed, the string will not match. - ** When a name path segment is matched against a pattern path segment, the following special characters can be used:
+ * + *
* '*' matches zero or more characters
* '?' matches one character. - ** Examples: - *
- * "**\*.class" matches all .class files/dirs in a directory tree. - * - * "test\a??.java" matches all files/dirs which start with an 'a', then two more characters and then ".java", in a - * directory called test. - * - * "**" matches everything in a directory tree. - * - * "**\test\**\XYZ*" matches all files/dirs which start with "XYZ" and where there is a parent directory called test - * (e.g. "abc\test\def\ghi\XYZ123"). - * + *+ *
+ *- "**\*.class" matches all .class files/dirs in a directory tree.
+ *- "test\a??.java" matches all files/dirs which start with an 'a', then two more characters and then ".java", in a + * directory called test.
+ *- "**" matches everything in a directory tree.
+ *- "**\test\**\XYZ*" matches all files/dirs which start with "XYZ" and where there is a parent directory called test + * (e.g. "abc\test\def\ghi\XYZ123").
+ ** Case sensitivity may be turned off if necessary. By default, it is turned on. - *
+ * + ** Example of usage: - *
+ * ** String[] includes = { "**\\*.class" }; * String[] excludes = { "modules\\*\\**" }; @@ -98,11 +104,13 @@ * System.out.println( files[i] ); * } *- * + ** This will scan a directory called test for .class files, but excludes all files in all proper subdirectories of a * directory called "modules" - *
+ * + ** This class must not be used from multiple Threads concurrently! + *
* * @author Arnout J. Kuiper ajkuiper@wxs.nl * @author Magesh Umasankar @@ -295,8 +303,9 @@ public void setFollowSymlinks( final boolean followSymlinks ) /** * Sets the list of include patterns to use. All '/' and '\' characters are replaced by *File.separatorChar
, so the separator used need not matchFile.separatorChar
. - * + ** When a pattern ends with a '/' or '\', "**" is appended. + *
* * @param includes A list of include patterns. May benull
, indicating that all files should be * included. If a non-null
list is given, all elements must be non-null
. @@ -326,8 +335,9 @@ public void setIncludes( final String... includes ) /** * Sets the list of exclude patterns to use. All '/' and '\' characters are replaced by *File.separatorChar
, so the separator used need not matchFile.separatorChar
. - * + ** When a pattern ends with a '/' or '\', "**" is appended. + *
* * @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
. @@ -431,13 +441,15 @@ public void scan() * a previously captured list of files. * This method will not look for a changed in content but sole in the * list of files given. - * + ** The method will compare the given array of file Strings with the result * of the last directory scan. It will execute a {@link #scan()} if no * result of a previous scan could be found. - *
+ * + ** The result of the diff can be queried by the methods * {@link DirectoryScanResult#getFilesAdded()} and {@link DirectoryScanResult#getFilesRemoved()} + *
* * @param oldFiles the list of previously captured files names. * @return the result of the directory scan. diff --git a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java index 4612b37f..4d80e180 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java +++ b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java @@ -61,28 +61,28 @@ * *Path-related methods
* - *Methods exist to retrieve the components of a typical file path. For example + * Methods exist to retrieve the components of a typical file path. For example *
/www/hosted/mysite/index.html
, can be broken into: **
- * - * + * *- *
/www/hosted/mysite/index
-- retrievable through {@link #removeExtension}- *
html
-- retrievable through {@link #getExtension}File-related methods
* - * There are methods to create a {@link #toFile File from a URL}, copy a + *There are methods to create a {@link #toFile File from a URL}, 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. - * + * + *Common {@link java.io.File} manipulation routines.
+ ** Taken from the commons-utils repo. * Also code from Alexandria's FileUtils. * And from Avalon Excalibur's IO. * And from Ant. + *
* * @author Kevin A. Burton * @author Scott Sanders @@ -482,8 +482,8 @@ public static void fileDelete( @Nonnull String fileName ) /** * Given a directory and an array of extensions return an array of compliant files. - * - * The given extensions should be like "java" and not like ".java". + * + *The given extensions should be like "java" and not like ".java".
* * @param directory the path of the directory * @param extensions an array of expected extensions @@ -688,9 +688,9 @@ public static boolean contentEquals( @Nonnull final File file1, @Nonnull final F /** * Remove extension from a path. E.g. *- * foo.txt --> foo - * a\b\c.jpg --> a\b\c - * a\b\c --> a\b\c + * foo.txt → foo + * a\b\c.jpg → a\b\c + * a\b\c → a\b\c ** * @param filename the path of the file @@ -715,9 +715,9 @@ public static boolean contentEquals( @Nonnull final File file1, @Nonnull final F * Get extension from a path. E.g. * *- * foo.txt --> "txt" - * a\b\c.jpg --> "jpg" - * a\b\c --> "" + * foo.txt → "txt" + * a\b\c.jpg → "jpg" + * a\b\c → "" ** * @param filename the path of the file @@ -962,13 +962,13 @@ private static void copyStreamToFile( @Nonnull @WillClose final InputStream sour * root. * Eg: *- * /foo// --> /foo/ - * /foo/./ --> /foo/ - * /foo/../bar --> /bar - * /foo/../bar/ --> /bar/ - * /foo/../bar/../baz --> /baz - * //foo//./bar --> /foo/bar - * /../ --> null + * /foo// → /foo/ + * /foo/./ → /foo/ + * /foo/../bar → /bar + * /foo/../bar/ → /bar/ + * /foo/../bar/../baz → /baz + * //foo//./bar → /foo/bar + * /../ → null ** * @param path the path to normalize @@ -1666,8 +1666,7 @@ else if ( !sourceDirectory.isDirectory() ) /** * Copies an entire directory structure. - * - * Note: + *Note:
**
* - *- It will include empty directories. *
- The
sourceDirectory
must exist. @@ -1766,7 +1765,6 @@ else if ( file.isDirectory() ) /** * Renames a file, even if that involves crossing file system boundaries. - * *This will remove
+ *to
(if it exists), ensure that *to
's parent directory exists and move *from
, which involves deletingfrom
as @@ -1804,8 +1802,7 @@ public static void rename( @Nonnull File from, @Nonnull File to ) } /** - * Create a temporary file in a given directory. - *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.
@@ -1859,7 +1856,7 @@ private static int positiveRandom( Random rand ) } /** - * If wrappers is null or empty, the file will be copied only if to.lastModified() < from.lastModified() + * If wrappers is null or empty, the file will be copied only if to.lastModified() < from.lastModified() * * @param from the file to copy * @param to the destination file @@ -1887,7 +1884,7 @@ public abstract static class FilterWrapper } /** - * If wrappers is null or empty, the file will be copy only if to.lastModified() < from.lastModified() or if + * If wrappers is null or empty, the file will be copy only if to.lastModified() < from.lastModified() or if * overwrite is true * * @param from the file to copy @@ -1895,7 +1892,7 @@ public abstract static class FilterWrapper * @param encoding the file output encoding (only if wrappers is not empty) * @param wrappers array of {@link FilterWrapper} * @param overwrite if true and wrappers is null or empty, the file will be copied even if - * to.lastModified() < from.lastModified() + * to.lastModified() < from.lastModified() * @throws IOException if an IO error occurs during copying or filtering */ public static void copyFile( @Nonnull File from, @Nonnull File to, @Nullable String encoding, @@ -2144,8 +2141,8 @@ public static boolean isSymbolicLinkForSure( @Nonnull final File file ) * @param target the target * @return the linked file * @throws IOException in case of an error - * @see {@code java.nio.file.Files.createSymbolicLink(Path)} which creates a new - * symbolic link but does not replace existing symbolic links + * @see Files#createSymbolicLink(Path, Path, FileAttribute[]) which creates a new symbolic link but does + * not replace existing symbolic links */ @Nonnull public static File createSymbolicLink( @Nonnull File symlink, @Nonnull File target ) throws IOException diff --git a/src/main/java/org/apache/maven/shared/utils/io/IOUtil.java b/src/main/java/org/apache/maven/shared/utils/io/IOUtil.java index 11f1bdd4..534a4a02 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/IOUtil.java +++ b/src/main/java/org/apache/maven/shared/utils/io/IOUtil.java @@ -37,12 +37,12 @@ import java.nio.channels.Channel; /** - * General IO Stream manipulation. + *General IO Stream manipulation.
** This class provides static utility methods for input/output operations, particularly buffered * copying between sources (
* *InputStream
,Reader
,String
and *byte[]
) and destinations (OutputStream
,Writer
, - *String
andbyte[]
). + *String
andbyte[]
).Unless otherwise noted, these
copy
methods do not flush or close the * streams. Often, doing so would require making non-portable assumptions about the streams' origin @@ -837,7 +837,7 @@ public static boolean contentEquals( @Nonnull final InputStream input1, @Nonnull // ---------------------------------------------------------------------- /** - * Closes a {@code Channel} suppressing any {@code IOException}. + *Closes a {@code Channel} suppressing any {@code IOException}.
** Note: The use case justifying this method is a shortcoming of the Java language up to but not including * Java 7. For any code targeting Java 7 or later use of this method is highly discouraged and the @@ -847,7 +847,8 @@ public static boolean contentEquals( @Nonnull final InputStream input1, @Nonnull * {@code finally} block incorrectly by using this method. *
*- * Example:
*
+ * Example: + ** // Introduce variables for the resources and initialize them to null. This cannot throw an exception. * Closeable resource1 = null; @@ -921,7 +922,6 @@ public static boolean contentEquals( @Nonnull final InputStream input1, @Nonnull * // } * } *- * * * @param channel The channel to close or {@code null}. * @deprecated use try-with-resources @@ -943,7 +943,7 @@ public static void close( @Nullable Channel channel ) } /** - * Closes an {@code InputStream} suppressing any {@code IOException}. + *Closes an {@code InputStream} suppressing any {@code IOException}.
** Note: The use case justifying this method is a shortcoming of the Java language up to but not including * Java 7. For any code targeting Java 7 or later use of this method is highly discouraged and the @@ -953,7 +953,8 @@ public static void close( @Nullable Channel channel ) * {@code finally} block incorrectly by using this method. *
*- * Example:
*
+ * Example: + ** // Introduce variables for the resources and initialize them to null. This cannot throw an exception. * Closeable resource1 = null; @@ -1027,7 +1028,6 @@ public static void close( @Nullable Channel channel ) * // } * } *- * * * @param inputStream The stream to close or {@code null}. * @deprecated use try-with-resources @@ -1049,7 +1049,7 @@ public static void close( @Nullable InputStream inputStream ) } /** - * Closes an {@code OutputStream} suppressing any {@code IOException}. + *Closes an {@code OutputStream} suppressing any {@code IOException}.
** Note: The use case justifying this method is a shortcoming of the Java language up to but not including * Java 7. For any code targeting Java 7 or later use of this method is highly discouraged and the @@ -1059,7 +1059,8 @@ public static void close( @Nullable InputStream inputStream ) * {@code finally} block incorrectly by using this method. *
*- * Example:
*
+ * Example: + ** // Introduce variables for the resources and initialize them to null. This cannot throw an exception. * Closeable resource1 = null; @@ -1133,7 +1134,6 @@ public static void close( @Nullable InputStream inputStream ) * // } * } *- * * * @param outputStream The stream to close or {@code null}. * @deprecated use try-with-resources @@ -1155,7 +1155,7 @@ public static void close( @Nullable OutputStream outputStream ) } /** - * Closes a {@code Reader} suppressing any {@code IOException}. + *Closes a {@code Reader} suppressing any {@code IOException}.
** Note: The use case justifying this method is a shortcoming of the Java language up to but not including * Java 7. For any code targeting Java 7 or later use of this method is highly discouraged and the @@ -1165,7 +1165,8 @@ public static void close( @Nullable OutputStream outputStream ) * {@code finally} block incorrectly by using this method. *
*- * Example:
*
+ * Example: + ** // Introduce variables for the resources and initialize them to null. This cannot throw an exception. * Closeable resource1 = null; @@ -1239,7 +1240,6 @@ public static void close( @Nullable OutputStream outputStream ) * // } * } *- * * * @param reader The reader to close or {@code null}. * @deprecated use try-with-resources @@ -1261,7 +1261,7 @@ public static void close( @Nullable Reader reader ) } /** - * Closes a {@code Writer} suppressing any {@code IOException}. + *Closes a {@code Writer} suppressing any {@code IOException}.
** Note: The use case justifying this method is a shortcoming of the Java language up to but not including * Java 7. For any code targeting Java 7 or later use of this method is highly discouraged and the @@ -1271,7 +1271,8 @@ public static void close( @Nullable Reader reader ) * {@code finally} block incorrectly by using this method. *
*- * Example:
*
+ * Example: + ** // Introduce variables for the resources and initialize them to null. This cannot throw an exception. * Closeable resource1 = null; @@ -1345,7 +1346,6 @@ public static void close( @Nullable Reader reader ) * // } * } *- * * * @param writer The writer to close or {@code null}. * @deprecated use try-with-resources diff --git a/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java b/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java index 8abff427..bdce10d7 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java +++ b/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java @@ -28,9 +28,9 @@ import javax.annotation.Nonnull; /** - * Describes a match target for SelectorUtils. - * - * Significantly more efficient than using strings, since re-evaluation and re-tokenizing is avoided. + *Describes a match target for SelectorUtils.
+ *+ * Significantly more efficient than using strings, since re-evaluation and re-tokenizing is avoided.
* * @author Kristian Rosenvold * @deprecated use {@code java.nio.filejava.nio.file.DirectoryStream.Filter} and related classes diff --git a/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java b/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java index 693acb1c..638586f2 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java +++ b/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java @@ -40,9 +40,8 @@ private MatchPatterns( @Nonnull MatchPattern... patterns ) } /** - * Checks these MatchPatterns against a specified string. - * - * Uses far less string tokenization than any of the alternatives. + * Checks these MatchPatterns against a specified string.
+ *Uses far less string tokenization than any of the alternatives.
* * @param name The name to look for * @param isCaseSensitive If the comparison is case sensitive diff --git a/src/main/java/org/apache/maven/shared/utils/io/ScanConductor.java b/src/main/java/org/apache/maven/shared/utils/io/ScanConductor.java index 08d7a1cd..0a0d82d7 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/ScanConductor.java +++ b/src/main/java/org/apache/maven/shared/utils/io/ScanConductor.java @@ -23,12 +23,10 @@ /** *Visitor pattern for the DirectoryScanner. A ScanConductor controls the scanning process.
- * *Create an instance and pass it to * {@link org.apache.maven.shared.utils.io.DirectoryScanner#setScanConductor(ScanConductor)}. * You will get notified about every visited directory and file. You can use the {@link ScanAction} * to control what should happen next.
- * *A ScanConductor might also store own information but users must make sure that the state gets * cleaned between two scan() invocations.
* diff --git a/src/main/java/org/apache/maven/shared/utils/io/SelectorUtils.java b/src/main/java/org/apache/maven/shared/utils/io/SelectorUtils.java index b716e7c8..56a43992 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/SelectorUtils.java +++ b/src/main/java/org/apache/maven/shared/utils/io/SelectorUtils.java @@ -73,12 +73,12 @@ private SelectorUtils() } /** - * Tests whether or not a given path matches the start of a given - * pattern up to the first "**". - * + *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,
* * @param pattern The pattern to match against. Must not be *pattern=**\a
- * andstr=b
will yieldtrue
. + * andstr=b
will yieldtrue
.null
. @@ -93,12 +93,11 @@ public static boolean matchPatternStart( String pattern, String str ) } /** - * Tests whether or not a given path matches the start of a given - * pattern up to the first "**". - * - * This is not a general purpose test and should only be used if you + *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,
* * @param pattern The pattern to match against. Must not be *pattern=**\a
- * andstr=b
will yieldtrue
. + * andstr=b
will yieldtrue
.null
. diff --git a/src/main/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilder.java b/src/main/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilder.java index 2d59bc9d..7f442397 100644 --- a/src/main/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilder.java +++ b/src/main/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilder.java @@ -50,24 +50,24 @@ class AnsiMessageBuilder this.ansi = ansi; } - public String debug( String level ) + public String debug( String message ) { - return Style.DEBUG.apply( ansi ).a( level ).reset().toString(); + return Style.DEBUG.apply( ansi ).a( message ).reset().toString(); } - public String info( String level ) + public String info( String message ) { - return Style.INFO.apply( ansi ).a( level ).reset().toString(); + return Style.INFO.apply( ansi ).a( message ).reset().toString(); } - public String warning( String level ) + public String warning( String message ) { - return Style.WARNING.apply( ansi ).a( level ).reset().toString(); + return Style.WARNING.apply( ansi ).a( message ).reset().toString(); } - public String error( String level ) + public String error( String message ) { - return Style.ERROR.apply( ansi ).a( level ).reset().toString(); + return Style.ERROR.apply( ansi ).a( message ).reset().toString(); } public AnsiMessageBuilder success( Object message ) diff --git a/src/main/java/org/apache/maven/shared/utils/logging/LoggerLevelRenderer.java b/src/main/java/org/apache/maven/shared/utils/logging/LoggerLevelRenderer.java index 9dac0eb1..6caa797b 100644 --- a/src/main/java/org/apache/maven/shared/utils/logging/LoggerLevelRenderer.java +++ b/src/main/java/org/apache/maven/shared/utils/logging/LoggerLevelRenderer.java @@ -28,26 +28,30 @@ public interface LoggerLevelRenderer { /** - * Render DEBUG level. - * By default, bold cyan + * Render a message at DEBUG level. + * @param message the message to render. + * @return the formatted message. */ - String debug( String level ); + String debug( String message ); /** - * Render INFO level. - * By default, bold blue + * Render a message at INFO level. + * @param message the message to render. + * @return the formatted message. */ - String info( String level ); + String info( String message ); /** - * Render WARNING level. - * By default, bold yellow + * Render a message at WARNING level. + * @param message the message to render. + * @return the formatted message. */ - String warning( String level ); + String warning( String message ); /** - * Render ERROR level. - * By default, bold red + * Render a message at ERROR level. + * @param message the message to render. + * @return the formatted message. */ - String error( String level ); + String error( String message ); } diff --git a/src/main/java/org/apache/maven/shared/utils/logging/MessageBuilder.java b/src/main/java/org/apache/maven/shared/utils/logging/MessageBuilder.java index 060e824e..649c0860 100644 --- a/src/main/java/org/apache/maven/shared/utils/logging/MessageBuilder.java +++ b/src/main/java/org/apache/maven/shared/utils/logging/MessageBuilder.java @@ -29,36 +29,48 @@ public interface MessageBuilder /** * Append message content in success style. * By default, bold green + * @param message the message to append + * @return the current builder */ MessageBuilder success( Object message ); /** * Append message content in warning style. * By default, bold yellow + * @param message the message to append + * @return the current builder */ MessageBuilder warning( Object message ); /** * Append message content in failure style. * By default, bold red + * @param message the message to append + * @return the current builder */ MessageBuilder failure( Object message ); /** * Append message content in strong style. * By default, bold + * @param message the message to append + * @return the current builder */ MessageBuilder strong( Object message ); /** * Append message content in mojo style. * By default, green + * @param message the message to append + * @return the current builder */ MessageBuilder mojo( Object message ); /** * Append message content in project style. * By default, cyan + * @param message the message to append + * @return the current builder */ MessageBuilder project( Object message ); @@ -67,37 +79,55 @@ public interface MessageBuilder // /** * Append content to the message buffer. + * @param value the content to append + * @param offset the index of the first {@code char} to append + * @param len the number of {@code char}s to append + * @return the current builder */ MessageBuilder a( char[] value, int offset, int len ); /** * Append content to the message buffer. + * @param value the content to append + * @return the current builder */ MessageBuilder a( char[] value ); /** * Append content to the message buffer. + * @param value the content to append + * @param start the starting index of the subsequence to be appended + * @param end the end index of the subsequence to be appended + * @return the current builder */ MessageBuilder a( CharSequence value, int start, int end ); /** * Append content to the message buffer. + * @param value the content to append + * @return the current builder */ MessageBuilder a( CharSequence value ); /** * Append content to the message buffer. + * @param value the content to append + * @return the current builder */ MessageBuilder a( Object value ); /** * Append newline to the message buffer. + * @return the current builder */ MessageBuilder newline(); /** * Append formatted content to the buffer. * @see String#format(String, Object...) + * @param pattern a format string + * @param args arguments referenced by the format specifiers in the format string. + * @return the current builder */ MessageBuilder format( String pattern, Object... args ); } diff --git a/src/main/java/org/apache/maven/shared/utils/logging/MessageUtils.java b/src/main/java/org/apache/maven/shared/utils/logging/MessageUtils.java index 090b6a00..f28058b7 100644 --- a/src/main/java/org/apache/maven/shared/utils/logging/MessageUtils.java +++ b/src/main/java/org/apache/maven/shared/utils/logging/MessageUtils.java @@ -46,7 +46,7 @@ public class MessageUtils boolean jansi = true; try { - // JAnsi is provided by Maven core since 3.5.0 + // Jansi is provided by Maven core since 3.5.0 Class.forName( "org.fusesource.jansi.Ansi" ); } catch ( ClassNotFoundException cnfe ) @@ -79,7 +79,7 @@ public static void systemUninstall() { doSystemUninstall(); - // hook can only set when JANSI is true + // hook can only set when Jansi is true if ( shutdownHook != null ) { try @@ -103,8 +103,8 @@ private static void doSystemUninstall() } /** - * Enables message color (if JAnsi is available). - * @param flag + * Enables message color (if Jansi is available). + * @param flag to enable Jansi */ public static void setColorEnabled( boolean flag ) { @@ -127,7 +127,8 @@ public static void setColorEnabled( boolean flag ) } /** - * Is message color enabled: requires JAnsi available (through Maven) and the color has not been disabled. + * Is message color enabled: requires Jansi available (through Maven) and the color has not been disabled. + * @return whether colored messages are enabled */ public static boolean isColorEnabled() { @@ -145,6 +146,7 @@ public static MessageBuilder buffer() /** * Create a message buffer with defined String builder. + * @param builder initial content of the message buffer * @return a new buffer */ public static MessageBuilder buffer( StringBuilder builder ) @@ -154,6 +156,7 @@ public static MessageBuilder buffer( StringBuilder builder ) /** * Create a message buffer with an internal buffer of defined size. + * @param size size of the buffer * @return a new buffer */ public static MessageBuilder buffer( int size ) diff --git a/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java b/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java index 6a7b56e1..5ff48844 100644 --- a/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java +++ b/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java @@ -42,24 +42,24 @@ class PlainMessageBuilder buffer = new StringBuilder( size ); } - public String debug( String level ) + public String debug( String message ) { - return a( level ).toString(); + return a( message ).toString(); } - public String info( String level ) + public String info( String message ) { - return a( level ).toString(); + return a( message ).toString(); } - public String warning( String level ) + public String warning( String message ) { - return a( level ).toString(); + return a( message ).toString(); } - public String error( String level ) + public String error( String message ) { - return a( level ).toString(); + return a( message ).toString(); } public PlainMessageBuilder success( Object message ) diff --git a/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java b/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java index f1bc0c6f..5ee48a01 100644 --- a/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java +++ b/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java @@ -23,12 +23,11 @@ import java.io.InputStream; /** - * The XmlReaderException is thrown by the XmlReader constructors if the charset encoding can not be determined - * according to the XML 1.0 specification and RFC 3023. - * - * The exception returns the unconsumed InputStream to allow the application to do an alternate processing with the - * stream. Note that the original InputStream given to the XmlReader cannot be used as that one has been already read. - * + *The XmlReaderException is thrown by the XmlReader constructors if the charset encoding can not be determined + * according to the XML 1.0 specification and RFC 3023.
+ *The exception returns the unconsumed InputStream to allow the application to do an alternate processing with the + * stream. Note that the original InputStream given to the XmlReader cannot be used as that one has been already + * read.
* * @author Alejandro Abdelnur * @version revision 1.1 taken on 26/06/2007 from Rome (see https://rome.dev.java.net/source/browse/rome/src/java/com/sun/syndication/io/XmlReaderException.java) @@ -54,10 +53,8 @@ class XmlReaderException private final InputStream is; /** - * Creates an exception instance if the charset encoding could not be determined. - * - * Instances of this exception are thrown by the XmlReader. - * + *Creates an exception instance if the charset encoding could not be determined.
+ *Instances of this exception are thrown by the XmlReader.
* * @param msg message describing the reason for the exception. * @param bomEnc BOM encoding. @@ -71,10 +68,8 @@ class XmlReaderException } /** - * Creates an exception instance if the charset encoding could not be determined. - * - * Instances of this exception are thrown by the XmlReader. - * + *Creates an exception instance if the charset encoding could not be determined.
+ *Instances of this exception are thrown by the XmlReader.
* * @param msg message describing the reason for the exception. * @param ctMime MIME type in the content-type. @@ -98,7 +93,6 @@ class XmlReaderException /** * Returns the BOM encoding found in the InputStream. - * * * @return the BOM encoding, null if none. */ @@ -109,7 +103,6 @@ public String getBomEncoding() /** * Returns the encoding guess based on the first bytes of the InputStream. - * * * @return the encoding guess, null if it couldn't be guessed. */ @@ -120,7 +113,6 @@ public String getXmlGuessEncoding() /** * Returns the encoding found in the XML prolog of the InputStream. - * * * @return the encoding of the XML prolog, null if none. */ @@ -131,7 +123,6 @@ public String getXmlEncoding() /** * Returns the MIME type in the content-type used to attempt determining the encoding. - * * * @return the MIME type in the content-type, null if there was not content-type or the encoding detection did not * involve HTTP. @@ -143,7 +134,6 @@ public String getContentTypeMime() /** * Returns the encoding in the content-type used to attempt determining the encoding. - * * * @return the encoding in the content-type, null if there was not content-type, no encoding in it or the encoding * detection did not involve HTTP. @@ -156,7 +146,6 @@ public String getContentTypeEncoding() /** * Returns the unconsumed InputStream to allow the application to do an alternate encoding detection on the * InputStream. - * * * @return the unconsumed InputStream. */ diff --git a/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java b/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java index eeabae53..992b833c 100644 --- a/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java +++ b/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java @@ -22,13 +22,11 @@ import java.io.InputStream; /** - * The XmlStreamReaderException is thrown by the XmlStreamReader constructors if the charset encoding can not be - * determined according to the XML 1.0 specification and RFC 3023. - * - * The exception returns the unconsumed InputStream to allow the application to do an alternate processing with the + *The XmlStreamReaderException is thrown by the XmlStreamReader constructors if the charset encoding can not be + * determined according to the XML 1.0 specification and RFC 3023.
+ *The exception returns the unconsumed InputStream to allow the application to do an alternate processing with the * stream. Note that the original InputStream given to the XmlStreamReader cannot be used as that one has been already - * read. - *
+ * read. * * @author Alejandro Abdelnur * @version revision 1.1 taken on 26/06/2007 from Rome (see diff --git a/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java b/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java index d0611119..fdf81302 100644 --- a/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java +++ b/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java @@ -34,7 +34,7 @@ */ public class PrettyPrintXmlWriterTest { - private StringWriter w = new StringWriter();; + private StringWriter w = new StringWriter(); private PrettyPrintXMLWriter writer = new PrettyPrintXMLWriter( w ); @Test From 17091d82508deb9b7067f3434ba16f660ffc5023 Mon Sep 17 00:00:00 2001 From: Maarten MuldersDate: Mon, 26 Apr 2021 15:54:15 +0200 Subject: [PATCH 208/265] [maven-release-plugin] prepare release maven-shared-utils-3.3.4 --- pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 7516b15e..8faf21da 100644 --- a/pom.xml +++ b/pom.xml @@ -27,7 +27,7 @@ maven-shared-utils -3.3.4-SNAPSHOT +3.3.4 Apache Maven Shared Utils Shared utilities for use by Maven core and plugins @@ -36,7 +36,7 @@scm:git:https://gitbox.apache.org/repos/asf/maven-shared-utils.git scm:git:https://gitbox.apache.org/repos/asf/maven-shared-utils.git https://github.com/apache/maven-shared-utils/tree/${project.scm.tag} -HEAD +maven-shared-utils-3.3.4 jira @@ -61,7 +61,7 @@From f45fc4edf74b02b05851d5f9ad7d92d6dede90b5 Mon Sep 17 00:00:00 2001 From: Maarten Mulders RedundantThrows,NewlineAtEndOfFile,ParameterNumber,MethodLength,FileLength,ModifierOrder -2020-04-04T09:03:59Z +2021-04-26T13:53:43Z 7 3.1.0 Date: Mon, 26 Apr 2021 15:54:26 +0200 Subject: [PATCH 209/265] [maven-release-plugin] prepare for next development iteration --- pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 8faf21da..ff9236c4 100644 --- a/pom.xml +++ b/pom.xml @@ -27,7 +27,7 @@ maven-shared-utils -3.3.4 +3.3.5-SNAPSHOT Apache Maven Shared Utils Shared utilities for use by Maven core and plugins @@ -36,7 +36,7 @@scm:git:https://gitbox.apache.org/repos/asf/maven-shared-utils.git scm:git:https://gitbox.apache.org/repos/asf/maven-shared-utils.git https://github.com/apache/maven-shared-utils/tree/${project.scm.tag} -maven-shared-utils-3.3.4 +HEAD jira @@ -61,7 +61,7 @@From 7d30e7c02824b9f8f30976e58e617950b050ee7f Mon Sep 17 00:00:00 2001 From: Elliotte Rusty Harold RedundantThrows,NewlineAtEndOfFile,ParameterNumber,MethodLength,FileLength,ModifierOrder -2021-04-26T13:53:43Z +2021-04-26T13:54:25Z 7 3.1.0 Date: Mon, 26 Apr 2021 21:01:29 +0000 Subject: [PATCH 210/265] avoid reusing fixtures (#86) * avoid reusing fixtures --- .../shared/utils/xml/XmlWriterUtilTest.java | 107 ++++++++---------- 1 file changed, 48 insertions(+), 59 deletions(-) diff --git a/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java b/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java index a22cece1..9a050da3 100644 --- a/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java +++ b/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java @@ -20,6 +20,7 @@ */ import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import org.apache.maven.shared.utils.StringUtils; @@ -51,17 +52,6 @@ protected void setUp() xmlWriter = new PrettyPrintXMLWriter( writer ); } - /** {@inheritDoc} */ - protected void tearDown() - throws Exception - { - super.tearDown(); - - xmlWriter = null; - writer = null; - output = null; - } - /** * Test method for {@link org.apache.maven.shared.utils.xml.XmlWriterUtil#writeLineBreak(XMLWriter)}. * @@ -72,8 +62,7 @@ public void testWriteLineBreakXMLWriter() { XmlWriterUtil.writeLineBreak( xmlWriter ); writer.close(); - System.out.println( "output = " + output.toString() + "x"); - assertTrue( StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) == 1 ); + assertEquals( 1, StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) ); } /** @@ -86,7 +75,7 @@ public void testWriteLineBreakXMLWriterInt() { XmlWriterUtil.writeLineBreak( xmlWriter, 10 ); writer.close(); - assertTrue( StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) == 10 ); + assertEquals( 10, StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) ); } /** @@ -99,9 +88,9 @@ public void testWriteLineBreakXMLWriterIntInt() { XmlWriterUtil.writeLineBreak( xmlWriter, 10, 2 ); writer.close(); - assertTrue( StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) == 10 ); - assertTrue( StringUtils.countMatches( output.toString(), StringUtils - .repeat( " ", 2 * XmlWriterUtil.DEFAULT_INDENTATION_SIZE ) ) == 1 ); + assertEquals( 10, StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) ); + assertEquals( 1, StringUtils.countMatches( output.toString(), StringUtils + .repeat( " ", 2 * XmlWriterUtil.DEFAULT_INDENTATION_SIZE ) ) ); } /** @@ -114,8 +103,8 @@ public void testWriteLineBreakXMLWriterIntIntInt() { XmlWriterUtil.writeLineBreak( xmlWriter, 10, 2, 4 ); writer.close(); - assertTrue( StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) == 10 ); - assertTrue( StringUtils.countMatches( output.toString(), StringUtils.repeat( " ", 2 * 4 ) ) == 1 ); + assertEquals( 10, StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) ); + assertEquals( 1, StringUtils.countMatches( output.toString(), StringUtils.repeat( " ", 2 * 4 ) ) ); } /** @@ -131,7 +120,7 @@ public void testWriteCommentLineBreakXMLWriter() StringBuilder sb = new StringBuilder(); sb.append( "" ).append( XmlWriterUtil.LS ); assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ); + assertEquals( output.toString().length(), XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ); } /** @@ -145,10 +134,9 @@ public void testWriteCommentLineBreakXMLWriterInt() XmlWriterUtil.writeCommentLineBreak( xmlWriter, 20 ); writer.close(); assertEquals( output.toString(), "" + XmlWriterUtil.LS ); + } - tearDown(); - setUp(); - + public void testWriteCommentLineBreak() throws IOException { XmlWriterUtil.writeCommentLineBreak( xmlWriter, 10 ); writer.close(); assertEquals( output.toString(), output.toString(), "" + XmlWriterUtil.LS ); @@ -167,30 +155,29 @@ public void testWriteCommentXMLWriterString() StringBuffer sb = new StringBuffer(); sb.append( "" ).append( XmlWriterUtil.LS ); assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ); - - tearDown(); - setUp(); + assertEquals( output.toString().length(), XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ); + } + + public void testWriteComment() throws IOException { XmlWriterUtil.writeComment( xmlWriter, "hellooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" ); writer.close(); - sb = new StringBuffer(); + StringBuffer sb = new StringBuffer(); sb.append( "" ) .append( XmlWriterUtil.LS ); assertEquals( output.toString(), sb.toString() ); assertTrue( output.toString().length() >= XmlWriterUtil.DEFAULT_COLUMN_LINE ); - - tearDown(); - setUp(); - + } + + public void testWriteComment_2() throws IOException { XmlWriterUtil.writeComment( xmlWriter, "hello\nworld" ); writer.close(); - sb = new StringBuffer(); + StringBuffer sb = new StringBuffer(); sb.append( "" ).append( XmlWriterUtil.LS ); sb.append( "" ).append( XmlWriterUtil.LS ); assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 2 * ( XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ) ); + assertEquals( output.toString().length(), 2 * ( XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ) ); } /** @@ -209,21 +196,22 @@ public void testWriteCommentXMLWriterStringInt() sb.append( indent ); sb.append( "" ).append( XmlWriterUtil.LS ); assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() + 2 + assertEquals( output.toString().length(), XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() + 2 * XmlWriterUtil.DEFAULT_INDENTATION_SIZE ); - tearDown(); - setUp(); - + } + + public void testWriteComment_3() throws IOException { + String indent = StringUtils.repeat( " ", 2 * XmlWriterUtil.DEFAULT_INDENTATION_SIZE ); XmlWriterUtil.writeComment( xmlWriter, "hello\nworld", 2 ); writer.close(); - sb = new StringBuffer(); + StringBuffer sb = new StringBuffer(); sb.append( indent ); sb.append( "" ).append( XmlWriterUtil.LS ); sb.append( indent ); sb.append( "" ).append( XmlWriterUtil.LS ); assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 2 * ( XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ) + 2 * indent.length() ); + assertEquals( output.toString().length(), 2 * ( XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ) + 2 * indent.length() ); } /** @@ -242,14 +230,15 @@ public void testWriteCommentXMLWriterStringIntInt() sb.append( repeat ); sb.append( "" ).append( XmlWriterUtil.LS ); assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() + 2 * 4 ); - - tearDown(); - setUp(); - + assertEquals( output.toString().length(), XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() + 2 * 4 ); + } + + + public void testWriteCommentXMLWriterStringIntInt_2() throws IOException { + String repeat = StringUtils.repeat( " ", 2 * 4 ); XmlWriterUtil.writeComment( xmlWriter, "hello\nworld", 2, 4 ); writer.close(); - sb = new StringBuffer(); + StringBuffer sb = new StringBuffer(); sb.append( repeat ); sb.append( "" ).append( XmlWriterUtil.LS ); sb.append( repeat ); @@ -275,13 +264,14 @@ public void testWriteCommentXMLWriterStringIntIntInt() sb.append( "" ).append( XmlWriterUtil.LS ); assertEquals( output.toString(), sb.toString() ); assertTrue( output.toString().length() == 50 - 1 + XmlWriterUtil.LS.length() + 2 * 4 ); - - tearDown(); - setUp(); - + } + + public void testWriteCommentXMLWriterStringIntIntInt_2() throws IOException + { + String indent = StringUtils.repeat( " ", 2 * 4 ); XmlWriterUtil.writeComment( xmlWriter, "hello", 2, 4, 10 ); writer.close(); - sb = new StringBuffer(); + StringBuffer sb = new StringBuffer(); sb.append( indent ); sb.append( "" ).append( XmlWriterUtil.LS ); assertEquals( output.toString(), sb.toString() ); @@ -305,17 +295,16 @@ public void testWriteCommentTextXMLWriterStringInt() sb.append( "" ).append( XmlWriterUtil.LS ); sb.append( XmlWriterUtil.LS ); assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 3 * ( 80 - 1 + XmlWriterUtil.LS.length() ) + 2 * XmlWriterUtil.LS.length() ); - - tearDown(); - setUp(); - + assertEquals( output.toString().length(), 3 * ( 80 - 1 + XmlWriterUtil.LS.length() ) + 2 * XmlWriterUtil.LS.length() ); + } + + public void testWriteCommentTextXMLWriterStringInt_2() throws IOException { String indent = StringUtils.repeat( " ", 2 * 2 ); XmlWriterUtil.writeCommentText( xmlWriter, "hello world with end of line\n and " + "loooooooooooooooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnong line", 2 ); writer.close(); - sb = new StringBuffer(); + StringBuffer sb = new StringBuffer(); sb.append( XmlWriterUtil.LS ); sb.append( indent ).append( "" ) .append( XmlWriterUtil.LS ); @@ -358,7 +347,7 @@ public void testWriteCommentTextXMLWriterStringIntInt() sb.append( XmlWriterUtil.LS ); sb.append( indent ); assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 3 * ( 80 - 1 + XmlWriterUtil.LS.length() ) + 4 * 2 * 4 + 2 * XmlWriterUtil.LS.length() ); + assertEquals( output.toString().length(), 3 * ( 80 - 1 + XmlWriterUtil.LS.length() ) + 4 * 2 * 4 + 2 * XmlWriterUtil.LS.length() ); } /** @@ -381,7 +370,7 @@ public void testWriteCommentTextXMLWriterStringIntIntInt() sb.append( XmlWriterUtil.LS ); sb.append( indent ); assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 3 * ( 50 - 1 + XmlWriterUtil.LS.length() ) + 4 * 2 * 4 + 2 * XmlWriterUtil.LS.length() ); + assertEquals( output.toString().length(), 3 * ( 50 - 1 + XmlWriterUtil.LS.length() ) + 4 * 2 * 4 + 2 * XmlWriterUtil.LS.length() ); } /** From 1285a156a173be446213dc39d5e196ee7b7d4ed2 Mon Sep 17 00:00:00 2001 From: Tamas Cservenak Date: Fri, 30 Apr 2021 12:45:25 +0200 Subject: [PATCH 211/265] Add GH actions As they provide nice (and quick) feedback about issues and problems with the build. --- .github/workflows/maven.yml | 49 +++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 .github/workflows/maven.yml diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 00000000..eb39c5d8 --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,49 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +name: Java CI + +on: [push, pull_request] + +jobs: + build: + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macOS-latest] + fail-fast: false + + runs-on: ${{ matrix.os }} + + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Set up cache for ~/.m2/repository + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: maven-${{ matrix.os }}-${{ hashFiles('**/pom.xml') }} + restore-keys: | + maven-${{ matrix.os }}- + + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + + - name: Build with Maven + run: mvn clean verify -e -B -V From 1e6748cc36464c6899c43d6acaea8156d0956391 Mon Sep 17 00:00:00 2001 From: Tamas Cservenak Date: Sat, 1 May 2021 20:56:24 +0200 Subject: [PATCH 212/265] [MSHARED-983] Drop plexus container default (#87) * Drop plexus container default The complete container was only here to make use of AbstractLogEnabled ancient class, that uses ancient logging. Drop it. * Up major version As this change is not API compatible --- pom.xml | 26 ++++++++++--------- .../utils/cli/javatool/AbstractJavaTool.java | 10 +++++-- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/pom.xml b/pom.xml index ff9236c4..daf55b01 100644 --- a/pom.xml +++ b/pom.xml @@ -27,7 +27,7 @@ maven-shared-utils -3.3.5-SNAPSHOT +4.0.0-SNAPSHOT Apache Maven Shared Utils Shared utilities for use by Maven core and plugins @@ -67,12 +67,25 @@+ + +org.slf4j +slf4j-api +1.7.25 ++ + org.fusesource.jansi jansi 2.2.0 true + +commons-io +commons-io +2.6 +- junit junit @@ -85,11 +98,6 @@2.2 test - commons-io -commons-io -2.6 -- org.apache.commons commons-text @@ -111,12 +119,6 @@${mavenVersion} test - org.codehaus.plexus -plexus-container-default -2.1.0 -provided -org.codehaus.plexus plexus-utils diff --git a/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java b/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java index 738f660d..971b9626 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java @@ -25,7 +25,8 @@ import org.apache.maven.shared.utils.cli.CommandLineUtils; import org.apache.maven.shared.utils.cli.Commandline; import org.apache.maven.shared.utils.cli.StreamConsumer; -import org.codehaus.plexus.logging.AbstractLogEnabled; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; import java.io.InputStream; @@ -41,9 +42,9 @@ * @paramTool-specific request type */ public abstract class AbstractJavaTool - extends AbstractLogEnabled implements JavaTool { + private final Logger logger = LoggerFactory.getLogger( getClass() ); /** * The java tool name to find out in the jdk. @@ -79,6 +80,11 @@ protected AbstractJavaTool( String javaToolName ) protected abstract Commandline createCommandLine( Request request, String javaToolFileLocation ) throws JavaToolException; + protected Logger getLogger() + { + return logger; + } + /** * {@inheritDoc} */ From ff58583c0c4ffc34de52567f78bca99d65e14d24 Mon Sep 17 00:00:00 2001 From: Elliotte Rusty Harold Date: Sun, 2 May 2021 16:07:12 +0000 Subject: [PATCH 213/265] remove two unused non-public exception classes (#89) --- .../shared/utils/xml/XmlReaderException.java | 156 ------------------ .../shared/utils/xml/XmlStreamReader.java | 9 +- .../utils/xml/XmlStreamReaderException.java | 79 --------- 3 files changed, 3 insertions(+), 241 deletions(-) delete mode 100644 src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java delete mode 100644 src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java diff --git a/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java b/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java deleted file mode 100644 index 5ee48a01..00000000 --- a/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java +++ /dev/null @@ -1,156 +0,0 @@ -package org.apache.maven.shared.utils.xml; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.IOException; -import java.io.InputStream; - -/** - * The XmlReaderException is thrown by the XmlReader constructors if the charset encoding can not be determined - * according to the XML 1.0 specification and RFC 3023.
- *The exception returns the unconsumed InputStream to allow the application to do an alternate processing with the - * stream. Note that the original InputStream given to the XmlReader cannot be used as that one has been already - * read.
- * - * @author Alejandro Abdelnur - * @version revision 1.1 taken on 26/06/2007 from Rome (see https://rome.dev.java.net/source/browse/rome/src/java/com/sun/syndication/io/XmlReaderException.java) - */ -class XmlReaderException - extends IOException -{ - /** - * - */ - private static final long serialVersionUID = 5044326391409597950L; - - private final String bomEncoding; - - private final String xmlGuessEncoding; - - private final String xmlEncoding; - - private final String contentTypeMime; - - private final String contentTypeEncoding; - - private final InputStream is; - - /** - *Creates an exception instance if the charset encoding could not be determined.
- *Instances of this exception are thrown by the XmlReader.
- * - * @param msg message describing the reason for the exception. - * @param bomEnc BOM encoding. - * @param xmlGuessEnc XML guess encoding. - * @param xmlEnc XML prolog encoding. - * @param is the unconsumed InputStream. - */ - XmlReaderException( String msg, String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is ) - { - this( msg, null, null, bomEnc, xmlGuessEnc, xmlEnc, is ); - } - - /** - *Creates an exception instance if the charset encoding could not be determined.
- *Instances of this exception are thrown by the XmlReader.
- * - * @param msg message describing the reason for the exception. - * @param ctMime MIME type in the content-type. - * @param ctEnc encoding in the content-type. - * @param bomEnc BOM encoding. - * @param xmlGuessEnc XML guess encoding. - * @param xmlEnc XML prolog encoding. - * @param is the unconsumed InputStream. - */ - XmlReaderException( String msg, String ctMime, String ctEnc, String bomEnc, String xmlGuessEnc, - String xmlEnc, InputStream is ) - { - super( msg ); - contentTypeMime = ctMime; - contentTypeEncoding = ctEnc; - bomEncoding = bomEnc; - xmlGuessEncoding = xmlGuessEnc; - xmlEncoding = xmlEnc; - this.is = is; - } - - /** - * Returns the BOM encoding found in the InputStream. - * - * @return the BOM encoding, null if none. - */ - public String getBomEncoding() - { - return bomEncoding; - } - - /** - * Returns the encoding guess based on the first bytes of the InputStream. - * - * @return the encoding guess, null if it couldn't be guessed. - */ - public String getXmlGuessEncoding() - { - return xmlGuessEncoding; - } - - /** - * Returns the encoding found in the XML prolog of the InputStream. - * - * @return the encoding of the XML prolog, null if none. - */ - public String getXmlEncoding() - { - return xmlEncoding; - } - - /** - * Returns the MIME type in the content-type used to attempt determining the encoding. - * - * @return the MIME type in the content-type, null if there was not content-type or the encoding detection did not - * involve HTTP. - */ - public String getContentTypeMime() - { - return contentTypeMime; - } - - /** - * Returns the encoding in the content-type used to attempt determining the encoding. - * - * @return the encoding in the content-type, null if there was not content-type, no encoding in it or the encoding - * detection did not involve HTTP. - */ - public String getContentTypeEncoding() - { - return contentTypeEncoding; - } - - /** - * Returns the unconsumed InputStream to allow the application to do an alternate encoding detection on the - * InputStream. - * - * @return the unconsumed InputStream. - */ - public InputStream getInputStream() - { - return is; - } -} diff --git a/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReader.java b/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReader.java index 6990d4f3..da58a0ba 100644 --- a/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReader.java +++ b/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReader.java @@ -79,10 +79,9 @@ public XmlStreamReader( InputStream is ) * @param is {@link InputStream} * @param lenient yes/no * @throws IOException in case of an error - * @throws XmlStreamReaderException in case of an error */ public XmlStreamReader( InputStream is, boolean lenient ) - throws IOException, XmlStreamReaderException + throws IOException { reader = new org.apache.commons.io.input.XmlStreamReader( is, lenient, staticDefaultEncoding ); } @@ -124,10 +123,9 @@ public XmlStreamReader( InputStream is, String httpContentType ) * @param lenient yes/no * @param defaultEncoding the default encoding * @throws IOException in case of error - * @throws XmlStreamReaderException in case of error */ public XmlStreamReader( InputStream is, String httpContentType, boolean lenient, String defaultEncoding ) - throws IOException, XmlStreamReaderException + throws IOException { reader = new org.apache.commons.io.input.XmlStreamReader( is, httpContentType, lenient, ( defaultEncoding == null ) @@ -140,10 +138,9 @@ public XmlStreamReader( InputStream is, String httpContentType, boolean lenient, * @param httpContentType content type * @param lenient yes/no * @throws IOException in case of error - * @throws XmlStreamReaderException in case of error */ public XmlStreamReader( InputStream is, String httpContentType, boolean lenient ) - throws IOException, XmlStreamReaderException + throws IOException { this( is, httpContentType, lenient, null ); } diff --git a/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java b/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java deleted file mode 100644 index 992b833c..00000000 --- a/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.apache.maven.shared.utils.xml; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.InputStream; - -/** - *The XmlStreamReaderException is thrown by the XmlStreamReader constructors if the charset encoding can not be - * determined according to the XML 1.0 specification and RFC 3023.
- *The exception returns the unconsumed InputStream to allow the application to do an alternate processing with the - * stream. Note that the original InputStream given to the XmlStreamReader cannot be used as that one has been already - * read.
- * - * @author Alejandro Abdelnur - * @version revision 1.1 taken on 26/06/2007 from Rome (see - * https://rome.dev.java.net/source/browse/rome/src/java/com/sun/syndication/io/XmlReaderException.java) - */ -class XmlStreamReaderException - extends XmlReaderException -{ - /** - * - */ - private static final long serialVersionUID = 1007947701939672080L; - - /** - * Creates an exception instance if the charset encoding could not be determined. - * - * Instances of this exception are thrown by the XmlReader. - * - * - * @param msg message describing the reason for the exception. - * @param bomEnc BOM encoding. - * @param xmlGuessEnc XML guess encoding. - * @param xmlEnc XML prolog encoding. - * @param is the unconsumed InputStream. - */ - XmlStreamReaderException( String msg, String bomEnc, String xmlGuessEnc, String xmlEnc, InputStream is ) - { - super( msg, bomEnc, xmlGuessEnc, xmlEnc, is ); - } - - /** - * Creates an exception instance if the charset encoding could not be determined. - * - * Instances of this exception are thrown by the XmlReader. - * - * - * @param msg message describing the reason for the exception. - * @param ctMime MIME type in the content-type. - * @param ctEnc encoding in the content-type. - * @param bomEnc BOM encoding. - * @param xmlGuessEnc XML guess encoding. - * @param xmlEnc XML prolog encoding. - * @param is the unconsumed InputStream. - */ - XmlStreamReaderException( String msg, String ctMime, String ctEnc, String bomEnc, String xmlGuessEnc, - String xmlEnc, InputStream is ) - { - super( msg, ctMime, ctEnc, bomEnc, xmlGuessEnc, xmlEnc, is ); - } -} From 5b1706211be0be129952aa65d6655a93212c970b Mon Sep 17 00:00:00 2001 From: Elliotte Rusty HaroldDate: Sun, 2 May 2021 12:23:55 -0400 Subject: [PATCH 214/265] cleanup large chunks of unused YAGNI code and support accurate exception handling --- .../maven/shared/utils/xml/XMLEncode.java | 350 ++++-------------- 1 file changed, 80 insertions(+), 270 deletions(-) diff --git a/src/main/java/org/apache/maven/shared/utils/xml/XMLEncode.java b/src/main/java/org/apache/maven/shared/utils/xml/XMLEncode.java index 0d6ecd16..5c2d10f7 100644 --- a/src/main/java/org/apache/maven/shared/utils/xml/XMLEncode.java +++ b/src/main/java/org/apache/maven/shared/utils/xml/XMLEncode.java @@ -20,7 +20,6 @@ */ import java.io.IOException; -import java.io.StringWriter; import java.io.Writer; /** @@ -35,210 +34,114 @@ final class XMLEncode private static final char DEFAULT_QUOTE_CHAR = '"'; - /** - * Checks if this text purely consists of the white space characters - * ' ', TAB, NEWLINE. - */ - public static boolean isWhiteSpace( String text ) - { - for ( int i = 0; i < text.length(); i++ ) - { - char c = text.charAt( i ); - if ( !Character.isWhitespace( c ) ) - { - return false; - } - } - return true; - } - - /** - * Makes any text fit into XML attributes. - */ - public static String xmlEncodeTextForAttribute( String text, char quoteChar ) - { - if ( text == null ) - { - return null; - } - return xmlEncodeTextAsPCDATA( text, true, quoteChar ); - } - - /** - * Encodes text as XML in the most suitable way, either CDATA block or PCDATA. - */ - public static String xmlEncodeText( String text ) + static void xmlEncodeText( String text, Writer writer ) throws IOException { if ( text == null ) { - return null; + return; } - StringWriter writer = new StringWriter( text.length() * 2 ); - xmlEncodeText( text, writer ); - return writer.toString(); - } - public static void xmlEncodeText( String text, Writer writer ) - { - if ( text == null ) + if ( !needsEncoding( text ) ) { + writer.write( text ); return; } - try + else { - if ( !needsEncoding( text ) ) - { - writer.write( text ); - return; - } - else + // only encode as cdata if is is longer than CDATA block overhead: + if ( text.length() > CDATA_BLOCK_THRESHOLD_LENGTH ) { - // only encode as cdata if is is longer than CDATA block overhead: - if ( text.length() > CDATA_BLOCK_THRESHOLD_LENGTH ) + String cdata = xmlEncodeTextAsCDATABlock( text ); + if ( cdata != null ) { - String cdata = xmlEncodeTextAsCDATABlock( text ); - if ( cdata != null ) - { - writer.write( cdata ); - return; - } + writer.write( cdata ); + return; } } } - catch ( IOException e ) - { - throw new RuntimeException( e ); - } + // if every thing else fails, do it the save way... xmlEncodeTextAsPCDATA( text, false, DEFAULT_QUOTE_CHAR, writer ); } - /** - * Encodes any text as PCDATA. - */ - public static String xmlEncodeTextAsPCDATA( String text ) + static void xmlEncodeTextAsPCDATA( String text, boolean forAttribute, char quoteChar, Writer n ) throws IOException { if ( text == null ) { - return null; + return; } - return xmlEncodeTextAsPCDATA( text, false ); - } - - /** - * Encodes any text as PCDATA. - * - * @param forAttribute if you want - * quotes and apostrophes specially treated for attributes - */ - public static String xmlEncodeTextAsPCDATA( String text, boolean forAttribute ) - { - return xmlEncodeTextAsPCDATA( text, forAttribute, DEFAULT_QUOTE_CHAR ); - } - /** - * Encodes any text as PCDATA. - * - * @param forAttribute if you want - * quotes and apostrophes specially treated for attributes - * @param quoteChar if this is for attributes this char
is used to quote the attribute value - */ - public static String xmlEncodeTextAsPCDATA( String text, boolean forAttribute, char quoteChar ) - { - if ( text == null ) + int length = text.length(); + if ( forAttribute ) { - return null; + n.append( quoteChar ); } - StringWriter writer = new StringWriter( text.length() * 2 ); - xmlEncodeTextAsPCDATA( text, forAttribute, quoteChar, writer ); - return writer.toString(); - } - public static void xmlEncodeTextAsPCDATA( String text, boolean forAttribute, char quoteChar, Writer n ) - { - if ( text == null ) - { - return; - } - try + for ( int i = 0; i < length; i++ ) { - char c; - int length = text.length(); - if ( forAttribute ) - { - n.append( quoteChar ); - } - - for ( int i = 0; i < length; i++ ) + char c = text.charAt( i ); + switch ( c ) { - c = text.charAt( i ); - switch ( c ) - { - case '&': - n.append( "&" ); - break; - case '<': - n.append( "<" ); - break; - case '>': // FIX for sourceforge bug #802520 ("]]>" needs encoding) - n.append( ">" ); - break; - case '"': - if ( forAttribute ) - { - n.append( """ ); - } - else - { - n.append( c ); - } - break; - case '\'': - if ( forAttribute ) - { - n.append( "'" ); - } - else - { - n.append( c ); - } - break; - case '\r': - if ( forAttribute ) - { - if ( i == ( length - 1 ) || text.charAt( i + 1 ) != '\n' ) - { - n.append( " " ); - } - } - else - { - n.append( c ); - } - // but skip the \r in \r\n - - break; - case '\n': - if ( forAttribute ) + case '&': + n.append( "&" ); + break; + case '<': + n.append( "<" ); + break; + case '>': // FIX for sourceforge bug #802520 ("]]>" needs encoding) + n.append( ">" ); + break; + case '"': + if ( forAttribute ) + { + n.append( """ ); + } + else + { + n.append( c ); + } + break; + case '\'': + if ( forAttribute ) + { + n.append( "'" ); + } + else + { + n.append( c ); + } + break; + case '\r': + if ( forAttribute ) + { + if ( i == ( length - 1 ) || text.charAt( i + 1 ) != '\n' ) { - n.append( " " ); + n.append( " " ); } - break; - - default: + } + else + { n.append( c ); - break; - } - } + } + // but skip the \r in \r\n - if ( forAttribute ) - { - n.append( quoteChar ); + break; + case '\n': + if ( forAttribute ) + { + n.append( " " ); + } + break; + + default: + n.append( c ); + break; } } - catch ( IOException e ) + + if ( forAttribute ) { - throw new RuntimeException( e ); + n.append( quoteChar ); } } @@ -246,13 +149,13 @@ public static void xmlEncodeTextAsPCDATA( String text, boolean forAttribute, cha /** * Returns string as CDATA block if possible, otherwise null. */ - public static String xmlEncodeTextAsCDATABlock( String text ) + private static String xmlEncodeTextAsCDATABlock( String text ) { if ( text == null ) { return null; } - if ( isCompatibleWithCDATABlock( text ) ) + if ( !text.contains( "]]>" ) ) { return ""; } @@ -265,28 +168,16 @@ public static String xmlEncodeTextAsCDATABlock( String text ) /** * Checks if this text needs encoding in order to be represented in XML. */ - public static boolean needsEncoding( String text ) - { - return needsEncoding( text, false ); - } - - /** - * Checks if this text needs encoding in order to be represented in XML. - * - * SetcheckForAttr
if you want to check for storability in - * an attribute. - */ - public static boolean needsEncoding( String data, boolean checkForAttr ) + private static boolean needsEncoding( String text ) { - if ( data == null ) + if ( text == null ) { return false; } - char c; - for ( int i = 0; i < data.length(); i++ ) + for ( int i = 0; i < text.length(); i++ ) { - c = data.charAt( i ); - if ( c == '&' || c == '<' || ( checkForAttr && ( c == '"' || c == '\'' ) ) ) + char c = text.charAt( i ); + if ( c == '&' || c == '<' ) { return true; } @@ -294,85 +185,4 @@ public static boolean needsEncoding( String data, boolean checkForAttr ) return false; } - /** - * Can this text be stored into a CDATA block? - */ - public static boolean isCompatibleWithCDATABlock( String text ) - { - return text != null && ( !text.contains( "]]>" ) ); - } - - /** - * Make CDATA out of possibly encoded PCDATA.
- * E.g. make '&' out of '&' - */ - public static String xmlDecodeTextToCDATA( String pcdata ) - { - if ( pcdata == null ) - { - return null; - } - char c, c1, c2, c3, c4, c5; - StringBuilder n = new StringBuilder( pcdata.length() ); - for ( int i = 0; i < pcdata.length(); i++ ) - { - c = pcdata.charAt( i ); - if ( c == '&' ) - { - c1 = lookAhead( 1, i, pcdata ); - c2 = lookAhead( 2, i, pcdata ); - c3 = lookAhead( 3, i, pcdata ); - c4 = lookAhead( 4, i, pcdata ); - c5 = lookAhead( 5, i, pcdata ); - - if ( c1 == 'a' && c2 == 'm' && c3 == 'p' && c4 == ';' ) - { - n.append( "&" ); - i += 4; - } - else if ( c1 == 'l' && c2 == 't' && c3 == ';' ) - { - n.append( "<" ); - i += 3; - } - else if ( c1 == 'g' && c2 == 't' && c3 == ';' ) - { - n.append( ">" ); - i += 3; - } - else if ( c1 == 'q' && c2 == 'u' && c3 == 'o' && c4 == 't' && c5 == ';' ) - { - n.append( "\"" ); - i += 5; - } - else if ( c1 == 'a' && c2 == 'p' && c3 == 'o' && c4 == 's' && c5 == ';' ) - { - n.append( "'" ); - i += 5; - } - else - { - n.append( "&" ); - } - } - else - { - n.append( c ); - } - } - return n.toString(); - } - - private static char lookAhead( int la, int offset, String data ) - { - try - { - return data.charAt( offset + la ); - } - catch ( StringIndexOutOfBoundsException e ) - { - return 0x0; - } - } - } From 02325f14661be9b5b992eca27c84c263c83430ef Mon Sep 17 00:00:00 2001 From: Tamas CservenakDate: Mon, 3 May 2021 08:59:01 +0200 Subject: [PATCH 215/265] Update actions/java-setup to v2 --- .github/workflows/maven.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index eb39c5d8..4d7fff4e 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -41,9 +41,10 @@ jobs: maven-${{ matrix.os }}- - name: Set up JDK 1.8 - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: - java-version: 1.8 + java-version: '8' + distribution: 'adopt' - name: Build with Maven run: mvn clean verify -e -B -V From 48e1564e8d572fb2a6ce5668b9b405ea35f5cee9 Mon Sep 17 00:00:00 2001 From: Elliotte Rusty Harold Date: Mon, 3 May 2021 10:09:13 +0000 Subject: [PATCH 216/265] [MSHARED-985] XmlWriterUtil platform independent and consistent (#91) * make XmlWriterUtil platform independent and consistent with its documentation --- .../maven/shared/utils/xml/XmlWriterUtil.java | 43 ++++--- .../shared/utils/xml/XmlWriterUtilTest.java | 118 +++++++++--------- 2 files changed, 82 insertions(+), 79 deletions(-) diff --git a/src/main/java/org/apache/maven/shared/utils/xml/XmlWriterUtil.java b/src/main/java/org/apache/maven/shared/utils/xml/XmlWriterUtil.java index d9dd49e3..7d84d91a 100644 --- a/src/main/java/org/apache/maven/shared/utils/xml/XmlWriterUtil.java +++ b/src/main/java/org/apache/maven/shared/utils/xml/XmlWriterUtil.java @@ -32,6 +32,9 @@ public class XmlWriterUtil { /** The vm line separator */ public static final String LS = System.getProperty( "line.separator" ); + + /** Platform independent line separator */ + private static final String CRLF = "\r\n"; /** The default line indenter size i.e. 2. */ public static final int DEFAULT_INDENTATION_SIZE = 2; @@ -43,7 +46,7 @@ public class XmlWriterUtil * Convenience method to write one CRLF
. * * @param writer not null writer - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeLineBreak( XMLWriter writer ) throws IOException { @@ -55,13 +58,13 @@ public static void writeLineBreak( XMLWriter writer ) throws IOException * * @param writer not null * @param repeat positive number - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeLineBreak( XMLWriter writer, int repeat ) throws IOException { for ( int i = 0; i < repeat; i++ ) { - writer.writeMarkup( LS ); + writer.writeMarkup( CRLF ); } } @@ -73,7 +76,7 @@ public static void writeLineBreak( XMLWriter writer, int repeat ) throws IOExcep * @param indent positive number * @see #DEFAULT_INDENTATION_SIZE * @see #writeLineBreak(XMLWriter, int, int, int) - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeLineBreak( XMLWriter writer, int repeat, int indent ) throws IOException { @@ -87,7 +90,7 @@ public static void writeLineBreak( XMLWriter writer, int repeat, int indent ) th * @param repeat The number of repetitions of the indent * @param indent positive number * @param indentSize positive number - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeLineBreak( XMLWriter writer, int repeat, int indent, int indentSize ) throws IOException { @@ -112,7 +115,7 @@ public static void writeLineBreak( XMLWriter writer, int repeat, int indent, int * @param writer not null * @see #DEFAULT_COLUMN_LINE * @see #writeCommentLineBreak(XMLWriter, int) - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeCommentLineBreak( XMLWriter writer ) throws IOException { @@ -124,7 +127,7 @@ public static void writeCommentLineBreak( XMLWriter writer ) throws IOException * * @param writer not null * @param columnSize positive number - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeCommentLineBreak( XMLWriter writer, int columnSize ) throws IOException { @@ -133,18 +136,18 @@ public static void writeCommentLineBreak( XMLWriter writer, int columnSize ) thr columnSize = DEFAULT_COLUMN_LINE; } - writer.writeMarkup( "" + LS ); + writer.writeMarkup( "" + CRLF ); } /** - * Convenience method to write XML comment line. Thecomment
is splitted to have a size of + * Convenience method to write XML comment line. Thecomment
is split to have a size of *80
. * * @param writer not null * @param comment The comment to write * @see #DEFAULT_INDENTATION_SIZE * @see #writeComment(XMLWriter, String, int, int) - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeComment( XMLWriter writer, String comment ) throws IOException { @@ -160,7 +163,7 @@ public static void writeComment( XMLWriter writer, String comment ) throws IOExc * @param indent positive number * @see #DEFAULT_INDENTATION_SIZE * @see #writeComment(XMLWriter, String, int, int) - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeComment( XMLWriter writer, String comment, int indent ) throws IOException { @@ -177,7 +180,7 @@ public static void writeComment( XMLWriter writer, String comment, int indent ) * @param indentSize positive number * @see #DEFAULT_COLUMN_LINE * @see #writeComment(XMLWriter, String, int, int, int) - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeComment( XMLWriter writer, String comment, int indent, int indentSize ) throws IOException { @@ -193,7 +196,7 @@ public static void writeComment( XMLWriter writer, String comment, int indent, i * @param indent positive number * @param indentSize positive number * @param columnSize positive number - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeComment( XMLWriter writer, String comment, int indent, int indentSize, int columnSize ) throws IOException @@ -220,7 +223,7 @@ public static void writeComment( XMLWriter writer, String comment, int indent, i String indentation = StringUtils.repeat( " ", indent * indentSize ); int magicNumber = indentation.length() + columnSize - "-->".length() - 1; - String[] sentences = StringUtils.split( comment, LS ); + String[] sentences = StringUtils.split( comment, CRLF ); StringBuffer line = new StringBuffer( indentation + "" ).append( LS ); + line.append( "-->" ).append( CRLF ); writer.writeMarkup( line.toString() ); } line = new StringBuffer( indentation + "" ).append( LS ); + line.append( "-->" ).append( CRLF ); writer.writeMarkup( line.toString() ); } @@ -275,7 +278,7 @@ public static void writeComment( XMLWriter writer, String comment, int indent, i * @param comment The comment to write * @see #DEFAULT_INDENTATION_SIZE * @see #writeCommentText(XMLWriter, String, int, int) - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeCommentText( XMLWriter writer, String comment ) throws IOException { @@ -292,7 +295,7 @@ public static void writeCommentText( XMLWriter writer, String comment ) throws I * @param indent positive number * @see #DEFAULT_INDENTATION_SIZE * @see #writeCommentText(XMLWriter, String, int, int) - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeCommentText( XMLWriter writer, String comment, int indent ) throws IOException { @@ -309,7 +312,7 @@ public static void writeCommentText( XMLWriter writer, String comment, int inden * @param indentSize positive number * @see #DEFAULT_COLUMN_LINE * @see #writeCommentText(XMLWriter, String, int, int, int) - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeCommentText( XMLWriter writer, String comment, int indent, int indentSize ) throws IOException @@ -327,7 +330,7 @@ public static void writeCommentText( XMLWriter writer, String comment, int inden * @param indent positive number * @param indentSize positive number * @param columnSize positive number - * @throws IOException if writing fails. + * @throws IOException if writing fails */ public static void writeCommentText( XMLWriter writer, String comment, int indent, int indentSize, int columnSize ) throws IOException diff --git a/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java b/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java index 9a050da3..433e5feb 100644 --- a/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java +++ b/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java @@ -62,7 +62,7 @@ public void testWriteLineBreakXMLWriter() { XmlWriterUtil.writeLineBreak( xmlWriter ); writer.close(); - assertEquals( 1, StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) ); + assertEquals( 1, StringUtils.countMatches( output.toString(), "\r\n" ) ); } /** @@ -75,7 +75,7 @@ public void testWriteLineBreakXMLWriterInt() { XmlWriterUtil.writeLineBreak( xmlWriter, 10 ); writer.close(); - assertEquals( 10, StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) ); + assertEquals( 10, StringUtils.countMatches( output.toString(), "\r\n" ) ); } /** @@ -88,7 +88,7 @@ public void testWriteLineBreakXMLWriterIntInt() { XmlWriterUtil.writeLineBreak( xmlWriter, 10, 2 ); writer.close(); - assertEquals( 10, StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) ); + assertEquals( 10, StringUtils.countMatches( output.toString(), "\r\n" ) ); assertEquals( 1, StringUtils.countMatches( output.toString(), StringUtils .repeat( " ", 2 * XmlWriterUtil.DEFAULT_INDENTATION_SIZE ) ) ); } @@ -103,7 +103,7 @@ public void testWriteLineBreakXMLWriterIntIntInt() { XmlWriterUtil.writeLineBreak( xmlWriter, 10, 2, 4 ); writer.close(); - assertEquals( 10, StringUtils.countMatches( output.toString(), XmlWriterUtil.LS ) ); + assertEquals( 10, StringUtils.countMatches( output.toString(), "\r\n" ) ); assertEquals( 1, StringUtils.countMatches( output.toString(), StringUtils.repeat( " ", 2 * 4 ) ) ); } @@ -118,9 +118,9 @@ public void testWriteCommentLineBreakXMLWriter() XmlWriterUtil.writeCommentLineBreak( xmlWriter ); writer.close(); StringBuilder sb = new StringBuilder(); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); - assertEquals( output.toString().length(), XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ); + assertEquals( output.toString().length(), XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + "\r\n".length() ); } /** @@ -133,13 +133,13 @@ public void testWriteCommentLineBreakXMLWriterInt() { XmlWriterUtil.writeCommentLineBreak( xmlWriter, 20 ); writer.close(); - assertEquals( output.toString(), "" + XmlWriterUtil.LS ); + assertEquals( output.toString(), "" + "\r\n" ); } public void testWriteCommentLineBreak() throws IOException { XmlWriterUtil.writeCommentLineBreak( xmlWriter, 10 ); writer.close(); - assertEquals( output.toString(), output.toString(), "" + XmlWriterUtil.LS ); + assertEquals( output.toString(), output.toString(), "" + "\r\n" ); } /** @@ -153,9 +153,9 @@ public void testWriteCommentXMLWriterString() XmlWriterUtil.writeComment( xmlWriter, "hello" ); writer.close(); StringBuffer sb = new StringBuffer(); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); - assertEquals( output.toString().length(), XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ); + assertEquals( output.toString().length(), XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + "\r\n".length() ); } @@ -165,7 +165,7 @@ public void testWriteComment() throws IOException { writer.close(); StringBuffer sb = new StringBuffer(); sb.append( "" ) - .append( XmlWriterUtil.LS ); + .append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); assertTrue( output.toString().length() >= XmlWriterUtil.DEFAULT_COLUMN_LINE ); } @@ -174,10 +174,10 @@ public void testWriteComment_2() throws IOException { XmlWriterUtil.writeComment( xmlWriter, "hello\nworld" ); writer.close(); StringBuffer sb = new StringBuffer(); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); + sb.append( "" ).append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); - assertEquals( output.toString().length(), 2 * ( XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ) ); + assertEquals( output.toString().length(), 2 * ( XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + "\r\n".length() ) ); } /** @@ -194,9 +194,9 @@ public void testWriteCommentXMLWriterStringInt() writer.close(); StringBuffer sb = new StringBuffer(); sb.append( indent ); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); - assertEquals( output.toString().length(), XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() + 2 + assertEquals( output.toString().length(), XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + "\r\n".length() + 2 * XmlWriterUtil.DEFAULT_INDENTATION_SIZE ); } @@ -207,11 +207,11 @@ public void testWriteComment_3() throws IOException { writer.close(); StringBuffer sb = new StringBuffer(); sb.append( indent ); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); sb.append( indent ); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); - assertEquals( output.toString().length(), 2 * ( XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ) + 2 * indent.length() ); + assertEquals( output.toString().length(), 2 * ( XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + "\r\n".length() ) + 2 * indent.length() ); } /** @@ -228,9 +228,9 @@ public void testWriteCommentXMLWriterStringIntInt() writer.close(); StringBuffer sb = new StringBuffer(); sb.append( repeat ); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); - assertEquals( output.toString().length(), XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() + 2 * 4 ); + assertEquals( output.toString().length(), XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + "\r\n".length() + 2 * 4 ); } @@ -240,11 +240,11 @@ public void testWriteCommentXMLWriterStringIntInt_2() throws IOException { writer.close(); StringBuffer sb = new StringBuffer(); sb.append( repeat ); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); sb.append( repeat ); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 2 * ( XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + XmlWriterUtil.LS.length() ) + 2 * repeat.length() ); + assertTrue( output.toString().length() == 2 * ( XmlWriterUtil.DEFAULT_COLUMN_LINE - 1 + "\r\n".length() ) + 2 * repeat.length() ); } /** @@ -261,9 +261,9 @@ public void testWriteCommentXMLWriterStringIntIntInt() writer.close(); StringBuffer sb = new StringBuffer(); sb.append( indent ); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); - assertTrue( output.toString().length() == 50 - 1 + XmlWriterUtil.LS.length() + 2 * 4 ); + assertTrue( output.toString().length() == 50 - 1 + "\r\n".length() + 2 * 4 ); } public void testWriteCommentXMLWriterStringIntIntInt_2() throws IOException @@ -273,7 +273,7 @@ public void testWriteCommentXMLWriterStringIntIntInt_2() throws IOException writer.close(); StringBuffer sb = new StringBuffer(); sb.append( indent ); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); assertTrue( output.toString().length() >= 10 + 2 * 4 ); } @@ -289,13 +289,13 @@ public void testWriteCommentTextXMLWriterStringInt() XmlWriterUtil.writeCommentText( xmlWriter, "hello", 0 ); writer.close(); StringBuffer sb = new StringBuffer(); - sb.append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( XmlWriterUtil.LS ); + sb.append( "\r\n" ); + sb.append( "" ).append( "\r\n" ); + sb.append( "" ).append( "\r\n" ); + sb.append( "" ).append( "\r\n" ); + sb.append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); - assertEquals( output.toString().length(), 3 * ( 80 - 1 + XmlWriterUtil.LS.length() ) + 2 * XmlWriterUtil.LS.length() ); + assertEquals( output.toString().length(), 3 * ( 80 - 1 + "\r\n".length() ) + 2 * "\r\n".length() ); } public void testWriteCommentTextXMLWriterStringInt_2() throws IOException { @@ -305,20 +305,20 @@ public void testWriteCommentTextXMLWriterStringInt_2() throws IOException { + "loooooooooooooooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnong line", 2 ); writer.close(); StringBuffer sb = new StringBuffer(); - sb.append( XmlWriterUtil.LS ); + sb.append( "\r\n" ); sb.append( indent ).append( "" ) - .append( XmlWriterUtil.LS ); + .append( "\r\n" ); sb.append( indent ).append( "" ) - .append( XmlWriterUtil.LS ); + .append( "\r\n" ); sb.append( indent ).append( "" ) - .append( XmlWriterUtil.LS ); + .append( "\r\n" ); sb.append( indent ).append( "" ) - .append( XmlWriterUtil.LS ); + .append( "\r\n" ); sb.append( indent ).append( "" ) - .append( XmlWriterUtil.LS ); + .append( "\r\n" ); sb.append( indent ).append( "" ) - .append( XmlWriterUtil.LS ); - sb.append( XmlWriterUtil.LS ); + .append( "\r\n" ); + sb.append( "\r\n" ); sb.append( indent ); assertEquals( output.toString(), sb.toString() ); } @@ -337,17 +337,17 @@ public void testWriteCommentTextXMLWriterStringIntInt() XmlWriterUtil.writeCommentText( xmlWriter, "hello", 2, 4 ); writer.close(); StringBuilder sb = new StringBuilder(); - sb.append( XmlWriterUtil.LS ); + sb.append( "\r\n" ); sb.append( indent ).append( "" ) - .append( XmlWriterUtil.LS ); + .append( "\r\n" ); sb.append( indent ).append( "" ) - .append( XmlWriterUtil.LS ); + .append( "\r\n" ); sb.append( indent ).append( "" ) - .append( XmlWriterUtil.LS ); - sb.append( XmlWriterUtil.LS ); + .append( "\r\n" ); + sb.append( "\r\n" ); sb.append( indent ); assertEquals( output.toString(), sb.toString() ); - assertEquals( output.toString().length(), 3 * ( 80 - 1 + XmlWriterUtil.LS.length() ) + 4 * 2 * 4 + 2 * XmlWriterUtil.LS.length() ); + assertEquals( output.toString().length(), 3 * ( 80 - 1 + "\r\n".length() ) + 4 * 2 * 4 + 2 * "\r\n".length() ); } /** @@ -363,14 +363,14 @@ public void testWriteCommentTextXMLWriterStringIntIntInt() XmlWriterUtil.writeCommentText( xmlWriter, "hello", 2, 4, 50 ); writer.close(); StringBuilder sb = new StringBuilder(); - sb.append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( indent ).append( "" ).append( XmlWriterUtil.LS ); - sb.append( XmlWriterUtil.LS ); + sb.append( "\r\n" ); + sb.append( indent ).append( "" ).append( "\r\n" ); + sb.append( indent ).append( "" ).append( "\r\n" ); + sb.append( indent ).append( "" ).append( "\r\n" ); + sb.append( "\r\n" ); sb.append( indent ); assertEquals( output.toString(), sb.toString() ); - assertEquals( output.toString().length(), 3 * ( 50 - 1 + XmlWriterUtil.LS.length() ) + 4 * 2 * 4 + 2 * XmlWriterUtil.LS.length() ); + assertEquals( output.toString().length(), 3 * ( 50 - 1 + "\r\n".length() ) + 4 * 2 * 4 + 2 * "\r\n".length() ); } /** @@ -384,7 +384,7 @@ public void testWriteCommentNull() XmlWriterUtil.writeComment( xmlWriter, null ); writer.close(); StringBuilder sb = new StringBuilder(); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); } @@ -399,7 +399,7 @@ public void testWriteCommentShort() XmlWriterUtil.writeComment( xmlWriter, "This is a short text" ); writer.close(); StringBuilder sb = new StringBuilder(); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); } @@ -416,10 +416,10 @@ public void testWriteCommentLong() + "and documentation from a central piece of information." ); writer.close(); StringBuilder sb = new StringBuilder(); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); - sb.append( "" ).append( XmlWriterUtil.LS ); + sb.append( "" ).append( "\r\n" ); + sb.append( "" ).append( "\r\n" ); + sb.append( "" ).append( "\r\n" ); + sb.append( "" ).append( "\r\n" ); assertEquals( output.toString(), sb.toString() ); } } From 20086c4e19fad70b1eb0cde70d61867fb2f0b993 Mon Sep 17 00:00:00 2001 From: Elliotte Rusty HaroldDate: Wed, 2 Jun 2021 11:19:22 -0400 Subject: [PATCH 217/265] fix double typo --- .../java/org/apache/maven/shared/utils/io/MatchPattern.java | 2 +- .../java/org/apache/maven/shared/utils/io/MatchPatterns.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java b/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java index bdce10d7..60606573 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java +++ b/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java @@ -33,7 +33,7 @@ * Significantly more efficient than using strings, since re-evaluation and re-tokenizing is avoided. * * @author Kristian Rosenvold - * @deprecated use {@code java.nio.filejava.nio.file.DirectoryStream.Filter } and related classes + * @deprecated use {@code java.nio.file.DirectoryStream.Filter } and related classes */ @Deprecated public class MatchPattern diff --git a/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java b/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java index 638586f2..90c71802 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java +++ b/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java @@ -27,7 +27,7 @@ * A list of patterns to be matched * * @author Kristian Rosenvold - * @deprecated use {@code java.nio.filejava.nio.file.DirectoryStream.Filter } and related classes + * @deprecated use {@code java.nio.file.DirectoryStream.Filter } and related classes */ @Deprecated public class MatchPatterns From 4dd9b90faed6d31019a7062045443964ed19f6fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Herv=C3=A9=20Boutemy?= Date: Sun, 25 Jul 2021 15:43:22 +0200 Subject: [PATCH 218/265] update CI url --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 1c376af9..f5528645 100644 --- a/README.md +++ b/README.md @@ -20,8 +20,8 @@ Contributing to [Apache Maven Shared Utils](https://maven.apache.org/shared/mave [][jira] [][license] [](https://search.maven.org/artifact/org.apache.maven.shared/maven-shared-utils) -[][build] -[][test-results] +[][build] +[][test-results] You have found a bug or you have an idea for a cool new feature? Contributing @@ -95,5 +95,5 @@ Additional Resources [code-style]: https://maven.apache.org/developers/conventions/code.html [cla]: https://www.apache.org/licenses/#clas [maven-wiki]: https://cwiki.apache.org/confluence/display/MAVEN/Index -[test-results]: https://ci-builds.apache.org/job/Maven/job/maven-box/job/maven-shared-utils/job/master/lastCompletedBuild/testReport/ -[build]: https://ci-builds.apache.org/job/Maven/job/maven-box/job/maven-shared-utils/job/master/ +[test-results]: https://ci-maven.apache.org/job/Maven/job/maven-box/job/maven-shared-utils/job/master/lastCompletedBuild/testReport/ +[build]: https://ci-maven.apache.org/job/Maven/job/maven-box/job/maven-shared-utils/job/master/ From 0e4aa7569ad335b7f14eb529573d815717f5537b Mon Sep 17 00:00:00 2001 From: Slawomir Jaranowski Date: Mon, 3 Jan 2022 09:17:13 +0100 Subject: [PATCH 219/265] GitHub Shared Actions --- .../workflows/{maven.yml => maven-verify.yml} | 35 ++++--------------- 1 file changed, 6 insertions(+), 29 deletions(-) rename .github/workflows/{maven.yml => maven-verify.yml} (52%) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven-verify.yml similarity index 52% rename from .github/workflows/maven.yml rename to .github/workflows/maven-verify.yml index 4d7fff4e..bbd77865 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven-verify.yml @@ -15,36 +15,13 @@ # specific language governing permissions and limitations # under the License. -name: Java CI +name: Verify -on: [push, pull_request] +on: + push: + pull_request: jobs: build: - strategy: - matrix: - os: [ubuntu-latest, windows-latest, macOS-latest] - fail-fast: false - - runs-on: ${{ matrix.os }} - - steps: - - name: Checkout - uses: actions/checkout@v2 - - - name: Set up cache for ~/.m2/repository - uses: actions/cache@v2 - with: - path: ~/.m2/repository - key: maven-${{ matrix.os }}-${{ hashFiles('**/pom.xml') }} - restore-keys: | - maven-${{ matrix.os }}- - - - name: Set up JDK 1.8 - uses: actions/setup-java@v2 - with: - java-version: '8' - distribution: 'adopt' - - - name: Build with Maven - run: mvn clean verify -e -B -V + name: Verify + uses: apache/maven-gh-actions-shared/.github/workflows/maven-verify.yml@v2 From 89b81b6e49505352fe89599354156730a524ee55 Mon Sep 17 00:00:00 2001 From: Slawomir Jaranowski Date: Mon, 3 Jan 2022 09:33:52 +0100 Subject: [PATCH 220/265] (doc) Fix javadoc --- src/main/java/org/apache/maven/shared/utils/io/FileUtils.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java index 4d80e180..79c96b3a 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java +++ b/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java @@ -59,7 +59,7 @@ /** * This class provides basic facilities for manipulating files and file paths. * - * Path-related methods
+ *Path-related methods
* * Methods exist to retrieve the components of a typical file path. For example */www/hosted/mysite/index.html
, can be broken into: @@ -68,7 +68,7 @@ *- *
html
-- retrievable through {@link #getExtension}File-related methods
+ *File-related methods
* *There are methods to create a {@link #toFile File from a URL}, copy a * {@link #copyFile File to another File}, From ad8dd6ac0a974c0040a5ffd3203b0fd31733d2d2 Mon Sep 17 00:00:00 2001 From: Slawomir Jaranowski
Date: Mon, 3 Jan 2022 18:12:15 +0100 Subject: [PATCH 221/265] [MSHARED-1014] Optionally inherit system environment variables by Commandline --- .../maven/shared/utils/cli/Commandline.java | 38 ++++++++++++++++--- .../utils/cli/CommandLineUtilsTest.java | 34 ++++++++++------- 2 files changed, 53 insertions(+), 19 deletions(-) diff --git a/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java b/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java index e03e905c..2d5d63c8 100644 --- a/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java +++ b/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java @@ -65,12 +65,14 @@ public class Commandline implements Cloneable { - private final List arguments = new Vector (); + private final List arguments = new Vector<>(); private final Map envVars = Collections.synchronizedMap( new LinkedHashMap () ); private Shell shell; + private boolean shellEnvironmentInherited = true; + /** * Create a new command line object. * Shell is autodetected from operating system. @@ -198,14 +200,13 @@ public void addArguments( String... line ) */ public void addEnvironment( String name, String value ) { - //envVars.add( name + "=" + value ); envVars.put( name, value ); } /** * Add system environment variables. */ - public void addSystemEnvironment() + private void addSystemEnvironment() { Properties systemEnvVars = CommandLineUtils.getSystemEnvVars(); @@ -226,7 +227,11 @@ public void addSystemEnvironment() */ public String[] getEnvironmentVariables() { - addSystemEnvironment(); + if ( isShellEnvironmentInherited() ) + { + addSystemEnvironment(); + } + List environmentVars = new ArrayList<>(); for ( String name : envVars.keySet() ) { @@ -297,7 +302,7 @@ public String[] getArguments() */ public String[] getArguments( boolean mask ) { - List result = new ArrayList ( arguments.size() * 2 ); + List result = new ArrayList<>( arguments.size() * 2 ); for ( Arg argument : arguments ) { Argument arg = (Argument) argument; @@ -377,6 +382,29 @@ public void clearArgs() arguments.clear(); } + /** + * Indicates whether the environment variables of the current process + * should are propagated to the executing Command. + * By default, the current environment variables are inherited by the new Command line execution. + * + * @return true
if the environment variables should be propagated,false
otherwise. + */ + public boolean isShellEnvironmentInherited() + { + return shellEnvironmentInherited; + } + + /** + * Specifies whether the environment variables of the current process should be propagated to the executing Command. + * + * @param shellEnvironmentInheritedtrue
if the environment variables should be propagated, + *false
otherwise. + */ + public void setShellEnvironmentInherited( boolean shellEnvironmentInherited ) + { + this.shellEnvironmentInherited = shellEnvironmentInherited; + } + /** * Execute the command. * diff --git a/src/test/java/org/apache/maven/shared/utils/cli/CommandLineUtilsTest.java b/src/test/java/org/apache/maven/shared/utils/cli/CommandLineUtilsTest.java index 81b29971..fdc83b0a 100644 --- a/src/test/java/org/apache/maven/shared/utils/cli/CommandLineUtilsTest.java +++ b/src/test/java/org/apache/maven/shared/utils/cli/CommandLineUtilsTest.java @@ -56,9 +56,8 @@ public void testGetSystemEnvVarsCaseInsensitive() @Test public void testEnsureCaseSensitivity() - throws Exception { - Mapdata = new HashMap (); + Map data = new HashMap<>(); data.put( "abz", "cool" ); assertTrue( CommandLineUtils.ensureCaseSensitivity( data, false ).containsKey( "ABZ" ) ); assertTrue( CommandLineUtils.ensureCaseSensitivity( data, true ).containsKey( "abz" ) ); @@ -69,7 +68,6 @@ public void testEnsureCaseSensitivity() */ @Test public void testGetSystemEnvVarsWindows() - throws Exception { if ( !Os.isFamily( Os.FAMILY_WINDOWS ) ) { @@ -103,14 +101,9 @@ public void testTranslateCommandline() assertCmdLineArgs( new String[] { "foo", " ' ", "bar" }, "foo \" ' \" bar" ); } - @Test - public void givenASingleQuoteMarkInArgument_whenExecutingCode_thenNoExceptionIsThrown() throws Exception { - new Commandline("echo \"let's go\"").execute(); - } - - @Test - public void givenADoubleQuoteMarkInArgument_whenExecutingCode_thenCommandLineExceptionIsThrown() throws Exception { + public void givenADoubleQuoteMarkInArgument_whenExecutingCode_thenCommandLineExceptionIsThrown() + { try { new Commandline("echo \"let\"s go\"").execute(); } catch (CommandLineException e) { @@ -124,8 +117,7 @@ public void givenADoubleQuoteMarkInArgument_whenExecutingCode_thenCommandLineExc @Test public void givenASingleQuoteMarkInArgument_whenExecutingCode_thenExitCode0Returned() throws Exception { final Process p = new Commandline("echo \"let's go\"").execute(); - // Note, this sleep should be removed when java version reaches Java 8 - Thread.sleep(1000); + p.waitFor(); assertEquals(0, p.exitValue()); } @@ -160,7 +152,9 @@ public void givenAnEscapedSingleQuoteMarkInArgument_whenTranslatingToCmdLineArgs public void givenAnEscapedDoubleQuoteMarkInArgument_whenTranslatingToCmdLineArgs_thenNoExceptionIsThrown() throws Exception { - new Commandline( "echo \"let\\\"s go\"" ).execute(); + Process p = new Commandline( "echo \"let\\\"s go\"" ).execute(); + p.waitFor(); + assertEquals(0, p.exitValue()); } private void assertCmdLineArgs( final String[] expected, final String cmdLine ) @@ -185,7 +179,7 @@ public void environmentVariableWithNullShouldNotBeSet() { } @Test - public void environmentVariableFromSystemIsCopied() { + public void environmentVariableFromSystemIsCopiedByDefault() { Commandline commandline = new Commandline(); @@ -195,6 +189,18 @@ public void environmentVariableFromSystemIsCopied() { assertThat(environmentVariables, hasItemInArray( "TEST_SHARED_ENV=TestValue" ) ); } + @Test + public void environmentVariableFromSystemIsNotCopiedIfInheritedIsFalse() { + + Commandline commandline = new Commandline(); + commandline.setShellEnvironmentInherited( false ); + + String[] environmentVariables = commandline.getEnvironmentVariables(); + + assertNotNull(environmentVariables); + assertEquals(0, environmentVariables.length ); + } + @Test public void environmentVariableFromSystemIsRemoved() { From 412b279a9b24d4ae08889743dd9e6fb275d12973 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotrek=20=C5=BBygie=C5=82o?= <11896137+pzygielo@users.noreply.github.com> Date: Fri, 11 Mar 2022 14:52:13 +0100 Subject: [PATCH 222/265] (doc) Throw more descriptive NPEx (#95) --- .../shared/utils/io/DirectoryScanner.java | 13 +++++++ .../shared/utils/io/DirectoryScannerTest.java | 36 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java index bd8bd7d9..8f92fd2b 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java +++ b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java @@ -321,6 +321,10 @@ public void setIncludes( final String... includes ) this.includes = new String[includes.length]; for ( int i = 0; i < includes.length; i++ ) { + if ( includes[i] == null ) + { + throw new NullPointerException( messageForNullListElement( "includes" ) ); + } String pattern; pattern = includes[i].trim().replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); if ( pattern.endsWith( File.separator ) ) @@ -353,6 +357,10 @@ public void setExcludes( final String... excludes ) this.excludes = new String[excludes.length]; for ( int i = 0; i < excludes.length; i++ ) { + if ( excludes[i] == null ) + { + throw new NullPointerException( messageForNullListElement( "excludes" ) ); + } String pattern; pattern = excludes[i].trim().replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); if ( pattern.endsWith( File.separator ) ) @@ -364,6 +372,11 @@ public void setExcludes( final String... excludes ) } } + private static String messageForNullListElement( String listName ) + { + return "If a non-null " + listName + " list is given, all elements must be non-null"; + } + /** * @param scanConductor {@link #scanConductor} */ diff --git a/src/test/java/org/apache/maven/shared/utils/io/DirectoryScannerTest.java b/src/test/java/org/apache/maven/shared/utils/io/DirectoryScannerTest.java index 01110069..9dffdad5 100644 --- a/src/test/java/org/apache/maven/shared/utils/io/DirectoryScannerTest.java +++ b/src/test/java/org/apache/maven/shared/utils/io/DirectoryScannerTest.java @@ -25,6 +25,7 @@ import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import java.io.File; @@ -128,6 +129,41 @@ public void testSimpleIncludes() /* expExclDirs */ NONE ); } + @Rule + public ExpectedException xcludesNPExRule = ExpectedException.none(); + + @Test + public void testIncludesWithNull() + throws Exception + { + testXcludesWithNull( new String[]{ null }, null, "includes" ); + } + + @Test + public void testExcludesWithNull() + throws Exception + { + testXcludesWithNull( null, new String[]{ null }, "excludes" ); + } + + private void testXcludesWithNull( String[] includes, String[] excludes, String listName ) + throws Exception + { + createTestData(); + xcludesNPExRule.expect( NullPointerException.class ); + xcludesNPExRule.expectMessage( "If a non-null " + listName + " list is given, all elements must be non-null" ); + + fitScanTest( true, true, true, + /* includes */ includes, + /* excludes */ excludes, + /* expInclFiles */ new String[]{ "file3.dat", "folder1/file5.dat" }, + /* expInclDirs */ NONE, + /* expNotInclFiles */ new String[]{ "file1.txt", "file2.txt", "folder1/file4.txt" }, + /* expNotInclDirs */ new String[]{ "", "folder1" }, + /* expExclFiles */ NONE, + /* expExclDirs */ NONE ); + } + @Test public void checkSymlinkBehaviour() { From e838d1ae06c15e2d36830896fa75cd30568d73ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=A1clav=20Haisman?= Date: Sat, 11 Jun 2022 11:20:19 +0200 Subject: [PATCH 223/265] Fix typo in DirectoryScanner.java MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cannonical → canonical --- .../java/org/apache/maven/shared/utils/io/DirectoryScanner.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java index 8f92fd2b..468e226f 100644 --- a/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java +++ b/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java @@ -762,7 +762,7 @@ private String[] doNotFollowSymbolicLinks( final File dir, final String vpath, S catch ( final IOException ioe ) { final String msg = - "IOException caught while checking " + "for links, couldn't get cannonical path!"; + "IOException caught while checking " + "for links, couldn't get canonical path!"; // will be caught and redirected to Ant's logging system System.err.println( msg ); noLinks.add( newfile ); From 1fa7a4c9dea71d430d4fade4d52f8261108c66e2 Mon Sep 17 00:00:00 2001 From: Slawomir Jaranowski Date: Tue, 21 Jun 2022 01:15:37 +0200 Subject: [PATCH 224/265] Cleanup unneeded dependencies --- pom.xml | 16 ---------------- .../ReflectionValueExtractorTest.java | 16 +++++++++++++--- 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/pom.xml b/pom.xml index daf55b01..fcfc09ba 100644 --- a/pom.xml +++ b/pom.xml @@ -63,7 +63,6 @@ RedundantThrows,NewlineAtEndOfFile,ParameterNumber,MethodLength,FileLength,ModifierOrder 2021-04-26T13:54:25Z 7 -3.1.0 @@ -110,27 +109,12 @@ 3.0.2 provided
java.lang.String.join(
) instead
*/
+ @Deprecated
@Nonnull public static String join( @Nonnull Object[] array, @Nullable String separator )
{
if ( separator == null )
@@ -650,7 +652,9 @@ public static String mid( String str, int pos, int len )
* @param iterator the Iterator
of values to join together
* @param separator the separator character to use
* @return the joined String
+ * @deprecated use java.lang.String.join(
) instead
*/
+ @Deprecated
@Nonnull public static String join( @Nonnull Iterator> iterator, String separator )
{
if ( separator == null )
@@ -689,7 +693,7 @@ public static String replaceOnce( @Nullable String text, char repl, char with )
}
/**
- * Replace all occurances of a char within another char.
+ *Replace all occurrences of a char within a string with another char.
* *A null
reference passed to this method is a no-op.
true
in case string is empty false
otherwise.
+ * @deprecated use str == null || String.isBlank(str)
(Java 11+)
+ * or org.apache.commons.lang3.StringUtils.isBlank(str)
+ * @param str the string to be checked
+ * @return true
if the string is null, empty, or whitespace only; false
otherwise
*/
+ @Deprecated
public static boolean isEmpty( String str )
{
return str == null || str.trim().length() == 0;
}
-
-
-
}
From 0c1a7d4115e17ab318c48ec7e65775a67dc65198 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Fri, 24 Feb 2023 20:03:05 +0000
Subject: [PATCH 244/265] Bump apache/maven-gh-actions-shared from 2 to 3
Bumps [apache/maven-gh-actions-shared](https://github.com/apache/maven-gh-actions-shared) from 2 to 3.
- [Release notes](https://github.com/apache/maven-gh-actions-shared/releases)
- [Commits](https://github.com/apache/maven-gh-actions-shared/commits/v3)
---
updated-dependencies:
- dependency-name: apache/maven-gh-actions-shared
dependency-type: direct:production
update-type: version-update:semver-major
...
Signed-off-by: dependabot[bot] comment
is split to have a size of
* columnSize
and is indented by indent
using indentSize
.
@@ -198,76 +184,62 @@ public static void writeComment( XMLWriter writer, String comment, int indent, i
* @param columnSize positive number
* @throws IOException if writing fails
*/
- public static void writeComment( XMLWriter writer, String comment, int indent, int indentSize, int columnSize )
- throws IOException
- {
- if ( comment == null )
- {
+ public static void writeComment(XMLWriter writer, String comment, int indent, int indentSize, int columnSize)
+ throws IOException {
+ if (comment == null) {
comment = "null";
}
- if ( indent < 0 )
- {
+ if (indent < 0) {
indent = 0;
}
- if ( indentSize < 0 )
- {
+ if (indentSize < 0) {
indentSize = 0;
}
- if ( columnSize < 0 )
- {
+ if (columnSize < 0) {
columnSize = DEFAULT_COLUMN_LINE;
}
- String indentation = StringUtils.repeat( " ", indent * indentSize );
+ String indentation = StringUtils.repeat(" ", indent * indentSize);
int magicNumber = indentation.length() + columnSize - "-->".length() - 1;
- String[] sentences = StringUtils.split( comment, CRLF );
-
- StringBuffer line = new StringBuffer( indentation + "" ).append( CRLF );
- writer.writeMarkup( line.toString() );
+ line.append("-->").append(CRLF);
+ writer.writeMarkup(line.toString());
}
- line = new StringBuffer( indentation + "" ).append( CRLF );
+ line.append("-->").append(CRLF);
- writer.writeMarkup( line.toString() );
+ writer.writeMarkup(line.toString());
}
/**
@@ -280,9 +252,8 @@ public static void writeComment( XMLWriter writer, String comment, int indent, i
* @see #writeCommentText(XMLWriter, String, int, int)
* @throws IOException if writing fails
*/
- public static void writeCommentText( XMLWriter writer, String comment ) throws IOException
- {
- writeCommentText( writer, comment, 0, DEFAULT_INDENTATION_SIZE );
+ public static void writeCommentText(XMLWriter writer, String comment) throws IOException {
+ writeCommentText(writer, comment, 0, DEFAULT_INDENTATION_SIZE);
}
/**
@@ -297,9 +268,8 @@ public static void writeCommentText( XMLWriter writer, String comment ) throws I
* @see #writeCommentText(XMLWriter, String, int, int)
* @throws IOException if writing fails
*/
- public static void writeCommentText( XMLWriter writer, String comment, int indent ) throws IOException
- {
- writeCommentText( writer, comment, indent, DEFAULT_INDENTATION_SIZE );
+ public static void writeCommentText(XMLWriter writer, String comment, int indent) throws IOException {
+ writeCommentText(writer, comment, indent, DEFAULT_INDENTATION_SIZE);
}
/**
@@ -314,10 +284,9 @@ public static void writeCommentText( XMLWriter writer, String comment, int inden
* @see #writeCommentText(XMLWriter, String, int, int, int)
* @throws IOException if writing fails
*/
- public static void writeCommentText( XMLWriter writer, String comment, int indent, int indentSize )
- throws IOException
- {
- writeCommentText( writer, comment, indent, indentSize, DEFAULT_COLUMN_LINE );
+ public static void writeCommentText(XMLWriter writer, String comment, int indent, int indentSize)
+ throws IOException {
+ writeCommentText(writer, comment, indent, indentSize, DEFAULT_COLUMN_LINE);
}
/**
@@ -332,34 +301,30 @@ public static void writeCommentText( XMLWriter writer, String comment, int inden
* @param columnSize positive number
* @throws IOException if writing fails
*/
- public static void writeCommentText( XMLWriter writer, String comment, int indent, int indentSize, int columnSize )
- throws IOException
- {
- if ( indent < 0 )
- {
+ public static void writeCommentText(XMLWriter writer, String comment, int indent, int indentSize, int columnSize)
+ throws IOException {
+ if (indent < 0) {
indent = 0;
}
- if ( indentSize < 0 )
- {
+ if (indentSize < 0) {
indentSize = 0;
}
- if ( columnSize < 0 )
- {
+ if (columnSize < 0) {
columnSize = DEFAULT_COLUMN_LINE;
}
- writeLineBreak( writer, 1 );
+ writeLineBreak(writer, 1);
- writer.writeMarkup( StringUtils.repeat( " ", indent * indentSize ) );
- writeCommentLineBreak( writer, columnSize );
+ writer.writeMarkup(StringUtils.repeat(" ", indent * indentSize));
+ writeCommentLineBreak(writer, columnSize);
- writeComment( writer, comment, indent, indentSize, columnSize );
+ writeComment(writer, comment, indent, indentSize, columnSize);
- writer.writeMarkup( StringUtils.repeat( " ", indent * indentSize ) );
- writeCommentLineBreak( writer, columnSize );
+ writer.writeMarkup(StringUtils.repeat(" ", indent * indentSize));
+ writeCommentLineBreak(writer, columnSize);
- writeLineBreak( writer, 1, indent, indentSize );
+ writeLineBreak(writer, 1, indent, indentSize);
}
}
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java
index 1b2f1b66..40b7b633 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.xml;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,7 +7,7 @@
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@@ -18,6 +16,9 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.xml;
+
+import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.StringWriter;
@@ -28,16 +29,12 @@
import java.util.List;
import java.util.Map;
-import javax.annotation.Nonnull;
-
/**
* A reimplementation of Plexus Xpp3Dom based on the public interface of Plexus Xpp3Dom.
*
* @author Kristian Rosenvold
*/
-public class Xpp3Dom
- implements Iterableoverride
.
*/
- public static final String SELF_COMBINATION_OVERRIDE = "override"; // plexus: public
+ public static final String SELF_COMBINATION_OVERRIDE = "override"; // plexus: public
/**
* The attribute which identifies merge
*/
public static final String SELF_COMBINATION_MERGE = "merge";
- @SuppressWarnings( "UnusedDeclaration" )
- private static final String DEFAULT_SELF_COMBINATION_MODE = SELF_COMBINATION_MERGE; // plexus: public
+ @SuppressWarnings("UnusedDeclaration")
+ private static final String DEFAULT_SELF_COMBINATION_MODE = SELF_COMBINATION_MERGE; // plexus: public
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private static final Xpp3Dom[] EMPTY_DOM_ARRAY = new Xpp3Dom[0];
@@ -91,8 +88,7 @@ public class Xpp3Dom
/**
* @param name The name of the instance.
*/
- public Xpp3Dom( String name )
- {
+ public Xpp3Dom(String name) {
this.name = name;
childList = new ArrayListnull
.
*/
- public static boolean isNotEmpty( String str )
- {
+ public static boolean isNotEmpty(String str) {
return str != null && str.length() > 0;
}
@@ -416,14 +365,12 @@ public static boolean isNotEmpty( String str )
* @param str The string to be checked.
* @return true if the string is empty or null
.
*/
- public static boolean isEmpty( String str )
- {
+ public static boolean isEmpty(String str) {
return str == null || str.trim().length() == 0;
}
/** {@inheritDoc} */
- public Iteratorstr == null || String.isBlank(str)
(Java 11+)
+ * @deprecated use str == null || String.isBlank(str)
(Java 11+)
* or org.apache.commons.lang3.StringUtils.isBlank(str)
* @param str the string to be checked
* @return true
if the string is null, empty, or whitespace only; false
otherwise
*/
@Deprecated
- public static boolean isEmpty( String str )
- {
+ public static boolean isEmpty(String str) {
return str == null || str.trim().length() == 0;
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomWriter.java b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomWriter.java
index b390c545..f4924985 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomWriter.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomWriter.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.xml;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,7 +7,7 @@
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@@ -18,6 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils.xml;
import java.io.IOException;
import java.io.PrintWriter;
@@ -26,16 +25,14 @@
/**
* @author Brett Porter
*/
-public class Xpp3DomWriter
-{
+public class Xpp3DomWriter {
/**
* @param writer {@link Writer}
* @param dom {@link Xpp3Dom}
* @throws IOException if writing fails.
*/
- public static void write( Writer writer, Xpp3Dom dom ) throws IOException
- {
- write( new PrettyPrintXMLWriter( writer ), dom );
+ public static void write(Writer writer, Xpp3Dom dom) throws IOException {
+ write(new PrettyPrintXMLWriter(writer), dom);
}
/**
@@ -43,9 +40,8 @@ public static void write( Writer writer, Xpp3Dom dom ) throws IOException
* @param dom {@link Xpp3Dom}
* @throws IOException if writing fails.
*/
- public static void write( PrintWriter writer, Xpp3Dom dom ) throws IOException
- {
- write( new PrettyPrintXMLWriter( writer ), dom );
+ public static void write(PrintWriter writer, Xpp3Dom dom) throws IOException {
+ write(new PrettyPrintXMLWriter(writer), dom);
}
/**
@@ -53,9 +49,8 @@ public static void write( PrintWriter writer, Xpp3Dom dom ) throws IOException
* @param dom {@link Xpp3Dom}
* @throws IOException if writing fails.
*/
- public static void write( XMLWriter xmlWriter, Xpp3Dom dom ) throws IOException
- {
- write( xmlWriter, dom, true );
+ public static void write(XMLWriter xmlWriter, Xpp3Dom dom) throws IOException {
+ write(xmlWriter, dom, true);
}
/**
@@ -64,33 +59,25 @@ public static void write( XMLWriter xmlWriter, Xpp3Dom dom ) throws IOException
* @param escape true/false.
* @throws IOException if writing fails.
*/
- public static void write( XMLWriter xmlWriter, Xpp3Dom dom, boolean escape ) throws IOException
- {
- xmlWriter.startElement( dom.getName() );
+ public static void write(XMLWriter xmlWriter, Xpp3Dom dom, boolean escape) throws IOException {
+ xmlWriter.startElement(dom.getName());
String[] attributeNames = dom.getAttributeNames();
- for ( String attributeName : attributeNames )
- {
- xmlWriter.addAttribute( attributeName, dom.getAttribute( attributeName ) );
+ for (String attributeName : attributeNames) {
+ xmlWriter.addAttribute(attributeName, dom.getAttribute(attributeName));
}
Xpp3Dom[] children = dom.getChildren();
- for ( Xpp3Dom aChildren : children )
- {
- write( xmlWriter, aChildren, escape );
+ for (Xpp3Dom aChildren : children) {
+ write(xmlWriter, aChildren, escape);
}
String value = dom.getValue();
- if ( value != null )
- {
- if ( escape )
- {
- xmlWriter.writeText( value );
- }
- else
- {
- xmlWriter.writeMarkup( value );
+ if (value != null) {
+ if (escape) {
+ xmlWriter.writeText(value);
+ } else {
+ xmlWriter.writeMarkup(value);
}
}
xmlWriter.endElement();
}
-
}
diff --git a/src/main/java/org/apache/maven/shared/utils/xml/pull/XmlPullParserException.java b/src/main/java/org/apache/maven/shared/utils/xml/pull/XmlPullParserException.java
index 3858a902..5f495b11 100644
--- a/src/main/java/org/apache/maven/shared/utils/xml/pull/XmlPullParserException.java
+++ b/src/main/java/org/apache/maven/shared/utils/xml/pull/XmlPullParserException.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils.xml.pull;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,7 +7,7 @@
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@@ -18,44 +16,34 @@
* specific language governing permissions and limitations
* under the License.
*/
-
-import org.xml.sax.SAXException;
+package org.apache.maven.shared.utils.xml.pull;
import java.io.IOException;
-/**
- *
- */
-public class XmlPullParserException
- extends RuntimeException
-{
+import org.xml.sax.SAXException;
+
+public class XmlPullParserException extends RuntimeException {
- /**
- *
- */
private static final long serialVersionUID = 117075811816936575L;
/**
* @param e IOException.
*/
- public XmlPullParserException( IOException e )
- {
- super( e );
+ public XmlPullParserException(IOException e) {
+ super(e);
}
/**
* @param e The exception.
*/
- public XmlPullParserException( SAXException e )
- {
- super( e );
+ public XmlPullParserException(SAXException e) {
+ super(e);
}
/**
* @param message The message.
*/
- public XmlPullParserException( String message )
- {
- super( message );
+ public XmlPullParserException(String message) {
+ super(message);
}
}
diff --git a/src/test/java/org/apache/maven/shared/utils/CaseTest.java b/src/test/java/org/apache/maven/shared/utils/CaseTest.java
index 7eae3028..113c441c 100644
--- a/src/test/java/org/apache/maven/shared/utils/CaseTest.java
+++ b/src/test/java/org/apache/maven/shared/utils/CaseTest.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,7 +7,7 @@
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@@ -18,6 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils;
import java.util.Locale;
@@ -32,36 +31,33 @@
* give intuitive result, or why one should avoid {@link String#toUpperCase()} and {@link String#toLowerCase()}
* (platform locale dependent, with sometimes unexpected results)
* but prefer {@link String#equalsIgnoreCase(String)} when possible.
- *
+ *
* @author Hervé Boutemy
* @see Simple Smiles - Xuelei Fan's Blog
*/
-public class CaseTest
- extends Assert
-{
- private final static Locale LOCALE_TURKISH = new Locale( "tr" );
+public class CaseTest extends Assert {
+ private static final Locale LOCALE_TURKISH = new Locale("tr");
/** common ASCII 'i' */
- private final static char DOTTED_i = '\u0069';
+ private static final char DOTTED_i = '\u0069';
/** common ASCII 'I' */
- private final static char DOTLESS_I = '\u0049';
+ private static final char DOTLESS_I = '\u0049';
/** turkish dotless i = ı */
- private final static char DOTLESS_i = '\u0131';
+ private static final char DOTLESS_i = '\u0131';
/** turkish dotted I = İ */
- private final static char DOTTED_I = '\u0130';
+ private static final char DOTTED_I = '\u0130';
/** http://en.wikipedia.org/wiki/Dot_(diacritic) */
- private final static char COMBINING_DOT_ABOVE = '\u0307';
+ private static final char COMBINING_DOT_ABOVE = '\u0307';
- private final static Locale SAVED_DEFAULT_LOCALE = Locale.getDefault();
+ private static final Locale SAVED_DEFAULT_LOCALE = Locale.getDefault();
@AfterClass
- public static void restoreDefaultLocale()
- {
- Locale.setDefault( SAVED_DEFAULT_LOCALE );
+ public static void restoreDefaultLocale() {
+ Locale.setDefault(SAVED_DEFAULT_LOCALE);
}
/**
@@ -69,42 +65,47 @@ public static void restoreDefaultLocale()
* @see The infamous Turkish locale bug
*/
@Test
- public void testTurkishI()
- {
+ public void testTurkishI() {
// check common i and I
- assertEquals( "common lowercase i should have a dot", 'i', DOTTED_i );
- assertEquals( "common uppercase I should not have a dot", 'I', DOTLESS_I );
+ assertEquals("common lowercase i should have a dot", 'i', DOTTED_i);
+ assertEquals("common uppercase I should not have a dot", 'I', DOTLESS_I);
final String iIıİ = "iIıİ";
// check source encoding doesn't wreck havoc */
- assertUnicodeEquals( "misc i directly in (UTF-8) source", iIıİ, "" + DOTTED_i + DOTLESS_I + DOTLESS_i
- + DOTTED_I );
+ assertUnicodeEquals(
+ "misc i directly in (UTF-8) source", iIıİ, "" + DOTTED_i + DOTLESS_I + DOTLESS_i + DOTTED_I);
// check toUpperCase and toLowerCase difference with turkish and english locales
- assertUnicodeEquals( "'iIıİ'.toUpperCase('tr')=='İIIİ'", "" + DOTTED_I + DOTLESS_I + DOTLESS_I + DOTTED_I,
- iIıİ.toUpperCase( LOCALE_TURKISH ) );
- assertUnicodeEquals( "'iIıİ'.toLowerCase('tr')=='iııi'", "" + DOTTED_i + DOTLESS_i + DOTLESS_i + DOTTED_i,
- iIıİ.toLowerCase( LOCALE_TURKISH ) );
- assertUnicodeEquals( "'iIıİ'.toUpperCase('en')=='IIIİ'", "" + DOTLESS_I + DOTLESS_I + DOTLESS_I + DOTTED_I,
- iIıİ.toUpperCase( Locale.ENGLISH ) );
- String lower = iIıİ.toLowerCase( Locale.ENGLISH ); // on some platforms, ends with extra COMBINED DOT ABOVE
- assertUnicodeEquals( "'iIıİ'.toLowerCase('en')=='iiıi'", "" + DOTTED_i + DOTTED_i + DOTLESS_i + DOTTED_i
- + ( lower.length() > 4 ? COMBINING_DOT_ABOVE : "" ), lower );
+ assertUnicodeEquals(
+ "'iIıİ'.toUpperCase('tr')=='İIIİ'",
+ "" + DOTTED_I + DOTLESS_I + DOTLESS_I + DOTTED_I,
+ iIıİ.toUpperCase(LOCALE_TURKISH));
+ assertUnicodeEquals(
+ "'iIıİ'.toLowerCase('tr')=='iııi'",
+ "" + DOTTED_i + DOTLESS_i + DOTLESS_i + DOTTED_i,
+ iIıİ.toLowerCase(LOCALE_TURKISH));
+ assertUnicodeEquals(
+ "'iIıİ'.toUpperCase('en')=='IIIİ'",
+ "" + DOTLESS_I + DOTLESS_I + DOTLESS_I + DOTTED_I,
+ iIıİ.toUpperCase(Locale.ENGLISH));
+ String lower = iIıİ.toLowerCase(Locale.ENGLISH); // on some platforms, ends with extra COMBINED DOT ABOVE
+ assertUnicodeEquals(
+ "'iIıİ'.toLowerCase('en')=='iiıi'",
+ "" + DOTTED_i + DOTTED_i + DOTLESS_i + DOTTED_i + (lower.length() > 4 ? COMBINING_DOT_ABOVE : ""),
+ lower);
// check equalsIgnoreCase() , which has no locale
- for ( int i = 0; i < iIıİ.length(); i++ )
- {
- char currentI = iIıİ.charAt( i );
-
- StringBuilder sb = new StringBuilder( iIıİ.length() );
- for ( int j = 0; j < iIıİ.length(); j++ )
- {
- sb.append( currentI );
+ for (int i = 0; i < iIıİ.length(); i++) {
+ char currentI = iIıİ.charAt(i);
+
+ StringBuilder sb = new StringBuilder(iIıİ.length());
+ for (int j = 0; j < iIıİ.length(); j++) {
+ sb.append(currentI);
}
String current = sb.toString();
- assertTrue( "'" + current + "'.equalsIgnoreCase('" + iIıİ + "')", current.equalsIgnoreCase( iIıİ ) );
+ assertTrue("'" + current + "'.equalsIgnoreCase('" + iIıİ + "')", current.equalsIgnoreCase(iIıİ));
}
}
@@ -114,15 +115,13 @@ public void testTurkishI()
* @param expected
* @param actual
*/
- private void assertUnicodeEquals( String message, String expected, String actual )
- {
- if ( expected.equals( actual ) )
- {
+ private void assertUnicodeEquals(String message, String expected, String actual) {
+ if (expected.equals(actual)) {
return;
}
- throw new ComparisonFailure( message, StringEscapeUtils.escapeJava( expected ),
- StringEscapeUtils.escapeJava( actual ) );
+ throw new ComparisonFailure(
+ message, StringEscapeUtils.escapeJava(expected), StringEscapeUtils.escapeJava(actual));
}
/**
@@ -130,43 +129,46 @@ private void assertUnicodeEquals( String message, String expected, String actual
* exception on these characters.
*/
@Test
- public void testAsciiAvailableLocales()
- {
+ public void testAsciiAvailableLocales() {
final String lower = "abcdefghijklmnopqrstuvwxyz";
final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- for ( Locale locale : Locale.getAvailableLocales() )
- {
+ for (Locale locale : Locale.getAvailableLocales()) {
// check that toUpper() == toUpper(default locale) and toLower() = toLower(default locale)
- Locale.setDefault( locale );
- assertEquals( lower.toUpperCase(), lower.toUpperCase( locale ) );
- assertEquals( upper.toLowerCase(), upper.toLowerCase( locale ) );
+ Locale.setDefault(locale);
+ assertEquals(lower.toUpperCase(), lower.toUpperCase(locale));
+ assertEquals(upper.toLowerCase(), upper.toLowerCase(locale));
// check result
String expectedToUpperCase = upper;
String expectedToLowerCase = lower;
- if ( LOCALE_TURKISH.getLanguage().equals( locale.getLanguage() ) ||
- new Locale( "az" ).getLanguage().equals( locale.getLanguage() ) )
- {
- expectedToUpperCase = upper.replace( DOTLESS_I, DOTTED_I );
- expectedToLowerCase = lower.replace( DOTTED_i, DOTLESS_i );
+ if (LOCALE_TURKISH.getLanguage().equals(locale.getLanguage())
+ || new Locale("az").getLanguage().equals(locale.getLanguage())) {
+ expectedToUpperCase = upper.replace(DOTLESS_I, DOTTED_I);
+ expectedToLowerCase = lower.replace(DOTTED_i, DOTLESS_i);
}
- assertEquals( "'" + lower + "'.toUpperCase('" + locale.toString() + "')", expectedToUpperCase,
- lower.toUpperCase( locale ) );
- assertEquals( "'" + upper + "'.toLowerCase('" + locale.toString() + "')", expectedToLowerCase,
- upper.toLowerCase( locale ) );
+ assertEquals(
+ "'" + lower + "'.toUpperCase('" + locale.toString() + "')",
+ expectedToUpperCase,
+ lower.toUpperCase(locale));
+ assertEquals(
+ "'" + upper + "'.toLowerCase('" + locale.toString() + "')",
+ expectedToLowerCase,
+ upper.toLowerCase(locale));
// check that toLowerCase on lower and toUpperCase on upper don't cause harm
- assertEquals( "'" + lower + "'.toLowerCase('" + locale.toString() + "')", lower, lower.toLowerCase( locale ) );
- assertEquals( "'" + upper + "'.toUpperCase('" + locale.toString() + "')", upper, upper.toUpperCase( locale ) );
+ assertEquals("'" + lower + "'.toLowerCase('" + locale.toString() + "')", lower, lower.toLowerCase(locale));
+ assertEquals("'" + upper + "'.toUpperCase('" + locale.toString() + "')", upper, upper.toUpperCase(locale));
// check equalsIgnoreCase
- assertTrue( "'" + upper + "'.equalsIgnoreCase('" + lower + "')", upper.equalsIgnoreCase( lower ) );
- assertTrue( "'" + upper + "'.equalsIgnoreCase('" + expectedToLowerCase + "')",
- upper.equalsIgnoreCase( expectedToLowerCase ) );
- assertTrue( "'" + expectedToUpperCase + "'.equalsIgnoreCase('" + lower + "')",
- expectedToUpperCase.equalsIgnoreCase( lower ) );
+ assertTrue("'" + upper + "'.equalsIgnoreCase('" + lower + "')", upper.equalsIgnoreCase(lower));
+ assertTrue(
+ "'" + upper + "'.equalsIgnoreCase('" + expectedToLowerCase + "')",
+ upper.equalsIgnoreCase(expectedToLowerCase));
+ assertTrue(
+ "'" + expectedToUpperCase + "'.equalsIgnoreCase('" + lower + "')",
+ expectedToUpperCase.equalsIgnoreCase(lower));
}
}
}
diff --git a/src/test/java/org/apache/maven/shared/utils/OsTest.java b/src/test/java/org/apache/maven/shared/utils/OsTest.java
index 951c9fc2..e5a321a0 100644
--- a/src/test/java/org/apache/maven/shared/utils/OsTest.java
+++ b/src/test/java/org/apache/maven/shared/utils/OsTest.java
@@ -1,5 +1,3 @@
-package org.apache.maven.shared.utils;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,7 +7,7 @@
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
@@ -18,13 +16,14 @@
* specific language governing permissions and limitations
* under the License.
*/
+package org.apache.maven.shared.utils;
+
+import java.util.Set;
-import org.junit.Test;
-import org.junit.Before;
import org.junit.After;
import org.junit.Assert;
-
-import java.util.Set;
+import org.junit.Before;
+import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -34,156 +33,118 @@
*
* @author Mark Struberg
*/
-public class OsTest
-{
+public class OsTest {
private String origOsName;
private String origOsArch;
private String origOsVersion;
-
@Before
- public void setUp()
- {
- origOsName = System.getProperty( "os.name" );
- origOsArch = System.getProperty( "os.arch" );
- origOsVersion = System.getProperty( "os.version" );
+ public void setUp() {
+ origOsName = System.getProperty("os.name");
+ origOsArch = System.getProperty("os.arch");
+ origOsVersion = System.getProperty("os.version");
// and now set some special settings ;)
- System.setProperty( "os.name" , "os/2" );
- System.setProperty( "os.arch" , "i386" );
- System.setProperty( "os.version", "2.1.32" );
+ System.setProperty("os.name", "os/2");
+ System.setProperty("os.arch", "i386");
+ System.setProperty("os.version", "2.1.32");
}
@After
- public void tearDown()
- {
+ public void tearDown() {
// set the original OS settings again
- System.setProperty( "os.name" , origOsName );
- System.setProperty( "os.arch" , origOsArch );
- System.setProperty( "os.version", origOsVersion );
+ System.setProperty("os.name", origOsName);
+ System.setProperty("os.arch", origOsArch);
+ System.setProperty("os.version", origOsVersion);
}
@Test
- public void testConstructor()
- {
- Os os = new Os();
+ public void testConstructor() {
+ Os os = new Os();
os.eval();
- Assert.assertTrue( Os.isName( Os.FAMILY_OS2 ) );
-
- Assert.assertFalse( Os.isName( Os.FAMILY_DOS ) );
- Assert.assertFalse( Os.isName( Os.FAMILY_MAC ) );
- Assert.assertFalse( Os.isName( Os.FAMILY_NETWARE ) );
- Assert.assertFalse( Os.isName( Os.FAMILY_OPENVMS ) );
- Assert.assertFalse( Os.isName( Os.FAMILY_OS400 ) );
- Assert.assertFalse( Os.isName( Os.FAMILY_TANDEM ) );
- Assert.assertFalse( Os.isName( Os.FAMILY_UNIX ) );
- Assert.assertFalse( Os.isName( Os.FAMILY_WIN9X ) );
- Assert.assertFalse( Os.isName( Os.FAMILY_WINDOWS ) );
- Assert.assertFalse( Os.isName( Os.FAMILY_ZOS ) );
+ Assert.assertTrue(Os.isName(Os.FAMILY_OS2));
+
+ Assert.assertFalse(Os.isName(Os.FAMILY_DOS));
+ Assert.assertFalse(Os.isName(Os.FAMILY_MAC));
+ Assert.assertFalse(Os.isName(Os.FAMILY_NETWARE));
+ Assert.assertFalse(Os.isName(Os.FAMILY_OPENVMS));
+ Assert.assertFalse(Os.isName(Os.FAMILY_OS400));
+ Assert.assertFalse(Os.isName(Os.FAMILY_TANDEM));
+ Assert.assertFalse(Os.isName(Os.FAMILY_UNIX));
+ Assert.assertFalse(Os.isName(Os.FAMILY_WIN9X));
+ Assert.assertFalse(Os.isName(Os.FAMILY_WINDOWS));
+ Assert.assertFalse(Os.isName(Os.FAMILY_ZOS));
}
@Test
- public void testFamilyNames()
- {
- Assert.assertEquals( Os.FAMILY_DOS, "dos" );
- Assert.assertEquals( Os.FAMILY_MAC, "mac" );
- Assert.assertEquals( Os.FAMILY_NETWARE, "netware" );
- Assert.assertEquals( Os.FAMILY_OPENVMS, "openvms" );
- Assert.assertEquals( Os.FAMILY_OS2, "os/2" );
- Assert.assertEquals( Os.FAMILY_OS400, "os/400" );
- Assert.assertEquals( Os.FAMILY_TANDEM, "tandem" );
- Assert.assertEquals( Os.FAMILY_UNIX, "unix" );
- Assert.assertEquals( Os.FAMILY_WIN9X, "win9x" );
- Assert.assertEquals( Os.FAMILY_WINDOWS, "windows" );
- Assert.assertEquals( Os.FAMILY_ZOS, "z/os" );
+ public void testFamilyNames() {
+ Assert.assertEquals(Os.FAMILY_DOS, "dos");
+ Assert.assertEquals(Os.FAMILY_MAC, "mac");
+ Assert.assertEquals(Os.FAMILY_NETWARE, "netware");
+ Assert.assertEquals(Os.FAMILY_OPENVMS, "openvms");
+ Assert.assertEquals(Os.FAMILY_OS2, "os/2");
+ Assert.assertEquals(Os.FAMILY_OS400, "os/400");
+ Assert.assertEquals(Os.FAMILY_TANDEM, "tandem");
+ Assert.assertEquals(Os.FAMILY_UNIX, "unix");
+ Assert.assertEquals(Os.FAMILY_WIN9X, "win9x");
+ Assert.assertEquals(Os.FAMILY_WINDOWS, "windows");
+ Assert.assertEquals(Os.FAMILY_ZOS, "z/os");
}
@Test
- public void testGetValidFamilies()
- {
+ public void testGetValidFamilies() {
SetParagraph 1, line 1. Paragraph 1, line 2.
" ).append( lineSeparator ); - expected.append( StringUtils.repeat( lineIndenter, 2 ) ).append( "Paragraph 1, line 1. Paragraph 1, line 2.
") + .append(lineSeparator); + expected.append(StringUtils.repeat(lineIndenter, 2)) + .append("${project.name} ${project.version} is distributed in source format. Use a source archive if you intend to build - ${project.name} yourself. Otherwise, simply use the ready-made binary artifacts from central repository.
- -You will be prompted for a mirror - if the file is not found on yours, please be patient, as it may take 24 - hours to reach all mirrors.
- -In order to guard against corrupted downloads/installations, it is highly recommended to - verify the signature - of the release bundles against the public KEYS used by the Apache Maven - developers.
+${project.name} ${project.version} is distributed in source format.
-${project.name} is distributed under the Apache License, version 2.0.
+Use a source archive if you intend to build ${project.name} yourself.
- We strongly encourage our users to configure a Maven repository mirror closer to their location, please read How to Use Mirrors for Repositories. - - -
- [if-any logo]
-
-
-
- [end]
- The currently selected mirror is
- [preferred].
- If you encounter a problem with this mirror,
- please select another mirror.
- If all mirrors are failing, there are
- backup
- mirrors
- (at the end of the mirrors list) that should be available.
-
Otherwise, simply use the ready-made binary artifacts from central repository.
- +${project.name} is distributed under the Apache License, version 2.0.
-
- You may also consult the
- complete list of
- mirrors.
+ This is the current stable version of ${project.name}. It is essential that you verify the integrity of the downloaded file
+ using the checksum (.sha512 file)
+ or using the signature (.asc file) against the public KEYS used by the Apache Maven developers.
This is the current stable version of ${project.name}. Older non-recommended releases can be found on our archive site. It is strongly recommended to use the latest release version of ${project.name} to take advantage of the newest features and bug fixes. Older non-recommended releases can be found on our archive site.
+
+
+
+
+
+
+
+
+ Link
+ Checksum
+ Signature
+
+
+
+ ${project.name} ${project.version} (Source zip)
+ ${project.artifactId}-${project.version}-source-release.zip
+ ${project.artifactId}-${project.version}-source-release.zip.sha512
+ ${project.artifactId}-${project.version}-source-release.zip.asc
+
-
-
-
-
-
-
-
- Link
- Checksum
- Signature
-
-
-
- ${project.name} ${project.version} (Source zip)
- maven/shared/${project.artifactId}-${project.version}-source-release.zip
- maven/shared/${project.artifactId}-${project.version}-source-release.zip.sha512
- maven/shared/${project.artifactId}-${project.version}-source-release.zip.asc
-
null
.
+ * Warning: this is not the reverse of {@link #isEmpty}.
+ * Whitespace only strings are both empty and not empty.
+ *
+ * @param str the string to be checked
+ * @return true if the string is not empty (length > 0) and not null
+ * @deprecated use str != null && !str.isEmpty()
*/
+ @Deprecated
public static boolean isNotEmpty(String str) {
return str != null && str.length() > 0;
}
/**
- * @param str The string to be checked.
- * @return true if the string is empty or null
.
+ * Warning: this is not the reverse of {@link #isNotEmpty}.
+ * Whitespace only strings are both empty and not empty.
+ *
+ * @param str the string to be checked
+ * @return true if the string only contains whitespace or is null
+ * @deprecated use str == null || str.trim().isEmpty()
*/
+ @Deprecated
public static boolean isEmpty(String str) {
return str == null || str.trim().length() == 0;
}
From 0dd10e9030a1f29416f68cbdedf053a3993bf4f6 Mon Sep 17 00:00:00 2001
From: Elliotte Rusty Harold