Migrating maven2-repository to java.nio

This commit is contained in:
Martin Stockhammer 2017-09-14 07:45:04 +02:00
parent a446c03853
commit 0eadc9bab1
21 changed files with 835 additions and 589 deletions

View File

@ -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.&lt;YOUR_TYPE&gt;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();
}
}

View File

@ -93,16 +93,20 @@ public class DaysOldRepositoryPurgeTest
setLastModified( projectRoot + "/" + projectVersion + "/", OLD_TIMESTAMP ); setLastModified( projectRoot + "/" + projectVersion + "/", OLD_TIMESTAMP );
// test listeners for the correct artifacts // test listeners for the correct artifacts
listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", String[] exts = {".md5",".sha1",""};
"maven-install-plugin", "2.2-SNAPSHOT", "maven-install-plugin-2.2-SNAPSHOT.jar" ); 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.pom" ); listener.deleteArtifact(metadataRepository, getRepository().getId(), "org.apache.maven.plugins",
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",
"maven-install-plugin-2.2-20061118.060401-2.jar" ); "maven-install-plugin-2.2-20061118.060401-2.jar"+exts[i]);
listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", 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",
"maven-install-plugin-2.2-20061118.060401-2.pom" ); "maven-install-plugin-2.2-20061118.060401-2.pom"+exts[i]);
}
listenerControl.replay(); listenerControl.replay();
// Provide the metadata list // Provide the metadata list
@ -178,12 +182,15 @@ public class DaysOldRepositoryPurgeTest
setLastModified( projectRoot + "/" + projectVersion + "/", OLD_TIMESTAMP ); setLastModified( projectRoot + "/" + projectVersion + "/", OLD_TIMESTAMP );
// test listeners for the correct artifacts // test listeners for the correct artifacts
listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", 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",
"maven-assembly-plugin-1.1.2-20070427.065136-1.jar" ); "maven-assembly-plugin-1.1.2-20070427.065136-1.jar"+exts[i]);
listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.apache.maven.plugins", 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",
"maven-assembly-plugin-1.1.2-20070427.065136-1.pom" ); "maven-assembly-plugin-1.1.2-20070427.065136-1.pom"+exts[i]);
}
listenerControl.replay(); listenerControl.replay();
// Provide the metadata list // Provide the metadata list
@ -274,10 +281,14 @@ public class DaysOldRepositoryPurgeTest
} }
// test listeners for the correct artifacts // test listeners for the correct artifacts
listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.codehaus.plexus", "plexus-utils", String[] exts = {".sha1",""};
"1.4.3-20070113.163208-4", "plexus-utils-1.4.3-20070113.163208-4.jar" ); 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.pom" ); 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(); listenerControl.replay();
// Provide the metadata list // Provide the metadata list

View File

@ -85,27 +85,31 @@ public class RetentionCountRepositoryPurgeTest
String versionRoot = projectRoot + "/" + projectVersion; String versionRoot = projectRoot + "/" + projectVersion;
// test listeners for the correct artifacts // test listeners for the correct artifacts
listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", String[] exts = { ".md5", ".sha1", ""};
"1.0RC1-20070504.153317-1", "jruby-rake-plugin-1.0RC1-20070504.153317-1.jar" ); for (int i=0 ; i<exts.length; i++) {
listener.deleteArtifact( metadataRepository, getRepository().getId(), "org.jruby.plugins", "jruby-rake-plugin", 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" ); "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", 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" ); "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", 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" ); "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", 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" ); "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", 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" ); "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.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(); listenerControl.replay();
// Provide the metadata list // Provide the metadata list
@ -181,8 +185,16 @@ public class RetentionCountRepositoryPurgeTest
// test listeners for the correct artifacts // 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", 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" ); "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", 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" ); "1.1.2-20070427.065136-1", "castor-anttasks-1.1.2-20070427.065136-1.pom" );
listenerControl.replay(); listenerControl.replay();
@ -255,9 +267,21 @@ public class RetentionCountRepositoryPurgeTest
// test listeners for the correct artifacts // 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", 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",
"maven-assembly-plugin-1.1.2-20070427.065136-1.jar" ); "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", 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",
"maven-assembly-plugin-1.1.2-20070427.065136-1.pom" ); "maven-assembly-plugin-1.1.2-20070427.065136-1.pom" );

View File

@ -21,7 +21,7 @@ package org.apache.archiva.metadata.repository.storage;
import org.apache.archiva.metadata.model.ArtifactMetadata; import org.apache.archiva.metadata.model.ArtifactMetadata;
import java.io.File; import java.nio.file.Path;
public interface RepositoryPathTranslator public interface RepositoryPathTranslator
{ {
@ -31,13 +31,13 @@ public interface RepositoryPathTranslator
String toPath( String namespace, String projectId ); 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 ); ArtifactMetadata getArtifactForPath( String repoId, String relativePath );

View File

@ -62,7 +62,6 @@ import org.sonatype.aether.impl.VersionRangeResolver;
import org.sonatype.aether.impl.VersionResolver; import org.sonatype.aether.impl.VersionResolver;
import org.sonatype.aether.impl.internal.DefaultServiceLocator; import org.sonatype.aether.impl.internal.DefaultServiceLocator;
import org.sonatype.aether.impl.internal.SimpleLocalRepositoryManager; import org.sonatype.aether.impl.internal.SimpleLocalRepositoryManager;
import org.sonatype.aether.repository.LocalRepository;
import org.sonatype.aether.spi.connector.RepositoryConnectorFactory; import org.sonatype.aether.spi.connector.RepositoryConnectorFactory;
import org.sonatype.aether.util.artifact.DefaultArtifact; import org.sonatype.aether.util.artifact.DefaultArtifact;
import org.sonatype.aether.util.graph.selector.AndDependencySelector; import org.sonatype.aether.util.graph.selector.AndDependencySelector;
@ -72,7 +71,9 @@ import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; 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.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -294,25 +295,25 @@ public class Maven3DependencyTreeBuilder
{ {
ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repoId ); ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repoId );
File repoDir = new File( managedRepository.getLocation() ); Path repoDir = Paths.get( managedRepository.getLocation() );
File file = pathTranslator.toFile( repoDir, projectArtifact.getGroupId(), projectArtifact.getArtifactId(), Path file = pathTranslator.toFile( repoDir, projectArtifact.getGroupId(), projectArtifact.getArtifactId(),
projectArtifact.getBaseVersion(), projectArtifact.getBaseVersion(),
projectArtifact.getArtifactId() + "-" + projectArtifact.getVersion() projectArtifact.getArtifactId() + "-" + projectArtifact.getVersion()
+ ".pom" ); + ".pom" );
if ( file.exists() ) if ( Files.exists(file) )
{ {
return managedRepository; return managedRepository;
} }
// try with snapshot version // try with snapshot version
if ( StringUtils.endsWith( projectArtifact.getBaseVersion(), VersionUtil.SNAPSHOT ) ) if ( StringUtils.endsWith( projectArtifact.getBaseVersion(), VersionUtil.SNAPSHOT ) )
{ {
File metadataFile = new File( file.getParent(), MetadataTools.MAVEN_METADATA ); Path metadataFile = file.getParent().resolve( MetadataTools.MAVEN_METADATA );
if ( metadataFile.exists() ) if ( Files.exists(metadataFile) )
{ {
try try
{ {
ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read( metadataFile.toPath() ); ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read( metadataFile);
int buildNumber = archivaRepositoryMetadata.getSnapshotVersion().getBuildNumber(); int buildNumber = archivaRepositoryMetadata.getSnapshotVersion().getBuildNumber();
String timeStamp = archivaRepositoryMetadata.getSnapshotVersion().getTimestamp(); String timeStamp = archivaRepositoryMetadata.getSnapshotVersion().getTimestamp();
// rebuild file name with timestamped version and build number // rebuild file name with timestamped version and build number
@ -322,9 +323,9 @@ public class Maven3DependencyTreeBuilder
"-" + VersionUtil.SNAPSHOT ) ).append( '-' ).append( "-" + VersionUtil.SNAPSHOT ) ).append( '-' ).append(
timeStamp ).append( '-' ).append( Integer.toString( buildNumber ) ).append( timeStamp ).append( '-' ).append( Integer.toString( buildNumber ) ).append(
".pom" ).toString(); ".pom" ).toString();
File timeStampFile = new File( file.getParent(), timeStampFileName ); Path timeStampFile = file.getParent().resolve( timeStampFileName );
log.debug( "try to find timestamped snapshot version file: {}", timeStampFile.getPath() ); log.debug( "try to find timestamped snapshot version file: {}", timeStampFile);
if ( timeStampFile.exists() ) if ( Files.exists(timeStampFile) )
{ {
return managedRepository; return managedRepository;
} }

View File

@ -19,17 +19,17 @@ package org.apache.archiva.metadata.repository.storage.maven2;
* under the License. * under the License.
*/ */
import org.apache.archiva.common.utils.VersionUtil;
import org.apache.archiva.metadata.model.ArtifactMetadata; import org.apache.archiva.metadata.model.ArtifactMetadata;
import org.apache.archiva.metadata.model.maven2.MavenArtifactFacet; import org.apache.archiva.metadata.model.maven2.MavenArtifactFacet;
import org.apache.archiva.metadata.repository.storage.RepositoryPathTranslator; import org.apache.archiva.metadata.repository.storage.RepositoryPathTranslator;
import org.apache.archiva.common.utils.VersionUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.inject.Inject; import javax.inject.Inject;
import java.io.File; import java.nio.file.Path;
import java.util.List; import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -78,15 +78,15 @@ public class Maven2RepositoryPathTranslator
} }
@Override @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 @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 @Override
@ -148,15 +148,15 @@ public class Maven2RepositoryPathTranslator
} }
@Override @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 @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 ) private String formatAsDirectory( String directory )

