]> source.dussan.org Git - archiva.git/blob
8acdd2f4b9525838d63066e5d635426cc11e7645
[archiva.git] /
1 package org.apache.archiva.web.xmlrpc.services;
2
3 /*
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
11  *
12  *   http://www.apache.org/licenses/LICENSE-2.0
13  *
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
19  * under the License.
20  */
21
22 import junit.framework.TestCase;
23 import org.apache.archiva.admin.repository.RepositoryCommonValidator;
24 import org.apache.archiva.admin.repository.managed.DefaultManagedRepositoryAdmin;
25 import org.apache.archiva.admin.repository.remote.DefaultRemoteRepositoryAdmin;
26 import org.apache.archiva.audit.AuditEvent;
27 import org.apache.archiva.audit.AuditListener;
28 import org.apache.archiva.metadata.model.ArtifactMetadata;
29 import org.apache.archiva.metadata.repository.MetadataRepository;
30 import org.apache.archiva.metadata.repository.RepositorySession;
31 import org.apache.archiva.metadata.repository.RepositorySessionFactory;
32 import org.apache.archiva.metadata.repository.filter.Filter;
33 import org.apache.archiva.metadata.repository.filter.IncludesFilter;
34 import org.apache.archiva.metadata.repository.stats.RepositoryStatisticsManager;
35 import org.apache.archiva.repository.events.RepositoryListener;
36 import org.apache.archiva.repository.scanner.RepositoryContentConsumers;
37 import org.apache.archiva.scheduler.repository.RepositoryArchivaTaskScheduler;
38 import org.apache.archiva.scheduler.repository.RepositoryTask;
39 import org.apache.archiva.security.ArchivaRoleConstants;
40 import org.apache.archiva.stagerepository.merge.RepositoryMerger;
41 import org.apache.archiva.web.xmlrpc.api.beans.ManagedRepository;
42 import org.apache.archiva.web.xmlrpc.api.beans.RemoteRepository;
43 import org.apache.commons.io.FileUtils;
44 import org.apache.commons.io.filefilter.FileFilterUtils;
45 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
46 import org.apache.maven.archiva.configuration.Configuration;
47 import org.apache.maven.archiva.configuration.FileTypes;
48 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
49 import org.apache.maven.archiva.configuration.RemoteRepositoryConfiguration;
50 import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration;
51 import org.apache.maven.archiva.configuration.RepositoryScanningConfiguration;
52 import org.apache.maven.archiva.consumers.InvalidRepositoryContentConsumer;
53 import org.apache.maven.archiva.consumers.KnownRepositoryContentConsumer;
54 import org.apache.maven.archiva.model.ArtifactReference;
55 import org.apache.maven.archiva.repository.RepositoryContentFactory;
56 import org.apache.maven.archiva.repository.content.ManagedDefaultRepositoryContent;
57 import org.apache.maven.archiva.repository.content.ManagedLegacyRepositoryContent;
58 import org.apache.maven.archiva.repository.content.PathParser;
59 import org.apache.maven.archiva.repository.layout.LayoutException;
60 import org.codehaus.plexus.redback.role.RoleManager;
61 import org.codehaus.plexus.registry.Registry;
62 import org.easymock.MockControl;
63 import org.easymock.classextension.MockClassControl;
64 import org.junit.Before;
65 import org.junit.Test;
66 import org.junit.runner.RunWith;
67 import org.springframework.context.ApplicationContext;
68 import org.springframework.test.context.ContextConfiguration;
69 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
70
71 import java.io.File;
72 import java.io.IOException;
73 import java.util.ArrayList;
74 import java.util.Arrays;
75 import java.util.Collections;
76 import java.util.Date;
77 import java.util.HashMap;
78 import java.util.List;
79 import java.util.Map;
80
81 import static org.mockito.Mockito.mock;
82 import static org.mockito.Mockito.when;
83
84 /**
85  * AdministrationServiceImplTest
86  *
87  * @version $Id: AdministrationServiceImplTest.java
88  */
89 @RunWith( SpringJUnit4ClassRunner.class )
90 @ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" } )
91 public class AdministrationServiceImplTest
92     extends TestCase
93 {
94     private MockControl archivaConfigControl;
95
96     private ArchivaConfiguration archivaConfig;
97
98     private MockControl configControl;
99
100     private Configuration config;
101
102     private AdministrationServiceImpl service;
103
104     private MockControl repositoryTaskSchedulerControl;
105
106     private RepositoryArchivaTaskScheduler repositoryTaskScheduler;
107
108     // repository consumers
109     private MockControl repoConsumerUtilsControl;
110
111     private RepositoryContentConsumers repoConsumersUtil;
112
113     private MockControl knownContentConsumerControl;
114
115     private MockControl invalidContentConsumerControl;
116
117     private KnownRepositoryContentConsumer indexArtifactConsumer;
118
119     private KnownRepositoryContentConsumer indexPomConsumer;
120
121     private InvalidRepositoryContentConsumer checkPomConsumer;
122
123     private InvalidRepositoryContentConsumer checkMetadataConsumer;
124
125     // delete artifact
126     private MockControl repoFactoryControl;
127
128     private RepositoryContentFactory repositoryFactory;
129
130     private MockControl listenerControl;
131
132     private RepositoryListener listener;
133
134     private MockControl metadataRepositoryControl;
135
136     private MetadataRepository metadataRepository;
137
138     private MockControl repositoryStatisticsManagerControl;
139
140     private RepositoryStatisticsManager repositoryStatisticsManager;
141
142     private MockControl repositoryMergerControl;
143
144     private RepositoryMerger repositoryMerger;
145
146     private MockControl auditListenerControl;
147
148     private AuditListener auditListener;
149
150     private MockControl roleManagerControl;
151
152     private RoleManager roleManager;
153
154     private MockControl registryControl;
155
156     private Registry registry;
157
158     private static final String STAGE = "-stage";
159
160     private DefaultManagedRepositoryAdmin managedRepositoryAdmin;
161
162     private DefaultRemoteRepositoryAdmin remoteRepositoryAdmin;
163
164     private ApplicationContext applicationContext;
165
166     @Before
167     public void setUp()
168         throws Exception
169     {
170         super.setUp();
171
172         archivaConfigControl = MockControl.createControl( ArchivaConfiguration.class );
173         archivaConfig = (ArchivaConfiguration) archivaConfigControl.getMock();
174
175         configControl = MockClassControl.createControl( Configuration.class );
176         config = (Configuration) configControl.getMock();
177
178         repositoryTaskSchedulerControl = MockClassControl.createControl( RepositoryArchivaTaskScheduler.class );
179         repositoryTaskScheduler = (RepositoryArchivaTaskScheduler) repositoryTaskSchedulerControl.getMock();
180
181         // repo consumers
182         repoConsumerUtilsControl = MockClassControl.createControl( RepositoryContentConsumers.class );
183         repoConsumersUtil = (RepositoryContentConsumers) repoConsumerUtilsControl.getMock();
184
185         knownContentConsumerControl = MockControl.createControl( KnownRepositoryContentConsumer.class );
186         indexArtifactConsumer = (KnownRepositoryContentConsumer) knownContentConsumerControl.getMock();
187         indexPomConsumer = (KnownRepositoryContentConsumer) knownContentConsumerControl.getMock();
188
189         invalidContentConsumerControl = MockControl.createControl( InvalidRepositoryContentConsumer.class );
190         checkPomConsumer = (InvalidRepositoryContentConsumer) invalidContentConsumerControl.getMock();
191         checkMetadataConsumer = (InvalidRepositoryContentConsumer) invalidContentConsumerControl.getMock();
192
193         // delete artifact
194         repoFactoryControl = MockClassControl.createControl( RepositoryContentFactory.class );
195         repositoryFactory = (RepositoryContentFactory) repoFactoryControl.getMock();
196
197         metadataRepositoryControl = MockControl.createControl( MetadataRepository.class );
198         metadataRepository = (MetadataRepository) metadataRepositoryControl.getMock();
199
200         RepositorySession repositorySession = mock( RepositorySession.class );
201         when( repositorySession.getRepository() ).thenReturn( metadataRepository );
202
203         RepositorySessionFactory repositorySessionFactory = mock( RepositorySessionFactory.class );
204         when( repositorySessionFactory.createSession() ).thenReturn( repositorySession );
205
206         listenerControl = MockControl.createControl( RepositoryListener.class );
207         listener = (RepositoryListener) listenerControl.getMock();
208
209         roleManagerControl = MockControl.createControl( RoleManager.class );
210         roleManager = (RoleManager) roleManagerControl.getMock();
211
212         repositoryStatisticsManagerControl = MockControl.createControl( RepositoryStatisticsManager.class );
213         repositoryStatisticsManager = (RepositoryStatisticsManager) repositoryStatisticsManagerControl.getMock();
214
215         repositoryMergerControl = MockControl.createControl( RepositoryMerger.class );
216         repositoryMerger = (RepositoryMerger) repositoryMergerControl.getMock();
217
218         auditListenerControl = MockControl.createControl( AuditListener.class );
219         auditListener = (AuditListener) auditListenerControl.getMock();
220
221         registryControl = MockControl.createControl( Registry.class );
222         registry = (Registry) registryControl.getMock();
223
224         managedRepositoryAdmin = new DefaultManagedRepositoryAdmin();
225         managedRepositoryAdmin.setArchivaConfiguration( archivaConfig );
226         managedRepositoryAdmin.setRegistry( registry );
227         managedRepositoryAdmin.setRepositoryStatisticsManager( repositoryStatisticsManager );
228         managedRepositoryAdmin.setRepositoryTaskScheduler( repositoryTaskScheduler );
229         managedRepositoryAdmin.setRepositorySessionFactory( repositorySessionFactory );
230         managedRepositoryAdmin.setAuditListeners( Arrays.asList( auditListener ) );
231         managedRepositoryAdmin.setRoleManager( roleManager );
232
233         RepositoryCommonValidator repositoryCommonValidator = new RepositoryCommonValidator();
234         repositoryCommonValidator.setArchivaConfiguration( archivaConfig );
235         repositoryCommonValidator.setRegistry( registry );
236
237         managedRepositoryAdmin.setRepositoryCommonValidator( repositoryCommonValidator );
238
239         remoteRepositoryAdmin = new DefaultRemoteRepositoryAdmin();
240         remoteRepositoryAdmin.setArchivaConfiguration( archivaConfig );
241         remoteRepositoryAdmin.setAuditListeners( Arrays.asList( auditListener ) );
242
243         remoteRepositoryAdmin.setRepositoryCommonValidator( repositoryCommonValidator );
244
245         service = new AdministrationServiceImpl( archivaConfig, repoConsumersUtil, repositoryFactory,
246                                                  repositorySessionFactory, repositoryTaskScheduler,
247                                                  Collections.singletonList( listener ), repositoryStatisticsManager,
248                                                  repositoryMerger, auditListener, managedRepositoryAdmin,
249                                                  remoteRepositoryAdmin );
250     }
251
252     /* Tests for repository consumers */
253     @Test
254     public void testGetAllRepoConsumers()
255         throws Exception
256     {
257         recordRepoConsumers();
258
259         repoConsumerUtilsControl.replay();
260         knownContentConsumerControl.replay();
261         invalidContentConsumerControl.replay();
262
263         List<String> repoConsumers = service.getAllRepositoryConsumers();
264
265         repoConsumerUtilsControl.verify();
266         knownContentConsumerControl.verify();
267         invalidContentConsumerControl.verify();
268
269         assertNotNull( repoConsumers );
270         assertEquals( 4, repoConsumers.size() );
271         assertTrue( repoConsumers.contains( "index-artifact" ) );
272         assertTrue( repoConsumers.contains( "index-pom" ) );
273         assertTrue( repoConsumers.contains( "check-pom" ) );
274         assertTrue( repoConsumers.contains( "check-metadata" ) );
275     }
276
277     @Test
278     public void testConfigureValidRepositoryConsumer()
279         throws Exception
280     {
281         RepositoryScanningConfiguration repoScanning = new RepositoryScanningConfiguration();
282         repoScanning.addKnownContentConsumer( "index-artifact" );
283         repoScanning.addKnownContentConsumer( "index-pom" );
284         repoScanning.addInvalidContentConsumer( "check-pom" );
285
286         // test enable "check-metadata" consumer
287         recordRepoConsumers();
288
289         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
290         configControl.expectAndReturn( config.getRepositoryScanning(), repoScanning );
291
292         config.setRepositoryScanning( repoScanning );
293         configControl.setMatcher( MockControl.ALWAYS_MATCHER );
294         configControl.setVoidCallable();
295
296         archivaConfig.save( config );
297         archivaConfigControl.setVoidCallable();
298
299         repoConsumerUtilsControl.replay();
300         knownContentConsumerControl.replay();
301         invalidContentConsumerControl.replay();
302         archivaConfigControl.replay();
303         configControl.replay();
304
305         try
306         {
307             boolean success = service.configureRepositoryConsumer( null, "check-metadata", true );
308             assertTrue( success );
309         }
310         catch ( Exception e )
311         {
312             fail( "An exception should not have been thrown." );
313         }
314
315         repoConsumerUtilsControl.verify();
316         knownContentConsumerControl.verify();
317         invalidContentConsumerControl.verify();
318         archivaConfigControl.verify();
319         configControl.verify();
320
321         // test disable "check-metadata" consumer
322         repoConsumerUtilsControl.reset();
323         knownContentConsumerControl.reset();
324         invalidContentConsumerControl.reset();
325         archivaConfigControl.reset();
326         configControl.reset();
327
328         repoScanning.addInvalidContentConsumer( "check-metadata" );
329
330         recordRepoConsumers();
331
332         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
333         configControl.expectAndReturn( config.getRepositoryScanning(), repoScanning );
334
335         config.setRepositoryScanning( repoScanning );
336         configControl.setMatcher( MockControl.ALWAYS_MATCHER );
337         configControl.setVoidCallable();
338
339         archivaConfig.save( config );
340         archivaConfigControl.setVoidCallable();
341
342         repoConsumerUtilsControl.replay();
343         knownContentConsumerControl.replay();
344         invalidContentConsumerControl.replay();
345         archivaConfigControl.replay();
346         configControl.replay();
347
348         try
349         {
350             boolean success = service.configureRepositoryConsumer( null, "check-metadata", false );
351
352             repoConsumerUtilsControl.verify();
353             knownContentConsumerControl.verify();
354             invalidContentConsumerControl.verify();
355             archivaConfigControl.verify();
356             configControl.verify();
357
358             assertTrue( success );
359         }
360         catch ( Exception e )
361         {
362             fail( "An excecption should not have been thrown." );
363         }
364     }
365
366     @Test
367     public void testConfigureInvalidRepositoryConsumer()
368         throws Exception
369     {
370         recordRepoConsumers();
371
372         repoConsumerUtilsControl.replay();
373         knownContentConsumerControl.replay();
374         invalidContentConsumerControl.replay();
375
376         try
377         {
378             service.configureRepositoryConsumer( null, "invalid-consumer", true );
379             fail( "An exception should have been thrown." );
380         }
381         catch ( Exception e )
382         {
383             assertEquals( "Invalid repository consumer.", e.getMessage() );
384         }
385
386         repoConsumerUtilsControl.verify();
387         knownContentConsumerControl.verify();
388         invalidContentConsumerControl.verify();
389     }
390
391     /* Tests for delete artifact */
392     @Test
393     public void testDeleteM2ArtifactArtifactExists()
394         throws Exception
395     {
396         ManagedRepositoryConfiguration managedRepo = createManagedRepo( "default", "default-repo" );
397
398         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
399         configControl.expectAndReturn( config.findManagedRepositoryById( "internal" ), managedRepo );
400
401         ManagedDefaultRepositoryContent repoContent = new ManagedDefaultRepositoryContent();
402         repoContent.setRepository( managedRepo );
403
404         repoFactoryControl.expectAndReturn( repositoryFactory.getManagedRepositoryContent( "internal" ), repoContent );
405
406         List<ArtifactMetadata> artifacts = getArtifacts();
407         ArtifactMetadata artifact = artifacts.get( 0 );
408
409         metadataRepositoryControl.expectAndReturn(
410             metadataRepository.getArtifacts( repoContent.getId(), artifact.getNamespace(), artifact.getProject(),
411                                              artifact.getVersion() ), artifacts );
412         metadataRepository.removeArtifact( repoContent.getId(), artifact.getNamespace(), artifact.getProject(),
413                                            artifact.getVersion(), artifact.getId() );
414
415         listener.deleteArtifact( metadataRepository, repoContent.getId(), artifact.getNamespace(),
416                                  artifact.getProject(), artifact.getVersion(), artifact.getId() );
417         listenerControl.setVoidCallable( 1 );
418
419         archivaConfigControl.replay();
420         configControl.replay();
421         repoFactoryControl.replay();
422         metadataRepositoryControl.replay();
423         listenerControl.replay();
424
425         boolean success = service.deleteArtifact( "internal", "org.apache.archiva", "archiva-test", "1.0" );
426         assertTrue( success );
427
428         archivaConfigControl.verify();
429         configControl.verify();
430         repoFactoryControl.verify();
431         metadataRepositoryControl.verify();
432         listenerControl.verify();
433
434         assertFalse( new File( managedRepo.getLocation(), "org/apache/archiva/archiva-test/1.0" ).exists() );
435         assertTrue( new File( managedRepo.getLocation(), "org/apache/archiva/archiva-test/1.1" ).exists() );
436     }
437
438     @Test
439     public void testDeleteM1ArtifactArtifactExists()
440         throws Exception
441     {
442         MockControl fileTypesControl = MockClassControl.createControl( FileTypes.class );
443         FileTypes fileTypes = (FileTypes) fileTypesControl.getMock();
444
445         MockControl pathParserControl = MockClassControl.createControl( PathParser.class );
446         PathParser parser = (PathParser) pathParserControl.getMock();
447
448         ManagedRepositoryConfiguration managedRepo = createManagedRepo( "legacy", "legacy-repo" );
449
450         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
451         configControl.expectAndReturn( config.findManagedRepositoryById( "internal" ), managedRepo );
452
453         ManagedLegacyRepositoryContent repoContent = new ManagedLegacyRepositoryContent();
454         repoContent.setRepository( managedRepo );
455         repoContent.setFileTypes( fileTypes );
456         repoContent.setLegacyPathParser( parser );
457
458         repoFactoryControl.expectAndReturn( repositoryFactory.getManagedRepositoryContent( "internal" ), repoContent );
459
460         recordInManagedLegacyRepoContent( fileTypesControl, fileTypes, pathParserControl, parser );
461
462         List<ArtifactMetadata> artifacts = getArtifacts();
463         ArtifactMetadata artifact = artifacts.get( 0 );
464
465         metadataRepositoryControl.expectAndReturn(
466             metadataRepository.getArtifacts( repoContent.getId(), artifact.getNamespace(), artifact.getProject(),
467                                              artifact.getVersion() ), artifacts );
468         metadataRepository.removeArtifact( repoContent.getId(), artifact.getNamespace(), artifact.getProject(),
469                                            artifact.getVersion(), artifact.getId() );
470
471         listener.deleteArtifact( metadataRepository, repoContent.getId(), artifact.getNamespace(),
472                                  artifact.getProject(), artifact.getVersion(), artifact.getId() );
473         listenerControl.setVoidCallable( 1 );
474
475         archivaConfigControl.replay();
476         configControl.replay();
477         repoFactoryControl.replay();
478         metadataRepositoryControl.replay();
479         listenerControl.replay();
480         fileTypesControl.replay();
481         pathParserControl.replay();
482
483         boolean success = service.deleteArtifact( "internal", "org.apache.archiva", "archiva-test", "1.0" );
484         assertTrue( success );
485
486         archivaConfigControl.verify();
487         configControl.verify();
488         repoFactoryControl.verify();
489         metadataRepositoryControl.verify();
490         listenerControl.verify();
491         fileTypesControl.verify();
492         pathParserControl.verify();
493
494         File repo = new File( managedRepo.getLocation() );
495         assertFalse( new File( repo, "org.apache.archiva/jars/archiva-test-1.0.jar" ).exists() );
496         assertFalse( new File( repo, "org.apache.archiva/poms/archiva-test-1.0.pom" ).exists() );
497
498         assertTrue( new File( repo, "org.apache.archiva/jars/archiva-test-1.1.jar" ).exists() );
499         assertTrue( new File( repo, "org.apache.archiva/jars/archiva-diff-1.0.jar" ).exists() );
500         assertTrue( new File( repo, "org.apache.archiva/poms/archiva-test-1.1.pom" ).exists() );
501         assertTrue( new File( repo, "org.apache.archiva/poms/archiva-diff-1.0.pom" ).exists() );
502     }
503
504     @Test
505     public void testDeleteArtifactArtifactDoesNotExist()
506         throws Exception
507     {
508         ManagedRepositoryConfiguration managedRepo = createManagedRepo( "default", "default-repo" );
509
510         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
511         configControl.expectAndReturn( config.findManagedRepositoryById( "internal" ), managedRepo );
512
513         ManagedDefaultRepositoryContent repoContent = new ManagedDefaultRepositoryContent();
514         repoContent.setRepository( managedRepo );
515
516         repoFactoryControl.expectAndReturn( repositoryFactory.getManagedRepositoryContent( "internal" ), repoContent );
517
518         archivaConfigControl.replay();
519         configControl.replay();
520         repoFactoryControl.replay();
521
522         try
523         {
524             service.deleteArtifact( "internal", "org.apache.archiva", "archiva-non-existing", "1.0" );
525             fail( "An exception should have been thrown." );
526         }
527         catch ( Exception e )
528         {
529             assertEquals( "Artifact does not exist.", e.getMessage() );
530         }
531
532         archivaConfigControl.verify();
533         configControl.verify();
534         repoFactoryControl.verify();
535     }
536
537     private ManagedRepositoryConfiguration createManagedRepo( String layout, String directory )
538         throws IOException
539     {
540         File srcDir = new File( "src/test/repositories/" + directory );
541
542         File repoDir = new File( "target/test-repos/" + directory );
543
544         FileUtils.deleteDirectory( repoDir );
545
546         FileUtils.copyDirectory( srcDir, repoDir, FileFilterUtils.makeSVNAware( null ) );
547
548         ManagedRepositoryConfiguration managedRepo =
549             createManagedRepo( "internal", layout, "Internal Repository", true, false );
550         managedRepo.setLocation( repoDir.getAbsolutePath() );
551         return managedRepo;
552     }
553
554     @Test
555     public void testDeleteArtifacRepositoryDoesNotExist()
556         throws Exception
557     {
558         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
559         configControl.expectAndReturn( config.findManagedRepositoryById( "non-existing-repo" ), null );
560
561         archivaConfigControl.replay();
562         configControl.replay();
563
564         try
565         {
566             service.deleteArtifact( "non-existing-repo", "org.apache.archiva", "archiva-test", "1.0" );
567             fail( "An exception should have been thrown." );
568         }
569         catch ( Exception e )
570         {
571             assertEquals( "Repository does not exist.", e.getMessage() );
572         }
573
574         archivaConfigControl.verify();
575         configControl.verify();
576     }
577
578     /* Tests for repository scanning */
579     @Test
580     public void testExecuteRepoScannerRepoExistsAndNotBeingScanned()
581         throws Exception
582     {
583         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
584         configControl.expectAndReturn( config.findManagedRepositoryById( "internal" ),
585                                        createManagedRepo( "internal", "default", "Internal Repository", true, false ) );
586
587         RepositoryTask task = new RepositoryTask();
588
589         repositoryTaskSchedulerControl.expectAndReturn(
590             repositoryTaskScheduler.isProcessingRepositoryTask( "internal" ), false );
591
592         repositoryTaskScheduler.queueTask( task );
593         repositoryTaskSchedulerControl.setMatcher( MockControl.ALWAYS_MATCHER );
594         repositoryTaskSchedulerControl.setVoidCallable();
595
596         archivaConfigControl.replay();
597         configControl.replay();
598         repositoryTaskSchedulerControl.replay();
599
600         try
601         {
602             boolean success = service.executeRepositoryScanner( "internal" );
603             assertTrue( success );
604         }
605         catch ( Exception e )
606         {
607             fail( "An exception should not have been thrown." );
608         }
609
610         archivaConfigControl.verify();
611         configControl.verify();
612         repositoryTaskSchedulerControl.verify();
613     }
614
615     @Test
616     public void testExecuteRepoScannerRepoExistsButBeingScanned()
617         throws Exception
618     {
619         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
620         configControl.expectAndReturn( config.findManagedRepositoryById( "internal" ),
621                                        createManagedRepo( "internal", "default", "Internal Repository", true, false ) );
622
623         repositoryTaskSchedulerControl.expectAndReturn(
624             repositoryTaskScheduler.isProcessingRepositoryTask( "internal" ), true );
625
626         archivaConfigControl.replay();
627         configControl.replay();
628         repositoryTaskSchedulerControl.replay();
629
630         try
631         {
632             boolean success = service.executeRepositoryScanner( "internal" );
633             assertFalse( success );
634         }
635         catch ( Exception e )
636         {
637             fail( "An exception should not have been thrown." );
638         }
639
640         archivaConfigControl.verify();
641         configControl.verify();
642         repositoryTaskSchedulerControl.verify();
643     }
644
645     @Test
646     public void testExecuteRepoScannerRepoDoesNotExist()
647         throws Exception
648     {
649         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
650         configControl.expectAndReturn( config.findManagedRepositoryById( "internal" ), null );
651
652         archivaConfigControl.replay();
653         configControl.replay();
654
655         try
656         {
657             service.executeRepositoryScanner( "internal" );
658             fail( "An exception should have been thrown." );
659         }
660         catch ( Exception e )
661         {
662             assertEquals( "Repository does not exist.", e.getMessage() );
663         }
664
665         archivaConfigControl.verify();
666         configControl.verify();
667     }
668
669     /* Tests for querying repositories */
670     @Test
671     public void testGetAllManagedRepositories()
672         throws Exception
673     {
674         List<ManagedRepositoryConfiguration> managedRepos = new ArrayList<ManagedRepositoryConfiguration>();
675         managedRepos.add( createManagedRepo( "internal", "default", "Internal Repository", true, false ) );
676         managedRepos.add( createManagedRepo( "snapshots", "default", "Snapshots Repository", false, true ) );
677
678         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
679         configControl.expectAndReturn( config.getManagedRepositories(), managedRepos );
680
681         archivaConfigControl.replay();
682         configControl.replay();
683
684         List<ManagedRepository> repos = service.getAllManagedRepositories();
685
686         archivaConfigControl.verify();
687         configControl.verify();
688
689         assertNotNull( repos );
690         assertEquals( 2, repos.size() );
691
692         assertManagedRepo( repos.get( 0 ), managedRepos.get( 0 ) );
693         assertManagedRepo( repos.get( 1 ), managedRepos.get( 1 ) );
694     }
695
696     @Test
697     public void testGetAllRemoteRepositories()
698         throws Exception
699     {
700         List<RemoteRepositoryConfiguration> remoteRepos = new ArrayList<RemoteRepositoryConfiguration>();
701         remoteRepos.add(
702             createRemoteRepository( "central", "Central Repository", "default", "http://repo1.maven.org/maven2" ) );
703         remoteRepos.add(
704             createRemoteRepository( "dummy", "Dummy Remote Repository", "legacy", "http://dummy.com/dummy" ) );
705
706         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
707         configControl.expectAndReturn( config.getRemoteRepositories(), remoteRepos );
708
709         archivaConfigControl.replay();
710         configControl.replay();
711
712         List<RemoteRepository> repos = service.getAllRemoteRepositories();
713
714         archivaConfigControl.verify();
715         configControl.verify();
716
717         assertNotNull( repos );
718         assertEquals( 2, repos.size() );
719
720         assertRemoteRepo( repos.get( 0 ), remoteRepos.get( 0 ) );
721         assertRemoteRepo( repos.get( 1 ), remoteRepos.get( 1 ) );
722     }
723
724     @Test
725     public void testDeleteInvalidRepositoryContent()
726     {
727         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
728         configControl.expectAndReturn( config.findManagedRepositoryById( "invalid" ), null );
729
730         archivaConfigControl.replay();
731         configControl.replay();
732
733         try
734         {
735             service.deleteManagedRepositoryContent( "invalid" );
736         }
737         catch ( Exception e )
738         {
739             assertEquals( "Repository Id : invalid not found.", e.getMessage() );
740         }
741
742         archivaConfigControl.verify();
743         configControl.verify();
744     }
745
746     @Test
747     public void testDeleteRepositoryContent()
748         throws Exception
749     {
750         ManagedRepositoryConfiguration managedRepo = createManagedRepo( "default", "default-repo" );
751         assertTrue( new File( managedRepo.getLocation(), "org" ).exists() );
752
753         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
754         configControl.expectAndReturn( config.findManagedRepositoryById( "internal" ), managedRepo );
755         metadataRepository.removeRepository( "internal" );
756
757         archivaConfigControl.replay();
758         configControl.replay();
759         metadataRepositoryControl.replay();
760
761         boolean success = service.deleteManagedRepositoryContent( "internal" );
762         assertTrue( success );
763
764         archivaConfigControl.verify();
765         configControl.verify();
766         metadataRepositoryControl.verify();
767
768         assertFalse( new File( managedRepo.getLocation(), "org" ).exists() );
769         assertTrue( new File( managedRepo.getLocation() ).exists() );
770     }
771
772     /* Merge method */
773     @Test
774     public void testMergeRepositoryWithInvalidRepository()
775         throws Exception
776     {
777         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
778         configControl.expectAndReturn( config.findManagedRepositoryById( "invalid" ), null );
779
780         archivaConfigControl.replay();
781         configControl.replay();
782
783         try
784         {
785             service.merge( "invalid", true );
786         }
787         catch ( Exception e )
788         {
789             assertEquals( "Repository Id : invalid not found.", e.getMessage() );
790         }
791
792         archivaConfigControl.verify();
793         configControl.verify();
794     }
795
796     @Test
797     public void testMergeWithNoStagingRepository()
798         throws Exception
799     {
800         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
801         configControl.expectAndReturn( config.findManagedRepositoryById( "repo" ),
802                                        createManagedRepo( "repo", "default", "repo", true, false ) );
803         configControl.expectAndReturn( config.findManagedRepositoryById( "repo-stage" ), null );
804
805         archivaConfigControl.replay();
806         configControl.replay();
807
808         try
809         {
810             service.merge( "repo", true );
811         }
812         catch ( Exception e )
813         {
814             assertEquals( "Staging Id : repo-stage not found.", e.getMessage() );
815         }
816
817         archivaConfigControl.verify();
818         configControl.verify();
819     }
820
821     @Test
822     public void testMergeRepositoriesAndScan()
823         throws Exception
824     {
825         List<ArtifactMetadata> sources = new ArrayList<ArtifactMetadata>();
826
827         ArtifactMetadata artifact = new ArtifactMetadata();
828         artifact.setId( "artifact" );
829         artifact.setFileLastModified( System.currentTimeMillis() );
830
831         sources.add( artifact );
832
833         ManagedRepositoryConfiguration merge = createManagedRepo( "merge", "default", "merge", true, true );
834         merge.setLocation( "target/test-repository/merge" );
835         ManagedRepositoryConfiguration staging = createStagingRepo( merge );
836
837         RepositoryTask task = new RepositoryTask();
838         task.setScanAll( true );
839
840         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
841         configControl.expectAndReturn( config.findManagedRepositoryById( "merge" ), merge );
842         configControl.expectAndReturn( config.findManagedRepositoryById( "merge-stage" ), staging );
843
844         metadataRepositoryControl.expectAndReturn( metadataRepository.getArtifacts( staging.getId() ), sources );
845         repositoryMergerControl.expectAndDefaultReturn(
846             repositoryMerger.getConflictingArtifacts( metadataRepository, staging.getId(), merge.getId() ), sources );
847         repositoryMerger.merge( metadataRepository, staging.getId(), merge.getId() );
848         repositoryMergerControl.setVoidCallable();
849         repositoryTaskSchedulerControl.expectAndReturn( repositoryTaskScheduler.isProcessingRepositoryTask( "merge" ),
850                                                         false );
851
852         // scanning after merge
853         repositoryTaskScheduler.queueTask( task );
854         repositoryTaskSchedulerControl.setMatcher( MockControl.ALWAYS_MATCHER );
855         repositoryTaskSchedulerControl.setVoidCallable();
856
857         // audit logs
858         metadataRepository.addMetadataFacet( merge.getId(), createAuditEvent( merge ) );
859         metadataRepositoryControl.setMatcher( MockControl.ALWAYS_MATCHER );
860         metadataRepositoryControl.setVoidCallable();
861
862         archivaConfigControl.replay();
863         metadataRepositoryControl.replay();
864         configControl.replay();
865         repositoryMergerControl.replay();
866         repositoryTaskSchedulerControl.replay();
867
868         boolean a = service.merge( "merge", false );
869         assertTrue( a );
870
871         archivaConfigControl.verify();
872         configControl.verify();
873         configControl.verify();
874         metadataRepositoryControl.verify();
875         repositoryMergerControl.verify();
876         repositoryTaskSchedulerControl.verify();
877     }
878
879     @Test
880     public void testMergeRepositoriesWithConflictsAndScan()
881         throws Exception
882     {
883         List<ArtifactMetadata> sources = new ArrayList<ArtifactMetadata>();
884         ArtifactMetadata one = new ArtifactMetadata();
885         one.setId( "one" );
886         one.setVersion( "1.0" );
887
888         ArtifactMetadata two = new ArtifactMetadata();
889         two.setId( "two" );
890         two.setVersion( "1.0-SNAPSHOT" );
891
892         sources.add( one );
893         sources.add( two );
894
895         List<ArtifactMetadata> conflicts = new ArrayList<ArtifactMetadata>();
896         conflicts.add( one );
897
898         sources.removeAll( conflicts );
899
900         Filter<ArtifactMetadata> artifactsWithOutConflicts = new IncludesFilter<ArtifactMetadata>( sources );
901
902         RepositoryTask task = new RepositoryTask();
903         task.setScanAll( true );
904
905         ManagedRepositoryConfiguration repo = createManagedRepo( "repo", "default", "repo", true, true );
906         repo.setLocation( "target/test-repository/one" );
907         ManagedRepositoryConfiguration staging = createStagingRepo( repo );
908
909         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
910         configControl.expectAndReturn( config.findManagedRepositoryById( "repo" ), repo );
911         configControl.expectAndReturn( config.findManagedRepositoryById( "repo-stage" ), staging );
912
913         metadataRepositoryControl.expectAndReturn( metadataRepository.getArtifacts( staging.getId() ), sources );
914         repositoryMergerControl.expectAndDefaultReturn(
915             repositoryMerger.getConflictingArtifacts( metadataRepository, staging.getId(), repo.getId() ), conflicts );
916         repositoryMerger.merge( metadataRepository, staging.getId(), repo.getId(), artifactsWithOutConflicts );
917         repositoryMergerControl.setMatcher( MockControl.ALWAYS_MATCHER );
918         repositoryMergerControl.setVoidCallable();
919         repositoryTaskSchedulerControl.expectAndReturn( repositoryTaskScheduler.isProcessingRepositoryTask( "repo" ),
920                                                         false );
921         repositoryTaskScheduler.queueTask( task );
922         repositoryTaskSchedulerControl.setMatcher( MockControl.ALWAYS_MATCHER );
923         repositoryTaskSchedulerControl.setVoidCallable();
924
925         // audit logs
926         metadataRepository.addMetadataFacet( repo.getId(), createAuditEvent( repo ) );
927         metadataRepositoryControl.setMatcher( MockControl.ALWAYS_MATCHER );
928         metadataRepositoryControl.setVoidCallable();
929
930         archivaConfigControl.replay();
931         metadataRepositoryControl.replay();
932         configControl.replay();
933         repositoryMergerControl.replay();
934         repositoryTaskSchedulerControl.replay();
935
936         boolean a = service.merge( "repo", true );
937         assertTrue( a );
938
939         archivaConfigControl.verify();
940         configControl.verify();
941         configControl.verify();
942         metadataRepositoryControl.verify();
943         repositoryMergerControl.verify();
944         repositoryTaskSchedulerControl.verify();
945     }
946
947     @Test
948     public void testAddManagedRepository()
949         throws Exception
950     {
951         String projId = "org.apache.archiva";
952         String repoId = projId + ".releases";
953         String layout = "default";
954         String name = projId + " Releases";
955         String releaseLocation = "target/test-repository/" + projId + ".releases";
956         String stageLocation = releaseLocation + "-stage";
957         String appserverBase = "target";
958
959         ManagedRepositoryConfiguration managedRepo = createManagedRepo( "repo1", "default", "repo", true, false );
960         RemoteRepositoryConfiguration remoteRepo =
961             createRemoteRepository( "central", "Central Repository", "default", "http://repo1.maven.org/maven2" );
962         List<String> repositories = new ArrayList<String>();
963         repositories.add( managedRepo.getName() );
964         RepositoryGroupConfiguration repoGroup = createRepoGroupConfig( "repoGroup", repositories );
965         Map<String, ManagedRepositoryConfiguration> managedRepoMap =
966             new HashMap<String, ManagedRepositoryConfiguration>();
967         Map<String, RemoteRepositoryConfiguration> remoteRepoMap = new HashMap<String, RemoteRepositoryConfiguration>();
968         Map<String, RepositoryGroupConfiguration> repoGroupMap = new HashMap<String, RepositoryGroupConfiguration>();
969         managedRepoMap.put( "repo1", managedRepo );
970         remoteRepoMap.put( "repo1", remoteRepo );
971         repoGroupMap.put( "repo1", repoGroup );
972
973         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
974
975         configControl.expectAndReturn( config.getManagedRepositoriesAsMap(), managedRepoMap );
976         configControl.expectAndReturn( config.getRemoteRepositoriesAsMap(), remoteRepoMap );
977         configControl.expectAndReturn( config.getRepositoryGroupsAsMap(), repoGroupMap );
978
979         roleManager.templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, repoId );
980         roleManagerControl.setReturnValue( false );
981         roleManager.createTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, repoId );
982         roleManagerControl.setVoidCallable();
983         roleManager.templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_MANAGER, repoId );
984         roleManagerControl.setReturnValue( false );
985         roleManager.createTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_MANAGER, repoId );
986         roleManagerControl.setVoidCallable();
987
988         roleManager.templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, repoId + "-stage" );
989         roleManagerControl.setReturnValue( false );
990         roleManager.createTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, repoId + "-stage" );
991         roleManagerControl.setVoidCallable();
992         roleManager.templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_MANAGER, repoId + "-stage" );
993         roleManagerControl.setReturnValue( false );
994         roleManager.createTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_MANAGER, repoId + "-stage" );
995         roleManagerControl.setVoidCallable();
996
997         roleManagerControl.replay();
998
999         registryControl.expectAndReturn( registry.getString( "appserver.base", "${appserver.base}" ), appserverBase );
1000         registryControl.expectAndReturn( registry.getString( "appserver.home", "${appserver.home}" ), appserverBase );
1001         config.addManagedRepository( managedRepo );
1002         configControl.setMatcher( MockControl.ALWAYS_MATCHER );
1003         configControl.setVoidCallable();
1004         config.addManagedRepository( managedRepo );
1005         configControl.setMatcher( MockControl.ALWAYS_MATCHER );
1006         configControl.setVoidCallable();
1007         archivaConfig.save( config );
1008         archivaConfigControl.setVoidCallable();
1009
1010         //managed repo
1011         repositoryTaskSchedulerControl.expectAndReturn( repositoryTaskScheduler.isProcessingRepositoryTask( repoId ),
1012                                                         false );
1013
1014         RepositoryTask task = new RepositoryTask();
1015         task.setRepositoryId( repoId );
1016         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
1017
1018         configControl.expectAndReturn( config.findManagedRepositoryById( repoId ), managedRepo );
1019         repositoryTaskScheduler.queueTask( task );
1020         repositoryTaskSchedulerControl.setVoidCallable();
1021
1022         //staged repo
1023         repositoryTaskSchedulerControl.expectAndReturn(
1024             repositoryTaskScheduler.isProcessingRepositoryTask( repoId + STAGE ), false );
1025         task = new RepositoryTask();
1026         task.setRepositoryId( repoId + STAGE );
1027         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
1028
1029         configControl.expectAndReturn( config.findManagedRepositoryById( repoId + STAGE ), managedRepo );
1030         repositoryTaskScheduler.queueTask( task );
1031         repositoryTaskSchedulerControl.setVoidCallable();
1032
1033         archivaConfigControl.replay();
1034         configControl.replay();
1035         registryControl.replay();
1036         repositoryTaskSchedulerControl.replay();
1037         assertFalse( new File( releaseLocation ).isDirectory() );
1038         assertFalse( new File( stageLocation ).isDirectory() );
1039         boolean success = service.addManagedRepository( repoId, layout, name,
1040                                                         "${appserver.base}/test-repository/" + projId + ".releases",
1041                                                         true, true, false, true, "0 15 3 * * ? *", 1, 1, true );
1042         assertTrue( success );
1043         assertTrue( new File( releaseLocation ).isDirectory() );
1044         assertTrue( new File( stageLocation ).isDirectory() );
1045         new File( releaseLocation ).delete();
1046         new File( stageLocation ).delete();
1047
1048         registryControl.verify();
1049     }
1050
1051     @Test
1052     public void testAddManagedRepositoryInvalidId()
1053         throws Exception
1054     {
1055         String projId = "org.apache.archiva";
1056         String repoId = projId + "<script>alert('xss')</script>";
1057         String layout = "default";
1058         String name = projId + " Releases";
1059
1060         ManagedRepositoryConfiguration managedRepo = createManagedRepo( "repo1", "default", "repo", true, false );
1061         RemoteRepositoryConfiguration remoteRepo =
1062             createRemoteRepository( "central", "Central Repository", "default", "http://repo1.maven.org/maven2" );
1063         List<String> repositories = new ArrayList<String>();
1064         repositories.add( managedRepo.getName() );
1065         RepositoryGroupConfiguration repoGroup = createRepoGroupConfig( "repoGroup", repositories );
1066         Map<String, ManagedRepositoryConfiguration> managedRepoMap =
1067             new HashMap<String, ManagedRepositoryConfiguration>();
1068         Map<String, RemoteRepositoryConfiguration> remoteRepoMap = new HashMap<String, RemoteRepositoryConfiguration>();
1069         Map<String, RepositoryGroupConfiguration> repoGroupMap = new HashMap<String, RepositoryGroupConfiguration>();
1070         managedRepoMap.put( "repo1", managedRepo );
1071         remoteRepoMap.put( "repo1", remoteRepo );
1072         repoGroupMap.put( "repo1", repoGroup );
1073
1074         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
1075
1076         configControl.expectAndReturn( config.getManagedRepositoriesAsMap(), managedRepoMap );
1077         configControl.expectAndReturn( config.getRemoteRepositoriesAsMap(), remoteRepoMap );
1078         configControl.expectAndReturn( config.getRepositoryGroupsAsMap(), repoGroupMap );
1079
1080         archivaConfigControl.replay();
1081         configControl.replay();
1082
1083         try
1084         {
1085             service.addManagedRepository( repoId, layout, name,
1086                                           "${appserver.base}/test-repository/" + projId + ".releases", true, true,
1087                                           false, true, "0 15 3 * * ? *", 1, 1, true );
1088             fail( "An exception should have been thrown! Repository ID is not valid." );
1089         }
1090         catch ( Exception e )
1091         {
1092             assertEquals(
1093                 "Invalid repository ID. Identifier must only contain alphanumeric characters, underscores(_), dots(.), and dashes(-).",
1094                 e.getMessage() );
1095         }
1096     }
1097
1098     @Test
1099     public void testAddManagedRepositoryInvalidName()
1100         throws Exception
1101     {
1102         String projId = "org.apache.archiva";
1103         String repoId = projId + ".releases";
1104         String layout = "default";
1105         String name = projId + " <script>alert('xss')</script>";
1106
1107         ManagedRepositoryConfiguration managedRepo = createManagedRepo( "repo1", "default", "repo", true, false );
1108         RemoteRepositoryConfiguration remoteRepo =
1109             createRemoteRepository( "central", "Central Repository", "default", "http://repo1.maven.org/maven2" );
1110         List<String> repositories = new ArrayList<String>();
1111         repositories.add( managedRepo.getName() );
1112         RepositoryGroupConfiguration repoGroup = createRepoGroupConfig( "repoGroup", repositories );
1113         Map<String, ManagedRepositoryConfiguration> managedRepoMap =
1114             new HashMap<String, ManagedRepositoryConfiguration>();
1115         Map<String, RemoteRepositoryConfiguration> remoteRepoMap = new HashMap<String, RemoteRepositoryConfiguration>();
1116         Map<String, RepositoryGroupConfiguration> repoGroupMap = new HashMap<String, RepositoryGroupConfiguration>();
1117         managedRepoMap.put( "repo1", managedRepo );
1118         remoteRepoMap.put( "repo1", remoteRepo );
1119         repoGroupMap.put( "repo1", repoGroup );
1120
1121         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
1122
1123         configControl.expectAndReturn( config.getManagedRepositoriesAsMap(), managedRepoMap );
1124         configControl.expectAndReturn( config.getRemoteRepositoriesAsMap(), remoteRepoMap );
1125         configControl.expectAndReturn( config.getRepositoryGroupsAsMap(), repoGroupMap );
1126
1127         archivaConfigControl.replay();
1128         configControl.replay();
1129
1130         try
1131         {
1132             service.addManagedRepository( repoId, layout, name,
1133                                           "${appserver.base}/test-repository/" + projId + ".releases", true, true,
1134                                           false, true, "0 15 3 * * ? *", 1, 1, true );
1135             fail( "An exception should have been thrown! Repository name is not valid." );
1136         }
1137         catch ( Exception e )
1138         {
1139             assertEquals(
1140                 "Invalid repository name. Repository Name must only contain alphanumeric characters, white-spaces(' '), "
1141                     + "forward-slashes(/), open-parenthesis('('), close-parenthesis(')'),  underscores(_), dots(.), and dashes(-).",
1142                 e.getMessage() );
1143         }
1144     }
1145
1146     @Test
1147     public void testAddManagedRepositoryInvalidLocation()
1148         throws Exception
1149     {
1150         String projId = "org.apache.archiva";
1151         String repoId = projId + ".releases";
1152         String layout = "default";
1153         String name = projId + " Releases";
1154         String appserverBase = "target";
1155
1156         ManagedRepositoryConfiguration managedRepo = createManagedRepo( "repo1", "default", "repo", true, false );
1157         RemoteRepositoryConfiguration remoteRepo =
1158             createRemoteRepository( "central", "Central Repository", "default", "http://repo1.maven.org/maven2" );
1159         List<String> repositories = new ArrayList<String>();
1160         repositories.add( managedRepo.getName() );
1161         RepositoryGroupConfiguration repoGroup = createRepoGroupConfig( "repoGroup", repositories );
1162         Map<String, ManagedRepositoryConfiguration> managedRepoMap =
1163             new HashMap<String, ManagedRepositoryConfiguration>();
1164         Map<String, RemoteRepositoryConfiguration> remoteRepoMap = new HashMap<String, RemoteRepositoryConfiguration>();
1165         Map<String, RepositoryGroupConfiguration> repoGroupMap = new HashMap<String, RepositoryGroupConfiguration>();
1166         managedRepoMap.put( "repo1", managedRepo );
1167         remoteRepoMap.put( "repo1", remoteRepo );
1168         repoGroupMap.put( "repo1", repoGroup );
1169
1170         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
1171         archivaConfigControl.expectAndReturn( archivaConfig.getConfiguration(), config );
1172
1173         configControl.expectAndReturn( config.getManagedRepositoriesAsMap(), managedRepoMap );
1174         configControl.expectAndReturn( config.getRemoteRepositoriesAsMap(), remoteRepoMap );
1175         configControl.expectAndReturn( config.getRepositoryGroupsAsMap(), repoGroupMap );
1176         registryControl.expectAndReturn( registry.getString( "appserver.base", "${appserver.base}" ), appserverBase );
1177         registryControl.expectAndReturn( registry.getString( "appserver.home", "${appserver.home}" ), appserverBase );
1178
1179         archivaConfigControl.replay();
1180         configControl.replay();
1181         registryControl.replay();
1182
1183         try
1184         {
1185             service.addManagedRepository( repoId, layout, name,
1186                                           "${appserver.base}/<script>alert('xss')</script>" + projId + ".releases",
1187                                           true, true, false, true, "0 15 3 * * ? *", 1, 1, true );
1188             fail( "An exception should have been thrown! Repository location is not valid." );
1189         }
1190         catch ( Exception e )
1191         {
1192             assertEquals( "message found " + e.getMessage(),
1193                           "Invalid repository location. Directory must only contain alphanumeric characters, equals(=), question-marks(?), "
1194                               + "exclamation-points(!), ampersands(&amp;), forward-slashes(/), back-slashes(\\), underscores(_), dots(.), colons(:), tildes(~), and dashes(-).",
1195                           e.getMessage() );
1196         }
1197
1198         registryControl.verify();
1199     }
1200
1201     /* private methods */
1202
1203     private void assertRemoteRepo( RemoteRepository remoteRepo, RemoteRepositoryConfiguration expectedRepoConfig )
1204     {
1205         assertEquals( expectedRepoConfig.getId(), remoteRepo.getId() );
1206         assertEquals( expectedRepoConfig.getLayout(), remoteRepo.getLayout() );
1207         assertEquals( expectedRepoConfig.getName(), remoteRepo.getName() );
1208         assertEquals( expectedRepoConfig.getUrl(), remoteRepo.getUrl() );
1209     }
1210
1211     private RemoteRepositoryConfiguration createRemoteRepository( String id, String name, String layout, String url )
1212     {
1213         RemoteRepositoryConfiguration remoteConfig = new RemoteRepositoryConfiguration();
1214         remoteConfig.setId( id );
1215         remoteConfig.setName( name );
1216         remoteConfig.setLayout( layout );
1217         remoteConfig.setUrl( url );
1218
1219         return remoteConfig;
1220     }
1221
1222     private void assertManagedRepo( ManagedRepository managedRepo, ManagedRepositoryConfiguration expectedRepoConfig )
1223     {
1224         assertEquals( expectedRepoConfig.getId(), managedRepo.getId() );
1225         assertEquals( expectedRepoConfig.getLayout(), managedRepo.getLayout() );
1226         assertEquals( expectedRepoConfig.getName(), managedRepo.getName() );
1227
1228         // TODO enable assert once fixed in AdministrationServiceImpl!
1229         // assertEquals( "http://localhost:8080/archiva/repository/" + expectedRepoConfig.getId(), managedRepo.getUrl()
1230         // );
1231         assertEquals( expectedRepoConfig.isReleases(), managedRepo.isReleases() );
1232         assertEquals( expectedRepoConfig.isSnapshots(), managedRepo.isSnapshots() );
1233     }
1234
1235     private ManagedRepositoryConfiguration createManagedRepo( String id, String layout, String name,
1236                                                               boolean hasReleases, boolean hasSnapshots )
1237     {
1238         ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration();
1239         repoConfig.setId( id );
1240         repoConfig.setLayout( layout );
1241         repoConfig.setName( name );
1242         repoConfig.setReleases( hasReleases );
1243         repoConfig.setSnapshots( hasSnapshots );
1244
1245         return repoConfig;
1246     }
1247
1248     private ManagedRepositoryConfiguration createStagingRepo( ManagedRepositoryConfiguration repoConfig )
1249     {
1250         ManagedRepositoryConfiguration stagingRepo = new ManagedRepositoryConfiguration();
1251         stagingRepo.setId( repoConfig.getId() + STAGE );
1252         stagingRepo.setLayout( repoConfig.getLayout() );
1253         stagingRepo.setName( repoConfig + STAGE );
1254         stagingRepo.setReleases( repoConfig.isReleases() );
1255         stagingRepo.setSnapshots( repoConfig.isSnapshots() );
1256         stagingRepo.setLocation( repoConfig.getLocation() );
1257
1258         return stagingRepo;
1259     }
1260
1261     private AuditEvent createAuditEvent( ManagedRepositoryConfiguration repoConfig )
1262     {
1263         AuditEvent auditEvent = new AuditEvent();
1264
1265         auditEvent.setAction( AuditEvent.MERGE_REPO_REMOTE );
1266         auditEvent.setRepositoryId( repoConfig.getId() );
1267         auditEvent.setResource( repoConfig.getLocation() );
1268         auditEvent.setTimestamp( new Date() );
1269
1270         return auditEvent;
1271     }
1272
1273     private void recordRepoConsumers()
1274     {
1275         List<KnownRepositoryContentConsumer> availableKnownConsumers = new ArrayList<KnownRepositoryContentConsumer>();
1276         availableKnownConsumers.add( indexArtifactConsumer );
1277         availableKnownConsumers.add( indexPomConsumer );
1278
1279         List<InvalidRepositoryContentConsumer> availableInvalidConsumers =
1280             new ArrayList<InvalidRepositoryContentConsumer>();
1281         availableInvalidConsumers.add( checkPomConsumer );
1282         availableInvalidConsumers.add( checkMetadataConsumer );
1283
1284         repoConsumerUtilsControl.expectAndReturn( repoConsumersUtil.getAvailableKnownConsumers(),
1285                                                   availableKnownConsumers );
1286         knownContentConsumerControl.expectAndReturn( indexArtifactConsumer.getId(), "index-artifact" );
1287         knownContentConsumerControl.expectAndReturn( indexPomConsumer.getId(), "index-pom" );
1288
1289         repoConsumerUtilsControl.expectAndReturn( repoConsumersUtil.getAvailableInvalidConsumers(),
1290                                                   availableInvalidConsumers );
1291         invalidContentConsumerControl.expectAndReturn( checkPomConsumer.getId(), "check-pom" );
1292         invalidContentConsumerControl.expectAndReturn( checkMetadataConsumer.getId(), "check-metadata" );
1293     }
1294
1295     private void recordInManagedLegacyRepoContent( MockControl fileTypesControl, FileTypes fileTypes,
1296                                                    MockControl pathParserControl, PathParser parser )
1297         throws LayoutException
1298     {
1299         String sep = File.separator;
1300         String ad10p = "org.apache.archiva" + sep + "poms" + sep + "archiva-diff-1.0.pom";
1301         String at10p = "org.apache.archiva" + sep + "poms" + sep + "archiva-test-1.0.pom";
1302         String at11p = "org.apache.archiva" + sep + "poms" + sep + "archiva-test-1.1.pom";
1303         String ad10j = "org.apache.archiva" + sep + "jars" + sep + "archiva-diff-1.0.jar";
1304         String at10j = "org.apache.archiva" + sep + "jars" + sep + "archiva-test-1.0.jar";
1305         String at11j = "org.apache.archiva" + sep + "jars" + sep + "archiva-test-1.1.jar";
1306
1307         fileTypesControl.expectAndReturn( fileTypes.matchesArtifactPattern( at10p ), true );
1308         fileTypesControl.expectAndReturn( fileTypes.matchesArtifactPattern( at11p ), true );
1309         fileTypesControl.expectAndReturn( fileTypes.matchesArtifactPattern( ad10p ), true );
1310         fileTypesControl.expectAndReturn( fileTypes.matchesArtifactPattern( ad10j ), true );
1311         fileTypesControl.expectAndReturn( fileTypes.matchesArtifactPattern( at10j ), true );
1312         fileTypesControl.expectAndReturn( fileTypes.matchesArtifactPattern( at11j ), true );
1313
1314         ArtifactReference aRef = createArtifactReference( "archiva-test", "org.apache.archiva", "1.1", "pom" );
1315         pathParserControl.expectAndReturn( parser.toArtifactReference( at11p ), aRef );
1316
1317         aRef = createArtifactReference( "archiva-test", "org.apache.archiva", "1.0", "pom" );
1318         pathParserControl.expectAndReturn( parser.toArtifactReference( at10p ), aRef );
1319
1320         aRef = createArtifactReference( "archiva-diff", "org.apache.archiva", "1.0", "pom" );
1321         pathParserControl.expectAndReturn( parser.toArtifactReference( ad10p ), aRef );
1322
1323         aRef = createArtifactReference( "archiva-diff", "org.apache.archiva", "1.0", "jar" );
1324         pathParserControl.expectAndReturn( parser.toArtifactReference( ad10j ), aRef );
1325
1326         aRef = createArtifactReference( "archiva-test", "org.apache.archiva", "1.0", "jar" );
1327         pathParserControl.expectAndReturn( parser.toArtifactReference( at10j ), aRef );
1328
1329         aRef = createArtifactReference( "archiva-test", "org.apache.archiva", "1.1", "jar" );
1330         pathParserControl.expectAndReturn( parser.toArtifactReference( at11j ), aRef );
1331     }
1332
1333     private List<ArtifactMetadata> getArtifacts()
1334     {
1335         List<ArtifactMetadata> artifacts = new ArrayList<ArtifactMetadata>();
1336
1337         ArtifactMetadata artifact = new ArtifactMetadata();
1338         artifact.setId( "archiva-test-1.0.jar" );
1339         artifact.setProject( "archiva-test" );
1340         artifact.setVersion( "1.0" );
1341         artifact.setProjectVersion( "1.0" );
1342         artifact.setNamespace( "org.apache.archiva" );
1343         artifact.setRepositoryId( "internal" );
1344         artifacts.add( artifact );
1345         return artifacts;
1346     }
1347
1348     private ArtifactReference createArtifactReference( String artifactId, String groupId, String version, String type )
1349     {
1350         ArtifactReference aRef = new ArtifactReference();
1351         aRef.setArtifactId( artifactId );
1352         aRef.setGroupId( groupId );
1353         aRef.setType( type );
1354         aRef.setVersion( version );
1355
1356         return aRef;
1357     }
1358
1359     private RepositoryGroupConfiguration createRepoGroupConfig( String id, List<String> repositories )
1360     {
1361         RepositoryGroupConfiguration repoGroup = new RepositoryGroupConfiguration();
1362         repoGroup.setId( id );
1363         repoGroup.setRepositories( repositories );
1364         return repoGroup;
1365     }
1366 }