1 package org.apache.maven.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 java.io.BufferedReader;
24 import java.io.FileReader;
25 import java.io.IOException;
26 import java.text.ParseException;
27 import java.text.SimpleDateFormat;
28 import java.util.Calendar;
29 import java.util.Collection;
30 import java.util.Date;
31 import java.util.Locale;
33 import org.apache.commons.io.FileUtils;
34 import org.apache.commons.lang.ArrayUtils;
35 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
36 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
37 import org.apache.maven.archiva.configuration.ProxyConnectorConfiguration;
38 import org.apache.maven.archiva.configuration.RemoteRepositoryConfiguration;
39 import org.apache.maven.archiva.policies.CachedFailuresPolicy;
40 import org.apache.maven.archiva.policies.ChecksumPolicy;
41 import org.apache.maven.archiva.policies.PropagateErrorsDownloadPolicy;
42 import org.apache.maven.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
43 import org.apache.maven.archiva.policies.ReleasesPolicy;
44 import org.apache.maven.archiva.policies.SnapshotsPolicy;
45 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
46 import org.apache.maven.wagon.Wagon;
47 import org.codehaus.plexus.spring.PlexusInSpringTestCase;
48 import org.easymock.ArgumentsMatcher;
49 import org.easymock.MockControl;
52 * AbstractProxyTestCase
56 public abstract class AbstractProxyTestCase
57 extends PlexusInSpringTestCase
59 protected static final String ID_LEGACY_PROXIED = "legacy-proxied";
61 protected static final String ID_PROXIED1 = "proxied1";
63 protected static final String ID_PROXIED1_TARGET = "proxied1-target";
65 protected static final String ID_PROXIED2 = "proxied2";
67 protected static final String ID_PROXIED2_TARGET = "proxied2-target";
69 protected static final String ID_DEFAULT_MANAGED = "default-managed-repository";
71 protected static final String ID_LEGACY_MANAGED = "legacy-managed-repository";
73 protected static final String REPOPATH_PROXIED_LEGACY = "src/test/repositories/legacy-proxied";
75 protected static final String REPOPATH_PROXIED1 = "src/test/repositories/proxied1";
77 protected static final String REPOPATH_PROXIED1_TARGET = "target/test-repository/proxied1";
79 protected static final String REPOPATH_PROXIED2 = "src/test/repositories/proxied2";
81 protected static final String REPOPATH_PROXIED2_TARGET = "target/test-repository/proxied2";
83 protected static final String REPOPATH_DEFAULT_MANAGED = "src/test/repositories/managed";
85 // protected static final String REPOPATH_DEFAULT_MANAGED_TARGET = "target/test-repository/managed";
87 protected static final String REPOPATH_LEGACY_MANAGED = "src/test/repositories/legacy-managed";
89 protected static final String REPOPATH_LEGACY_MANAGED_TARGET = "target/test-repository/legacy-managed";
91 protected static final ArgumentsMatcher customWagonGetIfNewerMatcher = new ArgumentsMatcher() {
93 public boolean matches(Object[] expected, Object[] actual) {
94 if (expected.length < 1 || actual.length < 1)
98 return MockControl.ARRAY_MATCHER.matches(ArrayUtils.remove(expected, 1), ArrayUtils.remove(actual, 1));
101 public String toString(Object[] arguments) {
102 return ArrayUtils.toString(arguments);
106 protected static final ArgumentsMatcher customWagonGetMatcher = new ArgumentsMatcher() {
108 public boolean matches(Object[] expected, Object[] actual)
110 if (expected.length == 2 && actual.length == 2)
112 if (expected[0] == null && actual[0] == null)
117 if (expected[0] == null)
119 return actual[0] == null;
122 if (actual[0] == null)
124 return expected[0] == null;
127 return expected[0].equals(actual[0]);
132 public String toString(Object[] arguments)
134 return ArrayUtils.toString(arguments);
138 protected MockControl wagonMockControl;
140 protected Wagon wagonMock;
142 protected RepositoryProxyConnectors proxyHandler;
144 protected ManagedRepositoryContent managedDefaultRepository;
146 protected File managedDefaultDir;
148 protected ManagedRepositoryContent managedLegacyRepository;
150 protected File managedLegacyDir;
152 protected MockConfiguration config;
154 protected void assertChecksums( File expectedFile, String expectedSha1Contents, String expectedMd5Contents )
157 File sha1File = new File( expectedFile.getAbsolutePath() + ".sha1" );
158 File md5File = new File( expectedFile.getAbsolutePath() + ".md5" );
160 if ( expectedSha1Contents == null )
162 assertFalse( "SHA1 File should NOT exist: " + sha1File.getPath(), sha1File.exists() );
166 assertTrue( "SHA1 File should exist: " + sha1File.getPath(), sha1File.exists() );
167 String actualSha1Contents = readChecksumFile( sha1File );
168 assertEquals( "SHA1 File contents: " + sha1File.getPath(), expectedSha1Contents, actualSha1Contents );
171 if ( expectedMd5Contents == null )
173 assertFalse( "MD5 File should NOT exist: " + md5File.getPath(), md5File.exists() );
177 assertTrue( "MD5 File should exist: " + md5File.getPath(), md5File.exists() );
178 String actualMd5Contents = readChecksumFile( md5File );
179 assertEquals( "MD5 File contents: " + md5File.getPath(), expectedMd5Contents, actualMd5Contents );
183 protected void assertFileEquals( File expectedFile, File actualFile, File sourceFile )
186 assertNotNull( "Expected File should not be null.", expectedFile );
187 assertNotNull( "Actual File should not be null.", actualFile );
189 assertTrue( "Check actual file exists.", actualFile.exists() );
190 assertEquals( "Check filename path is appropriate.", expectedFile.getCanonicalPath(), actualFile.getCanonicalPath() );
191 assertEquals( "Check file path matches.", expectedFile.getAbsolutePath(), actualFile.getAbsolutePath() );
193 String expectedContents = FileUtils.readFileToString( sourceFile, null );
194 String actualContents = FileUtils.readFileToString( actualFile, null );
195 assertEquals( "Check file contents.", expectedContents, actualContents );
198 protected void assertNotDownloaded( File downloadedFile )
200 assertNull( "Found file: " + downloadedFile + "; but was expecting a failure", downloadedFile );
203 protected void assertNoTempFiles( File expectedFile )
205 File workingDir = expectedFile.getParentFile();
206 if ( ( workingDir == null ) || !workingDir.isDirectory() )
211 Collection<File> tmpFiles = FileUtils.listFiles( workingDir, new String[] { "tmp" }, false );
212 if ( !tmpFiles.isEmpty() )
214 StringBuffer emsg = new StringBuffer();
215 emsg.append( "Found Temp Files in dir: " ).append( workingDir.getPath() );
216 for ( File tfile : tmpFiles )
218 emsg.append( "\n " ).append( tfile.getName() );
220 fail( emsg.toString() );
225 * A faster recursive copy that omits .svn directories.
227 * @param sourceDirectory the source directory to copy
228 * @param destDirectory the target location
229 * @throws java.io.IOException if there is a copying problem
230 * @todo get back into plexus-utils, share with converter module
232 protected void copyDirectoryStructure( File sourceDirectory, File destDirectory )
235 if ( !sourceDirectory.exists() )
237 throw new IOException( "Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")." );
240 File[] files = sourceDirectory.listFiles();
242 String sourcePath = sourceDirectory.getAbsolutePath();
244 for ( int i = 0; i < files.length; i++ )
246 File file = files[i];
248 String dest = file.getAbsolutePath();
250 dest = dest.substring( sourcePath.length() + 1 );
252 File destination = new File( destDirectory, dest );
256 destination = destination.getParentFile();
258 FileUtils.copyFile( file, new File( destination, file.getName() ), false );
259 // TODO: Change when there is a FileUtils.copyFileToDirectory(file, destination, boolean) option
260 //FileUtils.copyFileToDirectory( file, destination );
262 else if ( file.isDirectory() )
264 if ( !".svn".equals( file.getName() ) )
266 if ( !destination.exists() && !destination.mkdirs() )
268 throw new IOException( "Could not create destination directory '"
269 + destination.getAbsolutePath() + "'." );
272 copyDirectoryStructure( file, destination );
277 throw new IOException( "Unknown file type: " + file.getAbsolutePath() );
282 protected ManagedRepositoryContent createManagedLegacyRepository()
285 return createRepository( "testManagedLegacyRepo", "Test Managed (Legacy) Repository",
286 "src/test/repositories/legacy-managed", "legacy" );
289 protected ManagedRepositoryContent createProxiedLegacyRepository()
292 return createRepository( "testProxiedLegacyRepo", "Test Proxied (Legacy) Repository",
293 "src/test/repositories/legacy-proxied", "legacy" );
296 protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )
299 ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
301 repo.setName( name );
302 repo.setLocation( path );
303 repo.setLayout( layout );
305 ManagedRepositoryContent repoContent = (ManagedRepositoryContent) lookup( ManagedRepositoryContent.class,
307 repoContent.setRepository( repo );
312 * Read the first line from the checksum file, and return it (trimmed).
314 protected String readChecksumFile( File checksumFile )
317 FileReader freader = null;
318 BufferedReader buf = null;
322 freader = new FileReader( checksumFile );
323 buf = new BufferedReader( freader );
324 return buf.readLine();
333 if ( freader != null )
340 protected void saveConnector( String sourceRepoId, String targetRepoId, boolean disabled )
342 saveConnector( sourceRepoId, targetRepoId, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
343 SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO, disabled );
346 protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
347 String snapshotPolicy, String cacheFailuresPolicy, boolean disabled )
349 saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
350 PropagateErrorsDownloadPolicy.QUEUE, disabled );
353 protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
354 String snapshotPolicy, String cacheFailuresPolicy, String errorPolicy, boolean disabled )
356 saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
357 errorPolicy, PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT, disabled );
360 protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
361 String snapshotPolicy, String cacheFailuresPolicy, String errorPolicy,
362 String errorOnUpdatePolicy, boolean disabled )
364 ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
365 connectorConfig.setSourceRepoId( sourceRepoId );
366 connectorConfig.setTargetRepoId( targetRepoId );
367 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, checksumPolicy );
368 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, releasePolicy );
369 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, snapshotPolicy );
370 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, cacheFailuresPolicy );
371 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS, errorPolicy );
372 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE, errorOnUpdatePolicy );
373 connectorConfig.setDisabled(disabled);
375 int count = config.getConfiguration().getProxyConnectors().size();
376 config.getConfiguration().addProxyConnector( connectorConfig );
378 // Proper Triggering ...
379 String prefix = "proxyConnectors.proxyConnector(" + count + ")";
380 config.triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
381 config.triggerChange( prefix + ".targetRepoId", connectorConfig.getTargetRepoId() );
382 config.triggerChange( prefix + ".proxyId", connectorConfig.getProxyId() );
383 config.triggerChange( prefix + ".policies.releases", connectorConfig.getPolicy( "releases", "" ) );
384 config.triggerChange( prefix + ".policies.checksum", connectorConfig.getPolicy( "checksum", "" ) );
385 config.triggerChange( prefix + ".policies.snapshots", connectorConfig.getPolicy( "snapshots", "" ) );
386 config.triggerChange( prefix + ".policies.cache-failures", connectorConfig.getPolicy( "cache-failures", "" ) );
387 config.triggerChange( prefix + ".policies.propagate-errors",
388 connectorConfig.getPolicy( "propagate-errors", "" ) );
389 config.triggerChange( prefix + ".policies.propagate-errors-on-update",
390 connectorConfig.getPolicy( "propagate-errors-on-update", "" ) );
393 protected void saveManagedRepositoryConfig( String id, String name, String path, String layout )
395 ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration();
397 repoConfig.setId( id );
398 repoConfig.setName( name );
399 repoConfig.setLayout( layout );
401 repoConfig.setLocation( path );
403 int count = config.getConfiguration().getManagedRepositories().size();
404 config.getConfiguration().addManagedRepository( repoConfig );
406 String prefix = "managedRepositories.managedRepository(" + count + ")";
407 config.triggerChange( prefix + ".id", repoConfig.getId() );
408 config.triggerChange( prefix + ".name", repoConfig.getName() );
409 config.triggerChange( prefix + ".location", repoConfig.getLocation() );
410 config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
413 protected void saveRemoteRepositoryConfig( String id, String name, String url, String layout )
415 RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
417 repoConfig.setId( id );
418 repoConfig.setName( name );
419 repoConfig.setLayout( layout );
420 repoConfig.setUrl( url );
422 int count = config.getConfiguration().getRemoteRepositories().size();
423 config.getConfiguration().addRemoteRepository( repoConfig );
425 String prefix = "remoteRepositories.remoteRepository(" + count + ")";
426 config.triggerChange( prefix + ".id", repoConfig.getId() );
427 config.triggerChange( prefix + ".name", repoConfig.getName() );
428 config.triggerChange( prefix + ".url", repoConfig.getUrl() );
429 config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
432 protected File saveTargetedRepositoryConfig( String id, String originalPath, String targetPath, String layout )
435 File repoLocation = getTestFile( targetPath );
436 FileUtils.deleteDirectory( repoLocation );
437 copyDirectoryStructure( getTestFile( originalPath ), repoLocation );
439 saveRemoteRepositoryConfig( id, "Target Repo-" + id, targetPath, layout );
446 * @see org.codehaus.plexus.spring.PlexusInSpringTestCase#getConfigLocation()
449 protected String getSpringConfigLocation()
451 return "org/apache/maven/archiva/proxy/spring-context.xml";
455 protected void setUp()
460 config = (MockConfiguration) lookup( ArchivaConfiguration.class.getName(), "mock" );
462 // Setup source repository (using default layout)
463 String repoPath = "target/test-repository/managed/" + getName();
464 File repoLocation = getTestFile( repoPath );
466 managedDefaultRepository = createRepository( ID_DEFAULT_MANAGED, "Default Managed Repository", repoPath,
469 managedDefaultDir = new File( managedDefaultRepository.getRepoRoot() );
471 ManagedRepositoryConfiguration repoConfig = managedDefaultRepository.getRepository();
473 config.getConfiguration().addManagedRepository( repoConfig );
475 // Setup source repository (using legacy layout)
476 repoLocation = getTestFile( REPOPATH_LEGACY_MANAGED_TARGET );
477 FileUtils.deleteDirectory( repoLocation );
478 copyDirectoryStructure( getTestFile( REPOPATH_LEGACY_MANAGED ), repoLocation );
480 managedLegacyRepository = createRepository( ID_LEGACY_MANAGED, "Legacy Managed Repository",
481 REPOPATH_LEGACY_MANAGED_TARGET, "legacy" );
483 managedLegacyDir = new File( managedLegacyRepository.getRepoRoot() );
485 repoConfig = managedLegacyRepository.getRepository();
487 config.getConfiguration().addManagedRepository( repoConfig );
489 // Setup target (proxied to) repository.
490 saveRemoteRepositoryConfig( ID_PROXIED1, "Proxied Repository 1", new File( REPOPATH_PROXIED1 ).toURL()
491 .toExternalForm(), "default" );
493 // Setup target (proxied to) repository.
494 saveRemoteRepositoryConfig( ID_PROXIED2, "Proxied Repository 2", new File( REPOPATH_PROXIED2 ).toURL()
495 .toExternalForm(), "default" );
497 // Setup target (proxied to) repository using legacy layout.
498 saveRemoteRepositoryConfig( ID_LEGACY_PROXIED, "Proxied Legacy Repository", new File( REPOPATH_PROXIED_LEGACY )
499 .toURL().toExternalForm(), "legacy" );
501 // Setup the proxy handler.
502 proxyHandler = (RepositoryProxyConnectors) lookup( RepositoryProxyConnectors.class.getName() );
504 // Setup the wagon mock.
505 wagonMockControl = MockControl.createNiceControl( Wagon.class );
506 wagonMock = (Wagon) wagonMockControl.getMock();
507 WagonDelegate delegate = (WagonDelegate) lookup( Wagon.ROLE, "test" );
508 delegate.setDelegate( wagonMock );
510 System.out.println( "\n.\\ " + getName() + "() \\._________________________________________\n" );
514 * Copy the specified resource directory from the src/test/repository/managed/ to
515 * the testable directory under target/test-repository/managed/${testName}/
518 * @throws IOException
520 protected void setupTestableManagedRepository( String resourcePath )
523 String resourceDir = resourcePath;
525 if ( !resourcePath.endsWith( "/" ) )
527 int idx = resourcePath.lastIndexOf( '/' );
528 resourceDir = resourcePath.substring( 0, idx );
531 File sourceRepoDir = new File( REPOPATH_DEFAULT_MANAGED );
532 File sourceDir = new File( sourceRepoDir, resourceDir );
534 File destRepoDir = managedDefaultDir;
535 File destDir = new File( destRepoDir, resourceDir );
537 // Cleanout destination dirs.
538 if ( destDir.exists() )
540 FileUtils.deleteDirectory( destDir );
543 // Make the destination dir.
546 // Test the source dir.
547 if ( !sourceDir.exists() )
549 // This is just a warning.
550 System.err.println( "[WARN] Skipping setup of testable managed repository, source dir does not exist: "
556 // Test that the source is a dir.
557 if ( !sourceDir.isDirectory() )
559 fail( "Unable to setup testable managed repository, source is not a directory: " + sourceDir );
562 // Copy directory structure.
563 copyDirectoryStructure( sourceDir, destDir );
567 protected void setManagedNewerThanRemote( File managedFile, File remoteFile )
569 assertTrue( "Managed File should exist: ", managedFile.exists() );
570 assertTrue( "Remote File should exist: ", remoteFile.exists() );
572 managedFile.setLastModified( remoteFile.lastModified() + 55000 );
575 protected void setManagedOlderThanRemote( File managedFile, File remoteFile )
577 assertTrue( "Managed File should exist: ", managedFile.exists() );
578 assertTrue( "Remote File should exist: ", remoteFile.exists() );
580 managedFile.setLastModified( remoteFile.lastModified() - 55000 );
583 protected void assertNotModified( File file, long expectedModificationTime )
585 assertEquals( "File <" + file.getAbsolutePath() + "> not have been modified.",
586 expectedModificationTime, file.lastModified() );
589 protected void assertNotExistsInManagedLegacyRepo( File file )
592 String managedLegacyPath = managedLegacyDir.getCanonicalPath();
593 String testFile = file.getCanonicalPath();
595 assertTrue( "Unit Test Failure: File <" + testFile
596 + "> should be have been defined within the legacy managed path of <" + managedLegacyPath + ">", testFile
597 .startsWith( managedLegacyPath ) );
599 assertFalse( "File < " + testFile + "> should not exist in managed legacy repository.", file.exists() );
602 protected void assertNotExistsInManagedDefaultRepo( File file )
605 String managedDefaultPath = managedDefaultDir.getCanonicalPath();
606 String testFile = file.getCanonicalPath();
608 assertTrue( "Unit Test Failure: File <" + testFile
609 + "> should be have been defined within the managed default path of <" + managedDefaultPath + ">", testFile
610 .startsWith( managedDefaultPath ) );
612 assertFalse( "File < " + testFile + "> should not exist in managed default repository.", file.exists() );
615 protected static Date getFutureDate()
616 throws ParseException
618 Calendar cal = Calendar.getInstance();
619 cal.add( Calendar.YEAR, 1 );
620 return cal.getTime();
623 protected static Date getPastDate()
624 throws ParseException
626 return new SimpleDateFormat( "yyyy-MM-dd", Locale.US ).parse( "2000-01-01" );