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