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
54 * @author <a href="mailto:joakime@apache.org">Joakim Erdfelt</a>
57 public abstract class AbstractProxyTestCase
58 extends PlexusInSpringTestCase
60 protected static final String ID_LEGACY_PROXIED = "legacy-proxied";
62 protected static final String ID_PROXIED1 = "proxied1";
64 protected static final String ID_PROXIED1_TARGET = "proxied1-target";
66 protected static final String ID_PROXIED2 = "proxied2";
68 protected static final String ID_PROXIED2_TARGET = "proxied2-target";
70 protected static final String ID_DEFAULT_MANAGED = "default-managed-repository";
72 protected static final String ID_LEGACY_MANAGED = "legacy-managed-repository";
74 protected static final String REPOPATH_PROXIED_LEGACY = "src/test/repositories/legacy-proxied";
76 protected static final String REPOPATH_PROXIED1 = "src/test/repositories/proxied1";
78 protected static final String REPOPATH_PROXIED1_TARGET = "target/test-repository/proxied1";
80 protected static final String REPOPATH_PROXIED2 = "src/test/repositories/proxied2";
82 protected static final String REPOPATH_PROXIED2_TARGET = "target/test-repository/proxied2";
84 protected static final String REPOPATH_DEFAULT_MANAGED = "src/test/repositories/managed";
86 // protected static final String REPOPATH_DEFAULT_MANAGED_TARGET = "target/test-repository/managed";
88 protected static final String REPOPATH_LEGACY_MANAGED = "src/test/repositories/legacy-managed";
90 protected static final String REPOPATH_LEGACY_MANAGED_TARGET = "target/test-repository/legacy-managed";
92 protected static final ArgumentsMatcher customWagonGetIfNewerMatcher = new ArgumentsMatcher() {
94 public boolean matches(Object[] expected, Object[] actual) {
95 if (expected.length < 1 || actual.length < 1)
99 return MockControl.ARRAY_MATCHER.matches(ArrayUtils.remove(expected, 1), ArrayUtils.remove(actual, 1));
102 public String toString(Object[] arguments) {
103 return ArrayUtils.toString(arguments);
107 protected static final ArgumentsMatcher customWagonGetMatcher = new ArgumentsMatcher() {
109 public boolean matches(Object[] expected, Object[] actual)
111 if (expected.length == 2 && actual.length == 2)
113 if (expected[0] == null && actual[0] == null)
118 if (expected[0] == null)
120 return actual[0] == null;
123 if (actual[0] == null)
125 return expected[0] == null;
128 return expected[0].equals(actual[0]);
133 public String toString(Object[] arguments)
135 return ArrayUtils.toString(arguments);
139 protected MockControl wagonMockControl;
141 protected Wagon wagonMock;
143 protected RepositoryProxyConnectors proxyHandler;
145 protected ManagedRepositoryContent managedDefaultRepository;
147 protected File managedDefaultDir;
149 protected ManagedRepositoryContent managedLegacyRepository;
151 protected File managedLegacyDir;
153 protected MockConfiguration config;
155 protected void assertChecksums( File expectedFile, String expectedSha1Contents, String expectedMd5Contents )
158 File sha1File = new File( expectedFile.getAbsolutePath() + ".sha1" );
159 File md5File = new File( expectedFile.getAbsolutePath() + ".md5" );
161 if ( expectedSha1Contents == null )
163 assertFalse( "SHA1 File should NOT exist: " + sha1File.getPath(), sha1File.exists() );
167 assertTrue( "SHA1 File should exist: " + sha1File.getPath(), sha1File.exists() );
168 String actualSha1Contents = readChecksumFile( sha1File );
169 assertEquals( "SHA1 File contents: " + sha1File.getPath(), expectedSha1Contents, actualSha1Contents );
172 if ( expectedMd5Contents == null )
174 assertFalse( "MD5 File should NOT exist: " + md5File.getPath(), md5File.exists() );
178 assertTrue( "MD5 File should exist: " + md5File.getPath(), md5File.exists() );
179 String actualMd5Contents = readChecksumFile( md5File );
180 assertEquals( "MD5 File contents: " + md5File.getPath(), expectedMd5Contents, actualMd5Contents );
184 protected void assertFileEquals( File expectedFile, File actualFile, File sourceFile )
187 assertNotNull( "Expected File should not be null.", expectedFile );
188 assertNotNull( "Actual File should not be null.", actualFile );
190 assertTrue( "Check actual file exists.", actualFile.exists() );
191 assertEquals( "Check filename path is appropriate.", expectedFile.getCanonicalPath(), actualFile.getCanonicalPath() );
192 assertEquals( "Check file path matches.", expectedFile.getAbsolutePath(), actualFile.getAbsolutePath() );
194 String expectedContents = FileUtils.readFileToString( sourceFile, null );
195 String actualContents = FileUtils.readFileToString( actualFile, null );
196 assertEquals( "Check file contents.", expectedContents, actualContents );
199 protected void assertNotDownloaded( File downloadedFile )
201 assertNull( "Found file: " + downloadedFile + "; but was expecting a failure", downloadedFile );
204 protected void assertNoTempFiles( File expectedFile )
206 File workingDir = expectedFile.getParentFile();
207 if ( ( workingDir == null ) || !workingDir.isDirectory() )
212 Collection<File> tmpFiles = FileUtils.listFiles( workingDir, new String[] { "tmp" }, false );
213 if ( !tmpFiles.isEmpty() )
215 StringBuffer emsg = new StringBuffer();
216 emsg.append( "Found Temp Files in dir: " ).append( workingDir.getPath() );
217 for ( File tfile : tmpFiles )
219 emsg.append( "\n " ).append( tfile.getName() );
221 fail( emsg.toString() );
226 * A faster recursive copy that omits .svn directories.
228 * @param sourceDirectory the source directory to copy
229 * @param destDirectory the target location
230 * @throws java.io.IOException if there is a copying problem
231 * @todo get back into plexus-utils, share with converter module
233 protected void copyDirectoryStructure( File sourceDirectory, File destDirectory )
236 if ( !sourceDirectory.exists() )
238 throw new IOException( "Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")." );
241 File[] files = sourceDirectory.listFiles();
243 String sourcePath = sourceDirectory.getAbsolutePath();
245 for ( int i = 0; i < files.length; i++ )
247 File file = files[i];
249 String dest = file.getAbsolutePath();
251 dest = dest.substring( sourcePath.length() + 1 );
253 File destination = new File( destDirectory, dest );
257 destination = destination.getParentFile();
259 FileUtils.copyFile( file, new File( destination, file.getName() ), false );
260 // TODO: Change when there is a FileUtils.copyFileToDirectory(file, destination, boolean) option
261 //FileUtils.copyFileToDirectory( file, destination );
263 else if ( file.isDirectory() )
265 if ( !".svn".equals( file.getName() ) )
267 if ( !destination.exists() && !destination.mkdirs() )
269 throw new IOException( "Could not create destination directory '"
270 + destination.getAbsolutePath() + "'." );
273 copyDirectoryStructure( file, destination );
278 throw new IOException( "Unknown file type: " + file.getAbsolutePath() );
283 protected ManagedRepositoryContent createManagedLegacyRepository()
286 return createRepository( "testManagedLegacyRepo", "Test Managed (Legacy) Repository",
287 "src/test/repositories/legacy-managed", "legacy" );
290 protected ManagedRepositoryContent createProxiedLegacyRepository()
293 return createRepository( "testProxiedLegacyRepo", "Test Proxied (Legacy) Repository",
294 "src/test/repositories/legacy-proxied", "legacy" );
297 protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )
300 ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
302 repo.setName( name );
303 repo.setLocation( path );
304 repo.setLayout( layout );
306 ManagedRepositoryContent repoContent = (ManagedRepositoryContent) lookup( ManagedRepositoryContent.class,
308 repoContent.setRepository( repo );
313 * Read the first line from the checksum file, and return it (trimmed).
315 protected String readChecksumFile( File checksumFile )
318 FileReader freader = null;
319 BufferedReader buf = null;
323 freader = new FileReader( checksumFile );
324 buf = new BufferedReader( freader );
325 return buf.readLine();
334 if ( freader != null )
341 protected void saveConnector( String sourceRepoId, String targetRepoId )
343 saveConnector( sourceRepoId, targetRepoId, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS,
344 SnapshotsPolicy.ALWAYS, CachedFailuresPolicy.NO );
347 protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
348 String snapshotPolicy, String cacheFailuresPolicy )
350 saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
351 PropagateErrorsDownloadPolicy.QUEUE );
354 protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
355 String snapshotPolicy, String cacheFailuresPolicy, String errorPolicy )
357 saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
358 errorPolicy, PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT );
361 protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
362 String snapshotPolicy, String cacheFailuresPolicy, String errorPolicy,
363 String errorOnUpdatePolicy )
365 ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
366 connectorConfig.setSourceRepoId( sourceRepoId );
367 connectorConfig.setTargetRepoId( targetRepoId );
368 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, checksumPolicy );
369 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, releasePolicy );
370 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, snapshotPolicy );
371 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, cacheFailuresPolicy );
372 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS, errorPolicy );
373 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE, errorOnUpdatePolicy );
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: "
555 // Test that the source is a dir.
556 if ( !sourceDir.isDirectory() )
558 fail( "Unable to setup testable managed repository, source is not a directory: " + sourceDir );
561 // Copy directory structure.
562 copyDirectoryStructure( sourceDir, destDir );
565 protected void setManagedNewerThanRemote( File managedFile, File remoteFile )
567 assertTrue( "Managed File should exist: ", managedFile.exists() );
568 assertTrue( "Remote File should exist: ", remoteFile.exists() );
570 managedFile.setLastModified( remoteFile.lastModified() + 55000 );
573 protected void setManagedOlderThanRemote( File managedFile, File remoteFile )
575 assertTrue( "Managed File should exist: ", managedFile.exists() );
576 assertTrue( "Remote File should exist: ", remoteFile.exists() );
578 managedFile.setLastModified( remoteFile.lastModified() - 55000 );
581 protected void assertNotModified( File file, long expectedModificationTime )
583 assertEquals( "File <" + file.getAbsolutePath() + "> not have been modified.",
584 expectedModificationTime, file.lastModified() );
587 protected void assertNotExistsInManagedLegacyRepo( File file )
590 String managedLegacyPath = managedLegacyDir.getCanonicalPath();
591 String testFile = file.getCanonicalPath();
593 assertTrue( "Unit Test Failure: File <" + testFile
594 + "> should be have been defined within the legacy managed path of <" + managedLegacyPath + ">", testFile
595 .startsWith( managedLegacyPath ) );
597 assertFalse( "File < " + testFile + "> should not exist in managed legacy repository.", file.exists() );
600 protected void assertNotExistsInManagedDefaultRepo( File file )
603 String managedDefaultPath = managedDefaultDir.getCanonicalPath();
604 String testFile = file.getCanonicalPath();
606 assertTrue( "Unit Test Failure: File <" + testFile
607 + "> should be have been defined within the managed default path of <" + managedDefaultPath + ">", testFile
608 .startsWith( managedDefaultPath ) );
610 assertFalse( "File < " + testFile + "> should not exist in managed default repository.", file.exists() );
613 protected static Date getFutureDate()
614 throws ParseException
616 Calendar cal = Calendar.getInstance();
617 cal.add( Calendar.YEAR, 1 );
618 return cal.getTime();
621 protected static Date getPastDate()
622 throws ParseException
624 return new SimpleDateFormat( "yyyy-MM-dd", Locale.US ).parse( "2000-01-01" );