View File

@ -30,6 +30,7 @@ import org.apache.archiva.admin.model.proxyconnector.ProxyConnectorAdmin;
import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin; import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
import org.apache.archiva.checksum.ChecksumAlgorithm; import org.apache.archiva.checksum.ChecksumAlgorithm;
import org.apache.archiva.checksum.ChecksummedFile; import org.apache.archiva.checksum.ChecksummedFile;
import org.apache.archiva.common.Try;
import org.apache.archiva.common.utils.VersionUtil; import org.apache.archiva.common.utils.VersionUtil;
import org.apache.archiva.maven2.metadata.MavenMetadataReader; import org.apache.archiva.maven2.metadata.MavenMetadataReader;
import org.apache.archiva.metadata.model.ArtifactMetadata; 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.ProjectVersionMetadata;
import org.apache.archiva.metadata.model.facets.RepositoryProblemFacet; import org.apache.archiva.metadata.model.facets.RepositoryProblemFacet;
import org.apache.archiva.metadata.repository.filter.Filter; import org.apache.archiva.metadata.repository.filter.Filter;
import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest; import org.apache.archiva.metadata.repository.storage.*;
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.model.ArchivaRepositoryMetadata; import org.apache.archiva.model.ArchivaRepositoryMetadata;
import org.apache.archiva.model.ArtifactReference; import org.apache.archiva.model.ArtifactReference;
import org.apache.archiva.model.SnapshotVersion; 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.archiva.xml.XMLException;
import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.maven.model.CiManagement; import org.apache.maven.model.*;
import org.apache.maven.model.Dependency; import org.apache.maven.model.building.*;
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.io.xpp3.MavenXpp3Reader; import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -82,22 +63,20 @@ import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.nio.file.Paths;
import java.util.Arrays; import java.util.*;
import java.util.Collection; import java.util.function.Predicate;
import java.util.Collections; import java.util.stream.Collectors;
import java.util.Date; import java.util.stream.Stream;
import java.util.HashMap;
import java.util.List; // import java.io.FileNotFoundException;
import java.util.Map;
/** /**
* <p> * <p>
@ -200,15 +179,15 @@ public class Maven2RepositoryStorage
} }
} }
} }
File basedir = new File( managedRepository.getLocation() ); Path basedir = Paths.get( managedRepository.getLocation() );
if ( VersionUtil.isSnapshot( artifactVersion ) ) if ( VersionUtil.isSnapshot( artifactVersion ) )
{ {
File metadataFile = pathTranslator.toFile( basedir, readMetadataRequest.getNamespace(), Path metadataFile = pathTranslator.toFile( basedir, readMetadataRequest.getNamespace(),
readMetadataRequest.getProjectId(), artifactVersion, readMetadataRequest.getProjectId(), artifactVersion,
METADATA_FILENAME ); METADATA_FILENAME );
try try
{ {
ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile.toPath() ); ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile );
// re-adjust to timestamp if present, otherwise retain the original -SNAPSHOT filename // re-adjust to timestamp if present, otherwise retain the original -SNAPSHOT filename
SnapshotVersion snapshotVersion = metadata.getSnapshotVersion(); 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 // 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"; String id = readMetadataRequest.getProjectId() + "-" + artifactVersion + ".pom";
File file = Path file =
pathTranslator.toFile( basedir, readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(), pathTranslator.toFile( basedir, readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(),
readMetadataRequest.getProjectVersion(), id ); readMetadataRequest.getProjectVersion(), id );
if ( !file.exists() ) if ( !Files.exists(file) )
{ {
// metadata could not be resolved // metadata could not be resolved
throw new RepositoryStorageMetadataNotFoundException( 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 // 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 = ModelBuildingRequest req =
new DefaultModelBuildingRequest().setProcessPlugins( false ).setPomFile( file ).setTwoPhaseBuilding( new DefaultModelBuildingRequest().setProcessPlugins( false ).setPomFile( file.toFile() ).setTwoPhaseBuilding(
false ).setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL ); false ).setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );
//MRM-1607. olamy this will resolve jdk profiles on the current running archiva jvm //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 // olamy really hackhish but fail with java profile so use error message
// || ( StringUtils.startsWith( problem.getMessage(), "Failed to determine Java version for profile" ) ) // || ( StringUtils.startsWith( problem.getMessage(), "Failed to determine Java version for profile" ) )
// but setTwoPhaseBuilding(true) fix that // 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() ) ) ) !e.getModelId().equals( problem.getModelId() ) ) )
{ {
LOGGER.warn( "The artifact's parent POM file '{}' cannot be resolved. " 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 ) public Collection<String> listRootNamespaces( String repoId, Filter<String> filter )
throws RepositoryStorageRuntimeException throws RepositoryStorageRuntimeException
{ {
File dir = getRepositoryBasedir( repoId ); Path dir = getRepositoryBasedir( repoId );
return getSortedFiles( dir, filter ); 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 ) ); try(Stream<Path> stream = Files.list(dir)) {
if ( files != null ) final Predicate<Path> dFilter = new DirectoryFilter( filter );
{ return stream.filter(Files::isDirectory)
fileNames = new ArrayList<>( Arrays.asList( files ) ); .filter(dFilter)
Collections.sort( fileNames ); .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();
} }
else
{
fileNames = Collections.emptyList();
}
return fileNames;
} }
private File getRepositoryBasedir( String repoId ) private Path getRepositoryBasedir( String repoId )
throws RepositoryStorageRuntimeException throws RepositoryStorageRuntimeException
{ {
try try
{ {
ManagedRepository repositoryConfiguration = managedRepositoryAdmin.getManagedRepository( repoId ); ManagedRepository repositoryConfiguration = managedRepositoryAdmin.getManagedRepository( repoId );
return new File( repositoryConfiguration.getLocation() ); return Paths.get( repositoryConfiguration.getLocation() );
} }
catch ( RepositoryAdminException e ) catch ( RepositoryAdminException e )
{ {
@ -551,47 +532,39 @@ public class Maven2RepositoryStorage
public Collection<String> listNamespaces( String repoId, String namespace, Filter<String> filter ) public Collection<String> listNamespaces( String repoId, String namespace, Filter<String> filter )
throws RepositoryStorageRuntimeException 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 // scan all the directories which are potential namespaces. Any directories known to be projects are excluded
List<String> namespaces = new ArrayList<>(); Predicate<Path> dFilter = new DirectoryFilter(filter);
File[] files = dir.listFiles( new DirectoryFilter( filter ) ); try(Stream<Path> stream = Files.list(dir)) {
if ( files != null ) return stream.filter(dFilter).filter(path -> !isProject(path, filter)).map(path -> path.getFileName().toString())
{ .sorted().collect(Collectors.toList());
for ( File file : files ) } catch (IOException e) {
{ LOGGER.error("Could not read directory {}: {}", dir, e.getMessage(), e);
if ( !isProject( file, filter ) ) return Collections.emptyList();
{
namespaces.add( file.getName() );
} }
} }
}
Collections.sort( namespaces );
return namespaces;
}
@Override @Override
public Collection<String> listProjects( String repoId, String namespace, Filter<String> filter ) public Collection<String> listProjects( String repoId, String namespace, Filter<String> filter )
throws RepositoryStorageRuntimeException 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 // scan all directories in the namespace, and only include those that are known to be projects
List<String> projects = new ArrayList<>(); 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();
}
File[] files = dir.listFiles( new DirectoryFilter( filter ) );
if ( files != null )
{
for ( File file : files )
{
if ( isProject( file, filter ) )
{
projects.add( file.getName() );
}
}
}
Collections.sort( projects );
return projects;
} }
@Override @Override
@ -599,7 +572,10 @@ public class Maven2RepositoryStorage
Filter<String> filter ) Filter<String> filter )
throws RepositoryStorageRuntimeException 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 // all directories in a project directory can be considered a version
return getSortedFiles( dir, filter ); return getSortedFiles( dir, filter );
@ -609,38 +585,44 @@ public class Maven2RepositoryStorage
public Collection<ArtifactMetadata> readArtifactsMetadata( ReadMetadataRequest readMetadataRequest ) public Collection<ArtifactMetadata> readArtifactsMetadata( ReadMetadataRequest readMetadataRequest )
throws RepositoryStorageRuntimeException throws RepositoryStorageRuntimeException
{ {
File dir = pathTranslator.toFile( getRepositoryBasedir( readMetadataRequest.getRepositoryId() ), Path dir = pathTranslator.toFile( getRepositoryBasedir( readMetadataRequest.getRepositoryId() ),
readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(), readMetadataRequest.getNamespace(), readMetadataRequest.getProjectId(),
readMetadataRequest.getProjectVersion() ); 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 // all files that are not metadata and not a checksum / signature are considered artifacts
File[] files = dir.listFiles( new ArtifactDirectoryFilter( readMetadataRequest.getFilter() ) ); final Predicate<Path> dFilter = new ArtifactDirectoryFilter(readMetadataRequest.getFilter());
try(Stream<Path> stream = Files.list(dir)) {
List<ArtifactMetadata> artifacts = new ArrayList<>(); // Returns a map TRUE -> (success values), FALSE -> (Exceptions)
if ( files != null ) Map<Boolean, List<Try<ArtifactMetadata>>> result = stream.filter(dFilter).map(path -> {
{
int errorCount=0;
for ( File file : files )
{
try { try {
ArtifactMetadata metadata = return Try.success(getArtifactFromFile(readMetadataRequest.getRepositoryId(), readMetadataRequest.getNamespace(),
getArtifactFromFile(readMetadataRequest.getRepositoryId(), readMetadataRequest.getNamespace(),
readMetadataRequest.getProjectId(), readMetadataRequest.getProjectVersion(), readMetadataRequest.getProjectId(), readMetadataRequest.getProjectVersion(),
file); path));
artifacts.add(metadata); } catch (Exception e) {
} catch (Exception ex) { LOGGER.debug("Could not create metadata for {}: {}", path, e.getMessage(), e);
LOGGER.error("Error while retrieving metadata of file {} (Project: {}, Repository: {}): {}", return Try.<ArtifactMetadata>failure(e);
file.getName(), readMetadataRequest.getProjectId(), readMetadataRequest.getRepositoryId(),
ex.getMessage());
errorCount++;
} }
} }
// We throw only an error, if the number of errors equals the number of files ).collect(Collectors.groupingBy(Try::isSuccess));
if (errorCount>0 && errorCount==files.length) { 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"); 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());
} }
return artifacts; } catch (IOException e) {
LOGGER.error("Could not read directory {}: {}", dir, e.getMessage(), e);
}
return Collections.emptyList();
} }
@Override @Override
@ -649,16 +631,19 @@ public class Maven2RepositoryStorage
{ {
ArtifactMetadata metadata = pathTranslator.getArtifactForPath( repoId, path ); 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; return metadata;
} }
private ArtifactMetadata getArtifactFromFile( String repoId, String namespace, String projectId, private ArtifactMetadata getArtifactFromFile( String repoId, String namespace, String projectId,
String projectVersion, File file ) String projectVersion, Path file ) throws IOException {
{
ArtifactMetadata metadata = ArtifactMetadata metadata =
pathTranslator.getArtifactFromId( repoId, namespace, projectId, projectVersion, file.getName() ); pathTranslator.getArtifactFromId( repoId, namespace, projectId, projectVersion, file.getFileName().toString() );
populateArtifactMetadataFromFile( metadata, file ); populateArtifactMetadataFromFile( metadata, file );
@ -810,17 +795,17 @@ public class Maven2RepositoryStorage
if ( StringUtils.endsWith( artifactReference.getVersion(), VersionUtil.SNAPSHOT ) ) if ( StringUtils.endsWith( artifactReference.getVersion(), VersionUtil.SNAPSHOT ) )
{ {
// read maven metadata to get last timestamp // read maven metadata to get last timestamp
File metadataDir = new File( managedRepositoryContent.getRepoRoot(), filePath ).getParentFile(); Path metadataDir = Paths.get( managedRepositoryContent.getRepoRoot(), filePath ).getParent();
if ( !metadataDir.exists() ) if ( !Files.exists(metadataDir) )
{ {
return filePath; return filePath;
} }
File metadataFile = new File( metadataDir, METADATA_FILENAME ); Path metadataFile = metadataDir.resolve( METADATA_FILENAME );
if ( !metadataFile.exists() ) if ( !Files.exists(metadataFile) )
{ {
return filePath; return filePath;
} }
ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read( metadataFile.toPath() ); ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read( metadataFile );
int buildNumber = archivaRepositoryMetadata.getSnapshotVersion().getBuildNumber(); int buildNumber = archivaRepositoryMetadata.getSnapshotVersion().getBuildNumber();
String timestamp = archivaRepositoryMetadata.getSnapshotVersion().getTimestamp(); String timestamp = archivaRepositoryMetadata.getSnapshotVersion().getTimestamp();
@ -879,11 +864,10 @@ public class Maven2RepositoryStorage
return joinedString; 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.setWhenGathered( new Date() );
metadata.setFileLastModified( file.lastModified() ); metadata.setFileLastModified( Files.getLastModifiedTime(file).toMillis() );
ChecksummedFile checksummedFile = new ChecksummedFile( file.toPath() ); ChecksummedFile checksummedFile = new ChecksummedFile( file );
try try
{ {
metadata.setMd5( checksummedFile.calculateChecksum( ChecksumAlgorithm.MD5 ) ); metadata.setMd5( checksummedFile.calculateChecksum( ChecksumAlgorithm.MD5 ) );
@ -900,27 +884,26 @@ public class Maven2RepositoryStorage
{ {
LOGGER.error( "Unable to checksum file {}: {},SHA1", file, e.getMessage() ); 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 // scan directories for a valid project version subdirectory, meaning this must be a project directory
File[] files = dir.listFiles( new DirectoryFilter( filter ) ); final Predicate<Path> dFilter = new DirectoryFilter(filter);
if ( files != null ) try(Stream<Path> stream = Files.list(dir)) {
{ boolean projFound = stream.filter(dFilter)
for ( File file : files ) .anyMatch(path -> isProjectVersion(path));
{ if (projFound) {
if ( isProjectVersion( file ) )
{
return true; 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 // if a metadata file is present, check if this is the "artifactId" directory, marking it as a project
ArchivaRepositoryMetadata metadata = readMetadata( dir ); ArchivaRepositoryMetadata metadata = readMetadata( dir );
if ( metadata != null && dir.getName().equals( metadata.getArtifactId() ) ) if ( metadata != null && dir.getFileName().toString().equals( metadata.getArtifactId() ) )
{ {
return true; return true;
} }
@ -928,26 +911,30 @@ public class Maven2RepositoryStorage
return false; return false;
} }
private boolean isProjectVersion( File dir ) private boolean isProjectVersion( Path dir )
{ {
final String artifactId = dir.getParentFile().getName(); final String artifactId = dir.getParent().getFileName().toString();
final String projectVersion = dir.getName(); final String projectVersion = dir.getFileName().toString();
// check if there is a POM artifact file to ensure it is a version directory // check if there is a POM artifact file to ensure it is a version directory
File[] files;
Predicate<Path> filter;
if ( VersionUtil.isSnapshot( projectVersion ) ) if ( VersionUtil.isSnapshot( projectVersion ) )
{ {
files = dir.listFiles( new PomFilenameFilter( artifactId, projectVersion ) ); filter = new PomFilenameFilter(artifactId, projectVersion);
} }
else else
{ {
final String pomFile = artifactId + "-" + projectVersion + ".pom"; final String pomFile = artifactId + "-" + projectVersion + ".pom";
files = dir.listFiles( new PomFileFilter( pomFile ) ); filter = new PomFileFilter(pomFile);
} }
if ( files != null && files.length > 0 ) try(Stream<Path> stream = Files.list(dir)) {
{ if (stream.filter(Files::isRegularFile).anyMatch(filter)){
return true; 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 // if a metadata file is present, check if this is the "version" directory, marking it as a project version
ArchivaRepositoryMetadata metadata = readMetadata( dir ); ArchivaRepositoryMetadata metadata = readMetadata( dir );
@ -959,15 +946,15 @@ public class Maven2RepositoryStorage
return false; return false;
} }
private ArchivaRepositoryMetadata readMetadata( File directory ) private ArchivaRepositoryMetadata readMetadata( Path directory )
{ {
ArchivaRepositoryMetadata metadata = null; ArchivaRepositoryMetadata metadata = null;
File metadataFile = new File( directory, METADATA_FILENAME ); Path metadataFile = directory.resolve( METADATA_FILENAME );
if ( metadataFile.exists() ) if ( Files.exists(metadataFile) )
{ {
try try
{ {
metadata = MavenMetadataReader.read( metadataFile.toPath() ); metadata = MavenMetadataReader.read( metadataFile );
} }
catch ( XMLException e ) catch ( XMLException e )
{ {
@ -978,7 +965,7 @@ public class Maven2RepositoryStorage
} }
private static class DirectoryFilter private static class DirectoryFilter
implements FilenameFilter implements Predicate<Path>
{ {
private final Filter<String> filter; private final Filter<String> filter;
@ -988,8 +975,9 @@ public class Maven2RepositoryStorage
} }
@Override @Override
public boolean accept( File dir, String name ) public boolean test( Path dir )
{ {
final String name = dir.getFileName().toString();
if ( !filter.accept( name ) ) if ( !filter.accept( name ) )
{ {
return false; return false;
@ -998,7 +986,7 @@ public class Maven2RepositoryStorage
{ {
return false; return false;
} }
else if ( !new File( dir, name ).isDirectory() ) else if ( !Files.isDirectory(dir))
{ {
return false; return false;
} }
@ -1007,7 +995,7 @@ public class Maven2RepositoryStorage
} }
private static class ArtifactDirectoryFilter private static class ArtifactDirectoryFilter
implements FilenameFilter implements Predicate<Path>
{ {
private final Filter<String> filter; private final Filter<String> filter;
@ -1017,8 +1005,9 @@ public class Maven2RepositoryStorage
} }
@Override @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 // TODO compare to logic in maven-repository-layer
if ( !filter.accept( name ) ) if ( !filter.accept( name ) )
{ {
@ -1036,7 +1025,7 @@ public class Maven2RepositoryStorage
{ {
return false; return false;
} }
else if ( new File( dir, name ).isDirectory() ) else if ( Files.isDirectory(dir) )
{ {
return false; return false;
} }
@ -1053,7 +1042,7 @@ public class Maven2RepositoryStorage
private static final class PomFilenameFilter private static final class PomFilenameFilter
implements FilenameFilter implements Predicate<Path>
{ {
private final String artifactId, projectVersion; private final String artifactId, projectVersion;
@ -1065,8 +1054,9 @@ public class Maven2RepositoryStorage
} }
@Override @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" ) ) if ( name.startsWith( artifactId + "-" ) && name.endsWith( ".pom" ) )
{ {
String v = name.substring( artifactId.length() + 1, name.length() - 4 ); String v = name.substring( artifactId.length() + 1, name.length() - 4 );
@ -1078,10 +1068,11 @@ public class Maven2RepositoryStorage
} }
return false; return false;
} }
} }
private static class PomFileFilter private static class PomFileFilter
implements FilenameFilter implements Predicate<Path>
{ {
private final String pomFile; private final String pomFile;
@ -1091,9 +1082,9 @@ public class Maven2RepositoryStorage
} }
@Override @Override
public boolean accept( File dir, String name ) public boolean test( Path dir )
{ {
return pomFile.equals( name ); return pomFile.equals( dir.getFileName().toString());
} }
} }

View File

@ -31,7 +31,6 @@ import org.apache.archiva.proxy.common.WagonFactory;
import org.apache.archiva.proxy.common.WagonFactoryException; import org.apache.archiva.proxy.common.WagonFactoryException;
import org.apache.archiva.proxy.common.WagonFactoryRequest; import org.apache.archiva.proxy.common.WagonFactoryRequest;
import org.apache.archiva.xml.XMLException; import org.apache.archiva.xml.XMLException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.maven.model.Repository; import org.apache.maven.model.Repository;
import org.apache.maven.model.building.FileModelSource; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
public class RepositoryModelResolver public class RepositoryModelResolver
implements ModelResolver implements ModelResolver
{ {
private File basedir; private Path basedir;
private RepositoryPathTranslator pathTranslator; private RepositoryPathTranslator pathTranslator;
@ -78,7 +78,7 @@ public class RepositoryModelResolver
private ManagedRepository managedRepository; private ManagedRepository managedRepository;
public RepositoryModelResolver( File basedir, RepositoryPathTranslator pathTranslator ) public RepositoryModelResolver( Path basedir, RepositoryPathTranslator pathTranslator )
{ {
this.basedir = basedir; this.basedir = basedir;
@ -89,7 +89,7 @@ public class RepositoryModelResolver
WagonFactory wagonFactory, List<RemoteRepository> remoteRepositories, WagonFactory wagonFactory, List<RemoteRepository> remoteRepositories,
Map<String, NetworkProxy> networkProxiesMap, ManagedRepository targetRepository ) Map<String, NetworkProxy> networkProxiesMap, ManagedRepository targetRepository )
{ {
this( new File( managedRepository.getLocation() ), pathTranslator ); this( Paths.get( managedRepository.getLocation() ), pathTranslator );
this.managedRepository = managedRepository; this.managedRepository = managedRepository;
@ -109,9 +109,9 @@ public class RepositoryModelResolver
String filename = artifactId + "-" + version + ".pom"; 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 // 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. // is a SNAPSHOT ? so we can try to find locally before asking remote repositories.
if ( StringUtils.contains( version, VersionUtil.SNAPSHOT ) ) 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 ) if ( localSnapshotModel != null )
{ {
return new FileModelSource( localSnapshotModel ); return new FileModelSource( localSnapshotModel.toFile() );
} }
} }
@ -132,10 +132,10 @@ public class RepositoryModelResolver
try try
{ {
boolean success = getModelFromProxy( remoteRepository, groupId, artifactId, version, filename ); 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 '{}'", log.info( "Model '{}' successfully retrieved from remote repository '{}'",
model.getAbsolutePath(), remoteRepository.getId() ); model.toAbsolutePath(), remoteRepository.getId() );
break; break;
} }
} }
@ -143,33 +143,33 @@ public class RepositoryModelResolver
{ {
log.info( log.info(
"An exception was caught while attempting to retrieve model '{}' from remote repository '{}'.Reason:{}", "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 ) catch ( Exception e )
{ {
log.warn( log.warn(
"An exception was caught while attempting to retrieve model '{}' from remote repository '{}'.Reason:{}", "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; 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 ) String parentDirectory )
{ {
// reading metadata if there // reading metadata if there
File mavenMetadata = new File( parentDirectory, METADATA_FILENAME ); Path mavenMetadata = Paths.get( parentDirectory, METADATA_FILENAME );
if ( mavenMetadata.exists() ) if ( Files.exists(mavenMetadata) )
{ {
try try
{ {
ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read( mavenMetadata.toPath() ); ArchivaRepositoryMetadata archivaRepositoryMetadata = MavenMetadataReader.read( mavenMetadata);
SnapshotVersion snapshotVersion = archivaRepositoryMetadata.getSnapshotVersion(); SnapshotVersion snapshotVersion = archivaRepositoryMetadata.getSnapshotVersion();
if ( snapshotVersion != null ) if ( snapshotVersion != null )
{ {
@ -183,9 +183,9 @@ public class RepositoryModelResolver
log.debug( "use snapshot path {} for maven coordinate {}:{}:{}", snapshotPath, groupId, artifactId, log.debug( "use snapshot path {} for maven coordinate {}:{}:{}", snapshotPath, groupId, artifactId,
version ); version );
File model = new File( basedir, snapshotPath ); Path model = basedir.resolve( snapshotPath );
//model = pathTranslator.toFile( basedir, groupId, artifactId, lastVersion, filename ); //model = pathTranslator.toFile( basedir, groupId, artifactId, lastVersion, filename );
if ( model.exists() ) if ( Files.exists(model) )
{ {
return model; return model;
} }
@ -193,7 +193,7 @@ public class RepositoryModelResolver
} }
catch ( XMLException e ) 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 XMLException, IOException
{ {
boolean success = false; boolean success = false;
File tmpMd5 = null; Path tmpMd5 = null;
File tmpSha1 = null; Path tmpSha1 = null;
File tmpResource = null; Path tmpResource = null;
String artifactPath = pathTranslator.toPath( groupId, artifactId, version, filename ); 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 try
{ {
Wagon wagon = null; Wagon wagon = null;
@ -252,21 +252,21 @@ public class RepositoryModelResolver
boolean connected = connectToRepository( wagon, remoteRepository ); boolean connected = connectToRepository( wagon, remoteRepository );
if ( connected ) if ( connected )
{ {
tmpResource = new File( workingDirectory, filename ); tmpResource = workingDirectory.resolve( filename );
if ( VersionUtil.isSnapshot( version ) ) if ( VersionUtil.isSnapshot( version ) )
{ {
// get the metadata first! // get the metadata first!
File tmpMetadataResource = new File( workingDirectory, METADATA_FILENAME ); Path tmpMetadataResource = workingDirectory.resolve( METADATA_FILENAME );
String metadataPath = String metadataPath =
StringUtils.substringBeforeLast( artifactPath, "/" ) + "/" + METADATA_FILENAME; StringUtils.substringBeforeLast( artifactPath, "/" ) + "/" + METADATA_FILENAME;
wagon.get( addParameters( metadataPath, remoteRepository ), tmpMetadataResource ); wagon.get( addParameters( metadataPath, remoteRepository ), tmpMetadataResource.toFile() );
log.debug( "Successfully downloaded metadata." ); 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 // re-adjust to timestamp if present, otherwise retain the original -SNAPSHOT filename
SnapshotVersion snapshotVersion = metadata.getSnapshotVersion(); SnapshotVersion snapshotVersion = metadata.getSnapshotVersion();
@ -288,7 +288,7 @@ public class RepositoryModelResolver
log.info( "Retrieving {} from {}", artifactPath, remoteRepository.getName() ); log.info( "Retrieving {} from {}", artifactPath, remoteRepository.getName() );
wagon.get( addParameters( artifactPath, remoteRepository ), tmpResource ); wagon.get( addParameters( artifactPath, remoteRepository ), tmpResource.toFile() );
log.debug( "Downloaded successfully." ); log.debug( "Downloaded successfully." );
@ -315,9 +315,9 @@ public class RepositoryModelResolver
if ( resource != null ) if ( resource != null )
{ {
synchronized ( resource.getAbsolutePath().intern() ) synchronized ( resource.toAbsolutePath().toString().intern() )
{ {
File directory = resource.getParentFile(); Path directory = resource.getParent();
moveFileIfExists( tmpMd5, directory ); moveFileIfExists( tmpMd5, directory );
moveFileIfExists( tmpSha1, directory ); moveFileIfExists( tmpSha1, directory );
moveFileIfExists( tmpResource, directory ); moveFileIfExists( tmpResource, directory );
@ -327,7 +327,7 @@ public class RepositoryModelResolver
} }
finally finally
{ {
FileUtils.deleteQuietly( workingDirectory ); org.apache.archiva.common.utils.FileUtils.deleteQuietly( workingDirectory );
} }
// do we still need to execute the consumers? // do we still need to execute the consumers?
@ -426,17 +426,17 @@ public class RepositoryModelResolver
* @throws TransferFailedException * @throws TransferFailedException
* @throws ResourceDoesNotExistException * @throws ResourceDoesNotExistException
*/ */
private File transferChecksum( final Wagon wagon, final RemoteRepository remoteRepository, private Path transferChecksum( final Wagon wagon, final RemoteRepository remoteRepository,
final String remotePath, final File resource, final String remotePath, final Path resource,
final File workingDir, final String ext ) final Path workingDir, final String ext )
throws AuthorizationException, TransferFailedException, ResourceDoesNotExistException throws AuthorizationException, TransferFailedException, ResourceDoesNotExistException
{ {
File destFile = new File( workingDir, resource.getName() + ext ); Path destFile = workingDir.resolve( resource.getFileName() + ext );
String remoteChecksumPath = remotePath + ext; String remoteChecksumPath = remotePath + ext;
log.info( "Retrieving {} from {}", remoteChecksumPath, remoteRepository.getName() ); log.info( "Retrieving {} from {}", remoteChecksumPath, remoteRepository.getName() );
wagon.get( addParameters( remoteChecksumPath, remoteRepository ), destFile ); wagon.get( addParameters( remoteChecksumPath, remoteRepository ), destFile.toFile() );
log.debug( "Downloaded successfully." ); log.debug( "Downloaded successfully." );
@ -450,49 +450,45 @@ public class RepositoryModelResolver
return protocol; return protocol;
} }
private File createWorkingDirectory( String targetRepository ) private Path createWorkingDirectory( String targetRepository )
throws IOException 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( throw new RuntimeException(
"Unable to overwrite existing target file: " + newLocation.getAbsolutePath() ); "Unable to overwrite existing target file: " + newLocation.toAbsolutePath(), e );
} }
newLocation.getParentFile().mkdirs(); try {
if ( !fileToMove.renameTo( newLocation ) ) Files.createDirectories(newLocation.getParent());
{ } catch (IOException e) {
log.warn( "Unable to rename tmp file to its final name... resorting to copy command." ); e.printStackTrace();
try
{
FileUtils.copyFile( fileToMove, newLocation );
} }
catch ( IOException e ) try {
{ Files.move(fileToMove, newLocation );
if ( newLocation.exists() ) } 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.", log.error( "Tried to copy file {} to {} but file with this name already exists.",
fileToMove.getName(), newLocation.getAbsolutePath() ); fileToMove.getFileName(), newLocation.toAbsolutePath() );
} } else {
else
{
throw new RuntimeException( 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 } finally {
{ org.apache.archiva.common.utils.FileUtils.deleteQuietly(fileToMove);
FileUtils.deleteQuietly( fileToMove );
}
} }
} }
} }

