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.configuration.*;
24 import org.apache.archiva.policies.*;
25 import org.apache.archiva.proxy.model.RepositoryProxyHandler;
26 import org.apache.archiva.repository.*;
27 import org.apache.archiva.repository.base.BasicManagedRepository;
28 import org.apache.archiva.repository.storage.StorageAsset;
29 import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
30 import org.apache.maven.wagon.Wagon;
31 import org.easymock.EasyMock;
32 import org.easymock.IMocksControl;
33 import org.junit.Before;
34 import org.junit.runner.RunWith;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.context.ApplicationContext;
38 import org.springframework.test.context.ContextConfiguration;
40 import javax.inject.Inject;
41 import java.io.BufferedReader;
42 import java.io.FileReader;
43 import java.io.IOException;
44 import java.nio.charset.Charset;
45 import java.nio.file.Files;
46 import java.nio.file.Path;
47 import java.nio.file.Paths;
48 import java.nio.file.attribute.FileTime;
49 import java.text.ParseException;
50 import java.text.SimpleDateFormat;
52 import java.util.concurrent.TimeUnit;
53 import java.util.stream.Collectors;
55 import static org.junit.Assert.*;
58 * AbstractProxyTestCase
60 @RunWith( ArchivaSpringJUnit4ClassRunner.class )
61 @ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
62 public abstract class AbstractProxyTestCase
65 protected ApplicationContext applicationContext;
68 private ProxyRegistry proxyRegistry;
71 RepositoryRegistry repositoryRegistry;
73 protected static final String ID_PROXIED1 = "proxied1";
75 protected static final String ID_PROXIED1_TARGET = "proxied1-target";
77 protected static final String ID_PROXIED2 = "proxied2";
79 protected static final String ID_PROXIED2_TARGET = "proxied2-target";
81 protected static final String ID_DEFAULT_MANAGED = "default-managed-repository";
83 protected static final String REPOPATH_PROXIED1 = "src/test/repositories/proxied1";
85 protected static final String REPOPATH_PROXIED1_TARGET = "target/test-repository/proxied1";
87 protected static final String REPOPATH_PROXIED2 = "src/test/repositories/proxied2";
89 protected static final String REPOPATH_PROXIED2_TARGET = "target/test-repository/proxied2";
91 protected static final String REPOPATH_DEFAULT_MANAGED = "src/test/repositories/managed";
93 // protected static final String REPOPATH_DEFAULT_MANAGED_TARGET = "target/test-repository/managed";
95 protected IMocksControl wagonMockControl;
97 protected Wagon wagonMock;
100 protected RepositoryProxyHandler proxyHandler;
102 protected ManagedRepositoryContent managedDefaultRepository;
104 protected Path managedDefaultDir;
106 protected MockConfiguration config;
108 protected Logger log = LoggerFactory.getLogger( getClass() );
110 WagonDelegate delegate;
117 (MockConfiguration) applicationContext.getBean( "archivaConfiguration#mock", ArchivaConfiguration.class );
119 config.getConfiguration().setManagedRepositories( new ArrayList<ManagedRepositoryConfiguration>() );
120 config.getConfiguration().setRemoteRepositories( new ArrayList<RemoteRepositoryConfiguration>() );
121 config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>() );
122 ArchivaRuntimeConfiguration runtimeConfiguration = new ArchivaRuntimeConfiguration();
123 List<String> checksumTypes = new ArrayList<>();
124 checksumTypes.add("md5");
125 checksumTypes.add("sha256");
126 checksumTypes.add("sha1");
127 checksumTypes.add("asc");
128 runtimeConfiguration.setChecksumTypes(checksumTypes);
129 config.getConfiguration().setArchivaRuntimeConfiguration(runtimeConfiguration);
130 repositoryRegistry.setArchivaConfiguration( config );
132 // Setup source repository (using default layout)
133 String name = getClass().getSimpleName();
134 Path repoPath = Paths.get("target/test-repository/managed/" + name);
136 managedDefaultRepository =
137 createRepository( ID_DEFAULT_MANAGED, "Default Managed Repository", repoPath.toString(), "default" );
139 managedDefaultDir = repoPath.resolve(ID_DEFAULT_MANAGED) ;
141 org.apache.archiva.repository.ManagedRepository repoConfig = repositoryRegistry.getManagedRepository(ID_DEFAULT_MANAGED);
143 // Setup target (proxied to) repository.
144 saveRemoteRepositoryConfig( ID_PROXIED1, "Proxied Repository 1",
145 Paths.get( REPOPATH_PROXIED1 ).toUri().toURL().toExternalForm(), "default" );
147 // Setup target (proxied to) repository.
148 saveRemoteRepositoryConfig( ID_PROXIED2, "Proxied Repository 2",
149 Paths.get( REPOPATH_PROXIED2 ).toUri().toURL().toExternalForm(), "default" );
152 repositoryRegistry.reload();
153 repositoryRegistry.putRepository(repoConfig);
156 // Setup the proxy handler.
157 //proxyHandler = applicationContext.getBean (RepositoryProxyHandler) lookup( RepositoryProxyHandler.class.getName() );
159 proxyHandler = applicationContext.getBean( "repositoryProxyHandler#test", RepositoryProxyHandler.class );
160 assertNotNull( proxyRegistry );
161 assertTrue(proxyRegistry.getAllHandler( ).get( RepositoryType.MAVEN).contains( proxyHandler ));
164 // Setup the wagon mock.
165 wagonMockControl = EasyMock.createNiceControl();
166 wagonMock = wagonMockControl.createMock( Wagon.class );
168 delegate = (WagonDelegate) applicationContext.getBean( "wagon#http", Wagon.class );
170 delegate.setDelegate( wagonMock );
172 CacheManager.getInstance().clearAll();
174 log.info( "\n.\\ {}() \\._________________________________________\n", name );
177 protected void assertChecksums( Path expectedFile, String expectedSha1Contents, String expectedMd5Contents )
180 Path sha1File = expectedFile.toAbsolutePath().resolveSibling( expectedFile.getFileName().toString()+ ".sha1" );
181 Path md5File = expectedFile.toAbsolutePath().resolveSibling( expectedFile.getFileName().toString() + ".md5" );
183 if ( expectedSha1Contents == null )
185 assertFalse( "SHA1 File should NOT exist: " + sha1File.toAbsolutePath(), Files.exists(sha1File) );
189 assertTrue( "SHA1 File should exist: " + sha1File.toAbsolutePath(), Files.exists(sha1File) );
190 String actualSha1Contents = readChecksumFile( sha1File );
191 assertEquals( "SHA1 File contents: " + sha1File.toAbsolutePath(), expectedSha1Contents, actualSha1Contents );
194 if ( expectedMd5Contents == null )
196 assertFalse( "MD5 File should NOT exist: " + md5File.toAbsolutePath(), Files.exists(md5File) );
200 assertTrue( "MD5 File should exist: " + md5File.toAbsolutePath(), Files.exists(md5File) );
201 String actualMd5Contents = readChecksumFile( md5File );
202 assertEquals( "MD5 File contents: " + md5File.toAbsolutePath(), expectedMd5Contents, actualMd5Contents );
206 protected void assertFileEquals( Path expectedFile, Path actualFile, Path sourceFile )
209 assertNotNull( "Expected File should not be null.", expectedFile );
210 assertNotNull( "Actual File should not be null.", actualFile );
212 assertTrue( "Check actual file exists.", Files.exists(actualFile) );
213 assertTrue("Check expected file exists", Files.exists(expectedFile));
214 assertTrue( "Check file is the same.", Files.isSameFile( expectedFile,
216 String expectedContents =
217 org.apache.commons.io.FileUtils.readFileToString( sourceFile.toFile(), Charset.defaultCharset() );
218 String actualContents =
219 org.apache.commons.io.FileUtils.readFileToString( actualFile.toFile(), Charset.defaultCharset() );
220 assertEquals( "Check file contents.", expectedContents, actualContents );
223 protected void assertNotDownloaded( StorageAsset downloadedFile )
225 assertNull( "Found file: " + downloadedFile + "; but was expecting a failure", downloadedFile );
228 @SuppressWarnings( "unchecked" )
229 protected void assertNoTempFiles( Path expectedFile )
231 Path workingDir = expectedFile.getParent();
232 if ( ( workingDir == null ) || !Files.isDirectory( workingDir) )
237 Collection<Path> tmpFiles = null;
239 tmpFiles = Files.list(workingDir).filter(path -> Files.isRegularFile(path) && path.getFileName().toString().endsWith(".tmp")).collect(Collectors.toList());
240 } catch (IOException e) {
241 log.error("Could not retrieve tmpFiles {}", workingDir);
243 if ( tmpFiles!=null && !tmpFiles.isEmpty() )
245 StringBuilder emsg = new StringBuilder();
246 emsg.append( "Found Temp Files in dir: " ).append( workingDir.toString() );
247 for ( Path tfile : tmpFiles )
249 emsg.append( "\n " ).append( tfile.getFileName().toString());
251 fail( emsg.toString() );
256 * A faster recursive copy that omits .svn directories.
258 * @param sourceDirectory the source directory to copy
259 * @param destDirectory the target location
260 * @throws java.io.IOException if there is a copying problem
261 * @todo get back into plexus-utils, share with converter module
263 protected void copyDirectoryStructure( Path sourceDirectory, Path destDirectory )
266 if ( !Files.exists(sourceDirectory) )
268 throw new IOException( "Source directory doesn't exists (" + sourceDirectory.toAbsolutePath() + ")." );
271 Path[] files = Files.list(sourceDirectory).filter(path -> Files.isRegularFile(path)).toArray(Path[]::new);
273 String sourcePath = sourceDirectory.toAbsolutePath().toString();
275 for ( int i = 0; i < files.length; i++ )
277 Path file = files[i];
279 String dest = file.toAbsolutePath().toString();
281 dest = dest.substring( sourcePath.length() + 1 );
283 Path destination = destDirectory.resolve( dest );
285 if ( Files.isRegularFile(file) )
287 destination = destination.getParent();
289 org.apache.commons.io.FileUtils.copyFile( file.toFile(), destination.resolve( file.getFileName() ).toFile(), false );
290 // TODO: Change when there is a FileUtils.copyFileToDirectory(file, destination, boolean) option
291 //FileUtils.copyFileToDirectory( file, destination );
293 else if ( Files.isDirectory(file) )
295 if ( !".svn".equals( file.getFileName().toString() ) )
297 if ( !Files.exists(destination))
299 Files.createDirectories(destination);
302 copyDirectoryStructure( file, destination );
307 throw new IOException( "Unknown file type: " + file.toAbsolutePath() );
313 protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )
316 ManagedRepository repo = BasicManagedRepository.newFilesystemInstance(id, name, Paths.get(path).resolve(id));
317 repositoryRegistry.putRepository(repo);
318 return repositoryRegistry.getManagedRepository(id).getContent();
322 * Read the first line from the checksum file, and return it (trimmed).
324 protected String readChecksumFile( Path checksumFile )
327 FileReader freader = null;
328 BufferedReader buf = null;
332 freader = new FileReader( checksumFile.toFile() );
333 buf = new BufferedReader( freader );
334 return buf.readLine();
343 if ( freader != null )
350 protected void saveConnector( String sourceRepoId, String targetRepoId, boolean disabled )
352 saveConnector( sourceRepoId, targetRepoId, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
353 CachedFailuresPolicy.NO, disabled );
356 protected void saveConnector( String sourceRepoId, String targetRepoId, PolicyOption checksumPolicy, PolicyOption releasePolicy,
357 PolicyOption snapshotPolicy, PolicyOption cacheFailuresPolicy, boolean disabled )
359 saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
360 PropagateErrorsDownloadPolicy.QUEUE, disabled );
363 protected void saveConnector( String sourceRepoId, String targetRepoId, PolicyOption checksumPolicy, PolicyOption releasePolicy,
364 PolicyOption snapshotPolicy, PolicyOption cacheFailuresPolicy, PolicyOption errorPolicy,
367 saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
368 errorPolicy, PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT, disabled );
371 protected void saveConnector(String sourceRepoId, String targetRepoId, PolicyOption checksumPolicy, PolicyOption releasePolicy,
372 PolicyOption snapshotPolicy, PolicyOption cacheFailuresPolicy, PolicyOption errorPolicy,
373 PolicyOption errorOnUpdatePolicy, boolean disabled )
375 ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
376 connectorConfig.setSourceRepoId( sourceRepoId );
377 connectorConfig.setTargetRepoId( targetRepoId );
378 connectorConfig.setProxyId(sourceRepoId);
379 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, checksumPolicy.getId() );
380 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, releasePolicy.getId() );
381 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, snapshotPolicy.getId() );
382 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, cacheFailuresPolicy.getId());
383 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS, errorPolicy.getId() );
384 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE, errorOnUpdatePolicy.getId() );
385 connectorConfig.setDisabled( disabled );
387 int count = config.getConfiguration().getProxyConnectors().size();
388 config.getConfiguration().addProxyConnector( connectorConfig );
390 // Proper Triggering ...
391 String prefix = "proxyConnectors.proxyConnector(" + count + ")";
392 config.triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
393 config.triggerChange( prefix + ".targetRepoId", connectorConfig.getTargetRepoId() );
394 config.triggerChange( prefix + ".proxyId", connectorConfig.getProxyId() );
395 config.triggerChange( prefix + ".policies.releases", connectorConfig.getPolicy( "releases", "" ) );
396 config.triggerChange( prefix + ".policies.checksum", connectorConfig.getPolicy( "checksum", "" ) );
397 config.triggerChange( prefix + ".policies.snapshots", connectorConfig.getPolicy( "snapshots", "" ) );
398 config.triggerChange( prefix + ".policies.cache-failures", connectorConfig.getPolicy( "cache-failures", "" ) );
399 config.triggerChange( prefix + ".policies.propagate-errors",
400 connectorConfig.getPolicy( "propagate-errors", "" ) );
401 config.triggerChange( prefix + ".policies.propagate-errors-on-update",
402 connectorConfig.getPolicy( "propagate-errors-on-update", "" ) );
405 protected void saveManagedRepositoryConfig( String id, String name, String path, String layout )
407 ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration();
409 repoConfig.setId( id );
410 repoConfig.setName( name );
411 repoConfig.setLayout( layout );
413 repoConfig.setLocation( path );
415 int count = config.getConfiguration().getManagedRepositories().size();
416 config.getConfiguration().addManagedRepository( repoConfig );
418 String prefix = "managedRepositories.managedRepository(" + count + ")";
419 config.triggerChange( prefix + ".id", repoConfig.getId() );
420 config.triggerChange( prefix + ".name", repoConfig.getName() );
421 config.triggerChange( prefix + ".location", repoConfig.getLocation() );
422 config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
425 protected void saveRemoteRepositoryConfig( String id, String name, String url, String layout )
427 RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
429 repoConfig.setId( id );
430 repoConfig.setName( name );
431 repoConfig.setLayout( layout );
432 repoConfig.setUrl( url );
434 int count = config.getConfiguration().getRemoteRepositories().size();
435 config.getConfiguration().addRemoteRepository( repoConfig );
437 String prefix = "remoteRepositories.remoteRepository(" + count + ")";
438 config.triggerChange( prefix + ".id", repoConfig.getId() );
439 config.triggerChange( prefix + ".name", repoConfig.getName() );
440 config.triggerChange( prefix + ".url", repoConfig.getUrl() );
441 config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
442 repositoryRegistry.reload();
445 protected Path saveTargetedRepositoryConfig( String id, String originalPath, String targetPath, String layout )
448 Path repoLocation = Paths.get( targetPath );
449 org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoLocation );
450 copyDirectoryStructure( Paths.get(originalPath) , repoLocation );
452 saveRemoteRepositoryConfig( id, "Target Repo-" + id, targetPath, layout );
459 * Copy the specified resource directory from the src/test/repository/managed/ to
460 * the testable directory under target/test-repository/managed/${testName}/
462 * @param resourcePath
463 * @throws IOException
465 protected void setupTestableManagedRepository( String resourcePath )
468 String resourceDir = resourcePath;
470 if ( !resourcePath.endsWith( "/" ) )
472 int idx = resourcePath.lastIndexOf( '/' );
473 resourceDir = resourcePath.substring( 0, idx );
476 Path sourceRepoDir = Paths.get( REPOPATH_DEFAULT_MANAGED );
477 Path sourceDir = sourceRepoDir.resolve(resourceDir );
479 Path destRepoDir = managedDefaultDir;
480 Path destDir = destRepoDir.resolve(resourceDir );
482 // Cleanout destination dirs.
483 if ( Files.exists(destDir))
485 org.apache.archiva.common.utils.FileUtils.deleteDirectory( destDir );
488 // Make the destination dir.
489 Files.createDirectories(destDir);
491 // Test the source dir.
492 if ( !Files.exists(sourceDir) )
494 // This is just a warning.
495 log.error( "[WARN] Skipping setup of testable managed repository, source dir does not exist: {}", //
501 // Test that the source is a dir.
502 if ( !Files.isDirectory( sourceDir) )
504 fail( "Unable to setup testable managed repository, source is not a directory: " + sourceDir );
507 // Copy directory structure.
508 copyDirectoryStructure( sourceDir, destDir );
512 protected void setManagedNewerThanRemote( Path managedFile, Path remoteFile )
514 setManagedNewerThanRemote( managedFile, remoteFile, 55000 );
517 protected void setManagedNewerThanRemote( Path managedFile, Path remoteFile, long time )
519 assertTrue( "Managed File should exist: ", Files.exists(managedFile) );
520 assertTrue( "Remote File should exist: ", Files.exists(remoteFile) );
524 Files.setLastModifiedTime( managedFile,
525 FileTime.from(Files.getLastModifiedTime( remoteFile ).toMillis() + time, TimeUnit.MILLISECONDS ));
527 catch ( IOException e )
529 e.printStackTrace( );
534 assertTrue( Files.getLastModifiedTime( managedFile).compareTo( Files.getLastModifiedTime( remoteFile )) > 0);
536 catch ( IOException e )
538 e.printStackTrace( );
542 protected void setManagedOlderThanRemote( Path managedFile, Path remoteFile )
544 setManagedOlderThanRemote( managedFile, remoteFile, 55000 );
547 protected void setManagedOlderThanRemote( Path managedFile, Path remoteFile, long time )
549 assertTrue( "Managed File should exist: ", Files.exists(managedFile) );
550 assertTrue( "Remote File should exist: ", Files.exists(remoteFile) );
554 Files.setLastModifiedTime( managedFile,
555 FileTime.from(Files.getLastModifiedTime( remoteFile ).toMillis() - time, TimeUnit.MILLISECONDS ));
557 catch ( IOException e )
559 e.printStackTrace( );
564 assertTrue( Files.getLastModifiedTime( managedFile ).compareTo(Files.getLastModifiedTime( remoteFile )) < 0 );
566 catch ( IOException e )
568 e.printStackTrace( );
573 protected void assertNotModified( Path file, long expectedModificationTime )
577 assertEquals( "File <" + file.toAbsolutePath() + "> not have been modified.", expectedModificationTime,
578 Files.getLastModifiedTime( file ).toMillis());
580 catch ( IOException e )
582 e.printStackTrace( );
587 protected void assertNotExistsInManagedDefaultRepo( Path testFile )
590 Path managedDefaultPath = managedDefaultDir;
592 assertTrue( "Unit Test Failure: File <" + testFile
593 + "> should be have been defined within the managed default path of <" + managedDefaultPath
594 + ">", testFile.startsWith( managedDefaultPath ) );
596 assertFalse( "File < " + testFile + "> should not exist in managed default repository.", Files.exists(testFile) );
599 protected static Date getFutureDate()
600 throws ParseException
602 Calendar cal = Calendar.getInstance();
603 cal.add( Calendar.YEAR, 1 );
604 return cal.getTime();
607 protected static Date getPastDate()
608 throws ParseException
610 return new SimpleDateFormat( "yyyy-MM-dd", Locale.US ).parse( "2000-01-01" );