From 7f206ef1cc11585094cb045db4ec35fcbb1715a1 Mon Sep 17 00:00:00 2001 From: sugartxy Date: Fri, 19 Jun 2015 17:10:43 +0800 Subject: [PATCH] try-with-resources Reformatted to code style by me. This fixes #53 --- .../maven/settings/GlobalSettingsTest.java | 9 +- .../repository/internal/MavenMetadata.java | 33 +--- .../apache/maven/building/FileSourceTest.java | 24 +-- .../maven/building/StringSourceTest.java | 23 +-- .../apache/maven/building/UrlSourceTest.java | 26 +-- .../DefaultRepositoryMetadataManager.java | 97 ++++------ .../profiles/DefaultMavenProfilesBuilder.java | 18 +- .../legacy/DefaultUpdateCheckManager.java | 52 ++--- .../plugin/ExpressionDocumenter.java | 58 +++--- .../AbstractArtifactComponentTestCase.java | 62 +++--- .../metadata/AbstractRepositoryMetadata.java | 51 ++--- .../internal/CoreExtensionEntry.java | 22 +-- ...DefaultRepositorySystemSessionFactory.java | 49 +++-- .../internal/DefaultMavenPluginManager.java | 123 ++++++------ .../project/ExtensionDescriptorBuilder.java | 16 +- .../project/ProjectBuildingException.java | 33 ++-- .../internal/DefaultRuntimeInformation.java | 44 ++--- .../toolchain/DefaultToolchainsBuilder.java | 21 +- .../PomConstructionWithSettingsTest.java | 45 +++-- .../maven/toolchain/DefaultToolchainTest.java | 48 ++--- .../merge/MavenToolchainMergerTest.java | 101 +++------- .../apache/maven/cli/CLIReportingUtils.java | 29 +-- .../java/org/apache/maven/cli/MavenCli.java | 183 +++++++++--------- .../DefaultInheritanceAssemblerTest.java | 29 +-- .../plugin/descriptor/PluginDescriptor.java | 44 ++--- 25 files changed, 517 insertions(+), 723 deletions(-) diff --git a/apache-maven/src/test/java/org/apache/maven/settings/GlobalSettingsTest.java b/apache-maven/src/test/java/org/apache/maven/settings/GlobalSettingsTest.java index 5176ef0ad1..0d0543e289 100644 --- a/apache-maven/src/test/java/org/apache/maven/settings/GlobalSettingsTest.java +++ b/apache-maven/src/test/java/org/apache/maven/settings/GlobalSettingsTest.java @@ -19,15 +19,14 @@ package org.apache.maven.settings; * under the License. */ +import junit.framework.TestCase; +import org.apache.maven.settings.io.xpp3.SettingsXpp3Reader; + import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Reader; -import junit.framework.TestCase; - -import org.apache.maven.settings.io.xpp3.SettingsXpp3Reader; - /** * Tests that the global settings.xml shipped with the distribution is in good state. * @@ -45,7 +44,7 @@ public class GlobalSettingsTest File globalSettingsFile = new File( basedir, "src/conf/settings.xml" ); assertTrue( globalSettingsFile.getAbsolutePath(), globalSettingsFile.isFile() ); - try (Reader reader = new InputStreamReader( new FileInputStream( globalSettingsFile ), "UTF-8" )) + try ( Reader reader = new InputStreamReader( new FileInputStream( globalSettingsFile ), "UTF-8" ) ) { new SettingsXpp3Reader().read( reader ); } diff --git a/maven-aether-provider/src/main/java/org/apache/maven/repository/internal/MavenMetadata.java b/maven-aether-provider/src/main/java/org/apache/maven/repository/internal/MavenMetadata.java index bdf287831b..aef44f6bbb 100644 --- a/maven-aether-provider/src/main/java/org/apache/maven/repository/internal/MavenMetadata.java +++ b/maven-aether-provider/src/main/java/org/apache/maven/repository/internal/MavenMetadata.java @@ -19,17 +19,9 @@ package org.apache.maven.repository.internal; * under the License. */ -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; -import java.util.Collections; -import java.util.Map; - import org.apache.maven.artifact.repository.metadata.Metadata; import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader; import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.WriterFactory; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; @@ -37,6 +29,13 @@ import org.eclipse.aether.RepositoryException; import org.eclipse.aether.metadata.AbstractMetadata; import org.eclipse.aether.metadata.MergeableMetadata; +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.util.Collections; +import java.util.Map; + /** * @author Benjamin Bentmann */ @@ -96,10 +95,8 @@ abstract class MavenMetadata return new Metadata(); } - Reader reader = null; - try + try ( Reader reader = ReaderFactory.newXmlReader( metadataFile ) ) { - reader = ReaderFactory.newXmlReader( metadataFile ); return new MetadataXpp3Reader().read( reader, false ); } catch ( IOException e ) @@ -110,30 +107,20 @@ abstract class MavenMetadata { throw new RepositoryException( "Could not parse metadata " + metadataFile + ": " + e.getMessage(), e ); } - finally - { - IOUtil.close( reader ); - } } private void write( File metadataFile, Metadata metadata ) throws RepositoryException { - Writer writer = null; - try + metadataFile.getParentFile().mkdirs(); + try ( Writer writer = WriterFactory.newXmlWriter( metadataFile ) ) { - metadataFile.getParentFile().mkdirs(); - writer = WriterFactory.newXmlWriter( metadataFile ); new MetadataXpp3Writer().write( writer, metadata ); } catch ( IOException e ) { throw new RepositoryException( "Could not write metadata " + metadataFile + ": " + e.getMessage(), e ); } - finally - { - IOUtil.close( writer ); - } } public Map getProperties() diff --git a/maven-builder-support/src/test/java/org/apache/maven/building/FileSourceTest.java b/maven-builder-support/src/test/java/org/apache/maven/building/FileSourceTest.java index 086adda869..3da216957a 100644 --- a/maven-builder-support/src/test/java/org/apache/maven/building/FileSourceTest.java +++ b/maven-builder-support/src/test/java/org/apache/maven/building/FileSourceTest.java @@ -19,14 +19,14 @@ package org.apache.maven.building; * under the License. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.junit.Test; import java.io.File; import java.io.InputStream; import java.util.Scanner; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; public class FileSourceTest { @@ -52,26 +52,12 @@ public class FileSourceTest File txtFile = new File( "target/test-classes/source.txt" ); FileSource source = new FileSource( txtFile ); - Scanner scanner = null; - InputStream is = null; - try + try ( InputStream is = source.getInputStream(); + Scanner scanner = new Scanner( is ) ) { - is = source.getInputStream(); - scanner = new Scanner( is ); assertEquals( "Hello World!", scanner.nextLine() ); } - finally - { - if ( scanner != null ) - { - scanner.close(); - } - if ( is != null ) - { - is.close(); - } - } } @Test diff --git a/maven-builder-support/src/test/java/org/apache/maven/building/StringSourceTest.java b/maven-builder-support/src/test/java/org/apache/maven/building/StringSourceTest.java index 013b8a4d9c..6d9a671e71 100644 --- a/maven-builder-support/src/test/java/org/apache/maven/building/StringSourceTest.java +++ b/maven-builder-support/src/test/java/org/apache/maven/building/StringSourceTest.java @@ -19,12 +19,12 @@ package org.apache.maven.building; * under the License. */ -import static org.junit.Assert.assertEquals; +import org.junit.Test; import java.io.InputStream; import java.util.Scanner; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class StringSourceTest { @@ -34,26 +34,11 @@ public class StringSourceTest { StringSource source = new StringSource( "Hello World!" ); - Scanner scanner = null; - InputStream is = null; - try + try ( InputStream is = source.getInputStream(); + Scanner scanner = new Scanner( is ) ) { - is = source.getInputStream(); - - scanner = new Scanner( is ); assertEquals( "Hello World!", scanner.nextLine() ); } - finally - { - if ( scanner != null ) - { - scanner.close(); - } - if ( is != null ) - { - is.close(); - } - } } @Test diff --git a/maven-builder-support/src/test/java/org/apache/maven/building/UrlSourceTest.java b/maven-builder-support/src/test/java/org/apache/maven/building/UrlSourceTest.java index 5524c9b355..e374f69bba 100644 --- a/maven-builder-support/src/test/java/org/apache/maven/building/UrlSourceTest.java +++ b/maven-builder-support/src/test/java/org/apache/maven/building/UrlSourceTest.java @@ -19,15 +19,15 @@ package org.apache.maven.building; * under the License. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.junit.Test; import java.io.File; import java.io.InputStream; import java.net.URL; import java.util.Scanner; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; public class UrlSourceTest { @@ -52,27 +52,11 @@ public class UrlSourceTest { URL txtFile = new File( "target/test-classes/source.txt" ).toURI().toURL(); UrlSource source = new UrlSource( txtFile ); - - Scanner scanner = null; - InputStream is = null; - try + try ( InputStream is = source.getInputStream(); + Scanner scanner = new Scanner( is ) ) { - is = source.getInputStream(); - - scanner = new Scanner( is ); assertEquals( "Hello World!", scanner.nextLine() ); } - finally - { - if ( scanner != null ) - { - scanner.close(); - } - if ( is != null ) - { - is.close(); - } - } } @Test diff --git a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/DefaultRepositoryMetadataManager.java b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/DefaultRepositoryMetadataManager.java index 718aa0c9cb..d01a290bd4 100644 --- a/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/DefaultRepositoryMetadataManager.java +++ b/maven-compat/src/main/java/org/apache/maven/artifact/repository/metadata/DefaultRepositoryMetadataManager.java @@ -19,16 +19,6 @@ package org.apache.maven.artifact.repository.metadata; * under the License. */ -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; @@ -43,11 +33,20 @@ import org.apache.maven.wagon.TransferFailedException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.AbstractLogEnabled; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.WriterFactory; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** * @author Jason van Zyl */ @@ -100,8 +99,7 @@ public class DefaultRepositoryMetadataManager if ( getLogger().isDebugEnabled() ) { - getLogger().debug( - "Skipping update check for " + metadata.getKey() + " (" + file + getLogger().debug( "Skipping update check for " + metadata.getKey() + " (" + file + ") from disabled repository " + repository.getId() + " (" + repository.getUrl() + ")" ); } @@ -117,9 +115,8 @@ public class DefaultRepositoryMetadataManager if ( getLogger().isDebugEnabled() ) { getLogger().debug( - "Skipping update check for " + metadata.getKey() + " (" + file - + ") from repository " + repository.getId() + " (" + repository.getUrl() - + ") in favor of local copy" ); + "Skipping update check for " + metadata.getKey() + " (" + file + ") from repository " + + repository.getId() + " (" + repository.getUrl() + ") in favor of local copy" ); } } else @@ -183,8 +180,8 @@ public class DefaultRepositoryMetadataManager } catch ( RepositoryMetadataStoreException e ) { - throw new RepositoryMetadataResolutionException( "Unable to store local copy of metadata: " - + e.getMessage(), e ); + throw new RepositoryMetadataResolutionException( + "Unable to store local copy of metadata: " + e.getMessage(), e ); } } @@ -267,14 +264,13 @@ public class DefaultRepositoryMetadataManager } private boolean loadMetadata( RepositoryMetadata repoMetadata, ArtifactRepository remoteRepository, - ArtifactRepository localRepository, Map previousMetadata ) + ArtifactRepository localRepository, + Map previousMetadata ) { boolean setRepository = false; - File metadataFile = - new File( localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata( repoMetadata, - remoteRepository ) ); + File metadataFile = new File( localRepository.getBasedir(), + localRepository.pathOfLocalRepositoryMetadata( repoMetadata, remoteRepository ) ); if ( metadataFile.exists() ) { @@ -315,17 +311,16 @@ public class DefaultRepositoryMetadataManager return setRepository; } - /** @todo share with DefaultPluginMappingManager. */ + /** + * @todo share with DefaultPluginMappingManager. + */ protected Metadata readMetadata( File mappingFile ) throws RepositoryMetadataReadException { Metadata result; - Reader reader = null; - try + try ( Reader reader = ReaderFactory.newXmlReader( mappingFile ) ) { - reader = ReaderFactory.newXmlReader( mappingFile ); - MetadataXpp3Reader mappingReader = new MetadataXpp3Reader(); result = mappingReader.read( reader, false ); @@ -336,14 +331,9 @@ public class DefaultRepositoryMetadataManager } catch ( IOException | XmlPullParserException e ) { - throw new RepositoryMetadataReadException( "Cannot read metadata from '" + mappingFile + "': " - + e.getMessage(), e ); + throw new RepositoryMetadataReadException( + "Cannot read metadata from '" + mappingFile + "': " + e.getMessage(), e ); } - finally - { - IOUtil.close( reader ); - } - return result; } @@ -366,10 +356,9 @@ public class DefaultRepositoryMetadataManager if ( lastUpdated != null && now != null && now.compareTo( lastUpdated ) < 0 ) { getLogger().warn( - "The last updated timestamp in " + metadataFile + " refers to the future (now = " - + now + ", lastUpdated = " + lastUpdated - + "). Please verify that the clocks of all" - + " deploying machines are reasonably synchronized." ); + "The last updated timestamp in " + metadataFile + " refers to the future (now = " + now + + ", lastUpdated = " + lastUpdated + "). Please verify that the clocks of all" + + " deploying machines are reasonably synchronized." ); versioning.setLastUpdated( now ); changed = true; } @@ -380,10 +369,8 @@ public class DefaultRepositoryMetadataManager { getLogger().debug( "Repairing metadata in " + metadataFile ); - Writer writer = null; - try + try ( Writer writer = WriterFactory.newXmlWriter( metadataFile ) ) { - writer = WriterFactory.newXmlWriter( metadataFile ); new MetadataXpp3Writer().write( writer, metadata ); } catch ( IOException e ) @@ -398,10 +385,6 @@ public class DefaultRepositoryMetadataManager getLogger().warn( msg ); } } - finally - { - IOUtil.close( writer ); - } } } @@ -416,8 +399,9 @@ public class DefaultRepositoryMetadataManager } catch ( TransferFailedException e ) { - throw new RepositoryMetadataResolutionException( metadata + " could not be retrieved from repository: " - + remoteRepository.getId() + " due to an error: " + e.getMessage(), e ); + throw new RepositoryMetadataResolutionException( + metadata + " could not be retrieved from repository: " + remoteRepository.getId() + " due to an error: " + + e.getMessage(), e ); } try @@ -434,8 +418,7 @@ public class DefaultRepositoryMetadataManager } } - private File getArtifactMetadataFromDeploymentRepository( ArtifactMetadata metadata, - ArtifactRepository localRepo, + private File getArtifactMetadataFromDeploymentRepository( ArtifactMetadata metadata, ArtifactRepository localRepo, ArtifactRepository remoteRepository ) throws TransferFailedException { @@ -449,8 +432,8 @@ public class DefaultRepositoryMetadataManager } catch ( ResourceDoesNotExistException e ) { - getLogger().info( metadata + " could not be found on repository: " + remoteRepository.getId() - + ", so will be created" ); + getLogger().info( + metadata + " could not be found on repository: " + remoteRepository.getId() + ", so will be created" ); // delete the local copy so the old details aren't used. if ( file.exists() ) @@ -494,8 +477,9 @@ public class DefaultRepositoryMetadataManager } catch ( TransferFailedException e ) { - throw new RepositoryMetadataDeploymentException( metadata + " could not be retrieved from repository: " - + deploymentRepository.getId() + " due to an error: " + e.getMessage(), e ); + throw new RepositoryMetadataDeploymentException( + metadata + " could not be retrieved from repository: " + deploymentRepository.getId() + + " due to an error: " + e.getMessage(), e ); } if ( file.isFile() ) @@ -513,9 +497,8 @@ public class DefaultRepositoryMetadataManager else { // It's a POM - we don't need to retrieve it first - file = - new File( localRepository.getBasedir(), - localRepository.pathOfLocalRepositoryMetadata( metadata, deploymentRepository ) ); + file = new File( localRepository.getBasedir(), + localRepository.pathOfLocalRepositoryMetadata( metadata, deploymentRepository ) ); } try diff --git a/maven-compat/src/main/java/org/apache/maven/profiles/DefaultMavenProfilesBuilder.java b/maven-compat/src/main/java/org/apache/maven/profiles/DefaultMavenProfilesBuilder.java index 4745749b08..98ff3d0502 100644 --- a/maven-compat/src/main/java/org/apache/maven/profiles/DefaultMavenProfilesBuilder.java +++ b/maven-compat/src/main/java/org/apache/maven/profiles/DefaultMavenProfilesBuilder.java @@ -52,13 +52,9 @@ public class DefaultMavenProfilesBuilder if ( profilesXml.exists() ) { ProfilesXpp3Reader reader = new ProfilesXpp3Reader(); - Reader profileReader = null; - try + try ( Reader profileReader = ReaderFactory.newXmlReader( profilesXml ); + StringWriter sWriter = new StringWriter() ) { - profileReader = ReaderFactory.newXmlReader( profilesXml ); - - StringWriter sWriter = new StringWriter(); - IOUtil.copy( profileReader, sWriter ); String rawInput = sWriter.toString(); @@ -72,8 +68,9 @@ public class DefaultMavenProfilesBuilder } catch ( Exception e ) { - getLogger().warn( "Failed to initialize environment variable resolver. Skipping environment " - + "substitution in " + PROFILES_XML_FILE + "." ); + getLogger().warn( + "Failed to initialize environment variable resolver. Skipping environment " + "substitution in " + + PROFILES_XML_FILE + "." ); getLogger().debug( "Failed to initialize envar resolver. Skipping resolution.", e ); } @@ -81,10 +78,7 @@ public class DefaultMavenProfilesBuilder profilesRoot = reader.read( sReader ); } - finally - { - IOUtil.close( profileReader ); - } + } return profilesRoot; diff --git a/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultUpdateCheckManager.java b/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultUpdateCheckManager.java index 57b307ef1f..dfc463b519 100644 --- a/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultUpdateCheckManager.java +++ b/maven-compat/src/main/java/org/apache/maven/repository/legacy/DefaultUpdateCheckManager.java @@ -19,6 +19,17 @@ package org.apache.maven.repository.legacy; * under the License. */ +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; +import org.apache.maven.artifact.repository.Authentication; +import org.apache.maven.artifact.repository.metadata.RepositoryMetadata; +import org.apache.maven.repository.Proxy; +import org.codehaus.plexus.component.annotations.Component; +import org.codehaus.plexus.logging.AbstractLogEnabled; +import org.codehaus.plexus.logging.Logger; +import org.codehaus.plexus.util.IOUtil; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -31,17 +42,6 @@ import java.nio.channels.FileLock; import java.util.Date; import java.util.Properties; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; -import org.apache.maven.artifact.repository.Authentication; -import org.apache.maven.artifact.repository.metadata.RepositoryMetadata; -import org.apache.maven.repository.Proxy; -import org.codehaus.plexus.component.annotations.Component; -import org.codehaus.plexus.logging.AbstractLogEnabled; -import org.codehaus.plexus.logging.Logger; -import org.codehaus.plexus.util.IOUtil; - @Component( role = UpdateCheckManager.class ) public class DefaultUpdateCheckManager extends AbstractLogEnabled @@ -75,8 +75,8 @@ public class DefaultUpdateCheckManager if ( getLogger().isDebugEnabled() ) { getLogger().debug( - "Skipping update check for " + artifact + " (" + file + ") from " - + repository.getId() + " (" + repository.getUrl() + ")" ); + "Skipping update check for " + artifact + " (" + file + ") from " + repository.getId() + " (" + + repository.getUrl() + ")" ); } return false; @@ -85,8 +85,8 @@ public class DefaultUpdateCheckManager if ( getLogger().isDebugEnabled() ) { getLogger().debug( - "Determining update check for " + artifact + " (" + file + ") from " - + repository.getId() + " (" + repository.getUrl() + ")" ); + "Determining update check for " + artifact + " (" + file + ") from " + repository.getId() + " (" + + repository.getUrl() + ")" ); } if ( file == null ) @@ -99,7 +99,7 @@ public class DefaultUpdateCheckManager if ( file.exists() ) { - lastCheckDate = new Date ( file.lastModified() ); + lastCheckDate = new Date( file.lastModified() ); } else { @@ -125,8 +125,8 @@ public class DefaultUpdateCheckManager if ( getLogger().isDebugEnabled() ) { getLogger().debug( - "Skipping update check for " + metadata.getKey() + " (" + file + ") from " - + repository.getId() + " (" + repository.getUrl() + ")" ); + "Skipping update check for " + metadata.getKey() + " (" + file + ") from " + repository.getId() + + " (" + repository.getUrl() + ")" ); } return false; @@ -135,8 +135,8 @@ public class DefaultUpdateCheckManager if ( getLogger().isDebugEnabled() ) { getLogger().debug( - "Determining update check for " + metadata.getKey() + " (" + file + ") from " - + repository.getId() + " (" + repository.getUrl() + ")" ); + "Determining update check for " + metadata.getKey() + " (" + file + ") from " + repository.getId() + + " (" + repository.getUrl() + ")" ); } if ( file == null ) @@ -282,8 +282,9 @@ public class DefaultUpdateCheckManager } catch ( IOException e ) { - getLogger().debug( "Failed to record lastUpdated information for resolution.\nFile: " - + touchfile.toString() + "; key: " + key, e ); + getLogger().debug( + "Failed to record lastUpdated information for resolution.\nFile: " + touchfile.toString() + + "; key: " + key, e ); } finally { @@ -295,8 +296,8 @@ public class DefaultUpdateCheckManager } catch ( IOException e ) { - getLogger().debug( "Error releasing exclusive lock for resolution tracking file: " - + touchfile, e ); + getLogger().debug( "Error releasing exclusive lock for resolution tracking file: " + touchfile, + e ); } } @@ -308,8 +309,7 @@ public class DefaultUpdateCheckManager } catch ( IOException e ) { - getLogger().debug( "Error closing FileChannel for resolution tracking file: " - + touchfile, e ); + getLogger().debug( "Error closing FileChannel for resolution tracking file: " + touchfile, e ); } } } diff --git a/maven-compat/src/main/java/org/apache/maven/usability/plugin/ExpressionDocumenter.java b/maven-compat/src/main/java/org/apache/maven/usability/plugin/ExpressionDocumenter.java index 99c0b0b243..d0aeb31609 100644 --- a/maven-compat/src/main/java/org/apache/maven/usability/plugin/ExpressionDocumenter.java +++ b/maven-compat/src/main/java/org/apache/maven/usability/plugin/ExpressionDocumenter.java @@ -20,7 +20,6 @@ package org.apache.maven.usability.plugin; */ import org.apache.maven.usability.plugin.io.xpp3.ParamdocXpp3Reader; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; @@ -56,12 +55,9 @@ public class ExpressionDocumenter for ( String EXPRESSION_ROOT : EXPRESSION_ROOTS ) { - InputStream docStream = null; - try + try ( InputStream docStream = docLoader.getResourceAsStream( + EXPRESSION_DOCO_ROOTPATH + EXPRESSION_ROOT + ".paramdoc.xml" ) ) { - docStream = - docLoader.getResourceAsStream( EXPRESSION_DOCO_ROOTPATH + EXPRESSION_ROOT + ".paramdoc.xml" ); - if ( docStream != null ) { Map doco = parseExpressionDocumentation( docStream ); @@ -79,10 +75,7 @@ public class ExpressionDocumenter throw new ExpressionDocumentationException( "Failed to parse documentation for expression root: " + EXPRESSION_ROOT, e ); } - finally - { - IOUtil.close( docStream ); - } + } } @@ -91,26 +84,27 @@ public class ExpressionDocumenter /** * - * - * project.distributionManagementArtifactRepository - * - * - * some-repo - * scp://host/path - * - * - * some-snap-repo - * scp://host/snapshot-path - * - * - * ]]> - * - * + * + * project.distributionManagementArtifactRepository + * + * + * some-repo + * scp://host/path + * + * + * some-snap-repo + * scp://host/snapshot-path + * + * + * ]]> + * + * * + * * @throws IOException * @throws XmlPullParserException */ @@ -165,11 +159,11 @@ public class ExpressionDocumenter } catch ( MalformedURLException e ) { - throw new ExpressionDocumentationException( "Cannot construct expression documentation classpath" - + " resource base.", e ); + throw new ExpressionDocumentationException( + "Cannot construct expression documentation classpath" + " resource base.", e ); } - return new URLClassLoader( new URL[] { docResource } ); + return new URLClassLoader( new URL[]{ docResource } ); } } diff --git a/maven-compat/src/test/java/org/apache/maven/artifact/AbstractArtifactComponentTestCase.java b/maven-compat/src/test/java/org/apache/maven/artifact/AbstractArtifactComponentTestCase.java index fc2fde0c14..0cdea195d7 100644 --- a/maven-compat/src/test/java/org/apache/maven/artifact/AbstractArtifactComponentTestCase.java +++ b/maven-compat/src/test/java/org/apache/maven/artifact/AbstractArtifactComponentTestCase.java @@ -19,23 +19,15 @@ package org.apache.maven.artifact; * under the License. */ -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.List; - import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.plugin.LegacySupport; -import org.apache.maven.repository.legacy.repository.ArtifactRepositoryFactory; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.DefaultMavenExecutionResult; import org.apache.maven.execution.MavenSession; +import org.apache.maven.plugin.LegacySupport; +import org.apache.maven.repository.legacy.repository.ArtifactRepositoryFactory; import org.codehaus.plexus.ContainerConfiguration; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusTestCase; @@ -54,14 +46,22 @@ import org.eclipse.aether.util.graph.selector.OptionalDependencySelector; import org.eclipse.aether.util.graph.selector.ScopeDependencySelector; import org.eclipse.aether.util.graph.transformer.ChainedDependencyGraphTransformer; import org.eclipse.aether.util.graph.transformer.ConflictResolver; +import org.eclipse.aether.util.graph.transformer.JavaDependencyContextRefiner; import org.eclipse.aether.util.graph.transformer.JavaScopeDeriver; import org.eclipse.aether.util.graph.transformer.JavaScopeSelector; -import org.eclipse.aether.util.graph.transformer.JavaDependencyContextRefiner; import org.eclipse.aether.util.graph.transformer.NearestVersionSelector; import org.eclipse.aether.util.graph.transformer.SimpleOptionalitySelector; import org.eclipse.aether.util.graph.traverser.FatArtifactTraverser; import org.eclipse.aether.util.repository.SimpleArtifactDescriptorPolicy; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.ArrayList; +import java.util.List; + /** * @author Jason van Zyl */ @@ -85,15 +85,14 @@ public abstract class AbstractArtifactComponentTestCase throws Exception { super.setUp(); - artifactFactory = lookup( ArtifactFactory.class); + artifactFactory = lookup( ArtifactFactory.class ); artifactRepositoryFactory = lookup( ArtifactRepositoryFactory.class ); RepositorySystemSession repoSession = initRepoSession(); - MavenSession session = - new MavenSession( getContainer(), repoSession, new DefaultMavenExecutionRequest(), - new DefaultMavenExecutionResult() ); + MavenSession session = new MavenSession( getContainer(), repoSession, new DefaultMavenExecutionRequest(), + new DefaultMavenExecutionResult() ); - LegacySupport legacySupport = lookup(LegacySupport.class); + LegacySupport legacySupport = lookup( LegacySupport.class ); legacySupport.setSession( session ); } @@ -125,7 +124,8 @@ public abstract class AbstractArtifactComponentTestCase ArtifactRepositoryLayout repoLayout = (ArtifactRepositoryLayout) lookup( ArtifactRepositoryLayout.ROLE, "default" ); - return artifactRepositoryFactory.createArtifactRepository( "test", "file://" + f.getPath(), repoLayout, null, null ); + return artifactRepositoryFactory.createArtifactRepository( "test", "file://" + f.getPath(), repoLayout, null, + null ); } protected String getRepositoryLayout() @@ -143,7 +143,8 @@ public abstract class AbstractArtifactComponentTestCase ArtifactRepositoryLayout repoLayout = (ArtifactRepositoryLayout) lookup( ArtifactRepositoryLayout.ROLE, "default" ); - return artifactRepositoryFactory.createArtifactRepository( "local", "file://" + f.getPath(), repoLayout, null, null ); + return artifactRepositoryFactory.createArtifactRepository( "local", "file://" + f.getPath(), repoLayout, null, + null ); } protected ArtifactRepository remoteRepository() @@ -157,7 +158,8 @@ public abstract class AbstractArtifactComponentTestCase (ArtifactRepositoryLayout) lookup( ArtifactRepositoryLayout.ROLE, "default" ); return artifactRepositoryFactory.createArtifactRepository( "test", "file://" + f.getPath(), repoLayout, - new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy() ); + new ArtifactRepositoryPolicy(), + new ArtifactRepositoryPolicy() ); } protected ArtifactRepository badRemoteRepository() @@ -166,7 +168,8 @@ public abstract class AbstractArtifactComponentTestCase ArtifactRepositoryLayout repoLayout = (ArtifactRepositoryLayout) lookup( ArtifactRepositoryLayout.ROLE, "default" ); - return artifactRepositoryFactory.createArtifactRepository( "test", "http://foo.bar/repository", repoLayout, null, null ); + return artifactRepositoryFactory.createArtifactRepository( "test", "http://foo.bar/repository", repoLayout, + null, null ); } protected void assertRemoteArtifactPresent( Artifact artifact ) @@ -290,12 +293,10 @@ public abstract class AbstractArtifactComponentTestCase { artifactFile.getParentFile().mkdirs(); } - - Writer writer = new OutputStreamWriter( new FileOutputStream( artifactFile ), "ISO-8859-1" ); - - writer.write( artifact.getId() ); - - writer.close(); + try ( Writer writer = new OutputStreamWriter( new FileOutputStream( artifactFile ), "ISO-8859-1" ) ) + { + writer.write( artifact.getId() ); + } } protected Artifact createArtifact( String artifactId, String version ) @@ -351,9 +352,9 @@ public abstract class AbstractArtifactComponentTestCase DependencyManager depManager = new ClassicDependencyManager(); session.setDependencyManager( depManager ); - DependencySelector depFilter = - new AndDependencySelector( new ScopeDependencySelector( "test", "provided" ), - new OptionalDependencySelector(), new ExclusionDependencySelector() ); + DependencySelector depFilter = new AndDependencySelector( new ScopeDependencySelector( "test", "provided" ), + new OptionalDependencySelector(), + new ExclusionDependencySelector() ); session.setDependencySelector( depFilter ); DependencyGraphTransformer transformer = @@ -363,7 +364,8 @@ public abstract class AbstractArtifactComponentTestCase session.setDependencyGraphTransformer( transformer ); LocalRepository localRepo = new LocalRepository( localRepository().getBasedir() ); - session.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( session, localRepo ) ); + session.setLocalRepositoryManager( + new SimpleLocalRepositoryManagerFactory().newInstance( session, localRepo ) ); return session; } diff --git a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java index 537fbe5256..05284174a0 100644 --- a/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java +++ b/maven-core/src/main/java/org/apache/maven/artifact/repository/metadata/AbstractRepositoryMetadata.java @@ -19,22 +19,21 @@ package org.apache.maven.artifact.repository.metadata; * under the License. */ -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; - import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader; import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.WriterFactory; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; + /** * Shared methods of the repository metadata handling. * @@ -60,8 +59,7 @@ public abstract class AbstractRepositoryMetadata return "maven-metadata-" + repository.getKey() + ".xml"; } - public void storeInLocalRepository( ArtifactRepository localRepository, - ArtifactRepository remoteRepository ) + public void storeInLocalRepository( ArtifactRepository localRepository, ArtifactRepository remoteRepository ) throws RepositoryMetadataStoreException { try @@ -74,8 +72,7 @@ public abstract class AbstractRepositoryMetadata } } - protected void updateRepositoryMetadata( ArtifactRepository localRepository, - ArtifactRepository remoteRepository ) + protected void updateRepositoryMetadata( ArtifactRepository localRepository, ArtifactRepository remoteRepository ) throws IOException, XmlPullParserException { MetadataXpp3Reader mappingReader = new MetadataXpp3Reader(); @@ -83,7 +80,7 @@ public abstract class AbstractRepositoryMetadata Metadata metadata = null; File metadataFile = new File( localRepository.getBasedir(), - localRepository.pathOfLocalRepositoryMetadata( this, remoteRepository ) ); + localRepository.pathOfLocalRepositoryMetadata( this, remoteRepository ) ); if ( metadataFile.length() == 0 ) { @@ -99,23 +96,15 @@ public abstract class AbstractRepositoryMetadata // ignore } metadataFile.delete(); // if this fails, forget about it, we'll try to overwrite it anyway so no need - // to delete on exit + // to delete on exit } } else if ( metadataFile.exists() ) { - Reader reader = null; - - try + try ( Reader reader = ReaderFactory.newXmlReader( metadataFile ) ) { - reader = ReaderFactory.newXmlReader( metadataFile ); - metadata = mappingReader.read( reader, false ); } - finally - { - IOUtil.close( reader ); - } } boolean changed; @@ -143,20 +132,13 @@ public abstract class AbstractRepositoryMetadata if ( changed || !metadataFile.exists() ) { - Writer writer = null; - try + metadataFile.getParentFile().mkdirs(); + try ( Writer writer = WriterFactory.newXmlWriter( metadataFile ) ) { - metadataFile.getParentFile().mkdirs(); - writer = WriterFactory.newXmlWriter( metadataFile ); - MetadataXpp3Writer mappingWriter = new MetadataXpp3Writer(); mappingWriter.write( writer, metadata ); } - finally - { - IOUtil.close( writer ); - } } else { @@ -169,8 +151,7 @@ public abstract class AbstractRepositoryMetadata return "repository metadata for: \'" + getKey() + "\'"; } - protected static Metadata createMetadata( Artifact artifact, - Versioning versioning ) + protected static Metadata createMetadata( Artifact artifact, Versioning versioning ) { Metadata metadata = new Metadata(); metadata.setGroupId( artifact.getGroupId() ); @@ -200,14 +181,16 @@ public abstract class AbstractRepositoryMetadata public void merge( org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata ) { - // TODO: not sure that it should assume this, maybe the calls to addMetadata should pre-merge, then artifact replaces? + // TODO: not sure that it should assume this, maybe the calls to addMetadata should pre-merge, then artifact + // replaces? AbstractRepositoryMetadata repoMetadata = (AbstractRepositoryMetadata) metadata; this.metadata.merge( repoMetadata.getMetadata() ); } public void merge( ArtifactMetadata metadata ) { - // TODO: not sure that it should assume this, maybe the calls to addMetadata should pre-merge, then artifact replaces? + // TODO: not sure that it should assume this, maybe the calls to addMetadata should pre-merge, then artifact + // replaces? AbstractRepositoryMetadata repoMetadata = (AbstractRepositoryMetadata) metadata; this.metadata.merge( repoMetadata.getMetadata() ); } diff --git a/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExtensionEntry.java b/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExtensionEntry.java index 4ac5183d52..ce740a9679 100644 --- a/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExtensionEntry.java +++ b/maven-core/src/main/java/org/apache/maven/extension/internal/CoreExtensionEntry.java @@ -19,6 +19,11 @@ package org.apache.maven.extension.internal; * under the License. */ +import com.google.common.collect.ImmutableSet; +import org.apache.maven.project.ExtensionDescriptor; +import org.apache.maven.project.ExtensionDescriptorBuilder; +import org.codehaus.plexus.classworlds.realm.ClassRealm; + import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -28,17 +33,10 @@ import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Set; -import org.apache.maven.project.ExtensionDescriptor; -import org.apache.maven.project.ExtensionDescriptorBuilder; -import org.codehaus.plexus.classworlds.realm.ClassRealm; -import org.codehaus.plexus.util.IOUtil; - -import com.google.common.collect.ImmutableSet; - /** * Provides information about artifacts (identified by groupId:artifactId string key) and classpath elements exported by * Maven core itself or a Maven core extension. - * + * * @since 3.3.0 */ public class CoreExtensionEntry @@ -92,17 +90,13 @@ public class CoreExtensionEntry Enumeration urls = loader.getResources( builder.getExtensionDescriptorLocation() ); while ( urls.hasMoreElements() ) { - InputStream is = urls.nextElement().openStream(); - try + + try ( InputStream is = urls.nextElement().openStream() ) { ExtensionDescriptor descriptor = builder.build( is ); artifacts.addAll( descriptor.getExportedArtifacts() ); packages.addAll( descriptor.getExportedPackages() ); } - finally - { - IOUtil.close( is ); - } } } catch ( IOException ignored ) diff --git a/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java b/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java index 3e799158dc..0c91cf9419 100644 --- a/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java +++ b/maven-core/src/main/java/org/apache/maven/internal/aether/DefaultRepositorySystemSessionFactory.java @@ -19,15 +19,6 @@ package org.apache.maven.internal.aether; * under the License. */ -import java.io.IOException; -import java.io.InputStream; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Properties; - -import javax.inject.Inject; -import javax.inject.Named; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager; import org.apache.maven.bridge.MavenRepositorySystem; @@ -43,7 +34,6 @@ import org.apache.maven.settings.crypto.SettingsDecrypter; import org.apache.maven.settings.crypto.SettingsDecryptionResult; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.logging.Logger; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.eclipse.aether.ConfigurationProperties; import org.eclipse.aether.DefaultRepositorySystemSession; @@ -61,6 +51,14 @@ import org.eclipse.aether.util.repository.DefaultProxySelector; import org.eclipse.aether.util.repository.SimpleResolutionErrorPolicy; import org.eclipse.sisu.Nullable; +import javax.inject.Inject; +import javax.inject.Named; +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; + /** * @since 3.3.0 */ @@ -94,7 +92,7 @@ public class DefaultRepositorySystemSessionFactory @Inject MavenRepositorySystem mavenRepositorySystem; - + public DefaultRepositorySystemSession newRepositorySession( MavenExecutionRequest request ) { DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); @@ -125,8 +123,8 @@ public class DefaultRepositorySystemSessionFactory int errorPolicy = 0; errorPolicy |= request.isCacheNotFound() ? ResolutionErrorPolicy.CACHE_NOT_FOUND : 0; errorPolicy |= request.isCacheTransferError() ? ResolutionErrorPolicy.CACHE_TRANSFER_ERROR : 0; - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( errorPolicy, errorPolicy - | ResolutionErrorPolicy.CACHE_NOT_FOUND ) ); + session.setResolutionErrorPolicy( + new SimpleResolutionErrorPolicy( errorPolicy, errorPolicy | ResolutionErrorPolicy.CACHE_NOT_FOUND ) ); session.setArtifactTypeRegistry( RepositoryUtils.newArtifactTypeRegistry( artifactHandlerManager ) ); @@ -135,7 +133,7 @@ public class DefaultRepositorySystemSessionFactory if ( request.isUseLegacyLocalRepository() ) { logger.warn( "Disabling enhanced local repository: using legacy is strongly discouraged to ensure" - + " build reproducibility." ); + + " build reproducibility." ); try { session.setLocalRepositoryManager( simpleLocalRepoMgrFactory.newInstance( session, localRepo ) ); @@ -187,9 +185,9 @@ public class DefaultRepositorySystemSessionFactory { AuthenticationBuilder authBuilder = new AuthenticationBuilder(); authBuilder.addUsername( proxy.getUsername() ).addPassword( proxy.getPassword() ); - proxySelector.add( new org.eclipse.aether.repository.Proxy( proxy.getProtocol(), proxy.getHost(), - proxy.getPort(), authBuilder.build() ), - proxy.getNonProxyHosts() ); + proxySelector.add( + new org.eclipse.aether.repository.Proxy( proxy.getProtocol(), proxy.getHost(), proxy.getPort(), + authBuilder.build() ), proxy.getNonProxyHosts() ); } session.setProxySelector( proxySelector ); @@ -234,7 +232,7 @@ public class DefaultRepositorySystemSessionFactory mavenRepositorySystem.injectProxy( session, request.getRemoteRepositories() ); mavenRepositorySystem.injectAuthentication( session, request.getRemoteRepositories() ); - mavenRepositorySystem.injectMirror( request.getPluginArtifactRepositories(), request.getMirrors() ); + mavenRepositorySystem.injectMirror( request.getPluginArtifactRepositories(), request.getMirrors() ); mavenRepositorySystem.injectProxy( session, request.getPluginArtifactRepositories() ); mavenRepositorySystem.injectAuthentication( session, request.getPluginArtifactRepositories() ); @@ -251,18 +249,17 @@ public class DefaultRepositorySystemSessionFactory { Properties props = new Properties(); - InputStream is = getClass().getResourceAsStream( "/META-INF/maven/org.apache.maven/maven-core/pom.properties" ); - if ( is != null ) + try ( InputStream is = getClass().getResourceAsStream( + "/META-INF/maven/org.apache.maven/maven-core/pom.properties" ) ) { - try + if ( is != null ) { props.load( is ); } - catch ( IOException e ) - { - logger.debug( "Failed to read Maven version", e ); - } - IOUtil.close( is ); + } + catch ( IOException e ) + { + logger.debug( "Failed to read Maven version", e ); } return props.getProperty( "version", "unknown-version" ); diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java index d32e04c162..edb5cfe231 100644 --- a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java +++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java @@ -19,24 +19,6 @@ package org.apache.maven.plugin.internal; * under the License. */ -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.io.Reader; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.jar.JarFile; -import java.util.zip.ZipEntry; - import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.classrealm.ClassRealmManager; @@ -96,7 +78,6 @@ import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.logging.LoggerManager; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; @@ -107,13 +88,31 @@ import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.util.filter.AndDependencyFilter; import org.eclipse.aether.util.graph.visitor.PreorderNodeListGenerator; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.io.Reader; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.jar.JarFile; +import java.util.zip.ZipEntry; + /** * Provides basic services to manage Maven plugins and their mojos. This component is kept general in its design such * that the plugins/mojos can be used in arbitrary contexts. In particular, the mojos can be used for ordinary build * plugins as well as special purpose plugins like reports. * - * @since 3.0 * @author Benjamin Bentmann + * @since 3.0 */ @Component( role = MavenPluginManager.class ) public class DefaultMavenPluginManager @@ -123,7 +122,7 @@ public class DefaultMavenPluginManager /** * PluginId=>ExtensionRealmCache.CacheRecord map MavenProject context value key. The map is used to ensure the same * class realm is used to load build extensions and load mojos for extensions=true plugins. - * + * * @noreference this is part of internal implementation and may be changed or removed without notice * @since 3.3.0 */ @@ -227,15 +226,10 @@ public class DefaultMavenPluginManager if ( pluginXml.isFile() ) { - InputStream is = new BufferedInputStream( new FileInputStream( pluginXml ) ); - try + try ( InputStream is = new BufferedInputStream( new FileInputStream( pluginXml ) ) ) { pluginDescriptor = parsePluginDescriptor( is, plugin, pluginXml.getAbsolutePath() ); } - finally - { - IOUtil.close( is ); - } } } @@ -255,8 +249,8 @@ public class DefaultMavenPluginManager if ( validator.hasErrors() ) { - throw new InvalidPluginDescriptorException( "Invalid plugin descriptor for " + plugin.getId() + " (" - + pluginFile + ")", validator.getErrors() ); + throw new InvalidPluginDescriptorException( + "Invalid plugin descriptor for " + plugin.getId() + " (" + pluginFile + ")", validator.getErrors() ); } pluginDescriptor.setPluginArtifact( pluginArtifact ); @@ -317,8 +311,9 @@ public class DefaultMavenPluginManager { if ( !runtimeInformation.isMavenVersion( requiredMavenVersion ) ) { - throw new PluginIncompatibleException( pluginDescriptor.getPlugin(), "The plugin " - + pluginDescriptor.getId() + " requires Maven version " + requiredMavenVersion ); + throw new PluginIncompatibleException( pluginDescriptor.getPlugin(), + "The plugin " + pluginDescriptor.getId() + + " requires Maven version " + requiredMavenVersion ); } } catch ( RuntimeException e ) @@ -365,9 +360,9 @@ public class DefaultMavenPluginManager { Map foreignImports = calcImports( project, parent, imports ); - PluginRealmCache.Key cacheKey = - pluginRealmCache.createKey( plugin, parent, foreignImports, filter, - project.getRemotePluginRepositories(), session.getRepositorySession() ); + PluginRealmCache.Key cacheKey = pluginRealmCache.createKey( plugin, parent, foreignImports, filter, + project.getRemotePluginRepositories(), + session.getRepositorySession() ); PluginRealmCache.CacheRecord cacheRecord = pluginRealmCache.get( cacheKey ); @@ -420,18 +415,16 @@ public class DefaultMavenPluginManager dependencyFilter = AndDependencyFilter.newInstance( dependencyFilter, filter ); DependencyNode root = - pluginDependenciesResolver.resolve( plugin, RepositoryUtils.toArtifact( pluginArtifact ), - dependencyFilter, project.getRemotePluginRepositories(), - repositorySession ); + pluginDependenciesResolver.resolve( plugin, RepositoryUtils.toArtifact( pluginArtifact ), dependencyFilter, + project.getRemotePluginRepositories(), repositorySession ); PreorderNodeListGenerator nlg = new PreorderNodeListGenerator(); root.accept( nlg ); pluginArtifacts = toMavenArtifacts( root, nlg ); - pluginRealm = - classRealmManager.createPluginRealm( plugin, parent, null, foreignImports, - toAetherArtifacts( pluginArtifacts ) ); + pluginRealm = classRealmManager.createPluginRealm( plugin, parent, null, foreignImports, + toAetherArtifacts( pluginArtifacts ) ); discoverPluginComponents( pluginRealm, plugin, pluginDescriptor ); @@ -454,19 +447,20 @@ public class DefaultMavenPluginManager } } - ( (DefaultPlexusContainer) container ).discoverComponents( pluginRealm, - new SessionScopeModule( container ), + ( (DefaultPlexusContainer) container ).discoverComponents( pluginRealm, new SessionScopeModule( container ), new MojoExecutionScopeModule( container ) ); } catch ( ComponentLookupException e ) { - throw new PluginContainerException( plugin, pluginRealm, "Error in component graph of plugin " - + plugin.getId() + ": " + e.getMessage(), e ); + throw new PluginContainerException( plugin, pluginRealm, + "Error in component graph of plugin " + plugin.getId() + ": " + + e.getMessage(), e ); } catch ( CycleDetectedInComponentGraphException e ) { - throw new PluginContainerException( plugin, pluginRealm, "Error in component graph of plugin " - + plugin.getId() + ": " + e.getMessage(), e ); + throw new PluginContainerException( plugin, pluginRealm, + "Error in component graph of plugin " + plugin.getId() + ": " + + e.getMessage(), e ); } } @@ -559,7 +553,8 @@ public class DefaultMavenPluginManager ByteArrayOutputStream os = new ByteArrayOutputStream( 1024 ); PrintStream ps = new PrintStream( os ); ps.println( "Unable to load the mojo '" + mojoDescriptor.getGoal() + "' in the plugin '" - + pluginDescriptor.getId() + "'. A required class is missing: " + cause.getMessage() ); + + pluginDescriptor.getId() + "'. A required class is missing: " + + cause.getMessage() ); pluginRealm.display( ps ); throw new PluginContainerException( mojoDescriptor, pluginRealm, os.toString(), cause ); @@ -569,16 +564,17 @@ public class DefaultMavenPluginManager ByteArrayOutputStream os = new ByteArrayOutputStream( 1024 ); PrintStream ps = new PrintStream( os ); ps.println( "Unable to load the mojo '" + mojoDescriptor.getGoal() + "' in the plugin '" - + pluginDescriptor.getId() + "' due to an API incompatibility: " + e.getClass().getName() - + ": " + cause.getMessage() ); + + pluginDescriptor.getId() + "' due to an API incompatibility: " + + e.getClass().getName() + ": " + cause.getMessage() ); pluginRealm.display( ps ); throw new PluginContainerException( mojoDescriptor, pluginRealm, os.toString(), cause ); } - throw new PluginContainerException( mojoDescriptor, pluginRealm, "Unable to load the mojo '" - + mojoDescriptor.getGoal() + "' (or one of its required components) from the plugin '" - + pluginDescriptor.getId() + "'", e ); + throw new PluginContainerException( mojoDescriptor, pluginRealm, + "Unable to load the mojo '" + mojoDescriptor.getGoal() + + "' (or one of its required components) from the plugin '" + + pluginDescriptor.getId() + "'", e ); } if ( mojo instanceof ContextEnabled ) @@ -653,8 +649,8 @@ public class DefaultMavenPluginManager ValidatingConfigurationListener validator = new ValidatingConfigurationListener( mojo, mojoDescriptor, listener ); - logger.debug( "Configuring mojo '" + mojoDescriptor.getId() + "' with " + configuratorId - + " configurator -->" ); + logger.debug( + "Configuring mojo '" + mojoDescriptor.getId() + "' with " + configuratorId + " configurator -->" ); configurator.configureComponent( mojo, configuration, expressionEvaluator, pluginRealm, validator ); @@ -699,7 +695,7 @@ public class DefaultMavenPluginManager ByteArrayOutputStream os = new ByteArrayOutputStream( 1024 ); PrintStream ps = new PrintStream( os ); ps.println( "A required class was missing during configuration of mojo " + mojoDescriptor.getId() + ": " - + e.getMessage() ); + + e.getMessage() ); pluginRealm.display( ps ); throw new PluginConfigurationException( mojoDescriptor.getPluginDescriptor(), os.toString(), e ); @@ -708,8 +704,9 @@ public class DefaultMavenPluginManager { ByteArrayOutputStream os = new ByteArrayOutputStream( 1024 ); PrintStream ps = new PrintStream( os ); - ps.println( "An API incompatibility was encountered during configuration of mojo " + mojoDescriptor.getId() - + ": " + e.getClass().getName() + ": " + e.getMessage() ); + ps.println( + "An API incompatibility was encountered during configuration of mojo " + mojoDescriptor.getId() + ": " + + e.getClass().getName() + ": " + e.getMessage() ); pluginRealm.display( ps ); throw new PluginConfigurationException( mojoDescriptor.getPluginDescriptor(), os.toString(), e ); @@ -766,9 +763,8 @@ public class DefaultMavenPluginManager } catch ( ExpressionEvaluationException e ) { - String msg = - "Error evaluating the expression '" + expression + "' for configuration value '" - + configuration.getName() + "'"; + String msg = "Error evaluating the expression '" + expression + "' for configuration value '" + + configuration.getName() + "'"; throw new ComponentConfigurationException( configuration, msg, e ); } } @@ -811,8 +807,7 @@ public class DefaultMavenPluginManager RepositorySystemSession session ) throws PluginManagerException { - @SuppressWarnings( "unchecked" ) - Map pluginRealms = + @SuppressWarnings( "unchecked" ) Map pluginRealms = (Map) project.getContextValue( KEY_EXTENSIONS_REALMS ); if ( pluginRealms == null ) { @@ -881,8 +876,8 @@ public class DefaultMavenPluginManager extensionRecord = extensionRealmCache.get( extensionKey ); if ( extensionRecord == null ) { - ClassRealm extensionRealm = classRealmManager.createExtensionRealm( plugin, - toAetherArtifacts( artifacts ) ); + ClassRealm extensionRealm = + classRealmManager.createExtensionRealm( plugin, toAetherArtifacts( artifacts ) ); // TODO figure out how to use the same PluginDescriptor when running mojos diff --git a/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptorBuilder.java b/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptorBuilder.java index d990880532..8d732c1e92 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptorBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/project/ExtensionDescriptorBuilder.java @@ -19,7 +19,6 @@ package org.apache.maven.project; * under the License. */ -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; @@ -71,16 +70,10 @@ public class ExtensionDescriptorBuilder if ( pluginDescriptorEntry != null ) { - InputStream is = pluginJar.getInputStream( pluginDescriptorEntry ); - - try + try ( InputStream is = pluginJar.getInputStream( pluginDescriptorEntry ) ) { extensionDescriptor = build( is ); } - finally - { - IOUtil.close( is ); - } } } } @@ -90,15 +83,10 @@ public class ExtensionDescriptorBuilder if ( pluginXml.canRead() ) { - InputStream is = new BufferedInputStream( new FileInputStream( pluginXml ) ); - try + try ( InputStream is = new BufferedInputStream( new FileInputStream( pluginXml ) ) ) { extensionDescriptor = build( is ); } - finally - { - IOUtil.close( is ); - } } } diff --git a/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingException.java b/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingException.java index 47c12315cf..7786c90deb 100644 --- a/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingException.java +++ b/maven-core/src/main/java/org/apache/maven/project/ProjectBuildingException.java @@ -19,14 +19,14 @@ package org.apache.maven.project; * under the License. */ +import org.apache.maven.model.building.ModelProblem; +import org.apache.maven.model.building.ModelProblemUtils; + import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; -import org.apache.maven.model.building.ModelProblem; -import org.apache.maven.model.building.ModelProblemUtils; - /** * @author Jason van Zyl */ @@ -122,23 +122,28 @@ public class ProjectBuildingException private static String createMessage( List results ) { StringWriter buffer = new StringWriter( 1024 ); - PrintWriter writer = new PrintWriter( buffer ); writer.println( "Some problems were encountered while processing the POMs:" ); - for ( ProjectBuildingResult result : results ) + try { - for ( ModelProblem problem : result.getProblems() ) + + for ( ProjectBuildingResult result : results ) { - writer.print( "[" ); - writer.print( problem.getSeverity() ); - writer.print( "] " ); - writer.print( problem.getMessage() ); - writer.print( " @ " ); - writer.println( ModelProblemUtils.formatLocation( problem, result.getProjectId() ) ); + for ( ModelProblem problem : result.getProblems() ) + { + writer.print( "[" ); + writer.print( problem.getSeverity() ); + writer.print( "] " ); + writer.print( problem.getMessage() ); + writer.print( " @ " ); + writer.println( ModelProblemUtils.formatLocation( problem, result.getProjectId() ) ); + } } } - writer.close(); - + finally + { + writer.close(); + } return buffer.toString(); } diff --git a/maven-core/src/main/java/org/apache/maven/rtinfo/internal/DefaultRuntimeInformation.java b/maven-core/src/main/java/org/apache/maven/rtinfo/internal/DefaultRuntimeInformation.java index 6a733f9b9b..f5e97846a3 100644 --- a/maven-core/src/main/java/org/apache/maven/rtinfo/internal/DefaultRuntimeInformation.java +++ b/maven-core/src/main/java/org/apache/maven/rtinfo/internal/DefaultRuntimeInformation.java @@ -19,15 +19,10 @@ package org.apache.maven.rtinfo.internal; * under the License. */ -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - import org.apache.maven.rtinfo.RuntimeInformation; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.Logger; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.StringUtils; import org.eclipse.aether.util.version.GenericVersionScheme; import org.eclipse.aether.version.InvalidVersionSpecificationException; @@ -35,6 +30,10 @@ import org.eclipse.aether.version.Version; import org.eclipse.aether.version.VersionConstraint; import org.eclipse.aether.version.VersionScheme; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + /** * Provides information about the current Maven runtime. */ @@ -56,34 +55,29 @@ public class DefaultRuntimeInformation String resource = "META-INF/maven/org.apache.maven/maven-core/pom.properties"; - InputStream is = DefaultRuntimeInformation.class.getResourceAsStream( "/" + resource ); - if ( is != null ) + try ( InputStream is = DefaultRuntimeInformation.class.getResourceAsStream( "/" + resource ) ) { - try + if ( is != null ) { props.load( is ); } - catch ( IOException e ) + else { - String msg = "Could not parse " + resource + ", Maven runtime information not available"; - if ( logger.isDebugEnabled() ) - { - logger.warn( msg, e ); - } - else - { - logger.warn( msg ); - } - } - finally - { - IOUtil.close( is ); + logger.warn( + "Could not locate " + resource + " on classpath, Maven runtime information not available" ); } } - else + catch ( IOException e ) { - logger.warn( "Could not locate " + resource - + " on classpath, Maven runtime information not available" ); + String msg = "Could not parse " + resource + ", Maven runtime information not available"; + if ( logger.isDebugEnabled() ) + { + logger.warn( msg, e ); + } + else + { + logger.warn( msg ); + } } String version = props.getProperty( "version", "" ).trim(); diff --git a/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainsBuilder.java b/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainsBuilder.java index 5bd3e82a6a..c2b6a61b50 100644 --- a/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainsBuilder.java +++ b/maven-core/src/main/java/org/apache/maven/toolchain/DefaultToolchainsBuilder.java @@ -19,20 +19,18 @@ package org.apache.maven.toolchain; * under the License. */ -import java.io.File; -import java.io.Reader; - import org.apache.maven.toolchain.model.PersistedToolchains; import org.apache.maven.toolchain.model.io.xpp3.MavenToolchainsXpp3Reader; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.Logger; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; +import java.io.File; +import java.io.Reader; + /** * @author Benjamin Bentmann - * * @deprecated instead use {@link org.apache.maven.toolchain.building.DefaultToolchainsBuilder} */ @Deprecated @@ -51,21 +49,16 @@ public class DefaultToolchainsBuilder if ( userToolchainsFile != null && userToolchainsFile.isFile() ) { - Reader in = null; - try + try ( Reader in = ReaderFactory.newXmlReader( userToolchainsFile ) ) { - in = ReaderFactory.newXmlReader( userToolchainsFile ); toolchains = new MavenToolchainsXpp3Reader().read( in ); } catch ( Exception e ) { - throw new MisconfiguredToolchainException( "Cannot read toolchains file at " - + userToolchainsFile.getAbsolutePath(), e ); - } - finally - { - IOUtil.close( in ); + throw new MisconfiguredToolchainException( + "Cannot read toolchains file at " + userToolchainsFile.getAbsolutePath(), e ); } + } else if ( userToolchainsFile != null ) { diff --git a/maven-core/src/test/java/org/apache/maven/settings/PomConstructionWithSettingsTest.java b/maven-core/src/test/java/org/apache/maven/settings/PomConstructionWithSettingsTest.java index 5c16686896..78d0da8de6 100644 --- a/maven-core/src/test/java/org/apache/maven/settings/PomConstructionWithSettingsTest.java +++ b/maven-core/src/test/java/org/apache/maven/settings/PomConstructionWithSettingsTest.java @@ -19,10 +19,6 @@ package org.apache.maven.settings; * under the License. */ -import java.io.File; -import java.io.IOException; -import java.io.Reader; - import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; import org.apache.maven.model.Profile; import org.apache.maven.project.DefaultProjectBuilder; @@ -36,13 +32,16 @@ import org.apache.maven.settings.io.xpp3.SettingsXpp3Reader; import org.codehaus.plexus.ContainerConfiguration; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusTestCase; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; import org.eclipse.aether.repository.LocalRepository; +import java.io.File; +import java.io.IOException; +import java.io.Reader; + public class PomConstructionWithSettingsTest extends PlexusTestCase { @@ -81,14 +80,18 @@ public class PomConstructionWithSettingsTest super.tearDown(); } - public void testSettingsNoPom() throws Exception + public void testSettingsNoPom() + throws Exception { PomTestWrapper pom = buildPom( "settings-no-pom" ); assertEquals( "local-profile-prop-value", pom.getValue( "properties/local-profile-prop" ) ); } - /**MNG-4107 */ - public void testPomAndSettingsInterpolation() throws Exception + /** + * MNG-4107 + */ + public void testPomAndSettingsInterpolation() + throws Exception { PomTestWrapper pom = buildPom( "test-pom-and-settings-interpolation" ); assertEquals( "applied", pom.getValue( "properties/settingsProfile" ) ); @@ -97,8 +100,11 @@ public class PomConstructionWithSettingsTest assertEquals( "settings", pom.getValue( "properties/pomVsSettingsInterpolated" ) ); } - /**MNG-4107 */ - public void testRepositories() throws Exception + /** + * MNG-4107 + */ + public void testRepositories() + throws Exception { PomTestWrapper pom = buildPom( "repositories" ); assertEquals( "maven-core-it-0", pom.getValue( "repositories[1]/id" ) ); @@ -122,13 +128,15 @@ public class PomConstructionWithSettingsTest String localRepoUrl = System.getProperty( "maven.repo.local", System.getProperty( "user.home" ) + "/.m2/repository" ); localRepoUrl = "file://" + localRepoUrl; - config.setLocalRepository( repositorySystem.createArtifactRepository( "local", localRepoUrl, - new DefaultRepositoryLayout(), null, null ) ); + config.setLocalRepository( + repositorySystem.createArtifactRepository( "local", localRepoUrl, new DefaultRepositoryLayout(), null, + null ) ); config.setActiveProfileIds( settings.getActiveProfiles() ); DefaultRepositorySystemSession repoSession = MavenRepositorySystemUtils.newSession(); LocalRepository localRepo = new LocalRepository( config.getLocalRepository().getBasedir() ); - repoSession.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( repoSession, localRepo ) ); + repoSession.setLocalRepositoryManager( + new SimpleLocalRepositoryManagerFactory().newInstance( repoSession, localRepo ) ); config.setRepositorySession( repoSession ); return new PomTestWrapper( pomFile, projectBuilder.build( pomFile, config ).getProject() ); @@ -139,21 +147,12 @@ public class PomConstructionWithSettingsTest { Settings settings = null; - Reader reader = null; - - try + try ( Reader reader = ReaderFactory.newXmlReader( settingsFile ) ) { - reader = ReaderFactory.newXmlReader( settingsFile ); - SettingsXpp3Reader modelReader = new SettingsXpp3Reader(); settings = modelReader.read( reader ); } - finally - { - IOUtil.close( reader ); - } - return settings; } } diff --git a/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainTest.java b/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainTest.java index 3bba8177d1..eeb07cfcac 100644 --- a/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainTest.java +++ b/maven-core/src/test/java/org/apache/maven/toolchain/DefaultToolchainTest.java @@ -19,38 +19,38 @@ package org.apache.maven.toolchain; * under the License. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.verify; - -import java.io.InputStream; -import java.util.Collections; - import org.apache.maven.toolchain.java.DefaultJavaToolChain; import org.apache.maven.toolchain.model.PersistedToolchains; import org.apache.maven.toolchain.model.ToolchainModel; import org.apache.maven.toolchain.model.io.xpp3.MavenToolchainsXpp3Reader; import org.codehaus.plexus.logging.Logger; -import org.codehaus.plexus.util.IOUtil; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import java.io.InputStream; +import java.util.Collections; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; + public class DefaultToolchainTest { @Mock private Logger logger; - + private MavenToolchainsXpp3Reader reader = new MavenToolchainsXpp3Reader(); - + @Before - public void setUp() throws Exception + public void setUp() + throws Exception { MockitoAnnotations.initMocks( this ); } - + private DefaultToolchain newDefaultToolchain( ToolchainModel model ) { return new DefaultToolchain( model, logger ) @@ -102,14 +102,14 @@ public class DefaultToolchainTest DefaultToolchain toolchain = newDefaultToolchain( model ); assertEquals( logger, toolchain.getLog() ); } - + @Test public void testMissingRequirementProperty() { ToolchainModel model = new ToolchainModel(); model.setType( "TYPE" ); DefaultToolchain toolchain = newDefaultToolchain( model ); - + assertFalse( toolchain.matchesRequirements( Collections.singletonMap( "name", "John Doe" ) ) ); verify( logger ).debug( "Toolchain type:TYPE{} is missing required property: name" ); } @@ -122,22 +122,19 @@ public class DefaultToolchainTest model.setType( "TYPE" ); DefaultToolchain toolchain = newDefaultToolchain( model ); toolchain.addProvideToken( "name", RequirementMatcherFactory.createExactMatcher( "Jane Doe" ) ); - + assertFalse( toolchain.matchesRequirements( Collections.singletonMap( "name", "John Doe" ) ) ); verify( logger ).debug( "Toolchain type:TYPE{name = Jane Doe} doesn't match required property: name" ); } @Test - public void testEquals() throws Exception + public void testEquals() + throws Exception { - InputStream jdksIS = null; - InputStream jdksExtraIS = null; - try + try ( InputStream jdksIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ); + InputStream jdksExtraIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks-extra.xml" ) ) { - jdksIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ); - jdksExtraIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks-extra.xml" ); - PersistedToolchains jdks = reader.read( jdksIS ); PersistedToolchains jdksExtra = reader.read( jdksExtraIS ); @@ -149,10 +146,5 @@ public class DefaultToolchainTest assertFalse( tc2.equals( tc1 ) ); assertTrue( tc2.equals( tc2 ) ); } - finally - { - IOUtil.close( jdksIS ); - IOUtil.close( jdksExtraIS ); - } } } diff --git a/maven-core/src/test/java/org/apache/maven/toolchain/merge/MavenToolchainMergerTest.java b/maven-core/src/test/java/org/apache/maven/toolchain/merge/MavenToolchainMergerTest.java index 9183e175f3..536e1a66d9 100644 --- a/maven-core/src/test/java/org/apache/maven/toolchain/merge/MavenToolchainMergerTest.java +++ b/maven-core/src/test/java/org/apache/maven/toolchain/merge/MavenToolchainMergerTest.java @@ -19,18 +19,17 @@ package org.apache.maven.toolchain.merge; * under the License. */ -import static org.junit.Assert.assertEquals; - -import java.io.InputStream; - import org.apache.maven.toolchain.model.PersistedToolchains; import org.apache.maven.toolchain.model.ToolchainModel; import org.apache.maven.toolchain.model.TrackableBase; import org.apache.maven.toolchain.model.io.xpp3.MavenToolchainsXpp3Reader; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.Test; +import java.io.InputStream; + +import static org.junit.Assert.assertEquals; + public class MavenToolchainMergerTest { private MavenToolchainMerger merger = new MavenToolchainMerger(); @@ -41,97 +40,71 @@ public class MavenToolchainMergerTest public void testMergeNulls() { merger.merge( null, null, null ); - + PersistedToolchains pt = new PersistedToolchains(); merger.merge( pt, null, null ); merger.merge( null, pt, null ); } - + @Test - public void testMergeJdk() throws Exception + public void testMergeJdk() + throws Exception { - InputStream isDominant = null; - InputStream isRecessive = null; - try + try ( InputStream isDominant = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ); + InputStream isRecessive = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ) ) { - isDominant = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ); - isRecessive = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ); - PersistedToolchains dominant = reader.read( isDominant ); PersistedToolchains recessive = reader.read( isRecessive ); assertEquals( 2, dominant.getToolchains().size() ); - + merger.merge( dominant, recessive, TrackableBase.USER_LEVEL ); assertEquals( 2, dominant.getToolchains().size() ); } - finally - { - IOUtil.close( isDominant ); - } } @Test - public void testMergeJdkExtra() throws Exception + public void testMergeJdkExtra() + throws Exception { - InputStream jdksIS = null; - InputStream jdksExtraIS = null; - try + try ( InputStream jdksIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ); + InputStream jdksExtraIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks-extra.xml" ) ) { - jdksIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ); - jdksExtraIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks-extra.xml" ); - PersistedToolchains jdks = reader.read( jdksIS ); PersistedToolchains jdksExtra = reader.read( jdksExtraIS ); assertEquals( 2, jdks.getToolchains().size() ); - + merger.merge( jdks, jdksExtra, TrackableBase.USER_LEVEL ); assertEquals( 4, jdks.getToolchains().size() ); assertEquals( 2, jdksExtra.getToolchains().size() ); } - finally + try ( InputStream jdksIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ); + InputStream jdksExtraIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks-extra.xml" ) ) { - IOUtil.close( jdksIS ); - IOUtil.close( jdksExtraIS ); - } - - try - { - jdksIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ); - jdksExtraIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks-extra.xml" ); - PersistedToolchains jdks = reader.read( jdksIS ); PersistedToolchains jdksExtra = reader.read( jdksExtraIS ); assertEquals( 2, jdks.getToolchains().size() ); - + // switch dominant with reccessive merger.merge( jdksExtra, jdks, TrackableBase.USER_LEVEL ); assertEquals( 4, jdksExtra.getToolchains().size() ); assertEquals( 2, jdks.getToolchains().size() ); } - finally - { - IOUtil.close( jdksIS ); - IOUtil.close( jdksExtraIS ); - } } - + @Test - public void testMergeJdkExtend() throws Exception + public void testMergeJdkExtend() + throws Exception { - InputStream jdksIS = null; - InputStream jdksExtendIS = null; - try + try ( InputStream jdksIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ); + InputStream jdksExtendIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks-extend.xml" ) ) { - jdksIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ); - jdksExtendIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks-extend.xml" ); - PersistedToolchains jdks = reader.read( jdksIS ); PersistedToolchains jdksExtend = reader.read( jdksExtendIS ); assertEquals( 2, jdks.getToolchains().size() ); - + merger.merge( jdks, jdksExtend, TrackableBase.USER_LEVEL ); assertEquals( 2, jdks.getToolchains().size() ); - Xpp3Dom config0 = (Xpp3Dom) jdks.getToolchains().get( 0 ).getConfiguration(); + Xpp3Dom config0 = (Xpp3Dom) jdks.getToolchains().get( 0 ).getConfiguration(); assertEquals( "lib/tools.jar", config0.getChild( "toolsJar" ).getValue() ); assertEquals( 2, config0.getChildCount() ); Xpp3Dom config1 = (Xpp3Dom) jdks.getToolchains().get( 1 ).getConfiguration(); @@ -139,25 +112,17 @@ public class MavenToolchainMergerTest assertEquals( "lib/classes.jar", config1.getChild( "toolsJar" ).getValue() ); assertEquals( 2, jdksExtend.getToolchains().size() ); } - finally + try ( InputStream jdksIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ); + InputStream jdksExtendIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks-extend.xml" ) ) { - IOUtil.close( jdksIS ); - IOUtil.close( jdksExtendIS ); - } - - try - { - jdksIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks.xml" ); - jdksExtendIS = ToolchainModel.class.getResourceAsStream( "toolchains-jdks-extend.xml" ); - PersistedToolchains jdks = reader.read( jdksIS ); PersistedToolchains jdksExtend = reader.read( jdksExtendIS ); assertEquals( 2, jdks.getToolchains().size() ); - + // switch dominant with reccessive merger.merge( jdksExtend, jdks, TrackableBase.USER_LEVEL ); assertEquals( 2, jdksExtend.getToolchains().size() ); - Xpp3Dom config0 = (Xpp3Dom) jdksExtend.getToolchains().get( 0 ).getConfiguration(); + Xpp3Dom config0 = (Xpp3Dom) jdksExtend.getToolchains().get( 0 ).getConfiguration(); assertEquals( "lib/tools.jar", config0.getChild( "toolsJar" ).getValue() ); assertEquals( 2, config0.getChildCount() ); Xpp3Dom config1 = (Xpp3Dom) jdksExtend.getToolchains().get( 1 ).getConfiguration(); @@ -165,12 +130,6 @@ public class MavenToolchainMergerTest assertEquals( "lib/classes.jar", config1.getChild( "toolsJar" ).getValue() ); assertEquals( 2, jdks.getToolchains().size() ); } - finally - { - IOUtil.close( jdksIS ); - IOUtil.close( jdksExtendIS ); - } - } } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/CLIReportingUtils.java b/maven-embedder/src/main/java/org/apache/maven/cli/CLIReportingUtils.java index 07863b723c..cab39e20dd 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/CLIReportingUtils.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/CLIReportingUtils.java @@ -19,6 +19,9 @@ package org.apache.maven.cli; * under the License. */ +import org.codehaus.plexus.util.Os; +import org.slf4j.Logger; + import java.io.IOException; import java.io.InputStream; import java.util.Date; @@ -26,15 +29,10 @@ import java.util.Locale; import java.util.Properties; import java.util.TimeZone; -import org.codehaus.plexus.util.IOUtil; -import org.codehaus.plexus.util.Os; -import org.slf4j.Logger; - /** * Utility class used to report errors, statistics, application version info, etc. * * @author jdcasey - * */ public final class CLIReportingUtils { @@ -42,8 +40,11 @@ public final class CLIReportingUtils public static final long MB = 1024 * 1024; private static final long ONE_SECOND = 1000L; + private static final long ONE_MINUTE = 60 * ONE_SECOND; + private static final long ONE_HOUR = 60 * ONE_MINUTE; + private static final long ONE_DAY = 24 * ONE_HOUR; // CHECKSTYLE_ON: MagicNumber @@ -55,8 +56,12 @@ public final class CLIReportingUtils Properties properties = getBuildProperties(); StringBuilder version = new StringBuilder(); version.append( createMavenVersionString( properties ) ).append( ls ); - version.append( reduce( properties.getProperty( "distributionShortName" ) + " home: " - + System.getProperty( "maven.home", "" ) ) ).append( ls ); + version.append( reduce( + properties.getProperty( "distributionShortName" ) + " home: " + System.getProperty( "maven.home", + "" ) ) ) + .append( + ls ); version.append( "Java version: " ).append( System.getProperty( "java.version", "" ) ).append( ", vendor: " ).append( System.getProperty( "java.vendor", "" ) ).append( ls ); @@ -105,10 +110,10 @@ public final class CLIReportingUtils static Properties getBuildProperties() { Properties properties = new Properties(); - InputStream resourceAsStream = null; - try + + try ( InputStream resourceAsStream = MavenCli.class.getResourceAsStream( + "/org/apache/maven/messages/build.properties" ) ) { - resourceAsStream = MavenCli.class.getResourceAsStream( "/org/apache/maven/messages/build.properties" ); if ( resourceAsStream != null ) { @@ -119,10 +124,6 @@ public final class CLIReportingUtils { System.err.println( "Unable determine version from JAR file: " + e.getMessage() ); } - finally - { - IOUtil.close( resourceAsStream ); - } return properties; } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java b/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java index 2f170086ed..8ce299f653 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java @@ -19,27 +19,9 @@ package org.apache.maven.cli; * under the License. */ -import java.io.BufferedInputStream; -import java.io.Console; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.StringTokenizer; - +import com.google.common.base.Charsets; +import com.google.common.io.Files; +import com.google.inject.AbstractModule; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.UnrecognizedOptionException; @@ -93,7 +75,6 @@ import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.classworlds.realm.NoSuchRealmException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.logging.LoggerManager; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.eclipse.aether.transfer.TransferListener; @@ -106,15 +87,32 @@ import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher; import org.sonatype.plexus.components.sec.dispatcher.SecUtil; import org.sonatype.plexus.components.sec.dispatcher.model.SettingsSecurity; -import com.google.common.base.Charsets; -import com.google.common.io.Files; -import com.google.inject.AbstractModule; +import java.io.BufferedInputStream; +import java.io.Console; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; +import java.util.Set; +import java.util.StringTokenizer; // TODO: push all common bits back to plexus cli and prepare for transition to Guice. We don't need 50 ways to make CLIs /** * @author Jason van Zyl - * @noinspection UseOfSystemOutOrSystemErr,ACCESS_STATIC_VIA_INSTANCE + * @noinspection UseOfSystemOutOrSystemErr, ACCESS_STATIC_VIA_INSTANCE */ public class MavenCli { @@ -143,8 +141,8 @@ public class MavenCli public static final File DEFAULT_USER_TOOLCHAINS_FILE = new File( userMavenConfigurationHome, "toolchains.xml" ); - public static final File DEFAULT_GLOBAL_TOOLCHAINS_FILE = - new File( System.getProperty( "maven.home", System.getProperty( "user.dir", "" ) ), "conf/toolchains.xml" ); + public static final File DEFAULT_GLOBAL_TOOLCHAINS_FILE = + new File( System.getProperty( "maven.home", System.getProperty( "user.dir", "" ) ), "conf/toolchains.xml" ); private static final String EXT_CLASS_PATH = "maven.ext.class.path"; @@ -171,7 +169,7 @@ public class MavenCli private DefaultSecDispatcher dispatcher; private Map configurationProcessors; - + public MavenCli() { this( null ); @@ -190,7 +188,9 @@ public class MavenCli System.exit( result ); } - /** @noinspection ConfusingMainMethod */ + /** + * @noinspection ConfusingMainMethod + */ public static int main( String[] args, ClassWorld classWorld ) { MavenCli cli = new MavenCli(); @@ -328,8 +328,9 @@ public class MavenCli String basedirProperty = System.getProperty( MULTIMODULE_PROJECT_DIRECTORY ); if ( basedirProperty == null ) { - System.err.format( "-D%s system property is not set." - + " Check $M2_HOME environment variable and mvn script match.", MULTIMODULE_PROJECT_DIRECTORY ); + System.err.format( + "-D%s system property is not set." + " Check $M2_HOME environment variable and mvn script match.", + MULTIMODULE_PROJECT_DIRECTORY ); throw new ExitException( 1 ); } File basedir = basedirProperty != null ? new File( basedirProperty ) : new File( "" ); @@ -522,12 +523,9 @@ public class MavenCli ClassRealm containerRealm = setupContainerRealm( cliRequest.classWorld, coreRealm, extClassPath, extensions ); - ContainerConfiguration cc = new DefaultContainerConfiguration() - .setClassWorld( cliRequest.classWorld ) - .setRealm( containerRealm ) - .setClassPathScanning( PlexusConstants.SCANNING_INDEX ) - .setAutoWiring( true ) - .setName( "maven" ); + ContainerConfiguration cc = new DefaultContainerConfiguration().setClassWorld( cliRequest.classWorld ).setRealm( + containerRealm ).setClassPathScanning( PlexusConstants.SCANNING_INDEX ).setAutoWiring( true ).setName( + "maven" ); Set exportedArtifacts = new HashSet<>( coreEntry.getExportedArtifacts() ); Set exportedPackages = new HashSet<>( coreEntry.getExportedPackages() ); @@ -586,7 +584,7 @@ public class MavenCli modelProcessor = createModelProcessor( container ); configurationProcessors = container.lookupMap( ConfigurationProcessor.class ); - + toolchainsBuilder = container.lookup( ToolchainsBuilder.class ); dispatcher = (DefaultSecDispatcher) container.lookup( SecDispatcher.class, "maven" ); @@ -643,19 +641,19 @@ public class MavenCli Thread.currentThread().setContextClassLoader( container.getContainerRealm() ); executionRequestPopulator = container.lookup( MavenExecutionRequestPopulator.class ); - + configurationProcessors = container.lookupMap( ConfigurationProcessor.class ); - + configure( cliRequest ); - + MavenExecutionRequest request = DefaultMavenExecutionRequest.copy( cliRequest.request ); request = populateRequest( cliRequest, request ); - + request = executionRequestPopulator.populateDefaults( request ); BootstrapCoreExtensionManager resolver = container.lookup( BootstrapCoreExtensionManager.class ); - + return resolver.loadCoreExtensions( request, providedArtifacts, extensions ); } finally @@ -680,16 +678,13 @@ public class MavenCli throws IOException, XmlPullParserException { CoreExtensionsXpp3Reader parser = new CoreExtensionsXpp3Reader(); - InputStream is = null; - try + + try ( InputStream is = new BufferedInputStream( new FileInputStream( extensionsFile ) ) ) { - is = new BufferedInputStream( new FileInputStream( extensionsFile ) ); + return parser.read( is ).getExtensions(); } - finally - { - IOUtil.close( is ); - } + } private ClassRealm setupContainerRealm( ClassWorld classWorld, ClassRealm coreRealm, List extClassPath, @@ -790,8 +785,8 @@ public class MavenCli DefaultPlexusCipher cipher = new DefaultPlexusCipher(); - System.out.println( cipher.encryptAndDecorate( passwd, - DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION ) ); + System.out.println( + cipher.encryptAndDecorate( passwd, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION ) ); throw new ExitException( 0 ); } @@ -846,17 +841,18 @@ public class MavenCli private void repository( CliRequest cliRequest ) throws Exception { - if ( cliRequest.commandLine.hasOption( CLIManager.LEGACY_LOCAL_REPOSITORY ) - || Boolean.getBoolean( "maven.legacyLocalRepo" ) ) + if ( cliRequest.commandLine.hasOption( CLIManager.LEGACY_LOCAL_REPOSITORY ) || Boolean.getBoolean( + "maven.legacyLocalRepo" ) ) { - cliRequest.request.setUseLegacyLocalRepository( true ); + cliRequest.request.setUseLegacyLocalRepository( true ); } } - private int execute( CliRequest cliRequest ) throws MavenExecutionRequestPopulationException + private int execute( CliRequest cliRequest ) + throws MavenExecutionRequestPopulationException { MavenExecutionRequest request = executionRequestPopulator.populateDefaults( cliRequest.request ); - + eventSpyDispatcher.onEvent( request ); MavenExecutionResult result = maven.execute( request ); @@ -900,7 +896,7 @@ public class MavenCli { slf4jLogger.error( "" ); slf4jLogger.error( "For more information about the errors and possible solutions" - + ", please read the following articles:" ); + + ", please read the following articles:" ); for ( Map.Entry entry : references.entrySet() ) { @@ -967,8 +963,8 @@ public class MavenCli { String line = indent + lines[i].trim(); - if ( ( i == lines.length - 1 ) - && ( showErrors || ( summary.getException() instanceof InternalErrorException ) ) ) + if ( ( i == lines.length - 1 ) && ( showErrors + || ( summary.getException() instanceof InternalErrorException ) ) ) { slf4jLogger.error( line, summary.getException() ); } @@ -997,7 +993,7 @@ public class MavenCli // it can be accessed by configuration processors. // cliRequest.request.setEventSpyDispatcher( eventSpyDispatcher ); - + // // We expect at most 2 implementations to be available. The SettingsXmlConfigurationProcessor implementation // is always available in the core and likely always will be, but we may have another ConfigurationProcessor @@ -1006,15 +1002,15 @@ public class MavenCli // the default SettingsXmlConfigurationProcessor. // int userSuppliedConfigurationProcessorCount = configurationProcessors.size() - 1; - + if ( userSuppliedConfigurationProcessorCount == 0 ) { // // Our settings.xml source is historically how we have configured Maven from the CLI so we are going to // have to honour its existence forever. So let's run it. // - configurationProcessors.get( SettingsXmlConfigurationProcessor.HINT ).process( cliRequest ); - } + configurationProcessors.get( SettingsXmlConfigurationProcessor.HINT ).process( cliRequest ); + } else if ( userSuppliedConfigurationProcessorCount == 1 ) { // @@ -1028,7 +1024,7 @@ public class MavenCli ConfigurationProcessor configurationProcessor = entry.getValue(); configurationProcessor.process( cliRequest ); } - } + } } else if ( userSuppliedConfigurationProcessorCount > 1 ) { @@ -1036,7 +1032,7 @@ public class MavenCli // There are too many ConfigurationProcessors so we don't know which one to run so report the error. // StringBuilder sb = new StringBuilder( - String.format( "\nThere can only be one user supplied ConfigurationProcessor, there are %s:\n\n", + String.format( "\nThere can only be one user supplied ConfigurationProcessor, there are %s:\n\n", userSuppliedConfigurationProcessorCount ) ); for ( Entry entry : configurationProcessors.entrySet() ) { @@ -1049,9 +1045,9 @@ public class MavenCli } sb.append( String.format( "\n" ) ); throw new Exception( sb.toString() ); - } + } } - + @SuppressWarnings( "checkstyle:methodlength" ) private void toolchains( CliRequest cliRequest ) throws Exception @@ -1066,8 +1062,8 @@ public class MavenCli if ( !userToolchainsFile.isFile() ) { - throw new FileNotFoundException( "The specified user toolchains file does not exist: " - + userToolchainsFile ); + throw new FileNotFoundException( + "The specified user toolchains file does not exist: " + userToolchainsFile ); } } else @@ -1085,8 +1081,8 @@ public class MavenCli if ( !globalToolchainsFile.isFile() ) { - throw new FileNotFoundException( "The specified global toolchains file does not exist: " - + globalToolchainsFile ); + throw new FileNotFoundException( + "The specified global toolchains file does not exist: " + globalToolchainsFile ); } } else @@ -1109,10 +1105,11 @@ public class MavenCli eventSpyDispatcher.onEvent( toolchainsRequest ); - slf4jLogger.debug( "Reading global toolchains from " - + getLocation( toolchainsRequest.getGlobalToolchainsSource(), globalToolchainsFile ) ); - slf4jLogger.debug( "Reading user toolchains from " - + getLocation( toolchainsRequest.getUserToolchainsSource(), userToolchainsFile ) ); + slf4jLogger.debug( + "Reading global toolchains from " + getLocation( toolchainsRequest.getGlobalToolchainsSource(), + globalToolchainsFile ) ); + slf4jLogger.debug( "Reading user toolchains from " + getLocation( toolchainsRequest.getUserToolchainsSource(), + userToolchainsFile ) ); ToolchainsBuildingResult toolchainsResult = toolchainsBuilder.build( toolchainsRequest ); @@ -1162,7 +1159,7 @@ public class MavenCli if ( commandLine.hasOption( deprecatedOption ) ) { slf4jLogger.warn( "Command line option -" + deprecatedOption - + " is deprecated and will be removed in future Maven versions." ); + + " is deprecated and will be removed in future Maven versions." ); } } @@ -1186,8 +1183,7 @@ public class MavenCli // // ---------------------------------------------------------------------- - @SuppressWarnings( "unchecked" ) - List goals = commandLine.getArgList(); + @SuppressWarnings( "unchecked" ) List goals = commandLine.getArgList(); boolean recursive = true; @@ -1317,16 +1313,15 @@ public class MavenCli userToolchainsFile = MavenCli.DEFAULT_USER_TOOLCHAINS_FILE; } - request.setBaseDirectory( baseDirectory ).setGoals( goals ) - .setSystemProperties( cliRequest.systemProperties ) - .setUserProperties( cliRequest.userProperties ) - .setReactorFailureBehavior( reactorFailureBehaviour ) // default: fail fast + request.setBaseDirectory( baseDirectory ).setGoals( goals ).setSystemProperties( + cliRequest.systemProperties ).setUserProperties( cliRequest.userProperties ).setReactorFailureBehavior( + reactorFailureBehaviour ) // default: fail fast .setRecursive( recursive ) // default: true .setShowErrors( showErrors ) // default: false .addActiveProfiles( activeProfiles ) // optional .addInactiveProfiles( inactiveProfiles ) // optional - .setExecutionListener( executionListener ) - .setTransferListener( transferListener ) // default: batch mode which goes along with interactive + .setExecutionListener( executionListener ).setTransferListener( + transferListener ) // default: batch mode which goes along with interactive .setUpdateSnapshots( updateSnapshots ) // default: false .setNoSnapshotUpdates( noSnapshotUpdates ) // default: false .setGlobalChecksumPolicy( globalChecksumPolicy ) // default: warn @@ -1399,18 +1394,18 @@ public class MavenCli request.setExcludedProjects( exclProjects ); } - if ( commandLine.hasOption( CLIManager.ALSO_MAKE ) - && !commandLine.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) ) + if ( commandLine.hasOption( CLIManager.ALSO_MAKE ) && !commandLine.hasOption( + CLIManager.ALSO_MAKE_DEPENDENTS ) ) { request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_UPSTREAM ); } - else if ( !commandLine.hasOption( CLIManager.ALSO_MAKE ) - && commandLine.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) ) + else if ( !commandLine.hasOption( CLIManager.ALSO_MAKE ) && commandLine.hasOption( + CLIManager.ALSO_MAKE_DEPENDENTS ) ) { request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM ); } - else if ( commandLine.hasOption( CLIManager.ALSO_MAKE ) - && commandLine.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) ) + else if ( commandLine.hasOption( CLIManager.ALSO_MAKE ) && commandLine.hasOption( + CLIManager.ALSO_MAKE_DEPENDENTS ) ) { request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_BOTH ); } @@ -1420,8 +1415,8 @@ public class MavenCli if ( localRepoProperty == null ) { localRepoProperty = request.getSystemProperties().getProperty( MavenCli.LOCAL_REPO_PROPERTY ); - } - + } + if ( localRepoProperty != null ) { request.setLocalRepositoryPath( localRepoProperty ); diff --git a/maven-model-builder/src/test/java/org/apache/maven/model/inheritance/DefaultInheritanceAssemblerTest.java b/maven-model-builder/src/test/java/org/apache/maven/model/inheritance/DefaultInheritanceAssemblerTest.java index 1aef12ec71..f9e95ecd67 100644 --- a/maven-model-builder/src/test/java/org/apache/maven/model/inheritance/DefaultInheritanceAssemblerTest.java +++ b/maven-model-builder/src/test/java/org/apache/maven/model/inheritance/DefaultInheritanceAssemblerTest.java @@ -19,22 +19,21 @@ package org.apache.maven.model.inheritance; * under the License. */ -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; - import org.apache.maven.model.Model; import org.apache.maven.model.building.SimpleProblemCollector; import org.apache.maven.model.io.ModelParseException; import org.apache.maven.model.io.ModelReader; import org.apache.maven.model.io.ModelWriter; import org.codehaus.plexus.PlexusTestCase; -import org.codehaus.plexus.util.IOUtil; import org.custommonkey.xmlunit.XMLAssert; import org.custommonkey.xmlunit.XMLUnit; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; + /** * @author Hervé Boutemy */ @@ -85,24 +84,16 @@ public class DefaultInheritanceAssemblerTest writer.write( actual, null, child ); // check with getPom( "plugin-configuration-effective" ) - Reader control = null; - Reader test = null; - try + File expected = getPom( "plugin-configuration-expected" ); + try ( Reader control = new InputStreamReader( new FileInputStream( expected ), "UTF-8" ); + Reader test = new InputStreamReader( new FileInputStream( actual ), "UTF-8" ) ) { - File expected = getPom( "plugin-configuration-expected" ); - control = new InputStreamReader( new FileInputStream( expected ), "UTF-8" ); - - test = new InputStreamReader( new FileInputStream( actual ), "UTF-8" ); XMLUnit.setIgnoreComments( true ); XMLUnit.setIgnoreWhitespace( true ); XMLAssert.assertXMLEqual( control, test ); } - catch ( IOException ioe ) - { - IOUtil.close( control ); - IOUtil.close( test ); - } + } } diff --git a/maven-plugin-api/src/main/java/org/apache/maven/plugin/descriptor/PluginDescriptor.java b/maven-plugin-api/src/main/java/org/apache/maven/plugin/descriptor/PluginDescriptor.java index b70d291267..f65f8247b3 100644 --- a/maven-plugin-api/src/main/java/org/apache/maven/plugin/descriptor/PluginDescriptor.java +++ b/maven-plugin-api/src/main/java/org/apache/maven/plugin/descriptor/PluginDescriptor.java @@ -19,6 +19,17 @@ package org.apache.maven.plugin.descriptor; * under the License. */ +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.ArtifactUtils; +import org.apache.maven.model.Plugin; +import org.apache.maven.plugin.lifecycle.Lifecycle; +import org.apache.maven.plugin.lifecycle.LifecycleConfiguration; +import org.apache.maven.plugin.lifecycle.io.xpp3.LifecycleMappingsXpp3Reader; +import org.codehaus.plexus.classworlds.realm.ClassRealm; +import org.codehaus.plexus.component.repository.ComponentSetDescriptor; +import org.codehaus.plexus.util.ReaderFactory; +import org.codehaus.plexus.util.xml.pull.XmlPullParserException; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -32,18 +43,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.ArtifactUtils; -import org.apache.maven.model.Plugin; -import org.apache.maven.plugin.lifecycle.Lifecycle; -import org.apache.maven.plugin.lifecycle.LifecycleConfiguration; -import org.apache.maven.plugin.lifecycle.io.xpp3.LifecycleMappingsXpp3Reader; -import org.codehaus.plexus.classworlds.realm.ClassRealm; -import org.codehaus.plexus.component.repository.ComponentSetDescriptor; -import org.codehaus.plexus.util.IOUtil; -import org.codehaus.plexus.util.ReaderFactory; -import org.codehaus.plexus.util.xml.pull.XmlPullParserException; - /** * @author Jason van Zyl */ @@ -115,8 +114,9 @@ public class PluginDescriptor if ( existing != null ) { - throw new DuplicateMojoDescriptorException( getGoalPrefix(), mojoDescriptor.getGoal(), existing - .getImplementation(), mojoDescriptor.getImplementation() ); + throw new DuplicateMojoDescriptorException( getGoalPrefix(), mojoDescriptor.getGoal(), + existing.getImplementation(), + mojoDescriptor.getImplementation() ); } else { @@ -272,7 +272,7 @@ public class PluginDescriptor return true; } - return object instanceof PluginDescriptor && getId().equals( ( (PluginDescriptor) object ).getId() ); + return object instanceof PluginDescriptor && getId().equals( ( (PluginDescriptor) object ).getId() ); } public int hashCode() @@ -316,8 +316,9 @@ public class PluginDescriptor public Set getIntroducedDependencyArtifacts() { - return ( introducedDependencyArtifacts != null ) ? introducedDependencyArtifacts - : Collections.emptySet(); + return ( introducedDependencyArtifacts != null ) + ? introducedDependencyArtifacts + : Collections.emptySet(); } public void setName( String name ) @@ -377,17 +378,10 @@ public class PluginDescriptor { LifecycleConfiguration lifecycleConfiguration; - Reader reader = null; - try + try ( Reader reader = ReaderFactory.newXmlReader( getDescriptorStream( LIFECYCLE_DESCRIPTOR ) ) ) { - reader = ReaderFactory.newXmlReader( getDescriptorStream( LIFECYCLE_DESCRIPTOR ) ); - lifecycleConfiguration = new LifecycleMappingsXpp3Reader().read( reader ); } - finally - { - IOUtil.close( reader ); - } lifecycleMappings = new HashMap<>();