diff options
21 files changed, 840 insertions, 594 deletions
diff --git a/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java new file mode 100644 index 000000000..f71d45fc7 --- /dev/null +++ b/archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/archiva/common/Try.java @@ -0,0 +1,253 @@ +package org.apache.archiva.common; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.function.Function; + +/** + * This is a class that can be used for the Try monad + * + * The Try monad is able to collect exceptions during processing + * of a stream. + * + * + * + */ +public abstract class Try<V> { + + private Try() { + + } + + public abstract Boolean isSuccess(); + + public abstract Boolean isFailure(); + + public abstract void throwException(); + + /** + * Returns the value if this is a success instance. Otherwise throws + * a runtime exception with the stored throwable as cause. + * + * @return The value + */ + public abstract V get(); + + /** + * Returns the throwable that is stored in the failure. + * + * @return The Throwable or null. + */ + public abstract Throwable getError(); + + + /** + * A mapping method for mapping the current instance to a new type. + * + * @param fn + * @param <U> + * @return + */ + public <U> Try<U> map(Function<? super V, U> fn) { + try { + return Try.success(fn.apply(get())); + } catch (Throwable e) { + return Try.failure(e); + } + } + + /** + * This is the bind method. + * If this instance is success the function will be applied. If any error occurs + * a failure instance will be returned. + * If this instance is failure a new failure will be returned. + * + * @param fn + * @param <U> + * @return + */ + public <U> Try<U> flatMap(Function<? super V, Try<U>> fn) { + try { + return fn.apply(get()); + } catch (Throwable t) { + return Try.failure(t); + } + } + + public static <V> Try<V> failure(String message) { + + return new Failure<>(message); + + } + + public static <V> Try<V> failure(String message, Throwable e) { + + return new Failure<>(message, e); + + } + + /** + * If you need type coercion, you should call this method as + * Try.<YOUR_TYPE>failure(e) + * + * + * + * @param e The exception that is thrown + * @param <V> The generic type this monad keeps + * @return A new Try instance that represents a failure. + */ + public static <V> Try<V> failure(Throwable e) { + + return new Failure<>(e); + + } + + + /** + * Returns a instance for the success case. + * + * @param value The value that should be stored. + * @param <V> The return type + * @return A new Try instance with the given value + */ + public static <V> Try<V> success(V value) { + + return new Success<>(value); + + } + + private static class Failure<V> extends Try<V> { + + private Throwable exception; + + public Failure(String message) { + + super(); + + this.exception = new IllegalStateException(message); + + } + + public Failure(String message, Throwable e) { + + super(); + + this.exception = new IllegalStateException(message, e); + + } + + public Failure(Throwable e) { + + super(); + + this.exception = new IllegalStateException(e); + + } + + @Override + + public Boolean isSuccess() { + + return false; + + } + + @Override + + public Boolean isFailure() { + + return true; + + } + + @Override + + public void throwException() { + + throw new RuntimeException(this.exception); + + } + + @Override + public V get() { + throw new RuntimeException(this.exception); + } + + @Override + public Throwable getError() { + return exception; + } + } + + private static class Success<V> extends Try<V> { + + private V value; + + public Success(V value) { + + super(); + + this.value = value; + + } + + @Override + + public Boolean isSuccess() { + + return true; + + } + + @Override + + public Boolean isFailure() { + + return false; + + } + + @Override + + public void throwException() { + + //log.error("Method throwException() called on a Success instance"); + + } + + @Override + public V get() { + return value; + } + + @Override + public Throwable getError() { + return null; + } + } + + // various method such as map an flatMap + + + @Override + public String toString() { + return isSuccess() ? "true: "+get() : "false: "+ getError().getMessage(); + } +} diff --git a/archiva-modules/archiva-base/archiva-consumers/archiva-core-consumers/src/test/java/org/apache/archiva/consumers/core/repository/DaysOldRepositoryPurgeTest.java b/archiva-modules/archiva-base/archiva-consumers/archiva-core-consumers/src/test/java/org/apache/archiva/consumers/core/repository/DaysOldRepositoryPurgeTest.java index 0f41f6c32..1d4ddebcb 100644 --- a/archiva-modules/archiva-base/archiva-consumers/archiva-core-consumers/src/test/java/org/apache/archiva/consumers/core/repository/DaysOldRepositoryPurgeTest.java +++ b/archiva-modules/archiva-base/archiva-consumers/archiva-core-consumers/src/test/java/org/apache/archiva/consumers/core/repository/DaysOldRepositoryPurgeTest.java @@ -93,16 +93,20 @@ public class DaysOldRepositoryPurgeTest setLastModified( projectRoot + "/" + projectVersion + "/", OLD_TIMESTAMP ); // test listeners for the correct artifacts - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", - "maven-install-plugin", "2.2-SNAPSHOT", "maven-install-plugin-2.2-SNAPSHOT.jar" ); - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", - "maven-install-plugin", "2.2-SNAPSHOT", "maven-install-plugin-2.2-SNAPSHOT.pom" ); - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", - "maven-install-plugin", "2.2-20061118.060401-2", - "maven-install-plugin-2.2-20061118.060401-2.jar" ); - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", - "maven-install-plugin", "2.2-20061118.060401-2", - "maven-install-plugin-2.2-20061118.060401-2.pom" ); + String[] exts = {".md5",".sha1",""}; + for (int i=0; i<exts.length; i++) { + + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.apache.maven.plugins", + "maven-install-plugin", "2.2-SNAPSHOT", "maven-install-plugin-2.2-SNAPSHOT.jar"+exts[i]); + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.apache.maven.plugins", + "maven-install-plugin", "2.2-SNAPSHOT", "maven-install-plugin-2.2-SNAPSHOT.pom"+exts[i]); + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.apache.maven.plugins", + "maven-install-plugin", "2.2-20061118.060401-2", + "maven-install-plugin-2.2-20061118.060401-2.jar"+exts[i]); + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.apache.maven.plugins", + "maven-install-plugin", "2.2-20061118.060401-2", + "maven-install-plugin-2.2-20061118.060401-2.pom"+exts[i]); + } listenerControl.replay(); // Provide the metadata list @@ -178,12 +182,15 @@ public class DaysOldRepositoryPurgeTest setLastModified( projectRoot + "/" + projectVersion + "/", OLD_TIMESTAMP ); // test listeners for the correct artifacts - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", - "maven-assembly-plugin", "1.1.2-20070427.065136-1", - "maven-assembly-plugin-1.1.2-20070427.065136-1.jar" ); - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", - "maven-assembly-plugin", "1.1.2-20070427.065136-1", - "maven-assembly-plugin-1.1.2-20070427.065136-1.pom" ); + String[] exts = {".md5",".sha1",""}; + for (int i=0; i<exts.length; i++) { + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.apache.maven.plugins", + "maven-assembly-plugin", "1.1.2-20070427.065136-1", + "maven-assembly-plugin-1.1.2-20070427.065136-1.jar"+exts[i]); + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.apache.maven.plugins", + "maven-assembly-plugin", "1.1.2-20070427.065136-1", + "maven-assembly-plugin-1.1.2-20070427.065136-1.pom"+exts[i]); + } listenerControl.replay(); // Provide the metadata list @@ -274,10 +281,14 @@ public class DaysOldRepositoryPurgeTest } // test listeners for the correct artifacts - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.codehaus.plexus", "plexus-utils", - "1.4.3-20070113.163208-4", "plexus-utils-1.4.3-20070113.163208-4.jar" ); - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.codehaus.plexus", "plexus-utils", - "1.4.3-20070113.163208-4", "plexus-utils-1.4.3-20070113.163208-4.pom" ); + String[] exts = {".sha1",""}; + for (int i=0; i<exts.length; i++) { + + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.codehaus.plexus", "plexus-utils", + "1.4.3-20070113.163208-4", "plexus-utils-1.4.3-20070113.163208-4.jar"+exts[i]); + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.codehaus.plexus", "plexus-utils", + "1.4.3-20070113.163208-4", "plexus-utils-1.4.3-20070113.163208-4.pom"+exts[i]); + } listenerControl.replay(); // Provide the metadata list diff --git a/archiva-modules/archiva-base/archiva-consumers/archiva-core-consumers/src/test/java/org/apache/archiva/consumers/core/repository/RetentionCountRepositoryPurgeTest.java b/archiva-modules/archiva-base/archiva-consumers/archiva-core-consumers/src/test/java/org/apache/archiva/consumers/core/repository/RetentionCountRepositoryPurgeTest.java index 06e2108ee..009830c41 100644 --- a/archiva-modules/archiva-base/archiva-consumers/archiva-core-consumers/src/test/java/org/apache/archiva/consumers/core/repository/RetentionCountRepositoryPurgeTest.java +++ b/archiva-modules/archiva-base/archiva-consumers/archiva-core-consumers/src/test/java/org/apache/archiva/consumers/core/repository/RetentionCountRepositoryPurgeTest.java @@ -85,27 +85,31 @@ public class RetentionCountRepositoryPurgeTest String versionRoot = projectRoot + "/" + projectVersion; // test listeners for the correct artifacts - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", - "1.0RC1-20070504.153317-1", "jruby-rake-plugin-1.0RC1-20070504.153317-1.jar" ); - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", - "1.0RC1-20070504.153317-1", "jruby-rake-plugin-1.0RC1-20070504.153317-1.pom" ); - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", - "1.0RC1-20070504.153317-1", "jruby-rake-plugin-1.0RC1-20070504.153317-1-javadoc.jar" ); + String[] exts = { ".md5", ".sha1", ""}; + for (int i=0 ; i<exts.length; i++) { + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", + "1.0RC1-20070504.153317-1", "jruby-rake-plugin-1.0RC1-20070504.153317-1.jar"+exts[i]); + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", + "1.0RC1-20070504.153317-1", "jruby-rake-plugin-1.0RC1-20070504.153317-1.pom"+exts[i]); - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", - "1.0RC1-20070504.153317-1", "jruby-rake-plugin-1.0RC1-20070504.153317-1-javadoc.zip" ); + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", + "1.0RC1-20070504.160758-2", "jruby-rake-plugin-1.0RC1-20070504.160758-2.jar"+exts[i]); - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", - "1.0RC1-20070504.160758-2", "jruby-rake-plugin-1.0RC1-20070504.160758-2.jar" ); - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", - "1.0RC1-20070504.160758-2", "jruby-rake-plugin-1.0RC1-20070504.160758-2-javadoc.jar" ); + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", + "1.0RC1-20070504.160758-2", "jruby-rake-plugin-1.0RC1-20070504.160758-2.pom"+exts[i]); + } + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", + "1.0RC1-20070504.160758-2", "jruby-rake-plugin-1.0RC1-20070504.160758-2-javadoc.jar"); + + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", + "1.0RC1-20070504.160758-2", "jruby-rake-plugin-1.0RC1-20070504.160758-2-javadoc.zip"); + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", + "1.0RC1-20070504.153317-1", "jruby-rake-plugin-1.0RC1-20070504.153317-1-javadoc.jar"); - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", - "1.0RC1-20070504.160758-2", "jruby-rake-plugin-1.0RC1-20070504.160758-2-javadoc.zip" ); + listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", + "1.0RC1-20070504.153317-1", "jruby-rake-plugin-1.0RC1-20070504.153317-1-javadoc.zip"); - listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", - "1.0RC1-20070504.160758-2", "jruby-rake-plugin-1.0RC1-20070504.160758-2.pom" ); listenerControl.replay(); // Provide the metadata list @@ -182,8 +186,16 @@ public class RetentionCountRepositoryPurgeTest // test listeners for the correct artifacts listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.codehaus.castor", "castor-anttasks", + "1.1.2-20070427.065136-1", "castor-anttasks-1.1.2-20070427.065136-1.jar.md5" ); + listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.codehaus.castor", "castor-anttasks", + "1.1.2-20070427.065136-1", "castor-anttasks-1.1.2-20070427.065136-1.jar.sha1" ); + listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.codehaus.castor", "castor-anttasks", "1.1.2-20070427.065136-1", "castor-anttasks-1.1.2-20070427.065136-1.jar" ); listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.codehaus.castor", "castor-anttasks", + "1.1.2-20070427.065136-1", "castor-anttasks-1.1.2-20070427.065136-1.pom.md5" ); + listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.codehaus.castor", "castor-anttasks", + "1.1.2-20070427.065136-1", "castor-anttasks-1.1.2-20070427.065136-1.pom.sha1" ); + listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.codehaus.castor", "castor-anttasks", "1.1.2-20070427.065136-1", "castor-anttasks-1.1.2-20070427.065136-1.pom" ); listenerControl.replay(); @@ -256,9 +268,21 @@ public class RetentionCountRepositoryPurgeTest // test listeners for the correct artifacts listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", + "maven-assembly-plugin", "1.1.2-20070427.065136-1", + "maven-assembly-plugin-1.1.2-20070427.065136-1.jar.md5" ); + listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", + "maven-assembly-plugin", "1.1.2-20070427.065136-1", + "maven-assembly-plugin-1.1.2-20070427.065136-1.jar.sha1" ); + listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", "maven-assembly-plugin", "1.1.2-20070427.065136-1", "maven-assembly-plugin-1.1.2-20070427.065136-1.jar" ); listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", + "maven-assembly-plugin", "1.1.2-20070427.065136-1", + "maven-assembly-plugin-1.1.2-20070427.065136-1.pom.md5" ); + listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", + "maven-assembly-plugin", "1.1.2-20070427.065136-1", + "maven-assembly-plugin-1.1.2-20070427.065136-1.pom.sha1" ); + listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", "maven-assembly-plugin", "1.1.2-20070427.065136-1", "maven-assembly-plugin-1.1.2-20070427.065136-1.pom" ); listenerControl.replay(); diff --git a/archiva-modules/metadata/metadata-repository-api/src/main/java/org/apache/archiva/metadata/repository/storage/RepositoryPathTranslator.java b/archiva-modules/metadata/metadata-repository-api/src/main/java/org/apache/archiva/metadata/repository/storage/RepositoryPathTranslator.java index 8c7b2894f..77bcb9ec0 100644 --- a/archiva-modules/metadata/metadata-repository-api/src/main/java/org/apache/archiva/metadata/repository/storage/RepositoryPathTranslator.java +++ b/archiva-modules/metadata/metadata-repository-api/src/main/java/org/apache/archiva/metadata/repository/storage/RepositoryPathTranslator.java @@ -21,7 +21,7 @@ package org.apache.archiva.metadata.repository.storage; import org.apache.archiva.metadata.model.ArtifactMetadata; -import java.io.File; +import java.nio.file.Path; public interface RepositoryPathTranslator { @@ -31,13 +31,13 @@ public interface RepositoryPathTranslator String toPath( String namespace, String projectId ); - File toFile( File basedir, String namespace, String projectId, String projectVersion, String filename ); + Path toFile( Path basedir, String namespace, String projectId, String projectVersion, String filename ); - File toFile( File basedir, String namespace, String projectId ); + Path toFile( Path basedir, String namespace, String projectId ); - File toFile( File basedir, String namespace ); + Path toFile(Path basedir, String namespace ); - File toFile( File basedir, String namespace, String projectId, String projectVersion ); + Path toFile( Path basedir, String namespace, String projectId, String projectVersion ); ArtifactMetadata getArtifactForPath( String repoId, String relativePath ); diff --git a/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/dependency/tree/maven2/Maven3DependencyTreeBuilder.java b/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/dependency/tree/maven2/Maven3DependencyTreeBuilder.java index 24982f21d..a6624286d 100644 --- a/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/dependency/tree/maven2/Maven3DependencyTreeBuilder.java +++ b/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/dependency/tree/maven2/Maven3DependencyTreeBuilder.java @@ -62,7 +62,6 @@ import org.sonatype.aether.impl.VersionRangeResolver; import org.sonatype.aether.impl.VersionResolver; import org.sonatype.aether.impl.internal.DefaultServiceLocator; import org.sonatype.aether.impl.internal.SimpleLocalRepositoryManager; -import org.sonatype.aether.repository.LocalRepository; import org.sonatype.aether.spi.connector.RepositoryConnectorFactory; import org.sonatype.aether.util.artifact.DefaultArtifact; import org.sonatype.aether.util.graph.selector.AndDependencySelector; @@ -72,7 +71,9 @@ import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Named; -import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -294,25 +295,25 @@ public class Maven3DependencyTreeBuilder { ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repoId ); - File repoDir = new File( managedRepository.getLocation() ); - File file = pathTranslator.toFile( repoDir, projectArtifact.getGroupId(), projectArtifact.getArtifactId(), + Path repoDir = Paths.get( managedRepository.getLocation() ); + Path file = pathTranslator.toFile( repoDir, projectArtifact.getGroupId(), projectArtifact.getArtifactId(), projectArtifact.getBaseVersion(), projectArtifact.getArtifactId() + "-" + projectArtifact.getVersion() + ".pom" ); - if ( file.exists() ) + if ( Files.exists(file) ) { return managedRepository; } // try with snapshot version if ( StringUtils.endsWith( projectArtifact.getBaseVersion(), VersionUtil.SNAPSHOT ) ) { - File metadataFile = new File( file.getParent(), MetadataTools.MAVEN_METADATA ); - if ( metadataFile.exists() ) + Path metadataFile = file.getParent().resolve( MetadataTools.MAVEN_METADATA ); + if ( Files.exists(metadataFile) ) { try { - ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read( metadataFile.toPath() ); + ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read( metadataFile); int buildNumber = archivaRepositoryMetadata.getSnapshotVersion().getBuildNumber(); String timeStamp = archivaRepositoryMetadata.getSnapshotVersion().getTimestamp(); // rebuild file name with timestamped version and build number @@ -322,9 +323,9 @@ public class Maven3DependencyTreeBuilder "-" + VersionUtil.SNAPSHOT ) ).append( '-' ).append( timeStamp ).append( '-' ).append( Integer.toString( buildNumber ) ).append( ".pom" ).toString(); - File timeStampFile = new File( file.getParent(), timeStampFileName ); - log.debug( "try to find timestamped snapshot version file: {}", timeStampFile.getPath() ); - if ( timeStampFile.exists() ) + Path timeStampFile = file.getParent().resolve( timeStampFileName ); + log.debug( "try to find timestamped snapshot version file: {}", timeStampFile); + if ( Files.exists(timeStampFile) ) { return managedRepository; } diff --git a/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryPathTranslator.java b/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryPathTranslator.java index 763ba42c2..b91036809 100644 --- a/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryPathTranslator.java +++ b/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryPathTranslator.java @@ -19,17 +19,17 @@ package org.apache.archiva.metadata.repository.storage.maven2; * under the License. */ +import org.apache.archiva.common.utils.VersionUtil; import org.apache.archiva.metadata.model.ArtifactMetadata; import org.apache.archiva.metadata.model.maven2.MavenArtifactFacet; import org.apache.archiva.metadata.repository.storage.RepositoryPathTranslator; -import org.apache.archiva.common.utils.VersionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.inject.Inject; -import java.io.File; +import java.nio.file.Path; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -78,15 +78,15 @@ public class Maven2RepositoryPathTranslator } @Override - public File toFile( File basedir, String namespace, String projectId, String projectVersion, String filename ) + public Path toFile(Path basedir, String namespace, String projectId, String projectVersion, String filename ) { - return new File( basedir, toPath( namespace, projectId, projectVersion, filename ) ); + return basedir.resolve( toPath( namespace, projectId, projectVersion, filename ) ); } @Override - public File toFile( File basedir, String namespace, String projectId, String projectVersion ) + public Path toFile( Path basedir, String namespace, String projectId, String projectVersion ) { - return new File( basedir, toPath( namespace, projectId, projectVersion ) ); + return basedir.resolve( toPath( namespace, projectId, projectVersion ) ); } @Override @@ -148,15 +148,15 @@ public class Maven2RepositoryPathTranslator } @Override - public File toFile( File basedir, String namespace, String projectId ) + public Path toFile( Path basedir, String namespace, String projectId ) { - return new File( basedir, toPath( namespace, projectId ) ); + return basedir.resolve( toPath( namespace, projectId ) ); } @Override - public File toFile( File basedir, String namespace ) + public Path toFile( Path basedir, String namespace ) { - return new File( basedir, toPath( namespace ) ); + return basedir.resolve( toPath( namespace ) ); } private String formatAsDirectory( String directory ) diff --git a/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryStorage.java b/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryStorage.java index e1f45ced3..31e8c674e 100644 --- a/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryStorage.java +++ b/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryStorage.java @@ -30,6 +30,7 @@ import org.apache.archiva.admin.model.proxyconnector.ProxyConnectorAdmin; import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin; import org.apache.archiva.checksum.ChecksumAlgorithm; import org.apache.archiva.checksum.ChecksummedFile; +import org.apache.archiva.common.Try; import org.apache.archiva.common.utils.VersionUtil; import org.apache.archiva.maven2.metadata.MavenMetadataReader; import org.apache.archiva.metadata.model.ArtifactMetadata; @@ -37,13 +38,7 @@ import org.apache.archiva.metadata.model.ProjectMetadata; import org.apache.archiva.metadata.model.ProjectVersionMetadata; import org.apache.archiva.metadata.model.facets.RepositoryProblemFacet; import org.apache.archiva.metadata.repository.filter.Filter; -import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest; -import org.apache.archiva.metadata.repository.storage.RelocationException; -import org.apache.archiva.metadata.repository.storage.RepositoryPathTranslator; -import org.apache.archiva.metadata.repository.storage.RepositoryStorage; -import org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataInvalidException; -import org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataNotFoundException; -import org.apache.archiva.metadata.repository.storage.RepositoryStorageRuntimeException; +import org.apache.archiva.metadata.repository.storage.*; import org.apache.archiva.model.ArchivaRepositoryMetadata; import org.apache.archiva.model.ArtifactReference; import org.apache.archiva.model.SnapshotVersion; @@ -56,22 +51,8 @@ import org.apache.archiva.repository.layout.LayoutException; import org.apache.archiva.xml.XMLException; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; -import org.apache.maven.model.CiManagement; -import org.apache.maven.model.Dependency; -import org.apache.maven.model.DistributionManagement; -import org.apache.maven.model.IssueManagement; -import org.apache.maven.model.License; -import org.apache.maven.model.MailingList; -import org.apache.maven.model.Model; -import org.apache.maven.model.Organization; -import org.apache.maven.model.Relocation; -import org.apache.maven.model.Scm; -import org.apache.maven.model.building.DefaultModelBuilderFactory; -import org.apache.maven.model.building.DefaultModelBuildingRequest; -import org.apache.maven.model.building.ModelBuilder; -import org.apache.maven.model.building.ModelBuildingException; -import org.apache.maven.model.building.ModelBuildingRequest; -import org.apache.maven.model.building.ModelProblem; +import org.apache.maven.model.*; +import org.apache.maven.model.building.*; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.slf4j.Logger; @@ -82,22 +63,20 @@ import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Named; -import java.io.File; import java.io.FileNotFoundException; -import java.io.FilenameFilter; import java.io.IOException; import java.io.Reader; import java.nio.charset.Charset; import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.nio.file.Paths; +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +// import java.io.FileNotFoundException; /** * <p> @@ -200,15 +179,15 @@ public class Maven2RepositoryStorage } } } - File basedir = new File( managedRepository.getLocation() ); + Path basedir = Paths.get( managedRepository.getLocation() ); if ( VersionUtil.isSnapshot( artifactVersion ) ) { - File metadataFile = pathTranslator.toFile( basedir, readMetadataRequest.getNamespace(), + Path metadataFile = pathTranslator.toFile( basedir, readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(), artifactVersion, METADATA_FILENAME ); try { - ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile.toPath() ); + ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile ); // re-adjust to timestamp if present, otherwise retain the original -SNAPSHOT filename SnapshotVersion snapshotVersion = metadata.getSnapshotVersion(); @@ -229,15 +208,15 @@ public class Maven2RepositoryStorage // TODO: won't work well with some other layouts, might need to convert artifact parts to ID by path translator String id = readMetadataRequest.getProjectId() + "-" + artifactVersion + ".pom"; - File file = + Path file = pathTranslator.toFile( basedir, readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(), readMetadataRequest.getProjectVersion(), id ); - if ( !file.exists() ) + if ( !Files.exists(file) ) { // metadata could not be resolved throw new RepositoryStorageMetadataNotFoundException( - "The artifact's POM file '" + file.getAbsolutePath() + "' was missing" ); + "The artifact's POM file '" + file.toAbsolutePath() + "' was missing" ); } // TODO: this is a workaround until we can properly resolve using proxies as well - this doesn't cache @@ -278,7 +257,7 @@ public class Maven2RepositoryStorage } ModelBuildingRequest req = - new DefaultModelBuildingRequest().setProcessPlugins( false ).setPomFile( file ).setTwoPhaseBuilding( + new DefaultModelBuildingRequest().setProcessPlugins( false ).setPomFile( file.toFile() ).setTwoPhaseBuilding( false ).setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL ); //MRM-1607. olamy this will resolve jdk profiles on the current running archiva jvm @@ -306,7 +285,9 @@ public class Maven2RepositoryStorage // olamy really hackhish but fail with java profile so use error message // || ( StringUtils.startsWith( problem.getMessage(), "Failed to determine Java version for profile" ) ) // but setTwoPhaseBuilding(true) fix that - if ( ( problem.getException() instanceof FileNotFoundException && e.getModelId() != null && + if ( ( (problem.getException() instanceof FileNotFoundException + || problem.getException() instanceof NoSuchFileException + ) && e.getModelId() != null && !e.getModelId().equals( problem.getModelId() ) ) ) { LOGGER.warn( "The artifact's parent POM file '{}' cannot be resolved. " @@ -511,35 +492,35 @@ public class Maven2RepositoryStorage public Collection<String> listRootNamespaces( String repoId, Filter<String> filter ) throws RepositoryStorageRuntimeException { - File dir = getRepositoryBasedir( repoId ); + Path dir = getRepositoryBasedir( repoId ); return getSortedFiles( dir, filter ); } - private static Collection<String> getSortedFiles( File dir, Filter<String> filter ) + private static Collection<String> getSortedFiles( Path dir, Filter<String> filter ) { - List<String> fileNames; - String[] files = dir.list( new DirectoryFilter( filter ) ); - if ( files != null ) - { - fileNames = new ArrayList<>( Arrays.asList( files ) ); - Collections.sort( fileNames ); - } - else - { - fileNames = Collections.emptyList(); + + try(Stream<Path> stream = Files.list(dir)) { + final Predicate<Path> dFilter = new DirectoryFilter( filter ); + return stream.filter(Files::isDirectory) + .filter(dFilter) + .map(path -> path.getFileName().toString()) + .sorted().collect(Collectors.toList()); + + } catch (IOException e) { + LOGGER.error("Could not read directory list {}: {}", dir, e.getMessage(),e); + return Collections.emptyList(); } - return fileNames; } - private File getRepositoryBasedir( String repoId ) + private Path getRepositoryBasedir( String repoId ) throws RepositoryStorageRuntimeException { try { ManagedRepository repositoryConfiguration = managedRepositoryAdmin.getManagedRepository( repoId ); - return new File( repositoryConfiguration.getLocation() ); + return Paths.get( repositoryConfiguration.getLocation() ); } catch ( RepositoryAdminException e ) { @@ -551,47 +532,39 @@ public class Maven2RepositoryStorage public Collection<String> listNamespaces( String repoId, String namespace, Filter<String> filter ) throws RepositoryStorageRuntimeException { - File dir = pathTranslator.toFile( getRepositoryBasedir( repoId ), namespace ); - + Path dir = pathTranslator.toFile( getRepositoryBasedir( repoId ), namespace ); + if (!(Files.exists(dir) && Files.isDirectory(dir))) { + return Collections.emptyList(); + } // scan all the directories which are potential namespaces. Any directories known to be projects are excluded - List<String> namespaces = new ArrayList<>(); - File[] files = dir.listFiles( new DirectoryFilter( filter ) ); - if ( files != null ) - { - for ( File file : files ) - { - if ( !isProject( file, filter ) ) - { - namespaces.add( file.getName() ); - } - } + Predicate<Path> dFilter = new DirectoryFilter(filter); + try(Stream<Path> stream = Files.list(dir)) { + return stream.filter(dFilter).filter(path -> !isProject(path, filter)).map(path -> path.getFileName().toString()) + .sorted().collect(Collectors.toList()); + } catch (IOException e) { + LOGGER.error("Could not read directory {}: {}", dir, e.getMessage(), e); + return Collections.emptyList(); } - Collections.sort( namespaces ); - return namespaces; } @Override public Collection<String> listProjects( String repoId, String namespace, Filter<String> filter ) throws RepositoryStorageRuntimeException { - File dir = pathTranslator.toFile( getRepositoryBasedir( repoId ), namespace ); - + Path dir = pathTranslator.toFile( getRepositoryBasedir( repoId ), namespace ); + if (!(Files.exists(dir) && Files.isDirectory(dir))) { + return Collections.emptyList(); + } // scan all directories in the namespace, and only include those that are known to be projects - List<String> projects = new ArrayList<>(); - - File[] files = dir.listFiles( new DirectoryFilter( filter ) ); - if ( files != null ) - { - for ( File file : files ) - { - if ( isProject( file, filter ) ) - { - projects.add( file.getName() ); - } - } + final Predicate<Path> dFilter = new DirectoryFilter(filter); + try(Stream<Path> stream = Files.list(dir)) { + return stream.filter(dFilter).filter(path -> isProject(path, filter)).map(path -> path.getFileName().toString()) + .sorted().collect(Collectors.toList()); + } catch (IOException e) { + LOGGER.error("Could not read directory {}: {}", dir, e.getMessage(), e); + return Collections.emptyList(); } - Collections.sort( projects ); - return projects; + } @Override @@ -599,7 +572,10 @@ public class Maven2RepositoryStorage Filter<String> filter ) throws RepositoryStorageRuntimeException { - File dir = pathTranslator.toFile( getRepositoryBasedir( repoId ), namespace, projectId ); + Path dir = pathTranslator.toFile( getRepositoryBasedir( repoId ), namespace, projectId ); + if (!(Files.exists(dir) && Files.isDirectory(dir))) { + return Collections.emptyList(); + } // all directories in a project directory can be considered a version return getSortedFiles( dir, filter ); @@ -609,38 +585,44 @@ public class Maven2RepositoryStorage public Collection<ArtifactMetadata> readArtifactsMetadata( ReadMetadataRequest readMetadataRequest ) throws RepositoryStorageRuntimeException { - File dir = pathTranslator.toFile( getRepositoryBasedir( readMetadataRequest.getRepositoryId() ), + Path dir = pathTranslator.toFile( getRepositoryBasedir( readMetadataRequest.getRepositoryId() ), readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(), readMetadataRequest.getProjectVersion() ); + if (!(Files.exists(dir) && Files.isDirectory(dir))) { + return Collections.emptyList(); + } // all files that are not metadata and not a checksum / signature are considered artifacts - File[] files = dir.listFiles( new ArtifactDirectoryFilter( readMetadataRequest.getFilter() ) ); - - List<ArtifactMetadata> artifacts = new ArrayList<>(); - if ( files != null ) - { - int errorCount=0; - for ( File file : files ) - { - try { - ArtifactMetadata metadata = - getArtifactFromFile(readMetadataRequest.getRepositoryId(), readMetadataRequest.getNamespace(), + final Predicate<Path> dFilter = new ArtifactDirectoryFilter(readMetadataRequest.getFilter()); + try(Stream<Path> stream = Files.list(dir)) { + // Returns a map TRUE -> (success values), FALSE -> (Exceptions) + Map<Boolean, List<Try<ArtifactMetadata>>> result = stream.filter(dFilter).map(path -> { + try { + return Try.success(getArtifactFromFile(readMetadataRequest.getRepositoryId(), readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(), readMetadataRequest.getProjectVersion(), - file); - artifacts.add(metadata); - } catch (Exception ex) { - LOGGER.error("Error while retrieving metadata of file {} (Project: {}, Repository: {}): {}", - file.getName(), readMetadataRequest.getProjectId(), readMetadataRequest.getRepositoryId(), - ex.getMessage()); - errorCount++; - } - } - // We throw only an error, if the number of errors equals the number of files - if (errorCount>0 && errorCount==files.length) { + path)); + } catch (Exception e) { + LOGGER.debug("Could not create metadata for {}: {}", path, e.getMessage(), e); + return Try.<ArtifactMetadata>failure(e); + } + } + ).collect(Collectors.groupingBy(Try::isSuccess)); + if (result.containsKey(Boolean.FALSE) && result.get(Boolean.FALSE).size()>0 && (!result.containsKey(Boolean.TRUE) || result.get(Boolean.TRUE).size()==0)) { + LOGGER.error("Could not get artifact metadata. Directory: {}. Number of errors {}.", dir, result.get(Boolean.FALSE).size()); + Try<ArtifactMetadata> failure = result.get(Boolean.FALSE).get(0); + LOGGER.error("Sample exception {}", failure.getError().getMessage(), failure.getError()); throw new RepositoryStorageRuntimeException(readMetadataRequest.getRepositoryId(), "Could not retrieve metadata of the files"); + } else { + if (!result.containsKey(Boolean.TRUE) || result.get(Boolean.TRUE) == null) { + return Collections.emptyList(); + } + return result.get(Boolean.TRUE).stream().map(tr -> tr.get()).collect(Collectors.toList()); } + } catch (IOException e) { + LOGGER.error("Could not read directory {}: {}", dir, e.getMessage(), e); } - return artifacts; + return Collections.emptyList(); + } @Override @@ -649,16 +631,19 @@ public class Maven2RepositoryStorage { ArtifactMetadata metadata = pathTranslator.getArtifactForPath( repoId, path ); - populateArtifactMetadataFromFile( metadata, new File( getRepositoryBasedir( repoId ), path ) ); + try { + populateArtifactMetadataFromFile( metadata, getRepositoryBasedir( repoId ).resolve( path ) ); + } catch (IOException e) { + throw new RepositoryStorageRuntimeException(repoId, "Error during metadata retrieval of "+path+" :"+e.getMessage(), e); + } return metadata; } private ArtifactMetadata getArtifactFromFile( String repoId, String namespace, String projectId, - String projectVersion, File file ) - { + String projectVersion, Path file ) throws IOException { ArtifactMetadata metadata = - pathTranslator.getArtifactFromId( repoId, namespace, projectId, projectVersion, file.getName() ); + pathTranslator.getArtifactFromId( repoId, namespace, projectId, projectVersion, file.getFileName().toString() ); populateArtifactMetadataFromFile( metadata, file ); @@ -810,17 +795,17 @@ public class Maven2RepositoryStorage if ( StringUtils.endsWith( artifactReference.getVersion(), VersionUtil.SNAPSHOT ) ) { // read maven metadata to get last timestamp - File metadataDir = new File( managedRepositoryContent.getRepoRoot(), filePath ).getParentFile(); - if ( !metadataDir.exists() ) + Path metadataDir = Paths.get( managedRepositoryContent.getRepoRoot(), filePath ).getParent(); + if ( !Files.exists(metadataDir) ) { return filePath; } - File metadataFile = new File( metadataDir, METADATA_FILENAME ); - if ( !metadataFile.exists() ) + Path metadataFile = metadataDir.resolve( METADATA_FILENAME ); + if ( !Files.exists(metadataFile) ) { return filePath; } - ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read( metadataFile.toPath() ); + ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read( metadataFile ); int buildNumber = archivaRepositoryMetadata.getSnapshotVersion().getBuildNumber(); String timestamp = archivaRepositoryMetadata.getSnapshotVersion().getTimestamp(); @@ -879,11 +864,10 @@ public class Maven2RepositoryStorage return joinedString; } - private static void populateArtifactMetadataFromFile( ArtifactMetadata metadata, File file ) - { + private static void populateArtifactMetadataFromFile( ArtifactMetadata metadata, Path file ) throws IOException { metadata.setWhenGathered( new Date() ); - metadata.setFileLastModified( file.lastModified() ); - ChecksummedFile checksummedFile = new ChecksummedFile( file.toPath() ); + metadata.setFileLastModified( Files.getLastModifiedTime(file).toMillis() ); + ChecksummedFile checksummedFile = new ChecksummedFile( file ); try { metadata.setMd5( checksummedFile.calculateChecksum( ChecksumAlgorithm.MD5 ) ); @@ -900,27 +884,26 @@ public class Maven2RepositoryStorage { LOGGER.error( "Unable to checksum file {}: {},SHA1", file, e.getMessage() ); } - metadata.setSize( file.length() ); + metadata.setSize( Files.size(file) ); } - private boolean isProject( File dir, Filter<String> filter ) + private boolean isProject( Path dir, Filter<String> filter ) { // scan directories for a valid project version subdirectory, meaning this must be a project directory - File[] files = dir.listFiles( new DirectoryFilter( filter ) ); - if ( files != null ) - { - for ( File file : files ) - { - if ( isProjectVersion( file ) ) - { - return true; - } + final Predicate<Path> dFilter = new DirectoryFilter(filter); + try(Stream<Path> stream = Files.list(dir)) { + boolean projFound = stream.filter(dFilter) + .anyMatch(path -> isProjectVersion(path)); + if (projFound) { + return true; } + } catch (IOException e) { + LOGGER.error("Could not read directory list {}: {}", dir, e.getMessage(), e); } // if a metadata file is present, check if this is the "artifactId" directory, marking it as a project ArchivaRepositoryMetadata metadata = readMetadata( dir ); - if ( metadata != null && dir.getName().equals( metadata.getArtifactId() ) ) + if ( metadata != null && dir.getFileName().toString().equals( metadata.getArtifactId() ) ) { return true; } @@ -928,25 +911,29 @@ public class Maven2RepositoryStorage return false; } - private boolean isProjectVersion( File dir ) + private boolean isProjectVersion( Path dir ) { - final String artifactId = dir.getParentFile().getName(); - final String projectVersion = dir.getName(); + final String artifactId = dir.getParent().getFileName().toString(); + final String projectVersion = dir.getFileName().toString(); // check if there is a POM artifact file to ensure it is a version directory - File[] files; + + Predicate<Path> filter; if ( VersionUtil.isSnapshot( projectVersion ) ) { - files = dir.listFiles( new PomFilenameFilter( artifactId, projectVersion ) ); + filter = new PomFilenameFilter(artifactId, projectVersion); } else { final String pomFile = artifactId + "-" + projectVersion + ".pom"; - files = dir.listFiles( new PomFileFilter( pomFile ) ); + filter = new PomFileFilter(pomFile); } - if ( files != null && files.length > 0 ) - { - return true; + try(Stream<Path> stream = Files.list(dir)) { + if (stream.filter(Files::isRegularFile).anyMatch(filter)){ + return true; + } + } catch (IOException e) { + LOGGER.error("Could not list directory {}: {}", dir, e.getMessage(), e); } // if a metadata file is present, check if this is the "version" directory, marking it as a project version @@ -959,15 +946,15 @@ public class Maven2RepositoryStorage return false; } - private ArchivaRepositoryMetadata readMetadata( File directory ) + private ArchivaRepositoryMetadata readMetadata( Path directory ) { ArchivaRepositoryMetadata metadata = null; - File metadataFile = new File( directory, METADATA_FILENAME ); - if ( metadataFile.exists() ) + Path metadataFile = directory.resolve( METADATA_FILENAME ); + if ( Files.exists(metadataFile) ) { try { - metadata = MavenMetadataReader.read( metadataFile.toPath() ); + metadata = MavenMetadataReader.read( metadataFile ); } catch ( XMLException e ) { @@ -978,7 +965,7 @@ public class Maven2RepositoryStorage } private static class DirectoryFilter - implements FilenameFilter + implements Predicate<Path> { private final Filter<String> filter; @@ -988,8 +975,9 @@ public class Maven2RepositoryStorage } @Override - public boolean accept( File dir, String name ) + public boolean test( Path dir ) { + final String name = dir.getFileName().toString(); if ( !filter.accept( name ) ) { return false; @@ -998,7 +986,7 @@ public class Maven2RepositoryStorage { return false; } - else if ( !new File( dir, name ).isDirectory() ) + else if ( !Files.isDirectory(dir)) { return false; } @@ -1007,7 +995,7 @@ public class Maven2RepositoryStorage } private static class ArtifactDirectoryFilter - implements FilenameFilter + implements Predicate<Path> { private final Filter<String> filter; @@ -1017,8 +1005,9 @@ public class Maven2RepositoryStorage } @Override - public boolean accept( File dir, String name ) + public boolean test( Path dir ) { + final String name = dir.getFileName().toString(); // TODO compare to logic in maven-repository-layer if ( !filter.accept( name ) ) { @@ -1036,7 +1025,7 @@ public class Maven2RepositoryStorage { return false; } - else if ( new File( dir, name ).isDirectory() ) + else if ( Files.isDirectory(dir) ) { return false; } @@ -1053,7 +1042,7 @@ public class Maven2RepositoryStorage private static final class PomFilenameFilter - implements FilenameFilter + implements Predicate<Path> { private final String artifactId, projectVersion; @@ -1065,8 +1054,9 @@ public class Maven2RepositoryStorage } @Override - public boolean accept( File dir, String name ) + public boolean test( Path dir ) { + final String name = dir.getFileName().toString(); if ( name.startsWith( artifactId + "-" ) && name.endsWith( ".pom" ) ) { String v = name.substring( artifactId.length() + 1, name.length() - 4 ); @@ -1078,10 +1068,11 @@ public class Maven2RepositoryStorage } return false; } + } private static class PomFileFilter - implements FilenameFilter + implements Predicate<Path> { private final String pomFile; @@ -1091,9 +1082,9 @@ public class Maven2RepositoryStorage } @Override - public boolean accept( File dir, String name ) + public boolean test( Path dir ) { - return pomFile.equals( name ); + return pomFile.equals( dir.getFileName().toString()); } } diff --git a/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/metadata/repository/storage/maven2/RepositoryModelResolver.java b/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/metadata/repository/storage/maven2/RepositoryModelResolver.java index cd6cc5514..b769fb261 100644 --- a/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/metadata/repository/storage/maven2/RepositoryModelResolver.java +++ b/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/metadata/repository/storage/maven2/RepositoryModelResolver.java @@ -31,7 +31,6 @@ import org.apache.archiva.proxy.common.WagonFactory; import org.apache.archiva.proxy.common.WagonFactoryException; import org.apache.archiva.proxy.common.WagonFactoryRequest; import org.apache.archiva.xml.XMLException; -import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.model.Repository; import org.apache.maven.model.building.FileModelSource; @@ -50,16 +49,17 @@ import org.apache.maven.wagon.proxy.ProxyInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; import java.io.IOException; import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.List; import java.util.Map; public class RepositoryModelResolver implements ModelResolver { - private File basedir; + private Path basedir; private RepositoryPathTranslator pathTranslator; @@ -78,7 +78,7 @@ public class RepositoryModelResolver private ManagedRepository managedRepository; - public RepositoryModelResolver( File basedir, RepositoryPathTranslator pathTranslator ) + public RepositoryModelResolver( Path basedir, RepositoryPathTranslator pathTranslator ) { this.basedir = basedir; @@ -89,7 +89,7 @@ public class RepositoryModelResolver WagonFactory wagonFactory, List<RemoteRepository> remoteRepositories, Map<String, NetworkProxy> networkProxiesMap, ManagedRepository targetRepository ) { - this( new File( managedRepository.getLocation() ), pathTranslator ); + this( Paths.get( managedRepository.getLocation() ), pathTranslator ); this.managedRepository = managedRepository; @@ -109,9 +109,9 @@ public class RepositoryModelResolver String filename = artifactId + "-" + version + ".pom"; // TODO: we need to convert 1.0-20091120.112233-1 type paths to baseVersion for the below call - add a test - File model = pathTranslator.toFile( basedir, groupId, artifactId, version, filename ); + Path model = pathTranslator.toFile( basedir, groupId, artifactId, version, filename ); - if ( !model.exists() ) + if ( !Files.exists(model) ) { /** * @@ -119,10 +119,10 @@ public class RepositoryModelResolver // is a SNAPSHOT ? so we can try to find locally before asking remote repositories. if ( StringUtils.contains( version, VersionUtil.SNAPSHOT ) ) { - File localSnapshotModel = findTimeStampedSnapshotPom( groupId, artifactId, version, model.getParent() ); + Path localSnapshotModel = findTimeStampedSnapshotPom( groupId, artifactId, version, model.getParent().toString() ); if ( localSnapshotModel != null ) { - return new FileModelSource( localSnapshotModel ); + return new FileModelSource( localSnapshotModel.toFile() ); } } @@ -132,10 +132,10 @@ public class RepositoryModelResolver try { boolean success = getModelFromProxy( remoteRepository, groupId, artifactId, version, filename ); - if ( success && model.exists() ) + if ( success && Files.exists(model) ) { log.info( "Model '{}' successfully retrieved from remote repository '{}'", - model.getAbsolutePath(), remoteRepository.getId() ); + model.toAbsolutePath(), remoteRepository.getId() ); break; } } @@ -143,33 +143,33 @@ public class RepositoryModelResolver { log.info( "An exception was caught while attempting to retrieve model '{}' from remote repository '{}'.Reason:{}", - model.getAbsolutePath(), remoteRepository.getId(), e.getMessage() ); + model.toAbsolutePath(), remoteRepository.getId(), e.getMessage() ); } catch ( Exception e ) { log.warn( "An exception was caught while attempting to retrieve model '{}' from remote repository '{}'.Reason:{}", - model.getAbsolutePath(), remoteRepository.getId(), e.getMessage() ); + model.toAbsolutePath(), remoteRepository.getId(), e.getMessage() ); continue; } } } - return new FileModelSource( model ); + return new FileModelSource( model.toFile() ); } - protected File findTimeStampedSnapshotPom( String groupId, String artifactId, String version, + protected Path findTimeStampedSnapshotPom( String groupId, String artifactId, String version, String parentDirectory ) { // reading metadata if there - File mavenMetadata = new File( parentDirectory, METADATA_FILENAME ); - if ( mavenMetadata.exists() ) + Path mavenMetadata = Paths.get( parentDirectory, METADATA_FILENAME ); + if ( Files.exists(mavenMetadata) ) { try { - ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read( mavenMetadata.toPath() ); + ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read( mavenMetadata); SnapshotVersion snapshotVersion = archivaRepositoryMetadata.getSnapshotVersion(); if ( snapshotVersion != null ) { @@ -183,9 +183,9 @@ public class RepositoryModelResolver log.debug( "use snapshot path {} for maven coordinate {}:{}:{}", snapshotPath, groupId, artifactId, version ); - File model = new File( basedir, snapshotPath ); + Path model = basedir.resolve( snapshotPath ); //model = pathTranslator.toFile( basedir, groupId, artifactId, lastVersion, filename ); - if ( model.exists() ) + if ( Files.exists(model) ) { return model; } @@ -193,7 +193,7 @@ public class RepositoryModelResolver } catch ( XMLException e ) { - log.warn( "fail to read {}, {}", mavenMetadata.getAbsolutePath(), e.getCause() ); + log.warn( "fail to read {}, {}", mavenMetadata.toAbsolutePath(), e.getCause() ); } } @@ -224,13 +224,13 @@ public class RepositoryModelResolver XMLException, IOException { boolean success = false; - File tmpMd5 = null; - File tmpSha1 = null; - File tmpResource = null; + Path tmpMd5 = null; + Path tmpSha1 = null; + Path tmpResource = null; String artifactPath = pathTranslator.toPath( groupId, artifactId, version, filename ); - File resource = new File( targetRepository.getLocation(), artifactPath ); + Path resource = Paths.get( targetRepository.getLocation(), artifactPath ); - File workingDirectory = createWorkingDirectory( targetRepository.getLocation() ); + Path workingDirectory = createWorkingDirectory( targetRepository.getLocation() ); try { Wagon wagon = null; @@ -252,21 +252,21 @@ public class RepositoryModelResolver boolean connected = connectToRepository( wagon, remoteRepository ); if ( connected ) { - tmpResource = new File( workingDirectory, filename ); + tmpResource = workingDirectory.resolve( filename ); if ( VersionUtil.isSnapshot( version ) ) { // get the metadata first! - File tmpMetadataResource = new File( workingDirectory, METADATA_FILENAME ); + Path tmpMetadataResource = workingDirectory.resolve( METADATA_FILENAME ); String metadataPath = StringUtils.substringBeforeLast( artifactPath, "/" ) + "/" + METADATA_FILENAME; - wagon.get( addParameters( metadataPath, remoteRepository ), tmpMetadataResource ); + wagon.get( addParameters( metadataPath, remoteRepository ), tmpMetadataResource.toFile() ); log.debug( "Successfully downloaded metadata." ); - ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( tmpMetadataResource.toPath() ); + ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( tmpMetadataResource ); // re-adjust to timestamp if present, otherwise retain the original -SNAPSHOT filename SnapshotVersion snapshotVersion = metadata.getSnapshotVersion(); @@ -288,7 +288,7 @@ public class RepositoryModelResolver log.info( "Retrieving {} from {}", artifactPath, remoteRepository.getName() ); - wagon.get( addParameters( artifactPath, remoteRepository ), tmpResource ); + wagon.get( addParameters( artifactPath, remoteRepository ), tmpResource.toFile() ); log.debug( "Downloaded successfully." ); @@ -315,9 +315,9 @@ public class RepositoryModelResolver if ( resource != null ) { - synchronized ( resource.getAbsolutePath().intern() ) + synchronized ( resource.toAbsolutePath().toString().intern() ) { - File directory = resource.getParentFile(); + Path directory = resource.getParent(); moveFileIfExists( tmpMd5, directory ); moveFileIfExists( tmpSha1, directory ); moveFileIfExists( tmpResource, directory ); @@ -327,7 +327,7 @@ public class RepositoryModelResolver } finally { - FileUtils.deleteQuietly( workingDirectory ); + org.apache.archiva.common.utils.FileUtils.deleteQuietly( workingDirectory ); } // do we still need to execute the consumers? @@ -426,17 +426,17 @@ public class RepositoryModelResolver * @throws TransferFailedException * @throws ResourceDoesNotExistException */ - private File transferChecksum( final Wagon wagon, final RemoteRepository remoteRepository, - final String remotePath, final File resource, - final File workingDir, final String ext ) + private Path transferChecksum( final Wagon wagon, final RemoteRepository remoteRepository, + final String remotePath, final Path resource, + final Path workingDir, final String ext ) throws AuthorizationException, TransferFailedException, ResourceDoesNotExistException { - File destFile = new File( workingDir, resource.getName() + ext ); + Path destFile = workingDir.resolve( resource.getFileName() + ext ); String remoteChecksumPath = remotePath + ext; log.info( "Retrieving {} from {}", remoteChecksumPath, remoteRepository.getName() ); - wagon.get( addParameters( remoteChecksumPath, remoteRepository ), destFile ); + wagon.get( addParameters( remoteChecksumPath, remoteRepository ), destFile.toFile() ); log.debug( "Downloaded successfully." ); @@ -450,49 +450,45 @@ public class RepositoryModelResolver return protocol; } - private File createWorkingDirectory( String targetRepository ) + private Path createWorkingDirectory( String targetRepository ) throws IOException { - return Files.createTempDirectory( "temp" ).toFile(); + return Files.createTempDirectory( "temp" ); } - private void moveFileIfExists( File fileToMove, File directory ) + private void moveFileIfExists( Path fileToMove, Path directory ) { - if ( fileToMove != null && fileToMove.exists() ) + if ( fileToMove != null && Files.exists(fileToMove) ) { - File newLocation = new File( directory, fileToMove.getName() ); - if ( newLocation.exists() && !newLocation.delete() ) - { + Path newLocation = directory.resolve( fileToMove.getFileName() ); + try { + Files.deleteIfExists(newLocation); + } catch (IOException e) { throw new RuntimeException( - "Unable to overwrite existing target file: " + newLocation.getAbsolutePath() ); + "Unable to overwrite existing target file: " + newLocation.toAbsolutePath(), e ); } - newLocation.getParentFile().mkdirs(); - if ( !fileToMove.renameTo( newLocation ) ) - { - log.warn( "Unable to rename tmp file to its final name... resorting to copy command." ); - - try - { - FileUtils.copyFile( fileToMove, newLocation ); - } - catch ( IOException e ) - { - if ( newLocation.exists() ) - { + try { + Files.createDirectories(newLocation.getParent()); + } catch (IOException e) { + e.printStackTrace(); + } + try { + Files.move(fileToMove, newLocation ); + } catch (IOException e) { + try { + Files.copy(fileToMove, newLocation); + } catch (IOException e1) { + if (Files.exists(newLocation)) { log.error( "Tried to copy file {} to {} but file with this name already exists.", - fileToMove.getName(), newLocation.getAbsolutePath() ); - } - else - { + fileToMove.getFileName(), newLocation.toAbsolutePath() ); + } else { throw new RuntimeException( - "Cannot copy tmp file " + fileToMove.getAbsolutePath() + " to its final location", e ); + "Cannot copy tmp file " + fileToMove.toAbsolutePath() + " to its final location", e ); } } - finally - { - FileUtils.deleteQuietly( fileToMove ); - } + } finally { + org.apache.archiva.common.utils.FileUtils.deleteQuietly(fileToMove); } } } diff --git a/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/repository/content/maven2/ManagedDefaultRepositoryContent.java b/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/repository/content/maven2/ManagedDefaultRepositoryContent.java index 03bdfe0d9..1fb858d91 100644 --- a/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/repository/content/maven2/ManagedDefaultRepositoryContent.java +++ b/archiva-modules/plugins/maven2-repository/src/main/java/org/apache/archiva/repository/content/maven2/ManagedDefaultRepositoryContent.java @@ -20,7 +20,6 @@ package org.apache.archiva.repository.content.maven2; */ import org.apache.archiva.admin.model.beans.ManagedRepository; -import org.apache.archiva.common.utils.PathUtil; import org.apache.archiva.configuration.FileTypes; import org.apache.archiva.metadata.repository.storage.maven2.DefaultArtifactMappingProvider; import org.apache.archiva.model.ArchivaArtifact; @@ -31,21 +30,22 @@ import org.apache.archiva.repository.ContentNotFoundException; import org.apache.archiva.repository.ManagedRepositoryContent; import org.apache.archiva.repository.RepositoryException; import org.apache.archiva.repository.layout.LayoutException; -import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import javax.inject.Inject; import javax.inject.Named; -import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.HashSet; +import java.util.Objects; import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; /** * ManagedDefaultRepositoryContent @@ -72,33 +72,33 @@ public class ManagedDefaultRepositoryContent public void deleteVersion( VersionedReference reference ) { String path = toMetadataPath( reference ); - File projectPath = new File( getRepoRoot(), path ); + Path projectPath = Paths.get( getRepoRoot(), path ); - File projectDir = projectPath.getParentFile(); - if ( projectDir.exists() && projectDir.isDirectory() ) + Path projectDir = projectPath.getParent(); + if ( Files.exists(projectDir) && Files.isDirectory(projectDir) ) { - FileUtils.deleteQuietly( projectDir ); + org.apache.archiva.common.utils.FileUtils.deleteQuietly( projectDir ); } } @Override public void deleteProject( String namespace, String projectId ) - throws RepositoryException, ContentNotFoundException + throws RepositoryException { ArtifactReference artifactReference = new ArtifactReference(); artifactReference.setGroupId( namespace ); artifactReference.setArtifactId( projectId ); String path = toPath( artifactReference ); - File directory = new File( getRepoRoot(), path ); - if ( !directory.exists() ) + Path directory = Paths.get( getRepoRoot(), path ); + if ( !Files.exists(directory) ) { throw new ContentNotFoundException( "cannot found project " + namespace + ":" + projectId ); } - if ( directory.isDirectory() ) + if ( Files.isDirectory(directory) ) { try { - FileUtils.deleteDirectory( directory ); + org.apache.archiva.common.utils.FileUtils.deleteDirectory( directory ); } catch ( IOException e ) { @@ -116,25 +116,25 @@ public class ManagedDefaultRepositoryContent public void deleteArtifact( ArtifactReference artifactReference ) { String path = toPath( artifactReference ); - File filePath = new File( getRepoRoot(), path ); + Path filePath = Paths.get( getRepoRoot(), path ); - if ( filePath.exists() ) + if ( Files.exists(filePath) ) { - FileUtils.deleteQuietly( filePath ); + org.apache.archiva.common.utils.FileUtils.deleteQuietly( filePath ); } - File filePathmd5 = new File( getRepoRoot(), path + ".md5" ); + Path filePathmd5 = Paths.get( getRepoRoot(), path + ".md5" ); - if ( filePathmd5.exists() ) + if ( Files.exists(filePathmd5) ) { - FileUtils.deleteQuietly( filePathmd5 ); + org.apache.archiva.common.utils.FileUtils.deleteQuietly( filePathmd5 ); } - File filePathsha1 = new File( getRepoRoot(), path + ".sha1" ); + Path filePathsha1 = Paths.get( getRepoRoot(), path + ".sha1" ); - if ( filePathsha1.exists() ) + if ( Files.exists(filePathsha1) ) { - FileUtils.deleteQuietly( filePathsha1 ); + org.apache.archiva.common.utils.FileUtils.deleteQuietly( filePathsha1 ); } } @@ -145,17 +145,17 @@ public class ManagedDefaultRepositoryContent String path = StringUtils.replaceChars( groupId, '.', '/' ); - File directory = new File( getRepoRoot(), path ); + Path directory = Paths.get( getRepoRoot(), path ); - if ( directory.exists() ) + if ( Files.exists(directory) ) { try { - FileUtils.deleteDirectory( directory ); + org.apache.archiva.common.utils.FileUtils.deleteDirectory( directory ); } catch ( IOException e ) { - log.warn( "skip error deleting directory {}:", directory.getPath(), e ); + log.warn( "skip error deleting directory {}:", directory, e ); } } } @@ -171,7 +171,8 @@ public class ManagedDefaultRepositoryContent throws ContentNotFoundException { Path artifactFile = toFile( reference ); - Path repoDir = artifactFile.getParent(); + Path repoBase = Paths.get(repository.getLocation()).toAbsolutePath(); + Path repoDir = artifactFile.getParent().toAbsolutePath(); if ( !Files.exists(repoDir)) { @@ -185,37 +186,29 @@ public class ManagedDefaultRepositoryContent "Unable to get related artifacts using a non-directory: " + repoDir.toAbsolutePath() ); } - Set<ArtifactReference> foundArtifacts = new HashSet<>(); + Set<ArtifactReference> foundArtifacts; // First gather up the versions found as artifacts in the managed repository. - File repoFiles[] = repoDir.toFile().listFiles(); - for (File repoFile : repoFiles) - { - if (repoFile.isDirectory()) { - // Skip it. it's a directory. - continue; - } - String relativePath = PathUtil.getRelative(repository.getLocation(), repoFile); - if ( filetypes.matchesArtifactPattern( relativePath ) ) - { - try - { - ArtifactReference artifact = toArtifactReference( relativePath ); - - // Test for related, groupId / artifactId / version must match. - if ( artifact.getGroupId().equals( reference.getGroupId() ) && artifact.getArtifactId().equals( - reference.getArtifactId() ) && artifact.getVersion().equals( reference.getVersion() ) ) - { - foundArtifacts.add( artifact ); + + try (Stream<Path> stream = Files.list(repoDir)) { + foundArtifacts = stream.filter(Files::isRegularFile).map(path -> { + try { + ArtifactReference artifact = toArtifactReference(repoBase.relativize(path).toString()); + if( artifact.getGroupId().equals( reference.getGroupId() ) && artifact.getArtifactId().equals( + reference.getArtifactId() ) && artifact.getVersion().equals( reference.getVersion() )) { + return artifact; + } else { + return null; } - } - catch ( LayoutException e ) - { + } catch (LayoutException e) { log.debug( "Not processing file that is not an artifact: {}", e.getMessage() ); + return null; } - } + }).filter(Objects::nonNull).collect(Collectors.toSet()); + } catch (IOException e) { + log.error("Could not read directory {}: {}", repoDir, e.getMessage(), e); + return Collections.emptySet(); } - return foundArtifacts; } @@ -251,43 +244,45 @@ public class ManagedDefaultRepositoryContent path = path.substring( 0, idx ); } - File repoDir = new File( repository.getLocation(), path ); + Path repoDir = Paths.get( repository.getLocation(), path ); - if ( !repoDir.exists() ) + if ( !Files.exists(repoDir) ) { throw new ContentNotFoundException( - "Unable to get Versions on a non-existant directory: " + repoDir.getAbsolutePath() ); + "Unable to get Versions on a non-existant directory: " + repoDir.toAbsolutePath() ); } - if ( !repoDir.isDirectory() ) + if ( !Files.isDirectory(repoDir) ) { throw new ContentNotFoundException( - "Unable to get Versions on a non-directory: " + repoDir.getAbsolutePath() ); + "Unable to get Versions on a non-directory: " + repoDir.toAbsolutePath() ); } - Set<String> foundVersions = new HashSet<>(); - VersionedReference versionRef = new VersionedReference(); - versionRef.setGroupId( reference.getGroupId() ); - versionRef.setArtifactId( reference.getArtifactId() ); - - File repoFiles[] = repoDir.listFiles(); - for (File repoFile : repoFiles) - { - if (!repoFile.isDirectory()) { - // Skip it. not a directory. - continue; - } - // Test if dir has an artifact, which proves to us that it is a valid version directory. - String version = repoFile.getName(); - versionRef.setVersion( version ); - if ( hasArtifact( versionRef ) ) - { - // Found an artifact, must be a valid version. - foundVersions.add( version ); + final String groupId = reference.getGroupId(); + final String artifactId = reference.getArtifactId(); + try(Stream<Path> stream = Files.list(repoDir)) { + return stream.filter(Files::isDirectory).map( + p -> newVersionedRef(groupId, artifactId, p.getFileName().toString()) + ).filter(this::hasArtifact).map(ref -> ref.getVersion()) + .collect(Collectors.toSet()); + } catch (IOException e) { + log.error("Could not read directory {}: {}", repoDir, e.getMessage(), e); + } catch (RuntimeException e) { + if (e.getCause()!=null && e.getCause() instanceof LayoutException) { + throw (LayoutException)e.getCause(); + } else { + throw e; } } + return Collections.emptySet(); + } - return foundVersions; + static final VersionedReference newVersionedRef(final String groupId, final String artifactId, final String version) { + VersionedReference ref = new VersionedReference(); + ref.setGroupId(groupId); + ref.setArtifactId(artifactId); + ref.setVersion(version); + return ref; } @Override @@ -302,52 +297,42 @@ public class ManagedDefaultRepositoryContent path = path.substring( 0, idx ); } - File repoDir = new File( repository.getLocation(), path ); + Path repoBase = Paths.get(repository.getLocation()); + Path repoDir = repoBase.resolve( path ); - if ( !repoDir.exists() ) + if ( !Files.exists(repoDir) ) { throw new ContentNotFoundException( - "Unable to get versions on a non-existant directory: " + repoDir.getAbsolutePath() ); + "Unable to get versions on a non-existant directory: " + repoDir.toAbsolutePath() ); } - if ( !repoDir.isDirectory() ) + if ( !Files.isDirectory(repoDir) ) { throw new ContentNotFoundException( - "Unable to get versions on a non-directory: " + repoDir.getAbsolutePath() ); + "Unable to get versions on a non-directory: " + repoDir.toAbsolutePath() ); } Set<String> foundVersions = new HashSet<>(); - // First gather up the versions found as artifacts in the managed repository. - File repoFiles[] = repoDir.listFiles(); - for (File repoFile : repoFiles) - { - if (repoFile.isDirectory()) { - // Skip it. it's a directory. - continue; - } - String relativePath = PathUtil.getRelative(repository.getLocation(), repoFile); - if ( filetypes.matchesDefaultExclusions( relativePath ) ) - { - // Skip it, it's metadata or similar - continue; - } - if ( filetypes.matchesArtifactPattern( relativePath ) ) - { - try - { - ArtifactReference artifact = toArtifactReference( relativePath ); - - foundVersions.add( artifact.getVersion() ); - } - catch ( LayoutException e ) - { - log.debug( "Not processing file that is not an artifact: {}", e.getMessage() ); - } - } + try(Stream<Path> stream = Files.list(repoDir)) { + return stream.filter(Files::isRegularFile) + .map(p -> repoBase.relativize(p).toString()) + .filter(p -> !filetypes.matchesDefaultExclusions(p)) + .filter(filetypes::matchesArtifactPattern) + .map(path1 -> { + try { + return toArtifactReference(path1); + } catch (LayoutException e) { + log.debug( "Not processing file that is not an artifact: {}", e.getMessage() ); + return null; + } + }).filter(Objects::nonNull) + .map(ar -> ar.getVersion()) + .collect(Collectors.toSet()); + } catch (IOException e) { + log.error("Could not read directory {}: {}", repoDir, e.getMessage(), e); } - - return foundVersions; + return Collections.emptySet(); } @Override @@ -408,6 +393,17 @@ public class ManagedDefaultRepositoryContent return super.toArtifactReference( path ); } + // The variant with runtime exception for stream usage + private ArtifactReference toArtifactRef(String path) { + try { + return toArtifactReference(path); + } catch (LayoutException e) { + throw new RuntimeException(e); + } + } + + + @Override public Path toFile( ArtifactReference reference ) { @@ -440,42 +436,37 @@ public class ManagedDefaultRepositoryContent path = path.substring( 0, idx ); } - File repoDir = new File( repository.getLocation(), path ); + Path repoBase = Paths.get(repository.getLocation()).toAbsolutePath(); + Path repoDir = repoBase.resolve( path ); - if ( !repoDir.exists() ) + if ( !Files.exists(repoDir) ) { throw new IOException( "Unable to gather the list of snapshot versions on a non-existant directory: " - + repoDir.getAbsolutePath() ); + + repoDir.toAbsolutePath() ); } - if ( !repoDir.isDirectory() ) + if ( !Files.isDirectory(repoDir) ) { throw new IOException( - "Unable to gather the list of snapshot versions on a non-directory: " + repoDir.getAbsolutePath() ); + "Unable to gather the list of snapshot versions on a non-directory: " + repoDir.toAbsolutePath() ); } - - File repoFiles[] = repoDir.listFiles(); - for (File repoFile : repoFiles) - { - if (repoFile.isDirectory()) { - // Skip it. it's a directory. - continue; - } - String relativePath = PathUtil.getRelative(repository.getLocation(), repoFile); - if ( filetypes.matchesArtifactPattern( relativePath ) ) - { - ArtifactReference artifact = toArtifactReference( relativePath ); - - return artifact; + try(Stream<Path> stream = Files.list(repoDir)) { + return stream.filter(Files::isRegularFile) + .map(p -> repoBase.relativize(p).toString()) + .filter(filetypes::matchesArtifactPattern) + .map(this::toArtifactRef).findFirst().orElse(null); + } catch (RuntimeException e) { + if (e.getCause()!=null && e.getCause() instanceof LayoutException) { + throw (LayoutException)e.getCause(); + } else { + throw e; } } - // No artifact was found. - return null; } private boolean hasArtifact( VersionedReference reference ) - throws LayoutException + { try { @@ -484,6 +475,9 @@ public class ManagedDefaultRepositoryContent catch ( IOException e ) { return false; + } catch (LayoutException e) { + // We throw the runtime exception for better stream handling + throw new RuntimeException(e); } } diff --git a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/dependency/tree/maven2/DependencyTreeBuilderTestMaven3.java b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/dependency/tree/maven2/DependencyTreeBuilderTestMaven3.java index 93f6bc7fb..7dbb4dab9 100644 --- a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/dependency/tree/maven2/DependencyTreeBuilderTestMaven3.java +++ b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/dependency/tree/maven2/DependencyTreeBuilderTestMaven3.java @@ -27,7 +27,6 @@ import org.apache.archiva.configuration.ManagedRepositoryConfiguration; import org.apache.archiva.maven2.model.Artifact; import org.apache.archiva.maven2.model.TreeEntry; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; -import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -35,10 +34,12 @@ import org.springframework.test.context.ContextConfiguration; import javax.inject.Inject; import javax.inject.Named; -import java.io.File; +import java.nio.file.Paths; import java.util.Collections; import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; + @RunWith( ArchivaSpringJUnit4ClassRunner.class ) @ContextConfiguration( { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } ) public class DependencyTreeBuilderTestMaven3 @@ -74,7 +75,7 @@ public class DependencyTreeBuilderTestMaven3 Configuration configuration = new Configuration(); ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration(); repoConfig.setId( TEST_REPO_ID ); - repoConfig.setLocation( new File( "target/test-repository" ).getAbsolutePath() ); + repoConfig.setLocation(Paths.get("target/test-repository").toAbsolutePath().toString() ); configuration.addManagedRepository( repoConfig ); config.save( configuration ); diff --git a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/ManagedDefaultRepositoryContentTest.java b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/ManagedDefaultRepositoryContentTest.java index 6c0033e53..f8773c6f8 100644 --- a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/ManagedDefaultRepositoryContentTest.java +++ b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/ManagedDefaultRepositoryContentTest.java @@ -34,12 +34,9 @@ import org.junit.Test; import javax.inject.Inject; import javax.inject.Named; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Set; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @@ -65,7 +62,7 @@ public class ManagedDefaultRepositoryContentTest public void setUp() throws Exception { - File repoDir = new File( "src/test/repositories/default-repository" ); + Path repoDir = Paths.get( "src/test/repositories/default-repository" ); ManagedRepository repository = createRepository( "testRepo", "Unit Test Repo", repoDir ); @@ -178,8 +175,8 @@ public class ManagedDefaultRepositoryContentTest // Use the test metadata-repository, which is already setup for // These kind of version tests. - File repoDir = new File( "src/test/repositories/metadata-repository" ); - repoContent.getRepository().setLocation( repoDir.getAbsolutePath() ); + Path repoDir = Paths.get( "src/test/repositories/metadata-repository" ); + repoContent.getRepository().setLocation( repoDir.toAbsolutePath().toString() ); // Request the versions. Set<String> testedVersionSet = repoContent.getVersions( reference ); @@ -203,8 +200,8 @@ public class ManagedDefaultRepositoryContentTest // Use the test metadata-repository, which is already setup for // These kind of version tests. - File repoDir = new File( "src/test/repositories/metadata-repository" ); - repoContent.getRepository().setLocation( repoDir.getAbsolutePath() ); + Path repoDir = Paths.get( "src/test/repositories/metadata-repository" ); + repoContent.getRepository().setLocation( repoDir.toAbsolutePath().toString() ); // Request the versions. Set<String> testedVersionSet = repoContent.getVersions( reference ); diff --git a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryMetadataResolverMRM1411RepoGroupTest.java b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryMetadataResolverMRM1411RepoGroupTest.java index ed630ad66..ebb26770d 100644 --- a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryMetadataResolverMRM1411RepoGroupTest.java +++ b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryMetadataResolverMRM1411RepoGroupTest.java @@ -20,17 +20,8 @@ package org.apache.archiva.metadata.repository.storage.maven2; */ import junit.framework.TestCase; -import org.apache.archiva.configuration.ArchivaConfiguration; -import org.apache.archiva.configuration.Configuration; -import org.apache.archiva.configuration.ManagedRepositoryConfiguration; -import org.apache.archiva.configuration.ProxyConnectorConfiguration; -import org.apache.archiva.configuration.RemoteRepositoryConfiguration; -import org.apache.archiva.configuration.RepositoryGroupConfiguration; -import org.apache.archiva.metadata.model.ArtifactMetadata; -import org.apache.archiva.metadata.model.Dependency; -import org.apache.archiva.metadata.model.License; -import org.apache.archiva.metadata.model.MailingList; -import org.apache.archiva.metadata.model.ProjectVersionMetadata; +import org.apache.archiva.configuration.*; +import org.apache.archiva.metadata.model.*; import org.apache.archiva.metadata.repository.filter.AllFilter; import org.apache.archiva.metadata.repository.filter.Filter; import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest; @@ -46,8 +37,10 @@ import org.springframework.test.context.ContextConfiguration; import javax.inject.Inject; import javax.inject.Named; -import java.io.File; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -114,14 +107,14 @@ public class Maven2RepositoryMetadataResolverMRM1411RepoGroupTest testRepo = new ManagedRepositoryConfiguration(); testRepo.setId( TEST_REPO_ID ); - testRepo.setLocation( new File( "target/test-repository" ).getAbsolutePath() ); + testRepo.setLocation( Paths.get( "target/test-repository" ).toAbsolutePath().toString() ); testRepo.setReleases( true ); testRepo.setSnapshots( false ); c.addManagedRepository( testRepo ); testRepoS = new ManagedRepositoryConfiguration(); testRepoS.setId( TEST_SNAP_REPO_ID ); - testRepoS.setLocation( new File( "target/test-repositorys" ).getAbsolutePath() ); + testRepoS.setLocation( Paths.get( "target/test-repositorys" ).toAbsolutePath().toString() ); testRepoS.setReleases( false ); testRepoS.setSnapshots( true ); c.addManagedRepository( testRepoS ); @@ -493,33 +486,32 @@ public class Maven2RepositoryMetadataResolverMRM1411RepoGroupTest { for ( String path : pathsToBeDeleted ) { - File dir = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), path ); - FileUtils.deleteDirectory( dir ); + Path dir = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), path ); + org.apache.archiva.common.utils.FileUtils.deleteDirectory( dir ); - assertFalse( dir.exists() ); + assertFalse( Files.exists(dir) ); } - File dest = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-module-a" ); - File parentPom = - new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-parent" ); - File rootPom = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-root" ); - - FileUtils.deleteDirectory( dest ); - FileUtils.deleteDirectory( parentPom ); - FileUtils.deleteDirectory( rootPom ); - - assertFalse( dest.exists() ); - assertFalse( parentPom.exists() ); - assertFalse( rootPom.exists() ); + Path dest = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-module-a" ); + Path parentPom = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-parent" ); + Path rootPom = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-root" ); + + org.apache.archiva.common.utils.FileUtils.deleteDirectory( dest ); + org.apache.archiva.common.utils.FileUtils.deleteDirectory( parentPom ); + org.apache.archiva.common.utils.FileUtils.deleteDirectory( rootPom ); + + assertFalse( Files.exists(dest) ); + assertFalse( Files.exists(parentPom) ); + assertFalse( Files.exists(rootPom) ); } - private File copyTestArtifactWithParent( String srcPath, String destPath ) + private Path copyTestArtifactWithParent( String srcPath, String destPath ) throws IOException { - File src = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), srcPath ); - File dest = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), destPath ); + Path src = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), srcPath ); + Path dest = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), destPath ); - FileUtils.copyDirectory( src, dest ); - assertTrue( dest.exists() ); + FileUtils.copyDirectory( src.toFile(), dest.toFile() ); + assertTrue( Files.exists(dest) ); return dest; } diff --git a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryMetadataResolverMRM1411Test.java b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryMetadataResolverMRM1411Test.java index 5242414ba..d7678edbb 100644 --- a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryMetadataResolverMRM1411Test.java +++ b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryMetadataResolverMRM1411Test.java @@ -20,16 +20,8 @@ package org.apache.archiva.metadata.repository.storage.maven2; */ import junit.framework.TestCase; -import org.apache.archiva.configuration.ArchivaConfiguration; -import org.apache.archiva.configuration.Configuration; -import org.apache.archiva.configuration.ManagedRepositoryConfiguration; -import org.apache.archiva.configuration.ProxyConnectorConfiguration; -import org.apache.archiva.configuration.RemoteRepositoryConfiguration; -import org.apache.archiva.metadata.model.ArtifactMetadata; -import org.apache.archiva.metadata.model.Dependency; -import org.apache.archiva.metadata.model.License; -import org.apache.archiva.metadata.model.MailingList; -import org.apache.archiva.metadata.model.ProjectVersionMetadata; +import org.apache.archiva.configuration.*; +import org.apache.archiva.metadata.model.*; import org.apache.archiva.metadata.repository.filter.AllFilter; import org.apache.archiva.metadata.repository.filter.Filter; import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest; @@ -46,8 +38,10 @@ import org.springframework.test.context.ContextConfiguration; import javax.inject.Inject; import javax.inject.Named; -import java.io.File; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -107,7 +101,7 @@ public class Maven2RepositoryMetadataResolverMRM1411Test c = new Configuration(); testRepo = new ManagedRepositoryConfiguration(); testRepo.setId( TEST_REPO_ID ); - testRepo.setLocation( new File( "target/test-repository" ).getAbsolutePath() ); + testRepo.setLocation( Paths.get( "target/test-repository" ).toAbsolutePath().toString() ); testRepo.setReleases( true ); testRepo.setSnapshots( true ); c.addManagedRepository( testRepo ); @@ -397,33 +391,33 @@ public class Maven2RepositoryMetadataResolverMRM1411Test { for ( String path : pathsToBeDeleted ) { - File dir = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), path ); - FileUtils.deleteDirectory( dir ); + Path dir = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), path ); + org.apache.archiva.common.utils.FileUtils.deleteDirectory( dir ); - assertFalse( dir.exists() ); + assertFalse(Files.exists( dir) ); } - File dest = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-module-a" ); - File parentPom = - new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-parent" ); - File rootPom = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-root" ); - - FileUtils.deleteDirectory( dest ); - FileUtils.deleteDirectory( parentPom ); - FileUtils.deleteDirectory( rootPom ); - - assertFalse( dest.exists() ); - assertFalse( parentPom.exists() ); - assertFalse( rootPom.exists() ); + Path dest = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-module-a" ); + Path parentPom = + Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-parent" ); + Path rootPom = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-root" ); + + org.apache.archiva.common.utils.FileUtils.deleteDirectory( dest ); + org.apache.archiva.common.utils.FileUtils.deleteDirectory( parentPom ); + org.apache.archiva.common.utils.FileUtils.deleteDirectory( rootPom ); + + assertFalse( Files.exists(dest) ); + assertFalse( Files.exists(parentPom) ); + assertFalse( Files.exists(rootPom) ); } - private File copyTestArtifactWithParent( String srcPath, String destPath ) + private Path copyTestArtifactWithParent( String srcPath, String destPath ) throws IOException { - File src = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), srcPath ); - File dest = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), destPath ); + Path src = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), srcPath ); + Path dest = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), destPath ); - FileUtils.copyDirectory( src, dest ); - assertTrue( dest.exists() ); + FileUtils.copyDirectory( src.toFile(), dest.toFile() ); + assertTrue( Files.exists(dest) ); return dest; } diff --git a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryMetadataResolverTest.java b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryMetadataResolverTest.java index 46ef5ac54..24ce464c5 100644 --- a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryMetadataResolverTest.java +++ b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/Maven2RepositoryMetadataResolverTest.java @@ -20,16 +20,8 @@ package org.apache.archiva.metadata.repository.storage.maven2; */ import junit.framework.TestCase; -import org.apache.archiva.configuration.ArchivaConfiguration; -import org.apache.archiva.configuration.Configuration; -import org.apache.archiva.configuration.ManagedRepositoryConfiguration; -import org.apache.archiva.configuration.ProxyConnectorConfiguration; -import org.apache.archiva.configuration.RemoteRepositoryConfiguration; -import org.apache.archiva.metadata.model.ArtifactMetadata; -import org.apache.archiva.metadata.model.Dependency; -import org.apache.archiva.metadata.model.License; -import org.apache.archiva.metadata.model.MailingList; -import org.apache.archiva.metadata.model.ProjectVersionMetadata; +import org.apache.archiva.configuration.*; +import org.apache.archiva.metadata.model.*; import org.apache.archiva.metadata.model.maven2.MavenArtifactFacet; import org.apache.archiva.metadata.repository.filter.AllFilter; import org.apache.archiva.metadata.repository.filter.ExcludesFilter; @@ -49,19 +41,13 @@ import org.springframework.test.context.ContextConfiguration; import javax.inject.Inject; import javax.inject.Named; -import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; +import java.util.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -117,7 +103,7 @@ public class Maven2RepositoryMetadataResolverTest c = new Configuration(); testRepo = new ManagedRepositoryConfiguration(); testRepo.setId( TEST_REPO_ID ); - testRepo.setLocation( new File( "target/test-repository" ).getAbsolutePath() ); + testRepo.setLocation( Paths.get( "target/test-repository" ).toAbsolutePath().toString() ); testRepo.setReleases( true ); testRepo.setSnapshots( true ); c.addManagedRepository( testRepo ); @@ -771,33 +757,33 @@ public class Maven2RepositoryMetadataResolverTest { for ( String path : pathsToBeDeleted ) { - File dir = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), path ); - FileUtils.deleteDirectory( dir ); + Path dir = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), path ); + org.apache.archiva.common.utils.FileUtils.deleteDirectory( dir ); - assertFalse( dir.exists() ); + assertFalse( Files.exists(dir) ); } - File dest = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-module-a" ); - File parentPom = - new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-parent" ); - File rootPom = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-root" ); - - FileUtils.deleteDirectory( dest ); - FileUtils.deleteDirectory( parentPom ); - FileUtils.deleteDirectory( rootPom ); - - assertFalse( dest.exists() ); - assertFalse( parentPom.exists() ); - assertFalse( rootPom.exists() ); + Path dest = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-module-a" ); + Path parentPom = + Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-parent" ); + Path rootPom = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-root" ); + + org.apache.archiva.common.utils.FileUtils.deleteDirectory( dest ); + org.apache.archiva.common.utils.FileUtils.deleteDirectory( parentPom ); + org.apache.archiva.common.utils.FileUtils.deleteDirectory( rootPom ); + + assertFalse( Files.exists(dest) ); + assertFalse( Files.exists(parentPom) ); + assertFalse( Files.exists(rootPom) ); } - private File copyTestArtifactWithParent( String srcPath, String destPath ) + private Path copyTestArtifactWithParent( String srcPath, String destPath ) throws IOException { - File src = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), srcPath ); - File dest = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), destPath ); + Path src = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), srcPath ); + Path dest = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), destPath ); - FileUtils.copyDirectory( src, dest ); - assertTrue( dest.exists() ); + FileUtils.copyDirectory( src.toFile(), dest.toFile() ); + assertTrue( Files.exists(dest) ); return dest; } diff --git a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/MavenRepositoryMetadataReaderTest.java b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/MavenRepositoryMetadataReaderTest.java index 4d09032a9..e2fec5010 100644 --- a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/MavenRepositoryMetadataReaderTest.java +++ b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/metadata/repository/storage/maven2/MavenRepositoryMetadataReaderTest.java @@ -23,14 +23,15 @@ import junit.framework.TestCase; import org.apache.archiva.maven2.metadata.MavenMetadataReader; import org.apache.archiva.model.ArchivaRepositoryMetadata; import org.apache.archiva.model.Plugin; +import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner; import org.apache.archiva.xml.XMLException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Arrays; -import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner; /** * RepositoryMetadataReaderTest @@ -41,15 +42,15 @@ import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner; public class MavenRepositoryMetadataReaderTest extends TestCase { - private File defaultRepoDir; + private Path defaultRepoDir; @Test public void testGroupMetadata() throws XMLException { - File metadataFile = new File( defaultRepoDir, "org/apache/maven/plugins/maven-metadata.xml" ); + Path metadataFile = defaultRepoDir.resolve( "org/apache/maven/plugins/maven-metadata.xml" ); - ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile.toPath() ); + ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile ); assertNotNull( metadata ); assertEquals( "org.apache.maven.plugins", metadata.getGroupId() ); @@ -82,9 +83,9 @@ public class MavenRepositoryMetadataReaderTest public void testProjectMetadata() throws XMLException { - File metadataFile = new File( defaultRepoDir, "org/apache/maven/shared/maven-downloader/maven-metadata.xml" ); + Path metadataFile = defaultRepoDir.resolve( "org/apache/maven/shared/maven-downloader/maven-metadata.xml" ); - ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile.toPath() ); + ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile); assertNotNull( metadata ); assertEquals( "org.apache.maven.shared", metadata.getGroupId() ); @@ -100,9 +101,9 @@ public class MavenRepositoryMetadataReaderTest public void testProjectVersionMetadata() throws XMLException { - File metadataFile = new File( defaultRepoDir, "org/apache/apache/5-SNAPSHOT/maven-metadata.xml" ); + Path metadataFile = defaultRepoDir.resolve( "org/apache/apache/5-SNAPSHOT/maven-metadata.xml" ); - ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile.toPath() ); + ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile ); assertNotNull( metadata ); assertEquals( "org.apache", metadata.getGroupId() ); @@ -122,6 +123,6 @@ public class MavenRepositoryMetadataReaderTest throws Exception { super.setUp(); - defaultRepoDir = new File( "target/test-repository" ); + defaultRepoDir = Paths.get("target/test-repository"); } }
\ No newline at end of file diff --git a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/AbstractRepositoryLayerTestCase.java b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/AbstractRepositoryLayerTestCase.java index 94bfe47a0..02bbf0c31 100644 --- a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/AbstractRepositoryLayerTestCase.java +++ b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/AbstractRepositoryLayerTestCase.java @@ -21,15 +21,15 @@ package org.apache.archiva.repository; import org.apache.archiva.admin.model.beans.ManagedRepository; import org.apache.archiva.admin.model.beans.RemoteRepository; +import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.junit.Rule; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; -import java.io.File; import javax.inject.Inject; -import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; +import java.nio.file.Path; /** * AbstractRepositoryLayerTestCase @@ -46,12 +46,12 @@ public abstract class AbstractRepositoryLayerTestCase @Inject protected ApplicationContext applicationContext; - protected ManagedRepository createRepository( String id, String name, File location ) + protected ManagedRepository createRepository( String id, String name, Path location ) { ManagedRepository repo = new ManagedRepository(); repo.setId( id ); repo.setName( name ); - repo.setLocation( location.getAbsolutePath() ); + repo.setLocation( location.toAbsolutePath().toString() ); return repo; } @@ -64,14 +64,14 @@ public abstract class AbstractRepositoryLayerTestCase return repo; } - protected ManagedRepositoryContent createManagedRepositoryContent( String id, String name, File location, + protected ManagedRepositoryContent createManagedRepositoryContent( String id, String name, Path location, String layout ) throws Exception { ManagedRepository repo = new ManagedRepository(); repo.setId( id ); repo.setName( name ); - repo.setLocation( location.getAbsolutePath() ); + repo.setLocation( location.toAbsolutePath().toString() ); repo.setLayout( layout ); ManagedRepositoryContent repoContent = diff --git a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/content/maven2/RepositoryRequestTest.java b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/content/maven2/RepositoryRequestTest.java index 54ff2e947..ee56ed28e 100644 --- a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/content/maven2/RepositoryRequestTest.java +++ b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/content/maven2/RepositoryRequestTest.java @@ -35,7 +35,8 @@ import org.springframework.test.context.ContextConfiguration; import javax.inject.Inject; import javax.inject.Named; -import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; import static org.junit.Assert.*; @@ -368,7 +369,7 @@ public class RepositoryRequestTest private ManagedRepositoryContent createManagedRepo( String layout ) throws Exception { - File repoRoot = new File( FileUtils.getBasedir() + "/target/test-repo" ); + Path repoRoot = Paths.get( FileUtils.getBasedir() + "/target/test-repo" ); return createManagedRepositoryContent( "test-internal", "Internal Test Repo", repoRoot, layout ); } @@ -509,14 +510,14 @@ public class RepositoryRequestTest } } - protected ManagedRepositoryContent createManagedRepositoryContent( String id, String name, File location, + protected ManagedRepositoryContent createManagedRepositoryContent( String id, String name, Path location, String layout ) throws Exception { ManagedRepository repo = new ManagedRepository(); repo.setId( id ); repo.setName( name ); - repo.setLocation( location.getAbsolutePath() ); + repo.setLocation( location.toAbsolutePath().toString() ); repo.setLayout( layout ); ManagedRepositoryContent repoContent = diff --git a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/metadata/MetadataToolsTest.java b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/metadata/MetadataToolsTest.java index 5bb87cea6..a258108dd 100644 --- a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/metadata/MetadataToolsTest.java +++ b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/metadata/MetadataToolsTest.java @@ -22,6 +22,7 @@ package org.apache.archiva.repository.metadata; import org.apache.archiva.admin.model.beans.ManagedRepository; import org.apache.archiva.common.utils.VersionComparator; import org.apache.archiva.configuration.ProxyConnectorConfiguration; +import org.apache.archiva.metadata.repository.storage.maven2.conf.MockConfiguration; import org.apache.archiva.model.ProjectReference; import org.apache.archiva.model.VersionedReference; import org.apache.archiva.policies.CachedFailuresPolicy; @@ -30,7 +31,6 @@ import org.apache.archiva.policies.ReleasesPolicy; import org.apache.archiva.policies.SnapshotsPolicy; import org.apache.archiva.repository.AbstractRepositoryLayerTestCase; import org.apache.archiva.repository.ManagedRepositoryContent; -import org.apache.archiva.metadata.repository.storage.maven2.conf.MockConfiguration; import org.apache.archiva.repository.RemoteRepositoryContent; import org.apache.archiva.repository.layout.LayoutException; import org.apache.commons.io.FileUtils; @@ -44,9 +44,11 @@ import org.xml.sax.SAXException; import javax.inject.Inject; import javax.inject.Named; import javax.xml.parsers.ParserConfigurationException; -import java.io.File; import java.io.IOException; import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -353,7 +355,7 @@ public class MetadataToolsTest private void assertSnapshotVersions( String artifactId, String version, String[] expectedVersions ) throws Exception { - File repoRootDir = new File( "src/test/repositories/metadata-repository" ); + Path repoRootDir = Paths.get( "src/test/repositories/metadata-repository" ); VersionedReference reference = new VersionedReference(); reference.setGroupId( "org.apache.archiva.metadata.tests" ); @@ -387,8 +389,8 @@ public class MetadataToolsTest ProjectReference reference ) throws LayoutException, IOException, SAXException, ParserConfigurationException { - File metadataFile = new File( repository.getRepoRoot(), tools.toPath( reference ) ); - String actualMetadata = FileUtils.readFileToString( metadataFile, Charset.defaultCharset() ); + Path metadataFile = Paths.get( repository.getRepoRoot(), tools.toPath( reference ) ); + String actualMetadata = org.apache.archiva.common.utils.FileUtils.readFileToString( metadataFile, Charset.defaultCharset() ); DetailedDiff detailedDiff = new DetailedDiff( new Diff( expectedMetadata, actualMetadata ) ); if ( !detailedDiff.similar() ) @@ -402,8 +404,8 @@ public class MetadataToolsTest VersionedReference reference ) throws LayoutException, IOException, SAXException, ParserConfigurationException { - File metadataFile = new File( repository.getRepoRoot(), tools.toPath( reference ) ); - String actualMetadata = FileUtils.readFileToString( metadataFile, Charset.defaultCharset() ); + Path metadataFile = Paths.get( repository.getRepoRoot(), tools.toPath( reference ) ); + String actualMetadata = org.apache.archiva.common.utils.FileUtils.readFileToString( metadataFile, Charset.defaultCharset() ); DetailedDiff detailedDiff = new DetailedDiff( new Diff( expectedMetadata, actualMetadata ) ); if ( !detailedDiff.similar() ) @@ -604,13 +606,13 @@ public class MetadataToolsTest private ManagedRepositoryContent createTestRepoContent() throws Exception { - File repoRoot = new File( "target/metadata-tests/" + name.getMethodName() ); - if ( repoRoot.exists() ) + Path repoRoot = Paths.get( "target/metadata-tests/" + name.getMethodName() ); + if ( Files.exists(repoRoot) ) { - FileUtils.deleteDirectory( repoRoot ); + org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoRoot ); } - repoRoot.mkdirs(); + Files.createDirectories(repoRoot); ManagedRepository repoConfig = createRepository( "test-repo", "Test Repository: " + name.getMethodName(), repoRoot ); @@ -627,14 +629,14 @@ public class MetadataToolsTest String groupDir = StringUtils.replaceChars( reference.getGroupId(), '.', '/' ); String path = groupDir + "/" + reference.getArtifactId(); - File srcRepoDir = new File( "src/test/repositories/metadata-repository" ); - File srcDir = new File( srcRepoDir, path ); - File destDir = new File( repo.getRepoRoot(), path ); + Path srcRepoDir = Paths.get( "src/test/repositories/metadata-repository" ); + Path srcDir = srcRepoDir.resolve( path ); + Path destDir = Paths.get( repo.getRepoRoot(), path ); - assertTrue( "Source Dir exists: " + srcDir, srcDir.exists() ); - destDir.mkdirs(); + assertTrue( "Source Dir exists: " + srcDir, Files.exists(srcDir) ); + Files.createDirectories(destDir); - FileUtils.copyDirectory( srcDir, destDir ); + FileUtils.copyDirectory( srcDir.toFile(), destDir.toFile() ); } private void prepTestRepo( ManagedRepositoryContent repo, VersionedReference reference ) diff --git a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/metadata/RepositoryMetadataReaderTest.java b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/metadata/RepositoryMetadataReaderTest.java index 319443ae5..7c7da49cf 100644 --- a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/metadata/RepositoryMetadataReaderTest.java +++ b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/metadata/RepositoryMetadataReaderTest.java @@ -22,12 +22,13 @@ package org.apache.archiva.repository.metadata; import junit.framework.TestCase; import org.apache.archiva.maven2.metadata.MavenMetadataReader; import org.apache.archiva.model.ArchivaRepositoryMetadata; +import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner; import org.apache.archiva.xml.XMLException; import org.junit.Test; import org.junit.runner.RunWith; -import java.io.File; -import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner; +import java.nio.file.Path; +import java.nio.file.Paths; /** * RepositoryMetadataReaderTest @@ -42,10 +43,10 @@ public class RepositoryMetadataReaderTest public void testLoadSimple() throws XMLException { - File defaultRepoDir = new File( "src/test/repositories/default-repository" ); - File metadataFile = new File( defaultRepoDir, "org/apache/maven/shared/maven-downloader/maven-metadata.xml" ); + Path defaultRepoDir = Paths.get( "src/test/repositories/default-repository" ); + Path metadataFile = defaultRepoDir.resolve( "org/apache/maven/shared/maven-downloader/maven-metadata.xml" ); - ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile.toPath() ); + ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile); assertNotNull( metadata ); assertEquals( "Group Id", "org.apache.maven.shared", metadata.getGroupId() ); @@ -60,10 +61,10 @@ public class RepositoryMetadataReaderTest public void testLoadComplex() throws XMLException { - File defaultRepoDir = new File( "src/test/repositories/default-repository" ); - File metadataFile = new File( defaultRepoDir, "org/apache/maven/samplejar/maven-metadata.xml" ); + Path defaultRepoDir = Paths.get( "src/test/repositories/default-repository" ); + Path metadataFile = defaultRepoDir.resolve( "org/apache/maven/samplejar/maven-metadata.xml" ); - ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile.toPath() ); + ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile ); assertNotNull( metadata ); assertEquals( "Group Id", "org.apache.maven", metadata.getGroupId() ); diff --git a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/metadata/RepositoryMetadataWriterTest.java b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/metadata/RepositoryMetadataWriterTest.java index 51b9062d8..2a316a457 100644 --- a/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/metadata/RepositoryMetadataWriterTest.java +++ b/archiva-modules/plugins/maven2-repository/src/test/java/org/apache/archiva/repository/metadata/RepositoryMetadataWriterTest.java @@ -22,14 +22,14 @@ package org.apache.archiva.repository.metadata; import junit.framework.TestCase; import org.apache.archiva.model.ArchivaRepositoryMetadata; import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner; -import org.apache.commons.io.FileUtils; import org.custommonkey.xmlunit.XMLAssert; import org.junit.Test; import org.junit.runner.RunWith; -import java.io.File; import java.io.StringWriter; import java.nio.charset.Charset; +import java.nio.file.Path; +import java.nio.file.Paths; /** * RepositoryMetadataWriterTest @@ -43,9 +43,9 @@ public class RepositoryMetadataWriterTest public void testWriteSimple() throws Exception { - File defaultRepoDir = new File( "src/test/repositories/default-repository" ); - File expectedFile = new File( defaultRepoDir, "org/apache/maven/shared/maven-downloader/maven-metadata.xml" ); - String expectedContent = FileUtils.readFileToString( expectedFile, Charset.defaultCharset() ); + Path defaultRepoDir = Paths.get( "src/test/repositories/default-repository" ); + Path expectedFile = defaultRepoDir.resolve( "org/apache/maven/shared/maven-downloader/maven-metadata.xml" ); + String expectedContent = org.apache.archiva.common.utils.FileUtils.readFileToString( expectedFile, Charset.defaultCharset() ); ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata(); diff --git a/archiva-modules/plugins/stage-repository-merge/src/main/java/org/apache/archiva/stagerepository/merge/Maven2RepositoryMerger.java b/archiva-modules/plugins/stage-repository-merge/src/main/java/org/apache/archiva/stagerepository/merge/Maven2RepositoryMerger.java index 5bea095cc..5ffa85003 100644 --- a/archiva-modules/plugins/stage-repository-merge/src/main/java/org/apache/archiva/stagerepository/merge/Maven2RepositoryMerger.java +++ b/archiva-modules/plugins/stage-repository-merge/src/main/java/org/apache/archiva/stagerepository/merge/Maven2RepositoryMerger.java @@ -44,6 +44,7 @@ import javax.inject.Inject; import javax.inject.Named; import java.io.File; import java.io.IOException; +import java.nio.file.Paths; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -226,9 +227,9 @@ public class Maven2RepositoryMerger // updating version metadata files File versionMetaDataFileInSourceRepo = - pathTranslator.toFile( new File( sourceRepoPath ), artifactMetadata.getNamespace(), + pathTranslator.toFile( Paths.get( sourceRepoPath ), artifactMetadata.getNamespace(), artifactMetadata.getProject(), artifactMetadata.getVersion(), - METADATA_FILENAME ); + METADATA_FILENAME ).toFile(); if ( versionMetaDataFileInSourceRepo.exists() ) {//Pattern quote for windows path |