1 package org.apache.archiva.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
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import net.sf.ehcache.CacheManager;
23 import org.apache.archiva.admin.model.beans.ManagedRepository;
24 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
25 import org.apache.archiva.admin.repository.managed.DefaultManagedRepositoryAdmin;
26 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
27 import org.apache.archiva.configuration.ArchivaConfiguration;
28 import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
29 import org.apache.archiva.configuration.ProxyConnectorConfiguration;
30 import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
31 import org.apache.archiva.policies.CachedFailuresPolicy;
32 import org.apache.archiva.policies.ChecksumPolicy;
33 import org.apache.archiva.policies.PropagateErrorsDownloadPolicy;
34 import org.apache.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
35 import org.apache.archiva.policies.ReleasesPolicy;
36 import org.apache.archiva.policies.SnapshotsPolicy;
37 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
38 import org.apache.archiva.repository.ManagedRepositoryContent;
39 import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
40 import org.apache.commons.io.FileUtils;
41 import org.apache.maven.index.NexusIndexer;
42 import org.apache.maven.index.context.IndexingContext;
43 import org.apache.maven.wagon.Wagon;
44 import org.easymock.EasyMock;
45 import org.easymock.IMocksControl;
46 import org.junit.After;
47 import org.junit.Before;
48 import org.junit.runner.RunWith;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.springframework.context.ApplicationContext;
52 import org.springframework.test.context.ContextConfiguration;
54 import javax.inject.Inject;
55 import java.io.BufferedReader;
56 import java.io.FileReader;
57 import java.io.IOException;
58 import java.nio.charset.Charset;
59 import java.nio.file.Files;
60 import java.nio.file.Path;
61 import java.nio.file.Paths;
62 import java.nio.file.attribute.FileTime;
63 import java.text.ParseException;
64 import java.text.SimpleDateFormat;
66 import java.util.concurrent.TimeUnit;
67 import java.util.stream.Collectors;
69 import static org.junit.Assert.*;
72 * AbstractProxyTestCase
74 @RunWith( ArchivaSpringJUnit4ClassRunner.class )
75 @ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
76 public abstract class AbstractProxyTestCase
79 protected ApplicationContext applicationContext;
81 protected static final String ID_PROXIED1 = "proxied1";
83 protected static final String ID_PROXIED1_TARGET = "proxied1-target";
85 protected static final String ID_PROXIED2 = "proxied2";
87 protected static final String ID_PROXIED2_TARGET = "proxied2-target";
89 protected static final String ID_DEFAULT_MANAGED = "default-managed-repository";
91 protected static final String REPOPATH_PROXIED1 = "src/test/repositories/proxied1";
93 protected static final String REPOPATH_PROXIED1_TARGET = "target/test-repository/proxied1";
95 protected static final String REPOPATH_PROXIED2 = "src/test/repositories/proxied2";
97 protected static final String REPOPATH_PROXIED2_TARGET = "target/test-repository/proxied2";
99 protected static final String REPOPATH_DEFAULT_MANAGED = "src/test/repositories/managed";
101 // protected static final String REPOPATH_DEFAULT_MANAGED_TARGET = "target/test-repository/managed";
103 protected IMocksControl wagonMockControl;
105 protected Wagon wagonMock;
108 protected RepositoryProxyConnectors proxyHandler;
110 protected ManagedRepositoryContent managedDefaultRepository;
112 protected Path managedDefaultDir;
114 protected MockConfiguration config;
116 protected Logger log = LoggerFactory.getLogger( getClass() );
118 WagonDelegate delegate;
121 protected ManagedRepositoryAdmin managedRepositoryAdmin;
124 protected NexusIndexer nexusIndexer;
131 (MockConfiguration) applicationContext.getBean( "archivaConfiguration#mock", ArchivaConfiguration.class );
133 config.getConfiguration().setManagedRepositories( new ArrayList<ManagedRepositoryConfiguration>() );
134 config.getConfiguration().setRemoteRepositories( new ArrayList<RemoteRepositoryConfiguration>() );
135 config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>() );
137 // Setup source repository (using default layout)
138 String name = getClass().getSimpleName();
139 String repoPath = "target/test-repository/managed/" + name;
141 managedDefaultRepository =
142 createRepository( ID_DEFAULT_MANAGED, "Default Managed Repository", repoPath, "default" );
144 managedDefaultDir = Paths.get( managedDefaultRepository.getRepoRoot() );
146 ManagedRepository repoConfig = managedDefaultRepository.getRepository();
148 ( (DefaultManagedRepositoryAdmin) applicationContext.getBean(
149 ManagedRepositoryAdmin.class ) ).setArchivaConfiguration( config );
151 applicationContext.getBean( ManagedRepositoryAdmin.class ).addManagedRepository( repoConfig, false, null );
153 // to prevent windauze file leaking
154 removeMavenIndexes();
156 ManagedRepositoryAdmin managedRepositoryAdmin = applicationContext.getBean( ManagedRepositoryAdmin.class );
158 if ( managedRepositoryAdmin.getManagedRepository( repoConfig.getId() ) != null )
160 managedRepositoryAdmin.deleteManagedRepository( repoConfig.getId(), null, true );
163 managedRepositoryAdmin.addManagedRepository( repoConfig, false, null );
165 // Setup target (proxied to) repository.
166 saveRemoteRepositoryConfig( ID_PROXIED1, "Proxied Repository 1",
167 Paths.get( REPOPATH_PROXIED1 ).toUri().toURL().toExternalForm(), "default" );
169 // Setup target (proxied to) repository.
170 saveRemoteRepositoryConfig( ID_PROXIED2, "Proxied Repository 2",
171 Paths.get( REPOPATH_PROXIED2 ).toUri().toURL().toExternalForm(), "default" );
173 // Setup the proxy handler.
174 //proxyHandler = applicationContext.getBean (RepositoryProxyConnectors) lookup( RepositoryProxyConnectors.class.getName() );
176 proxyHandler = applicationContext.getBean( "repositoryProxyConnectors#test", RepositoryProxyConnectors.class );
178 // Setup the wagon mock.
179 wagonMockControl = EasyMock.createNiceControl();
180 wagonMock = wagonMockControl.createMock( Wagon.class );
182 delegate = (WagonDelegate) applicationContext.getBean( "wagon#test", Wagon.class );
184 delegate.setDelegate( wagonMock );
186 CacheManager.getInstance().clearAll();
188 log.info( "\n.\\ {}() \\._________________________________________\n", name );
192 public void shutdown()
195 removeMavenIndexes();
199 protected void removeMavenIndexes()
203 for ( IndexingContext indexingContext : nexusIndexer.getIndexingContexts().values() )
205 nexusIndexer.removeIndexingContext( indexingContext, false );
210 protected void assertChecksums( Path expectedFile, String expectedSha1Contents, String expectedMd5Contents )
213 Path sha1File = expectedFile.toAbsolutePath().resolveSibling( expectedFile.getFileName().toString()+ ".sha1" );
214 Path md5File = expectedFile.toAbsolutePath().resolveSibling( expectedFile.getFileName().toString() + ".md5" );
216 if ( expectedSha1Contents == null )
218 assertFalse( "SHA1 File should NOT exist: " + sha1File.toAbsolutePath(), Files.exists(sha1File) );
222 assertTrue( "SHA1 File should exist: " + sha1File.toAbsolutePath(), Files.exists(sha1File) );
223 String actualSha1Contents = readChecksumFile( sha1File );
224 assertEquals( "SHA1 File contents: " + sha1File.toAbsolutePath(), expectedSha1Contents, actualSha1Contents );
227 if ( expectedMd5Contents == null )
229 assertFalse( "MD5 File should NOT exist: " + md5File.toAbsolutePath(), Files.exists(md5File) );
233 assertTrue( "MD5 File should exist: " + md5File.toAbsolutePath(), Files.exists(md5File) );
234 String actualMd5Contents = readChecksumFile( md5File );
235 assertEquals( "MD5 File contents: " + md5File.toAbsolutePath(), expectedMd5Contents, actualMd5Contents );
239 protected void assertFileEquals( Path expectedFile, Path actualFile, Path sourceFile )
242 assertNotNull( "Expected File should not be null.", expectedFile );
243 assertNotNull( "Actual File should not be null.", actualFile );
245 assertTrue( "Check actual file exists.", Files.exists(actualFile) );
246 assertTrue( "Check file is the same.", Files.isSameFile( expectedFile,
248 String expectedContents =
249 org.apache.commons.io.FileUtils.readFileToString( sourceFile.toFile(), Charset.defaultCharset() );
250 String actualContents =
251 org.apache.commons.io.FileUtils.readFileToString( actualFile.toFile(), Charset.defaultCharset() );
252 assertEquals( "Check file contents.", expectedContents, actualContents );
255 protected void assertNotDownloaded( Path downloadedFile )
257 assertNull( "Found file: " + downloadedFile + "; but was expecting a failure", downloadedFile );
260 @SuppressWarnings( "unchecked" )
261 protected void assertNoTempFiles( Path expectedFile )
263 Path workingDir = expectedFile.getParent();
264 if ( ( workingDir == null ) || !Files.isDirectory( workingDir) )
269 Collection<Path> tmpFiles = null;
271 tmpFiles = Files.list(workingDir).filter(path -> Files.isRegularFile(path) && path.getFileName().toString().endsWith(".tmp")).collect(Collectors.toList());
272 } catch (IOException e) {
273 log.error("Could not retrieve tmpFiles {}", workingDir);
275 if ( tmpFiles!=null && !tmpFiles.isEmpty() )
277 StringBuilder emsg = new StringBuilder();
278 emsg.append( "Found Temp Files in dir: " ).append( workingDir.toString() );
279 for ( Path tfile : tmpFiles )
281 emsg.append( "\n " ).append( tfile.getFileName().toString());
283 fail( emsg.toString() );
288 * A faster recursive copy that omits .svn directories.
290 * @param sourceDirectory the source directory to copy
291 * @param destDirectory the target location
292 * @throws java.io.IOException if there is a copying problem
293 * @todo get back into plexus-utils, share with converter module
295 protected void copyDirectoryStructure( Path sourceDirectory, Path destDirectory )
298 if ( !Files.exists(sourceDirectory) )
300 throw new IOException( "Source directory doesn't exists (" + sourceDirectory.toAbsolutePath() + ")." );
303 Path[] files = Files.list(sourceDirectory).filter(path -> Files.isRegularFile(path)).toArray(Path[]::new);
305 String sourcePath = sourceDirectory.toAbsolutePath().toString();
307 for ( int i = 0; i < files.length; i++ )
309 Path file = files[i];
311 String dest = file.toAbsolutePath().toString();
313 dest = dest.substring( sourcePath.length() + 1 );
315 Path destination = destDirectory.resolve( dest );
317 if ( Files.isRegularFile(file) )
319 destination = destination.getParent();
321 org.apache.commons.io.FileUtils.copyFile( file.toFile(), destination.resolve( file.getFileName() ).toFile(), false );
322 // TODO: Change when there is a FileUtils.copyFileToDirectory(file, destination, boolean) option
323 //FileUtils.copyFileToDirectory( file, destination );
325 else if ( Files.isDirectory(file) )
327 if ( !".svn".equals( file.getFileName().toString() ) )
329 if ( !Files.exists(destination))
331 Files.createDirectories(destination);
334 copyDirectoryStructure( file, destination );
339 throw new IOException( "Unknown file type: " + file.toAbsolutePath() );
345 protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )
348 ManagedRepository repo = new ManagedRepository();
350 repo.setName( name );
351 repo.setLocation( path );
352 repo.setLayout( layout );
354 ManagedRepositoryContent repoContent =
355 applicationContext.getBean( "managedRepositoryContent#" + layout, ManagedRepositoryContent.class );
356 repoContent.setRepository( repo );
361 * Read the first line from the checksum file, and return it (trimmed).
363 protected String readChecksumFile( Path checksumFile )
366 FileReader freader = null;
367 BufferedReader buf = null;
371 freader = new FileReader( checksumFile.toFile() );
372 buf = new BufferedReader( freader );
373 return buf.readLine();
382 if ( freader != null )
389 protected void saveConnector( String sourceRepoId, String targetRepoId, boolean disabled )
391 saveConnector( sourceRepoId, targetRepoId, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
392 CachedFailuresPolicy.NO, disabled );
395 protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
396 String snapshotPolicy, String cacheFailuresPolicy, boolean disabled )
398 saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
399 PropagateErrorsDownloadPolicy.QUEUE, disabled );
402 protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
403 String snapshotPolicy, String cacheFailuresPolicy, String errorPolicy,
406 saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
407 errorPolicy, PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT, disabled );
410 protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
411 String snapshotPolicy, String cacheFailuresPolicy, String errorPolicy,
412 String errorOnUpdatePolicy, boolean disabled )
414 ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
415 connectorConfig.setSourceRepoId( sourceRepoId );
416 connectorConfig.setTargetRepoId( targetRepoId );
417 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, checksumPolicy );
418 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, releasePolicy );
419 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, snapshotPolicy );
420 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, cacheFailuresPolicy );
421 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS, errorPolicy );
422 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE, errorOnUpdatePolicy );
423 connectorConfig.setDisabled( disabled );
425 int count = config.getConfiguration().getProxyConnectors().size();
426 config.getConfiguration().addProxyConnector( connectorConfig );
428 // Proper Triggering ...
429 String prefix = "proxyConnectors.proxyConnector(" + count + ")";
430 config.triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
431 config.triggerChange( prefix + ".targetRepoId", connectorConfig.getTargetRepoId() );
432 config.triggerChange( prefix + ".proxyId", connectorConfig.getProxyId() );
433 config.triggerChange( prefix + ".policies.releases", connectorConfig.getPolicy( "releases", "" ) );
434 config.triggerChange( prefix + ".policies.checksum", connectorConfig.getPolicy( "checksum", "" ) );
435 config.triggerChange( prefix + ".policies.snapshots", connectorConfig.getPolicy( "snapshots", "" ) );
436 config.triggerChange( prefix + ".policies.cache-failures", connectorConfig.getPolicy( "cache-failures", "" ) );
437 config.triggerChange( prefix + ".policies.propagate-errors",
438 connectorConfig.getPolicy( "propagate-errors", "" ) );
439 config.triggerChange( prefix + ".policies.propagate-errors-on-update",
440 connectorConfig.getPolicy( "propagate-errors-on-update", "" ) );
443 protected void saveManagedRepositoryConfig( String id, String name, String path, String layout )
445 ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration();
447 repoConfig.setId( id );
448 repoConfig.setName( name );
449 repoConfig.setLayout( layout );
451 repoConfig.setLocation( path );
453 int count = config.getConfiguration().getManagedRepositories().size();
454 config.getConfiguration().addManagedRepository( repoConfig );
456 String prefix = "managedRepositories.managedRepository(" + count + ")";
457 config.triggerChange( prefix + ".id", repoConfig.getId() );
458 config.triggerChange( prefix + ".name", repoConfig.getName() );
459 config.triggerChange( prefix + ".location", repoConfig.getLocation() );
460 config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
463 protected void saveRemoteRepositoryConfig( String id, String name, String url, String layout )
465 RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
467 repoConfig.setId( id );
468 repoConfig.setName( name );
469 repoConfig.setLayout( layout );
470 repoConfig.setUrl( url );
472 int count = config.getConfiguration().getRemoteRepositories().size();
473 config.getConfiguration().addRemoteRepository( repoConfig );
475 String prefix = "remoteRepositories.remoteRepository(" + count + ")";
476 config.triggerChange( prefix + ".id", repoConfig.getId() );
477 config.triggerChange( prefix + ".name", repoConfig.getName() );
478 config.triggerChange( prefix + ".url", repoConfig.getUrl() );
479 config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
482 protected Path saveTargetedRepositoryConfig( String id, String originalPath, String targetPath, String layout )
485 Path repoLocation = Paths.get( targetPath );
486 org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoLocation );
487 copyDirectoryStructure( Paths.get(originalPath) , repoLocation );
489 saveRemoteRepositoryConfig( id, "Target Repo-" + id, targetPath, layout );
496 * Copy the specified resource directory from the src/test/repository/managed/ to
497 * the testable directory under target/test-repository/managed/${testName}/
499 * @param resourcePath
500 * @throws IOException
502 protected void setupTestableManagedRepository( String resourcePath )
505 String resourceDir = resourcePath;
507 if ( !resourcePath.endsWith( "/" ) )
509 int idx = resourcePath.lastIndexOf( '/' );
510 resourceDir = resourcePath.substring( 0, idx );
513 Path sourceRepoDir = Paths.get( REPOPATH_DEFAULT_MANAGED );
514 Path sourceDir = sourceRepoDir.resolve(resourceDir );
516 Path destRepoDir = managedDefaultDir;
517 Path destDir = destRepoDir.resolve(resourceDir );
519 // Cleanout destination dirs.
520 if ( Files.exists(destDir))
522 org.apache.archiva.common.utils.FileUtils.deleteDirectory( destDir );
525 // Make the destination dir.
526 Files.createDirectories(destDir);
528 // Test the source dir.
529 if ( !Files.exists(sourceDir) )
531 // This is just a warning.
532 log.error( "[WARN] Skipping setup of testable managed repository, source dir does not exist: {}", //
538 // Test that the source is a dir.
539 if ( !Files.isDirectory( sourceDir) )
541 fail( "Unable to setup testable managed repository, source is not a directory: " + sourceDir );
544 // Copy directory structure.
545 copyDirectoryStructure( sourceDir, destDir );
549 protected void setManagedNewerThanRemote( Path managedFile, Path remoteFile )
551 setManagedNewerThanRemote( managedFile, remoteFile, 55000 );
554 protected void setManagedNewerThanRemote( Path managedFile, Path remoteFile, long time )
556 assertTrue( "Managed File should exist: ", Files.exists(managedFile) );
557 assertTrue( "Remote File should exist: ", Files.exists(remoteFile) );
561 Files.setLastModifiedTime( managedFile,
562 FileTime.from(Files.getLastModifiedTime( remoteFile ).toMillis() + time, TimeUnit.MILLISECONDS ));
564 catch ( IOException e )
566 e.printStackTrace( );
571 assertTrue( Files.getLastModifiedTime( managedFile).compareTo( Files.getLastModifiedTime( remoteFile )) > 0);
573 catch ( IOException e )
575 e.printStackTrace( );
579 protected void setManagedOlderThanRemote( Path managedFile, Path remoteFile )
581 setManagedOlderThanRemote( managedFile, remoteFile, 55000 );
584 protected void setManagedOlderThanRemote( Path managedFile, Path remoteFile, long time )
586 assertTrue( "Managed File should exist: ", Files.exists(managedFile) );
587 assertTrue( "Remote File should exist: ", Files.exists(remoteFile) );
591 Files.setLastModifiedTime( managedFile,
592 FileTime.from(Files.getLastModifiedTime( remoteFile ).toMillis() - time, TimeUnit.MILLISECONDS ));
594 catch ( IOException e )
596 e.printStackTrace( );
601 assertTrue( Files.getLastModifiedTime( managedFile ).compareTo(Files.getLastModifiedTime( remoteFile )) < 0 );
603 catch ( IOException e )
605 e.printStackTrace( );
610 protected void assertNotModified( Path file, long expectedModificationTime )
614 assertEquals( "File <" + file.toAbsolutePath() + "> not have been modified.", expectedModificationTime,
615 Files.getLastModifiedTime( file ).toMillis());
617 catch ( IOException e )
619 e.printStackTrace( );
624 protected void assertNotExistsInManagedDefaultRepo( Path testFile )
627 Path managedDefaultPath = managedDefaultDir;
629 assertTrue( "Unit Test Failure: File <" + testFile
630 + "> should be have been defined within the managed default path of <" + managedDefaultPath
631 + ">", testFile.startsWith( managedDefaultPath ) );
633 assertFalse( "File < " + testFile + "> should not exist in managed default repository.", Files.exists(testFile) );
636 protected static Date getFutureDate()
637 throws ParseException
639 Calendar cal = Calendar.getInstance();
640 cal.add( Calendar.YEAR, 1 );
641 return cal.getTime();
644 protected static Date getPastDate()
645 throws ParseException
647 return new SimpleDateFormat( "yyyy-MM-dd", Locale.US ).parse( "2000-01-01" );