View File

@ -20,7 +20,6 @@ package org.apache.archiva.repository.content.maven2;
*/ */
import org.apache.archiva.admin.model.beans.ManagedRepository; 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.configuration.FileTypes;
import org.apache.archiva.metadata.repository.storage.maven2.DefaultArtifactMappingProvider; import org.apache.archiva.metadata.repository.storage.maven2.DefaultArtifactMappingProvider;
import org.apache.archiva.model.ArchivaArtifact; 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.ManagedRepositoryContent;
import org.apache.archiva.repository.RepositoryException; import org.apache.archiva.repository.RepositoryException;
import org.apache.archiva.repository.layout.LayoutException; import org.apache.archiva.repository.layout.LayoutException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** /**
* ManagedDefaultRepositoryContent * ManagedDefaultRepositoryContent
@ -72,33 +72,33 @@ public class ManagedDefaultRepositoryContent
public void deleteVersion( VersionedReference reference ) public void deleteVersion( VersionedReference reference )
{ {
String path = toMetadataPath( reference ); String path = toMetadataPath( reference );
File projectPath = new File( getRepoRoot(), path ); Path projectPath = Paths.get( getRepoRoot(), path );
File projectDir = projectPath.getParentFile(); Path projectDir = projectPath.getParent();
if ( projectDir.exists() && projectDir.isDirectory() ) if ( Files.exists(projectDir) && Files.isDirectory(projectDir) )
{ {
FileUtils.deleteQuietly( projectDir ); org.apache.archiva.common.utils.FileUtils.deleteQuietly( projectDir );
} }
} }
@Override @Override
public void deleteProject( String namespace, String projectId ) public void deleteProject( String namespace, String projectId )
throws RepositoryException, ContentNotFoundException throws RepositoryException
{ {
ArtifactReference artifactReference = new ArtifactReference(); ArtifactReference artifactReference = new ArtifactReference();
artifactReference.setGroupId( namespace ); artifactReference.setGroupId( namespace );
artifactReference.setArtifactId( projectId ); artifactReference.setArtifactId( projectId );
String path = toPath( artifactReference ); String path = toPath( artifactReference );
File directory = new File( getRepoRoot(), path ); Path directory = Paths.get( getRepoRoot(), path );
if ( !directory.exists() ) if ( !Files.exists(directory) )
{ {
throw new ContentNotFoundException( "cannot found project " + namespace + ":" + projectId ); throw new ContentNotFoundException( "cannot found project " + namespace + ":" + projectId );
} }
if ( directory.isDirectory() ) if ( Files.isDirectory(directory) )
{ {
try try
{ {
FileUtils.deleteDirectory( directory ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( directory );
} }
catch ( IOException e ) catch ( IOException e )
{ {
@ -116,25 +116,25 @@ public class ManagedDefaultRepositoryContent
public void deleteArtifact( ArtifactReference artifactReference ) public void deleteArtifact( ArtifactReference artifactReference )
{ {
String path = toPath( 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, '.', '/' ); 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 try
{ {
FileUtils.deleteDirectory( directory ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( directory );
} }
catch ( IOException e ) 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 throws ContentNotFoundException
{ {
Path artifactFile = toFile( reference ); Path artifactFile = toFile( reference );
Path repoDir = artifactFile.getParent(); Path repoBase = Paths.get(repository.getLocation()).toAbsolutePath();
Path repoDir = artifactFile.getParent().toAbsolutePath();
if ( !Files.exists(repoDir)) if ( !Files.exists(repoDir))
{ {
@ -185,37 +186,29 @@ public class ManagedDefaultRepositoryContent
"Unable to get related artifacts using a non-directory: " + repoDir.toAbsolutePath() ); "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. // 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. try (Stream<Path> stream = Files.list(repoDir)) {
if ( artifact.getGroupId().equals( reference.getGroupId() ) && artifact.getArtifactId().equals( foundArtifacts = stream.filter(Files::isRegularFile).map(path -> {
reference.getArtifactId() ) && artifact.getVersion().equals( reference.getVersion() ) ) try {
{ ArtifactReference artifact = toArtifactReference(repoBase.relativize(path).toString());
foundArtifacts.add( artifact ); 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() ); 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; return foundArtifacts;
} }
@ -251,43 +244,45 @@ public class ManagedDefaultRepositoryContent
path = path.substring( 0, idx ); 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( 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( 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<>(); final String groupId = reference.getGroupId();
VersionedReference versionRef = new VersionedReference(); final String artifactId = reference.getArtifactId();
versionRef.setGroupId( reference.getGroupId() ); try(Stream<Path> stream = Files.list(repoDir)) {
versionRef.setArtifactId( reference.getArtifactId() ); return stream.filter(Files::isDirectory).map(
p -> newVersionedRef(groupId, artifactId, p.getFileName().toString())
File repoFiles[] = repoDir.listFiles(); ).filter(this::hasArtifact).map(ref -> ref.getVersion())
for (File repoFile : repoFiles) .collect(Collectors.toSet());
{ } catch (IOException e) {
if (!repoFile.isDirectory()) { log.error("Could not read directory {}: {}", repoDir, e.getMessage(), e);
// Skip it. not a directory. } catch (RuntimeException e) {
continue; if (e.getCause()!=null && e.getCause() instanceof LayoutException) {
throw (LayoutException)e.getCause();
} else {
throw e;
} }
// 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 );
} }
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 @Override
@ -302,52 +297,42 @@ public class ManagedDefaultRepositoryContent
path = path.substring( 0, idx ); 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( 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( 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<>(); Set<String> foundVersions = new HashSet<>();
// First gather up the versions found as artifacts in the managed repository. try(Stream<Path> stream = Files.list(repoDir)) {
File repoFiles[] = repoDir.listFiles(); return stream.filter(Files::isRegularFile)
for (File repoFile : repoFiles) .map(p -> repoBase.relativize(p).toString())
{ .filter(p -> !filetypes.matchesDefaultExclusions(p))
if (repoFile.isDirectory()) { .filter(filetypes::matchesArtifactPattern)
// Skip it. it's a directory. .map(path1 -> {
continue; try {
} return toArtifactReference(path1);
String relativePath = PathUtil.getRelative(repository.getLocation(), repoFile); } catch (LayoutException e) {
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() ); 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 Collections.emptySet();
return foundVersions;
} }
@Override @Override
@ -408,6 +393,17 @@ public class ManagedDefaultRepositoryContent
return super.toArtifactReference( path ); 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 @Override
public Path toFile( ArtifactReference reference ) public Path toFile( ArtifactReference reference )
{ {
@ -440,42 +436,37 @@ public class ManagedDefaultRepositoryContent
path = path.substring( 0, idx ); 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: " 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( 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() );
} }
try(Stream<Path> stream = Files.list(repoDir)) {
File repoFiles[] = repoDir.listFiles(); return stream.filter(Files::isRegularFile)
for (File repoFile : repoFiles) .map(p -> repoBase.relativize(p).toString())
{ .filter(filetypes::matchesArtifactPattern)
if (repoFile.isDirectory()) { .map(this::toArtifactRef).findFirst().orElse(null);
// Skip it. it's a directory. } catch (RuntimeException e) {
continue; if (e.getCause()!=null && e.getCause() instanceof LayoutException) {
} throw (LayoutException)e.getCause();
String relativePath = PathUtil.getRelative(repository.getLocation(), repoFile); } else {
if ( filetypes.matchesArtifactPattern( relativePath ) ) throw e;
{
ArtifactReference artifact = toArtifactReference( relativePath );
return artifact;
} }
} }
// No artifact was found.
return null;
} }
private boolean hasArtifact( VersionedReference reference ) private boolean hasArtifact( VersionedReference reference )
throws LayoutException
{ {
try try
{ {
@ -484,6 +475,9 @@ public class ManagedDefaultRepositoryContent
catch ( IOException e ) catch ( IOException e )
{ {
return false; return false;
} catch (LayoutException e) {
// We throw the runtime exception for better stream handling
throw new RuntimeException(e);
} }
} }

View File

@ -27,7 +27,6 @@ import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
import org.apache.archiva.maven2.model.Artifact; import org.apache.archiva.maven2.model.Artifact;
import org.apache.archiva.maven2.model.TreeEntry; import org.apache.archiva.maven2.model.TreeEntry;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -35,10 +34,12 @@ import org.springframework.test.context.ContextConfiguration;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import java.io.File; import java.nio.file.Paths;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith( ArchivaSpringJUnit4ClassRunner.class ) @RunWith( ArchivaSpringJUnit4ClassRunner.class )
@ContextConfiguration( { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } ) @ContextConfiguration( { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
public class DependencyTreeBuilderTestMaven3 public class DependencyTreeBuilderTestMaven3
@ -74,7 +75,7 @@ public class DependencyTreeBuilderTestMaven3
Configuration configuration = new Configuration(); Configuration configuration = new Configuration();
ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration(); ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration();
repoConfig.setId( TEST_REPO_ID ); 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 ); configuration.addManagedRepository( repoConfig );
config.save( configuration ); config.save( configuration );

View File

@ -34,12 +34,9 @@ import org.junit.Test;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import java.io.File; import java.nio.file.Path;
import java.util.ArrayList; import java.nio.file.Paths;
import java.util.Arrays; import java.util.*;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -65,7 +62,7 @@ public class ManagedDefaultRepositoryContentTest
public void setUp() public void setUp()
throws Exception 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 ); 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 // Use the test metadata-repository, which is already setup for
// These kind of version tests. // These kind of version tests.
File repoDir = new File( "src/test/repositories/metadata-repository" ); Path repoDir = Paths.get( "src/test/repositories/metadata-repository" );
repoContent.getRepository().setLocation( repoDir.getAbsolutePath() ); repoContent.getRepository().setLocation( repoDir.toAbsolutePath().toString() );
// Request the versions. // Request the versions.
Set<String> testedVersionSet = repoContent.getVersions( reference ); Set<String> testedVersionSet = repoContent.getVersions( reference );
@ -203,8 +200,8 @@ public class ManagedDefaultRepositoryContentTest
// Use the test metadata-repository, which is already setup for // Use the test metadata-repository, which is already setup for
// These kind of version tests. // These kind of version tests.
File repoDir = new File( "src/test/repositories/metadata-repository" ); Path repoDir = Paths.get( "src/test/repositories/metadata-repository" );
repoContent.getRepository().setLocation( repoDir.getAbsolutePath() ); repoContent.getRepository().setLocation( repoDir.toAbsolutePath().toString() );
// Request the versions. // Request the versions.
Set<String> testedVersionSet = repoContent.getVersions( reference ); Set<String> testedVersionSet = repoContent.getVersions( reference );

View File

@ -20,17 +20,8 @@ package org.apache.archiva.metadata.repository.storage.maven2;
*/ */
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.archiva.configuration.ArchivaConfiguration; import org.apache.archiva.configuration.*;
import org.apache.archiva.configuration.Configuration; import org.apache.archiva.metadata.model.*;
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.metadata.repository.filter.AllFilter; import org.apache.archiva.metadata.repository.filter.AllFilter;
import org.apache.archiva.metadata.repository.filter.Filter; import org.apache.archiva.metadata.repository.filter.Filter;
import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest; 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.Inject;
import javax.inject.Named; import javax.inject.Named;
import java.io.File;
import java.io.IOException; 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.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -114,14 +107,14 @@ public class Maven2RepositoryMetadataResolverMRM1411RepoGroupTest
testRepo = new ManagedRepositoryConfiguration(); testRepo = new ManagedRepositoryConfiguration();
testRepo.setId( TEST_REPO_ID ); 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.setReleases( true );
testRepo.setSnapshots( false ); testRepo.setSnapshots( false );
c.addManagedRepository( testRepo ); c.addManagedRepository( testRepo );
testRepoS = new ManagedRepositoryConfiguration(); testRepoS = new ManagedRepositoryConfiguration();
testRepoS.setId( TEST_SNAP_REPO_ID ); 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.setReleases( false );
testRepoS.setSnapshots( true ); testRepoS.setSnapshots( true );
c.addManagedRepository( testRepoS ); c.addManagedRepository( testRepoS );
@ -493,33 +486,32 @@ public class Maven2RepositoryMetadataResolverMRM1411RepoGroupTest
{ {
for ( String path : pathsToBeDeleted ) for ( String path : pathsToBeDeleted )
{ {
File dir = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), path ); Path dir = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), path );
FileUtils.deleteDirectory( dir ); 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" ); Path dest = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-module-a" );
File parentPom = Path parentPom = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-parent" );
new File( 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" );
File rootPom = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-root" );
FileUtils.deleteDirectory( dest ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( dest );
FileUtils.deleteDirectory( parentPom ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( parentPom );
FileUtils.deleteDirectory( rootPom ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( rootPom );
assertFalse( dest.exists() ); assertFalse( Files.exists(dest) );
assertFalse( parentPom.exists() ); assertFalse( Files.exists(parentPom) );
assertFalse( rootPom.exists() ); assertFalse( Files.exists(rootPom) );
} }
private File copyTestArtifactWithParent( String srcPath, String destPath ) private Path copyTestArtifactWithParent( String srcPath, String destPath )
throws IOException throws IOException
{ {
File src = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), srcPath ); Path src = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), srcPath );
File dest = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), destPath ); Path dest = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), destPath );
FileUtils.copyDirectory( src, dest ); FileUtils.copyDirectory( src.toFile(), dest.toFile() );
assertTrue( dest.exists() ); assertTrue( Files.exists(dest) );
return dest; return dest;
} }

