diff -Nru maven-shared-utils-3.3.0/.asf.yaml maven-shared-utils-3.3.4/.asf.yaml --- maven-shared-utils-3.3.0/.asf.yaml 1970-01-01 00:00:00.000000000 +0000 +++ maven-shared-utils-3.3.4/.asf.yaml 2021-04-26 13:54:15.000000000 +0000 @@ -0,0 +1,25 @@ +# +# 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. +# +# see https://s.apache.org/asfyaml +github: + description: "Apache Maven Shared Utils" + homepage: https://maven.apache.org/shared/maven-shared-utils/ + labels: + - java + - build-management + - maven-shared + - maven diff -Nru maven-shared-utils-3.3.0/debian/changelog maven-shared-utils-3.3.4/debian/changelog --- maven-shared-utils-3.3.0/debian/changelog 2018-09-20 17:29:24.000000000 +0000 +++ maven-shared-utils-3.3.4/debian/changelog 2022-06-22 14:48:11.000000000 +0000 @@ -1,3 +1,17 @@ +maven-shared-utils (3.3.4-1) unstable; urgency=high + + * Team upload. + * New upstream version 3.3.4. + - Fix CVE-2022-29599: Apache Maven maven-shared-utils prior to version + 3.3.3, the Commandline class can emit double-quoted strings without + proper escaping, allowing shell injection attacks. (Closes: #1012314) + * Switch to debhelper-compat = 13. + * Declare compliance with Debian Policy 4.6.1. + * Drop 01-backward-compatibility.patch. + * Build-depend on libcommons-text-java. + + -- Markus Koschany Wed, 22 Jun 2022 16:48:11 +0200 + maven-shared-utils (3.3.0-1) unstable; urgency=medium * Team upload. diff -Nru maven-shared-utils-3.3.0/debian/compat maven-shared-utils-3.3.4/debian/compat --- maven-shared-utils-3.3.0/debian/compat 2018-09-20 17:27:53.000000000 +0000 +++ maven-shared-utils-3.3.4/debian/compat 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -11 diff -Nru maven-shared-utils-3.3.0/debian/control maven-shared-utils-3.3.4/debian/control --- maven-shared-utils-3.3.0/debian/control 2018-09-20 17:27:53.000000000 +0000 +++ maven-shared-utils-3.3.4/debian/control 2022-06-22 14:48:11.000000000 +0000 @@ -6,17 +6,18 @@ Jakub Adam , Kai-Chung Yan Build-Depends: - debhelper (>= 11~), + debhelper-compat (= 13), default-jdk, javahelper, junit4, libcommons-lang3-java, - libjansi-java, + libcommons-text-java, + libjansi-java (>= 2.2.0), libjsr305-java, libmaven-javadoc-plugin-java, libmaven-plugin-testing-java, maven-debian-helper (>= 2.2~) -Standards-Version: 4.2.1 +Standards-Version: 4.6.1 Vcs-Git: https://salsa.debian.org/java-team/maven-shared-utils.git Vcs-Browser: https://salsa.debian.org/java-team/maven-shared-utils Homepage: http://maven.apache.org/shared/maven-shared-utils/ diff -Nru maven-shared-utils-3.3.0/debian/libmaven-shared-utils-java-doc.install maven-shared-utils-3.3.4/debian/libmaven-shared-utils-java-doc.install --- maven-shared-utils-3.3.0/debian/libmaven-shared-utils-java-doc.install 2018-09-20 17:27:53.000000000 +0000 +++ maven-shared-utils-3.3.4/debian/libmaven-shared-utils-java-doc.install 2022-06-22 14:48:11.000000000 +0000 @@ -1 +1 @@ -readme.md usr/share/doc/libmaven-shared-utils-java +README.md usr/share/doc/libmaven-shared-utils-java diff -Nru maven-shared-utils-3.3.0/debian/patches/01-backward-compatibility.patch maven-shared-utils-3.3.4/debian/patches/01-backward-compatibility.patch --- maven-shared-utils-3.3.0/debian/patches/01-backward-compatibility.patch 2018-09-20 17:27:53.000000000 +0000 +++ maven-shared-utils-3.3.4/debian/patches/01-backward-compatibility.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,92 +0,0 @@ -Description: Restores the backward compatibility with maven-shared-utils 3.1 - This patch is required to build Maven 3.5.3 with Maven 3.5.2. It can be dropped - once maven/3.5.3-1 is uploaded. -Author: Emmanuel Bourg -Forwarded: no ---- a/src/main/java/org/apache/maven/shared/utils/logging/MessageBuilder.java -+++ b/src/main/java/org/apache/maven/shared/utils/logging/MessageBuilder.java -@@ -27,6 +27,27 @@ - public interface MessageBuilder - { - /** -+ * Append message content for DEBUG level. -+ * By default, bold cyan -+ */ -+ @Deprecated -+ MessageBuilder debug( Object message ); -+ -+ /** -+ * Append message content for INFO level. -+ * By default, bold blue -+ */ -+ @Deprecated -+ MessageBuilder info( Object message ); -+ -+ /** -+ * Append message content for ERROR level. -+ * By default, bold red -+ */ -+ @Deprecated -+ MessageBuilder error( Object message ); -+ -+ /** - * Append message content in success style. - * By default, bold green - */ ---- a/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java -+++ b/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java -@@ -62,6 +62,24 @@ - return a( level ).toString(); - } - -+ @Deprecated -+ public PlainMessageBuilder debug( Object message ) -+ { -+ return a( message ); -+ } -+ -+ @Deprecated -+ public PlainMessageBuilder info( Object message ) -+ { -+ return a( message ); -+ } -+ -+ @Deprecated -+ public PlainMessageBuilder error( Object message ) -+ { -+ return a( message ); -+ } -+ - public PlainMessageBuilder success( Object message ) - { - return a( message ); ---- a/src/main/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilder.java -+++ b/src/main/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilder.java -@@ -70,6 +70,27 @@ - return Style.ERROR.apply( ansi ).a( level ).reset().toString(); - } - -+ @Deprecated -+ public AnsiMessageBuilder debug( Object message ) -+ { -+ Style.DEBUG.apply( ansi ).a( message ).reset(); -+ return this; -+ } -+ -+ @Deprecated -+ public AnsiMessageBuilder info( Object message ) -+ { -+ Style.INFO.apply( ansi ).a( message ).reset(); -+ return this; -+ } -+ -+ @Deprecated -+ public AnsiMessageBuilder error( Object message ) -+ { -+ Style.ERROR.apply( ansi ).a( message ).reset(); -+ return this; -+ } -+ - public AnsiMessageBuilder success( Object message ) - { - Style.SUCCESS.apply( ansi ).a( message ).reset(); diff -Nru maven-shared-utils-3.3.0/debian/patches/series maven-shared-utils-3.3.4/debian/patches/series --- maven-shared-utils-3.3.0/debian/patches/series 2018-09-20 17:27:53.000000000 +0000 +++ maven-shared-utils-3.3.4/debian/patches/series 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -01-backward-compatibility.patch diff -Nru maven-shared-utils-3.3.0/.gitignore maven-shared-utils-3.3.4/.gitignore --- maven-shared-utils-3.3.0/.gitignore 1970-01-01 00:00:00.000000000 +0000 +++ maven-shared-utils-3.3.4/.gitignore 2021-04-26 13:54:15.000000000 +0000 @@ -0,0 +1,17 @@ +target/ +.project +.classpath +.settings/ +.svn/ +bin/ +# Intellij +*.ipr +*.iml +.idea +out/ +.DS_Store +/bootstrap +/dependencies.xml +.java-version +.checkstyle + diff -Nru maven-shared-utils-3.3.0/Jenkinsfile maven-shared-utils-3.3.4/Jenkinsfile --- maven-shared-utils-3.3.0/Jenkinsfile 1970-01-01 00:00:00.000000000 +0000 +++ maven-shared-utils-3.3.4/Jenkinsfile 2021-04-26 13:54:15.000000000 +0000 @@ -0,0 +1,20 @@ +/** + * 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. + */ + +asfMavenTlpStdBuild() diff -Nru maven-shared-utils-3.3.0/pom.xml maven-shared-utils-3.3.4/pom.xml --- maven-shared-utils-3.3.0/pom.xml 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/pom.xml 2021-04-26 13:54:15.000000000 +0000 @@ -23,73 +23,83 @@ org.apache.maven.shared maven-shared-components - 30 - ../../pom/maven/maven-shared-components/pom.xml + 34 maven-shared-utils - 3.3.0 + 3.3.4 Apache Maven Shared Utils - Shared utils without any further dependencies + Shared utilities for use by Maven core and plugins - scm:svn:http://svn.apache.org/repos/asf/maven/shared/tags/maven-shared-utils-3.3.0 - scm:svn:https://svn.apache.org/repos/asf/maven/shared/tags/maven-shared-utils-3.3.0 - - http://svn.apache.org/viewvc/maven/shared/tags/maven-shared-utils-3.3.0 - + 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 + jira - https://issues.apache.org/jira/browse/MSHARED/component/12326452 + https://issues.apache.org/jira/issues/?jql=project%20%3D%20MSHARED%20AND%20component%20%3D%20maven-shared-utils + + Jenkins + https://ci-builds.apache.org/job/Maven/job/maven-box/job/maven-shared-utils/ + apache.website - scm:svn:https://svn.apache.org/repos/infra/websites/production/maven/components/${maven.site.path} + scm:svn:https://svn.apache.org/repos/asf/maven/website/components/${maven.site.path} + + + Kathryn Newbould + + + RedundantThrows,NewlineAtEndOfFile,ParameterNumber,MethodLength,FileLength,ModifierOrder - - 3.0 + 2021-04-26T13:53:43Z + 7 + 3.1.0 org.fusesource.jansi jansi - 1.13 + 2.2.0 true junit junit - 4.11 + 4.13.2 test org.hamcrest hamcrest-core - 1.3 + 2.2 test commons-io commons-io - 2.5 + 2.6 org.apache.commons - commons-lang3 - 3.4 + commons-text + 1.3 test com.google.code.findbugs jsr305 - 3.0.0 + 3.0.2 provided -Apache Maven Shared Utils - -This project aims to be a functional replacement for -plexus-utils in maven core. \ No newline at end of file diff -Nru maven-shared-utils-3.3.0/README.md maven-shared-utils-3.3.4/README.md --- maven-shared-utils-3.3.0/README.md 1970-01-01 00:00:00.000000000 +0000 +++ maven-shared-utils-3.3.4/README.md 2021-04-26 13:54:15.000000000 +0000 @@ -0,0 +1,99 @@ + +Contributing to [Apache Maven Shared Utils](https://maven.apache.org/shared/maven-shared-utils/) +====================== + +[![ASF Jira](https://img.shields.io/endpoint?url=https%3A%2F%2Fmaven.apache.org%2Fbadges%2Fasf_jira-MSHARED.json)][jira] +[![Apache License, Version 2.0, January 2004](https://img.shields.io/github/license/apache/maven.svg?label=License)][license] +[![Maven Central](https://img.shields.io/maven-central/v/org.apache.maven.shared/maven-shared-utils.svg?label=Maven%20Central)](https://search.maven.org/artifact/org.apache.maven.shared/maven-shared-utils) +[![Jenkins Status](https://img.shields.io/jenkins/s/https/ci-builds.apache.org/job/Maven/job/maven-box/job/maven-shared-utils/job/master.svg)][build] +[![Jenkins tests](https://img.shields.io/jenkins/t/https/ci-builds.apache.org/job/Maven/job/maven-box/job/maven-shared-utils/job/master.svg)][test-results] + + +You have found a bug or you have an idea for a cool new feature? Contributing +code is a great way to give something back to the open source community. Before +you dig right into the code, there are a few guidelines that we need +contributors to follow so that we can have a chance of keeping on top of +things. + +Getting Started +--------------- + ++ Make sure you have a [JIRA account](https://issues.apache.org/jira/). ++ Make sure you have a [GitHub account](https://github.com/signup/free). ++ If you're planning to implement a new feature, it makes sense to discuss your changes + on the [dev list][ml-list] first. + This way you can make sure you're not wasting your time on something that isn't + considered to be in Apache Maven's scope. ++ Submit a ticket for your issue, assuming one does not already exist. + + Clearly describe the issue, including steps to reproduce when it is a bug. + + Make sure you fill in the earliest version that you know has the issue. ++ Fork the repository on GitHub. + +Making and Submitting Changes +-------------- + +We accept Pull Requests via GitHub. The [developer mailing list][ml-list] is the +main channel of communication for contributors. +There are some guidelines which will make applying PRs easier for us: ++ Create a topic branch from where you want to base your work (this is usually the master branch). + Push your changes to a topic branch in your fork of the repository. ++ Make commits of logical units. ++ Respect the original code style: by using the same [codestyle][code-style], + patches should only highlight the actual difference, not being disturbed by any formatting issues: + + Only use spaces for indentation. + + Create minimal diffs - disable on save actions like reformat source code or organize imports. + If you feel the source code should be reformatted, create a separate PR for this change. + + Check for unnecessary whitespace with `git diff --check` before committing. ++ Make sure your commit messages are in the proper format. Your commit message should contain the key of the JIRA issue. +``` +[MSHARED-XXX] - Subject of the JIRA Ticket + Optional supplemental description. +``` ++ Make sure you have added the necessary tests (JUnit/IT) for your changes. ++ Run all the tests with `mvn -Prun-its verify` to assure nothing else was accidentally broken. ++ Submit a pull request to the repository in the Apache organization. ++ Update your JIRA ticket and include a link to the pull request in the ticket. + +If you plan to contribute on a regular basis, please consider filing a [contributor license agreement][cla]. + +Making Trivial Changes +---------------------- + +For changes of a trivial nature to comments and documentation, it is not always +necessary to create a new ticket in JIRA. In this case, it is appropriate to +start the first line of a commit with '(doc)' instead of a ticket number. + +Additional Resources +-------------------- + ++ [Contributing patches](https://maven.apache.org/guides/development/guide-maven-development.html#Creating_and_submitting_a_patch) ++ [Apache Maven Shared Components project page][jira] ++ [Contributor License Agreement][cla] ++ [General GitHub documentation](https://help.github.com/) ++ [GitHub pull request documentation](https://help.github.com/send-pull-requests/) ++ [Apache Maven Twitter Account](https://twitter.com/ASFMavenProject) ++ #Maven IRC channel on freenode.org + +[jira]: https://issues.apache.org/jira/projects/MSHARED/ +[license]: https://www.apache.org/licenses/LICENSE-2.0 +[ml-list]: https://maven.apache.org/mailing-lists.html +[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/ diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/Arg.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/Arg.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/Arg.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/Arg.java 2021-04-26 13:54:15.000000000 +0000 @@ -27,24 +27,25 @@ public interface Arg { /** - * @param value Set the value. + * @param value the value to be set */ void setValue( String value ); /** - * @param line The line of arguments. + * @param line the line of arguments + * @throws CommandLineException in case of unbalanced quotes. */ - void setLine( String line ); + void setLine( String line ) throws CommandLineException; /** - * @param value The file to be set. + * @param file the file to be set */ - void setFile( File value ); + void setFile( File file ); /** - * To mask the argument value when a command line ask to print his arguments. + * Whether to hide the argument value when a command line prints the arguments. * - * @param mask new state of the {@code maks} property + * @param mask new state of the {@code mask} property * @since 0.6 */ void setMask( boolean mask ); diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/CommandLineException.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/CommandLineException.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/CommandLineException.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/CommandLineException.java 2021-04-26 13:54:15.000000000 +0000 @@ -21,7 +21,6 @@ /** * @author Trygve Laugstøl - * @version $Id$ */ public class CommandLineException extends Exception diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/Commandline.java 2021-04-26 13:54:15.000000000 +0000 @@ -34,19 +34,17 @@ import org.apache.maven.shared.utils.StringUtils; import org.apache.maven.shared.utils.cli.shell.BourneShell; import org.apache.maven.shared.utils.cli.shell.CmdShell; -import org.apache.maven.shared.utils.cli.shell.CommandShell; 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">
@@ -56,8 +54,7 @@ *   </acommandline>
* </someelement>
*
- *

- *

+ *

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

