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 junit.framework.TestCase;
23 import net.sf.ehcache.CacheManager;
24 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
25 import org.apache.commons.lang.ArrayUtils;
26 import org.apache.commons.lang.StringUtils;
27 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
28 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
29 import org.apache.maven.archiva.configuration.ProxyConnectorConfiguration;
30 import org.apache.maven.archiva.configuration.RemoteRepositoryConfiguration;
31 import org.apache.maven.archiva.policies.CachedFailuresPolicy;
32 import org.apache.maven.archiva.policies.ChecksumPolicy;
33 import org.apache.maven.archiva.policies.PropagateErrorsDownloadPolicy;
34 import org.apache.maven.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
35 import org.apache.maven.archiva.policies.ReleasesPolicy;
36 import org.apache.maven.archiva.policies.SnapshotsPolicy;
37 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
38 import org.apache.maven.wagon.Wagon;
39 import org.codehaus.plexus.util.FileUtils;
40 import org.easymock.ArgumentsMatcher;
41 import org.easymock.MockControl;
42 import org.junit.Before;
43 import org.junit.runner.RunWith;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.context.ApplicationContext;
47 import org.springframework.test.context.ContextConfiguration;
48 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
50 import javax.inject.Inject;
51 import java.io.BufferedReader;
53 import java.io.FileReader;
54 import java.io.IOException;
55 import java.text.ParseException;
56 import java.text.SimpleDateFormat;
57 import java.util.ArrayList;
58 import java.util.Calendar;
59 import java.util.Collection;
60 import java.util.Date;
61 import java.util.Locale;
64 * AbstractProxyTestCase
68 @RunWith( SpringJUnit4ClassRunner.class )
69 @ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
70 public abstract class AbstractProxyTestCase
75 protected ApplicationContext applicationContext;
77 protected static final String ID_LEGACY_PROXIED = "legacy-proxied";
79 protected static final String ID_PROXIED1 = "proxied1";
81 protected static final String ID_PROXIED1_TARGET = "proxied1-target";
83 protected static final String ID_PROXIED2 = "proxied2";
85 protected static final String ID_PROXIED2_TARGET = "proxied2-target";
87 protected static final String ID_DEFAULT_MANAGED = "default-managed-repository";
89 protected static final String ID_LEGACY_MANAGED = "legacy-managed-repository";
91 protected static final String REPOPATH_PROXIED_LEGACY = "src/test/repositories/legacy-proxied";
93 protected static final String REPOPATH_PROXIED1 = "src/test/repositories/proxied1";
95 protected static final String REPOPATH_PROXIED1_TARGET = "target/test-repository/proxied1";
97 protected static final String REPOPATH_PROXIED2 = "src/test/repositories/proxied2";
99 protected static final String REPOPATH_PROXIED2_TARGET = "target/test-repository/proxied2";
101 protected static final String REPOPATH_DEFAULT_MANAGED = "src/test/repositories/managed";
103 // protected static final String REPOPATH_DEFAULT_MANAGED_TARGET = "target/test-repository/managed";
105 protected static final String REPOPATH_LEGACY_MANAGED = "src/test/repositories/legacy-managed";
107 protected static final String REPOPATH_LEGACY_MANAGED_TARGET = "target/test-repository/legacy-managed";
109 protected MockControl wagonMockControl;
111 protected Wagon wagonMock;
114 protected RepositoryProxyConnectors proxyHandler;
116 protected ManagedRepositoryContent managedDefaultRepository;
118 protected File managedDefaultDir;
120 protected ManagedRepositoryContent managedLegacyRepository;
122 protected File managedLegacyDir;
124 protected MockConfiguration config;
126 protected Logger log = LoggerFactory.getLogger( getClass() );
128 WagonDelegate delegate;
131 PlexusSisuBridge plexusSisuBridge;
140 (MockConfiguration) applicationContext.getBean( "archivaConfiguration#mock", ArchivaConfiguration.class );
142 config.getConfiguration().setManagedRepositories( new ArrayList<ManagedRepositoryConfiguration>() );
143 config.getConfiguration().setRemoteRepositories( new ArrayList<RemoteRepositoryConfiguration>() );
144 config.getConfiguration().setProxyConnectors( new ArrayList<ProxyConnectorConfiguration>() );
146 // Setup source repository (using default layout)
147 String repoPath = "target/test-repository/managed/" + getName();
148 File repoLocation = new File( repoPath );
150 managedDefaultRepository =
151 createRepository( ID_DEFAULT_MANAGED, "Default Managed Repository", repoPath, "default" );
153 managedDefaultDir = new File( managedDefaultRepository.getRepoRoot() );
155 ManagedRepositoryConfiguration repoConfig = managedDefaultRepository.getRepository();
157 config.getConfiguration().addManagedRepository( repoConfig );
159 // Setup source repository (using legacy layout)
160 repoLocation = new File( REPOPATH_LEGACY_MANAGED_TARGET );
161 if (repoLocation.exists())
163 FileUtils.deleteDirectory( repoLocation );
165 copyDirectoryStructure( new File( REPOPATH_LEGACY_MANAGED ), repoLocation );
167 managedLegacyRepository =
168 createRepository( ID_LEGACY_MANAGED, "Legacy Managed Repository", REPOPATH_LEGACY_MANAGED_TARGET,
173 managedLegacyDir = new File( managedLegacyRepository.getRepoRoot() );
175 repoConfig = managedLegacyRepository.getRepository();
177 config.getConfiguration().addManagedRepository( repoConfig );
179 // Setup target (proxied to) repository.
180 saveRemoteRepositoryConfig( ID_PROXIED1, "Proxied Repository 1",
181 new File( REPOPATH_PROXIED1 ).toURL().toExternalForm(), "default" );
183 // Setup target (proxied to) repository.
184 saveRemoteRepositoryConfig( ID_PROXIED2, "Proxied Repository 2",
185 new File( REPOPATH_PROXIED2 ).toURL().toExternalForm(), "default" );
187 // Setup target (proxied to) repository using legacy layout.
188 saveRemoteRepositoryConfig( ID_LEGACY_PROXIED, "Proxied Legacy Repository",
189 new File( REPOPATH_PROXIED_LEGACY ).toURL().toExternalForm(), "legacy" );
191 // Setup the proxy handler.
192 //proxyHandler = applicationContext.getBean (RepositoryProxyConnectors) lookup( RepositoryProxyConnectors.class.getName() );
195 applicationContext.getBean( "repositoryProxyConnectors#test", RepositoryProxyConnectors.class );
197 // Setup the wagon mock.
198 wagonMockControl = MockControl.createNiceControl( Wagon.class );
199 wagonMock = (Wagon) wagonMockControl.getMock();
201 delegate = (WagonDelegate) plexusSisuBridge.lookup( Wagon.class, "test" );
203 delegate.setDelegate( wagonMock );
205 CacheManager.getInstance().clearAll();
207 log.info( "\n.\\ " + getName() + "() \\._________________________________________\n" );
211 public String getName()
213 return StringUtils.substringAfterLast( getClass().getName(), "." );
216 protected static final ArgumentsMatcher customWagonGetIfNewerMatcher = new ArgumentsMatcher()
219 public boolean matches( Object[] expected, Object[] actual )
221 if ( expected.length < 1 || actual.length < 1 )
225 return MockControl.ARRAY_MATCHER.matches( ArrayUtils.remove( expected, 1 ),
226 ArrayUtils.remove( actual, 1 ) );
229 public String toString( Object[] arguments )
231 return ArrayUtils.toString( arguments );
235 protected static final ArgumentsMatcher customWagonGetMatcher = new ArgumentsMatcher()
238 public boolean matches( Object[] expected, Object[] actual )
240 if ( expected.length == 2 && actual.length == 2 )
242 if ( expected[0] == null && actual[0] == null )
247 if ( expected[0] == null )
249 return actual[0] == null;
252 if ( actual[0] == null )
254 return expected[0] == null;
257 return expected[0].equals( actual[0] );
262 public String toString( Object[] arguments )
264 return ArrayUtils.toString( arguments );
269 protected void assertChecksums( File expectedFile, String expectedSha1Contents, String expectedMd5Contents )
272 File sha1File = new File( expectedFile.getAbsolutePath() + ".sha1" );
273 File md5File = new File( expectedFile.getAbsolutePath() + ".md5" );
275 if ( expectedSha1Contents == null )
277 assertFalse( "SHA1 File should NOT exist: " + sha1File.getPath(), sha1File.exists() );
281 assertTrue( "SHA1 File should exist: " + sha1File.getPath(), sha1File.exists() );
282 String actualSha1Contents = readChecksumFile( sha1File );
283 assertEquals( "SHA1 File contents: " + sha1File.getPath(), expectedSha1Contents, actualSha1Contents );
286 if ( expectedMd5Contents == null )
288 assertFalse( "MD5 File should NOT exist: " + md5File.getPath(), md5File.exists() );
292 assertTrue( "MD5 File should exist: " + md5File.getPath(), md5File.exists() );
293 String actualMd5Contents = readChecksumFile( md5File );
294 assertEquals( "MD5 File contents: " + md5File.getPath(), expectedMd5Contents, actualMd5Contents );
298 protected void assertFileEquals( File expectedFile, File actualFile, File sourceFile )
301 assertNotNull( "Expected File should not be null.", expectedFile );
302 assertNotNull( "Actual File should not be null.", actualFile );
304 assertTrue( "Check actual file exists.", actualFile.exists() );
305 assertEquals( "Check filename path is appropriate.", expectedFile.getCanonicalPath(),
306 actualFile.getCanonicalPath() );
307 assertEquals( "Check file path matches.", expectedFile.getAbsolutePath(), actualFile.getAbsolutePath() );
309 String expectedContents = org.apache.commons.io.FileUtils.readFileToString( sourceFile, null );
310 String actualContents = org.apache.commons.io.FileUtils.readFileToString( actualFile, null );
311 assertEquals( "Check file contents.", expectedContents, actualContents );
314 protected void assertNotDownloaded( File downloadedFile )
316 assertNull( "Found file: " + downloadedFile + "; but was expecting a failure", downloadedFile );
319 @SuppressWarnings( "unchecked" )
320 protected void assertNoTempFiles( File expectedFile )
322 File workingDir = expectedFile.getParentFile();
323 if ( ( workingDir == null ) || !workingDir.isDirectory() )
328 Collection<File> tmpFiles = org.apache.commons.io.FileUtils.listFiles( workingDir, new String[]{ "tmp" }, false );
329 if ( !tmpFiles.isEmpty() )
331 StringBuffer emsg = new StringBuffer();
332 emsg.append( "Found Temp Files in dir: " ).append( workingDir.getPath() );
333 for ( File tfile : tmpFiles )
335 emsg.append( "\n " ).append( tfile.getName() );
337 fail( emsg.toString() );
342 * A faster recursive copy that omits .svn directories.
344 * @param sourceDirectory the source directory to copy
345 * @param destDirectory the target location
346 * @throws java.io.IOException if there is a copying problem
347 * @todo get back into plexus-utils, share with converter module
349 protected void copyDirectoryStructure( File sourceDirectory, File destDirectory )
352 if ( !sourceDirectory.exists() )
354 throw new IOException( "Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")." );
357 File[] files = sourceDirectory.listFiles();
359 String sourcePath = sourceDirectory.getAbsolutePath();
361 for ( int i = 0; i < files.length; i++ )
363 File file = files[i];
365 String dest = file.getAbsolutePath();
367 dest = dest.substring( sourcePath.length() + 1 );
369 File destination = new File( destDirectory, dest );
373 destination = destination.getParentFile();
375 org.apache.commons.io.FileUtils.copyFile( file, new File( destination, file.getName() ), false );
376 // TODO: Change when there is a FileUtils.copyFileToDirectory(file, destination, boolean) option
377 //FileUtils.copyFileToDirectory( file, destination );
379 else if ( file.isDirectory() )
381 if ( !".svn".equals( file.getName() ) )
383 if ( !destination.exists() && !destination.mkdirs() )
385 throw new IOException(
386 "Could not create destination directory '" + destination.getAbsolutePath() + "'." );
389 copyDirectoryStructure( file, destination );
394 throw new IOException( "Unknown file type: " + file.getAbsolutePath() );
399 protected ManagedRepositoryContent createManagedLegacyRepository()
402 return createRepository( "testManagedLegacyRepo", "Test Managed (Legacy) Repository",
403 "src/test/repositories/legacy-managed", "legacy" );
406 protected ManagedRepositoryContent createProxiedLegacyRepository()
409 return createRepository( "testProxiedLegacyRepo", "Test Proxied (Legacy) Repository",
410 "src/test/repositories/legacy-proxied", "legacy" );
413 protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )
416 ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
418 repo.setName( name );
419 repo.setLocation( path );
420 repo.setLayout( layout );
422 ManagedRepositoryContent repoContent =
423 applicationContext.getBean( "managedRepositoryContent#" + layout, ManagedRepositoryContent.class );
424 repoContent.setRepository( repo );
429 * Read the first line from the checksum file, and return it (trimmed).
431 protected String readChecksumFile( File checksumFile )
434 FileReader freader = null;
435 BufferedReader buf = null;
439 freader = new FileReader( checksumFile );
440 buf = new BufferedReader( freader );
441 return buf.readLine();
450 if ( freader != null )
457 protected void saveConnector( String sourceRepoId, String targetRepoId, boolean disabled )
459 saveConnector( sourceRepoId, targetRepoId, ChecksumPolicy.IGNORE, ReleasesPolicy.ALWAYS, SnapshotsPolicy.ALWAYS,
460 CachedFailuresPolicy.NO, disabled );
463 protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
464 String snapshotPolicy, String cacheFailuresPolicy, boolean disabled )
466 saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
467 PropagateErrorsDownloadPolicy.QUEUE, disabled );
470 protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
471 String snapshotPolicy, String cacheFailuresPolicy, String errorPolicy,
474 saveConnector( sourceRepoId, targetRepoId, checksumPolicy, releasePolicy, snapshotPolicy, cacheFailuresPolicy,
475 errorPolicy, PropagateErrorsOnUpdateDownloadPolicy.NOT_PRESENT, disabled );
478 protected void saveConnector( String sourceRepoId, String targetRepoId, String checksumPolicy, String releasePolicy,
479 String snapshotPolicy, String cacheFailuresPolicy, String errorPolicy,
480 String errorOnUpdatePolicy, boolean disabled )
482 ProxyConnectorConfiguration connectorConfig = new ProxyConnectorConfiguration();
483 connectorConfig.setSourceRepoId( sourceRepoId );
484 connectorConfig.setTargetRepoId( targetRepoId );
485 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CHECKSUM, checksumPolicy );
486 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_RELEASES, releasePolicy );
487 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_SNAPSHOTS, snapshotPolicy );
488 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_CACHE_FAILURES, cacheFailuresPolicy );
489 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS, errorPolicy );
490 connectorConfig.addPolicy( ProxyConnectorConfiguration.POLICY_PROPAGATE_ERRORS_ON_UPDATE, errorOnUpdatePolicy );
491 connectorConfig.setDisabled( disabled );
493 int count = config.getConfiguration().getProxyConnectors().size();
494 config.getConfiguration().addProxyConnector( connectorConfig );
496 // Proper Triggering ...
497 String prefix = "proxyConnectors.proxyConnector(" + count + ")";
498 config.triggerChange( prefix + ".sourceRepoId", connectorConfig.getSourceRepoId() );
499 config.triggerChange( prefix + ".targetRepoId", connectorConfig.getTargetRepoId() );
500 config.triggerChange( prefix + ".proxyId", connectorConfig.getProxyId() );
501 config.triggerChange( prefix + ".policies.releases", connectorConfig.getPolicy( "releases", "" ) );
502 config.triggerChange( prefix + ".policies.checksum", connectorConfig.getPolicy( "checksum", "" ) );
503 config.triggerChange( prefix + ".policies.snapshots", connectorConfig.getPolicy( "snapshots", "" ) );
504 config.triggerChange( prefix + ".policies.cache-failures", connectorConfig.getPolicy( "cache-failures", "" ) );
505 config.triggerChange( prefix + ".policies.propagate-errors",
506 connectorConfig.getPolicy( "propagate-errors", "" ) );
507 config.triggerChange( prefix + ".policies.propagate-errors-on-update",
508 connectorConfig.getPolicy( "propagate-errors-on-update", "" ) );
511 protected void saveManagedRepositoryConfig( String id, String name, String path, String layout )
513 ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration();
515 repoConfig.setId( id );
516 repoConfig.setName( name );
517 repoConfig.setLayout( layout );
519 repoConfig.setLocation( path );
521 int count = config.getConfiguration().getManagedRepositories().size();
522 config.getConfiguration().addManagedRepository( repoConfig );
524 String prefix = "managedRepositories.managedRepository(" + count + ")";
525 config.triggerChange( prefix + ".id", repoConfig.getId() );
526 config.triggerChange( prefix + ".name", repoConfig.getName() );
527 config.triggerChange( prefix + ".location", repoConfig.getLocation() );
528 config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
531 protected void saveRemoteRepositoryConfig( String id, String name, String url, String layout )
533 RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
535 repoConfig.setId( id );
536 repoConfig.setName( name );
537 repoConfig.setLayout( layout );
538 repoConfig.setUrl( url );
540 int count = config.getConfiguration().getRemoteRepositories().size();
541 config.getConfiguration().addRemoteRepository( repoConfig );
543 String prefix = "remoteRepositories.remoteRepository(" + count + ")";
544 config.triggerChange( prefix + ".id", repoConfig.getId() );
545 config.triggerChange( prefix + ".name", repoConfig.getName() );
546 config.triggerChange( prefix + ".url", repoConfig.getUrl() );
547 config.triggerChange( prefix + ".layout", repoConfig.getLayout() );
550 protected File saveTargetedRepositoryConfig( String id, String originalPath, String targetPath, String layout )
553 File repoLocation = new File( targetPath );
554 FileUtils.deleteDirectory( repoLocation );
555 copyDirectoryStructure( new File( originalPath ), repoLocation );
557 saveRemoteRepositoryConfig( id, "Target Repo-" + id, targetPath, layout );
564 * Copy the specified resource directory from the src/test/repository/managed/ to
565 * the testable directory under target/test-repository/managed/${testName}/
567 * @param resourcePath
568 * @throws IOException
570 protected void setupTestableManagedRepository( String resourcePath )
573 String resourceDir = resourcePath;
575 if ( !resourcePath.endsWith( "/" ) )
577 int idx = resourcePath.lastIndexOf( '/' );
578 resourceDir = resourcePath.substring( 0, idx );
581 File sourceRepoDir = new File( REPOPATH_DEFAULT_MANAGED );
582 File sourceDir = new File( sourceRepoDir, resourceDir );
584 File destRepoDir = managedDefaultDir;
585 File destDir = new File( destRepoDir, resourceDir );
587 // Cleanout destination dirs.
588 if ( destDir.exists() )
590 FileUtils.deleteDirectory( destDir );
593 // Make the destination dir.
596 // Test the source dir.
597 if ( !sourceDir.exists() )
599 // This is just a warning.
601 "[WARN] Skipping setup of testable managed repository, source dir does not exist: " + sourceDir );
606 // Test that the source is a dir.
607 if ( !sourceDir.isDirectory() )
609 fail( "Unable to setup testable managed repository, source is not a directory: " + sourceDir );
612 // Copy directory structure.
613 copyDirectoryStructure( sourceDir, destDir );
617 protected void setManagedNewerThanRemote( File managedFile, File remoteFile )
619 setManagedNewerThanRemote(managedFile, remoteFile, 55000);
622 protected void setManagedNewerThanRemote( File managedFile, File remoteFile, long time )
624 assertTrue( "Managed File should exist: ", managedFile.exists() );
625 assertTrue( "Remote File should exist: ", remoteFile.exists() );
627 managedFile.setLastModified( remoteFile.lastModified() + time );
629 assertTrue( managedFile.lastModified() > remoteFile.lastModified() );
632 protected void setManagedOlderThanRemote( File managedFile, File remoteFile )
634 setManagedOlderThanRemote(managedFile, remoteFile, 55000 );
637 protected void setManagedOlderThanRemote( File managedFile, File remoteFile, long time )
639 assertTrue( "Managed File should exist: ", managedFile.exists() );
640 assertTrue( "Remote File should exist: ", remoteFile.exists() );
642 managedFile.setLastModified( remoteFile.lastModified() - time );
644 assertTrue( managedFile.lastModified() < remoteFile.lastModified() );
648 protected void assertNotModified( File file, long expectedModificationTime )
650 assertEquals( "File <" + file.getAbsolutePath() + "> not have been modified.", expectedModificationTime,
651 file.lastModified() );
654 protected void assertNotExistsInManagedLegacyRepo( File file )
657 String managedLegacyPath = managedLegacyDir.getCanonicalPath();
658 String testFile = file.getCanonicalPath();
661 "Unit Test Failure: File <" + testFile + "> should be have been defined within the legacy managed path of <"
662 + managedLegacyPath + ">", testFile.startsWith( managedLegacyPath ) );
664 assertFalse( "File < " + testFile + "> should not exist in managed legacy repository.", file.exists() );
667 protected void assertNotExistsInManagedDefaultRepo( File file )
670 String managedDefaultPath = managedDefaultDir.getCanonicalPath();
671 String testFile = file.getCanonicalPath();
673 assertTrue( "Unit Test Failure: File <" + testFile
674 + "> should be have been defined within the managed default path of <" + managedDefaultPath
675 + ">", testFile.startsWith( managedDefaultPath ) );
677 assertFalse( "File < " + testFile + "> should not exist in managed default repository.", file.exists() );
680 protected static Date getFutureDate()
681 throws ParseException
683 Calendar cal = Calendar.getInstance();
684 cal.add( Calendar.YEAR, 1 );
685 return cal.getTime();
688 protected static Date getPastDate()
689 throws ParseException
691 return new SimpleDateFormat( "yyyy-MM-dd", Locale.US ).parse( "2000-01-01" );