View File

@ -20,16 +20,8 @@ package org.apache.archiva.metadata.repository.storage.maven2;
*/ */
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.archiva.configuration.ArchivaConfiguration; import org.apache.archiva.configuration.*;
import org.apache.archiva.configuration.Configuration; import org.apache.archiva.metadata.model.*;
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.metadata.repository.filter.AllFilter; import org.apache.archiva.metadata.repository.filter.AllFilter;
import org.apache.archiva.metadata.repository.filter.Filter; import org.apache.archiva.metadata.repository.filter.Filter;
import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest; 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.Inject;
import javax.inject.Named; import javax.inject.Named;
import java.io.File;
import java.io.IOException; 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.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@ -107,7 +101,7 @@ public class Maven2RepositoryMetadataResolverMRM1411Test
c = new Configuration(); c = new Configuration();
testRepo = new ManagedRepositoryConfiguration(); testRepo = new ManagedRepositoryConfiguration();
testRepo.setId( TEST_REPO_ID ); 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.setReleases( true );
testRepo.setSnapshots( true ); testRepo.setSnapshots( true );
c.addManagedRepository( testRepo ); c.addManagedRepository( testRepo );
@ -397,33 +391,33 @@ public class Maven2RepositoryMetadataResolverMRM1411Test
{ {
for ( String path : pathsToBeDeleted ) for ( String path : pathsToBeDeleted )
{ {
File dir = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), path ); Path dir = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), path );
FileUtils.deleteDirectory( dir ); 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" ); Path dest = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-module-a" );
File parentPom = Path parentPom =
new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-parent" ); Paths.get( 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" ); Path rootPom = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-root" );
FileUtils.deleteDirectory( dest ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( dest );
FileUtils.deleteDirectory( parentPom ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( parentPom );
FileUtils.deleteDirectory( rootPom ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( rootPom );
assertFalse( dest.exists() ); assertFalse( Files.exists(dest) );
assertFalse( parentPom.exists() ); assertFalse( Files.exists(parentPom) );
assertFalse( rootPom.exists() ); assertFalse( Files.exists(rootPom) );
} }
private File copyTestArtifactWithParent( String srcPath, String destPath ) private Path copyTestArtifactWithParent( String srcPath, String destPath )
throws IOException throws IOException
{ {
File src = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), srcPath ); Path src = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), srcPath );
File dest = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), destPath ); Path dest = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), destPath );
FileUtils.copyDirectory( src, dest ); FileUtils.copyDirectory( src.toFile(), dest.toFile() );
assertTrue( dest.exists() ); assertTrue( Files.exists(dest) );
return dest; return dest;
} }

