This project has retired. For details please refer to its Attic page.
DefaultManagedRepositoryAdmin xref
View Javadoc
1   package org.apache.archiva.admin.repository.managed;
2   /*
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   */
20  
21  import org.apache.archiva.admin.model.AuditInformation;
22  import org.apache.archiva.admin.model.RepositoryAdminException;
23  import org.apache.archiva.admin.model.beans.ManagedRepository;
24  import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
25  import org.apache.archiva.admin.repository.AbstractRepositoryAdmin;
26  import org.apache.archiva.common.plexusbridge.MavenIndexerUtils;
27  import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
28  import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
29  import org.apache.archiva.configuration.Configuration;
30  import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
31  import org.apache.archiva.configuration.ProxyConnectorConfiguration;
32  import org.apache.archiva.configuration.RepositoryGroupConfiguration;
33  import org.apache.archiva.metadata.model.facets.AuditEvent;
34  import org.apache.archiva.metadata.repository.MetadataRepository;
35  import org.apache.archiva.metadata.repository.MetadataRepositoryException;
36  import org.apache.archiva.metadata.repository.RepositorySession;
37  import org.apache.archiva.metadata.repository.RepositorySessionFactory;
38  import org.apache.archiva.metadata.repository.stats.RepositoryStatisticsManager;
39  import org.apache.archiva.redback.components.cache.Cache;
40  import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
41  import org.apache.archiva.redback.role.RoleManager;
42  import org.apache.archiva.redback.role.RoleManagerException;
43  import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
44  import org.apache.archiva.scheduler.repository.model.RepositoryTask;
45  import org.apache.archiva.security.common.ArchivaRoleConstants;
46  import org.apache.commons.io.FileUtils;
47  import org.apache.commons.lang.StringUtils;
48  import org.apache.maven.index.NexusIndexer;
49  import org.apache.maven.index.context.IndexCreator;
50  import org.apache.maven.index.context.IndexingContext;
51  import org.apache.maven.index.context.UnsupportedExistingLuceneIndexException;
52  import org.slf4j.Logger;
53  import org.slf4j.LoggerFactory;
54  import org.springframework.stereotype.Service;
55  
56  import javax.annotation.PostConstruct;
57  import javax.annotation.PreDestroy;
58  import javax.inject.Inject;
59  import javax.inject.Named;
60  import java.io.File;
61  import java.io.IOException;
62  import java.net.MalformedURLException;
63  import java.util.ArrayList;
64  import java.util.Collection;
65  import java.util.Collections;
66  import java.util.HashMap;
67  import java.util.List;
68  import java.util.Map;
69  
70  /**
71   * FIXME review the staging mechanism to have a per user session one
72   *
73   * @author Olivier Lamy
74   */
75  @Service("managedRepositoryAdmin#default")
76  public class DefaultManagedRepositoryAdmin
77      extends AbstractRepositoryAdmin
78      implements ManagedRepositoryAdmin
79  {
80  
81      private final Logger log = LoggerFactory.getLogger( getClass() );
82  
83      public static final String STAGE_REPO_ID_END = "-stage";
84  
85      @Inject
86      @Named(value = "archivaTaskScheduler#repository")
87      private RepositoryArchivaTaskScheduler repositoryTaskScheduler;
88  
89      /**
90       * FIXME: this could be multiple implementations and needs to be configured.
91       */
92      @Inject
93      private RepositorySessionFactory repositorySessionFactory;
94  
95      @Inject
96      private RepositoryStatisticsManager repositoryStatisticsManager;
97  
98      @Inject
99      private PlexusSisuBridge plexusSisuBridge;
100 
101     @Inject
102     private MavenIndexerUtils mavenIndexerUtils;
103 
104     @Inject
105     protected RoleManager roleManager;
106 
107     @Inject
108     @Named(value = "cache#namespaces")
109     private Cache<String, Collection<String>> namespacesCache;
110 
111     // fields
112     List<? extends IndexCreator> indexCreators;
113 
114     NexusIndexer indexer;
115 
116     @PostConstruct
117     public void initialize()
118         throws RepositoryAdminException, RoleManagerException
119     {
120         try
121         {
122             indexCreators = mavenIndexerUtils.getAllIndexCreators();
123             indexer = plexusSisuBridge.lookup( NexusIndexer.class );
124         }
125         catch ( PlexusSisuBridgeException e )
126         {
127             throw new RepositoryAdminException( e.getMessage(), e );
128         }
129         // initialize index context on start and check roles here
130         for ( ManagedRepository managedRepository : getManagedRepositories() )
131         {
132             createIndexContext( managedRepository );
133             addRepositoryRoles( managedRepository.getId() );
134 
135         }
136     }
137 
138     @PreDestroy
139     public void shutdown()
140         throws RepositoryAdminException
141     {
142         try
143         {
144             // close index on shutdown
145             for ( ManagedRepository managedRepository : getManagedRepositories() )
146             {
147                 IndexingContext context = indexer.getIndexingContexts().get( managedRepository.getId() );
148                 if ( context != null )
149                 {
150                     indexer.removeIndexingContext( context, false );
151                 }
152             }
153         }
154         catch ( IOException e )
155         {
156             throw new RepositoryAdminException( e.getMessage(), e );
157         }
158     }
159 
160     @Override
161     public List<ManagedRepository> getManagedRepositories()
162         throws RepositoryAdminException
163     {
164         List<ManagedRepositoryConfiguration> managedRepoConfigs =
165             getArchivaConfiguration().getConfiguration().getManagedRepositories();
166 
167         if ( managedRepoConfigs == null )
168         {
169             return Collections.emptyList();
170         }
171 
172         List<ManagedRepository> managedRepos = new ArrayList<>( managedRepoConfigs.size() );
173 
174         for ( ManagedRepositoryConfiguration repoConfig : managedRepoConfigs )
175         {
176             ManagedRepository repo =
177                 new ManagedRepository( repoConfig.getId(), repoConfig.getName(), repoConfig.getLocation(),
178                                        repoConfig.getLayout(), repoConfig.isSnapshots(), repoConfig.isReleases(),
179                                        repoConfig.isBlockRedeployments(), repoConfig.getRefreshCronExpression(),
180                                        repoConfig.getIndexDir(), repoConfig.isScanned(), repoConfig.getDaysOlder(),
181                                        repoConfig.getRetentionCount(), repoConfig.isDeleteReleasedSnapshots(),
182                                        repoConfig.isStageRepoNeeded() );
183             repo.setDescription( repoConfig.getDescription() );
184             repo.setSkipPackedIndexCreation( repoConfig.isSkipPackedIndexCreation() );
185             managedRepos.add( repo );
186         }
187 
188         return managedRepos;
189     }
190 
191     @Override
192     public Map<String, ManagedRepository> getManagedRepositoriesAsMap()
193         throws RepositoryAdminException
194     {
195         List<ManagedRepository> managedRepositories = getManagedRepositories();
196         Map<String, ManagedRepository> repositoriesMap = new HashMap<>( managedRepositories.size() );
197         for ( ManagedRepository managedRepository : managedRepositories )
198         {
199             repositoriesMap.put( managedRepository.getId(), managedRepository );
200         }
201         return repositoriesMap;
202     }
203 
204     @Override
205     public ManagedRepository getManagedRepository( String repositoryId )
206         throws RepositoryAdminException
207     {
208         List<ManagedRepository> repos = getManagedRepositories();
209         for ( ManagedRepository repo : repos )
210         {
211             if ( StringUtils.equals( repo.getId(), repositoryId ) )
212             {
213                 return repo;
214             }
215         }
216         return null;
217     }
218 
219     @Override
220     public Boolean addManagedRepository( ManagedRepository managedRepository, boolean needStageRepo,
221                                          AuditInformation auditInformation )
222         throws RepositoryAdminException
223     {
224 
225         getRepositoryCommonValidator().basicValidation( managedRepository, false );
226         getRepositoryCommonValidator().validateManagedRepository( managedRepository );
227         triggerAuditEvent( managedRepository.getId(), null, AuditEvent.ADD_MANAGED_REPO, auditInformation );
228         Boolean res =
229             addManagedRepository( managedRepository.getId(), managedRepository.getLayout(), managedRepository.getName(),
230                                   managedRepository.getLocation(), managedRepository.isBlockRedeployments(),
231                                   managedRepository.isReleases(), managedRepository.isSnapshots(), needStageRepo,
232                                   managedRepository.getCronExpression(), managedRepository.getIndexDirectory(),
233                                   managedRepository.getDaysOlder(), managedRepository.getRetentionCount(),
234                                   managedRepository.isDeleteReleasedSnapshots(), managedRepository.getDescription(),
235                                   managedRepository.isSkipPackedIndexCreation(), managedRepository.isScanned(),
236                                   auditInformation, getArchivaConfiguration().getConfiguration() ) != null;
237 
238         createIndexContext( managedRepository );
239         return res;
240 
241     }
242 
243     private ManagedRepositoryConfiguration addManagedRepository( String repoId, String layout, String name,
244                                                                  String location, boolean blockRedeployments,
245                                                                  boolean releasesIncluded, boolean snapshotsIncluded,
246                                                                  boolean stageRepoNeeded, String cronExpression,
247                                                                  String indexDir, int daysOlder, int retentionCount,
248                                                                  boolean deteleReleasedSnapshots, String description,
249                                                                  boolean skipPackedIndexCreation, boolean scanned,
250                                                                  AuditInformation auditInformation,
251                                                                  Configuration config )
252         throws RepositoryAdminException
253     {
254 
255         ManagedRepositoryConfiguration repository = new ManagedRepositoryConfiguration();
256 
257         repository.setId( repoId );
258         repository.setBlockRedeployments( blockRedeployments );
259         repository.setReleases( releasesIncluded );
260         repository.setSnapshots( snapshotsIncluded );
261         repository.setScanned( scanned );
262         repository.setName( name );
263         repository.setLocation( getRepositoryCommonValidator().removeExpressions( location ) );
264         repository.setLayout( layout );
265         repository.setRefreshCronExpression( cronExpression );
266         repository.setIndexDir( indexDir );
267         repository.setDaysOlder( daysOlder );
268         repository.setRetentionCount( retentionCount );
269         repository.setDeleteReleasedSnapshots( deteleReleasedSnapshots );
270         repository.setIndexDir( indexDir );
271         repository.setDescription( description );
272         repository.setSkipPackedIndexCreation( skipPackedIndexCreation );
273         repository.setStageRepoNeeded( stageRepoNeeded );
274 
275         try
276         {
277             addRepository( repository, config );
278             addRepositoryRoles( repository.getId() );
279 
280             if ( stageRepoNeeded )
281             {
282                 ManagedRepositoryConfiguration stagingRepository = getStageRepoConfig( repository );
283                 addRepository( stagingRepository, config );
284                 addRepositoryRoles( stagingRepository.getId() );
285                 triggerAuditEvent( stagingRepository.getId(), null, AuditEvent.ADD_MANAGED_REPO, auditInformation );
286             }
287         }
288         catch ( RoleManagerException e )
289         {
290             throw new RepositoryAdminException( "failed to add repository roles " + e.getMessage(), e );
291         }
292         catch ( IOException e )
293         {
294             throw new RepositoryAdminException( "failed to add repository " + e.getMessage(), e );
295         }
296 
297         saveConfiguration( config );
298 
299         //MRM-1342 Repository statistics report doesn't appear to be working correctly
300         //scan repository when adding of repository is successful
301         try
302         {
303             if ( scanned )
304             {
305                 scanRepository( repoId, true );
306             }
307 
308             // TODO need a better to define scanning or not for staged repo
309             if ( stageRepoNeeded && scanned )
310             {
311                 ManagedRepositoryConfiguration stagingRepository = getStageRepoConfig( repository );
312                 scanRepository( stagingRepository.getId(), true );
313             }
314         }
315         catch ( Exception e )
316         {
317             log.warn("Unable to scan repository [" + repoId + "]: " + e.getMessage(), e );
318         }
319 
320         return repository;
321     }
322 
323     @Override
324     public Boolean deleteManagedRepository( String repositoryId, AuditInformation auditInformation,
325                                             boolean deleteContent )
326         throws RepositoryAdminException
327     {
328         Configuration config = getArchivaConfiguration().getConfiguration();
329 
330         ManagedRepositoryConfiguration repository = config.findManagedRepositoryById( repositoryId );
331 
332         if ( repository == null )
333         {
334             throw new RepositoryAdminException( "A repository with that id does not exist" );
335         }
336 
337         triggerAuditEvent( repositoryId, null, AuditEvent.DELETE_MANAGED_REPO, auditInformation );
338 
339         deleteManagedRepository( repository, deleteContent, config, false );
340 
341         // stage repo exists ?
342         ManagedRepositoryConfiguration stagingRepository =
343             getArchivaConfiguration().getConfiguration().findManagedRepositoryById( repositoryId + STAGE_REPO_ID_END );
344         if ( stagingRepository != null )
345         {
346             // do not trigger event when deleting the staged one
347             deleteManagedRepository( stagingRepository, deleteContent, config, true );
348         }
349 
350         try
351         {
352             saveConfiguration( config );
353         }
354         catch ( Exception e )
355         {
356             throw new RepositoryAdminException( "Error saving configuration for delete action" + e.getMessage(), e );
357         }
358 
359         return Boolean.TRUE;
360     }
361 
362     private Boolean deleteManagedRepository( ManagedRepositoryConfiguration repository, boolean deleteContent,
363                                              Configuration config, boolean stagedOne )
364         throws RepositoryAdminException
365     {
366 
367         try
368         {
369             NexusIndexer nexusIndexer = plexusSisuBridge.lookup( NexusIndexer.class );
370 
371             IndexingContext context = nexusIndexer.getIndexingContexts().get( repository.getId() );
372             if ( context != null )
373             {
374                 // delete content only if directory exists
375                 nexusIndexer.removeIndexingContext( context,
376                                                     deleteContent && context.getIndexDirectoryFile().exists() );
377             }
378         }
379         catch ( PlexusSisuBridgeException | IOException e )
380         {
381             throw new RepositoryAdminException( e.getMessage(), e );
382         }
383         if ( !stagedOne )
384         {
385             try (RepositorySession repositorySession = getRepositorySessionFactory().createSession())
386             {
387                 MetadataRepository metadataRepository = repositorySession.getRepository();
388                 metadataRepository.removeRepository( repository.getId() );
389                 //invalidate cache
390                 namespacesCache.remove( repository.getId() );
391                 log.debug( "call repositoryStatisticsManager.deleteStatistics" );
392                 getRepositoryStatisticsManager().deleteStatistics( metadataRepository, repository.getId() );
393                 repositorySession.save();
394             }
395             catch ( MetadataRepositoryException e )
396             {
397                 //throw new RepositoryAdminException( e.getMessage(), e );
398                 log.warn( "skip error during removing repository from MetadataRepository:{}", e.getMessage(), e );
399             }
400         }
401         config.removeManagedRepository( repository );
402 
403         if ( deleteContent )
404         {
405             // TODO could be async ? as directory can be huge
406             File dir = new File( repository.getLocation() );
407             if ( !FileUtils.deleteQuietly( dir ) )
408             {
409                 throw new RepositoryAdminException( "Cannot delete repository " + dir );
410             }
411         }
412 
413         // olamy: copy list for reading as a unit test in webapp fail with ConcurrentModificationException
414         List<ProxyConnectorConfiguration> proxyConnectors = new ArrayList<>( config.getProxyConnectors() );
415         for ( ProxyConnectorConfiguration proxyConnector : proxyConnectors )
416         {
417             if ( StringUtils.equals( proxyConnector.getSourceRepoId(), repository.getId() ) )
418             {
419                 config.removeProxyConnector( proxyConnector );
420             }
421         }
422 
423         Map<String, List<String>> repoToGroupMap = config.getRepositoryToGroupMap();
424         if ( repoToGroupMap != null )
425         {
426             if ( repoToGroupMap.containsKey( repository.getId() ) )
427             {
428                 List<String> repoGroups = repoToGroupMap.get( repository.getId() );
429                 for ( String repoGroup : repoGroups )
430                 {
431                     // copy to prevent UnsupportedOperationException
432                     RepositoryGroupConfiguration repositoryGroupConfiguration =
433                         config.findRepositoryGroupById( repoGroup );
434                     List<String> repos = new ArrayList<>( repositoryGroupConfiguration.getRepositories() );
435                     config.removeRepositoryGroup( repositoryGroupConfiguration );
436                     repos.remove( repository.getId() );
437                     repositoryGroupConfiguration.setRepositories( repos );
438                     config.addRepositoryGroup( repositoryGroupConfiguration );
439                 }
440             }
441         }
442 
443         try
444         {
445             removeRepositoryRoles( repository );
446         }
447         catch ( RoleManagerException e )
448         {
449             throw new RepositoryAdminException(
450                 "fail to remove repository roles for repository " + repository.getId() + " : " + e.getMessage(), e );
451         }
452 
453         saveConfiguration( config );
454 
455         return Boolean.TRUE;
456     }
457 
458 
459     @Override
460     public Boolean updateManagedRepository( ManagedRepository managedRepository, boolean needStageRepo,
461                                             AuditInformation auditInformation, boolean resetStats )
462         throws RepositoryAdminException
463     {
464 
465         log.debug( "updateManagedConfiguration repo {} needStage {} resetStats {} ", managedRepository, needStageRepo,
466                    resetStats );
467 
468         // Ensure that the fields are valid.
469 
470         getRepositoryCommonValidator().basicValidation( managedRepository, true );
471 
472         getRepositoryCommonValidator().validateManagedRepository( managedRepository );
473 
474         Configuration configuration = getArchivaConfiguration().getConfiguration();
475 
476         ManagedRepositoryConfiguration toremove = configuration.findManagedRepositoryById( managedRepository.getId() );
477 
478         boolean updateIndexContext = false;
479 
480         if ( toremove != null )
481         {
482             configuration.removeManagedRepository( toremove );
483 
484             updateIndexContext = !StringUtils.equals( toremove.getIndexDir(), managedRepository.getIndexDirectory() );
485         }
486 
487         ManagedRepositoryConfiguration stagingRepository = getStageRepoConfig( toremove );
488 
489         // TODO remove content from old if path has changed !!!!!
490 
491         if ( stagingRepository != null )
492         {
493             configuration.removeManagedRepository( stagingRepository );
494         }
495 
496         ManagedRepositoryConfiguration managedRepositoryConfiguration =
497             addManagedRepository( managedRepository.getId(), managedRepository.getLayout(), managedRepository.getName(),
498                                   managedRepository.getLocation(), managedRepository.isBlockRedeployments(),
499                                   managedRepository.isReleases(), managedRepository.isSnapshots(), needStageRepo,
500                                   managedRepository.getCronExpression(), managedRepository.getIndexDirectory(),
501                                   managedRepository.getDaysOlder(), managedRepository.getRetentionCount(),
502                                   managedRepository.isDeleteReleasedSnapshots(), managedRepository.getDescription(),
503                                   managedRepository.isSkipPackedIndexCreation(), managedRepository.isScanned(),
504                                   auditInformation, getArchivaConfiguration().getConfiguration() );
505 
506         // Save the repository configuration.
507 
508         try (RepositorySession repositorySession = getRepositorySessionFactory().createSession())
509         {
510             triggerAuditEvent( managedRepositoryConfiguration.getId(), null, AuditEvent.MODIFY_MANAGED_REPO,
511                                auditInformation );
512 
513             saveConfiguration( this.getArchivaConfiguration().getConfiguration() );
514             if ( resetStats )
515             {
516                 log.debug( "call repositoryStatisticsManager.deleteStatistics" );
517                 getRepositoryStatisticsManager().deleteStatistics( repositorySession.getRepository(),
518                                                                    managedRepositoryConfiguration.getId() );
519                 repositorySession.save();
520             }
521 
522         }
523         catch ( MetadataRepositoryException e )
524         {
525             throw new RepositoryAdminException( e.getMessage(), e );
526         }
527 
528         if ( updateIndexContext )
529         {
530             try
531             {
532                 IndexingContext indexingContext = indexer.getIndexingContexts().get( managedRepository.getId() );
533                 if ( indexingContext != null )
534                 {
535                     indexer.removeIndexingContext( indexingContext, true );
536                 }
537 
538                 // delete directory too as only content is deleted
539                 File indexDirectory = indexingContext.getIndexDirectoryFile();
540                 FileUtils.deleteDirectory( indexDirectory );
541 
542                 createIndexContext( managedRepository );
543             }
544             catch ( IOException e )
545             {
546                 throw new RepositoryAdminException( e.getMessage(), e );
547             }
548         }
549 
550         return true;
551     }
552 
553     //--------------------------
554     // utils methods
555     //--------------------------
556 
557 
558     protected void addRepository( ManagedRepositoryConfiguration repository, Configuration configuration )
559         throws RepositoryAdminException, IOException
560     {
561         // Normalize the path
562         File file = new File( repository.getLocation() );
563         if ( !file.isAbsolute() )
564         {
565             // add appserver.base/repositories
566             file = new File( getRegistry().getString( "appserver.base" ) + File.separatorChar + "repositories",
567                              repository.getLocation() );
568         }
569         repository.setLocation( file.getCanonicalPath() );
570         if ( !file.exists() )
571         {
572             file.mkdirs();
573         }
574         if ( !file.exists() || !file.isDirectory() )
575         {
576             throw new RepositoryAdminException(
577                 "Unable to add repository - no write access, can not create the root directory: " + file );
578         }
579 
580         configuration.addManagedRepository( repository );
581 
582     }
583 
584     @Override
585     public IndexingContext createIndexContext( ManagedRepository repository )
586         throws RepositoryAdminException
587     {
588 
589         IndexingContext context = indexer.getIndexingContexts().get( repository.getId() );
590 
591         if ( context != null )
592         {
593             log.debug( "skip creating repository indexingContent with id {} as already exists", repository.getId() );
594             return context;
595         }
596 
597         // take care first about repository location as can be relative
598         File repositoryDirectory = new File( repository.getLocation() );
599 
600         if ( !repositoryDirectory.isAbsolute() )
601         {
602             repositoryDirectory =
603                 new File( getRegistry().getString( "appserver.base" ) + File.separatorChar + "repositories",
604                           repository.getLocation() );
605         }
606 
607         if ( !repositoryDirectory.exists() )
608         {
609             repositoryDirectory.mkdirs();
610         }
611 
612         try
613         {
614 
615             String indexDir = repository.getIndexDirectory();
616             //File managedRepository = new File( repository.getLocation() );
617 
618             File indexDirectory = null;
619             if ( StringUtils.isNotBlank( indexDir ) )
620             {
621                 indexDirectory = new File( repository.getIndexDirectory() );
622                 // not absolute so create it in repository directory
623                 if ( !indexDirectory.isAbsolute() )
624                 {
625                     indexDirectory = new File( repositoryDirectory, repository.getIndexDirectory() );
626                 }
627                 repository.setIndexDirectory( indexDirectory.getAbsolutePath() );
628             }
629             else
630             {
631                 indexDirectory = new File( repositoryDirectory, ".indexer" );
632                 if ( !repositoryDirectory.isAbsolute() )
633                 {
634                     indexDirectory = new File( repositoryDirectory, ".indexer" );
635                 }
636                 repository.setIndexDirectory( indexDirectory.getAbsolutePath() );
637             }
638 
639             if ( !indexDirectory.exists() )
640             {
641                 indexDirectory.mkdirs();
642             }
643 
644             context = indexer.getIndexingContexts().get( repository.getId() );
645 
646             if ( context == null )
647             {
648                 context = indexer.addIndexingContext( repository.getId(), repository.getId(), repositoryDirectory,
649                                                       indexDirectory,
650                                                       repositoryDirectory.toURI().toURL().toExternalForm(),
651                                                       indexDirectory.toURI().toURL().toString(), indexCreators );
652 
653                 context.setSearchable( repository.isScanned() );
654             }
655             return context;
656         }
657         catch ( IOException | UnsupportedExistingLuceneIndexException e )
658         {
659             throw new RepositoryAdminException( e.getMessage(), e );
660         }
661     }
662 
663     private ManagedRepositoryConfiguration getStageRepoConfig( ManagedRepositoryConfiguration repository )
664     {
665         ManagedRepositoryConfiguration stagingRepository = new ManagedRepositoryConfiguration();
666         stagingRepository.setId( repository.getId() + STAGE_REPO_ID_END );
667         stagingRepository.setLayout( repository.getLayout() );
668         stagingRepository.setName( repository.getName() + STAGE_REPO_ID_END );
669         stagingRepository.setBlockRedeployments( repository.isBlockRedeployments() );
670         stagingRepository.setDaysOlder( repository.getDaysOlder() );
671         stagingRepository.setDeleteReleasedSnapshots( repository.isDeleteReleasedSnapshots() );
672 
673         String path = repository.getLocation();
674         int lastIndex = path.replace( '\\', '/' ).lastIndexOf( '/' );
675         stagingRepository.setLocation( path.substring( 0, lastIndex ) + "/" + stagingRepository.getId() );
676 
677         if ( StringUtils.isNotBlank( repository.getIndexDir() ) )
678         {
679             File indexDir = new File( repository.getIndexDir() );
680             // in case of absolute dir do not use the same
681             if ( indexDir.isAbsolute() )
682             {
683                 stagingRepository.setIndexDir( stagingRepository.getLocation() + "/.index" );
684             }
685             else
686             {
687                 stagingRepository.setIndexDir( repository.getIndexDir() );
688             }
689         }
690         stagingRepository.setRefreshCronExpression( repository.getRefreshCronExpression() );
691         stagingRepository.setReleases( repository.isReleases() );
692         stagingRepository.setRetentionCount( repository.getRetentionCount() );
693         stagingRepository.setScanned( repository.isScanned() );
694         stagingRepository.setSnapshots( repository.isSnapshots() );
695         stagingRepository.setSkipPackedIndexCreation( repository.isSkipPackedIndexCreation() );
696         // do not duplicate description
697         //stagingRepository.getDescription("")
698         return stagingRepository;
699     }
700 
701     public Boolean scanRepository( String repositoryId, boolean fullScan )
702     {
703         if ( getRepositoryTaskScheduler().isProcessingRepositoryTask( repositoryId ) )
704         {
705             log.info( "scanning of repository with id {} already scheduled", repositoryId );
706         }
707         RepositoryTask task = new RepositoryTask();
708         task.setRepositoryId( repositoryId );
709         task.setScanAll( fullScan );
710         try
711         {
712             getRepositoryTaskScheduler().queueTask( task );
713         }
714         catch ( TaskQueueException e )
715         {
716             log.error( "failed to schedule scanning of repo with id " + repositoryId, e );
717             return false;
718         }
719         return true;
720     }
721 
722 
723     private void addRepositoryRoles( String repoId )
724         throws RoleManagerException
725     {
726         // TODO: double check these are configured on start up
727         // TODO: belongs in the business logic
728 
729         if ( !getRoleManager().templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, repoId ) )
730         {
731             getRoleManager().createTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, repoId );
732         }
733 
734         if ( !getRoleManager().templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_MANAGER, repoId ) )
735         {
736             getRoleManager().createTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_MANAGER, repoId );
737         }
738     }
739 
740     protected void removeRepositoryRoles( ManagedRepositoryConfiguration existingRepository )
741         throws RoleManagerException
742     {
743         String repoId = existingRepository.getId();
744 
745         if ( getRoleManager().templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_MANAGER, repoId ) )
746         {
747             getRoleManager().removeTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_MANAGER, repoId );
748         }
749 
750         if ( getRoleManager().templatedRoleExists( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, repoId ) )
751         {
752             getRoleManager().removeTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, repoId );
753         }
754 
755         log.debug( "removed user roles associated with repository {}", repoId );
756     }
757 
758     //--------------------------
759     // setters/getters
760     //--------------------------
761 
762 
763     public RoleManager getRoleManager()
764     {
765         return roleManager;
766     }
767 
768     public void setRoleManager( RoleManager roleManager )
769     {
770         this.roleManager = roleManager;
771     }
772 
773     public RepositoryStatisticsManager getRepositoryStatisticsManager()
774     {
775         return repositoryStatisticsManager;
776     }
777 
778     public void setRepositoryStatisticsManager( RepositoryStatisticsManager repositoryStatisticsManager )
779     {
780         this.repositoryStatisticsManager = repositoryStatisticsManager;
781     }
782 
783     public RepositorySessionFactory getRepositorySessionFactory()
784     {
785         return repositorySessionFactory;
786     }
787 
788     public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
789     {
790         this.repositorySessionFactory = repositorySessionFactory;
791     }
792 
793 
794     public RepositoryArchivaTaskScheduler getRepositoryTaskScheduler()
795     {
796         return repositoryTaskScheduler;
797     }
798 
799     public void setRepositoryTaskScheduler( RepositoryArchivaTaskScheduler repositoryTaskScheduler )
800     {
801         this.repositoryTaskScheduler = repositoryTaskScheduler;
802     }
803 
804     public PlexusSisuBridge getPlexusSisuBridge()
805     {
806         return plexusSisuBridge;
807     }
808 
809     public void setPlexusSisuBridge( PlexusSisuBridge plexusSisuBridge )
810     {
811         this.plexusSisuBridge = plexusSisuBridge;
812     }
813 
814     public MavenIndexerUtils getMavenIndexerUtils()
815     {
816         return mavenIndexerUtils;
817     }
818 
819     public void setMavenIndexerUtils( MavenIndexerUtils mavenIndexerUtils )
820     {
821         this.mavenIndexerUtils = mavenIndexerUtils;
822     }
823 
824     public NexusIndexer getIndexer()
825     {
826         return indexer;
827     }
828 
829     public void setIndexer( NexusIndexer indexer )
830     {
831         this.indexer = indexer;
832     }
833 
834     public List<? extends IndexCreator> getIndexCreators()
835     {
836         return indexCreators;
837     }
838 
839     public void setIndexCreators( List<? extends IndexCreator> indexCreators )
840     {
841         this.indexCreators = indexCreators;
842     }
843 }