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