@@ -70,16 +67,15 @@ { private final List arguments = new Vector(); - //protected Vector envVars = new Vector(); - // synchronized added to preserve synchronize of Vector class private final Map envVars = Collections.synchronizedMap( new LinkedHashMap() ); private Shell shell; /** * Create a new command line object. - * Shell is autodetected from operating system - * @param shell The shell instance. + * Shell is autodetected from operating system. + * + * @param shell the shell instance */ public Commandline( Shell shell ) { @@ -88,23 +84,16 @@ /** * Create a new command line object. - * Shell is autodetected from operating system + * Shell is autodetected from operating system. * - * @param toProcess The command to process + * @param toProcess the command to process + * @throws CommandLineException in case of unbalanced quotes. */ - public Commandline( String toProcess ) + public Commandline( String toProcess ) throws CommandLineException { setDefaultShell(); - String[] tmp = new String[0]; - try - { - tmp = CommandLineUtils.translateCommandline( toProcess ); - } - catch ( Exception e ) - { - System.err.println( "Error translating Commandline." ); - } - if ( ( tmp != null ) && ( tmp.length > 0 ) ) + String[] tmp = CommandLineUtils.translateCommandline( toProcess ); + if ( ( tmp.length > 0 ) ) { setExecutable( tmp[0] ); for ( int i = 1; i < tmp.length; i++ ) @@ -116,7 +105,7 @@ /** * Create a new command line object. - * Shell is autodetected from operating system + * Shell is autodetected from operating system. */ public Commandline() { @@ -124,7 +113,7 @@ } /** - *

Sets 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() @@ -132,14 +121,7 @@ //If this is windows set the shell to command.com or cmd.exe with correct arguments. if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { - if ( Os.isFamily( Os.FAMILY_WIN9X ) ) - { - setShell( new CommandShell() ); - } - else - { - setShell( new CmdShell() ); - } + setShell( new CmdShell() ); } else { @@ -148,13 +130,9 @@ } /** - * Creates an argument object. - *

- *

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

+ * Creates an empty argument object and inserts it at the end of the argument list. * - * @return the argument object. + * @return the argument object */ public Arg createArg() { @@ -162,14 +140,11 @@ } /** - * Creates an argument object and adds it to our list of args. - *

- *

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

+ * Creates an argument object and adds it to 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 ) { @@ -187,7 +162,8 @@ /** * Sets the executable to run. - * @param executable The executable. + * + * @param executable the executable */ public void setExecutable( String executable ) { @@ -195,7 +171,7 @@ } /** - * @return The executable. + * @return the executable */ public String getExecutable() { @@ -204,7 +180,7 @@ } /** - * @param line The arguments. + * @param line the arguments */ public void addArguments( String... line ) { @@ -215,9 +191,10 @@ } /** - * 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 ) { @@ -226,7 +203,7 @@ } /** - * Add system environment variables + * Add system environment variables. */ public void addSystemEnvironment() { @@ -243,26 +220,29 @@ } /** - * 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() { addSystemEnvironment(); - String[] environmentVars = new String[envVars.size()]; - int i = 0; + List environmentVars = new ArrayList<>(); for ( String name : envVars.keySet() ) { String value = envVars.get( name ); - environmentVars[i] = name + "=" + value; - i++; + if ( value != null ) + { + environmentVars.add( name + "=" + value ); + } } - return environmentVars; + return environmentVars.toArray( new String[0] ); } /** * 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() { @@ -280,7 +260,7 @@ } /** - * @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() { @@ -288,7 +268,7 @@ } /** - * @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 */ @@ -310,10 +290,10 @@ /** * Returns all arguments defined by addLine, - * 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 ) { @@ -363,7 +343,8 @@ /** * Sets working directory. - * @param path The to be set as working directory. + * + * @param path the working directory */ public void setWorkingDirectory( String path ) { @@ -371,8 +352,9 @@ } /** - * Sets execution directory. - * @param workingDirectory The working directory. + * Sets working directory. + * + * @param workingDirectory the working directory */ public void setWorkingDirectory( File workingDirectory ) { @@ -380,7 +362,7 @@ } /** - * @return The working directory. + * @return the working directory */ public File getWorkingDirectory() { @@ -396,17 +378,16 @@ } /** - * 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(); @@ -442,7 +423,7 @@ } /** - * 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 */ @@ -453,7 +434,8 @@ /** * Get the shell to be used in this command line. - * @return the shell. + * + * @return the shell */ public Shell getShell() { @@ -461,7 +443,7 @@ } /** - * + * A single command line argument */ public static class Argument implements Arg @@ -484,20 +466,13 @@ /** * {@inheritDoc} */ - public void setLine( String line ) + public void setLine( String line ) throws CommandLineException { if ( line == null ) { return; } - try - { - parts = CommandLineUtils.translateCommandline( line ); - } - catch ( Exception e ) - { - System.err.println( "Error translating Commandline." ); - } + parts = CommandLineUtils.translateCommandline( line ); } /** @@ -517,7 +492,7 @@ } /** - * @return The parts. + * @return the parts */ private String[] getParts() { diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/CommandLineTimeOutException.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/CommandLineTimeOutException.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/CommandLineTimeOutException.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/CommandLineTimeOutException.java 2021-04-26 13:54:15.000000000 +0000 @@ -21,7 +21,6 @@ /** * @author Olivier Lamy - * @version $Id$ * */ public class CommandLineTimeOutException diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/CommandLineUtils.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/CommandLineUtils.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/CommandLineUtils.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/CommandLineUtils.java 2021-04-26 13:54:15.000000000 +0000 @@ -36,7 +36,6 @@ /** * @author Trygve Laugstøl - * @version $Id$ */ public abstract class CommandLineUtils { @@ -277,13 +276,16 @@ if ( systemIn != null ) { inputFeeder = new StreamFeeder( systemIn, p.getOutputStream() ); + inputFeeder.setName( "StreamFeeder-systemIn" ); inputFeeder.start(); } outputPumper = new StreamPumper( p.getInputStream(), systemOut ); + outputPumper.setName( "StreamPumper-systemOut" ); outputPumper.start(); errorPumper = new StreamPumper( p.getErrorStream(), systemErr ); + errorPumper.setName( "StreamPumper-systemErr" ); errorPumper.start(); int returnValue; @@ -419,9 +421,9 @@ * with case-insensitive environment variables like Windows, all variable names will be normalized to upper case. * * @return The shell environment variables, can be empty but never 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 ) ); @@ -433,9 +435,9 @@ * * @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 ) { Map envs = System.getenv(); @@ -477,8 +479,9 @@ final int normal = 0; final int inQuote = 1; final int inDoubleQuote = 2; + boolean inEscape = false; int state = normal; - StringTokenizer tok = new StringTokenizer( toProcess, "\"\' ", true ); + final StringTokenizer tok = new StringTokenizer( toProcess, "\"\' \\", true ); List tokens = new ArrayList(); StringBuilder current = new StringBuilder(); @@ -490,31 +493,65 @@ case inQuote: if ( "\'".equals( nextTok ) ) { - state = normal; + if ( inEscape ) + { + current.append( nextTok ); + inEscape = false; + } + else + { + state = normal; + } } else { current.append( nextTok ); + inEscape = "\\".equals( nextTok ); } break; case inDoubleQuote: if ( "\"".equals( nextTok ) ) { - state = normal; + if ( inEscape ) + { + current.append( nextTok ); + inEscape = false; + } + else + { + state = normal; + } } else { current.append( nextTok ); + inEscape = "\\".equals( nextTok ); } break; default: if ( "\'".equals( nextTok ) ) { - state = inQuote; + if ( inEscape ) + { + inEscape = false; + current.append( nextTok ); + } + else + { + state = inQuote; + } } else if ( "\"".equals( nextTok ) ) { - state = inDoubleQuote; + if ( inEscape ) + { + inEscape = false; + current.append( nextTok ); + } + else + { + state = inDoubleQuote; + } } else if ( " ".equals( nextTok ) ) { @@ -527,6 +564,7 @@ else { current.append( nextTok ); + inEscape = "\\".equals( nextTok ); } break; } @@ -546,8 +584,8 @@ } /** - * @param line The line - * @return The concatenate lines. + * @param line the lines + * @return the concatenated lines, quoted and escaped, separated by spaces */ public static String toString( String... line ) { @@ -557,7 +595,6 @@ return ""; } - // path containing one or more elements final StringBuilder result = new StringBuilder(); for ( int i = 0; i < line.length; i++ ) { @@ -565,14 +602,7 @@ { result.append( ' ' ); } - try - { - result.append( StringUtils.quoteAndEscape( line[i], '\"' ) ); - } - catch ( Exception e ) - { - System.err.println( "Error quoting argument: " + e.getMessage() ); - } + result.append( StringUtils.quoteAndEscape( line[i], '\"' ) ); } return result.toString(); } diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/DefaultConsumer.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/DefaultConsumer.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/DefaultConsumer.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/DefaultConsumer.java 2021-04-26 13:54:15.000000000 +0000 @@ -23,7 +23,6 @@ /** * @author Emmanuel Venisse - * @version $Id$ */ public class DefaultConsumer implements StreamConsumer diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaTool.java 2021-04-26 13:54:15.000000000 +0000 @@ -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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaToolRequest.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaToolRequest.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaToolRequest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/javatool/AbstractJavaToolRequest.java 2021-04-26 13:54:15.000000000 +0000 @@ -24,7 +24,7 @@ /** * Abstract implementation of a {@link JavaToolRequest}. * - * @author Tony Chemit + * @author Tony Chemit * @since 0.5 */ public class AbstractJavaToolRequest diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolException.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolException.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolException.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolException.java 2021-04-26 13:54:15.000000000 +0000 @@ -20,14 +20,13 @@ */ /** - * 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 - * @version $Id$ * @see JavaToolResult#getExitCode() * @since 0.5 */ diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaTool.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaTool.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaTool.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaTool.java 2021-04-26 13:54:15.000000000 +0000 @@ -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 @@ void 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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolRequest.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolRequest.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolRequest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolRequest.java 2021-04-26 13:54:15.000000000 +0000 @@ -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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolResult.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolResult.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolResult.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/javatool/JavaToolResult.java 2021-04-26 13:54:15.000000000 +0000 @@ -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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/shell/BourneShell.java 2021-04-26 13:54:15.000000000 +0000 @@ -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,17 +30,16 @@ public class BourneShell extends Shell { - private static final char[] BASH_QUOTING_TRIGGER_CHARS = - { ' ', '$', ';', '&', '|', '<', '>', '*', '?', '(', ')', '[', ']', '{', '}', '`' }; /** - * Create instance of BournShell. + * Create instance of BourneShell. */ public BourneShell() { + setUnconditionalQuoting( true ); setShellCommand( "/bin/sh" ); setArgumentQuoteDelimiter( '\'' ); - setExecutableQuoteDelimiter( '\"' ); + setExecutableQuoteDelimiter( '\'' ); setSingleQuotedArgumentEscaped( true ); setSingleQuotedExecutableEscaped( false ); setQuotedExecutableEnabled( true ); @@ -57,7 +55,7 @@ return super.getExecutable(); } - return unifyQuotes( super.getExecutable() ); + return quoteOneItem( super.getExecutable(), true ); } /** {@inheritDoc} */ @@ -107,50 +105,33 @@ } String dir = getWorkingDirectoryAsString(); - StringBuilder sb = new StringBuilder(); - sb.append( "cd " ); - sb.append( unifyQuotes( dir ) ); - sb.append( " && " ); - - return sb.toString(); - } - - /** {@inheritDoc} */ - protected char[] getQuotingTriggerChars() - { - return BASH_QUOTING_TRIGGER_CHARS; + return "cd " + quoteOneItem( dir, false ) + " && "; } /** *

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 ); + return "'" + path.replace( "'", "'\"'\"'" ) + "'"; } } diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/shell/CmdShell.java 2021-04-26 13:54:15.000000000 +0000 @@ -23,9 +23,7 @@ import java.util.List; /** - *

- * 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 * @@ -53,7 +51,6 @@ *

* 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
@@ -76,7 +73,6 @@
      *      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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/shell/CommandShell.java 2021-04-26 13:54:15.000000000 +0000 @@ -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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/shell/Shell.java 2021-04-26 13:54:15.000000000 +0000 @@ -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
  • *
- *

* * @author Carlos Sanchez * @@ -50,6 +49,8 @@ private boolean quotedArgumentsEnabled = true; + private boolean unconditionalQuoting = false; + private String executable; private String workingDir; @@ -65,9 +66,9 @@ private char exeQuoteDelimiter = '\"'; /** - * Set the command to execute the shell (eg. COMMAND.COM, /bin/bash,...) + * Set the command to execute the shell (e.g. COMMAND.COM, /bin/bash,...). * - * @param shellCommand The command + * @param shellCommand the command */ void setShellCommand( String shellCommand ) { @@ -75,9 +76,9 @@ } /** - * Get the command to execute the shell + * Get the command to execute the shell. * - * @return The command + * @return the command */ String getShellCommand() { @@ -86,7 +87,7 @@ /** * Set the shell arguments when calling a command line (not the executable arguments) - * (eg. /X /C for CMD.EXE) + * (e.g. /X /C for CMD.EXE). * * @param shellArgs the arguments to the shell */ @@ -99,26 +100,39 @@ /** * Get the shell arguments * - * @return The arguments + * @return the arguments */ String[] getShellArgs() { - if ( ( shellArgs == null ) || shellArgs.isEmpty() ) + if ( shellArgs.isEmpty() ) { return null; } else { - return shellArgs.toArray( new String[shellArgs.size()] ); + return shellArgs.toArray( new String[0] ); } } + 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 * * @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 + * @return list with one String object with executable and arguments quoted as needed */ List getCommandLine( String executableParameter, String... argumentsParameter ) { @@ -126,13 +140,13 @@ } /** - * @param executableParameter Executable. - * @param argumentsParameter The arguments for the executable. - * @return The list on command line. + * @param executableParameter Executable + * @param argumentsParameter the arguments for the executable + * @return the list on command line */ List getRawCommandLine( String executableParameter, String... argumentsParameter ) { - List commandLine = new ArrayList(); + List commandLine = new ArrayList<>(); StringBuilder sb = new StringBuilder(); if ( executableParameter != null ) @@ -145,15 +159,11 @@ 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 ) @@ -165,10 +175,7 @@ if ( isQuotedArgumentsEnabled() ) { - char[] escapeChars = getEscapeChars( isSingleQuotedArgumentEscaped(), isDoubleQuotedArgumentEscaped() ); - - sb.append( StringUtils.quoteAndEscape( argument, getArgumentQuoteDelimiter(), escapeChars, - getQuotingTriggerChars(), '\\', false ) ); + sb.append( quoteOneItem( argument, false ) ); } else { @@ -211,7 +218,7 @@ } /** - * @return false in all cases. + * @return false in all cases */ protected boolean isDoubleQuotedArgumentEscaped() { @@ -273,7 +280,7 @@ public List getShellCommandLine( String... arguments ) { - List commandLine = new ArrayList(); + List commandLine = new ArrayList<>(); if ( getShellCommand() != null ) { @@ -285,7 +292,7 @@ commandLine.addAll( getShellArgsList() ); } - commandLine.addAll( getCommandLine( getExecutable(), arguments ) ); + commandLine.addAll( getCommandLine( executable, arguments ) ); return commandLine; @@ -354,7 +361,8 @@ /** * Sets execution directory. - * @param workingDirectory The working directory. + * + * @param workingDirectory the working directory */ public void setWorkingDirectory( File workingDirectory ) { @@ -365,7 +373,7 @@ } /** - * @return The working directory. + * @return the working directory */ public File getWorkingDirectory() { @@ -398,4 +406,13 @@ this.singleQuotedExecutableEscaped = singleQuotedExecutableEscaped; } + public boolean isUnconditionalQuoting() + { + return unconditionalQuoting; + } + + public void setUnconditionalQuoting( boolean unconditionalQuoting ) + { + this.unconditionalQuoting = unconditionalQuoting; + } } diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/StreamConsumer.java 2021-04-26 13:54:15.000000000 +0000 @@ -22,12 +22,11 @@ import java.io.IOException; /** - * Works in concert with the StreamPumper class to + *

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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/StreamFeeder.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/StreamFeeder.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/StreamFeeder.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/StreamFeeder.java 2021-04-26 13:54:15.000000000 +0000 @@ -28,7 +28,6 @@ * Read from an InputStream and write the output to an OutputStream. * * @author Trygve Laugstøl - * @version $Id$ */ class StreamFeeder extends AbstractStreamHandler diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/WriterStreamConsumer.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/WriterStreamConsumer.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/cli/WriterStreamConsumer.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/cli/WriterStreamConsumer.java 2021-04-26 13:54:15.000000000 +0000 @@ -25,7 +25,7 @@ /** * @author Jason van Zyl - * @version $Id$ + * */ public class WriterStreamConsumer implements StreamConsumer diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/Expand.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/Expand.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/Expand.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/Expand.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,233 +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 java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Date; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -import org.apache.maven.shared.utils.io.FileUtils; -import org.apache.maven.shared.utils.io.IOUtil; - -/** - * Expand will unpack the given zip archive. - * - * @author Mark Struberg - */ -class Expand -{ - /** - * Source file which should get expanded - */ - private File source; - - /** - * destination directory - */ - private File dest; - - /** - * if the unpackaging should get performed if the destination already exists. - */ - private boolean overwrite = false; - - private static final int BUFFER_SIZE = 2 ^ 16; - - - /** - * The zip archive which should get expanded. - * - * @param sourceArchive - */ - public void setSrc( File sourceArchive ) - { - this.source = sourceArchive; - } - - /** - * Set the destination directory into which the archive should get expanded. - * The directory will get created if it doesn't yet exist - * while executing the expand. - * - * @param destinationDirectory - */ - public void setDest( File destinationDirectory ) - { - this.dest = destinationDirectory; - } - - /** - * If the destination directory should get overwritten if the content - * already exists. If 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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/introspection/ClassMap.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/introspection/ClassMap.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/introspection/ClassMap.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/introspection/ClassMap.java 2021-04-26 13:54:15.000000000 +0000 @@ -33,7 +33,7 @@ * @author Bob McWhirter * @author Attila Szegedi * @author Geir Magnusson Jr. - * @version $Id$ + * */ public class ClassMap { @@ -79,16 +79,13 @@ } /** - * Find a Method using the methodKey - * provided. - *

- * Look in the methodMap for an entry. If found, + *

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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/introspection/MethodMap.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/introspection/MethodMap.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/introspection/MethodMap.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/introspection/MethodMap.java 2021-04-26 13:54:15.000000000 +0000 @@ -33,7 +33,7 @@ * @author Christoph Reck * @author Geir Magnusson Jr. * @author Attila Szegedi - * @version $Id$ + * */ class MethodMap { diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractor.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractor.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractor.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractor.java 2021-04-26 13:54:15.000000000 +0000 @@ -36,12 +36,11 @@ /** *

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 * @author Vincent Siveton - * @version $Id$ + * * @see * http://struts.apache.org/1.x/struts-taglib/indexedprops.html */ @@ -146,14 +145,13 @@ /** *

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

    * 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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanner.java 2021-04-26 13:54:15.000000000 +0000 @@ -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; @@ -31,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.separators at the beginning of the pattern and the * string to match:
      * When a pattern starts with a File.separator, the string to match must also start with a * File.separator. When a pattern does not start with a File.separator, the string to match * may not start with a File.separator. When one of these rules is not obeyed, the string will not match. - *

      + *

      + *

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

      + *

      + *

      * Examples: - *

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

      - * "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\\*\\**" };
      @@ -97,17 +104,21 @@
        *     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 * @author Bruce Atherton * @author Antoine Levy-Lambert + * @deprecated use {@code java.nio.file.DirectoryStream} and related classes */ +@Deprecated public class DirectoryScanner { /** @@ -292,8 +303,9 @@ /** * Sets the list of include patterns to use. All '/' and '\' characters are replaced by * File.separatorChar, so the separator used need not match File.separatorChar. - *

      + *

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

      * * @param includes A list of include patterns. May be null, indicating that all files should be * included. If a non-null list is given, all elements must be non-null. @@ -323,8 +335,9 @@ /** * Sets the list of exclude patterns to use. All '/' and '\' characters are replaced by * File.separatorChar, so the separator used need not match File.separatorChar. - *

      + *

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

      * * @param excludes A list of exclude patterns. May be null, indicating that no files should be * excluded. If a non-null list is given, all elements must be non-null. @@ -428,13 +441,15 @@ * 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. @@ -451,9 +466,9 @@ } /** - * @param oldFiles array of old files. - * @param newFiles array of new files. - * @return calculated differerence. + * @param oldFiles array of old files + * @param newFiles array of new files + * @return calculated difference */ public static DirectoryScanResult diffFiles( @Nullable String[] oldFiles, @Nullable String[] newFiles ) { @@ -784,9 +799,11 @@ * Returns the names of the files which matched at least one of the include patterns and none of the exclude * patterns. The names are relative to the base directory. * + * @deprecated this method does not work correctly on Windows. * @return the names of the files which matched at least one of the include patterns and none of the exclude * patterns. May also contain symbolic links to files. */ + @Deprecated public String[] getIncludedFiles() { if ( filesIncluded == null ) @@ -828,9 +845,11 @@ * Returns the names of the directories which matched at least one of the include patterns and none of the exclude * patterns. The names are relative to the base directory. * + * @deprecated this method is buggy. Do not depend on it. * @return the names of the directories which matched at least one of the include patterns and none of the exclude * patterns. May also contain symbolic links to directories. */ + @Deprecated public String[] getIncludedDirectories() { return dirsIncluded.toArray( new String[dirsIncluded.size()] ); @@ -898,13 +917,7 @@ 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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanResult.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanResult.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanResult.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/DirectoryScanResult.java 2021-04-26 13:54:15.000000000 +0000 @@ -23,7 +23,10 @@ /** * Scan for files in a directory at a given time and reports removed and added files * between captures. + * + * @deprecated use {@code java.nio.file.DirectoryStream} and related classes */ +@Deprecated public class DirectoryScanResult { private final String[] filesAdded; diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/DirectoryWalker.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/DirectoryWalker.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/DirectoryWalker.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/DirectoryWalker.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,337 +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 java.util.ArrayList; -import java.util.List; -import java.util.Stack; - -/** - * DirectoryWalker - * - * @version $Id$ - */ -class DirectoryWalker -{ - /** - * DirStackEntry is an Item on the {@link DirectoryWalker#dirStack} - */ - static class DirStackEntry - { - /** - * Count of files in the directory. - */ - private final int count; - - /** - * Current Directory. - */ - private final File dir; - - /** - * Index (or offset) within the directory count. - */ - private int index; - - /** - * Offset for percentage calculations. Based on parent DirStackEntry. - */ - private double percentageOffset; - - /** - * Size of percentage space to work with. - */ - private double percentageSize; - - /** - * Create a DirStackEntry. - * - * @param d the directory to track - * @param length the length of entries in the directory. - */ - DirStackEntry( File d, int length ) - { - dir = d; - count = length; - } - - /** - * Calculate the next percentage offset. Used by the next DirStackEntry. - * - * @return the value for the next percentage offset. - */ - public double getNextPercentageOffset() - { - return percentageOffset + ( index * ( percentageSize / count ) ); - } - - /** - * Calculate the next percentage size. Used by the next DirStackEntry. - * - * @return the value for the next percentage size. - */ - public double getNextPercentageSize() - { - return ( percentageSize / count ); - } - - /** - * The percentage of the DirStackEntry right now. Based on count, index, percentageOffset, and percentageSize. - * - * @return the percentage right now. - */ - public int getPercentage() - { - double percentageWithinDir = (double) index / (double) count; - return (int) Math.floor( percentageOffset + ( percentageWithinDir * percentageSize ) ); - } - - public String toString() - { - return "DirStackEntry[" + "dir=" + dir.getAbsolutePath() + ",count=" + count + ",index=" + index - + ",percentageOffset=" + percentageOffset + ",percentageSize=" + percentageSize + ",percentage()=" - + getPercentage() + ",getNextPercentageOffset()=" + getNextPercentageOffset() - + ",getNextPercentageSize()=" + getNextPercentageSize() + "]"; - } - } - - private File baseDir; - - private int baseDirOffset; - - private Stack dirStack; - - private final List excludes; - - private final List includes; - - private final List listeners; - - DirectoryWalker() - { - this.includes = new ArrayList(); - this.excludes = new ArrayList(); - this.listeners = new ArrayList(); - } - - public void addDirectoryWalkListener( DirectoryWalkListener listener ) - { - this.listeners.add( listener ); - } - - void addExclude( String exclude ) - { - this.excludes.add( fixPattern( exclude ) ); - } - - void addInclude( String include ) - { - this.includes.add( fixPattern( include ) ); - } - - /** - * Add's to the Exclude List the default list of SCM excludes. - */ - public void addSCMExcludes() - { - String scmexcludes[] = DirectoryScanner.DEFAULTEXCLUDES; - for ( String scmexclude : scmexcludes ) - { - addExclude( scmexclude ); - } - } - - private void fireStep( File file ) - { - DirStackEntry dsEntry = dirStack.peek(); - int percentage = dsEntry.getPercentage(); - for ( DirectoryWalkListener listener : this.listeners ) - { - listener.directoryWalkStep( percentage, file ); - } - } - - private void fireWalkFinished() - { - for ( Object listener1 : this.listeners ) - { - DirectoryWalkListener listener = (DirectoryWalkListener) listener1; - listener.directoryWalkFinished(); - } - } - - private void fireWalkStarting() - { - for ( Object listener1 : this.listeners ) - { - DirectoryWalkListener listener = (DirectoryWalkListener) listener1; - listener.directoryWalkStarting( this.baseDir ); - } - } - - private void fireDebugMessage( String message ) - { - for ( Object listener1 : this.listeners ) - { - DirectoryWalkListener listener = (DirectoryWalkListener) listener1; - listener.debug( message ); - } - } - - private String fixPattern( String pattern ) - { - String cleanPattern = pattern; - - if ( File.separatorChar != '/' ) - { - cleanPattern = cleanPattern.replace( '/', File.separatorChar ); - } - - if ( File.separatorChar != '\\' ) - { - cleanPattern = cleanPattern.replace( '\\', File.separatorChar ); - } - - return cleanPattern; - } - - private boolean isExcluded( String name ) - { - return isMatch( this.excludes, name ); - } - - private boolean isIncluded( String name ) - { - return isMatch( this.includes, name ); - } - - private boolean isMatch( List patterns, String name ) - { - for ( String pattern : patterns ) - { - boolean caseSensitive = true; - if ( SelectorUtils.matchPath( pattern, name, caseSensitive ) ) - { - return true; - } - } - - return false; - } - - private String relativeToBaseDir( File file ) - { - return file.getAbsolutePath().substring( baseDirOffset + 1 ); - } - - /** - * Performs a Scan against the provided {@link #setBaseDir(File)} - */ - public void scan() - { - if ( baseDir == null ) - { - throw new IllegalStateException( "Scan Failure. BaseDir not specified." ); - } - - if ( !baseDir.exists() ) - { - throw new IllegalStateException( "Scan Failure. BaseDir does not exist." ); - } - - if ( !baseDir.isDirectory() ) - { - throw new IllegalStateException( "Scan Failure. BaseDir is not a directory." ); - } - - if ( this.includes.isEmpty() ) - { - // default to include all. - addInclude( "**" ); - } - - fireWalkStarting(); - dirStack = new Stack(); - scanDir( this.baseDir ); - fireWalkFinished(); - } - - private void scanDir( File dir ) - { - File files[] = dir.listFiles(); - - if ( files == null ) - { - return; - } - - DirStackEntry curStackEntry = new DirStackEntry( dir, files.length ); - if ( dirStack.isEmpty() ) - { - curStackEntry.percentageOffset = 0; - curStackEntry.percentageSize = 100; - } - else - { - DirStackEntry previousStackEntry = dirStack.peek(); - curStackEntry.percentageOffset = previousStackEntry.getNextPercentageOffset(); - curStackEntry.percentageSize = previousStackEntry.getNextPercentageSize(); - } - - dirStack.push( curStackEntry ); - - for ( int idx = 0; idx < files.length; idx++ ) - { - curStackEntry.index = idx; - String name = relativeToBaseDir( files[idx] ); - - if ( isExcluded( name ) ) - { - fireDebugMessage( name + " is excluded." ); - continue; - } - - if ( files[idx].isDirectory() ) - { - scanDir( files[idx] ); - } - else - { - if ( isIncluded( name ) ) - { - fireStep( files[idx] ); - } - } - } - - dirStack.pop(); - } - - /** - * @param baseDir The baseDir to set. - */ - public void setBaseDir( File baseDir ) - { - this.baseDir = baseDir; - this.baseDirOffset = baseDir.getAbsolutePath().length(); - } - -} diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/DirectoryWalkListener.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/DirectoryWalkListener.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/DirectoryWalkListener.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/DirectoryWalkListener.java 2021-04-26 13:54:15.000000000 +0000 @@ -22,16 +22,17 @@ import java.io.File; /** - * DirectoryWalkListener - * - * @version $Id$ + * DirectoryWalkListener. + * + * @deprecated use {@code java.nio.file.FileVisitor} and related classes */ +@Deprecated public interface DirectoryWalkListener { /** * The directory walking has begun. * - * @param basedir the basedir that walk started in. + * @param basedir the basedir that walk started in */ void directoryWalkStarting( File basedir ); @@ -39,7 +40,7 @@ * The included entry that was encountered. * * @param percentage rough percentage of the walk completed. (inaccurate) - * @param file the file that was included. + * @param file the file that was included */ void directoryWalkStep( int percentage, File file ); @@ -49,7 +50,7 @@ void directoryWalkFinished(); /** - * @param message The message for the debugging output. + * @param message the message for the debugging output */ void debug( String message ); } diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/FileUtils.java 2021-04-26 13:54:15.000000000 +0000 @@ -19,6 +19,7 @@ * under the License. */ +import org.apache.commons.io.IOUtils; import org.apache.maven.shared.utils.Os; import org.apache.maven.shared.utils.StringUtils; @@ -30,53 +31,58 @@ import java.io.File; 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; 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.nio.file.Path; import java.security.SecureRandom; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Objects; import java.util.Random; /** * This class provides basic facilities for manipulating files and file paths. - *

      + * *

      Path-related methods

      - *

      - *

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

        *
      • /www/hosted/mysite/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 - * copy a {@link #copyFile File to another File}, + * + *

      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 @@ -84,7 +90,6 @@ * @author Christoph.Reck * @author Peter Donald * @author Jeff Turner - * @version $Id$ */ public class FileUtils { @@ -93,7 +98,7 @@ */ protected FileUtils() { - // This is a utility class. Normally dont instantiate + // This is a utility class. Normally don't instantiate } /** @@ -107,14 +112,9 @@ private static final int ONE_MB = ONE_KB * ONE_KB; /** - * The number of bytes in a gigabyte. - */ - private static final int ONE_GB = ONE_KB * ONE_MB; - - /** * 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 @@ -139,7 +139,7 @@ } /** - * @return the default excludes pattern as list. + * @return the default excludes pattern as list * @see #getDefaultExcludes() */ @Nonnull public static List getDefaultExcludesAsList() @@ -161,47 +161,52 @@ * Returns the directory path portion of a file specification string. * Matches the equally named unix command. * - * @param filename the file path - * @return The directory portion excluding the ending file separator. + * @param path the file path + * @return the directory portion excluding the ending file separator + * @deprecated use {@code Paths.get(path).getParent().getName()} */ - @Nonnull public static String dirname( @Nonnull String filename ) + @Deprecated + @Nonnull public static String dirname( @Nonnull String path ) { - int i = filename.lastIndexOf( File.separator ); - return ( i >= 0 ? filename.substring( 0, i ) : "" ); + int i = path.lastIndexOf( File.separator ); + return ( i >= 0 ? path.substring( 0, i ) : "" ); } /** - * Returns the filename portion of a file specification string. + * Returns the filename portion of a path. * - * @param filename the file path - * @return The filename string with extension. + * @param path the file path + * @return the filename string with extension + * @deprecated use {@code Paths.get(path).getName()} */ - @Nonnull public static String filename( @Nonnull String filename ) + @Deprecated + @Nonnull public static String filename( @Nonnull String path ) { - int i = filename.lastIndexOf( File.separator ); - return ( i >= 0 ? filename.substring( i + 1 ) : filename ); + int i = path.lastIndexOf( File.separator ); + return ( i >= 0 ? path.substring( i + 1 ) : path ); } /** - * Returns the extension portion of a file specification string. - * This everything after the last dot '.' in the filename (NOT including - * the dot). + * Returns the extension portion of a file path. + * This is everything after the last dot '.' in the path (NOT including the dot). * - * @param filename the file path + * @param path the file path * @return the extension of the file + * @deprecated use {@code org.apache.commons.io.FilenameUtils.getExtension} */ - @Nonnull public static String extension( @Nonnull String filename ) + @Deprecated + @Nonnull public static String extension( @Nonnull String path ) { // Ensure the last dot is after the last file separator - int lastSep = filename.lastIndexOf( File.separatorChar ); + int lastSep = path.lastIndexOf( File.separatorChar ); int lastDot; if ( lastSep < 0 ) { - lastDot = filename.lastIndexOf( '.' ); + lastDot = path.lastIndexOf( '.' ); } else { - lastDot = filename.substring( lastSep + 1 ).lastIndexOf( '.' ); + lastDot = path.substring( lastSep + 1 ).lastIndexOf( '.' ); if ( lastDot >= 0 ) { lastDot += lastSep + 1; @@ -210,18 +215,20 @@ if ( lastDot >= 0 && lastDot > lastSep ) { - return filename.substring( lastDot + 1 ); + return path.substring( lastDot + 1 ); } return ""; } /** - * Check if a file exits. + * Check if a file exists. * - * @param fileName the file path. - * @return true if file exists. + * @param fileName the file path + * @return true if file exists + * @deprecated use {@code java.io.File.exists()} */ + @Deprecated public static boolean fileExists( @Nonnull String fileName ) { File file = new File( fileName ); @@ -232,9 +239,11 @@ * Note: the file content is read with platform encoding. * * @param file the file path - * @return the file content using the platform encoding. + * @return the file content using the platform encoding * @throws IOException if any + * @deprecated use {@code new String(java.nio.files.Files.readAllBytes(file))} */ + @Deprecated @Nonnull public static String fileRead( @Nonnull String file ) throws IOException { @@ -244,9 +253,11 @@ /** * @param file the file path * @param encoding the wanted encoding - * @return the file content using the specified encoding. + * @return the file content using the specified encoding * @throws IOException if any + * @deprecated use {@code new String(java.nio.files.Files.readAllBytes(Paths.get(file)), encoding)} */ + @Deprecated @Nonnull private static String fileRead( @Nonnull String file, @Nullable String encoding ) throws IOException { @@ -254,12 +265,14 @@ } /** - * Note: the file content is read with platform encoding + * Note: the file content is read with platform encoding. * * @param file the file path - * @return the file content using the platform encoding. + * @return the file content using the platform encoding * @throws IOException if any + * @deprecated use {@code new String(java.nio.files.Files.readAllBytes(file.toPath()))} */ + @Deprecated @Nonnull public static String fileRead( @Nonnull File file ) throws IOException { @@ -269,38 +282,27 @@ /** * @param file the file path * @param encoding the wanted encoding - * @return the file content using the specified encoding. + * @return the file content using the specified encoding * @throws IOException if any + * @deprecated use {@code new String(java.nio.files.Files.readAllBytes(file.toPath()), encoding)} */ + @Deprecated @Nonnull public static String fileRead( @Nonnull File file, @Nullable String encoding ) throws IOException { + Charset charset = charset( encoding ); + StringBuilder buf = new StringBuilder(); - Reader reader = null; - try + try ( Reader reader = Files.newBufferedReader( file.toPath(), charset ) ) { - 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(); @@ -308,10 +310,12 @@ /** * @param file the file path - * @return the file content lines as String[] using the systems default encoding. - * An empty List if the file didn't exist. - * @throws IOException in case of failure. + * @return the file content lines as String[] using the system default encoding. + * An empty List if the file doesn't exist. + * @throws IOException in case of failure + * @deprecated use {@code java.nio.files.Files.readAllLines()} */ + @Deprecated @Nonnull public static String[] fileReadArray( @Nonnull File file ) throws IOException { @@ -321,13 +325,16 @@ } /** - * Appends data to a file. The file will be created if it does not exist. - * Note: the data is written with platform encoding + * Appends data to a file. The file is created if it does not exist. + * Note: the data is written with platform encoding. * - * @param fileName The path of the file to write. - * @param data The content to write to the file. + * @param fileName the path of the file to write + * @param data the content to write to the file * @throws IOException if any + * @deprecated use {@code java.nio.files.Files.write(filename, data.getBytes(), + * StandardOpenOption.APPEND, StandardOpenOption.CREATE)} */ + @Deprecated public static void fileAppend( @Nonnull String fileName, @Nonnull String data ) throws IOException { @@ -337,32 +344,22 @@ /** * Appends data to a file. The file will be created if it does not exist. * - * @param fileName The path of the file to write. - * @param encoding The encoding of the file. - * @param data The content to write to the file. + * @param fileName the path of the file to write + * @param encoding the encoding of the file + * @param data the content to write to the file * @throws IOException if any + * @deprecated use {@code java.nio.files.Files.write(filename, data.getBytes(encoding), + * StandardOpenOption.APPEND, StandardOpenOption.CREATE)} */ + @Deprecated public static void fileAppend( @Nonnull String fileName, @Nullable String encoding, @Nonnull String data ) throws IOException { - FileOutputStream out = null; - try - { - out = new FileOutputStream( fileName, true ); - if ( encoding != null ) - { - out.write( data.getBytes( encoding ) ); - } - else - { - out.write( data.getBytes() ); - } - out.close(); - out = null; - } - finally + Charset charset = charset( encoding ); + + try ( OutputStream out = new FileOutputStream( fileName, true ) ) { - IOUtil.close( out ); + out.write( data.getBytes( charset ) ); } } @@ -370,10 +367,13 @@ * Writes data to a file. The file will be created if it does not exist. * Note: the data is written with platform encoding * - * @param fileName The path of the file to write. - * @param data The content to write to the file. + * @param fileName the path of the file to write + * @param data the content to write to the file * @throws IOException if any + * @deprecated use {@code java.nio.files.Files.write(filename, + * data.getBytes(), StandardOpenOption.CREATE)} */ + @Deprecated public static void fileWrite( @Nonnull String fileName, @Nonnull String data ) throws IOException { @@ -383,11 +383,14 @@ /** * Writes data to a file. The file will be created if it does not exist. * - * @param fileName The path of the file to write. - * @param encoding The encoding of the file. - * @param data The content to write to the file. + * @param fileName the path of the file to write + * @param encoding the encoding of the file + * @param data the content to write to the file * @throws IOException if any + * @deprecated use {@code java.nio.files.Files.write(Paths.get(filename), + * data.getBytes(encoding), StandardOpenOption.CREATE)} */ + @Deprecated public static void fileWrite( @Nonnull String fileName, @Nullable String encoding, @Nonnull String data ) throws IOException { @@ -398,32 +401,22 @@ /** * Writes data to a file. The file will be created if it does not exist. * - * @param file The path of the file to write. - * @param encoding The encoding of the file. - * @param data The content to write to the file. + * @param file the path of the file to write + * @param encoding the encoding of the file + * @param data the content to write to the file * @throws IOException if any + * @deprecated use {@code java.nio.files.Files.write(file.toPath(), + * data.getBytes(encoding), StandardOpenOption.CREATE)} */ + @Deprecated public static void fileWrite( @Nonnull File file, @Nullable String encoding, @Nonnull String data ) throws IOException { - Writer writer = null; - try + Charset charset = charset( encoding ); + + try ( Writer writer = Files.newBufferedWriter( file.toPath(), charset ) ) { - if ( encoding != null ) - { - writer = new OutputStreamWriter( new FileOutputStream( file ), encoding ); - } - else - { - writer = new OutputStreamWriter( new FileOutputStream( file ) ); - } writer.write( data ); - writer.close(); - writer = null; - } - finally - { - IOUtil.close( writer ); } } @@ -431,10 +424,13 @@ * Writes String array data to a file in the systems default encoding. * The file will be created if it does not exist. * - * @param file The path of the file to write. - * @param data The content to write to the file. + * @param file the path of the file to write + * @param data the content to write to the file * @throws IOException if any + * @deprecated use {@code java.nio.files.Files.write(file.toPath(), + * data.getBytes(encoding), StandardOpenOption.CREATE)} */ + @Deprecated public static void fileWriteArray( @Nonnull File file, @Nullable String... data ) throws IOException { @@ -442,28 +438,23 @@ } /** - * Writes String array data to a file. The file will be created if it does not exist. + * Writes String array data to a file. The file is created if it does not exist. * - * @param file The path of the file to write. - * @param encoding The encoding of the file. - * @param data The content to write to the file. + * @param file the path of the file to write + * @param encoding the encoding of the file + * @param data the content to write to the file * @throws IOException if any + * @deprecated use {@code java.nio.files.Files.write(file.toPath(), + * data.getBytes(encoding), StandardOpenOption.CREATE)} */ + @Deprecated public static void fileWriteArray( @Nonnull File file, @Nullable String encoding, @Nullable String... data ) throws IOException { - Writer writer = null; - try - { - if ( encoding != null ) - { - writer = new OutputStreamWriter( new FileOutputStream( file ), encoding ); - } - else - { - writer = new OutputStreamWriter( new FileOutputStream( file ) ); - } + Charset charset = charset( encoding ); + try ( Writer writer = Files.newBufferedWriter( file.toPath(), charset ) ) + { for ( int i = 0; data != null && i < data.length; i++ ) { writer.write( data[i] ); @@ -472,21 +463,16 @@ writer.write( "\n" ); } } - - writer.close(); - writer = null; - } - finally - { - IOUtil.close( writer ); } } /** * Deletes a file. * - * @param fileName The path of the file to delete. + * @param fileName the path of the file to delete + * @deprecated use {@code Files.delete(Paths.get(fileName))} */ + @Deprecated public static void fileDelete( @Nonnull String fileName ) { File file = new File( fileName ); @@ -496,15 +482,12 @@ /** * Given a directory and an array of extensions return an array of compliant files. - *

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

      - * The given extensions should be like "java" and not like ".java" - * - * @param directory The path of the directory. - * @param extensions an array of expected extensions. - * @return An array of files for the wanted extensions. + * + *

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

      + * + * @param directory the path of the directory + * @param extensions an array of expected extensions + * @return an array of files for the wanted extensions */ public static String[] getFilesFromExtension( @Nonnull String directory, @Nonnull String... extensions ) { @@ -532,7 +515,7 @@ continue; } - // ok... transverse into this directory and get all the files... then combine + // ok... traverse into this directory and get all the files... then combine // them with the current list. String[] fetchFiles = getFilesFromExtension( currentFileName, extensions ); @@ -592,12 +575,14 @@ } /** - * Simple way to make a directory + * Simple way to make a directory. * * @param dir the directory to create - * @throws IllegalArgumentException if the dir contains illegal Windows characters under Windows OS. + * @throws IllegalArgumentException if the dir contains illegal Windows characters under Windows OS * @see #INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME + * @deprecated use {@code java.nio.file.Files.createDirectories(Paths.get(dir))} */ + @Deprecated public static void mkdir( @Nonnull String dir ) { File file = new File( dir ); @@ -645,33 +630,19 @@ 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 IOUtils.contentEquals( input1, input2 ); } - finally - { - IOUtil.close( input1 ); - IOUtil.close( input2 ); - } - return equals; } /** * Convert from a 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 ) { @@ -715,17 +686,18 @@ } /** - * Remove extension from filename. - * ie + * 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 * @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 ); @@ -740,17 +712,19 @@ } /** - * Get extension from filename. - * ie + * 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 * @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 ); @@ -761,20 +735,22 @@ * (and any parent directories) will be created. If a file source in * destinationDirectory exists, it will be overwritten. * - * @param source An existing File to copy. - * @param destinationDirectory A directory to copy source into. - * @throws java.io.FileNotFoundException if source isn't a normal file. - * @throws IllegalArgumentException if destinationDirectory isn't a directory. + * @param source an existing File to copy + * @param destinationDirectory a directory to copy source into + * @throws java.io.FileNotFoundException if source isn't a normal file + * @throws IllegalArgumentException if 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 public static void copyFileToDirectory( @Nonnull final File source, @Nonnull final File destinationDirectory ) throws IOException { if ( destinationDirectory.exists() && !destinationDirectory.isDirectory() ) { - throw new IllegalArgumentException( "Destination is not a directory" ); + throw new IOException( "Destination is not a directory" ); } copyFile( source, new File( destinationDirectory, source.getName() ) ); @@ -783,16 +759,16 @@ /** * Copy file from source to destination only if source is newer than the target file. * If destinationDirectory does not exist, it - * (and any parent directories) will be created. If a file source in - * destinationDirectory exists, it will be overwritten. + * (and any parent directories) is created. If a file source in + * destinationDirectory exists, it is overwritten. * - * @param source An existing File to copy. - * @param destinationDirectory A directory to copy source into. - * @throws java.io.FileNotFoundException if source isn't a normal file. - * @throws IllegalArgumentException if destinationDirectory isn't a directory. + * @param source an existing File to copy + * @param destinationDirectory a directory to copy source into + * @throws java.io.FileNotFoundException if source isn't a normal file + * @throws IllegalArgumentException if 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 */ private static void copyFileToDirectoryIfModified( @Nonnull final File source, @Nonnull final File destinationDirectory ) @@ -812,13 +788,16 @@ * created if they don't already exist. destination will be overwritten if it * already exists. * - * @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. + * @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 java.io.FileNotFoundException if destination is a directory + * @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 ) throws IOException { @@ -828,10 +807,10 @@ 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; } @@ -866,16 +845,13 @@ 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; @@ -884,22 +860,9 @@ 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 ); } + + copyFilePermissions( source, destination ); } /** @@ -910,7 +873,7 @@ * @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. */ @@ -932,15 +895,17 @@ * 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 opened
      • *
      • destination cannot be written to
      • *
      • an IO error occurs during copying
      • *
      + * @deprecated use {@code java.nio.Files.copy(source.openStream(), destination.toPath(), + * StandardCopyOption.REPLACE_EXISTING)} */ public static void copyURLToFile( @Nonnull final URL source, @Nonnull final File destination ) throws IOException @@ -953,50 +918,41 @@ * The directories up to destination 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 URL cannot be opened
      • + *
      • source cannot be opened
      • *
      • destination cannot be written to
      • - *
      • an IO error occurs during copying
      • + *
      • an I/O error occurs during copying
      • *
      + * @deprecated use {@code java.nio.Files.copy(source, destination.toPath(), + * StandardCopyOption.REPLACE_EXISTING)} */ + @Deprecated private static void copyStreamToFile( @Nonnull @WillClose final InputStream source, @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 ); } } @@ -1006,18 +962,20 @@ * 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 - * @return the normalized String, or null if too many ..'s. + * @return the normalized String, or null 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; @@ -1064,14 +1022,13 @@ } /** - * Resolve a file 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. - * - * @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. + * 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 + * @return the canonical File of filename */ @Nonnull public static File resolveFile( final File baseFile, @Nonnull String filename ) { @@ -1145,11 +1102,13 @@ } /** - * 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 { @@ -1157,11 +1116,13 @@ } /** - * 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 { @@ -1185,50 +1146,35 @@ } /** - * deletes a file. + * Deletes a file. * - * @param file The file to delete - * @throws IOException If the file cannot be delted. + * @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 { - if ( Java7Support.isAtLeastJava7() ) - { - Java7Support.delete( file ); - } - else - { - if ( !file.delete() ) - { - throw new IOException( "Could not delete " + file.getName() ); - } - } + Files.delete( file.toPath() ); } /** - * @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 ) { - 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; } } @@ -1274,8 +1220,7 @@ * Make a directory. * * @param file not null - * @throws IOException If there already exists a file with specified name or - * the directory is unable to be created + * @throws IOException if a file already exists with the specified name or the directory is unable to be created * @throws IllegalArgumentException if the file contains illegal Windows characters under Windows OS. * @see #INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME */ @@ -1313,7 +1258,9 @@ * * @param directory a directory * @throws IOException if any + * @deprecated use {@code org.apache.commons.io.FileUtils.deleteDirectory()} */ + @Deprecated public static void deleteDirectory( @Nonnull final String directory ) throws IOException { @@ -1325,7 +1272,9 @@ * * @param directory a directory * @throws IOException if any + * @deprecated use {@code org.apache.commons.io.FileUtils.deleteDirectory()} */ + @Deprecated public static void deleteDirectory( @Nonnull final File directory ) throws IOException { @@ -1351,11 +1300,14 @@ } /** - * Clean a directory without deleting it. + * Remove all files from a directory without deleting it. * * @param directory a directory - * @throws IOException if any + * @throws IOException if any. This can leave cleaning in a half-finished state where + * some but not all files have been deleted. + * @deprecated use {@code org.apache.commons.io.FileUtils.cleanDirectory()} */ + @Deprecated public static void cleanDirectory( @Nonnull final File directory ) throws IOException { @@ -1402,8 +1354,10 @@ * Recursively count size of a directory. * * @param directory a directory - * @return size of directory in bytes. + * @return size of directory in bytes + * @deprecated use {@code org.apache.commons.io.FileUtils.sizeOf()} */ + @Deprecated public static long sizeOfDirectory( @Nonnull final String directory ) { return sizeOfDirectory( new File( directory ) ); @@ -1413,8 +1367,10 @@ * Recursively count size of a directory. * * @param directory a directory - * @return size of directory in bytes. + * @return size of directory in bytes + * @deprecated use {@code org.apache.commons.io.FileUtils.sizeOf()} */ + @Deprecated public static long sizeOfDirectory( @Nonnull final File directory ) { if ( !directory.exists() ) @@ -1457,8 +1413,8 @@ * including the directory name in each of the files * * @param directory the directory to scan - * @param includes the includes pattern, comma separated - * @param excludes the excludes pattern, comma separated + * @param includes the Ant includes pattern, comma separated + * @param excludes the Ant excludes pattern, comma separated * @return a list of File objects * @throws IOException in case of failure. * @see #getFileNames(File, String, String, boolean) @@ -1503,11 +1459,11 @@ * This method use case sensitive file name. * * @param directory the directory to scan - * @param includes the includes pattern, comma separated - * @param excludes the excludes pattern, comma separated - * @param includeBasedir true to include the base dir in each String of file - * @return a list of files as String - * @throws IOException in case of failure. + * @param includes the Ant includes pattern, comma separated + * @param excludes the Ant excludes pattern, comma separated + * @param includeBasedir true to include the base directory in each String of file + * @return a list of file names + * @throws IOException in case of failure */ @Nonnull public static List getFileNames( @Nonnull File directory, @Nullable String includes, @Nullable String excludes, boolean includeBasedir ) @@ -1520,8 +1476,8 @@ * Return a list of files as String depending options. * * @param directory the directory to scan - * @param includes the includes pattern, comma separated - * @param excludes the excludes pattern, comma separated + * @param includes the Ant includes pattern, comma separated + * @param excludes the Ant excludes pattern, comma separated * @param includeBasedir true to include the base dir in each String of file * @param isCaseSensitive true if case sensitive * @return a list of files as String @@ -1540,8 +1496,8 @@ * This method use case sensitive file name. * * @param directory the directory to scan - * @param includes the includes pattern, comma separated - * @param excludes the excludes pattern, comma separated + * @param includes the Ant includes pattern, comma separated + * @param excludes the Ant excludes pattern, comma separated * @param includeBasedir true to include the base dir in each String of file * @return a list of directories as String * @throws IOException in case of failure. @@ -1554,15 +1510,15 @@ } /** - * Return a list of directories as String depending options. + * Return a list of directories as Strings. * * @param directory the directory to scan - * @param includes the includes pattern, comma separated - * @param excludes the excludes pattern, comma separated - * @param includeBasedir true to include the base dir in each String of file + * @param includes the Ant includes pattern, comma separated + * @param excludes the Ant excludes pattern, comma separated + * @param includeBasedir true to include the base directory in each String of file * @param isCaseSensitive true if case sensitive * @return a list of directories as String - * @throws IOException in case of failure. + * @throws IOException in case of failure */ @Nonnull public static List getDirectoryNames( @Nonnull File directory, @Nullable String includes, @Nullable String excludes, boolean includeBasedir, @@ -1573,16 +1529,16 @@ } /** - * Return a list of files as String depending options. + * Return a list of file names as Strings. * * @param directory the directory to scan - * @param includes the includes pattern, comma separated - * @param excludes the excludes pattern, comma separated - * @param includeBasedir true to include the base dir in each String of file + * @param includes the Ant includes pattern, comma separated + * @param excludes the Ant excludes pattern, comma separated + * @param includeBasedir true to include the base directory in each String of file * @param isCaseSensitive true if case sensitive - * @param getFiles true if get files - * @param getDirectories true if get directories - * @return a list of files as String + * @param getFiles true to include regular files + * @param getDirectories true to include directories + * @return a list of file names */ @Nonnull public static List getFileAndDirectoryNames( File directory, @Nullable String includes, @Nullable String excludes, boolean includeBasedir, @@ -1647,28 +1603,46 @@ } /** - * Copy a directory to an other one. + * Copy the contents of a directory into another one. * - * @param sourceDirectory the source dir - * @param destinationDirectory the target dir + * @param sourceDirectory the source directory. If the source does not exist, + * the method simply returns. + * @param destinationDirectory the target directory; will be created if it doesn't exist * @throws IOException if any + * @deprecated use {@code org.apache.commons.io.FileUtils.copyDirectory()} */ + @Deprecated public static void copyDirectory( @Nonnull File sourceDirectory, @Nonnull File destinationDirectory ) throws IOException { - copyDirectory( sourceDirectory, destinationDirectory, "**", null ); + Objects.requireNonNull( sourceDirectory ); + Objects.requireNonNull( destinationDirectory ); + if ( destinationDirectory.equals( sourceDirectory ) ) + { + throw new IOException( "Can't copy directory " + sourceDirectory + " to itself." ); + } + else if ( !destinationDirectory.exists() ) + { + if ( !destinationDirectory.mkdirs() ) + { + throw new IOException( "Can't create directory " + destinationDirectory ); + } + } + copyDirectoryStructure( sourceDirectory, destinationDirectory ); } /** - * Copy a directory to an other one. + * Copy the contents of a directory into another one. * - * @param sourceDirectory the source dir - * @param destinationDirectory the target dir - * @param includes include pattern - * @param excludes exlucde pattern - * @throws IOException if any + * @param sourceDirectory the source directory + * @param destinationDirectory the target directory + * @param includes Ant include pattern + * @param excludes Ant exclude pattern + * @throws IOException if the source is a file or cannot be copied * @see #getFiles(File, String, String) + * @deprecated use {@code org.apache.commons.io.FileUtils.copyDirectory()} */ + @Deprecated public static void copyDirectory( @Nonnull File sourceDirectory, @Nonnull File destinationDirectory, @Nullable String includes, @Nullable String excludes ) throws IOException @@ -1677,6 +1651,10 @@ { return; } + else if ( !sourceDirectory.isDirectory() ) + { + throw new IOException( sourceDirectory + " is not a directory." ); + } List files = getFiles( sourceDirectory, includes, excludes ); @@ -1687,18 +1665,19 @@ } /** - * Copies a entire directory structure. - *

      - * Note: + * Copies an entire directory structure. + *

      Note:

      *
        *
      • It will include empty directories. - *
      • The sourceDirectory must exists. + *
      • The sourceDirectory must exist. *
      * - * @param sourceDirectory the source dir - * @param destinationDirectory the target dir + * @param sourceDirectory the existing directory to be copied + * @param destinationDirectory the new directory to be created * @throws IOException if any + * @deprecated use {@code org.apache.commons.io.FileUtils.copyDirectory()} */ + @Deprecated public static void copyDirectoryStructure( @Nonnull File sourceDirectory, @Nonnull File destinationDirectory ) throws IOException { @@ -1728,7 +1707,7 @@ if ( !sourceDirectory.exists() ) { - throw new IOException( "Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")." ); + throw new IOException( "Source directory doesn't exist (" + sourceDirectory.getAbsolutePath() + ")." ); } File[] files = sourceDirectory.listFiles(); @@ -1786,7 +1765,6 @@ /** * Renames a file, even if that involves crossing file system boundaries. - *

      *

      This will remove to (if it exists), ensure that * to's parent directory exists and move * from, which involves deleting from as @@ -1796,7 +1774,9 @@ * @param to the new file name * @throws IOException if anything bad happens during this process. * Note that 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 { @@ -1822,28 +1802,28 @@ } /** - * 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.

      - *

      + *

      * 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; @@ -1876,7 +1856,7 @@ } /** - * 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 @@ -1893,84 +1873,168 @@ /** * 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 ); } /** - * 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 * @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, @Nullable FilterWrapper[] wrappers, boolean overwrite ) throws IOException { - if ( wrappers != null && wrappers.length > 0 ) + if ( wrappers == null || wrappers.length == 0 ) { + if ( overwrite || to.lastModified() < from.lastModified() ) + { + copyFile( from, to ); + } + } + else + { + Charset charset = charset( encoding ); + // buffer so it isn't reading a byte at a time! - Reader fileReader = null; - Writer fileWriter = null; - try + try ( Reader fileReader = Files.newBufferedReader( from.toPath(), charset ) ) { - if ( encoding == null || encoding.length() < 1 ) - { - fileReader = new BufferedReader( new FileReader( from ) ); - fileWriter = new FileWriter( to ); - } - else + Reader wrapped = fileReader; + for ( FilterWrapper wrapper : wrappers ) { - fileReader = new BufferedReader( new InputStreamReader( new FileInputStream( from ), encoding ) ); - fileWriter = new OutputStreamWriter( new FileOutputStream( to ), encoding ); + wrapped = wrapper.getReader( wrapped ); } - for ( FilterWrapper wrapper : wrappers ) + if ( overwrite || !to.exists() ) { - fileReader = wrapper.getReader( fileReader ); + try ( Writer fileWriter = Files.newBufferedWriter( to.toPath(), charset ) ) + { + IOUtil.copy( wrapped, fileWriter ); + } } + else + { + CharsetEncoder encoder = charset.newEncoder(); - IOUtil.copy( fileReader, fileWriter ); - fileWriter.close(); - fileWriter = null; - fileReader.close(); - fileReader = null; - } - finally - { - IOUtil.close( fileReader ); - IOUtil.close( fileWriter ); + 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() ); + } + } + } } } - else + + 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 { - if ( to.lastModified() < from.lastModified() || overwrite ) - { - copyFile( from, to ); - } + // 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() ); } } /** - * 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 * @throws IOException if any + * @deprecated assumes the platform default character set */ + @Deprecated @Nonnull public static List loadFile( @Nonnull File file ) throws IOException { @@ -1978,31 +2042,38 @@ if ( file.exists() ) { - BufferedReader reader = null; - try + try ( BufferedReader reader = Files.newBufferedReader( file.toPath(), Charset.defaultCharset() ) ) { - 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; + + } + + /** + * 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 ); + } } /** @@ -2035,66 +2106,59 @@ /** * Checks whether a given file is a symbolic link. * - * This only works reliably on java7 and higher. For earlier version we use a highly crappy heuristic - * that mostly does not work. - *

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

      - * * @param file the file to check * @throws IOException in case of failure. * @return true if symbolic link false otherwise. - * + * @deprecated use {@code java.nio.file.Files.isSymbolicLink(file.toPath())} */ + @Deprecated 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() ); } /** * Checks whether a given file is a symbolic link. * * @param file the file to check - * @return true if and only if we reliably can say this is a symlink. This will - * always return false for java versions prior to 1.7. + * @return true if and only if we reliably can say this is a symlink * - * @throws IOException in case of failure. + * @throws IOException in case of failure + * @deprecated use {@code java.nio.file.Files.isSymbolicLink(file.toPath())} */ + @Deprecated public static boolean isSymbolicLinkForSure( @Nonnull final File file ) throws IOException { - return Java7Support.isAtLeastJava7() && Java7Support.isSymLink( file ); + return Files.isSymbolicLink( file.toPath() ); } /** - * Checks whether a given file is a symbolic link. - *

      - * It doesn't really test for symbolic links but whether the canonical and absolute - * paths of the file are identical - this may lead to false positives on some platforms. - * - * It also returns true for any file that has been reached via a symbolic link, - * if you decide to traverse into the symlink. - * - * As can be seen from the "return" clause of this method, there is really no - * guarantee of any sort from this method. Small wonder this ever got used for - * anything. - *

      - * - * @param file the file to check - * @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. + * 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 Files#createSymbolicLink(Path, Path, FileAttribute[]) which creates a new symbolic link but does + * not replace existing symbolic links */ - static boolean isSymbolicLinkLegacy( @Nonnull final File file ) - throws IOException + @Nonnull public static File createSymbolicLink( @Nonnull File symlink, @Nonnull File target ) + throws IOException { - final File canonical = new File( file.getCanonicalPath() ); - return !file.getAbsolutePath().equals( canonical.getPath() ); - } + final Path symlinkPath = symlink.toPath(); + if ( Files.exists( symlinkPath ) ) + { + if ( target.equals( Files.readSymbolicLink( symlinkPath ).toFile() ) ) + { + return symlink; + } + + Files.delete( symlinkPath ); + } + + return Files.createSymbolicLink( symlinkPath, target.toPath() ).toFile(); + } } diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/IOUtil.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/IOUtil.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/IOUtil.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/IOUtil.java 2021-04-26 13:54:15.000000000 +0000 @@ -37,40 +37,35 @@ 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 and byte[]). - *

      - *

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

      - *

      + * mechanism.

      + * *

      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,10 +128,14 @@ /** * 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 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 { @@ -146,11 +145,16 @@ /** * 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. + * 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 @@ -165,10 +169,12 @@ /** * 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 { @@ -178,11 +184,13 @@ /** * 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 { @@ -206,11 +214,15 @@ /** * 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 { @@ -222,11 +234,13 @@ * 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 { @@ -238,13 +252,15 @@ * 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 @@ -257,14 +273,16 @@ * 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 @@ -279,10 +297,13 @@ /** * 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 { @@ -293,11 +314,13 @@ * 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 { @@ -309,13 +332,15 @@ /** * 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 { @@ -325,14 +350,16 @@ /** * 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 @@ -347,10 +374,13 @@ /** * 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 { @@ -360,11 +390,13 @@ /** * 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 { @@ -384,10 +416,13 @@ /** * 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 { @@ -398,11 +433,13 @@ * 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 { @@ -418,10 +455,12 @@ /** * 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 { @@ -431,11 +470,13 @@ /** * 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 { @@ -449,10 +490,13 @@ /** * 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 { @@ -462,11 +506,13 @@ /** * 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 { @@ -486,10 +532,12 @@ /** * 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 { @@ -500,11 +548,13 @@ * 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 { @@ -521,10 +571,13 @@ /** * 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 { @@ -536,10 +589,13 @@ /** * 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 { @@ -549,11 +605,13 @@ /** * 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 { @@ -574,10 +632,13 @@ * 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 { @@ -589,11 +650,13 @@ * 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 { @@ -605,13 +668,15 @@ * 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 { @@ -623,14 +688,16 @@ * 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 @@ -645,10 +712,12 @@ /** * 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 { @@ -659,11 +728,13 @@ * 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 { @@ -675,13 +746,15 @@ /** * 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 { @@ -691,14 +764,16 @@ /** * 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 @@ -713,10 +788,13 @@ /** * 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 { @@ -724,13 +802,15 @@ } /** - * 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 { @@ -757,17 +837,18 @@ // ---------------------------------------------------------------------- /** - * Closes a {@code Channel} suppressing any {@code IOException}. + *

      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 * {@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;
      @@ -841,10 +922,11 @@
            *     // }
            * }
            * 
      - *

      * * @param channel The channel to close or {@code null}. + * @deprecated use try-with-resources */ + @Deprecated public static void close( @Nullable Channel channel ) { try @@ -861,9 +943,9 @@ } /** - * Closes an {@code InputStream} suppressing any {@code IOException}. + *

      Closes an {@code InputStream} suppressing any {@code IOException}.

      *

      - * 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. @@ -871,7 +953,8 @@ * {@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;
      @@ -945,10 +1028,11 @@
            *     // }
            * }
            * 
      - *

      * * @param inputStream The stream to close or {@code null}. + * @deprecated use try-with-resources */ + @Deprecated public static void close( @Nullable InputStream inputStream ) { try @@ -965,9 +1049,9 @@ } /** - * Closes an {@code OutputStream} suppressing any {@code IOException}. + *

      Closes an {@code OutputStream} suppressing any {@code IOException}.

      *

      - * 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. @@ -975,7 +1059,8 @@ * {@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;
      @@ -1049,10 +1134,11 @@
            *     // }
            * }
            * 
      - *

      * * @param outputStream The stream to close or {@code null}. + * @deprecated use try-with-resources */ + @Deprecated public static void close( @Nullable OutputStream outputStream ) { try @@ -1069,9 +1155,9 @@ } /** - * Closes a {@code Reader} suppressing any {@code IOException}. + *

      Closes a {@code Reader} suppressing any {@code IOException}.

      *

      - * 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. @@ -1079,7 +1165,8 @@ * {@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;
      @@ -1153,10 +1240,11 @@
            *     // }
            * }
            * 
      - *

      * * @param reader The reader to close or {@code null}. + * @deprecated use try-with-resources */ + @Deprecated public static void close( @Nullable Reader reader ) { try @@ -1173,9 +1261,9 @@ } /** - * Closes a {@code Writer} suppressing any {@code IOException}. + *

      Closes a {@code Writer} suppressing any {@code IOException}.

      *

      - * 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. @@ -1183,7 +1271,8 @@ * {@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;
      @@ -1257,10 +1346,11 @@
            *     // }
            * }
            * 
      - *

      * * @param writer The writer to close or {@code null}. + * @deprecated use try-with-resources */ + @Deprecated public static void close( @Nullable Writer writer ) { try diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/Java7Support.java 2021-04-26 13:54:15.000000000 +0000 @@ -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 @@ @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 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 @@ @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 @@ 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 boolean isJava7() { - return IS_JAVA7; + return true; } /** @@ -238,7 +101,6 @@ */ public static boolean isAtLeastJava7() { - return IS_JAVA7; + return true; } - } diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/MatchPattern.java 2021-04-26 13:54:15.000000000 +0000 @@ -28,12 +28,14 @@ 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 */ +@Deprecated public class MatchPattern { private final String source; @@ -98,7 +100,7 @@ { if ( regexPattern != null ) { - // FIXME: ICK! But we can't do partial matches for regex, so we have to reserve judgement until we have + // FIXME: ICK! But we can't do partial matches for regex, so we have to reserve judgment until we have // a file to deal with, or we can definitely say this is an exclusion... return true; } diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/MatchPatterns.java 2021-04-26 13:54:15.000000000 +0000 @@ -27,7 +27,9 @@ * A list of patterns to be matched * * @author Kristian Rosenvold + * @deprecated use {@code java.nio.filejava.nio.file.DirectoryStream.Filter} and related classes */ +@Deprecated public class MatchPatterns { private final MatchPattern[] patterns; @@ -38,9 +40,8 @@ } /** - * 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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/ScanConductor.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/ScanConductor.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/ScanConductor.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/ScanConductor.java 2021-04-26 13:54:15.000000000 +0000 @@ -23,17 +23,18 @@ /** *

      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.

      * * @author Mark Struberg + * + * @deprecated use {@code java.nio.file.Files.walkFileTree()} and related classes */ +@Deprecated public interface ScanConductor { /** diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/SelectorUtils.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/SelectorUtils.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/SelectorUtils.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/SelectorUtils.java 2021-04-26 13:54:15.000000000 +0000 @@ -39,7 +39,9 @@ * @author Magesh Umasankar * @author Bruce Atherton * + * @deprecated use {@code java.nio.file.Files.walkFileTree()} and related classes */ +@Deprecated public final class SelectorUtils { @@ -71,12 +73,12 @@ } /** - * 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, pattern=**\a - * and str=b will yield true. + * and str=b will yield true.

      * * @param pattern The pattern to match against. Must not be * null. @@ -91,12 +93,11 @@ } /** - * 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, pattern=**\a - * and str=b will yield true. + * and str=b will yield true.

      * * @param pattern The pattern to match against. Must not be * null. diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/WalkCollector.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/WalkCollector.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/io/WalkCollector.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/io/WalkCollector.java 2021-04-26 13:54:15.000000000 +0000 @@ -23,9 +23,10 @@ import java.util.ArrayList; import java.util.List; -/** - * +/** + * @deprecated use {@code java.nio.file.FileVisitor} and related classes */ +@Deprecated public class WalkCollector implements DirectoryWalkListener { diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilder.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilder.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilder.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilder.java 2021-04-26 13:54:15.000000000 +0000 @@ -50,24 +50,24 @@ 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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/logging/LoggerLevelRenderer.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/logging/LoggerLevelRenderer.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/logging/LoggerLevelRenderer.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/logging/LoggerLevelRenderer.java 2021-04-26 13:54:15.000000000 +0000 @@ -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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/logging/MessageBuilder.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/logging/MessageBuilder.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/logging/MessageBuilder.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/logging/MessageBuilder.java 2021-04-26 13:54:15.000000000 +0000 @@ -29,36 +29,48 @@ /** * 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 @@ // /** * 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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/logging/MessageUtils.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/logging/MessageUtils.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/logging/MessageUtils.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/logging/MessageUtils.java 2021-04-26 13:54:15.000000000 +0000 @@ -21,6 +21,7 @@ import org.fusesource.jansi.Ansi; import org.fusesource.jansi.AnsiConsole; +import org.fusesource.jansi.AnsiMode; /** * Colored message utils, to manage colors consistently across plugins (only if Maven version is at least 3.5.0). @@ -45,7 +46,7 @@ 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 ) @@ -78,20 +79,16 @@ { doSystemUninstall(); - // hook can only set when JANSI is true + // hook can only set when Jansi is true if ( shutdownHook != null ) { - // if out and system_out are same instance again, ansi is assumed to be uninstalled - if ( AnsiConsole.out == AnsiConsole.system_out ) + try { - try - { - Runtime.getRuntime().removeShutdownHook( shutdownHook ); - } - catch ( IllegalStateException ex ) - { - // ignore - VM is already shutting down - } + Runtime.getRuntime().removeShutdownHook( shutdownHook ); + } + catch ( IllegalStateException ex ) + { + // ignore - VM is already shutting down } } } @@ -106,19 +103,32 @@ } /** - * 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 ) { if ( JANSI ) { + AnsiConsole.out().setMode( flag ? AnsiMode.Force : AnsiMode.Strip ); Ansi.setEnabled( flag ); + System.setProperty( AnsiConsole.JANSI_MODE, + flag ? AnsiConsole.JANSI_MODE_FORCE : AnsiConsole.JANSI_MODE_STRIP ); + boolean installed = AnsiConsole.isInstalled(); + while ( AnsiConsole.isInstalled() ) + { + AnsiConsole.systemUninstall(); + } + if ( installed ) + { + AnsiConsole.systemInstall(); + } } } /** - * 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() { @@ -136,6 +146,7 @@ /** * 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 ) @@ -145,6 +156,7 @@ /** * 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 ) @@ -194,11 +206,32 @@ { synchronized ( STARTUP_SHUTDOWN_MONITOR ) { - doSystemUninstall(); + while ( AnsiConsole.isInstalled() ) + { + doSystemUninstall(); + } } } }; Runtime.getRuntime().addShutdownHook( shutdownHook ); } } + + /** + * Get the terminal width or -1 if the width cannot be determined. + * + * @return the terminal width + */ + public static int getTerminalWidth() + { + if ( JANSI ) + { + int width = AnsiConsole.getTerminalWidth(); + return width > 0 ? width : -1; + } + else + { + return -1; + } + } } diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/logging/PlainMessageBuilder.java 2021-04-26 13:54:15.000000000 +0000 @@ -42,24 +42,24 @@ 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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/Os.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/Os.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/Os.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/Os.java 2021-04-26 13:54:15.000000000 +0000 @@ -26,12 +26,10 @@ /** *

      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!

      * @@ -39,7 +37,6 @@ * @author Magesh Umasankar * @author Brian Fox * @author Mark Struberg - * @version $Revision$ * */ public class Os diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/package-info.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/package-info.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/package-info.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/package-info.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +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. - */ - -/** - * - * The following classes have not been implemented because they are easy to get other where: - * - *
      - *
      Base64
      - *
      commons-io has a much better maintained version than plexus-utils had. - * Commons / Jakarta is also the original source.
      - *
      - *
      - *
      FastMap
      - *
      This stuff contains tons of ancient java-1.2 logic. HotSpot collections are much faster that this stuff - * in the meantime.
      - *
      - */ diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/PathTool.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/PathTool.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/PathTool.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/PathTool.java 2021-04-26 13:54:15.000000000 +0000 @@ -26,15 +26,27 @@ 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 { + + /** + * The constructor. + * + * @deprecated This is a utility class with only static methods. Don't create instances of it. + */ + @Deprecated + public PathTool() + { + } + /** * Determines the relative path of a filename from a base directory. * This method is useful in building relative links within pages of @@ -44,9 +56,9 @@ * 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" )                  = ""
      @@ -100,8 +112,7 @@
           }
       
           /**
      -     * 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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/PropertyUtils.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/PropertyUtils.java
      --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/PropertyUtils.java	2017-08-08 19:49:52.000000000 +0000
      +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/PropertyUtils.java	2021-04-26 13:54:15.000000000 +0000
      @@ -29,37 +29,35 @@
       import javax.annotation.Nonnull;
       import javax.annotation.Nullable;
       
      -import org.apache.maven.shared.utils.io.IOUtil;
      -
       /**
      - *
      + * Static utility methods for loading properties.
        */
       public class PropertyUtils
       {
       
           /**
            * The constructor.
      +     *
      +     * @deprecated This is a utility class with only static methods. Don't create instances of it.
            */
      +    @Deprecated
           public PropertyUtils()
           {
      -        // should throw new IllegalAccessError( "Utility class" );
           }
       
           /**
      -     * @param url The URL which should be used to load the properties.
      -     *
      -     * @return The loaded properties.
      -     *
      -     * @deprecated As of 3.1.0, please use method {@link #loadOptionalProperties(java.net.URL)}. This method should not
      -     * be used as it suppresses exceptions silently when loading properties fails and returns {@code null} instead of an
      -     * empty {@code Properties} instance when the given {@code URL} is {@code null}.
      +     * @param url the URL which should be used to load the properties
      +     * @return the loaded properties
      +     * @deprecated use {@link #loadOptionalProperties(java.net.URL)} instead. This method should not
      +     *             be used as it suppresses exceptions silently when loading properties fails and returns {@code null}
      +     *             instead of an empty {@code Properties} instance when the given {@code URL} is {@code null}.
            */
           @Deprecated
           public static java.util.Properties loadProperties( @Nonnull URL url )
           {
      -        try
      +        try ( InputStream in = url.openStream() )
               {
      -            return loadProperties( url.openStream() );
      +            return loadProperties( in );
               }
               catch ( Exception e )
               {
      @@ -69,20 +67,18 @@
           }
       
           /**
      -     * @param file The file from which the properties will be loaded.
      -     *
      -     * @return The loaded properties.
      -     *
      -     * @deprecated As of 3.1.0, please use method {@link #loadOptionalProperties(java.io.File)}. This method should not
      -     * be used as it suppresses exceptions silently when loading properties fails and returns {@code null} instead of an
      -     * empty {@code Properties} instance when the given {@code File} is {@code null}.
      +     * @param file the file from which the properties will be loaded
      +     * @return the loaded properties
      +     * @deprecated use {@link #loadOptionalProperties(java.io.File)} instead. This method should not
      +     *             be used as it suppresses exceptions silently when loading properties fails and returns {@code null}
      +     *             instead of an empty {@code Properties} instance when the given {@code File} is {@code null}.
            */
           @Deprecated
           public static Properties loadProperties( @Nonnull File file )
           {
      -        try
      +        try  ( InputStream in = new FileInputStream( file ) )
               {
      -            return loadProperties( new FileInputStream( file ) );
      +            return loadProperties( in );
               }
               catch ( Exception e )
               {
      @@ -92,25 +88,26 @@
           }
       
           /**
      +     * Loads {@code Properties} from an {@code InputStream} and closes the stream.
      +     * In a future release, this will no longer close the stream, so callers
      +     * should close the stream themselves.  
      +     * 
            * @param is {@link InputStream}
      -     *
      -     * @return The loaded properties.
      -     *
      -     * @deprecated As of 3.1.0, please use method {@link #loadOptionalProperties(java.io.InputStream)}. This method
      -     * should not be used as it suppresses exceptions silently when loading properties fails.
      +     * @return the loaded properties
      +     * @deprecated use {@link #loadOptionalProperties(java.io.InputStream)} instead. This method
      +     *             should not be used as it suppresses exceptions silently when loading properties fails.
            */
           @Deprecated
           public static Properties loadProperties( @Nullable InputStream is )
           {
               try
               {
      -            // to make this the same behaviour as the others we should really return null on any error
                   Properties result = new Properties();
                   if ( is != null )
                   {
      -                try
      +                try ( InputStream in = is )
                       {
      -                    result.load( is );
      +                    result.load( in );
                       }
                       catch ( IOException e )
                       {
      @@ -123,131 +120,99 @@
               {
                   // ignore
               }
      -        finally
      -        {
      -            IOUtil.close( is );
      -        }
               return null;
           }
       
           /**
            * Loads {@code Properties} from a given {@code URL}.
            * 

      - * 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}. + * Loads {@code Properties} from a {@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. - *

      - * - * @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}. + * 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. 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 * @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 ) + Properties properties = new Properties(); + + if ( inputStream != null ) + { + try ( InputStream in = inputStream ) // reassign inputStream to autoclose { - in = inputStream; 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; + } } diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/ReaderFactory.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/ReaderFactory.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/ReaderFactory.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/ReaderFactory.java 2021-04-26 13:54:15.000000000 +0000 @@ -40,7 +40,7 @@ * * @author Hervé Boutemy * @see java.nio.charset.Charset - * @see Supported encodings + * @see Supported encodings */ public class ReaderFactory { @@ -48,16 +48,18 @@ * ISO Latin Alphabet #1, also known as ISO-LATIN-1. * Every implementation of the Java platform is required to support this character encoding. * - * @see java.nio.charset.Charset + * @deprecated use {@code java.nio.charset.StandardCharset.ISO_8859_1} */ + @Deprecated public static final String ISO_8859_1 = "ISO-8859-1"; /** * Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block of the Unicode character set. * Every implementation of the Java platform is required to support this character encoding. * - * @see java.nio.charset.Charset + * @deprecated use {@code java.nio.charset.StandardCharset.US_ASCII} */ + @Deprecated public static final String US_ASCII = "US-ASCII"; /** @@ -65,32 +67,36 @@ * order accepted on input, big-endian used on output). * Every implementation of the Java platform is required to support this character encoding. * - * @see java.nio.charset.Charset + * @deprecated use {@code java.nio.charset.StandardCharset.UTF_16} */ + @Deprecated public static final String UTF_16 = "UTF-16"; /** * Sixteen-bit Unicode Transformation Format, big-endian byte order. * Every implementation of the Java platform is required to support this character encoding. * - * @see java.nio.charset.Charset + * @deprecated use {@code java.nio.charset.StandardCharset.UTF_16BE} */ + @Deprecated public static final String UTF_16BE = "UTF-16BE"; /** * Sixteen-bit Unicode Transformation Format, little-endian byte order. * Every implementation of the Java platform is required to support this character encoding. * - * @see java.nio.charset.Charset + * @deprecated use {@code java.nio.charset.StandardCharset.UTF_16LE} */ + @Deprecated public static final String UTF_16LE = "UTF-16LE"; /** * Eight-bit Unicode Transformation Format. * Every implementation of the Java platform is required to support this character encoding. * - * @see java.nio.charset.Charset + * @deprecated use {@code java.nio.charset.StandardCharset.UTF_8} */ + @Deprecated public static final String UTF_8 = "UTF-8"; /** @@ -101,11 +107,12 @@ /** * Create a new Reader with XML encoding detection rules. * - * @param in not null input stream. - * @return an XML reader instance for the input stream. - * @throws IOException if any. - * @see XmlStreamReader + * @param in not null input stream + * @return an XML reader instance for the input stream + * @throws IOException if any + * @deprecated use org.apache.commons.io.input.XmlStreamReader instead */ + @Deprecated public static Reader newXmlReader( @Nonnull InputStream in ) throws IOException { @@ -115,11 +122,12 @@ /** * Create a new Reader with XML encoding detection rules. * - * @param file not null file. - * @return an XML reader instance for the input file. - * @throws IOException if any. - * @see XmlStreamReader + * @param file not null file + * @return an XML reader instance for the input file + * @throws IOException if any + * @deprecated use org.apache.commons.io.input.XmlStreamReader instead */ + @Deprecated public static Reader newXmlReader( @Nonnull File file ) throws IOException { @@ -129,11 +137,12 @@ /** * Create a new Reader with XML encoding detection rules. * - * @param url not null url. - * @return an XML reader instance for the input url. - * @throws IOException if any. - * @see XmlStreamReader + * @param url not null URL + * @return an XML reader instance for the input URL + * @throws IOException if any + * @deprecated use {@code org.apache.commons.io.input.XmlStreamReader} instead */ + @Deprecated public static Reader newXmlReader( @Nonnull URL url ) throws IOException { @@ -141,13 +150,15 @@ } /** - * Create a new Reader with default plaform encoding. + * Create a new Reader with default platform encoding. * * @param file not null file. - * @return a reader instance for the input file using the default platform charset. - * @throws FileNotFoundException if any. + * @return a reader instance for the input file using the default platform character set + * @throws FileNotFoundException if any * @see java.nio.charset.Charset#defaultCharset() + * @deprecated always specify an encoding. Do not depend on the default platform character set. */ + @Deprecated public static Reader newPlatformReader( @Nonnull File file ) throws FileNotFoundException { @@ -157,11 +168,12 @@ /** * Create a new Reader with specified encoding. * - * @param in not null input stream. - * @param encoding not null supported encoding. - * @return a reader instance for the input stream using the given encoding. - * @throws UnsupportedEncodingException if any. - * @see Supported encodings + * @param in not null input stream + * @param encoding not null supported encoding + * @return a reader instance for the input stream using the given encoding + * @throws UnsupportedEncodingException if any + * @see Supported + * encodings */ public static Reader newReader( @Nonnull InputStream in, @Nonnull String encoding ) throws UnsupportedEncodingException @@ -172,12 +184,13 @@ /** * Create a new Reader with specified encoding. * - * @param file not null file. - * @param encoding not null supported encoding. - * @return a reader instance for the input file using the given encoding. - * @throws FileNotFoundException if any. - * @throws UnsupportedEncodingException if any. - * @see Supported encodings + * @param file not null file + * @param encoding not null supported encoding + * @return a reader instance for the input file using the given encoding + * @throws FileNotFoundException if any + * @throws UnsupportedEncodingException if any + * @see Supported + * encodings */ public static Reader newReader( @Nonnull File file, @Nonnull String encoding ) throws FileNotFoundException, UnsupportedEncodingException @@ -188,11 +201,12 @@ /** * Create a new Reader with specified encoding. * - * @param url not null url. - * @param encoding not null supported encoding. - * @return a reader instance for the input url using the given encoding. - * @throws IOException if any. - * @see Supported encodings + * @param url not null URL + * @param encoding not null supported encoding + * @return a reader instance for the input URL using the given encoding + * @throws IOException if any + * @see Supported + * encodings */ public static Reader newReader( @Nonnull URL url, @Nonnull String encoding ) throws IOException diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/reflection/ReflectorException.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/reflection/ReflectorException.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/reflection/ReflectorException.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/reflection/ReflectorException.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,70 +0,0 @@ -package org.apache.maven.shared.utils.reflection; - -/* - * 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. - */ - -/** - * Exception indicating that an error has occurred while instantiating a class - * with the Reflector class. This exception is meant to put a more user-friendly - * face on the myriad other exceptions throws during reflective object creation. - * - * @author John Casey - */ -class ReflectorException - extends Exception -{ - /** - * Create a new ReflectorException. - */ - ReflectorException() - { - } - - /** - * Create a new ReflectorException with the specified message. - * - * @param msg The message. - */ - ReflectorException( String msg ) - { - super( msg ); - } - - /** - * Create a new ReflectorException with the specified root cause. - * - * @param root The root cause. - */ - ReflectorException( Throwable root ) - { - super( root ); - } - - /** - * Create a new ReflectorException with the specified message and root - * cause. - * - * @param msg The message. - * @param root The root cause. - */ - ReflectorException( String msg, Throwable root ) - { - super( msg, root ); - } -} diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/reflection/Reflector.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/reflection/Reflector.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/reflection/Reflector.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/reflection/Reflector.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,573 +0,0 @@ -package org.apache.maven.shared.utils.reflection; - -/* - * 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.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Member; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - -/** - * Utility class used to instantiate an object using reflection. This utility hides many of the gory details needed to - * do this. - * - * @author John Casey - */ -final class Reflector -{ - private static final String CONSTRUCTOR_METHOD_NAME = "$$CONSTRUCTOR$$"; - - private static final String GET_INSTANCE_METHOD_NAME = "getInstance"; - - private final Map>> classMaps = - new HashMap>>(); - - /** - * Ensure no instances of Reflector are created...this is a utility. - */ - Reflector() - { - } - - /** - * Create a new instance of a class, given the array of parameters... Uses constructor caching to find a constructor - * that matches the parameter types, either specifically (first choice) or abstractly... - * - * @param theClass The class to instantiate - * @param params The parameters to pass to the constructor - * @return The instantiated object - * @throws ReflectorException In case anything goes wrong here... - */ - public Object newInstance( Class theClass, Object... params ) - throws ReflectorException - { - if ( params == null ) - { - params = new Object[0]; - } - - Class[] paramTypes = new Class[params.length]; - - for ( int i = 0, len = params.length; i < len; i++ ) - { - paramTypes[i] = params[i].getClass(); - } - - try - { - Constructor con = getConstructor( theClass, paramTypes ); - - return con.newInstance( params ); - } - catch ( InstantiationException ex ) - { - throw new ReflectorException( ex ); - } - catch ( InvocationTargetException ex ) - { - throw new ReflectorException( ex ); - } - catch ( IllegalAccessException ex ) - { - throw new ReflectorException( ex ); - } - } - - /** - * Retrieve the singleton instance of a class, given the array of parameters... Uses constructor caching to find a - * constructor that matches the parameter types, either specifically (first choice) or abstractly... - * - * @param theClass The class to retrieve the singleton of - * @param initParams The parameters to pass to the constructor - * @return The singleton object - * @throws ReflectorException In case anything goes wrong here... - */ - public Object getSingleton( Class theClass, Object... initParams ) - throws ReflectorException - { - Class[] paramTypes = new Class[initParams.length]; - - for ( int i = 0, len = initParams.length; i < len; i++ ) - { - paramTypes[i] = initParams[i].getClass(); - } - - try - { - Method method = getMethod( theClass, GET_INSTANCE_METHOD_NAME, paramTypes ); - - return method.invoke( null, initParams ); - } - catch ( InvocationTargetException ex ) - { - throw new ReflectorException( ex ); - } - catch ( IllegalAccessException ex ) - { - throw new ReflectorException( ex ); - } - } - - /** - * Invoke the specified method on the specified target with the specified params... - * - * @param target The target of the invocation - * @param methodName The method name to invoke - * @param params The parameters to pass to the method invocation - * @return The result of the method call - * @throws ReflectorException In case of an error looking up or invoking the method. - */ - public Object invoke( Object target, String methodName, Object... params ) - throws ReflectorException - { - if ( params == null ) - { - params = new Object[0]; - } - - Class[] paramTypes = new Class[params.length]; - - for ( int i = 0, len = params.length; i < len; i++ ) - { - paramTypes[i] = params[i].getClass(); - } - - try - { - Method method = getMethod( target.getClass(), methodName, paramTypes ); - - return method.invoke( target, params ); - } - catch ( InvocationTargetException ex ) - { - throw new ReflectorException( ex ); - } - catch ( IllegalAccessException ex ) - { - throw new ReflectorException( ex ); - } - } - - public Object getStaticField( Class targetClass, String fieldName ) - throws ReflectorException - { - try - { - Field field = targetClass.getField( fieldName ); - - return field.get( null ); - } - catch ( SecurityException e ) - { - throw new ReflectorException( e ); - } - catch ( NoSuchFieldException e ) - { - throw new ReflectorException( e ); - } - catch ( IllegalArgumentException e ) - { - throw new ReflectorException( e ); - } - catch ( IllegalAccessException e ) - { - throw new ReflectorException( e ); - } - } - - public Object getField( Object target, String fieldName ) - throws ReflectorException - { - return getField( target, fieldName, false ); - } - - public Object getField( Object target, String fieldName, boolean breakAccessibility ) - throws ReflectorException - { - Class targetClass = target.getClass(); - while ( targetClass != null ) - { - try - { - Field field = targetClass.getDeclaredField( fieldName ); - - boolean accessibilityBroken = false; - if ( !field.isAccessible() && breakAccessibility ) - { - field.setAccessible( true ); - accessibilityBroken = true; - } - - Object result = field.get( target ); - - if ( accessibilityBroken ) - { - field.setAccessible( false ); - } - - return result; - } - catch ( SecurityException e ) - { - throw new ReflectorException( e ); - } - catch ( NoSuchFieldException e ) - { - if ( targetClass == Object.class ) - { - throw new ReflectorException( e ); - } - targetClass = targetClass.getSuperclass(); - } - catch ( IllegalAccessException e ) - { - throw new ReflectorException( e ); - } - } - // Never reached, but needed to satisfy compiler - return null; - } - - /** - * Invoke the specified static method with the specified params... - * - * @param targetClass The target class of the invocation - * @param methodName The method name to invoke - * @param params The parameters to pass to the method invocation - * @return The result of the method call - * @throws ReflectorException In case of an error looking up or invoking the method. - */ - public Object invokeStatic( Class targetClass, String methodName, Object... params ) - throws ReflectorException - { - if ( params == null ) - { - params = new Object[0]; - } - - Class[] paramTypes = new Class[params.length]; - - for ( int i = 0, len = params.length; i < len; i++ ) - { - paramTypes[i] = params[i].getClass(); - } - - try - { - Method method = getMethod( targetClass, methodName, paramTypes ); - - return method.invoke( null, params ); - } - catch ( InvocationTargetException ex ) - { - throw new ReflectorException( ex ); - } - catch ( IllegalAccessException ex ) - { - throw new ReflectorException( ex ); - } - } - - /** - * Return the constructor, checking the cache first and storing in cache if not already there.. - * - * @param targetClass The class to get the constructor from - * @param params The classes of the parameters which the constructor should match. - * @return the Constructor object that matches, never {@code null} - * @throws ReflectorException In case we can't retrieve the proper constructor. - */ - public Constructor getConstructor( Class targetClass, Class... params ) - throws ReflectorException - { - Map constructorMap = getConstructorMap( targetClass ); - - @SuppressWarnings( "checkstyle:magicnumber" ) - StringBuilder key = new StringBuilder( 200 ); - - key.append( "(" ); - - for ( Class param : params ) - { - key.append( param.getName() ); - key.append( "," ); - } - - if ( params.length > 0 ) - { - key.setLength( key.length() - 1 ); - } - - key.append( ")" ); - - Constructor constructor; - - String paramKey = key.toString(); - - synchronized ( paramKey.intern() ) - { - constructor = (Constructor) constructorMap.get( paramKey ); - - if ( constructor == null ) - { - Constructor[] cands = targetClass.getConstructors(); - - for ( Constructor cand : cands ) - { - Class[] types = cand.getParameterTypes(); - - if ( params.length != types.length ) - { - continue; - } - - for ( int j = 0, len2 = params.length; j < len2; j++ ) - { - if ( !types[j].isAssignableFrom( params[j] ) ) - { - continue; - } - } - - // we got it, so store it! - constructor = cand; - constructorMap.put( paramKey, constructor ); - } - } - } - - if ( constructor == null ) - { - throw new ReflectorException( "Error retrieving constructor object for: " + targetClass.getName() - + paramKey ); - } - - return constructor; - } - - public Object getObjectProperty( Object target, String propertyName ) - throws ReflectorException - { - Object returnValue; - - if ( propertyName == null || propertyName.trim().length() < 1 ) - { - throw new ReflectorException( "Cannot retrieve value for empty property." ); - } - - String beanAccessor = "get" + Character.toUpperCase( propertyName.charAt( 0 ) ); - if ( propertyName.trim().length() > 1 ) - { - beanAccessor += propertyName.substring( 1 ).trim(); - } - - Class targetClass = target.getClass(); - Class[] emptyParams = {}; - - Method method = _getMethod( targetClass, beanAccessor, emptyParams ); - if ( method == null ) - { - method = _getMethod( targetClass, propertyName, emptyParams ); - } - - if ( method != null ) - { - try - { - returnValue = method.invoke( target, new Object[] {} ); - } - catch ( IllegalAccessException e ) - { - throw new ReflectorException( "Error retrieving property \'" + propertyName + "\' from \'" - + targetClass + "\'", e ); - } - catch ( InvocationTargetException e ) - { - throw new ReflectorException( "Error retrieving property \'" + propertyName + "\' from \'" - + targetClass + "\'", e ); - } - } - else - { - returnValue = getField( target, propertyName, true ); - if ( returnValue == null ) - { - // TODO: Check if exception is the right action! Field exists, but contains null - throw new ReflectorException( "Neither method: \'" + propertyName + "\' nor bean accessor: \'" - + beanAccessor + "\' can be found for class: \'" + targetClass + "\', and retrieval of field: \'" - + propertyName + "\' returned null as value." ); - } - } - - return returnValue; - } - - /** - * Return the method, checking the cache first and storing in cache if not already there.. - * - * @param targetClass The class to get the method from - * @param params The classes of the parameters which the method should match. - * @return the Method object that matches, never {@code null} - * @throws ReflectorException In case we can't retrieve the proper method. - */ - public Method getMethod( Class targetClass, String methodName, Class... params ) - throws ReflectorException - { - Method method = _getMethod( targetClass, methodName, params ); - - if ( method == null ) - { - throw new ReflectorException( "Method: \'" + methodName + "\' not found in class: \'" + targetClass - + "\'" ); - } - - return method; - } - - @SuppressWarnings( "checkstyle:methodname" ) - private Method _getMethod( Class targetClass, String methodName, Class... params ) - throws ReflectorException - { - Map methodMap = getMethodMap( targetClass, methodName ); - - @SuppressWarnings( "checkstyle:magicnumber" ) - StringBuilder key = new StringBuilder( 200 ); - - key.append( "(" ); - - for ( Class param : params ) - { - key.append( param.getName() ); - key.append( "," ); - } - - key.append( ")" ); - - Method method; - - String paramKey = key.toString(); - - synchronized ( paramKey.intern() ) - { - method = (Method) methodMap.get( paramKey ); - - if ( method == null ) - { - Method[] cands = targetClass.getMethods(); - - for ( Method cand : cands ) - { - String name = cand.getName(); - - if ( !methodName.equals( name ) ) - { - continue; - } - - Class[] types = cand.getParameterTypes(); - - if ( params.length != types.length ) - { - continue; - } - - for ( int j = 0, len2 = params.length; j < len2; j++ ) - { - if ( !types[j].isAssignableFrom( params[j] ) ) - { - continue; - } - } - - // we got it, so store it! - method = cand; - methodMap.put( paramKey, method ); - } - } - } - - return method; - } - - /** - * Retrieve the cache of constructors for the specified class. - * - * @param theClass the class to lookup. - * @return The cache of constructors. - * @throws ReflectorException in case of a lookup error. - */ - private Map getConstructorMap( Class theClass ) - throws ReflectorException - { - return getMethodMap( theClass, CONSTRUCTOR_METHOD_NAME ); - } - - /** - * Retrieve the cache of methods for the specified class and method name. - * - * @param theClass the class to lookup. - * @param methodName The name of the method to lookup. - * @return The cache of constructors. - */ - private Map getMethodMap( Class theClass, String methodName ) - { - Map methodMap; - - if ( theClass == null ) - { - return null; - } - - String className = theClass.getName(); - - synchronized ( className.intern() ) - { - Map> classMethods = classMaps.get( className ); - - if ( classMethods == null ) - { - classMethods = new HashMap>(); - methodMap = new HashMap(); - classMethods.put( methodName, methodMap ); - - classMaps.put( className, classMethods ); - } - else - { - String key = className + "::" + methodName; - - synchronized ( key.intern() ) - { - methodMap = classMethods.get( methodName ); - - if ( methodMap == null ) - { - methodMap = new HashMap(); - classMethods.put( methodName, methodMap ); - } - } - } - } - - return methodMap; - } -} diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/StringUtils.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/StringUtils.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/StringUtils.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/StringUtils.java 2021-04-26 13:54:15.000000000 +0000 @@ -31,7 +31,7 @@ /** *

      Common String manipulation routines.

      - *

      + * *

      Originally from * Turbine, the * GenerationJavaCore library and Velocity. @@ -49,7 +49,6 @@ * @author Fredrik Westermarck * @author Holger Krauth * @author Alexander Day Chaffee - * @version $Id$ * */ public class StringUtils @@ -58,7 +57,7 @@ *

      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.

      */ @@ -70,7 +69,7 @@ //-------------------------------------------------------------------------- /** - *

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

      * @@ -84,7 +83,7 @@ } /** - *

      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.

      * @@ -98,14 +97,13 @@ } /** - *

      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 - * @throws NullPointerException + * @return the String without whitespace */ @Nonnull public static String deleteWhitespace( @Nonnull String str ) { @@ -123,7 +121,7 @@ /** *

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

      + * not empty (length > 0).

      * * @param str the String to check * @return true if the String is non-null, and not length zero @@ -135,7 +133,7 @@ /** *

      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.

      @@ -153,7 +151,7 @@ *

      * Checks if a String is whitespace, empty ("") or null. *

      - *

      + * *

            * StringUtils.isBlank(null)      = true
            * StringUtils.isBlank("")        = true
      @@ -189,7 +187,7 @@
            * 

      * Checks if a String is not empty (""), not null and not whitespace only. *

      - *

      + * *

            * StringUtils.isNotBlank(null)      = false
            * StringUtils.isNotBlank("")        = false
      @@ -212,7 +210,7 @@
       
           /**
            * 

      Compares two Strings, returning true if they are equal.

      - *

      + * *

      nulls are handled without exceptions. Two null * references are considered to be equal. The comparison is case sensitive.

      * @@ -221,7 +219,9 @@ * @return 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 ) ); @@ -230,7 +230,7 @@ /** *

      Compares two Strings, returning true if they are equal ignoring * the case.

      - *

      + * *

      Nulls are handled without exceptions. Two null * references are considered equal. Comparison is case insensitive.

      * @@ -247,7 +247,7 @@ /** *

      Find the first index of any of a set of potential substrings.

      - *

      + * *

      null String will return -1.

      * * @param str the String to check @@ -284,7 +284,7 @@ /** *

      Find the latest index of any of a set of potential substrings.

      - *

      + * *

      null string will return -1.

      * * @param str the String to check @@ -316,7 +316,7 @@ /** *

      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.

      * @@ -352,7 +352,7 @@ /** *

      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.

      * @@ -361,7 +361,7 @@ * count back from the end of the string by this many characters * @param end the position to end at (exclusive), negative means * count back from the end of the String by this many characters - * @return substring from start position to end positon + * @return substring from start position to end position */ public static String substring( String str, int start, int end ) { @@ -407,7 +407,7 @@ /** *

      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.

      @@ -435,7 +435,7 @@ /** *

      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.

      @@ -463,7 +463,7 @@ /** *

      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.

      @@ -505,7 +505,7 @@ /** *

      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 @@ -517,9 +517,9 @@ } /** - * @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 ) @@ -529,19 +529,19 @@ /** *

      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.

      - *

      - *

      This is useful for quickly splitting a String directly into + * 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).

      * - * @param str The string to parse. + * @param str the string to parse * @param separator Characters used as the delimiters. If * 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 */ @@ -597,7 +597,7 @@ /** *

      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. @@ -611,7 +611,7 @@ /** *

      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 * null separator is the same as a blank String.

      * @@ -643,7 +643,7 @@ /** *

      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 * null separator is the same as a blank String.

      * @@ -674,7 +674,7 @@ /** *

      Replace a char with another char inside a larger String, once.

      - *

      + * *

      A null reference passed to this method is a no-op.

      * * @param text text to search and replace in @@ -690,7 +690,7 @@ /** *

      Replace all occurances of a char within another char.

      - *

      + * *

      A null reference passed to this method is a no-op.

      * * @param text text to search and replace in @@ -707,7 +707,7 @@ /** *

      Replace a char with another char inside a larger String, * for the first max values of the search char.

      - *

      + * *

      A null reference passed to this method is a no-op.

      * * @param text text to search and replace in @@ -723,7 +723,7 @@ /** *

      Replace a String with another String inside a larger String, once.

      - *

      + * *

      A null reference passed to this method is a no-op.

      * * @param text text to search and replace in @@ -738,8 +738,8 @@ } /** - *

      Replace all occurances of a String within another String.

      - *

      + *

      Replace all occurrences of a String within another String.

      + * *

      A null reference passed to this method is a no-op.

      * * @param text text to search and replace in @@ -756,7 +756,7 @@ /** *

      Replace a String with another String inside a larger String, * for the first max values of the search String.

      - *

      + * *

      A null reference passed to this method is a no-op.

      * * @param text text to search and replace in @@ -793,9 +793,9 @@ * * @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 is null */ @Nonnull public static String overlayString( @Nonnull String text, @Nonnull String overlay, int start, int end ) @@ -815,8 +815,8 @@ //-------------------------------------------------------------------------- /** - *

      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 center(str, size, " ").

      * @@ -832,7 +832,7 @@ /** *

      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 @@ -1005,7 +1005,7 @@ /** *

      Remove the last character from a String.

      - *

      + * *

      If the String ends in \r\n, then remove both * of them.

      * @@ -1069,7 +1069,7 @@ /** *

      Escapes any values it finds into their String form.

      - *

      + * *

      So a tab becomes the characters '\\' and * 't'.

      * @@ -1173,7 +1173,7 @@ * @param str String to repeat * @param repeat number of times to repeat str * @return String with repeated String - * @throws NegativeArraySizeException if repeat < 0 + * @throws NegativeArraySizeException if repeat < 0 * @throws NullPointerException if str is null */ @Nonnull public static String repeat( @Nonnull String str, int repeat ) @@ -1188,7 +1188,7 @@ /** *

      Right pad a String with spaces.

      - *

      + * *

      The String is padded to the size of n.

      * * @param str String to repeat @@ -1203,7 +1203,7 @@ /** *

      Right pad a String with a specified string.

      - *

      + * *

      The String is padded to the size of n.

      * * @param str String to pad out @@ -1225,7 +1225,7 @@ /** *

      Left pad a String with spaces.

      - *

      + * *

      The String is padded to the size of n.

      * * @param str String to pad out @@ -1275,7 +1275,7 @@ /** *

      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.

      * @@ -1326,7 +1326,7 @@ /** *

      Strip any of a supplied String from the end of a String.

      - *

      + * *

      If the strip String is null, whitespace is * stripped.

      * @@ -1361,7 +1361,7 @@ /** *

      Strip any of a supplied String from the start of a String.

      - *

      + * *

      If the strip String is null, whitespace is * stripped.

      * @@ -1434,7 +1434,7 @@ /** *

      Uncapitalise a String.

      - *

      + * *

      That is, convert the first character into lower-case. * null is returned as null.

      * @@ -1466,7 +1466,7 @@ /** *

      Capitalise a String.

      - *

      + * *

      That is, convert the first character into title-case. * null is returned as null.

      * @@ -1498,10 +1498,10 @@ /** *

      Swaps the case of String.

      - *

      + * *

      Properly looks after making sure the start of words * are Titlecase and not Uppercase.

      - *

      + * *

      null is returned as null.

      * * @param str the String to swap the case of @@ -1555,10 +1555,10 @@ /** *

      Capitalise all the words in a String.

      - *

      + * *

      Uses {@link Character#isWhitespace(char)} as a * separator between words.

      - *

      + * *

      null will return null.

      * * @param str the String to capitalise @@ -1596,10 +1596,10 @@ /** *

      Uncapitalise all the words in a string.

      - *

      + * *

      Uses {@link Character#isWhitespace(char)} as a * separator between words.

      - *

      + * *

      null will return null.

      * * @param str the string to uncapitalise @@ -1641,7 +1641,7 @@ /** *

      Get the String that is nested in between two instances of the * same String.

      - *

      + * *

      If str is null, will * return null.

      * @@ -1684,12 +1684,12 @@ /** *

      How many times is the substring in the larger String.

      - *

      + * *

      null returns 0.

      * * @param str the String to check * @param sub the substring to count - * @return the number of occurances, 0 if the String is 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 ) @@ -1716,8 +1716,8 @@ //-------------------------------------------------------------------------- /** - *

      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.

      * @@ -1743,7 +1743,7 @@ /** *

      Checks if the String contains only whitespace.

      - *

      + * *

      null will return false. An * empty String will return true.

      * @@ -1768,9 +1768,9 @@ } /** - *

      Checks if the String contains only unicode letters and + *

      Checks if the String contains only Unicode letters and * space (' ').

      - *

      + * *

      null will return false. An * empty String will return true.

      * @@ -1796,8 +1796,8 @@ } /** - *

      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.

      * @@ -1823,9 +1823,9 @@ } /** - *

      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 * String will return true.

      * @@ -1851,8 +1851,8 @@ } /** - *

      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.

      * @@ -1887,7 +1887,9 @@ * @param obj the Object to check * @return the passed in Object's toString, or blank if it was * null + * @deprecated use {@code java.lang.Objects.toString()} */ + @Deprecated @Nonnull public static String defaultString( Object obj ) { return defaultString( obj, "" ); @@ -1903,7 +1905,9 @@ * 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(); @@ -1914,7 +1918,7 @@ /** *

      Reverse a String.

      - *

      + * *

      null String returns null.

      * * @param str the String to reverse @@ -1931,7 +1935,7 @@ /** *

      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 '.').

      @@ -1951,8 +1955,6 @@ /** *

      Reverses an array.

      - *

      - *

      TAKEN FROM CollectionsUtils.

      * * @param array the array to reverse */ @@ -1976,14 +1978,12 @@ //-------------------------------------------------------------------------- /** - * 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 @@ -1996,12 +1996,13 @@ /** * 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 @@ -2048,8 +2049,9 @@ * 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. @@ -2068,7 +2070,7 @@ /** * 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. @@ -2160,17 +2162,13 @@ } /** - * Convert the first character of the given String to uppercase. - * This method will not trim of spaces! - *

      - *

      - * Attention: this method will currently throw a - * IndexOutOfBoundsException for empty strings! - *

      + * 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 is null + * @throws IndexOutOfBoundsException if data is empty */ @Nonnull public static String capitalizeFirstLetter( @Nonnull String data ) { @@ -2187,17 +2185,13 @@ } /** - * Convert the first character of the given String to lowercase. - * This method will not trim of spaces! - *

      - *

      - * Attention: this method will currently throw a - * IndexOutOfBoundsException for empty strings! - *

      + * 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 * @throws NullPointerException if data is null + * @throws IndexOutOfBoundsException if data is empty */ @Nonnull public static String lowercaseFirstLetter( @Nonnull String data ) { @@ -2209,11 +2203,10 @@ } /** - * 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. + * @param view the view * @return deHumped String */ @Nonnull public static String addAndDeHump( @Nonnull String view ) @@ -2235,7 +2228,7 @@ /** *

      Quote and escape a String with the given character, handling null.

      - *

      + * *

            * StringUtils.quoteAndEscape(null, *)    = null
            * StringUtils.quoteAndEscape("", *)      = ""
      @@ -2259,9 +2252,9 @@
           /**
            * 

      Quote and escape a String with the given character, handling null.

      * - * @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) * @@ -2272,11 +2265,11 @@ } /** - * @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) * @@ -2288,12 +2281,12 @@ } /** - * @param source The source. - * @param quoteChar The quote character. - * @param escapedChars The escaped characters. - * @param quotingTriggers The quoting trigger. - * @param escapeChar The escape 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, @@ -2342,9 +2335,9 @@ } /** - * @param source The source. - * @param escapedChars escape characters. - * @param escapeChar escape 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 ) @@ -2376,11 +2369,10 @@ } /** - * 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 ) @@ -2403,13 +2395,17 @@ /** * Parses the given String and replaces all occurrences of - * '\n', '\r' and '\r\n' with the system line separator. + * '\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) - * + * @deprecated this method produces platform dependent code and contributes to + * non-reproducible builds. In the context of Maven, this is almost never what's needed. + * Remove calls to this method and do not replace them. That is, change + * {@code Stringutils.unifyLineSeparators(s)} to simply {@code s}. */ + @Deprecated public static String unifyLineSeparators( @Nullable String s ) { return unifyLineSeparators( s, System.getProperty( "line.separator" ) ); @@ -2420,9 +2416,9 @@ * '\n', '\r' and '\r\n' with the system line separator. * * @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. - * @throws IllegalArgumentException if ls is not '\n', '\r' and '\r\n' characters. + * @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 + * @throws IllegalArgumentException if ls is not '\n', '\r', or "\r\n" * */ public static String unifyLineSeparators( @Nullable String s, @Nullable String ls ) @@ -2472,9 +2468,9 @@ /** *

      Checks if String contains a search character, handling null. * This method uses {@link String#indexOf(int)}.

      - *

      + * *

      A null or empty ("") String will return false.

      - *

      + * *

            * StringUtils.contains(null, *)    = false
            * StringUtils.contains("", *)      = false
      @@ -2496,9 +2492,9 @@
           /**
            * 

      Checks if String contains a search String, handling null. * This method uses {@link String#indexOf(int)}.

      - *

      + * *

      A null String will return false.

      - *

      + * *

            * StringUtils.contains(null, *)     = false
            * StringUtils.contains(*, null)     = false
      @@ -2520,9 +2516,8 @@
       
           /**
            * 

      Checks if String ends with a search String, handling null.

      - *

      *

      A null String will return false.

      - *

      + * *

            * StringUtils.endsWithIgnoreCase(null, *)     = false
            * StringUtils.endsWithIgnoreCase(*, null)     = false
      diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/WriterFactory.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/WriterFactory.java
      --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/WriterFactory.java	2017-08-08 19:49:52.000000000 +0000
      +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/WriterFactory.java	2021-04-26 13:54:15.000000000 +0000
      @@ -39,52 +39,63 @@
        *
        * @author Hervé Boutemy
        * @see java.nio.charset.Charset
      - * @see Supported encodings
      - * @version $Id$
      + * @see Supported encodings
        */
       public class WriterFactory
       {
           /**
            * ISO Latin Alphabet #1, also known as ISO-LATIN-1.
            * Every implementation of the Java platform is required to support this character encoding.
      -     * @see java.nio.charset.Charset
      +     *
      +     * @deprecated use {@code java.nio.charset.StandardCharset.ISO_8859_1}
            */
      +    @Deprecated
           public static final String ISO_8859_1 = "ISO-8859-1";
       
           /**
            * Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block of the Unicode character set.
            * Every implementation of the Java platform is required to support this character encoding.
      -     * @see java.nio.charset.Charset
      +     *
      +     * @deprecated use {@code java.nio.charset.StandardCharset.US_ASCII}
            */
      +    @Deprecated
           public static final String US_ASCII = "US-ASCII";
       
           /**
            * Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either
            * order accepted on input, big-endian used on output).
            * Every implementation of the Java platform is required to support this character encoding.
      -     * @see java.nio.charset.Charset
      +     *
      +     * @deprecated use {@code java.nio.charset.StandardCharset.UTF_16}
            */
      +    @Deprecated
           public static final String UTF_16 = "UTF-16";
       
           /**
            * Sixteen-bit Unicode Transformation Format, big-endian byte order.
            * Every implementation of the Java platform is required to support this character encoding.
      -     * @see java.nio.charset.Charset
      +     *
      +     * @deprecated use {@code java.nio.charset.StandardCharset.UTF_16BE}
            */
      +    @Deprecated
           public static final String UTF_16BE = "UTF-16BE";
       
           /**
            * Sixteen-bit Unicode Transformation Format, little-endian byte order.
            * Every implementation of the Java platform is required to support this character encoding.
      -     * @see java.nio.charset.Charset
      +     *
      +     * @deprecated use {@code java.nio.charset.StandardCharset.UTF_16LE}
            */
      +    @Deprecated
           public static final String UTF_16LE = "UTF-16LE";
       
           /**
            * Eight-bit Unicode Transformation Format.
            * Every implementation of the Java platform is required to support this character encoding.
      -     * @see java.nio.charset.Charset
      +     *
      +     * @deprecated use {@code java.nio.charset.StandardCharset.UTF_8}
            */
      +    @Deprecated
           public static final String UTF_8 = "UTF-8";
       
           /**
      @@ -95,9 +106,9 @@
           /**
            * Create a new Writer with XML encoding detection rules.
            *
      -     * @param out not null output stream.
      -     * @return an XML writer instance for the output stream.
      -     * @throws IOException if any.
      +     * @param out not null output stream
      +     * @return an XML writer instance for the output stream
      +     * @throws IOException if any
            * @see XmlStreamWriter
            */
           public static XmlStreamWriter newXmlWriter( @Nonnull OutputStream out )
      @@ -109,9 +120,9 @@
           /**
            * Create a new Writer with XML encoding detection rules.
            *
      -     * @param file not null file.
      -     * @return an XML writer instance for the output file.
      -     * @throws IOException if any.
      +     * @param file not null file
      +     * @return an XML writer instance for the output file
      +     * @throws IOException if any
            * @see XmlStreamWriter
            */
           public static XmlStreamWriter newXmlWriter( @Nonnull File file )
      @@ -123,10 +134,11 @@
           /**
            * Create a new Writer with default platform encoding.
            *
      -     * @param out not null output stream.
      -     * @return a writer instance for the output stream using the default platform charset.
      -     * @see java.nio.charset.Charset#defaultCharset()
      +     * @param out not null output stream
      +     * @return a writer instance for the output stream using the default platform charset
      +     * @deprecated always specify an encoding. Do not depend on the default platform character set.
            */
      +    @Deprecated
           public static Writer newPlatformWriter( @Nonnull OutputStream out )
           {
               return new OutputStreamWriter( out );
      @@ -135,11 +147,12 @@
           /**
            * Create a new Writer with default platform encoding.
            *
      -     * @param file not null file.
      -     * @return a writer instance for the output file using the default platform charset.
      -     * @throws IOException if any.
      -     * @see java.nio.charset.Charset#defaultCharset()
      +     * @param file not null file
      +     * @return a writer instance for the output file using the default platform charset
      +     * @throws IOException if any
      +     * @deprecated always specify an encoding. Do not depend on the default platform character set.
            */
      +    @Deprecated
           public static Writer newPlatformWriter( @Nonnull File file )
               throws IOException
           {
      @@ -149,11 +162,12 @@
           /**
            * Create a new Writer with specified encoding.
            *
      -     * @param out not null output stream.
      -     * @param encoding not null supported encoding.
      -     * @return a writer instance for the output stream using the given encoding.
      -     * @throws UnsupportedEncodingException if any.
      -     * @see Supported encodings
      +     * @param out not null output stream
      +     * @param encoding not null supported encoding
      +     * @return a writer instance for the output stream using the given encoding
      +     * @throws UnsupportedEncodingException if any
      +     * @see Supported
      +     *         encodings
            */
           public static Writer newWriter( @Nonnull OutputStream out, @Nonnull String encoding )
               throws UnsupportedEncodingException
      @@ -164,12 +178,13 @@
           /**
            * Create a new Writer with specified encoding.
            *
      -     * @param file not null file.
      -     * @param encoding not null supported encoding.
      -     * @return a writer instance for the output file using the given encoding.
      -     * @throws UnsupportedEncodingException if any.
      -     * @throws FileNotFoundException if any.
      -     * @see Supported encodings
      +     * @param file not null file
      +     * @param encoding not null supported encoding
      +     * @return a writer instance for the output file using the given encoding
      +     * @throws UnsupportedEncodingException if any
      +     * @throws FileNotFoundException if any
      +     * @see Supported
      +     *         encodings
            */
           public static Writer newWriter( @Nonnull File file, @Nonnull String encoding )
               throws UnsupportedEncodingException, FileNotFoundException
      diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/PrettyPrintXMLWriter.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/PrettyPrintXMLWriter.java
      --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/PrettyPrintXMLWriter.java	2017-08-08 19:49:52.000000000 +0000
      +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/PrettyPrintXMLWriter.java	2021-04-26 13:54:15.000000000 +0000
      @@ -23,14 +23,11 @@
       import java.io.PrintWriter;
       import java.io.Writer;
       import java.util.ArrayList;
      -import org.apache.maven.shared.utils.Os;
       
       /**
      - * XMLWriter with nice indentation
      - */
      -/**
      + * XMLWriter with nice indentation.
      + * 
        * @author kama
      - *
        */
       public class PrettyPrintXMLWriter
           implements XMLWriter
      @@ -63,7 +60,7 @@
       
           /**
            * @param writer not null
      -     * @param lineIndent could be null, but the normal way is some spaces.
      +     * @param lineIndent can be null, but the normal way is some spaces
            */
           public PrettyPrintXMLWriter( PrintWriter writer, String lineIndent )
           {
      @@ -72,7 +69,7 @@
       
           /**
            * @param writer not null
      -     * @param lineIndent could be null, but the normal way is some spaces.
      +     * @param lineIndent can be null, but the normal way is some spaces.
            */
           public PrettyPrintXMLWriter( Writer writer, String lineIndent )
           {
      @@ -97,20 +94,20 @@
       
           /**
            * @param writer not null
      -     * @param lineIndent could be null, but the normal way is some spaces.
      -     * @param encoding could be null or invalid.
      -     * @param doctype could be null.
      +     * @param lineIndent can be null, but the normal way is some spaces
      +     * @param encoding can be null or invalid
      +     * @param doctype can be null
            */
           public PrettyPrintXMLWriter( PrintWriter writer, String lineIndent, String encoding, String doctype )
           {
      -        this( writer, lineIndent.toCharArray(), Os.LINE_SEP.toCharArray(), encoding, doctype );
      +        this( writer, lineIndent.toCharArray(), "\n".toCharArray(), encoding, doctype );
           }
       
           /**
            * @param writer not null
      -     * @param lineIndent could be null, but the normal way is some spaces.
      -     * @param encoding could be null or invalid.
      -     * @param doctype could be null.
      +     * @param lineIndent can be null, but the normal way is some spaces
      +     * @param encoding can be null or invalid
      +     * @param doctype can be null
            */
           public PrettyPrintXMLWriter( Writer writer, String lineIndent, String encoding, String doctype )
           {
      @@ -119,18 +116,18 @@
       
           /**
            * @param writer not null
      -     * @param encoding could be null or invalid.
      -     * @param doctype could be null.
      +     * @param encoding can be null or invalid
      +     * @param doctype can be null
            */
           public PrettyPrintXMLWriter( PrintWriter writer, String encoding, String doctype )
           {
      -        this( writer, DEFAULT_LINE_INDENT, Os.LINE_SEP.toCharArray(), encoding, doctype );
      +        this( writer, DEFAULT_LINE_INDENT, "\n".toCharArray(), encoding, doctype );
           }
       
           /**
            * @param writer not null
      -     * @param encoding could be null or invalid.
      -     * @param doctype could be null.
      +     * @param encoding can be null or invalid
      +     * @param doctype can be null
            */
           public PrettyPrintXMLWriter( Writer writer, String encoding, String doctype )
           {
      @@ -139,10 +136,10 @@
       
           /**
            * @param writer not null
      -     * @param lineIndent could be null, but the normal way is some spaces.
      -     * @param lineSeparator could be null, but the normal way is valid line separator
      -     * @param encoding could be null or the encoding to use.
      -     * @param doctype could be null.
      +     * @param lineIndent can be null, but the normal way is some spaces.
      +     * @param lineSeparator can be null, but the normal way is valid line separator
      +     * @param encoding can be null or the encoding to use.
      +     * @param doctype can be null
            */
           public PrettyPrintXMLWriter( PrintWriter writer, String lineIndent, String lineSeparator, String encoding,
                                        String doctype )
      @@ -152,10 +149,10 @@
       
           /**
            * @param writer        not null
      -     * @param lineIndent    could be null, but the normal way is some spaces.
      -     * @param lineSeparator could be null, but the normal way is valid line separator
      -     * @param encoding      could be null or the encoding to use.
      -     * @param doctype       could be null.
      +     * @param lineIndent    can be null, but the normal way is some spaces
      +     * @param lineSeparator can be null, but the normal way is valid line separator
      +     * @param encoding      can be null or the encoding to use
      +     * @param doctype       can be null
            */
           private PrettyPrintXMLWriter( PrintWriter writer, char[] lineIndent, char[] lineSeparator, String encoding,
                                         String doctype )
      @@ -214,7 +211,7 @@
           }
       
           /**
      -     * @param lineSeparator The line separator to be used.
      +     * @param lineSeparator the line separator to be output
            */
           public void setLineSeparator( String lineSeparator )
           {
      @@ -227,7 +224,7 @@
           }
       
           /**
      -     * @param lineIndentParameter The line indent parameter.
      +     * @param lineIndentParameter the line indent parameter
            */
           public void setLineIndenter( String lineIndentParameter )
           {
      @@ -242,6 +239,12 @@
           /** {@inheritDoc} */
           public void startElement( String elementName ) throws IOException
           {
      +        
      +        if ( elementName.isEmpty() )
      +        {
      +            throw new IllegalArgumentException( "Element name cannot be empty" );
      +        }
      +        
               boolean firstLine = ensureDocumentStarted();
       
               completePreviouslyOpenedElement();
      @@ -328,7 +331,7 @@
           }
       
           /**
      -     * Write the documents if not already done.
      +     * Write the document if not already done.
            *
            * @return true if the document headers have freshly been written.
            */
      @@ -366,10 +369,10 @@
       
               if ( docType != null )
               {
      -            newLine();
                   writer.write( "' );
      +            newLine();
               }
           }
       
      diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java
      --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java	2017-08-08 19:49:52.000000000 +0000
      +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/XmlReaderException.java	2021-04-26 13:54:15.000000000 +0000
      @@ -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 @@ 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 @@ } /** - * 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 @@ /** * Returns the BOM encoding found in the InputStream. - *

      * * @return the BOM encoding, null if none. */ @@ -109,7 +103,6 @@ /** * 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 @@ /** * 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 @@ /** * 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 @@ /** * 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 @@ /** * Returns the unconsumed InputStream to allow the application to do an alternate encoding detection on the * InputStream. - *

      * * @return the unconsumed InputStream. */ diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReaderException.java 2021-04-26 13:54:15.000000000 +0000 @@ -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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReader.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReader.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReader.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/XmlStreamReader.java 2021-04-26 13:54:15.000000000 +0000 @@ -29,8 +29,9 @@ import java.util.regex.Pattern; /** - * + * @deprecated use org.apache.commons.io.input.XmlStreamReader instead */ +@Deprecated public class XmlStreamReader extends Reader { @@ -56,7 +57,7 @@ /** * @param file The file to create it from. - * @throws IOException in case of an error. + * @throws IOException in case of an error */ public XmlStreamReader( File file ) throws IOException @@ -66,7 +67,7 @@ /** * @param is {@link InputStream} - * @throws IOException in case of an error. + * @throws IOException in case of an error */ public XmlStreamReader( InputStream is ) throws IOException @@ -77,8 +78,8 @@ /** * @param is {@link InputStream} * @param lenient yes/no - * @throws IOException in case of an error. - * @throws XmlStreamReaderException in case of an error. + * @throws IOException in case of an error + * @throws XmlStreamReaderException in case of an error */ public XmlStreamReader( InputStream is, boolean lenient ) throws IOException, XmlStreamReaderException @@ -88,7 +89,7 @@ /** * @param url {@link URL} - * @throws IOException in case of error. + * @throws IOException in case of error */ public XmlStreamReader( URL url ) throws IOException @@ -97,8 +98,8 @@ } /** - * @param conn The URL connection {@link URLConnection}. - * @throws IOException in case of error. + * @param conn The URL connection {@link URLConnection} + * @throws IOException in case of error */ public XmlStreamReader( URLConnection conn ) throws IOException @@ -108,8 +109,8 @@ /** * @param is {@link InputStream} - * @param httpContentType content type. - * @throws IOException in case of error. + * @param httpContentType content type + * @throws IOException in case of error */ public XmlStreamReader( InputStream is, String httpContentType ) throws IOException @@ -119,11 +120,11 @@ /** * @param is {@link InputStream} - * @param httpContentType content type. - * @param lenient yes/no. - * @param defaultEncoding The default encoding. - * @throws IOException in case of error. - * @throws XmlStreamReaderException in case of error. + * @param httpContentType content type + * @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 @@ -136,10 +137,10 @@ /** * @param is {@link InputStream} - * @param httpContentType content type. - * @param lenient yes/no. - * @throws IOException in case of error. - * @throws XmlStreamReaderException in case of error. + * @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 @@ -148,7 +149,7 @@ } /** - * @return The current encoding. + * @return the current encoding */ public String getEncoding() { diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/XMLWriter.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/XMLWriter.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/XMLWriter.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/XMLWriter.java 2021-04-26 13:54:15.000000000 +0000 @@ -30,7 +30,7 @@ /** * 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 @@ 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 @@ /** * 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 @@ 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 @@ 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 -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/XmlWriterUtil.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/XmlWriterUtil.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/XmlWriterUtil.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/XmlWriterUtil.java 2021-04-26 13:54:15.000000000 +0000 @@ -26,7 +26,7 @@ * Utility class for the XmlWriter class. * * @author Vincent Siveton - * @version $Id$ + * */ public class XmlWriterUtil { diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilder.java 2021-04-26 13:54:15.000000000 +0000 @@ -19,12 +19,10 @@ * under the License. */ -import org.apache.maven.shared.utils.io.IOUtil; import org.apache.maven.shared.utils.xml.pull.XmlPullParserException; 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; @@ -48,8 +46,8 @@ /** * @param reader {@link Reader} - * @return the built dom. - * @throws XmlPullParserException in case of an error. + * @return the built DOM + * @throws XmlPullParserException in case of an error */ public static Xpp3Dom build( @WillClose @Nonnull Reader reader ) throws XmlPullParserException @@ -59,9 +57,9 @@ /** * @param is {@link InputStream} - * @param encoding The encoding. - * @return the built dom. - * @throws XmlPullParserException in case of an error. + * @param encoding the encoding + * @return the built DOM + * @throws XmlPullParserException in case of an error */ public static Xpp3Dom build( @WillClose InputStream is, @Nonnull String encoding ) throws XmlPullParserException @@ -71,10 +69,10 @@ /** * @param is {@link InputStream} - * @param encoding The encoding. - * @param trim true/false. - * @return the built dom. - * @throws XmlPullParserException in case of an error. + * @param encoding the encoding + * @param trim true/false + * @return the built DOM + * @throws XmlPullParserException in case of an error */ public static Xpp3Dom build( @WillClose InputStream is, @Nonnull String encoding, boolean trim ) throws XmlPullParserException @@ -86,34 +84,29 @@ } catch ( UnsupportedEncodingException e ) { - throw new RuntimeException( e ); + throw new XmlPullParserException( e ); } } /** - * @param reader {@link Reader} - * @param trim true/false. - * @return the built dom. - * @throws XmlPullParserException in case of an error. + * @param in {@link Reader} + * @param trim true/false + * @return the built DOM + * @throws XmlPullParserException in case of an error */ - public static Xpp3Dom build( @WillClose Reader reader, boolean trim ) + public static Xpp3Dom build( @WillClose Reader in, boolean trim ) throws XmlPullParserException { - try + try ( Reader reader = in ) { DocHandler docHandler = parseSax( new InputSource( reader ), trim ); reader.close(); - reader = null; return docHandler.result; } catch ( final IOException e ) { throw new XmlPullParserException( e ); } - finally - { - IOUtil.close( reader ); - } } private static DocHandler parseSax( @Nonnull InputSource inputSource, boolean trim ) @@ -194,14 +187,6 @@ 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; @@ -223,8 +208,6 @@ attachToParent( child ); pushOnStack( child ); - // Todo: Detecting tags that close immediately seem to be impossible in sax ? - // http://stackoverflow.com/questions/12968390/detecting-self-closing-tags-in-sax values.add( new StringBuilder() ); int size = attributes.getLength(); @@ -251,27 +234,6 @@ } } - @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; diff -Nru maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java --- maven-shared-utils-3.3.0/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/main/java/org/apache/maven/shared/utils/xml/Xpp3Dom.java 2021-04-26 13:54:15.000000000 +0000 @@ -311,15 +311,6 @@ this.parent = parent; } - // Todo: Support writing to serializer (>1.0) - // public void writeToSerializer( String namespace, XmlSerializer serializer ) - // throws IOException - - private static Xpp3Dom merge( Xpp3Dom dominant, Xpp3Dom recessive, Boolean childMergeOverride ) - { - return Xpp3DomUtils.merge( dominant, recessive, childMergeOverride ); - } - /** * @param dominant The dominant part. * @param recessive The recessive part. diff -Nru maven-shared-utils-3.3.0/src/site/apt/index.apt.vm maven-shared-utils-3.3.4/src/site/apt/index.apt.vm --- maven-shared-utils-3.3.0/src/site/apt/index.apt.vm 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/site/apt/index.apt.vm 2021-04-26 13:54:15.000000000 +0000 @@ -40,22 +40,13 @@ Why? - plexus-utils consisted mostly of code that was forked from various apache projects. + plexus-utils consisted mostly of code that was forked from various Apache projects. maven-shared-utils is based on the original from the Apache sources. Why not commons? - We would prefer code to use commons-* code where appropriate, but the plexus-utils became + We would prefer code to use commons-* where appropriate, but the plexus-utils became slightly incompatible (different) from the commons over the years, so migrating is not always a 1:1 operation. Migrating to maven-shared-utils is a 1:1 operation in most cases. -Relation to Commons-* - - maven-shared-utils internally use {{{http://commons.apache.org/io/}commons-io}}. We shade all commons - classes into our own private package to prevent classpath clashes. - - This is the reason why any public API in maven-shared-utils must - avoid to expose commons-io classes directly. Most times it's sufficient - to just create an empty subclass and expose that instead. - [] diff -Nru maven-shared-utils-3.3.0/src/site/xdoc/download.xml.vm maven-shared-utils-3.3.4/src/site/xdoc/download.xml.vm --- maven-shared-utils-3.3.0/src/site/xdoc/download.xml.vm 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/site/xdoc/download.xml.vm 2021-04-26 13:54:15.000000000 +0000 @@ -34,7 +34,7 @@

      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 @@ ${project.name} ${project.version} (Source zip) maven/shared/${project.artifactId}-${project.version}-source-release.zip - maven/shared/${project.artifactId}-${project.version}-source-release.zip.md5 - maven/shared/${project.artifactId}-${project.version}-source-release.zip.asc + maven/shared/${project.artifactId}-${project.version}-source-release.zip.sha512 + maven/shared/${project.artifactId}-${project.version}-source-release.zip.asc diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/CaseTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/CaseTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/CaseTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/CaseTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -21,7 +21,7 @@ import java.util.Locale; -import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.text.StringEscapeUtils; import org.junit.AfterClass; import org.junit.Assert; import org.junit.ComparisonFailure; @@ -145,7 +145,8 @@ // check result String expectedToUpperCase = upper; String expectedToLowerCase = lower; - if ( LOCALE_TURKISH.getLanguage().equals( locale.getLanguage() ) ) + 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 ); diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/cli/CommandLineUtilsTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/cli/CommandLineUtilsTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/cli/CommandLineUtilsTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/cli/CommandLineUtilsTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -19,22 +19,31 @@ * under the License. */ +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItemInArray; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + import java.util.Arrays; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Properties; + import org.apache.maven.shared.utils.Os; -import junit.framework.TestCase; +import org.junit.Test; public class CommandLineUtilsTest - extends TestCase { /** * Tests that case-insensitive environment variables are normalized to upper case. */ + @Test public void testGetSystemEnvVarsCaseInsensitive() { Properties vars = CommandLineUtils.getSystemEnvVars( false ); @@ -45,6 +54,7 @@ } } + @Test public void testEnsureCaseSensitivity() throws Exception { @@ -57,6 +67,7 @@ /** * Tests that environment variables on Windows are normalized to upper case. Does nothing on Unix platforms. */ + @Test public void testGetSystemEnvVarsWindows() throws Exception { @@ -75,6 +86,7 @@ /** * Tests the splitting of a command line into distinct arguments. */ + @Test public void testTranslateCommandline() throws Exception { @@ -91,7 +103,67 @@ assertCmdLineArgs( new String[] { "foo", " ' ", "bar" }, "foo \" ' \" bar" ); } - private void assertCmdLineArgs( String[] expected, String cmdLine ) + + @Test + public void givenASingleQuoteMarkInArgument_whenExecutingCode_thenNoExceptionIsThrown() throws Exception { + new Commandline("echo \"let's go\"").execute(); + } + + @Test + public void givenADoubleQuoteMarkInArgument_whenExecutingCode_thenCommandLineExceptionIsThrown() throws Exception { + try { + new Commandline("echo \"let\"s go\"").execute(); + } catch (CommandLineException e) { + assertTrue(true); + return; + } + fail("Exception was not thrown when given invalid (3 unescaped double quote) input"); + } + + + @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); + assertEquals(0, p.exitValue()); + } + + @Test + public void givenASingleQuoteMarkInArgument_whenTranslatingToCmdLineArgs_thenTheQuotationMarkIsNotEscaped() + throws Exception + { + final String command = "echo \"let's go\""; + final String[] expected = new String[] { "echo", "let's go" }; + assertCmdLineArgs( expected, command ); + } + + @Test + public void givenAnEscapedDoubleQuoteMarkInArgument_whenTranslatingToCmdLineArgs_thenTheQuotationMarkRemainsEscaped() + throws Exception + { + final String command = "echo \"let\\\"s go\""; + final String[] expected = new String[] { "echo", "let\\\"s go" }; + assertCmdLineArgs( expected, command ); + } + + @Test + public void givenAnEscapedSingleQuoteMarkInArgument_whenTranslatingToCmdLineArgs_thenTheQuotationMarkRemainsEscaped() + throws Exception + { + final String command = "echo \"let\\'s go\""; + final String[] expected = new String[] { "echo", "let\\'s go"}; + assertCmdLineArgs( expected, command ); + } + + @Test + public void givenAnEscapedDoubleQuoteMarkInArgument_whenTranslatingToCmdLineArgs_thenNoExceptionIsThrown() + throws Exception + { + new Commandline( "echo \"let\\\"s go\"" ).execute(); + } + + private void assertCmdLineArgs( final String[] expected, final String cmdLine ) throws Exception { String[] actual = CommandLineUtils.translateCommandline( cmdLine ); @@ -100,4 +172,39 @@ assertEquals( Arrays.asList( expected ), Arrays.asList( actual ) ); } + @Test + public void environmentVariableWithNullShouldNotBeSet() { + + Commandline commandline = new Commandline(); + commandline.addEnvironment("TEST_NULL_ENV", null); + + String[] environmentVariables = commandline.getEnvironmentVariables(); + + assertNotNull( environmentVariables ); + assertThat( environmentVariables, not( hasItemInArray( "TEST_NULL_ENV=null" ) ) ); + } + + @Test + public void environmentVariableFromSystemIsCopied() { + + Commandline commandline = new Commandline(); + + String[] environmentVariables = commandline.getEnvironmentVariables(); + + assertNotNull(environmentVariables); + assertThat(environmentVariables, hasItemInArray( "TEST_SHARED_ENV=TestValue" ) ); + } + + @Test + public void environmentVariableFromSystemIsRemoved() { + + Commandline commandline = new Commandline(); + commandline.addEnvironment("TEST_SHARED_ENV", null); + + String[] environmentVariables = commandline.getEnvironmentVariables(); + + assertNotNull(environmentVariables); + assertThat(environmentVariables, not ( hasItemInArray( "TEST_SHARED_ENV=TestValue" ) ) ); + } + } diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/cli/shell/BourneShellTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -42,9 +42,9 @@ 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 ); + assertEquals( "/bin/sh -c cd '/usr/local/bin' && 'chmod'", executable ); } public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes() @@ -54,9 +54,9 @@ 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 ); + assertEquals( "/bin/sh -c cd '/usr/local/'\"'\"'something else'\"'\"'' && 'chmod'", executable ); } public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep() @@ -66,9 +66,9 @@ 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 ); + assertEquals( "/bin/sh -c cd '\\usr\\local\\'\"'\"'something else'\"'\"'' && 'chmod'", executable ); } public void testPreserveSingleQuotesOnArgument() @@ -78,13 +78,11 @@ 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 ); - assertTrue( cli.endsWith( args[0] ) ); + assertTrue( cli.endsWith( "'\"some arg with spaces\"'" ) ); } public void testAddSingleQuotesOnArgumentWithSpaces() @@ -94,16 +92,26 @@ 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 ); - 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" ); + + List shellCommandLine = sh.getShellCommandLine("arg'withquote"); + + assertEquals("cd '/usr/bin' && 'chmod' 'arg'\"'\"'withquote'", shellCommandLine.get(shellCommandLine.size() - 1)); } - public void testArgumentsWithsemicolon() + public void testArgumentsWithSemicolon() { System.out.println( "---- semi colon tests ----" ); @@ -113,13 +121,11 @@ 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 ); - assertTrue( cli.endsWith( "\'" + args[0] + "\'" ) ); + assertTrue( cli.endsWith( "';some&argwithunix$chars'" ) ); Commandline commandline = new Commandline( newShell() ); commandline.setExecutable( "chmod" ); @@ -132,7 +138,7 @@ 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 +150,7 @@ 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 ); @@ -186,13 +192,14 @@ 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 ) ); } diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/ExpandTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/ExpandTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/ExpandTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/ExpandTest.java 1970-01-01 00:00:00.000000000 +0000 @@ -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 ) ); - } -} diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractorTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractorTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractorTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/introspection/ReflectionValueExtractorTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -30,7 +30,7 @@ /** * @author Jason van Zyl - * @version $Id$ + * */ public class ReflectionValueExtractorTest extends TestCase diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/DirectoryScannerTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/DirectoryScannerTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/DirectoryScannerTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/DirectoryScannerTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -36,8 +36,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeFalse; -import static org.junit.Assume.assumeTrue; +@SuppressWarnings( "deprecation" ) public class DirectoryScannerTest { private static final String[] NONE = new String[0]; @@ -50,7 +50,10 @@ { File rootDir = tempFolder.getRoot(); File folder1 = new File( rootDir, "folder1" ); - folder1.mkdirs(); + if ( !folder1.mkdirs() ) + { + Assert.fail(); + } FileTestHelper.generateTestFile( new File( rootDir, "file1.txt" ), 11 ); FileTestHelper.generateTestFile( new File( rootDir, "file2.txt" ), 12 ); @@ -60,7 +63,10 @@ FileTestHelper.generateTestFile( new File( folder1, "file5.dat" ), 15 ); File folder2 = new File( folder1, "ignorefolder" ); - folder2.mkdirs(); + if ( !folder2.mkdirs() ) + { + Assert.fail(); + } FileTestHelper.generateTestFile( new File( folder2, "file7.txt" ), 17 ); } @@ -129,13 +135,17 @@ ds.setBasedir( new File( "src/test/resources/symlinks/src" ) ); ds.setFollowSymlinks( false ); ds.scan(); + String[] includedDirectories = ds.getIncludedDirectories(); + // FIXME 3 (Windows) and 5 (Linux) are both wrong. The correct answer is 4. + // This method is broken in different ways on different operating systems. + assertTrue( includedDirectories.length == 3 || includedDirectories.length == 5); + String[] files = ds.getIncludedFiles(); + assertAlwaysIncluded( Arrays.asList( files ) ); - //FIXME: This should be changed to some kind of assert...WhatEver()... - System.out.println( "files = " + files ); - - + // FIXME getIncludedFiles is broken on Windows; correct answer is 9 + assertTrue("files.length is " + files.length, files.length == 9 || files.length == 11 ); } @Test @@ -143,7 +153,6 @@ throws IOException { assumeFalse( Os.isFamily( Os.FAMILY_WINDOWS ) ); - assumeTrue( Java7Support.isAtLeastJava7() ); File testDir = SymlinkTestSetup.createStandardSymlinkTestDir( new File( "target/test/symlinkTestCase" ) ); @@ -155,7 +164,7 @@ assertAlwaysIncluded( included ); assertEquals( 9, included.size() ); List includedDirs = Arrays.asList( ds.getIncludedDirectories() ); - assertTrue( includedDirs.contains( "" ) ); // w00t ! + assertTrue( includedDirs.contains( "" ) ); assertTrue( includedDirs.contains( "aRegularDir" ) ); assertTrue( includedDirs.contains( "symDir" ) ); assertTrue( includedDirs.contains( "symLinkToDirOnTheOutside" ) ); @@ -165,8 +174,8 @@ private void assertAlwaysIncluded( List included ) { - assertTrue( included.contains( "aRegularDir/aRegularFile.txt" ) ); - assertTrue( included.contains( "targetDir/targetFile.txt" ) ); + assertTrue( included.contains( "aRegularDir" + File.separator + "aRegularFile.txt" ) ); + assertTrue( included.contains( "targetDir" + File.separator + "targetFile.txt" ) ); assertTrue( included.contains( "fileR.txt" ) ); assertTrue( included.contains( "fileW.txt" ) ); assertTrue( included.contains( "fileX.txt" ) ); @@ -181,7 +190,6 @@ throws IOException { assumeFalse( Os.isFamily( Os.FAMILY_WINDOWS ) ); - assumeTrue( Java7Support.isAtLeastJava7() ); DirectoryScanner ds = new DirectoryScanner(); File testDir = SymlinkTestSetup.createStandardSymlinkTestDir( new File( "target/test/symlinkTestCase" ) ); @@ -207,7 +215,6 @@ /* Creates a standard directory layout with symlinks and files. */ - @Test public void testSimpleExcludes() throws Exception @@ -236,7 +243,7 @@ /* expExclDirs */ NONE ); } - public void testIsSymLin() + public void testIsSymbolicLink() throws IOException { File file = new File( "." ); diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/DirectoryWalkerTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/DirectoryWalkerTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/DirectoryWalkerTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/DirectoryWalkerTest.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +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 org.junit.Assert; - -public class DirectoryWalkerTest -{ - @Test - public void testDirectoryWalk() - { - DirectoryWalker walker = new DirectoryWalker(); - - walker.addSCMExcludes(); - - walker.setBaseDir( new File("src/test/resources/directorywalker" ) ); - - WalkCollector collector = new WalkCollector(); - walker.addDirectoryWalkListener( collector ); - - walker.scan(); - - Assert.assertEquals( "Walk Collector / Starting Count", 1, collector.startCount ); - Assert.assertNotNull( "Walk Collector / Starting Dir", collector.startingDir ); - Assert.assertEquals( "Walk Collector / Finish Count", 1, collector.finishCount ); - Assert.assertEquals( "Walk Collector / Steps Count", 4, collector.steps.size() ); - Assert.assertTrue( "Walk Collector / percentage low >= 0", collector.percentageLow >= 0 ); - Assert.assertTrue( "Walk Collector / percentage high <= 100", collector.percentageHigh <= 100 ); - } -} diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/FileUtilsTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -4,26 +4,47 @@ 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.assertEquals; 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; import static org.junit.Assume.assumeThat; -import static org.junit.Assume.assumeTrue; +import org.apache.commons.io.IOUtils; +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 @@ -44,16 +65,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. * @@ -64,6 +75,7 @@ * @version $Id: FileUtilsTestCase.java 1081025 2011-03-13 00:45:10Z niallp $ * @see FileUtils */ +@SuppressWarnings( "deprecation" ) public class FileUtilsTest { @@ -80,11 +92,6 @@ */ 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; @@ -115,25 +122,17 @@ createFile( testFile2, testFile2Size ); } - void createFile( File file, long size ) + private static void createFile( File file, long size ) throws IOException { if ( !file.getParentFile().exists() ) { 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 ); } } @@ -141,13 +140,12 @@ /** * Assert that the content of a file is equal to that in a byte[]. */ - void assertEqualContent( byte[] b0, File file ) + private 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 ) { @@ -157,20 +155,16 @@ assertThat( "Different number of bytes: ", count, is( b0.length ) ); for ( int i = 0; i < count; i++ ) { - assertThat( "byte " + i + " differs", b1[i], is( b0[i] ) ); + assertEquals( "byte " + i + " differs", b1[i], b0[i] ); } } - finally - { - is.close(); - } } - void deleteFile( File file ) + private void deleteFile( File file ) { if ( file.exists() ) { - assertThat( "Couldn't delete file: " + file, file.delete(), is( true ) ); + assertTrue( "Couldn't delete file: " + file, file.delete() ); } } @@ -253,26 +247,6 @@ 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 @@ -333,17 +307,12 @@ 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() } @@ -438,11 +407,297 @@ 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 { - assumeTrue( Java7Support.isAtLeastJava7() ); + 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!" + ); + + 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 static 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, + IOUtils.toString( in ) + ); + } + } + + @Test + public void copyFileThatIsSymlink() + throws Exception + { assumeFalse( Os.isFamily( Os.FAMILY_WINDOWS ) ); File destination = new File( tempFolder.getRoot(), "symCopy.txt" ); @@ -450,9 +705,9 @@ 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() ) ); + } @Test @@ -491,6 +746,26 @@ } @Test + public void copyFileWithPermissions() + throws Exception + { + 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-copy" ); + + FileUtils.copyFile( source, destination ); + + 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 public void copyFile2() throws Exception { @@ -509,9 +784,7 @@ } @Test - @Ignore( "Commons test case that is failing for plexus" ) - public void copyToSelf() - throws Exception + public void copyToSelf() throws IOException { File destination = new File( tempFolder.getRoot(), "copy3.txt" ); //Prepare a test file @@ -521,33 +794,6 @@ } @Test - @Ignore( "Commons test case that is failing for plexus" ) - public void copyDirectoryToDirectory_NonExistingDest() - throws Exception - { - createFile( testFile1, 1234 ); - createFile( testFile2, 4321 ); - File srcDir = tempFolder.getRoot(); - File subDir = new File( srcDir, "sub" ); - subDir.mkdir(); - File subFile = new File( subDir, "A.txt" ); - FileUtils.fileWrite( subFile, "UTF8", "HELLO WORLD" ); - File destDir = new File( System.getProperty( "java.io.tmpdir" ), "tmp-FileUtilsTestCase" ); - FileUtils.deleteDirectory( destDir ); - File actualDestDir = new File( destDir, srcDir.getName() ); - - FileUtils.copyDirectory( srcDir, destDir ); - - assertThat( "Check exists", destDir.exists(), is( true ) ); - assertThat( "Check exists", actualDestDir.exists(), is( true ) ); - assertThat( "Check size", FileUtils.sizeOfDirectory( actualDestDir ), - is( FileUtils.sizeOfDirectory( srcDir ) ) ); - assertThat( new File( actualDestDir, "sub/A.txt" ).exists(), is( true ) ); - FileUtils.deleteDirectory( destDir ); - } - - @Test - @Ignore( "Commons test case that is failing for plexus" ) public void copyDirectoryToNonExistingDest() throws Exception { @@ -563,130 +809,34 @@ FileUtils.copyDirectory( srcDir, destDir ); - assertThat( "Check exists", destDir.exists(), is( true ) ); - assertThat( "Check size", FileUtils.sizeOfDirectory( destDir ), is( FileUtils.sizeOfDirectory( srcDir ) ) ); - assertThat( new File( destDir, "sub/A.txt" ).exists(), is( true ) ); + assertTrue( destDir.exists() ); + assertEquals( FileUtils.sizeOfDirectory( destDir ), FileUtils.sizeOfDirectory( srcDir ) ); + assertTrue( new File( destDir, "sub/A.txt" ).exists() ); FileUtils.deleteDirectory( destDir ); } @Test - @Ignore( "Commons test case that is failing for plexus" ) - public void copyDirectoryToExistingDest() - throws Exception + public void copyDirectoryToExistingDest() throws IOException { createFile( testFile1, 1234 ); createFile( testFile2, 4321 ); File srcDir = tempFolder.getRoot(); File subDir = new File( srcDir, "sub" ); - subDir.mkdir(); + assertTrue( subDir.mkdir() ); File subFile = new File( subDir, "A.txt" ); FileUtils.fileWrite( subFile, "UTF8", "HELLO WORLD" ); File destDir = new File( System.getProperty( "java.io.tmpdir" ), "tmp-FileUtilsTestCase" ); FileUtils.deleteDirectory( destDir ); - destDir.mkdirs(); + assertTrue ( destDir.mkdirs() ); FileUtils.copyDirectory( srcDir, destDir ); - assertThat( FileUtils.sizeOfDirectory( destDir ), is( FileUtils.sizeOfDirectory( srcDir ) ) ); - assertThat( new File( destDir, "sub/A.txt" ).exists(), is( true ) ); - } - - /** - * Test for IO-141 - */ - @Test - @Ignore( "Commons test case that is failing for plexus" ) - public void copyDirectoryToChild() - throws Exception - { - File grandParentDir = new File( tempFolder.getRoot(), "grandparent" ); - File parentDir = new File( grandParentDir, "parent" ); - File childDir = new File( parentDir, "child" ); - createFilesForTestCopyDirectory( grandParentDir, parentDir, childDir ); - - long expectedCount = - FileUtils.getFileAndDirectoryNames( grandParentDir, null, null, true, true, true, true ).size() - + FileUtils.getFileAndDirectoryNames( parentDir, null, null, true, true, true, true ).size(); - long expectedSize = FileUtils.sizeOfDirectory( grandParentDir ) + FileUtils.sizeOfDirectory( parentDir ); - FileUtils.copyDirectory( parentDir, childDir ); - assertThat( - 1L * FileUtils.getFileAndDirectoryNames( grandParentDir, null, null, true, true, true, true ).size(), - is( expectedCount ) ); - assertThat( FileUtils.sizeOfDirectory( grandParentDir ), is( expectedSize ) ); - } - - /** - * Test for IO-141 - */ - @Test - @Ignore( "Commons test case that is failing for plexus" ) - public void copyDirectoryToGrandChild() - throws Exception - { - File grandParentDir = new File( tempFolder.getRoot(), "grandparent" ); - File parentDir = new File( grandParentDir, "parent" ); - File childDir = new File( parentDir, "child" ); - createFilesForTestCopyDirectory( grandParentDir, parentDir, childDir ); - - long expectedCount = - ( FileUtils.getFileAndDirectoryNames( grandParentDir, null, null, true, true, true, true ).size() * 2 ); - long expectedSize = ( FileUtils.sizeOfDirectory( grandParentDir ) * 2 ); - FileUtils.copyDirectory( grandParentDir, childDir ); - assertThat( - 1L * FileUtils.getFileAndDirectoryNames( grandParentDir, null, null, true, true, true, true ).size(), - is( expectedCount ) ); - assertThat( FileUtils.sizeOfDirectory( grandParentDir ), is( expectedSize ) ); + assertEquals( FileUtils.sizeOfDirectory( destDir ), FileUtils.sizeOfDirectory( srcDir ) ); + assertTrue( new File( destDir, "sub/A.txt" ).exists() ); } - /** - * Test for IO-217 FileUtils.copyDirectoryToDirectory makes infinite loops - */ @Test - public void copyDirectoryToItself() - throws Exception - { - File dir = new File( tempFolder.getRoot(), "itself" ); - dir.mkdirs(); - FileUtils.copyDirectory( dir, dir ); - assertThat( FileUtils.getFileAndDirectoryNames( dir, null, null, true, true, true, true ).size(), is( 1 ) ); - } - - private void createFilesForTestCopyDirectory( File grandParentDir, File parentDir, File childDir ) - throws Exception - { - File childDir2 = new File( parentDir, "child2" ); - File grandChildDir = new File( childDir, "grandChild" ); - File grandChild2Dir = new File( childDir2, "grandChild2" ); - File file1 = new File( grandParentDir, "file1.txt" ); - File file2 = new File( parentDir, "file2.txt" ); - File file3 = new File( childDir, "file3.txt" ); - File file4 = new File( childDir2, "file4.txt" ); - File file5 = new File( grandChildDir, "file5.txt" ); - File file6 = new File( grandChild2Dir, "file6.txt" ); - FileUtils.deleteDirectory( grandParentDir ); - grandChildDir.mkdirs(); - grandChild2Dir.mkdirs(); - FileUtils.fileWrite( file1, "UTF8", "File 1 in grandparent" ); - FileUtils.fileWrite( file2, "UTF8", "File 2 in parent" ); - FileUtils.fileWrite( file3, "UTF8", "File 3 in child" ); - FileUtils.fileWrite( file4, "UTF8", "File 4 in child2" ); - FileUtils.fileWrite( file5, "UTF8", "File 5 in grandChild" ); - FileUtils.fileWrite( file6, "UTF8", "File 6 in grandChild2" ); - } - - @Test - @Ignore( "Commons test case that is failing for plexus" ) - public void copyDirectoryErrors() - throws Exception - { - try - { - FileUtils.copyDirectory( null, null ); - fail(); - } - catch ( NullPointerException ex ) - { - } + public void copyDirectoryErrors_nullDestination() throws IOException { try { FileUtils.copyDirectory( new File( "a" ), null ); @@ -695,41 +845,43 @@ catch ( NullPointerException ex ) { } + } + + @Test + public void copyDirectoryErrors_copyToSelf() { try { - FileUtils.copyDirectory( null, new File( "a" ) ); - fail(); - } - catch ( NullPointerException ex ) - { - } - try - { - FileUtils.copyDirectory( new File( "doesnt-exist" ), new File( "a" ) ); + FileUtils.copyDirectory( tempFolder.getRoot(), tempFolder.getRoot() ); fail(); } catch ( IOException ex ) { } + } + + @Test + public void copyDirectoryErrors() + throws IOException + { try { - FileUtils.copyDirectory( testFile1, new File( "a" ) ); + FileUtils.copyDirectory( null, null ); fail(); } - catch ( IOException ex ) + catch ( NullPointerException ex ) { } try { - FileUtils.copyDirectory( tempFolder.getRoot(), testFile1 ); + FileUtils.copyDirectory( null, new File( "a" ) ); fail(); } - catch ( IOException ex ) + catch ( NullPointerException ex ) { } try { - FileUtils.copyDirectory( tempFolder.getRoot(), tempFolder.getRoot() ); + FileUtils.copyDirectory( tempFolder.getRoot(), testFile1 ); fail(); } catch ( IOException ex ) @@ -745,9 +897,9 @@ { File destination = new File( tempFolder.getRoot(), "copy1.txt" ); destination.createNewFile(); - assertThat( "Copy1.txt doesn't exist to delete", destination.exists(), is( true ) ); + assertTrue( "Copy1.txt doesn't exist to delete", destination.exists() ); FileUtils.forceDelete( destination ); - assertThat( "Check No Exist", !destination.exists(), is( true ) ); + assertFalse( destination.exists() ); } @Test @@ -860,15 +1012,10 @@ 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" ); @@ -1113,7 +1260,6 @@ //// getDefaultExcludesAsList @Test - @SuppressWarnings( "unchecked" ) public void getDefaultExcludesAsList() throws Exception { @@ -1406,11 +1552,10 @@ 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 )); - assertTrue(FileUtils.isSymbolicLinkLegacy(file )); } @Test @@ -1420,7 +1565,6 @@ { File file = new File( "src/test/resources/symlinks/src/" ); assertFalse(FileUtils.isSymbolicLink(file )); - assertFalse(FileUtils.isSymbolicLinkLegacy(file )); } @Test @@ -1439,6 +1583,44 @@ assertThat( FileUtils.extension( "/test/foo.bar.txt" ), is( "txt" ) ); } + @Test + public void createAndReadSymlink() + throws Exception + { + assumeFalse( Os.isFamily( Os.FAMILY_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() ); + } + + @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 = { diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/IOUtilTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/IOUtilTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/IOUtilTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/IOUtilTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -38,8 +38,9 @@ import java.util.concurrent.atomic.AtomicBoolean; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +@SuppressWarnings( "deprecation" ) public class IOUtilTest { diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/Java7SupportTest.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +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; -import static org.hamcrest.CoreMatchers.startsWith; - -public class Java7SupportTest -{ - @Test - 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 ); - } - } - -} diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/MatchPatternsTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/MatchPatternsTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/MatchPatternsTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/MatchPatternsTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -26,11 +26,11 @@ /** * @author Kristian Rosenvold */ +@SuppressWarnings( "deprecation" ) public class MatchPatternsTest { @Test public void matches() - throws Exception { MatchPatterns from = MatchPatterns.from( "ABC**", "CDE**" ); assertTrue( from.matches( "ABCDE", true ) ); diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/MatchPatternTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/MatchPatternTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/MatchPatternTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/MatchPatternTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -25,11 +25,11 @@ /** * @author Kristian Rosenvold */ +@SuppressWarnings( "deprecation" ) public class MatchPatternTest { @Test public void matchPath() - throws Exception { MatchPattern mp = MatchPattern.fromString( "ABC*" ); assertTrue( mp.matchPath( "ABCD", true ) ); diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/SelectorUtilsTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/SelectorUtilsTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/SelectorUtilsTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/SelectorUtilsTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -27,8 +27,8 @@ /** * Test the {@link SelectorUtils} class. - * */ +@SuppressWarnings( "deprecation" ) public class SelectorUtilsTest { @@ -67,7 +67,6 @@ assertAntDoesNotMatch( "/aaa/", "\\aaa\\bbb" ); } - private void assertAntDoesNotMatch( String pattern, String target ) { assertEquals( false, SelectorUtils.matchPatternStart( wrapWithAntHandler( pattern ), target ) ); diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/SymlinkTestSetup.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/SymlinkTestSetup.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/io/SymlinkTestSetup.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/io/SymlinkTestSetup.java 2021-04-26 13:54:15.000000000 +0000 @@ -3,6 +3,7 @@ import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import static org.apache.commons.io.FileUtils.write; @@ -36,28 +37,26 @@ srcDir.mkdirs(); File target = new File( srcDir, "targetDir" ); target.mkdirs(); - write( new File( target, "targetFile.txt" ), "a regular File payload" ); + write( new File( target, "targetFile.txt" ), "a regular File payload", StandardCharsets.UTF_8 ); File aRegularDir = new File( srcDir, "aRegularDir" ); aRegularDir.mkdirs(); - write( new File( aRegularDir, "aRegularFile.txt" ), "a regular File payload" ); + write( new File( aRegularDir, "aRegularFile.txt" ), "a regular File payload", StandardCharsets.UTF_8 ); File dirOnTheOutside = new File( root, "dirOnTheOutside" ); dirOnTheOutside.mkdirs(); - write( new File( dirOnTheOutside, "FileInDirOnTheOutside.txt" ), "a file in dir on the outside" ); - write( new File( root, "onTheOutside.txt" ), "A file on the outside" ); - write( new File( srcDir, "fileR.txt" ), "FileR payload" ); - write( new File( srcDir, "fileW.txt" ), "FileW payload" ); - write( new File( srcDir, "fileX.txt" ), "FileX payload" ); + write( new File( dirOnTheOutside, "FileInDirOnTheOutside.txt" ), "a file in dir on the outside", StandardCharsets.UTF_8 ); + write( new File( root, "onTheOutside.txt" ), "A file on the outside", StandardCharsets.UTF_8 ); + write( new File( srcDir, "fileR.txt" ), "FileR payload", StandardCharsets.UTF_8 ); + write( new File( srcDir, "fileW.txt" ), "FileW payload", StandardCharsets.UTF_8 ); + 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; } } diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilderTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilderTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilderTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/logging/AnsiMessageBuilderTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -23,7 +23,7 @@ import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class AnsiMessageBuilderTest { diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/logging/MessageUtilsTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/logging/MessageUtilsTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/logging/MessageUtilsTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/logging/MessageUtilsTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -21,10 +21,19 @@ import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.sameInstance; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; +import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import org.fusesource.jansi.AnsiColors; +import org.fusesource.jansi.AnsiConsole; +import org.fusesource.jansi.AnsiMode; +import org.fusesource.jansi.AnsiPrintStream; +import org.fusesource.jansi.AnsiType; +import org.fusesource.jansi.io.AnsiOutputStream; import org.junit.Test; public class MessageUtilsTest @@ -45,4 +54,24 @@ System.setOut( currentOut ); } } + + @Test + public void testTerminalWidth() + { + AnsiOutputStream.WidthSupplier width = new AnsiOutputStream.WidthSupplier() + { + @Override + public int getTerminalWidth() + { + return 33; + } + }; + AnsiOutputStream aos = new AnsiOutputStream( new ByteArrayOutputStream(), width, AnsiMode.Default, + null, AnsiType.Emulation, AnsiColors.Colors256, StandardCharsets.UTF_8, + null, null, false ); + AnsiConsole.systemInstall(); + AnsiConsole.out = new AnsiPrintStream( aos, true ); + assertEquals( 33, MessageUtils.getTerminalWidth() ); + AnsiConsole.systemUninstall(); + } } diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/OsTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/OsTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/OsTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/OsTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -24,113 +24,79 @@ import org.junit.After; import org.junit.Assert; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; import java.util.Set; import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; /** - * This class will test the 'Os' class which evaluates - * operation system specific settings. + * Tests the 'Os' class which evaluates operation system specific settings. * * @author Mark Struberg */ public class OsTest - extends Assert { private String origOsName; - private String origOsFamily; private String origOsArch; private String origOsVersion; @Before public void setUp() - throws Exception { origOsName = System.getProperty( "os.name" ); origOsArch = System.getProperty( "os.arch" ); origOsVersion = System.getProperty( "os.version" ); - origOsFamily = Os.OS_FAMILY; // and now set some special settings ;) System.setProperty( "os.name" , "os/2" ); System.setProperty( "os.arch" , "i386" ); System.setProperty( "os.version", "2.1.32" ); - - // blow away the originally loaded values - setStaticOsField( "OS_NAME", "os/2" ); - setStaticOsField( "OS_FAMILY", "os/2" ); - setStaticOsField( "OS_ARCH", "i386" ); - setStaticOsField( "OS_VERSION", "2.1.32" ); } @After public void tearDown() - throws Exception { // set the original OS settings again System.setProperty( "os.name" , origOsName ); System.setProperty( "os.arch" , origOsArch ); System.setProperty( "os.version", origOsVersion ); - - // restore the originally loaded values - setStaticOsField( "OS_NAME", origOsName ); - setStaticOsField( "OS_ARCH", origOsArch ); - setStaticOsField( "OS_VERSION", origOsVersion ); - setStaticOsField( "OS_FAMILY", origOsFamily ); - } - - private void setStaticOsField( String variableName, Object value ) - throws NoSuchFieldException, IllegalAccessException - { - Field field = Os.class.getField( variableName ); - - Field modifiersField = Field.class.getDeclaredField( "modifiers" ); - modifiersField.setAccessible( true ); - modifiersField.setInt( field, field.getModifiers() & ~Modifier.FINAL ); - - field.setAccessible( true ); - field.set( null, value ); } - @Test public void testConstructor() - throws Exception { Os os = new Os(); os.eval(); - assertTrue( Os.isName( Os.FAMILY_OS2 ) ); + Assert.assertTrue( Os.isName( Os.FAMILY_OS2 ) ); - assertFalse( Os.isName( Os.FAMILY_DOS ) ); - assertFalse( Os.isName( Os.FAMILY_MAC ) ); - assertFalse( Os.isName( Os.FAMILY_NETWARE ) ); - assertFalse( Os.isName( Os.FAMILY_OPENVMS ) ); - assertFalse( Os.isName( Os.FAMILY_OS400 ) ); - assertFalse( Os.isName( Os.FAMILY_TANDEM ) ); - assertFalse( Os.isName( Os.FAMILY_UNIX ) ); - assertFalse( Os.isName( Os.FAMILY_WIN9X ) ); - assertFalse( Os.isName( Os.FAMILY_WINDOWS ) ); - assertFalse( Os.isName( Os.FAMILY_ZOS ) ); + 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() { - assertEquals( Os.FAMILY_DOS, "dos" ); - assertEquals( Os.FAMILY_MAC, "mac" ); - assertEquals( Os.FAMILY_NETWARE, "netware" ); - assertEquals( Os.FAMILY_OPENVMS, "openvms" ); - assertEquals( Os.FAMILY_OS2, "os/2" ); - assertEquals( Os.FAMILY_OS400, "os/400" ); - assertEquals( Os.FAMILY_TANDEM, "tandem" ); - assertEquals( Os.FAMILY_UNIX, "unix" ); - assertEquals( Os.FAMILY_WIN9X, "win9x" ); - assertEquals( Os.FAMILY_WINDOWS, "windows" ); - assertEquals( Os.FAMILY_ZOS, "z/os" ); + 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 @@ -138,20 +104,20 @@ { Set osFamilies = Os.getValidFamilies(); - assertTrue( "OsFamilies Set size" + Assert.assertTrue( "OsFamilies Set size" , osFamilies.size() >= 11 ); - assert( osFamilies.contains( Os.FAMILY_DOS ) ); - assert( osFamilies.contains( Os.FAMILY_MAC ) ); - assert( osFamilies.contains( Os.FAMILY_NETWARE ) ); - assert( osFamilies.contains( Os.FAMILY_OPENVMS ) ); - assert( osFamilies.contains( Os.FAMILY_OS2 ) ); - assert( osFamilies.contains( Os.FAMILY_OS400 ) ); - assert( osFamilies.contains( Os.FAMILY_TANDEM ) ); - assert( osFamilies.contains( Os.FAMILY_UNIX ) ); - assert( osFamilies.contains( Os.FAMILY_WIN9X ) ); - assert( osFamilies.contains( Os.FAMILY_WINDOWS ) ); - assert( osFamilies.contains( Os.FAMILY_ZOS ) ); + Assert.assertTrue( osFamilies.contains( Os.FAMILY_DOS ) ); + Assert.assertTrue( osFamilies.contains( Os.FAMILY_MAC ) ); + Assert.assertTrue( osFamilies.contains( Os.FAMILY_NETWARE ) ); + Assert.assertTrue( osFamilies.contains( Os.FAMILY_OPENVMS ) ); + Assert.assertTrue( osFamilies.contains( Os.FAMILY_OS2 ) ); + Assert.assertTrue( osFamilies.contains( Os.FAMILY_OS400 ) ); + Assert.assertTrue( osFamilies.contains( Os.FAMILY_TANDEM ) ); + Assert.assertTrue( osFamilies.contains( Os.FAMILY_UNIX ) ); + Assert.assertTrue( osFamilies.contains( Os.FAMILY_WIN9X ) ); + Assert.assertTrue( osFamilies.contains( Os.FAMILY_WINDOWS ) ); + Assert.assertTrue( osFamilies.contains( Os.FAMILY_ZOS ) ); } diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/PathToolTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/PathToolTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/PathToolTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/PathToolTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -23,21 +23,21 @@ import org.junit.Assume; import org.junit.Rule; import org.junit.Test; -import org.junit.Assert; import org.junit.rules.TemporaryFolder; import java.io.File; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + /** * Test the {@link PathTool} class. * - * We don't need to test this * @author Mark Struberg */ -public class PathToolTest extends Assert +public class PathToolTest { @Rule diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/PropertyUtilsTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/PropertyUtilsTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/PropertyUtilsTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/PropertyUtilsTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -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; @@ -31,14 +33,13 @@ 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; 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 +68,15 @@ { 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 +147,7 @@ @Test @SuppressWarnings( "deprecation" ) - public void loadValidInputStream() - throws Exception + public void loadValidInputStream() throws UnsupportedEncodingException { Properties value = new Properties(); value.setProperty( "a", "b" ); @@ -154,50 +163,32 @@ @Test @NeedsTemporaryFolder @SuppressWarnings( "deprecation" ) - public void loadValidFile() - throws Exception + 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 @NeedsTemporaryFolder @SuppressWarnings( "deprecation" ) - public void loadValidURL() - throws Exception + 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 ) ); } } diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/reflection/ReflectorTestHelper.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/reflection/ReflectorTestHelper.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/reflection/ReflectorTestHelper.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/reflection/ReflectorTestHelper.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,119 +0,0 @@ -package org.apache.maven.shared.utils.reflection; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * 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. - */ - -/** - * - * @author stephenc - */ -class ReflectorTestHelper -{ - static String PACKAGE_STATIC_STRING = "package static string"; - protected static String PROTECTED_STATIC_STRING = "protected static string"; - public static String PUBLIC_STATIC_STRING = "public static string"; - - private ReflectorTestHelper() - { - } - - ReflectorTestHelper( Boolean throwSomething ) - { - if ( Boolean.TRUE.equals( throwSomething ) ) - { - throw new HelperException( "Something" ); - } - } - - protected ReflectorTestHelper( Integer throwCount ) - { - if ( throwCount != null && throwCount > 0 ) - { - throw new HelperException( "Something" ); - } - } - - public ReflectorTestHelper( String throwMessage ) - { - if ( throwMessage != null && throwMessage.length() > 0 ) - { - throw new HelperException( throwMessage ); - } - } - - static ReflectorTestHelper getInstance( Boolean throwSomething ) - { - if ( Boolean.TRUE.equals( throwSomething ) ) - { - throw new HelperException( "Something" ); - } - return new ReflectorTestHelper(); - } - - protected static ReflectorTestHelper getInstance( Integer throwCount ) - { - if ( throwCount != null && throwCount > 0 ) - { - throw new HelperException( "Something" ); - } - return new ReflectorTestHelper(); - } - - public static ReflectorTestHelper getInstance( String throwMessage ) - { - if ( throwMessage != null && throwMessage.length() > 0 ) - { - throw new HelperException( throwMessage ); - } - return new ReflectorTestHelper(); - } - - public ReflectorTestHelper getInstance( String aString, Boolean aBoolean ) - { - return new ReflectorTestHelper(); - } - - public static class HelperException - extends RuntimeException - { - /** - * - */ - private static final long serialVersionUID = -3395757415194358525L; - - public HelperException() - { - super(); //To change body of overridden methods use File | Settings | File Templates. - } - - public HelperException( String message ) - { - super( message ); //To change body of overridden methods use File | Settings | File Templates. - } - - public HelperException( String message, Throwable cause ) - { - super( message, cause ); //To change body of overridden methods use File | Settings | File Templates. - } - - public HelperException( Throwable cause ) - { - super( cause ); //To change body of overridden methods use File | Settings | File Templates. - } - } -} diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/reflection/ReflectorTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/reflection/ReflectorTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/reflection/ReflectorTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/reflection/ReflectorTest.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,1232 +0,0 @@ -package org.apache.maven.shared.utils.reflection; - -/* - * 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.junit.Test; - -import java.lang.reflect.Constructor; - -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import static org.apache.maven.shared.utils.testhelpers.ExceptionHelper.*; - -/** - * @author Stephen Connolly - */ -public class ReflectorTest -{ - private final Reflector reflector = new Reflector(); - - //// newInstance( Class, Object[] ) - - @Test( expected = NullPointerException.class ) - public void newInstanceNullNull() - throws Exception - { - reflector.newInstance( (Class)null, (Object)null ); - } - - @Test - public void newInstanceClassNull() - throws Exception - { - assertThat( reflector.newInstance( Object.class, null ), is( Object.class ) ); - } - - @Test( expected = NullPointerException.class ) - public void newInstanceNullEmptyArray() - throws Exception - { - reflector.newInstance( null, new Object[0] ); - } - - @Test - public void newInstanceClassEmptyArray() - throws Exception - { - assertThat( reflector.newInstance( Object.class, new Object[0] ), is( Object.class ) ); - } - - @Test( expected = ReflectorException.class ) - public void newInstanceClassInvalidSignature() - throws Exception - { - reflector.newInstance( Object.class, new Object[]{ this } ); - } - - @Test( expected = ReflectorException.class ) - public void newInstancePrivateConstructor() - throws Exception - { - reflector.newInstance( ReflectorTestHelper.class, new Object[0] ); - } - - @Test( expected = IllegalArgumentException.class ) - // // @ReproducesPlexusBug( "Looking up constructors by signature has an unlabelled continue, so finds the wrong constructor" ) - public void newInstancePackageConstructor() - throws Exception - { - reflector.newInstance( ReflectorTestHelper.class, new Object[]{ Boolean.FALSE } ); - } - - @Test( expected = IllegalArgumentException.class ) - // // @ReproducesPlexusBug( "Looking up constructors by signature has an unlabelled continue, so finds the wrong constructor" ) - public void newInstancePackageConstructorThrowsSomething() - throws Exception - { - reflector.newInstance( ReflectorTestHelper.class, new Object[]{ Boolean.TRUE } ); - } - - @Test( expected = IllegalArgumentException.class ) - // // @ReproducesPlexusBug("Looking up constructors by signature has an unlabelled continue, so finds the wrong constructor" ) - public void newInstanceProtectedConstructor() - throws Exception - { - reflector.newInstance( ReflectorTestHelper.class, new Object[]{ 0 } ); - } - - @Test( expected = IllegalArgumentException.class ) - // // @ReproducesPlexusBug( "Looking up constructors by signature has an unlabelled continue, so finds the wrong constructor" ) - public void newInstanceProtectedConstructorThrowsSomething() - throws Exception - { - reflector.newInstance( ReflectorTestHelper.class, new Object[]{ 1 } ); - } - - @Test - public void newInstancePublicConstructor() - throws Exception - { - assertTrue( reflector.newInstance( ReflectorTestHelper.class, new Object[]{ "" } ) - instanceof ReflectorTestHelper ); - } - - @Test( expected = NullPointerException.class ) - public void newInstancePublicConstructorNullValue() - throws Exception - { - reflector.newInstance( ReflectorTestHelper.class, new Object[]{ null } ); - } - - @Test - public void newInstancePublicConstructorThrowsSomething() - throws Exception - { - try - { - reflector.newInstance( ReflectorTestHelper.class, new Object[]{ "Message" } ); - fail(); - } - catch ( ReflectorException e ) - { - assertThat( e, hasCause( ReflectorTestHelper.HelperException.class ) ); - } - } - - //// getSingleton( Class, Object[] ) - - @Test( expected = NullPointerException.class ) - public void getSingletonNullNull() - throws Exception - { - reflector.getSingleton( (Class)null, (Object)null ); - } - - @Test( expected = NullPointerException.class ) - public void getSingletonClassNull() - throws Exception - { - assertThat( reflector.getSingleton( (Class)Object.class, (Object)null ), is( Object.class ) ); - } - - @Test( expected = NullPointerException.class ) - public void getSingletonNullEmptyArray() - throws Exception - { - reflector.getSingleton( null, new Object[0] ); - } - - @Test( expected = ReflectorException.class ) - public void getSingletonClassEmptyArray() - throws Exception - { - assertThat( reflector.getSingleton( Object.class, new Object[0] ), is( Object.class ) ); - } - - @Test( expected = ReflectorException.class ) - public void getSingletonClassInvalidSignature() - throws Exception - { - reflector.getSingleton( Object.class, new Object[]{ this } ); - } - - @Test( expected = ReflectorException.class ) - public void getSingletonPrivateMethod() - throws Exception - { - reflector.getSingleton( ReflectorTestHelper.class, new Object[0] ); - } - - @Test( expected = IllegalArgumentException.class ) - // @ReproducesPlexusBug( "Looking up methods by signature has an unlabeled continue, so finds the wrong method" ) - public void getSingletonPackageMethod() - throws Exception - { - reflector.getSingleton( ReflectorTestHelper.class, new Object[]{ Boolean.FALSE } ); - } - - @Test( expected = IllegalArgumentException.class ) - // @ReproducesPlexusBug( "Looking up methods by signature has an unlabeled continue, so finds the wrong method" ) - public void getSingletonPackageMethodThrowsSomething() - throws Exception - { - reflector.getSingleton( ReflectorTestHelper.class, new Object[]{ Boolean.TRUE } ); - } - - @Test( expected = IllegalArgumentException.class ) - // @ReproducesPlexusBug( "Looking up methods by signature has an unlabeled continue, so finds the wrong method" ) - public void getSingletonProtectedMethod() - throws Exception - { - reflector.getSingleton( ReflectorTestHelper.class, new Object[]{ 0 } ); - } - - @Test( expected = IllegalArgumentException.class ) - // @ReproducesPlexusBug( "Looking up methods by signature has an unlabeled continue, so finds the wrong method" ) - public void getSingletonProtectedMethodThrowsSomething() - throws Exception - { - reflector.getSingleton( ReflectorTestHelper.class, new Object[]{ 1 } ); - } - - @Test - public void getSingletonPublicMethod() - throws Exception - { - assertTrue( reflector.getSingleton( ReflectorTestHelper.class, new Object[]{ "" } ) - instanceof ReflectorTestHelper ); - } - - @Test( expected = NullPointerException.class ) - public void getSingletonPublicMethodNullValue() - throws Exception - { - reflector.getSingleton( ReflectorTestHelper.class, new Object[]{ null } ); - } - - @Test - public void getSingletonPublicMethodThrowsSomething() - throws Exception - { - try - { - reflector.getSingleton( ReflectorTestHelper.class, new Object[]{ "Message" } ); - fail(); - } - catch ( ReflectorException e ) - { - assertThat( e, hasCause( ReflectorTestHelper.HelperException.class ) ); - } - } - - @Test( expected = NullPointerException.class ) - public void getSingletonNonStaticMethod() - throws Exception - { - assertTrue( reflector.getSingleton( ReflectorTestHelper.class, new Object[]{ "", Boolean.FALSE } ) - instanceof ReflectorTestHelper ); - } - - //// invoke( Object, String, Object[] ) - - @Test( expected = NullPointerException.class ) - public void invokeNullNullNull() - throws Exception - { - reflector.invoke( (Object)null, (String)null, (Object)null ); - } - - @Test( expected = NullPointerException.class ) - public void invokeNullNullEmpty() - throws Exception - { - reflector.invoke( null, null, new Object[0] ); - } - - @Test( expected = NullPointerException.class ) - public void invokeNullEmptyNull() - throws Exception - { - reflector.invoke( (Object)null, "", (Object)null ); - } - - @Test( expected = NullPointerException.class ) - public void invokeNullEmptyEmpty() - throws Exception - { - reflector.invoke( null, "", new Object[0] ); - } - - @Test( expected = NullPointerException.class ) - public void invokeObjectNullNull() - throws Exception - { - reflector.invoke( new Object(), (String)null, (Object)null ); - } - - @Test( expected = NullPointerException.class ) - public void invokeObjectNullEmpty() - throws Exception - { - reflector.invoke( new Object(), null, new Object[0] ); - } - - @Test( expected = ReflectorException.class ) - public void invokeObjectEmptyNull() - throws Exception - { - reflector.invoke( new Object(), "", null ); - } - - @Test( expected = ReflectorException.class ) - public void invokeObjectEmptyEmpty() - throws Exception - { - reflector.invoke( new Object(), "", new Object[0] ); - } - - @Test - public void invokeObjectValidNull() - throws Exception - { - Object object = new Object(); - assertThat( reflector.invoke( object, "hashCode", null ), is( (Object) object.hashCode() ) ); - } - - @Test - public void invokeObjectValidEmpty() - throws Exception - { - Object object = new Object(); - assertThat( reflector.invoke( object, "hashCode", new Object[0] ), - is( (Object) object.hashCode() ) ); - } - - @Test( expected = ReflectorException.class ) - public void invokeObjectValidWrongSignature() - throws Exception - { - reflector.invoke( new Object(), "hashCode", new Object[]{ this } ); - } - - @Test( expected = ReflectorException.class ) - public void invokePrivateMethod() - throws Exception - { - class CoT - { - @SuppressWarnings( "unused" ) - private Object doSomething() - { - return "Done"; - } - } - assertThat( reflector.invoke( new CoT(), "doSomething", new Object[0] ), is( (Object) "Done" ) ); - } - - @Test( expected = ReflectorException.class ) - public void invokePackageMethod() - throws Exception - { - class CoT - { - @SuppressWarnings( "unused" ) - Object doSomething() - { - return "Done"; - } - } - assertThat( reflector.invoke( new CoT(), "doSomething", new Object[0] ), is( (Object) "Done" ) ); - } - - @Test( expected = ReflectorException.class ) - public void invokeProtectedMethod() - throws Exception - { - class CoT - { - @SuppressWarnings( "unused" ) - protected Object doSomething() - { - return "Done"; - } - } - assertThat( reflector.invoke( new CoT(), "doSomething", new Object[0] ), is( (Object) "Done" ) ); - } - - @Test - public void invokePublicMethod() - throws Exception - { - class CoT - { - @SuppressWarnings( "unused" ) - public Object doSomething() - { - return "Done"; - } - } - assertThat( reflector.invoke( new CoT(), "doSomething", new Object[0] ), is( (Object) "Done" ) ); - } - - //// getStaticField( Class, String ) - - @Test( expected = NullPointerException.class ) - public void getStaticFieldNullNull() - throws Exception - { - reflector.getStaticField( null, null ); - } - - @Test( expected = NullPointerException.class ) - public void getStaticFieldNullEmpty() - throws Exception - { - reflector.getStaticField( null, "" ); - } - - @Test( expected = NullPointerException.class ) - public void getStaticFieldObjectNull() - throws Exception - { - reflector.getStaticField( Object.class, null ); - } - - @Test - public void getStaticFieldObjectEmpty() - throws Exception - { - try - { - reflector.getStaticField( Object.class, "" ); - fail(); - } - catch ( ReflectorException e ) - { - assertThat( e, hasCause( NoSuchFieldException.class ) ); - } - } - - @Test - public void getStaticFieldPrivateField() - throws Exception - { - try - { - reflector.getStaticField( ReflectorTestHelper.class, "PRIVATE_STATIC_STRING" ); - fail(); - } - catch ( ReflectorException e ) - { - assertThat( e, hasCause( NoSuchFieldException.class ) ); - } - } - - @Test - public void getStaticFieldPackageField() - throws Exception - { - try - { - reflector.getStaticField( ReflectorTestHelper.class, "PACKAGE_STATIC_STRING" ); - fail(); - } - catch ( ReflectorException e ) - { - assertThat( e, hasCause( NoSuchFieldException.class ) ); - } - } - - @Test - public void getStaticFieldProtectedField() - throws Exception - { - try - { - reflector.getStaticField( ReflectorTestHelper.class, "PROTECTED_STATIC_STRING" ); - fail(); - } - catch ( ReflectorException e ) - { - assertThat( e, hasCause( NoSuchFieldException.class ) ); - } - } - - @Test - public void getStaticFieldPublicField() - throws Exception - { - assertThat( reflector.getStaticField( ReflectorTestHelper.class, "PUBLIC_STATIC_STRING" ), - is( (Object) "public static string" ) ); - } - - //// getField( Object, String ) - - @Test( expected = NullPointerException.class ) - public void getFieldNullNull() - throws Exception - { - reflector.getField( null, null ); - } - - @Test( expected = NullPointerException.class ) - public void getFieldNullEmpty() - throws Exception - { - reflector.getField( null, "" ); - } - - @Test( expected = NullPointerException.class ) - public void getFieldObjectNull() - throws Exception - { - reflector.getField( new Object(), null ); - } - - @Test - public void getFieldObjectEmpty() - throws Exception - { - try - { - reflector.getField( new Object(), "" ); - fail(); - } - catch ( ReflectorException e ) - { - assertThat( e, hasCause( NoSuchFieldException.class ) ); - } - } - - @Test - public void getFieldCoTValuePrivateField() - throws Exception - { - final String expected = "gotIt"; - class CoT - { - @SuppressWarnings( "unused" ) - private String value = expected; - } - try - { - assertThat( reflector.getField( new CoT(), "value" ), is( (Object) expected ) ); - fail(); - } - catch ( ReflectorException e ) - { - assertThat( e, hasCause( IllegalAccessException.class ) ); - } - } - - @Test - public void getFieldCoTValuePackageField() - throws Exception - { - final String expected = "gotIt"; - class CoT - { - @SuppressWarnings( "unused" ) - String value = expected; - } - assertThat( reflector.getField( new CoT(), "value" ), is( (Object) expected ) ); - } - - @Test - public void getFieldCoTValueProtectedField() - throws Exception - { - final String expected = "gotIt"; - class CoT - { - @SuppressWarnings( "unused" ) - protected String value = expected; - } - assertThat( reflector.getField( new CoT(), "value" ), is( (Object) expected ) ); - } - - @Test - public void getFieldCoTValuePublicField() - throws Exception - { - final String expected = "gotIt"; - class CoT - { - @SuppressWarnings( "unused" ) - public String value = expected; - } - assertThat( reflector.getField( new CoT(), "value" ), is( (Object) expected ) ); - } - - //// getField( Object, String, boolean ) - - @Test( expected = NullPointerException.class ) - public void getFieldNullNullFalse() - throws Exception - { - reflector.getField( null, null, false ); - } - - @Test( expected = NullPointerException.class ) - public void getFieldNullEmptyFalse() - throws Exception - { - reflector.getField( null, "", false ); - } - - @Test( expected = NullPointerException.class ) - public void getFieldObjectNullFalse() - throws Exception - { - reflector.getField( new Object(), null, false ); - } - - @Test - public void getFieldObjectEmptyFalse() - throws Exception - { - try - { - reflector.getField( new Object(), "", false ); - fail(); - } - catch ( ReflectorException e ) - { - assertThat( e, hasCause( NoSuchFieldException.class ) ); - } - } - - @Test - public void getFieldCoTValueFalsePrivateField() - throws Exception - { - final String expected = "gotIt"; - class CoT - { - @SuppressWarnings( "unused" ) - private String value = expected; - } - try - { - assertThat( reflector.getField( new CoT(), "value", false ), is( (Object) expected ) ); - fail(); - } - catch ( ReflectorException e ) - { - assertThat( e, hasCause( IllegalAccessException.class ) ); - } - } - - @Test - public void getFieldCoTValueFalsePackageField() - throws Exception - { - final String expected = "gotIt"; - class CoT - { - @SuppressWarnings( "unused" ) - String value = expected; - } - assertThat( reflector.getField( new CoT(), "value", false ), is( (Object) expected ) ); - } - - @Test - public void getFieldCoTValueFalseProtectedField() - throws Exception - { - final String expected = "gotIt"; - class CoT - { - @SuppressWarnings( "unused" ) - protected String value = expected; - } - assertThat( reflector.getField( new CoT(), "value", false ), is( (Object) expected ) ); - } - - @Test - public void getFieldCoTValueFalsePublicField() - throws Exception - { - final String expected = "gotIt"; - class CoT - { - @SuppressWarnings( "unused" ) - public String value = expected; - } - assertThat( reflector.getField( new CoT(), "value", false ), is( (Object) expected ) ); - } - - @Test( expected = NullPointerException.class ) - public void getFieldNullNullTrue() - throws Exception - { - reflector.getField( null, null, true ); - } - - @Test( expected = NullPointerException.class ) - public void getFieldNullEmptyTrue() - throws Exception - { - reflector.getField( null, "", true ); - } - - @Test( expected = NullPointerException.class ) - public void getFieldObjectNullTrue() - throws Exception - { - reflector.getField( new Object(), null, true ); - } - - @Test - public void getFieldObjectEmptyTrue() - throws Exception - { - try - { - reflector.getField( new Object(), "", true ); - fail(); - } - catch ( ReflectorException e ) - { - assertThat( e, hasCause( NoSuchFieldException.class ) ); - } - } - - @Test - public void getFieldCoTValueTruePrivateField() - throws Exception - { - final String expected = "gotIt"; - class CoT - { - @SuppressWarnings( "unused" ) - private String value = expected; - } - assertThat( reflector.getField( new CoT(), "value", true ), is( (Object) expected ) ); - } - - @Test - public void getFieldCoTValueTruePackageField() - throws Exception - { - final String expected = "gotIt"; - class CoT - { - @SuppressWarnings( "unused" ) - String value = expected; - } - assertThat( reflector.getField( new CoT(), "value", true ), is( (Object) expected ) ); - } - - @Test - public void getFieldCoTValueTrueProtectedField() - throws Exception - { - final String expected = "gotIt"; - class CoT - { - @SuppressWarnings( "unused" ) - protected String value = expected; - } - assertThat( reflector.getField( new CoT(), "value", true ), is( (Object) expected ) ); - } - - @Test - public void getFieldCoTValueTruePublicField() - throws Exception - { - final String expected = "gotIt"; - class CoT - { - @SuppressWarnings( "unused" ) - public String value = expected; - } - assertThat( reflector.getField( new CoT(), "value", true ), is( (Object) expected ) ); - } - - //// invokeStatic( Class, String, Object[] ) - - @Test( expected = NullPointerException.class ) - public void invokeStaticNullNullNull() - throws Exception - { - reflector.invokeStatic( (Class)null, (String)null, (Object)null ); - } - - @Test( expected = NullPointerException.class ) - public void invokeStaticClassNullNull() - throws Exception - { - assertThat( reflector.invokeStatic( Object.class, (String)null, (Object)null ), is( Object.class ) ); - } - - @Test( expected = NullPointerException.class ) - public void invokeStaticNullNullEmptyArray() - throws Exception - { - reflector.invokeStatic( null, null, new Object[0] ); - } - - @Test( expected = NullPointerException.class ) - public void invokeStaticClassNullEmptyArray() - throws Exception - { - assertThat( reflector.invokeStatic( Object.class, null, new Object[0] ), is( Object.class ) ); - } - - @Test( expected = NullPointerException.class ) - public void invokeStaticNullEmptyNull() - throws Exception - { - reflector.invokeStatic( (Class)null, "", (Object)null ); - } - - @Test( expected = ReflectorException.class ) - public void invokeStaticClassEmptyNull() - throws Exception - { - reflector.invokeStatic( Object.class, "", null ); - } - - @Test( expected = NullPointerException.class ) - public void invokeStaticNullEmptyEmptyArray() - throws Exception - { - reflector.invokeStatic( null, "", new Object[0] ); - } - - @Test( expected = ReflectorException.class ) - public void invokeStaticClassEmptyEmptyArray() - throws Exception - { - assertThat( reflector.invokeStatic( Object.class, "", new Object[0] ), is( Object.class ) ); - } - - @Test( expected = IllegalArgumentException.class ) - // @ReproducesPlexusBug( "Looking up methods by signature has an unlabelled continue, so finds the wrong method" ) - public void invokeStaticClassInvalidSignature() - throws Exception - { - reflector.invokeStatic( ReflectorTestHelper.class, "getInstance", new Object[]{ this } ); - } - - @Test( expected = ReflectorException.class ) - public void invokeStaticPrivateMethod() - throws Exception - { - reflector.invokeStatic( ReflectorTestHelper.class, "getInstance", new Object[0] ); - } - - @Test( expected = IllegalArgumentException.class ) - // @ReproducesPlexusBug( "Looking up methods by signature has an unlabelled continue, so finds the wrong method" ) - public void invokeStaticPackageMethod() - throws Exception - { - reflector.invokeStatic( ReflectorTestHelper.class, "getInstance", new Object[]{ Boolean.FALSE } ); - } - - @Test( expected = IllegalArgumentException.class ) - // @ReproducesPlexusBug( "Looking up methods by signature has an unlabelled continue, so finds the wrong method" ) - public void invokeStaticPackageMethodThrowsSomething() - throws Exception - { - reflector.invokeStatic( ReflectorTestHelper.class, "getInstance", new Object[]{ Boolean.TRUE } ); - } - - @Test( expected = IllegalArgumentException.class ) - // @ReproducesPlexusBug( "Looking up methods by signature has an unlabelled continue, so finds the wrong method" ) - public void invokeStaticProtectedMethod() - throws Exception - { - reflector.invokeStatic( ReflectorTestHelper.class, "getInstance", new Object[]{ 0 } ); - } - - @Test( expected = IllegalArgumentException.class ) - // @ReproducesPlexusBug( "Looking up methods by signature has an unlabelled continue, so finds the wrong method" ) - public void invokeStaticProtectedMethodThrowsSomething() - throws Exception - { - reflector.invokeStatic( ReflectorTestHelper.class, "getInstance", new Object[]{ 1 } ); - } - - @Test - public void invokeStaticPublicMethod() - throws Exception - { - assertTrue( reflector.invokeStatic( ReflectorTestHelper.class, "getInstance", new Object[]{ "" } ) - instanceof ReflectorTestHelper ); - } - - @Test( expected = NullPointerException.class ) - public void invokeStaticPublicMethodNullValue() - throws Exception - { - reflector.invokeStatic( ReflectorTestHelper.class, "getInstance", new Object[]{ null } ); - } - - @Test - public void invokeStaticPublicMethodThrowsSomething() - throws Exception - { - try - { - reflector.invokeStatic( ReflectorTestHelper.class, "getInstance", new Object[]{ "Message" } ); - fail(); - } - catch ( ReflectorException e ) - { - assertThat( e, hasCause( ReflectorTestHelper.HelperException.class ) ); - } - } - - @Test( expected = NullPointerException.class ) - public void invokeStaticNonStaticMethod() - throws Exception - { - assertTrue( - reflector.invokeStatic( ReflectorTestHelper.class, "getInstance", new Object[]{ "", Boolean.FALSE } ) - instanceof ReflectorTestHelper ); - } - - //// getConstructor( Class, Class[] ) - - @Test( expected = NullPointerException.class ) - public void getConstructorNullNull() - throws Exception - { - reflector.getConstructor( (Class)null, (Class)null ); - } - - @Test( expected = NullPointerException.class ) - public void getConstructorNullEmpty() - throws Exception - { - reflector.getConstructor( null, new Class[0] ); - } - - @SuppressWarnings( "rawtypes" ) - @Test( expected = NullPointerException.class ) - public void getConstructorObjectNull() - throws Exception - { - assertThat( reflector.getConstructor( Object.class, (Class)null ), - is( (Constructor) Object.class.getDeclaredConstructor() ) ); - } - - @SuppressWarnings( "rawtypes" ) - @Test - public void getConstructorObjectEmpty() - throws Exception - { - assertThat( reflector.getConstructor( Object.class), - is( (Constructor) Object.class.getDeclaredConstructor() ) ); - } - - @SuppressWarnings( "rawtypes" ) - @Test( expected = ReflectorException.class ) - // @ReproducesPlexusBug( "Looking up methods by signature has an unlabelled continue, so finds the wrong method" ) - public void getConstructorPrivate() - throws Exception - { - assertThat( reflector.getConstructor( ReflectorTestHelper.class), - is( (Constructor) ReflectorTestHelper.class.getDeclaredConstructor() ) ); - } - - @SuppressWarnings( "rawtypes" ) - @Test - public void getConstructorPackage() - throws Exception - { - assertThat( reflector.getConstructor( ReflectorTestHelper.class, Boolean.class), - not( is( (Constructor) ReflectorTestHelper.class.getDeclaredConstructor( Boolean.class ) ) ) ); - } - - @SuppressWarnings( "rawtypes" ) - @Test - public void getConstructorProtected() - throws Exception - { - assertThat( reflector.getConstructor( ReflectorTestHelper.class, Integer.class), - not( is( (Constructor) ReflectorTestHelper.class.getDeclaredConstructor( Integer.class ) ) ) ); - } - - @SuppressWarnings( "rawtypes" ) - @Test - public void getConstructorPublic() - throws Exception - { - assertThat( reflector.getConstructor( ReflectorTestHelper.class, String.class), - is( (Constructor) ReflectorTestHelper.class.getDeclaredConstructor( String.class ) ) ); - } - - //// getObjectProperty( Object, String ) - - @Test( expected = ReflectorException.class ) - public void getObjectPropertyNullNull() - throws Exception - { - reflector.getObjectProperty( null, null ); - } - - @Test( expected = ReflectorException.class ) - public void getObjectPropertyNullEmpty() - throws Exception - { - reflector.getObjectProperty( null, "" ); - } - - @Test( expected = ReflectorException.class ) - public void getObjectPropertyObjectNull() - throws Exception - { - reflector.getObjectProperty( new Object(), null ); - } - - @Test( expected = ReflectorException.class ) - public void getObjectPropertyObjectEmpty() - throws Exception - { - reflector.getObjectProperty( new Object(), "" ); - } - - @Test - // @ReproducesPlexusBug( "Should only access public properties" ) - public void getObjectPropertyViaPrivateField() - throws Exception - { - class CoT - { - @SuppressWarnings( "unused" ) - private int value = 42; - } - assertThat( reflector.getObjectProperty( new CoT(), "value" ), is( (Object) 42 ) ); - } - - @Test - // @ReproducesPlexusBug( "Should only access public properties" ) - public void getObjectPropertyViaPackageField() - throws Exception - { - class CoT - { - @SuppressWarnings( "unused" ) - int value = 42; - } - assertThat( reflector.getObjectProperty( new CoT(), "value" ), is( (Object) 42 ) ); - } - - @Test - // @ReproducesPlexusBug( "Should only access public properties" ) - public void getObjectPropertyViaProtectedField() - throws Exception - { - class CoT - { - @SuppressWarnings( "unused" ) - protected int value = 42; - } - assertThat( reflector.getObjectProperty( new CoT(), "value" ), is( (Object) 42 ) ); - } - - @Test - public void getObjectPropertyViaPublicField() - throws Exception - { - class CoT - { - @SuppressWarnings( "unused" ) - public int value = 42; - } - assertThat( reflector.getObjectProperty( new CoT(), "value" ), is( (Object) 42 ) ); - } - - @Test( expected = ReflectorException.class ) - public void getObjectPropertyViaPrivateGetter() - throws Exception - { - class CoT - { - private final int _value = 42; - - @SuppressWarnings( "unused" ) - private int getValue() - { - return _value; - } - } - reflector.getObjectProperty( new CoT(), "value" ); - } - - @Test( expected = ReflectorException.class ) - public void getObjectPropertyViaPackageGetter() - throws Exception - { - class CoT - { - private final int _value = 42; - - @SuppressWarnings( "unused" ) - int getValue() - { - return _value; - } - } - reflector.getObjectProperty( new CoT(), "value" ); - } - - @Test( expected = ReflectorException.class ) - public void getObjectPropertyViaProtectedGetter() - throws Exception - { - class CoT - { - private final int _value = 42; - - @SuppressWarnings( "unused" ) - protected int getValue() - { - return _value; - } - } - reflector.getObjectProperty( new CoT(), "value" ); - } - - @Test - public void getObjectPropertyViaPublicGetter() - throws Exception - { - class CoT - { - private final int _value = 42; - - @SuppressWarnings( "unused" ) - public int getValue() - { - return _value; - } - } - assertThat( reflector.getObjectProperty( new CoT(), "value" ), is( (Object) 42 ) ); - } - - //// getMethod( Class, String, Class[] ) - - @Test( expected = NullPointerException.class ) - public void getMethodNullNullNull() - throws Exception - { - reflector.getMethod( (Class)null, (String)null, (Class)null ); - } - - @Test( expected = NullPointerException.class ) - public void getMethodNullNullEmpty() - throws Exception - { - reflector.getMethod( null, null, new Class[0] ); - } - - @Test( expected = NullPointerException.class ) - public void getMethodObjectNullNull() - throws Exception - { - reflector.getMethod( Object.class, (String)null, (Class)null ); - } - - @Test( expected = NullPointerException.class ) - public void getMethodObjectNullEmpty() - throws Exception - { - reflector.getMethod( Object.class, null, new Class[0] ); - } - - @Test( expected = NullPointerException.class ) - public void getMethodNullEmptyNull() - throws Exception - { - reflector.getMethod( (Class)null, "", (Class)null ); - } - - @Test( expected = NullPointerException.class ) - public void getMethodNullEmptyEmpty() - throws Exception - { - reflector.getMethod( null, "", new Class[0] ); - } - - @Test( expected = NullPointerException.class ) - public void getMethodObjectEmptyNull() - throws Exception - { - reflector.getMethod( Object.class, "", (Class)null ); - } - - @Test( expected = ReflectorException.class ) - public void getMethodObjectEmptyEmpty() - throws Exception - { - reflector.getMethod( Object.class, "", new Class[0] ); - } - - @Test( expected = ReflectorException.class ) - // @ReproducesPlexusBug( "Looking up methods by signature has an unlabelled continue, so finds the wrong method" ) - public void getMethodPrivate() - throws Exception - { - assertThat( reflector.getMethod( ReflectorTestHelper.class, "getInstance", new Class[0] ), - is( ReflectorTestHelper.class.getDeclaredMethod( "getInstance" ) ) ); - } - - @Test - public void getMethodPackage() - throws Exception - { - assertThat( reflector.getMethod( ReflectorTestHelper.class, "getInstance", new Class[]{ Boolean.class } ), - not( is( ReflectorTestHelper.class.getDeclaredMethod( "getInstance", Boolean.class ) ) ) ); - } - - @Test - public void getMethodProtected() - throws Exception - { - assertThat( reflector.getMethod( ReflectorTestHelper.class, "getInstance", new Class[]{ Integer.class } ), - not( is( ReflectorTestHelper.class.getDeclaredMethod( "getInstance", Integer.class ) ) ) ); - } - - @Test - public void getMethodPublic() - throws Exception - { - assertThat( reflector.getMethod( ReflectorTestHelper.class, "getInstance", new Class[]{ String.class } ), - is( ReflectorTestHelper.class.getDeclaredMethod( "getInstance", String.class ) ) ); - } - -} diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/StringUtilsTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/StringUtilsTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/StringUtilsTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/StringUtilsTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -24,28 +24,20 @@ import java.util.Iterator; import java.util.Map; -import org.junit.Assert; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.TemporaryFolder; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; /** * Test the {@link StringUtils} class. - * - * We don't need to test this + * * @author Mark Struberg */ public class StringUtilsTest - extends Assert { - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - @Test( expected = NullPointerException.class ) public void testAbbreviate_NPE() { diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/testhelpers/ExceptionHelper.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/testhelpers/ExceptionHelper.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/testhelpers/ExceptionHelper.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/testhelpers/ExceptionHelper.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,67 +0,0 @@ -package org.apache.maven.shared.utils.testhelpers; - -/* - * 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.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; - - -public class ExceptionHelper -{ - - /** - * A matcher that verifies that the a root cause of an exception is of the specified type. - * - * @param cause the type of exception that caused this. - * @return A matcher that verifies that the a root cause of an exception is of the specified type. - */ - public static Matcher hasCause( Class cause ) - { - return new HasCause( cause ); - } - - private static class HasCause - extends BaseMatcher - { - private final Class cause; - - public HasCause( Class cause ) - { - this.cause = cause; - } - - public boolean matches( Object item ) - { - Throwable throwable = (Throwable) item; - while ( throwable != null && !cause.isInstance( throwable ) ) - { - throwable = throwable.getCause(); - } - return cause.isInstance( throwable ); - } - - public void describeTo( Description description ) - { - description.appendText( "was caused by a " ).appendValue( cause ).appendText( " being thrown" ); - } - } -} diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/testhelpers/FileTestHelper.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/testhelpers/FileTestHelper.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/testhelpers/FileTestHelper.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/testhelpers/FileTestHelper.java 2021-04-26 13:54:15.000000000 +0000 @@ -19,21 +19,26 @@ * under the License. */ -import org.apache.maven.shared.utils.io.FileUtils; -import org.apache.maven.shared.utils.io.IOUtil; -import org.junit.rules.TemporaryFolder; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; + +import org.apache.commons.io.FileUtils; -import java.io.*; +import org.junit.rules.TemporaryFolder; /** - * A few utility methods for file based tests + * A few utility methods for file based tests. */ public final class FileTestHelper { private FileTestHelper() { - // utility function doesn't need a public ct + // utility function doesn't need a public constructor } public static void generateTestData( OutputStream out, long size ) @@ -55,14 +60,12 @@ testfile.delete(); } - OutputStream os = new FileOutputStream( testfile ); - generateTestData( os, size ); - os.flush(); - os.close(); + try ( OutputStream os = new FileOutputStream( testfile ) ) { + generateTestData( os, size ); + os.flush(); + } } - - public static void createLineBasedFile( File file, String[] data ) throws IOException { @@ -71,20 +74,13 @@ throw new IOException( "Cannot create file " + file + " as the parent directory does not exist" ); } - PrintWriter out = null; - try + try ( Writer out = new OutputStreamWriter( new FileOutputStream( file ), "UTF-8" ) ) { - out = new PrintWriter( new OutputStreamWriter( new FileOutputStream( file ), "UTF-8" ) ); for ( String aData : data ) { - out.println( aData ); + out.write( aData ); + out.write( System.lineSeparator() ); } - out.close(); - out = null; - } - finally - { - IOUtil.close( out ); } } @@ -101,7 +97,7 @@ if ( destination.exists() ) { - FileUtils.forceDelete( destination ); + FileUtils.deleteQuietly( destination ); } return destination; } diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/xml/PrettyPrintXmlWriterTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -1,9 +1,5 @@ package org.apache.maven.shared.utils.xml; -import java.io.IOException; -import javax.swing.text.html.HTML; -import java.io.StringWriter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -23,43 +19,37 @@ * under the License. */ +import java.io.IOException; +import java.io.StringWriter; +import javax.swing.text.html.HTML; - -import org.apache.maven.shared.utils.Os; import org.apache.maven.shared.utils.StringUtils; -import org.junit.After; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; /** * Test of {@link PrettyPrintXMLWriter} * * @author Vincent Siveton - * @version $Id$ */ public class PrettyPrintXmlWriterTest { - StringWriter w; - - PrettyPrintXMLWriter writer; - - @Before - public void before() - throws Exception - { - w = new StringWriter(); - writer = new PrettyPrintXMLWriter( w ); + 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() ); + } + } - - @After - public void after() - throws Exception - { - writer = null; - w = null; - } - + @Test public void testDefaultPrettyPrintXMLWriter() throws IOException { @@ -71,7 +61,7 @@ writer.endElement(); // Tag.HTML - Assert.assertEquals( expectedResult( Os.LINE_SEP ), w.toString() ); + Assert.assertEquals( expectedResult(), w.toString() ); } @Test @@ -87,7 +77,7 @@ writer.endElement(); // Tag.HTML - Assert.assertEquals( expectedResult( "\n" ), w.toString() ); + Assert.assertEquals( expectedResult(), w.toString() ); } @Test @@ -103,7 +93,7 @@ writer.endElement(); // Tag.HTML - Assert.assertEquals( expectedResult( " ", Os.LINE_SEP ), w.toString() ); + Assert.assertEquals( expectedResult( " " ), w.toString() ); } @Test @@ -178,13 +168,15 @@ writer.endElement(); // Tag.BODY } - private String expectedResult( String lineSeparator ) + private static String expectedResult() { - return expectedResult( " ", lineSeparator ); + return expectedResult( " " ); } - private String expectedResult( String lineIndenter, String lineSeparator ) + private static String expectedResult( String lineIndenter ) { + + String lineSeparator = "\n"; StringBuilder expected = new StringBuilder(); expected.append( "" ).append( lineSeparator ); diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/xml/XmlWriterUtilTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -29,7 +29,7 @@ /** * @author Vincent Siveton - * @version $Id$ + * */ public class XmlWriterUtilTest extends TestCase diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilderTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilderTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilderTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/xml/Xpp3DomBuilderTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -19,16 +19,20 @@ * under the License. */ -import org.apache.maven.shared.utils.StringUtils; import org.apache.maven.shared.utils.xml.pull.XmlPullParserException; - +import org.junit.Assert; import org.junit.Test; +import java.io.ByteArrayInputStream; import java.io.IOException; +import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -38,16 +42,13 @@ public class Xpp3DomBuilderTest { - private static final String LS = System.getProperty( "line.separator" ); - - private static final String xmlDeclaration = "\n"; + private static final String XML_DECLARATION = "\n"; - @Test + @Test public void selfClosingTag() throws Exception { - // Todo: http://stackoverflow.com/questions/12968390/detecting-self-closing-tags-in-sax String domString = selfClosingTagSource(); Xpp3Dom dom = Xpp3DomBuilder.build( new StringReader( domString ) ); @@ -58,6 +59,22 @@ } @Test + public void testUnrecognizedEncoding() + { + + byte[] data = "".getBytes(StandardCharsets.UTF_8); + InputStream in = new ByteArrayInputStream( data ); + try { + Xpp3DomBuilder.build( in , "nosuch encoding" ); + fail(); + } catch ( XmlPullParserException expected ) { + assertTrue( expected.getCause() instanceof UnsupportedEncodingException ); + } + + } + + + @Test public void trimming() throws Exception { @@ -76,11 +93,15 @@ assertEquals( " preserve space ", dom.getChild( "element6" ).getValue() ); } - @Test(expected = XmlPullParserException.class) - public void malformedXml() + @Test + public void testMalformedXml() { - Xpp3DomBuilder.build( new StringReader( "" + createDomString() ) ); - fail( "We're supposed to fail" ); + try { + Xpp3DomBuilder.build( new StringReader( "" + createDomString() ) ); + fail( "We're supposed to fail" ); + } catch (XmlPullParserException ex) { + Assert.assertNotNull( ex.getMessage() ); + } } @Test @@ -116,9 +137,9 @@ { StringBuilder domString = new StringBuilder(); domString.append( "" ); - domString.append( LS ); + domString.append( "\n" ); domString.append( " bar" ); - domString.append( LS ); + domString.append( "\n" ); domString.append( "" ); return domString.toString(); @@ -140,13 +161,13 @@ { StringBuilder domString = new StringBuilder(); domString.append( "" ); - domString.append( LS ); + domString.append( "\n" ); domString.append( " \"msg\"" ); - domString.append( LS ); + domString.append( "\n" ); domString.append( " <b>\"msg\"</b>" ); - domString.append( LS ); + domString.append( "\n" ); domString.append( " <b>\"msg\"</b>" ); - domString.append( LS ); + domString.append( "\n" ); domString.append( "" ); return domString.toString(); } @@ -174,12 +195,12 @@ buf.append( " \n" ); buf.append( " \n" ); buf.append( "" ); - return StringUtils.unifyLineSeparators( buf.toString() ); + return buf.toString(); } private static String expectedSelfClosingTag() { - return StringUtils.unifyLineSeparators( xmlDeclaration + selfClosingTagSource() ); + return XML_DECLARATION + selfClosingTagSource(); } } diff -Nru maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/XmlStreamReaderTest.java maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/XmlStreamReaderTest.java --- maven-shared-utils-3.3.0/src/test/java/org/apache/maven/shared/utils/XmlStreamReaderTest.java 2017-08-08 19:49:52.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/java/org/apache/maven/shared/utils/XmlStreamReaderTest.java 2021-04-26 13:54:15.000000000 +0000 @@ -27,7 +27,8 @@ import junit.framework.ComparisonFailure; import junit.framework.TestCase; -import org.apache.maven.shared.utils.io.IOUtil; + +import org.apache.commons.io.IOUtils; import org.apache.maven.shared.utils.xml.XmlStreamReader; /** @@ -55,8 +56,6 @@ private static final byte[] BOM_UTF8 = { (byte)0xEF, (byte)0xBB, (byte)0xBF }; private static final byte[] BOM_UTF16BE = { (byte)0xFE, (byte)0xFF }; private static final byte[] BOM_UTF16LE = { (byte)0xFF, (byte)0xFE }; - private static final byte[] BOM_UTF32BE = { (byte)0x00, (byte)0x00, (byte)0xFF, (byte)0xFE }; - private static final byte[] BOM_UTF32LE = { (byte)0xFF, (byte)0xFE, (byte)0x00, (byte)0x00 }; private static String createXmlContent( String text, String encoding ) { @@ -68,18 +67,16 @@ return xmlDecl + "\n" + text + ""; } - private static void checkXmlContent( String xml, String encoding ) - throws IOException + private static void checkXmlContent( String xml, String encoding ) throws IOException { checkXmlContent( xml, encoding, null ); } - private static void checkXmlContent( String xml, String encoding, byte[] bom ) - throws IOException + private static void checkXmlContent( String xml, String encoding, byte[] bom ) throws IOException { byte[] xmlContent = xml.getBytes( encoding ); InputStream in = new ByteArrayInputStream( xmlContent ); - + if ( bom != null ) { in = new SequenceInputStream( new ByteArrayInputStream( bom ), in ); @@ -87,109 +84,95 @@ XmlStreamReader reader = new XmlStreamReader( in ); assertEquals( encoding, reader.getEncoding() ); - String result = IOUtil.toString( reader ); + String result = IOUtils.toString( reader ); assertEquals( xml, result ); } private static void checkXmlStreamReader( String text, String encoding, String effectiveEncoding ) - throws IOException + throws IOException { checkXmlStreamReader( text, encoding, effectiveEncoding, null ); } - private static void checkXmlStreamReader( String text, String encoding ) - throws IOException + private static void checkXmlStreamReader( String text, String encoding ) throws IOException { checkXmlStreamReader( text, encoding, encoding, null ); } - private static void checkXmlStreamReader( String text, String encoding, byte[] bom ) - throws IOException + private static void checkXmlStreamReader( String text, String encoding, byte[] bom ) throws IOException { checkXmlStreamReader( text, encoding, encoding, bom ); } private static void checkXmlStreamReader( String text, String encoding, String effectiveEncoding, byte[] bom ) - throws IOException + throws IOException { String xml = createXmlContent( text, encoding ); checkXmlContent( xml, effectiveEncoding, bom ); } - public void testNoXmlHeader() - throws IOException + public void testNoXmlHeader() throws IOException { String xml = "text with no XML header"; checkXmlContent( xml, "UTF-8" ); checkXmlContent( xml, "UTF-8", BOM_UTF8 ); } - public void testDefaultEncoding() - throws IOException + public void testDefaultEncoding() throws IOException { checkXmlStreamReader( TEXT_UNICODE, null, "UTF-8" ); checkXmlStreamReader( TEXT_UNICODE, null, "UTF-8", BOM_UTF8 ); } - public void testUTF8Encoding() - throws IOException + public void testUTF8Encoding() throws IOException { checkXmlStreamReader( TEXT_UNICODE, "UTF-8" ); checkXmlStreamReader( TEXT_UNICODE, "UTF-8", BOM_UTF8 ); } - public void testUTF16Encoding() - throws IOException + public void testUTF16Encoding() throws IOException { checkXmlStreamReader( TEXT_UNICODE, "UTF-16", "UTF-16BE", null ); checkXmlStreamReader( TEXT_UNICODE, "UTF-16", "UTF-16LE", BOM_UTF16LE ); checkXmlStreamReader( TEXT_UNICODE, "UTF-16", "UTF-16BE", BOM_UTF16BE ); } - public void testUTF16BEEncoding() - throws IOException + public void testUTF16BEEncoding() throws IOException { checkXmlStreamReader( TEXT_UNICODE, "UTF-16BE" ); } - public void testUTF16LEEncoding() - throws IOException + public void testUTF16LEEncoding() throws IOException { checkXmlStreamReader( TEXT_UNICODE, "UTF-16LE" ); } - public void testLatin1Encoding() - throws IOException + public void testLatin1Encoding() throws IOException { checkXmlStreamReader( TEXT_LATIN1, "ISO-8859-1" ); } - public void testLatin7Encoding() - throws IOException + public void testLatin7Encoding() throws IOException { checkXmlStreamReader( TEXT_LATIN7, "ISO-8859-7" ); } - public void testLatin15Encoding() - throws IOException + public void testLatin15Encoding() throws IOException { checkXmlStreamReader( TEXT_LATIN15, "ISO-8859-15" ); } - public void testEUC_JPEncoding() - throws IOException + public void testEUC_JPEncoding() throws IOException { checkXmlStreamReader( TEXT_EUC_JP, "EUC-JP" ); } - public void testEBCDICEncoding() - throws IOException + public void testEBCDICEncoding() throws IOException { checkXmlStreamReader( "simple text in EBCDIC", "CP1047" ); } - public void testInappropriateEncoding() - throws IOException + public void testInappropriateEncoding() throws IOException { try { @@ -202,8 +185,7 @@ } } - public void testEncodingAttribute() - throws IOException + public void testEncodingAttribute() throws IOException { String xml = ""; checkXmlContent( xml, "US-ASCII" ); diff -Nru maven-shared-utils-3.3.0/src/test/resources/executable maven-shared-utils-3.3.4/src/test/resources/executable --- maven-shared-utils-3.3.0/src/test/resources/executable 1970-01-01 00:00:00.000000000 +0000 +++ maven-shared-utils-3.3.4/src/test/resources/executable 2021-04-26 13:54:15.000000000 +0000 @@ -0,0 +1 @@ +noop