View File

@ -20,16 +20,8 @@ package org.apache.archiva.metadata.repository.storage.maven2;
*/ */
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.archiva.configuration.ArchivaConfiguration; import org.apache.archiva.configuration.*;
import org.apache.archiva.configuration.Configuration; import org.apache.archiva.metadata.model.*;
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.metadata.model.maven2.MavenArtifactFacet; import org.apache.archiva.metadata.model.maven2.MavenArtifactFacet;
import org.apache.archiva.metadata.repository.filter.AllFilter; import org.apache.archiva.metadata.repository.filter.AllFilter;
import org.apache.archiva.metadata.repository.filter.ExcludesFilter; 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.Inject;
import javax.inject.Named; import javax.inject.Named;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -117,7 +103,7 @@ public class Maven2RepositoryMetadataResolverTest
c = new Configuration(); c = new Configuration();
testRepo = new ManagedRepositoryConfiguration(); testRepo = new ManagedRepositoryConfiguration();
testRepo.setId( TEST_REPO_ID ); 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.setReleases( true );
testRepo.setSnapshots( true ); testRepo.setSnapshots( true );
c.addManagedRepository( testRepo ); c.addManagedRepository( testRepo );
@ -771,33 +757,33 @@ public class Maven2RepositoryMetadataResolverTest
{ {
for ( String path : pathsToBeDeleted ) for ( String path : pathsToBeDeleted )
{ {
File dir = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), path ); Path dir = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), path );
FileUtils.deleteDirectory( dir ); 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" ); Path dest = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-module-a" );
File parentPom = Path parentPom =
new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-parent" ); Paths.get( 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" ); Path rootPom = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "target/test-repository/com/example/test/test-artifact-root" );
FileUtils.deleteDirectory( dest ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( dest );
FileUtils.deleteDirectory( parentPom ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( parentPom );
FileUtils.deleteDirectory( rootPom ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( rootPom );
assertFalse( dest.exists() ); assertFalse( Files.exists(dest) );
assertFalse( parentPom.exists() ); assertFalse( Files.exists(parentPom) );
assertFalse( rootPom.exists() ); assertFalse( Files.exists(rootPom) );
} }
private File copyTestArtifactWithParent( String srcPath, String destPath ) private Path copyTestArtifactWithParent( String srcPath, String destPath )
throws IOException throws IOException
{ {
File src = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), srcPath ); Path src = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), srcPath );
File dest = new File( org.apache.archiva.common.utils.FileUtils.getBasedir(), destPath ); Path dest = Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), destPath );
FileUtils.copyDirectory( src, dest ); FileUtils.copyDirectory( src.toFile(), dest.toFile() );
assertTrue( dest.exists() ); assertTrue( Files.exists(dest) );
return dest; return dest;
} }

