1 package org.apache.archiva.maven.proxy;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
21 import net.sf.ehcache.CacheManager;
22 import org.apache.archiva.configuration.ArchivaConfiguration;
23 import org.apache.archiva.configuration.ArchivaRuntimeConfiguration;
24 import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
25 import org.apache.archiva.configuration.ProxyConnectorConfiguration;
26 import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
27 import org.apache.archiva.policies.CachedFailuresPolicy;
28 import org.apache.archiva.policies.ChecksumPolicy;
29 import org.apache.archiva.policies.PolicyOption;
30 import org.apache.archiva.policies.PropagateErrorsDownloadPolicy;
31 import org.apache.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
32 import org.apache.archiva.policies.ReleasesPolicy;
33 import org.apache.archiva.policies.SnapshotsPolicy;
34 import org.apache.archiva.proxy.ProxyRegistry;
35 import org.apache.archiva.proxy.model.RepositoryProxyHandler;
36 import org.apache.archiva.repository.ManagedRepository;
37 import org.apache.archiva.repository.ManagedRepositoryContent;
38 import org.apache.archiva.repository.RepositoryRegistry;
39 import org.apache.archiva.repository.RepositoryType;
40 import org.apache.archiva.repository.base.RepositoryHandlerDependencies;
41 import org.apache.archiva.repository.base.managed.BasicManagedRepository;
42 import org.apache.archiva.repository.storage.StorageAsset;
43 import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
44 import org.apache.maven.wagon.Wagon;
45 import org.junit.Before;
46 import org.junit.runner.RunWith;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.springframework.context.ApplicationContext;
50 import org.springframework.test.context.ContextConfiguration;
52 import javax.inject.Inject;
53 import java.io.BufferedReader;
54 import java.io.FileReader;
55 import java.io.IOException;
56 import java.nio.charset.Charset;
57 import java.nio.file.Files;
58 import java.nio.file.Path;
59 import java.nio.file.Paths;
60 import java.nio.file.attribute.FileTime;
61 import java.text.ParseException;
62 import java.text.SimpleDateFormat;
63 import java.util.ArrayList;
64 import java.util.Calendar;
65 import java.util.Collection;
66 import java.util.Date;
67 import java.util.List;
68 import java.util.Locale;
69 import java.util.concurrent.TimeUnit;
70 import java.util.stream.Collectors;
72 import static org.junit.Assert.*;
73 import static org.mockito.Mockito.mock;
76 * AbstractProxyTestCase
78 @RunWith( ArchivaSpringJUnit4ClassRunner.class )
79 @ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
80 public abstract class AbstractProxyTestCase
83 protected ApplicationContext applicationContext;
86 private ProxyRegistry proxyRegistry;
89 RepositoryRegistry repositoryRegistry;
91 @SuppressWarnings( "unused" )
93 RepositoryHandlerDependencies repositoryHandlerDependencies;
95 protected static final String ID_PROXIED1 = "proxied1";
97 protected static final String ID_PROXIED1_TARGET = "proxied1-target";
99 protected static final String ID_PROXIED2 = "proxied2";
101 protected static final String ID_PROXIED2_TARGET = "proxied2-target";
103 protected static final String ID_DEFAULT_MANAGED = "default-managed-repository";
105 protected static final String REPOPATH_PROXIED1 = "src/test/repositories/proxied1";
107 protected static final String REPOPATH_PROXIED1_TARGET = "target/test-repository/proxied1";
109 protected static final String REPOPATH_PROXIED2 = "src/test/repositories/proxied2";
111 protected static final String REPOPATH_PROXIED2_TARGET = "target/test-repository/proxied2";
113 protected static final String REPOPATH_DEFAULT_MANAGED = "src/test/repositories/managed";
115 // protected static final String REPOPATH_DEFAULT_MANAGED_TARGET = "target/test-repository/managed";
117 protected Wagon wagonMock;
120 protected RepositoryProxyHandler proxyHandler;
122 protected ManagedRepositoryContent managedDefaultRepository;
124 protected Path managedDefaultDir;
126 protected MockConfiguration config;
128 protected Logger log = LoggerFactory.getLogger( getClass() );
130 WagonDelegate delegate;
137 (MockConfiguration) applicationContext.getBean( "archivaConfiguration#mock", ArchivaConfiguration.class );
139 config.getConfiguration().setManagedRepositories( new ArrayList<ManagedRepositoryConfiguration>() );
140 config.getConfiguration().setRemoteRepositories( new ArrayList<RemoteRepositoryConfiguration>() );
141 config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>() );
142 ArchivaRuntimeConfiguration runtimeConfiguration = new ArchivaRuntimeConfiguration();
143 List<String> checksumTypes = new ArrayList<>();
144 checksumTypes.add("md5");
145 checksumTypes.add("sha256");
146 checksumTypes.add("sha1");
147 checksumTypes.add("asc");
148 runtimeConfiguration.setChecksumTypes(checksumTypes);
149 config.getConfiguration().setArchivaRuntimeConfiguration(runtimeConfiguration);
150 repositoryRegistry.setArchivaConfiguration( config );
152 // Setup source repository (using default layout)
153 String name = getClass().getSimpleName();
154 Path repoPath = Paths.get("target/test-repository/managed/" + name);
156 managedDefaultRepository =
157 createRepository( ID_DEFAULT_MANAGED, "Default Managed Repository", repoPath.toString(), "default" );
159 managedDefaultDir = repoPath.resolve(ID_DEFAULT_MANAGED) ;
161 org.apache.archiva.repository.ManagedRepository repoConfig = repositoryRegistry.getManagedRepository(ID_DEFAULT_MANAGED);
163 // Setup target (proxied to) repository.
164 saveRemoteRepositoryConfig( ID_PROXIED1, "Proxied Repository 1",
165 Paths.get( REPOPATH_PROXIED1 ).toUri().toURL().toExternalForm(), "default" );
167 // Setup target (proxied to) repository.
168 saveRemoteRepositoryConfig( ID_PROXIED2, "Proxied Repository 2",
169 Paths.get( REPOPATH_PROXIED2 ).toUri().toURL().toExternalForm(), "default" );
172 repositoryRegistry.reload();
173 repositoryRegistry.putRepository(repoConfig);
176 // Setup the proxy handler.
177 //proxyHandler = applicationContext.getBean (RepositoryProxyHandler) lookup( RepositoryProxyHandler.class.getName() );
179 proxyHandler = applicationContext.getBean( "repositoryProxyHandler#test", RepositoryProxyHandler.class );
180 assertNotNull( proxyRegistry );
181 assertTrue(proxyRegistry.getAllHandler( ).get( RepositoryType.MAVEN).contains( proxyHandler ));
184 // Setup the wagon mock.
185 wagonMock = mock( Wagon.class );
187 delegate = (WagonDelegate) applicationContext.getBean( "wagon#http", Wagon.class );
189 delegate.setDelegate( wagonMock );
191 CacheManager.getInstance().clearAll();
193 log.info( "\n.\\ {}() \\._________________________________________\n", name );
196 protected void assertChecksums( Path expectedFile, String expectedSha1Contents, String expectedMd5Contents )
199 Path sha1File = expectedFile.toAbsolutePath().resolveSibling( expectedFile.getFileName().toString()+ ".sha1" );
200 Path md5File = expectedFile.toAbsolutePath().resolveSibling( expectedFile.getFileName().toString() + ".md5" );
202 if ( expectedSha1Contents == null )
204 assertFalse( "SHA1 File should NOT exist: " + sha1File.toAbsolutePath(), Files.exists(sha1File) );
208 assertTrue( "SHA1 File should exist: " + sha1File.toAbsolutePath(), Files.exists(sha1File) );
209 String actualSha1Contents = readChecksumFile( sha1File );
210 assertEquals( "SHA1 File contents: " + sha1File.toAbsolutePath(), expectedSha1Contents, actualSha1Contents );
213 if ( expectedMd5Contents == null )
215 assertFalse( "MD5 File should NOT exist: " + md5File.toAbsolutePath(), Files.exists(md5File) );
219 assertTrue( "MD5 File should exist: " + md5File.toAbsolutePath(), Files.exists(md5File) );
220 String actualMd5Contents = readChecksumFile( md5File );
221 assertEquals( "MD5 File contents: " + md5File.toAbsolutePath(), expectedMd5Contents, actualMd5Contents );
225 protected void assertFileEquals( Path expectedFile, Path actualFile, Path sourceFile )
228 assertNotNull( "Expected File should not be null.", expectedFile );
229 assertNotNull( "Actual File should not be null.", actualFile );
231 assertTrue( "Check actual file exists.", Files.exists(actualFile) );
232 assertTrue("Check expected file exists", Files.exists(expectedFile));
233 assertTrue( "Check file is the same.", Files.isSameFile( expectedFile,
235 String expectedContents =
236 org.apache.commons.io.FileUtils.readFileToString( sourceFile.toFile(), Charset.defaultCharset() );
237 String actualContents =
238 org.apache.commons.io.FileUtils.readFileToString( actualFile.toFile(), Charset.defaultCharset() );
239 assertEquals( "Check file contents.", expectedContents, actualContents );
242 protected void assertNotDownloaded( StorageAsset downloadedFile )
244 assertNull( "Found file: " + downloadedFile + "; but was expecting a failure", downloadedFile );
247 @SuppressWarnings( "unchecked" )
248 protected void assertNoTempFiles( Path expectedFile )
250 Path workingDir = expectedFile.getParent();
251 if ( ( workingDir == null ) || !Files.isDirectory( workingDir) )
256 Collection<Path> tmpFiles = null;
258 tmpFiles = Files.list(workingDir).filter(path -> Files.isRegularFile(path) && path.getFileName().toString().endsWith(".tmp")).collect(Collectors.toList());
259 } catch (IOException e) {
260 log.error("Could not retrieve tmpFiles {}", workingDir);
262 if ( tmpFiles!=null && !tmpFiles.isEmpty() )
264 StringBuilder emsg = new StringBuilder();
265 emsg.append( "Found Temp Files in dir: " ).append( workingDir.toString() );
266 for ( Path tfile : tmpFiles )
268 emsg.append( "\n " ).append( tfile.getFileName().toString());
270 fail( emsg.toString() );
275 * A faster recursive copy that omits .svn directories.
277 * @param sourceDirectory the source directory to copy
278 * @param destDirectory the target location
279 * @throws java.io.IOException if there is a copying problem
280 * @todo get back into plexus-utils, share with converter module
282 protected void copyDirectoryStructure( Path sourceDirectory, Path destDirectory )
285 if ( !Files.exists(sourceDirectory) )
287 throw new IOException( "Source directory doesn't exists (" + sourceDirectory.toAbsolutePath() + ")." );
290 Path[] files = Files.list(sourceDirectory).filter(path -> Files.isRegularFile(path)).toArray(Path[]::new);
292 String sourcePath = sourceDirectory.toAbsolutePath().toString();
294 for ( int i = 0; i < files.length; i++ )
296 Path file = files[i];
298 String dest = file.toAbsolutePath().toString();
300 dest = dest.substring( sourcePath.length() + 1 );
302 Path destination = destDirectory.resolve( dest );
304 if ( Files.isRegularFile(file) )
306 destination = destination.getParent();
308 org.apache.commons.io.FileUtils.copyFile( file.toFile(), destination.resolve( file.getFileName() ).toFile(), false );
309 // TODO: Change when there is a FileUtils.copyFileToDirectory(file, destination, boolean) option
310 //FileUtils.copyFileToDirectory( file, destination );
312 else if ( Files.isDirectory(file) )
314 if ( !".svn".equals( file.getFileName().toString() ) )
316 if ( !Files.exists(destination))
318 Files.createDirectories(destination);
321 copyDirectoryStructure( file, destination );
326 throw new IOException( "Unknown file type: " + file.toAbsolutePath() );
332 protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )
335 ManagedRepository repo = BasicManagedRepository.newFilesystemInstance(id, name, Paths.get(path).resolve(id));
336 repositoryRegistry.putRepository(repo);
337 return repositoryRegistry.getManagedRepository(id).getContent();
341 * Read the first line from the checksum file, and return it (trimmed).
343 protected String readChecksumFile( Path checksumFile )
346 FileReader freader = null;
347 BufferedReader buf = null;
351 freader = new FileReader( checksumFile.toFile() );
352 buf = new BufferedReader( freader );
353 return buf.readLine();
362 if ( freader != null )
369 protected void saveConnector( String sourceRepoId, String targetRepoId, boolean disabled )
371 saveConnector( sourceRepoId, targetRepoId, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
372 CachedFailuresPolicy.NO, disabled );
375 protected void saveConnector( String sourceRepoId, String targetRepoId, PolicyOption checksumPolicy, PolicyOption releasePolicy,
376 PolicyOption snapshotPolicy, PolicyOption cacheFailuresPolicy, boolean disabled )
378 saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
379 PropagateErrorsDownloadPolicy.QUEUE, disabled );
382 protected void saveConnector( String sourceRepoId, String targetRepoId, PolicyOption checksumPolicy, PolicyOption releasePolicy,
383 PolicyOption snapshotPolicy, PolicyOption cacheFailuresPolicy, PolicyOption errorPolicy,
386 saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
387 errorPolicy, PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT, disabled );
390 protected void saveConnector(String sourceRepoId, String targetRepoId, PolicyOption checksumPolicy, PolicyOption releasePolicy,
391 PolicyOption snapshotPolicy, PolicyOption cacheFailuresPolicy, PolicyOption errorPolicy,
392 PolicyOption errorOnUpdatePolicy, boolean disabled )
394 ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
395 connectorConfig.setSourceRepoId( sourceRepoId );
396 connectorConfig.setTargetRepoId( targetRepoId );
397 connectorConfig.setProxyId(sourceRepoId);
398 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, checksumPolicy.getId() );
399 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, releasePolicy.getId() );
400 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, snapshotPolicy.getId() );
401 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, cacheFailuresPolicy.getId());
402 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS, errorPolicy.getId() );
403 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE, errorOnUpdatePolicy.getId() );
404 connectorConfig.setDisabled( disabled );
406 int count = config.getConfiguration().getProxyConnectors().size();
407 config.getConfiguration().addProxyConnector( connectorConfig );
409 // Proper Triggering ...
410 String prefix = "proxyConnectors.proxyConnector(" + count + ")";
411 config.triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
412 config.triggerChange( prefix + ".targetRepoId", connectorConfig.getTargetRepoId() );
413 config.triggerChange( prefix + ".proxyId", connectorConfig.getProxyId() );
414 config.triggerChange( prefix + ".policies.releases", connectorConfig.getPolicy( "releases", "" ) );
415 config.triggerChange( prefix + ".policies.checksum", connectorConfig.getPolicy( "checksum", "" ) );
416 config.triggerChange( prefix + ".policies.snapshots", connectorConfig.getPolicy( "snapshots", "" ) );
417 config.triggerChange( prefix + ".policies.cache-failures", connectorConfig.getPolicy( "cache-failures", "" ) );
418 config.triggerChange( prefix + ".policies.propagate-errors",
419 connectorConfig.getPolicy( "propagate-errors", "" ) );
420 config.triggerChange( prefix + ".policies.propagate-errors-on-update",
421 connectorConfig.getPolicy( "propagate-errors-on-update", "" ) );
424 protected void saveManagedRepositoryConfig( String id, String name, String path, String layout )
426 ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration();
428 repoConfig.setId( id );
429 repoConfig.setName( name );
430 repoConfig.setLayout( layout );
432 repoConfig.setLocation( path );
434 int count = config.getConfiguration().getManagedRepositories().size();
435 config.getConfiguration().addManagedRepository( repoConfig );
437 String prefix = "managedRepositories.managedRepository(" + count + ")";
438 config.triggerChange( prefix + ".id", repoConfig.getId() );
439 config.triggerChange( prefix + ".name", repoConfig.getName() );
440 config.triggerChange( prefix + ".location", repoConfig.getLocation() );
441 config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
444 protected void saveRemoteRepositoryConfig( String id, String name, String url, String layout )
446 RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
448 repoConfig.setId( id );
449 repoConfig.setName( name );
450 repoConfig.setLayout( layout );
451 repoConfig.setUrl( url );
453 int count = config.getConfiguration().getRemoteRepositories().size();
454 config.getConfiguration().addRemoteRepository( repoConfig );
456 String prefix = "remoteRepositories.remoteRepository(" + count + ")";
457 config.triggerChange( prefix + ".id", repoConfig.getId() );
458 config.triggerChange( prefix + ".name", repoConfig.getName() );
459 config.triggerChange( prefix + ".url", repoConfig.getUrl() );
460 config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
461 repositoryRegistry.reload();
464 protected Path saveTargetedRepositoryConfig( String id, String originalPath, String targetPath, String layout )
467 Path repoLocation = Paths.get( targetPath );
468 org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoLocation );
469 copyDirectoryStructure( Paths.get(originalPath) , repoLocation );
471 saveRemoteRepositoryConfig( id, "Target Repo-" + id, targetPath, layout );
478 * Copy the specified resource directory from the src/test/repository/managed/ to
479 * the testable directory under target/test-repository/managed/${testName}/
481 * @param resourcePath
482 * @throws IOException
484 protected void setupTestableManagedRepository( String resourcePath )
487 String resourceDir = resourcePath;
489 if ( !resourcePath.endsWith( "/" ) )
491 int idx = resourcePath.lastIndexOf( '/' );
492 resourceDir = resourcePath.substring( 0, idx );
495 Path sourceRepoDir = Paths.get( REPOPATH_DEFAULT_MANAGED );
496 Path sourceDir = sourceRepoDir.resolve(resourceDir );
498 Path destRepoDir = managedDefaultDir;
499 Path destDir = destRepoDir.resolve(resourceDir );
501 // Cleanout destination dirs.
502 if ( Files.exists(destDir))
504 org.apache.archiva.common.utils.FileUtils.deleteDirectory( destDir );
507 // Make the destination dir.
508 Files.createDirectories(destDir);
510 // Test the source dir.
511 if ( !Files.exists(sourceDir) )
513 // This is just a warning.
514 log.error( "[WARN] Skipping setup of testable managed repository, source dir does not exist: {}", //
520 // Test that the source is a dir.
521 if ( !Files.isDirectory( sourceDir) )
523 fail( "Unable to setup testable managed repository, source is not a directory: " + sourceDir );
526 // Copy directory structure.
527 copyDirectoryStructure( sourceDir, destDir );
531 protected void setManagedNewerThanRemote( Path managedFile, Path remoteFile )
533 setManagedNewerThanRemote( managedFile, remoteFile, 55000 );
536 protected void setManagedNewerThanRemote( Path managedFile, Path remoteFile, long time )
538 assertTrue( "Managed File should exist: ", Files.exists(managedFile) );
539 assertTrue( "Remote File should exist: ", Files.exists(remoteFile) );
543 Files.setLastModifiedTime( managedFile,
544 FileTime.from(Files.getLastModifiedTime( remoteFile ).toMillis() + time, TimeUnit.MILLISECONDS ));
546 catch ( IOException e )
548 e.printStackTrace( );
553 assertTrue( Files.getLastModifiedTime( managedFile).compareTo( Files.getLastModifiedTime( remoteFile )) > 0);
555 catch ( IOException e )
557 e.printStackTrace( );
561 protected void setManagedOlderThanRemote( Path managedFile, Path remoteFile )
563 setManagedOlderThanRemote( managedFile, remoteFile, 55000 );
566 protected void setManagedOlderThanRemote( Path managedFile, Path remoteFile, long time )
568 assertTrue( "Managed File should exist: ", Files.exists(managedFile) );
569 assertTrue( "Remote File should exist: ", Files.exists(remoteFile) );
573 Files.setLastModifiedTime( managedFile,
574 FileTime.from(Files.getLastModifiedTime( remoteFile ).toMillis() - time, TimeUnit.MILLISECONDS ));
576 catch ( IOException e )
578 e.printStackTrace( );
583 assertTrue( Files.getLastModifiedTime( managedFile ).compareTo(Files.getLastModifiedTime( remoteFile )) < 0 );
585 catch ( IOException e )
587 e.printStackTrace( );
592 protected void assertNotModified( Path file, long expectedModificationTime )
596 assertEquals( "File <" + file.toAbsolutePath() + "> not have been modified.", expectedModificationTime,
597 Files.getLastModifiedTime( file ).toMillis());
599 catch ( IOException e )
601 e.printStackTrace( );
606 protected void assertNotExistsInManagedDefaultRepo( Path testFile )
609 Path managedDefaultPath = managedDefaultDir;
611 assertTrue( "Unit Test Failure: File <" + testFile
612 + "> should be have been defined within the managed default path of <" + managedDefaultPath
613 + ">", testFile.startsWith( managedDefaultPath ) );
615 assertFalse( "File < " + testFile + "> should not exist in managed default repository.", Files.exists(testFile) );
618 protected static Date getFutureDate()
619 throws ParseException
621 Calendar cal = Calendar.getInstance();
622 cal.add( Calendar.YEAR, 1 );
623 return cal.getTime();
626 protected static Date getPastDate()
627 throws ParseException
629 return new SimpleDateFormat( "yyyy-MM-dd", Locale.US ).parse( "2000-01-01" );