View File

@ -23,14 +23,15 @@ import junit.framework.TestCase;
import org.apache.archiva.maven2.metadata.MavenMetadataReader; import org.apache.archiva.maven2.metadata.MavenMetadataReader;
import org.apache.archiva.model.ArchivaRepositoryMetadata; import org.apache.archiva.model.ArchivaRepositoryMetadata;
import org.apache.archiva.model.Plugin; import org.apache.archiva.model.Plugin;
import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
import org.apache.archiva.xml.XMLException; import org.apache.archiva.xml.XMLException;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import java.io.File; import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays; import java.util.Arrays;
import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
/** /**
* RepositoryMetadataReaderTest * RepositoryMetadataReaderTest
@ -41,15 +42,15 @@ import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
public class MavenRepositoryMetadataReaderTest public class MavenRepositoryMetadataReaderTest
extends TestCase extends TestCase
{ {
private File defaultRepoDir; private Path defaultRepoDir;
@Test @Test
public void testGroupMetadata() public void testGroupMetadata()
throws XMLException 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 ); assertNotNull( metadata );
assertEquals( "org.apache.maven.plugins", metadata.getGroupId() ); assertEquals( "org.apache.maven.plugins", metadata.getGroupId() );
@ -82,9 +83,9 @@ public class MavenRepositoryMetadataReaderTest
public void testProjectMetadata() public void testProjectMetadata()
throws XMLException 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 ); assertNotNull( metadata );
assertEquals( "org.apache.maven.shared", metadata.getGroupId() ); assertEquals( "org.apache.maven.shared", metadata.getGroupId() );
@ -100,9 +101,9 @@ public class MavenRepositoryMetadataReaderTest
public void testProjectVersionMetadata() public void testProjectVersionMetadata()
throws XMLException 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 ); assertNotNull( metadata );
assertEquals( "org.apache", metadata.getGroupId() ); assertEquals( "org.apache", metadata.getGroupId() );
@ -122,6 +123,6 @@ public class MavenRepositoryMetadataReaderTest
throws Exception throws Exception
{ {
super.setUp(); super.setUp();
defaultRepoDir = new File( "target/test-repository" ); defaultRepoDir = Paths.get("target/test-repository");
} }
} }

View File

@ -21,15 +21,15 @@ package org.apache.archiva.repository;
import org.apache.archiva.admin.model.beans.ManagedRepository; import org.apache.archiva.admin.model.beans.ManagedRepository;
import org.apache.archiva.admin.model.beans.RemoteRepository; import org.apache.archiva.admin.model.beans.RemoteRepository;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.junit.Rule; import org.junit.Rule;
import org.junit.rules.TestName; import org.junit.rules.TestName;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import java.io.File;
import javax.inject.Inject; import javax.inject.Inject;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import java.nio.file.Path;
/** /**
* AbstractRepositoryLayerTestCase * AbstractRepositoryLayerTestCase
@ -46,12 +46,12 @@ public abstract class AbstractRepositoryLayerTestCase
@Inject @Inject
protected ApplicationContext applicationContext; 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(); ManagedRepository repo = new ManagedRepository();
repo.setId( id ); repo.setId( id );
repo.setName( name ); repo.setName( name );
repo.setLocation( location.getAbsolutePath() ); repo.setLocation( location.toAbsolutePath().toString() );
return repo; return repo;
} }
@ -64,14 +64,14 @@ public abstract class AbstractRepositoryLayerTestCase
return repo; return repo;
} }
protected ManagedRepositoryContent createManagedRepositoryContent( String id, String name, File location, protected ManagedRepositoryContent createManagedRepositoryContent( String id, String name, Path location,
String layout ) String layout )
throws Exception throws Exception
{ {
ManagedRepository repo = new ManagedRepository(); ManagedRepository repo = new ManagedRepository();
repo.setId( id ); repo.setId( id );
repo.setName( name ); repo.setName( name );
repo.setLocation( location.getAbsolutePath() ); repo.setLocation( location.toAbsolutePath().toString() );
repo.setLayout( layout ); repo.setLayout( layout );
ManagedRepositoryContent repoContent = ManagedRepositoryContent repoContent =

View File

@ -35,7 +35,8 @@ import org.springframework.test.context.ContextConfiguration;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import java.io.File; import java.nio.file.Path;
import java.nio.file.Paths;
import static org.junit.Assert.*; import static org.junit.Assert.*;
@ -368,7 +369,7 @@ public class RepositoryRequestTest
private ManagedRepositoryContent createManagedRepo( String layout ) private ManagedRepositoryContent createManagedRepo( String layout )
throws Exception 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 ); 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 ) String layout )
throws Exception throws Exception
{ {
ManagedRepository repo = new ManagedRepository(); ManagedRepository repo = new ManagedRepository();
repo.setId( id ); repo.setId( id );
repo.setName( name ); repo.setName( name );
repo.setLocation( location.getAbsolutePath() ); repo.setLocation( location.toAbsolutePath().toString() );
repo.setLayout( layout ); repo.setLayout( layout );
ManagedRepositoryContent repoContent = ManagedRepositoryContent repoContent =

View File

@ -22,6 +22,7 @@ package org.apache.archiva.repository.metadata;
import org.apache.archiva.admin.model.beans.ManagedRepository; import org.apache.archiva.admin.model.beans.ManagedRepository;
import org.apache.archiva.common.utils.VersionComparator; import org.apache.archiva.common.utils.VersionComparator;
import org.apache.archiva.configuration.ProxyConnectorConfiguration; 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.ProjectReference;
import org.apache.archiva.model.VersionedReference; import org.apache.archiva.model.VersionedReference;
import org.apache.archiva.policies.CachedFailuresPolicy; 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.policies.SnapshotsPolicy;
import org.apache.archiva.repository.AbstractRepositoryLayerTestCase; import org.apache.archiva.repository.AbstractRepositoryLayerTestCase;
import org.apache.archiva.repository.ManagedRepositoryContent; 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.RemoteRepositoryContent;
import org.apache.archiva.repository.layout.LayoutException; import org.apache.archiva.repository.layout.LayoutException;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
@ -44,9 +44,11 @@ import org.xml.sax.SAXException;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; 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.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -353,7 +355,7 @@ public class MetadataToolsTest
private void assertSnapshotVersions( String artifactId, String version, String[] expectedVersions ) private void assertSnapshotVersions( String artifactId, String version, String[] expectedVersions )
throws Exception throws Exception
{ {
File repoRootDir = new File( "src/test/repositories/metadata-repository" ); Path repoRootDir = Paths.get( "src/test/repositories/metadata-repository" );
VersionedReference reference = new VersionedReference(); VersionedReference reference = new VersionedReference();
reference.setGroupId( "org.apache.archiva.metadata.tests" ); reference.setGroupId( "org.apache.archiva.metadata.tests" );
@ -387,8 +389,8 @@ public class MetadataToolsTest
ProjectReference reference ) ProjectReference reference )
throws LayoutException, IOException, SAXException, ParserConfigurationException throws LayoutException, IOException, SAXException, ParserConfigurationException
{ {
File metadataFile = new File( repository.getRepoRoot(), tools.toPath( reference ) ); Path metadataFile = Paths.get( repository.getRepoRoot(), tools.toPath( reference ) );
String actualMetadata = FileUtils.readFileToString( metadataFile, Charset.defaultCharset() ); String actualMetadata = org.apache.archiva.common.utils.FileUtils.readFileToString( metadataFile, Charset.defaultCharset() );
DetailedDiff detailedDiff = new DetailedDiff( new Diff( expectedMetadata, actualMetadata ) ); DetailedDiff detailedDiff = new DetailedDiff( new Diff( expectedMetadata, actualMetadata ) );
if ( !detailedDiff.similar() ) if ( !detailedDiff.similar() )
@ -402,8 +404,8 @@ public class MetadataToolsTest
VersionedReference reference ) VersionedReference reference )
throws LayoutException, IOException, SAXException, ParserConfigurationException throws LayoutException, IOException, SAXException, ParserConfigurationException
{ {
File metadataFile = new File( repository.getRepoRoot(), tools.toPath( reference ) ); Path metadataFile = Paths.get( repository.getRepoRoot(), tools.toPath( reference ) );
String actualMetadata = FileUtils.readFileToString( metadataFile, Charset.defaultCharset() ); String actualMetadata = org.apache.archiva.common.utils.FileUtils.readFileToString( metadataFile, Charset.defaultCharset() );
DetailedDiff detailedDiff = new DetailedDiff( new Diff( expectedMetadata, actualMetadata ) ); DetailedDiff detailedDiff = new DetailedDiff( new Diff( expectedMetadata, actualMetadata ) );
if ( !detailedDiff.similar() ) if ( !detailedDiff.similar() )
@ -604,13 +606,13 @@ public class MetadataToolsTest
private ManagedRepositoryContent createTestRepoContent() private ManagedRepositoryContent createTestRepoContent()
throws Exception throws Exception
{ {
File repoRoot = new File( "target/metadata-tests/" + name.getMethodName() ); Path repoRoot = Paths.get( "target/metadata-tests/" + name.getMethodName() );
if ( repoRoot.exists() ) if ( Files.exists(repoRoot) )
{ {
FileUtils.deleteDirectory( repoRoot ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoRoot );
} }
repoRoot.mkdirs(); Files.createDirectories(repoRoot);
ManagedRepository repoConfig = ManagedRepository repoConfig =
createRepository( "test-repo", "Test Repository: " + name.getMethodName(), repoRoot ); createRepository( "test-repo", "Test Repository: " + name.getMethodName(), repoRoot );
@ -627,14 +629,14 @@ public class MetadataToolsTest
String groupDir = StringUtils.replaceChars( reference.getGroupId(), '.', '/' ); String groupDir = StringUtils.replaceChars( reference.getGroupId(), '.', '/' );
String path = groupDir + "/" + reference.getArtifactId(); String path = groupDir + "/" + reference.getArtifactId();
File srcRepoDir = new File( "src/test/repositories/metadata-repository" ); Path srcRepoDir = Paths.get( "src/test/repositories/metadata-repository" );
File srcDir = new File( srcRepoDir, path ); Path srcDir = srcRepoDir.resolve( path );
File destDir = new File( repo.getRepoRoot(), path ); Path destDir = Paths.get( repo.getRepoRoot(), path );
assertTrue( "Source Dir exists: " + srcDir, srcDir.exists() ); assertTrue( "Source Dir exists: " + srcDir, Files.exists(srcDir) );
destDir.mkdirs(); Files.createDirectories(destDir);
FileUtils.copyDirectory( srcDir, destDir ); FileUtils.copyDirectory( srcDir.toFile(), destDir.toFile() );
} }
private void prepTestRepo( ManagedRepositoryContent repo, VersionedReference reference ) private void prepTestRepo( ManagedRepositoryContent repo, VersionedReference reference )

View File

@ -22,12 +22,13 @@ package org.apache.archiva.repository.metadata;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.archiva.maven2.metadata.MavenMetadataReader; import org.apache.archiva.maven2.metadata.MavenMetadataReader;
import org.apache.archiva.model.ArchivaRepositoryMetadata; import org.apache.archiva.model.ArchivaRepositoryMetadata;
import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
import org.apache.archiva.xml.XMLException; import org.apache.archiva.xml.XMLException;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import java.io.File; import java.nio.file.Path;
import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner; import java.nio.file.Paths;
/** /**
* RepositoryMetadataReaderTest * RepositoryMetadataReaderTest
@ -42,10 +43,10 @@ public class RepositoryMetadataReaderTest
public void testLoadSimple() public void testLoadSimple()
throws XMLException throws XMLException
{ {
File defaultRepoDir = new File( "src/test/repositories/default-repository" ); Path defaultRepoDir = Paths.get( "src/test/repositories/default-repository" );
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 ); assertNotNull( metadata );
assertEquals( "Group Id", "org.apache.maven.shared", metadata.getGroupId() ); assertEquals( "Group Id", "org.apache.maven.shared", metadata.getGroupId() );
@ -60,10 +61,10 @@ public class RepositoryMetadataReaderTest
public void testLoadComplex() public void testLoadComplex()
throws XMLException throws XMLException
{ {
File defaultRepoDir = new File( "src/test/repositories/default-repository" ); Path defaultRepoDir = Paths.get( "src/test/repositories/default-repository" );
File metadataFile = new File( defaultRepoDir, "org/apache/maven/samplejar/maven-metadata.xml" ); Path metadataFile = defaultRepoDir.resolve( "org/apache/maven/samplejar/maven-metadata.xml" );
ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile.toPath() ); ArchivaRepositoryMetadata metadata = MavenMetadataReader.read( metadataFile );
assertNotNull( metadata ); assertNotNull( metadata );
assertEquals( "Group Id", "org.apache.maven", metadata.getGroupId() ); assertEquals( "Group Id", "org.apache.maven", metadata.getGroupId() );

View File

@ -22,14 +22,14 @@ package org.apache.archiva.repository.metadata;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.archiva.model.ArchivaRepositoryMetadata; import org.apache.archiva.model.ArchivaRepositoryMetadata;
import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaBlockJUnit4ClassRunner;
import org.apache.commons.io.FileUtils;
import org.custommonkey.xmlunit.XMLAssert; import org.custommonkey.xmlunit.XMLAssert;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import java.io.File;
import java.io.StringWriter; import java.io.StringWriter;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
/** /**
* RepositoryMetadataWriterTest * RepositoryMetadataWriterTest
@ -43,9 +43,9 @@ public class RepositoryMetadataWriterTest
public void testWriteSimple() public void testWriteSimple()
throws Exception throws Exception
{ {
File defaultRepoDir = new File( "src/test/repositories/default-repository" ); Path defaultRepoDir = Paths.get( "src/test/repositories/default-repository" );
File expectedFile = new File( defaultRepoDir, "org/apache/maven/shared/maven-downloader/maven-metadata.xml" ); Path expectedFile = defaultRepoDir.resolve( "org/apache/maven/shared/maven-downloader/maven-metadata.xml" );
String expectedContent = FileUtils.readFileToString( expectedFile, Charset.defaultCharset() ); String expectedContent = org.apache.archiva.common.utils.FileUtils.readFileToString( expectedFile, Charset.defaultCharset() );
ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata(); ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();

View File

@ -44,6 +44,7 @@ import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Paths;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
@ -226,9 +227,9 @@ public class Maven2RepositoryMerger
// updating version metadata files // updating version metadata files
File versionMetaDataFileInSourceRepo = File versionMetaDataFileInSourceRepo =
pathTranslator.toFile( new File( sourceRepoPath ), artifactMetadata.getNamespace(), pathTranslator.toFile( Paths.get( sourceRepoPath ), artifactMetadata.getNamespace(),
artifactMetadata.getProject(), artifactMetadata.getVersion(), artifactMetadata.getProject(), artifactMetadata.getVersion(),
METADATA_FILENAME ); METADATA_FILENAME ).toFile();
if ( versionMetaDataFileInSourceRepo.exists() ) if ( versionMetaDataFileInSourceRepo.exists() )
{//Pattern quote for windows path {//Pattern quote for windows path