Refactoring repository registry

This commit is contained in:
Martin Stockhammer 2021-08-09 23:40:20 +02:00
parent 32cf204092
commit 3e959d5b07
45 changed files with 2107 additions and 846 deletions

View File

@ -430,7 +430,7 @@ public class DefaultArchivaConfiguration
if (section == null) { if (section == null) {
section = baseSection; section = baseSection;
if (section == null) { if (section == null) {
section = createDefaultConfigurationFile(); section = createDefaultConfigurationFile(eventTag);
} }
} else if (baseSection != null) { } else if (baseSection != null) {
Collection<String> keys = baseSection.getKeys(); Collection<String> keys = baseSection.getKeys();
@ -513,7 +513,7 @@ public class DefaultArchivaConfiguration
} }
} }
private Registry createDefaultConfigurationFile() private Registry createDefaultConfigurationFile(String eventTag)
throws RegistryException { throws RegistryException {
// TODO: may not be needed under commons-configuration 1.4 - check // TODO: may not be needed under commons-configuration 1.4 - check
@ -543,7 +543,7 @@ public class DefaultArchivaConfiguration
addRegistryChangeListener(regListener); addRegistryChangeListener(regListener);
} }
triggerEvent(ConfigurationEvent.SAVED, "default-file"); triggerEvent(ConfigurationEvent.SAVED, eventTag==null?"default-file":eventTag);
Registry section = registry.getSection(KEY + ".user"); Registry section = registry.getSection(KEY + ".user");
if (section == null) { if (section == null) {

View File

@ -29,7 +29,7 @@ import java.util.List;
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
@SuppressWarnings( "all" ) @SuppressWarnings( "all" )
public class RepositoryGroupConfiguration public class RepositoryGroupConfiguration extends AbstractRepositoryConfiguration
implements Serializable implements Serializable
{ {

View File

@ -21,10 +21,13 @@ package $package;
import org.apache.archiva.metadata.repository.MetadataRepository; import org.apache.archiva.metadata.repository.MetadataRepository;
import org.apache.archiva.metadata.repository.RepositorySessionFactory; import org.apache.archiva.metadata.repository.RepositorySessionFactory;
import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
import org.apache.archiva.repository.base.managed.BasicManagedRepository; import org.apache.archiva.repository.base.managed.BasicManagedRepository;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.repository.RepositoryException; import org.apache.archiva.repository.RepositoryException;
import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryRegistry;
import org.junit.Before; import org.junit.Before;
import org.junit.After;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -52,7 +55,15 @@ public class SimpleArtifactConsumerTest
private SimpleArtifactConsumer consumer; private SimpleArtifactConsumer consumer;
@Inject @Inject
private RepositoryRegistry repositoryRegistry; private ArchivaRepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
private ManagedRepositoryHandler managedRepositoryHandler;
@SuppressWarnings( "unused" )
@Inject
private org.apache.archiva.repository.base.group.RepositoryGroupHandler repositoryGroupHandler;
@Inject @Inject
private RepositorySessionFactory repositorySessionFactory; private RepositorySessionFactory repositorySessionFactory;
@ -70,9 +81,20 @@ public class SimpleArtifactConsumerTest
setUpMockRepository(); setUpMockRepository();
} }
@After
public void tearDown() {
try
{
repositoryRegistry.removeRepository( "test-consumer-repository" );
} catch (Throwable ex) {
log.error( "Could not remove repository: {}", ex.getMessage( ) );
}
}
private void setUpMockRepository() private void setUpMockRepository()
throws IOException, RepositoryException throws IOException, RepositoryException
{ {
((ArchivaRepositoryRegistry)repositoryRegistry).setIgnoreIndexing( true );
Path repoDir = Paths.get( "target/test-consumer-repo" ); Path repoDir = Paths.get( "target/test-consumer-repo" );
Files.createDirectories( repoDir ); Files.createDirectories( repoDir );
repoDir.toFile().deleteOnExit(); repoDir.toFile().deleteOnExit();

View File

@ -25,7 +25,10 @@ import org.apache.archiva.configuration.FileType;
import org.apache.archiva.configuration.FileTypes; import org.apache.archiva.configuration.FileTypes;
import org.apache.archiva.consumers.KnownRepositoryContentConsumer; import org.apache.archiva.consumers.KnownRepositoryContentConsumer;
import org.apache.archiva.consumers.functors.ConsumerWantsFilePredicate; import org.apache.archiva.consumers.functors.ConsumerWantsFilePredicate;
import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.ArchivaRepositoryRegistry; import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.junit.After; import org.junit.After;
@ -56,6 +59,19 @@ public abstract class AbstractArtifactConsumerTest
@Inject @Inject
ArchivaConfiguration archivaConfiguration; ArchivaConfiguration archivaConfiguration;
@SuppressWarnings( "unused" )
@Inject
RepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
RepositoryGroupHandler repositoryGroupHandler;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
@Before @Before
public void setUp() public void setUp()
throws Exception throws Exception

View File

@ -25,6 +25,7 @@ import org.apache.archiva.metadata.repository.RepositorySession;
import org.apache.archiva.metadata.repository.RepositorySessionFactory; import org.apache.archiva.metadata.repository.RepositorySessionFactory;
import org.apache.archiva.repository.ManagedRepositoryContent; import org.apache.archiva.repository.ManagedRepositoryContent;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.repository.maven.metadata.storage.Maven2RepositoryPathTranslator; import org.apache.archiva.repository.maven.metadata.storage.Maven2RepositoryPathTranslator;
import org.apache.archiva.repository.base.managed.BasicManagedRepository; import org.apache.archiva.repository.base.managed.BasicManagedRepository;
import org.apache.archiva.repository.ReleaseScheme; import org.apache.archiva.repository.ReleaseScheme;
@ -115,6 +116,10 @@ public abstract class AbstractRepositoryPurgeTest
@Inject @Inject
RepositoryGroupHandler repositoryGroupHandler; RepositoryGroupHandler repositoryGroupHandler;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
@Before @Before
public void setUp() public void setUp()

View File

@ -28,6 +28,7 @@ import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
import org.apache.archiva.repository.base.managed.BasicManagedRepository; import org.apache.archiva.repository.base.managed.BasicManagedRepository;
import org.apache.archiva.repository.ReleaseScheme; import org.apache.archiva.repository.ReleaseScheme;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.scheduler.ArchivaTaskScheduler; import org.apache.archiva.scheduler.ArchivaTaskScheduler;
import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask; import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
@ -101,6 +102,10 @@ public class NexusIndexerConsumerTest
@Inject @Inject
RepositoryGroupHandler repositoryGroupHandler; RepositoryGroupHandler repositoryGroupHandler;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
@Override @Override
@Before @Before
public void setUp() public void setUp()

View File

@ -40,8 +40,11 @@ import org.apache.archiva.components.taskqueue.TaskQueueException;
import org.apache.archiva.redback.role.RoleManager; import org.apache.archiva.redback.role.RoleManager;
import org.apache.archiva.redback.role.RoleManagerException; import org.apache.archiva.redback.role.RoleManagerException;
import org.apache.archiva.repository.ReleaseScheme; import org.apache.archiva.repository.ReleaseScheme;
import org.apache.archiva.repository.Repository;
import org.apache.archiva.repository.RepositoryException; import org.apache.archiva.repository.RepositoryException;
import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.repository.features.ArtifactCleanupFeature; import org.apache.archiva.repository.features.ArtifactCleanupFeature;
import org.apache.archiva.repository.features.IndexCreationFeature; import org.apache.archiva.repository.features.IndexCreationFeature;
import org.apache.archiva.repository.features.StagingRepositoryFeature; import org.apache.archiva.repository.features.StagingRepositoryFeature;
@ -85,6 +88,12 @@ public class DefaultManagedRepositoryAdmin
@Inject @Inject
private RepositoryRegistry repositoryRegistry; private RepositoryRegistry repositoryRegistry;
@Inject
private ManagedRepositoryHandler managedRepositoryHandler;
@Inject
private RepositoryGroupHandler repositoryGroupHandler;
@Inject @Inject
@Named(value = "archivaTaskScheduler#repository") @Named(value = "archivaTaskScheduler#repository")
private RepositoryArchivaTaskScheduler repositoryTaskScheduler; private RepositoryArchivaTaskScheduler repositoryTaskScheduler;
@ -223,19 +232,9 @@ public class DefaultManagedRepositoryAdmin
Configuration configuration = getArchivaConfiguration().getConfiguration(); Configuration configuration = getArchivaConfiguration().getConfiguration();
try try
{ {
org.apache.archiva.repository.ManagedRepository newRepo = repositoryRegistry.putRepository( repoConfig, configuration ); org.apache.archiva.repository.ManagedRepository newRepo = repositoryRegistry.putRepository( repoConfig );
log.debug("Added new repository {}", newRepo.getId()); log.debug("Added new repository {}", newRepo.getId());
org.apache.archiva.repository.ManagedRepository stagingRepo = null;
addRepositoryRoles( newRepo.getId() ); addRepositoryRoles( newRepo.getId() );
if ( newRepo.supportsFeature( StagingRepositoryFeature.class )) {
StagingRepositoryFeature stf = newRepo.getFeature( StagingRepositoryFeature.class ).get();
stagingRepo = stf.getStagingRepository();
if (stf.isStageRepoNeeded() && stagingRepo != null) {
addRepositoryRoles( stagingRepo.getId() );
triggerAuditEvent( stagingRepo.getId(), null, AuditEvent.ADD_MANAGED_REPO, auditInformation );
}
}
saveConfiguration( configuration );
//MRM-1342 Repository statistics report doesn't appear to be working correctly //MRM-1342 Repository statistics report doesn't appear to be working correctly
//scan repository when adding of repository is successful //scan repository when adding of repository is successful
try try
@ -245,10 +244,14 @@ public class DefaultManagedRepositoryAdmin
scanRepository( newRepo.getId(), true ); scanRepository( newRepo.getId(), true );
} }
if ( stagingRepo!=null && stagingRepo.isScanned() ) org.apache.archiva.repository.ManagedRepository stagingRepo = newRepo.getFeature( StagingRepositoryFeature.class ).get( ).getStagingRepository( );
if ( stagingRepo!=null)
{ {
if (stagingRepo.isScanned()) {
scanRepository( stagingRepo.getId(), true ); scanRepository( stagingRepo.getId(), true );
} }
addRepositoryRoles( stagingRepo.getId( ) );
}
} }
catch ( Exception e ) catch ( Exception e )
{ {
@ -285,15 +288,9 @@ public class DefaultManagedRepositoryAdmin
org.apache.archiva.repository.ManagedRepository repo = repositoryRegistry.getManagedRepository(repositoryId); org.apache.archiva.repository.ManagedRepository repo = repositoryRegistry.getManagedRepository(repositoryId);
org.apache.archiva.repository.ManagedRepository stagingRepository = null; org.apache.archiva.repository.ManagedRepository stagingRepository = null;
if (repo != null) { if (repo != null) {
try {
if (repo.supportsFeature(StagingRepositoryFeature.class)) { if (repo.supportsFeature(StagingRepositoryFeature.class)) {
stagingRepository = repo.getFeature(StagingRepositoryFeature.class).get().getStagingRepository(); stagingRepository = repo.getFeature(StagingRepositoryFeature.class).get().getStagingRepository();
} }
repositoryRegistry.removeRepository(repo, config);
} catch (RepositoryException e) {
log.error("Removal of repository {} failed: {}", repositoryId, e.getMessage(), e);
throw new RepositoryAdminException("Removal of repository " + repositoryId + " failed.");
}
} else { } else {
throw new RepositoryAdminException("A repository with that id does not exist"); throw new RepositoryAdminException("A repository with that id does not exist");
} }
@ -308,14 +305,9 @@ public class DefaultManagedRepositoryAdmin
if (stagingRepository != null) { if (stagingRepository != null) {
// do not trigger event when deleting the staged one // do not trigger event when deleting the staged one
ManagedRepositoryConfiguration stagingRepositoryConfig = config.findManagedRepositoryById(stagingRepository.getId()); ManagedRepositoryConfiguration stagingRepositoryConfig = config.findManagedRepositoryById(stagingRepository.getId());
try {
repositoryRegistry.removeRepository(stagingRepository);
if (stagingRepositoryConfig != null) { if (stagingRepositoryConfig != null) {
deleteManagedRepository(stagingRepositoryConfig, deleteContent, config, true); deleteManagedRepository(stagingRepositoryConfig, deleteContent, config, true);
} }
} catch (RepositoryException e) {
log.error("Removal of staging repository {} failed: {}", stagingRepository.getId(), e.getMessage(), e);
}
} }
try { try {
@ -371,12 +363,6 @@ public class DefaultManagedRepositoryAdmin
} }
if ( deleteContent )
{
// TODO could be async ? as directory can be huge
Path dir = Paths.get( repository.getLocation() );
org.apache.archiva.common.utils.FileUtils.deleteQuietly( dir );
}
// olamy: copy list for reading as a unit test in webapp fail with ConcurrentModificationException // olamy: copy list for reading as a unit test in webapp fail with ConcurrentModificationException
List<ProxyConnectorConfiguration> proxyConnectors = new ArrayList<>( config.getProxyConnectors() ); List<ProxyConnectorConfiguration> proxyConnectors = new ArrayList<>( config.getProxyConnectors() );
@ -387,27 +373,6 @@ public class DefaultManagedRepositoryAdmin
config.removeProxyConnector( proxyConnector ); config.removeProxyConnector( proxyConnector );
} }
} }
Map<String, List<String>> repoToGroupMap = config.getRepositoryToGroupMap();
if ( repoToGroupMap != null )
{
if ( repoToGroupMap.containsKey( repository.getId() ) )
{
List<String> repoGroups = repoToGroupMap.get( repository.getId() );
for ( String repoGroup : repoGroups )
{
// copy to prevent UnsupportedOperationException
RepositoryGroupConfiguration repositoryGroupConfiguration =
config.findRepositoryGroupById( repoGroup );
List<String> repos = new ArrayList<>( repositoryGroupConfiguration.getRepositories() );
config.removeRepositoryGroup( repositoryGroupConfiguration );
repos.remove( repository.getId() );
repositoryGroupConfiguration.setRepositories( repos );
config.addRepositoryGroup( repositoryGroupConfiguration );
}
}
}
try try
{ {
removeRepositoryRoles( repository ); removeRepositoryRoles( repository );
@ -419,9 +384,16 @@ public class DefaultManagedRepositoryAdmin
} }
try { try {
final RepositoryRegistry reg = getRepositoryRegistry(); org.apache.archiva.repository.ManagedRepository repo = repositoryRegistry.getManagedRepository( repository.getId( ) );
if (reg.getManagedRepository(repository.getId())!=null) { if (repo!=null)
reg.removeRepository(reg.getManagedRepository(repository.getId())); {
repositoryRegistry.removeRepository( repo, config );
if ( deleteContent )
{
// TODO could be async ? as directory can be huge
Path dir = Paths.get( repository.getLocation( ) );
org.apache.archiva.common.utils.FileUtils.deleteQuietly( dir );
}
} }
} catch (RepositoryException e) { } catch (RepositoryException e) {
throw new RepositoryAdminException("Removal of repository "+repository.getId()+ " failed: "+e.getMessage()); throw new RepositoryAdminException("Removal of repository "+repository.getId()+ " failed: "+e.getMessage());
@ -429,6 +401,7 @@ public class DefaultManagedRepositoryAdmin
saveConfiguration( config ); saveConfiguration( config );
return Boolean.TRUE; return Boolean.TRUE;
} }
@ -452,8 +425,6 @@ public class DefaultManagedRepositoryAdmin
getRepositoryCommonValidator().validateManagedRepository( managedRepository ); getRepositoryCommonValidator().validateManagedRepository( managedRepository );
Configuration configuration = getArchivaConfiguration().getConfiguration();
ManagedRepositoryConfiguration updatedRepoConfig = getRepositoryConfiguration( managedRepository ); ManagedRepositoryConfiguration updatedRepoConfig = getRepositoryConfiguration( managedRepository );
updatedRepoConfig.setStageRepoNeeded( needStageRepo ); updatedRepoConfig.setStageRepoNeeded( needStageRepo );
@ -467,7 +438,7 @@ public class DefaultManagedRepositoryAdmin
// TODO remove content from old if path has changed !!!!! // TODO remove content from old if path has changed !!!!!
try try
{ {
newRepo = repositoryRegistry.putRepository( updatedRepoConfig, configuration ); newRepo = repositoryRegistry.putRepository( updatedRepoConfig );
if (newRepo.supportsFeature( StagingRepositoryFeature.class )) { if (newRepo.supportsFeature( StagingRepositoryFeature.class )) {
org.apache.archiva.repository.ManagedRepository stagingRepo = newRepo.getFeature( StagingRepositoryFeature.class ).get( ).getStagingRepository( ); org.apache.archiva.repository.ManagedRepository stagingRepo = newRepo.getFeature( StagingRepositoryFeature.class ).get( ).getStagingRepository( );
if (stagingRepo!=null && !stagingExists) if (stagingRepo!=null && !stagingExists)
@ -490,16 +461,6 @@ public class DefaultManagedRepositoryAdmin
} }
triggerAuditEvent( managedRepository.getId(), null, AuditEvent.MODIFY_MANAGED_REPO, triggerAuditEvent( managedRepository.getId(), null, AuditEvent.MODIFY_MANAGED_REPO,
auditInformation ); auditInformation );
try
{
getArchivaConfiguration().save(configuration);
}
catch ( RegistryException | IndeterminateConfigurationException e )
{
log.error("Could not save repository configuration: {}", e.getMessage(), e);
throw new RepositoryAdminException( "Could not save repository configuration: "+e.getMessage() );
}
// Save the repository configuration. // Save the repository configuration.
RepositorySession repositorySession = null; RepositorySession repositorySession = null;
try try

View File

@ -31,7 +31,9 @@ import org.apache.archiva.configuration.ArchivaConfiguration;
import org.apache.archiva.redback.role.RoleManager; import org.apache.archiva.redback.role.RoleManager;
import org.apache.archiva.redback.users.User; import org.apache.archiva.redback.users.User;
import org.apache.archiva.redback.users.memory.SimpleUser; import org.apache.archiva.redback.users.memory.SimpleUser;
import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.junit.Before; import org.junit.Before;
@ -84,10 +86,18 @@ public abstract class AbstractRepositoryAdminTest
@Inject @Inject
private ArchivaConfiguration archivaConfiguration; private ArchivaConfiguration archivaConfiguration;
@Inject
protected RepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
@SuppressWarnings( "unused" ) @SuppressWarnings( "unused" )
@Inject @Inject
RepositoryGroupHandler repositoryGroupHandler; RepositoryGroupHandler repositoryGroupHandler;
@Before @Before
public void initialize() { public void initialize() {
Path confFile = Paths.get(APPSERVER_BASE_PATH, "conf/archiva.xml"); Path confFile = Paths.get(APPSERVER_BASE_PATH, "conf/archiva.xml");

View File

@ -27,6 +27,7 @@ import org.apache.archiva.metadata.model.facets.AuditEvent;
import org.apache.archiva.repository.Repository; import org.apache.archiva.repository.Repository;
import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.junit.Test; import org.junit.Test;
import javax.inject.Inject; import javax.inject.Inject;
@ -42,11 +43,6 @@ public class RepositoryGroupAdminTest
@Inject @Inject
RepositoryGroupAdmin repositoryGroupAdmin; RepositoryGroupAdmin repositoryGroupAdmin;
@Inject
RepositoryRegistry repositoryRegistry;
@Inject
RepositoryGroupHandler repositoryGroupHandler;
@Test @Test
public void addAndDeleteGroup() public void addAndDeleteGroup()

View File

@ -17,6 +17,7 @@ package org.apache.archiva.repository;
* under the License. * under the License.
*/ */
import org.apache.archiva.configuration.AbstractRepositoryConfiguration;
import org.apache.archiva.configuration.Configuration; import org.apache.archiva.configuration.Configuration;
import org.apache.archiva.repository.validation.CheckedResult; import org.apache.archiva.repository.validation.CheckedResult;
import org.apache.archiva.repository.validation.RepositoryChecker; import org.apache.archiva.repository.validation.RepositoryChecker;
@ -44,7 +45,7 @@ import java.util.Map;
* *
* @author Martin Stockhammer <martin_s@apache.org> * @author Martin Stockhammer <martin_s@apache.org>
*/ */
public interface RepositoryHandler<R extends Repository, C> public interface RepositoryHandler<R extends Repository, C extends AbstractRepositoryConfiguration>
{ {
/** /**
@ -58,6 +59,12 @@ public interface RepositoryHandler<R extends Repository, C>
*/ */
void activateRepository( R repository ); void activateRepository( R repository );
/**
* Reset the repository. E.g. stops scheduling.
* @param repository
*/
void deactivateRepository( R repository );
/** /**
* Creates new instances from the archiva configuration. The instances are not registered in the registry. * Creates new instances from the archiva configuration. The instances are not registered in the registry.
* *
@ -163,9 +170,10 @@ public interface RepositoryHandler<R extends Repository, C>
* Clones a given repository without registering. * Clones a given repository without registering.
* *
* @param repo the repository that should be cloned * @param repo the repository that should be cloned
* @param newId the new identifier of the cloned instance
* @return a newly created instance with the same repository data * @return a newly created instance with the same repository data
*/ */
R clone( R repo ) throws RepositoryException; R clone( R repo, String newId ) throws RepositoryException;
/** /**
* Updates the references and stores updates in the given <code>configuration</code> instance. * Updates the references and stores updates in the given <code>configuration</code> instance.
@ -221,6 +229,13 @@ public interface RepositoryHandler<R extends Repository, C>
*/ */
boolean hasRepository( String id ); boolean hasRepository( String id );
/**
* This is called, when another variant repository was removed. This is needed only for certain variants.
*
* @param repository
*/
void processOtherVariantRemoval( Repository repository );
/** /**
* Initializes the handler. This method must be called before using the repository handler. * Initializes the handler. This method must be called before using the repository handler.
*/ */
@ -231,4 +246,20 @@ public interface RepositoryHandler<R extends Repository, C>
*/ */
void close( ); void close( );
/**
* Sets the repository provider list
* @param providers
*/
void setRepositoryProviders( List<RepositoryProvider> providers );
/**
* Sets the list of repository validators
* @param repositoryValidatorList
*/
void setRepositoryValidator( List<RepositoryValidator<? extends Repository>> repositoryValidatorList );
Class<R> getVariant();
Class<C> getConfigurationVariant();
} }

View File

@ -0,0 +1,35 @@
package org.apache.archiva.repository;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.configuration.AbstractRepositoryConfiguration;
import org.apache.archiva.event.Event;
import org.apache.archiva.event.EventHandler;
/**
* @author Martin Stockhammer <martin_s@apache.org>
*/
public interface RepositoryHandlerManager extends EventHandler<Event>
{
<R extends Repository, C extends AbstractRepositoryConfiguration> RepositoryHandler<R,C> getHandler( Class<R> repositoryClazz, Class<C> configurationClazz);
void registerHandler( RepositoryHandler<?, ?> handler );
boolean isRegisteredId(String id);
}

View File

@ -50,7 +50,7 @@ import java.util.Map;
* @author Martin Stockhammer <martin_s@apache.org> * @author Martin Stockhammer <martin_s@apache.org>
*/ */
@SuppressWarnings( "UnusedReturnValue" ) @SuppressWarnings( "UnusedReturnValue" )
public interface RepositoryRegistry extends EventSource public interface RepositoryRegistry extends EventSource, RepositoryHandlerManager
{ {
/** /**
* Set the configuration for the registry * Set the configuration for the registry

View File

@ -22,7 +22,7 @@ package org.apache.archiva.repository;
*/ */
public enum RepositoryState public enum RepositoryState
{ {
CREATED(0),REFERENCES_SET(100),SAVED(200),INITIALIZED(300),REGISTERED(400),UNREGISTERED(500),CLOSED(600); CREATED(0),REFERENCES_SET(100),SAVED(200),INITIALIZED(300),REGISTERED(400),DEACTIVATED(500), UNREGISTERED(600),CLOSED(700);
private final int orderNumber; private final int orderNumber;

View File

@ -17,51 +17,367 @@ package org.apache.archiva.repository.base;
* under the License. * under the License.
*/ */
import org.apache.archiva.components.registry.RegistryException;
import org.apache.archiva.configuration.AbstractRepositoryConfiguration;
import org.apache.archiva.configuration.Configuration;
import org.apache.archiva.configuration.IndeterminateConfigurationException;
import org.apache.archiva.event.Event;
import org.apache.archiva.event.EventManager;
import org.apache.archiva.event.EventType;
import org.apache.archiva.repository.EditableRepository; import org.apache.archiva.repository.EditableRepository;
import org.apache.archiva.repository.Repository; import org.apache.archiva.repository.Repository;
import org.apache.archiva.repository.RepositoryException;
import org.apache.archiva.repository.RepositoryHandler; import org.apache.archiva.repository.RepositoryHandler;
import org.apache.archiva.repository.RepositoryProvider;
import org.apache.archiva.repository.RepositoryState; import org.apache.archiva.repository.RepositoryState;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.RepositoryType;
import org.apache.archiva.repository.event.LifecycleEvent;
import org.apache.archiva.repository.validation.CheckedResult;
import org.apache.archiva.repository.validation.CombinedValidator; import org.apache.archiva.repository.validation.CombinedValidator;
import org.apache.archiva.repository.validation.RepositoryChecker;
import org.apache.archiva.repository.validation.RepositoryValidator; import org.apache.archiva.repository.validation.RepositoryValidator;
import org.apache.archiva.repository.validation.ValidationError;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* Base abstract class for repository handlers. * Base abstract class for repository handlers.
*
* @author Martin Stockhammer <martin_s@apache.org> * @author Martin Stockhammer <martin_s@apache.org>
*/ */
public abstract class AbstractRepositoryHandler<R extends Repository, C> implements RepositoryHandler<R, C> public abstract class AbstractRepositoryHandler<R extends Repository, C extends AbstractRepositoryConfiguration> implements RepositoryHandler<R, C>
{ {
private static final Logger log = LoggerFactory.getLogger( AbstractRepositoryHandler.class ); private static final Logger log = LoggerFactory.getLogger( AbstractRepositoryHandler.class );
protected List<RepositoryValidator<R>> initValidators( Class<R> clazz, List<RepositoryValidator<? extends Repository>> repositoryGroupValidatorList) { protected final Map<RepositoryType, RepositoryProvider> providerMap = new HashMap<>( );
if (repositoryGroupValidatorList!=null && repositoryGroupValidatorList.size()>0) { private CombinedValidator<R> combinedValidator;
private final Class<R> repositoryClazz;
private final Class<C> configurationClazz;
private final EventManager eventManager;
private final Map<String, R> repositoryMap = new HashMap<>( );
private final ConfigurationHandler configurationHandler;
public AbstractRepositoryHandler(Class<R> repositoryClazz, Class<C> configurationClazz, ConfigurationHandler configurationHandler) {
this.repositoryClazz = repositoryClazz;
this.configurationClazz = configurationClazz;
this.eventManager = new EventManager( this );
this.configurationHandler = configurationHandler;
}
protected List<RepositoryValidator<R>> initValidators( Class<R> clazz, List<RepositoryValidator<? extends Repository>> repositoryGroupValidatorList )
{
if ( repositoryGroupValidatorList != null && repositoryGroupValidatorList.size( ) > 0 )
{
return repositoryGroupValidatorList.stream( ).filter( return repositoryGroupValidatorList.stream( ).filter(
v -> v.isFlavour( clazz ) v -> v.isFlavour( clazz )
).map( v -> v.narrowTo( clazz ) ).collect( Collectors.toList( ) ); ).map( v -> v.narrowTo( clazz ) ).collect( Collectors.toList( ) );
} else { }
else
{
return Collections.emptyList( ); return Collections.emptyList( );
} }
} }
protected CombinedValidator<R> getCombinedValidatdor(Class<R> clazz, List<RepositoryValidator<? extends Repository>> repositoryGroupValidatorList) { protected CombinedValidator<R> getCombinedValidator( Class<R> clazz, List<RepositoryValidator<? extends Repository>> repositoryGroupValidatorList )
{
return new CombinedValidator<>( clazz, initValidators( clazz, repositoryGroupValidatorList ) ); return new CombinedValidator<>( clazz, initValidators( clazz, repositoryGroupValidatorList ) );
} }
protected void setLastState(Repository repo, RepositoryState state) { protected void setLastState( R repo, RepositoryState state )
if (repo instanceof EditableRepository ) { {
if (state.getOrderNumber()>repo.getLastState().getOrderNumber()) RepositoryState currentState = repo.getLastState( );
if ( repo instanceof EditableRepository )
{
if ( state.getOrderNumber( ) > repo.getLastState( ).getOrderNumber( ) )
{ {
( (EditableRepository) repo ).setLastState( state ); ( (EditableRepository) repo ).setLastState( state );
} }
} else { }
log.error( "Found a not editable repository instance: {}, {}", repo.getId( ), repo.getClass().getName() ); else
{
log.error( "Found a not editable repository instance: {}, {}", repo.getId( ), repo.getClass( ).getName( ) );
}
if (state == RepositoryState.REGISTERED && state != currentState ) {
pushEvent( LifecycleEvent.REGISTERED, repo );
} else if (state == RepositoryState.UNREGISTERED && state != currentState) {
pushEvent( LifecycleEvent.UNREGISTERED, repo );
} }
} }
@Override
public void setRepositoryProviders( List<RepositoryProvider> providers )
{
if ( providers != null )
{
for ( RepositoryProvider provider : providers )
{
for ( RepositoryType type : provider.provides( ) )
{
providerMap.put( type, provider );
}
}
}
}
protected RepositoryProvider getProvider(RepositoryType type) {
return providerMap.get( type );
}
@Override
public void setRepositoryValidator( List<RepositoryValidator<? extends Repository>> repositoryValidatorList )
{
this.combinedValidator = getCombinedValidator( repositoryClazz, repositoryValidatorList );
}
protected CombinedValidator<R> getCombinedValidator() {
return this.combinedValidator;
}
@Override
public Class<R> getVariant( )
{
return this.repositoryClazz;
}
@Override
public Class<C> getConfigurationVariant( )
{
return this.configurationClazz;
}
@Override
public void processOtherVariantRemoval( Repository repository )
{
// Default: do nothing
}
protected void pushEvent( Event event )
{
eventManager.fireEvent( event );
}
protected void pushEvent(EventType<? extends LifecycleEvent> event, R repo) {
pushEvent( new LifecycleEvent( event, this, repo ) );
}
protected Map<String, R> getRepositories() {
return repositoryMap;
}
protected ConfigurationHandler getConfigurationHandler() {
return configurationHandler;
}
@Override
public void activateRepository( R repository )
{
//
}
@Override
public void deactivateRepository( R repository )
{
}
@Override
public abstract R newInstance( C repositoryConfiguration ) throws RepositoryException;
@Override
public <D> CheckedResult<R, D> putWithCheck( C repositoryConfiguration, RepositoryChecker<R, D> checker ) throws RepositoryException
{
final String id = repositoryConfiguration.getId( );
R currentRepository = getRepositories().get( id );
R managedRepository = newInstance( repositoryConfiguration );
CheckedResult<R, D> result;
if ( currentRepository == null )
{
result = checker.apply( managedRepository );
}
else
{
result = checker.applyForUpdate( managedRepository );
}
if ( result.isValid( ) )
{
put( result.getRepository() );
}
return result;
}
protected abstract C findRepositoryConfiguration(Configuration configuration, String id);
protected abstract void removeRepositoryConfiguration(Configuration configuration, C repoConfiguration );
protected abstract void addRepositoryConfiguration( Configuration configuration, C repoConfiguration );
/**
* Removes a repository group from the registry and configuration, if it exists.
* The change is saved to the configuration immediately.
*
* @param id the id of the repository group to remove
* @throws RepositoryException if an error occurs during configuration save
*/
@Override
public void remove( String id ) throws RepositoryException
{
R repo = get( id );
if ( repo != null )
{
try
{
repo = getRepositories().remove( id );
if ( repo != null )
{
deactivateRepository( repo );
Configuration configuration = this.configurationHandler.getBaseConfiguration( );
C cfg = findRepositoryConfiguration( configuration, id );
if ( cfg != null )
{
removeRepositoryConfiguration( configuration, cfg );
}
this.configurationHandler.save( configuration, ConfigurationHandler.REGISTRY_EVENT_TAG );
setLastState( repo, RepositoryState.UNREGISTERED );
}
}
catch ( RegistryException | IndeterminateConfigurationException e )
{
// Rollback
log.error( "Could not save config after repository removal: {}", e.getMessage( ), e );
getRepositories().put( repo.getId( ), repo );
throw new RepositoryException( "Could not save configuration after repository removal: " + e.getMessage( ) );
}
}
}
@Override
public void remove( String id, Configuration configuration ) throws RepositoryException
{
R repo = getRepositories().get( id );
if ( repo != null )
{
repo = getRepositories().remove( id );
if ( repo != null )
{
deactivateRepository( repo );
}
setLastState( repo, RepositoryState.UNREGISTERED );
}
C cfg = findRepositoryConfiguration(configuration, id );
if ( cfg != null )
{
removeRepositoryConfiguration(configuration, cfg );
}
}
@Override
public R get( String groupId )
{
return getRepositories().get( groupId );
}
@Override
public Collection<R> getAll( )
{
return Collections.unmodifiableCollection( getRepositories( ).values( ) );
}
@Override
public RepositoryValidator<R> getValidator( )
{
return getCombinedValidator();
}
@Override
public CheckedResult<R, Map<String, List<ValidationError>>> validateRepository( R repository )
{
return getCombinedValidator( ).apply( repository );
}
@Override
public CheckedResult<R,Map<String, List<ValidationError>>> validateRepositoryForUpdate( R repository )
{
return getCombinedValidator().applyForUpdate( repository );
}
@Override
public boolean hasRepository( String id )
{
return getRepositories().containsKey( id );
}
@Override
public void close( )
{
for ( R repository : getRepositories().values( ) )
{
try
{
deactivateRepository( repository );
}
catch ( Throwable e )
{
log.error( "Could not close repository {}: {}", repository.getId( ), e.getMessage( ) );
}
}
getRepositories().clear( );
}
protected void registerNewRepository( C repositoryGroupConfiguration, R currentRepository, Configuration configuration, boolean updated ) throws IndeterminateConfigurationException, RegistryException, RepositoryException
{
final String id = repositoryGroupConfiguration.getId( );
getConfigurationHandler().save( configuration, ConfigurationHandler.REGISTRY_EVENT_TAG );
updateReferences( currentRepository, repositoryGroupConfiguration );
if (!updated )
{
setLastState( currentRepository, RepositoryState.REFERENCES_SET );
}
activateRepository( currentRepository );
getRepositories().put( id, currentRepository );
setLastState( currentRepository, RepositoryState.REGISTERED );
}
protected void rollback( Configuration configuration, R oldRepository, Exception e, C oldCfg ) throws RepositoryException
{
final String id = oldRepository.getId( );
replaceOrAddRepositoryConfig( oldCfg, configuration );
try
{
getConfigurationHandler().save( configuration, ConfigurationHandler.REGISTRY_EVENT_TAG );
}
catch ( IndeterminateConfigurationException | RegistryException indeterminateConfigurationException )
{
log.error( "Fatal error, config save during rollback failed: {}", e.getMessage( ), e );
}
updateReferences( oldRepository, oldCfg );
setLastState( oldRepository, RepositoryState.REFERENCES_SET );
activateRepository( oldRepository );
getRepositories().put( id, oldRepository );
setLastState( oldRepository, RepositoryState.REGISTERED );
}
protected void replaceOrAddRepositoryConfig( C repositoryGroupConfiguration, Configuration configuration )
{
C oldCfg = findRepositoryConfiguration( configuration, repositoryGroupConfiguration.getId( ) );
if ( oldCfg != null )
{
removeRepositoryConfiguration(configuration, oldCfg );
}
addRepositoryConfiguration( configuration, repositoryGroupConfiguration );
}
} }

View File

@ -20,6 +20,7 @@ package org.apache.archiva.repository.base;
*/ */
import org.apache.archiva.components.registry.RegistryException; import org.apache.archiva.components.registry.RegistryException;
import org.apache.archiva.configuration.AbstractRepositoryConfiguration;
import org.apache.archiva.configuration.ArchivaConfiguration; import org.apache.archiva.configuration.ArchivaConfiguration;
import org.apache.archiva.configuration.Configuration; import org.apache.archiva.configuration.Configuration;
import org.apache.archiva.configuration.ConfigurationEvent; import org.apache.archiva.configuration.ConfigurationEvent;
@ -38,8 +39,6 @@ import org.apache.archiva.indexer.ArchivaIndexingContext;
import org.apache.archiva.indexer.IndexCreationFailedException; import org.apache.archiva.indexer.IndexCreationFailedException;
import org.apache.archiva.indexer.IndexManagerFactory; import org.apache.archiva.indexer.IndexManagerFactory;
import org.apache.archiva.indexer.IndexUpdateFailedException; import org.apache.archiva.indexer.IndexUpdateFailedException;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.validation.CheckedResult;
import org.apache.archiva.repository.EditableManagedRepository; import org.apache.archiva.repository.EditableManagedRepository;
import org.apache.archiva.repository.EditableRemoteRepository; import org.apache.archiva.repository.EditableRemoteRepository;
import org.apache.archiva.repository.EditableRepository; import org.apache.archiva.repository.EditableRepository;
@ -49,6 +48,7 @@ import org.apache.archiva.repository.Repository;
import org.apache.archiva.repository.RepositoryContentFactory; import org.apache.archiva.repository.RepositoryContentFactory;
import org.apache.archiva.repository.RepositoryException; import org.apache.archiva.repository.RepositoryException;
import org.apache.archiva.repository.RepositoryGroup; import org.apache.archiva.repository.RepositoryGroup;
import org.apache.archiva.repository.RepositoryHandler;
import org.apache.archiva.repository.RepositoryProvider; import org.apache.archiva.repository.RepositoryProvider;
import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.RepositoryType; import org.apache.archiva.repository.RepositoryType;
@ -61,6 +61,7 @@ import org.apache.archiva.repository.features.IndexCreationFeature;
import org.apache.archiva.repository.features.StagingRepositoryFeature; import org.apache.archiva.repository.features.StagingRepositoryFeature;
import org.apache.archiva.repository.metadata.MetadataReader; import org.apache.archiva.repository.metadata.MetadataReader;
import org.apache.archiva.repository.storage.StorageAsset; import org.apache.archiva.repository.storage.StorageAsset;
import org.apache.archiva.repository.validation.CheckedResult;
import org.apache.archiva.repository.validation.RepositoryValidator; import org.apache.archiva.repository.validation.RepositoryValidator;
import org.apache.archiva.repository.validation.ValidationError; import org.apache.archiva.repository.validation.ValidationError;
import org.apache.archiva.repository.validation.ValidationResponse; import org.apache.archiva.repository.validation.ValidationResponse;
@ -118,23 +119,26 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
@Inject @Inject
List<MetadataReader> metadataReaderList; List<MetadataReader> metadataReaderList;
@Inject
List<RepositoryValidator<? extends Repository>> repositoryValidatorList;
@Inject @Inject
@Named( "repositoryContentFactory#default" ) @Named( "repositoryContentFactory#default" )
RepositoryContentFactory repositoryContentFactory; RepositoryContentFactory repositoryContentFactory;
private boolean ignoreIndexing = false;
private final EventManager eventManager; private final EventManager eventManager;
private Map<String, ManagedRepository> managedRepositories = new HashMap<>( );
private Map<String, ManagedRepository> uManagedRepository = Collections.unmodifiableMap( managedRepositories );
private Map<String, RemoteRepository> remoteRepositories = new HashMap<>( ); private Map<String, RemoteRepository> remoteRepositories = new HashMap<>( );
private Map<String, RemoteRepository> uRemoteRepositories = Collections.unmodifiableMap( remoteRepositories ); private Map<String, RemoteRepository> uRemoteRepositories = Collections.unmodifiableMap( remoteRepositories );
private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock( ); private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock( );
private RepositoryGroupHandler groupHandler; private RepositoryHandler<RepositoryGroup, RepositoryGroupConfiguration> groupHandler;
private RepositoryHandler<ManagedRepository, ManagedRepositoryConfiguration> managedRepositoryHandler;
private final Set<RepositoryValidator<? extends Repository>> validators; private final Set<RepositoryValidator<? extends Repository>> validators;
private final ConfigurationHandler configurationHandler; private final ConfigurationHandler configurationHandler;
@ -155,7 +159,8 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
private Set<RepositoryValidator<? extends Repository>> initValidatorList( List<RepositoryValidator<? extends Repository>> validators ) private Set<RepositoryValidator<? extends Repository>> initValidatorList( List<RepositoryValidator<? extends Repository>> validators )
{ {
TreeSet<RepositoryValidator<? extends Repository>> val = new TreeSet<>( ); TreeSet<RepositoryValidator<? extends Repository>> val = new TreeSet<>( );
for (RepositoryValidator<? extends Repository> validator : validators) { for ( RepositoryValidator<? extends Repository> validator : validators )
{
val.add( validator ); val.add( validator );
validator.setRepositoryRegistry( this ); validator.setRepositoryRegistry( this );
} }
@ -175,9 +180,7 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
try try
{ {
log.debug( "Initializing repository registry" ); log.debug( "Initializing repository registry" );
updateManagedRepositoriesFromConfig( ); initializeManagedRepositories();
pushEvent( new RepositoryRegistryEvent( RepositoryRegistryEvent.MANAGED_REPOS_INITIALIZED, this ) );
managed_initialized.set( true );
updateRemoteRepositoriesFromConfig( ); updateRemoteRepositoriesFromConfig( );
pushEvent( new RepositoryRegistryEvent( RepositoryRegistryEvent.REMOTE_REPOS_INITIALIZED, this ) ); pushEvent( new RepositoryRegistryEvent( RepositoryRegistryEvent.REMOTE_REPOS_INITIALIZED, this ) );
remote_initialized.set( true ); remote_initialized.set( true );
@ -211,9 +214,20 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
} }
} }
public void registerGroupHandler( RepositoryGroupHandler groupHandler ) private void initializeManagedRepositories( )
{
if ( this.managedRepositoryHandler != null )
{
this.managedRepositoryHandler.initializeFromConfig( );
this.managed_initialized.set( true );
pushEvent( new RepositoryRegistryEvent( RepositoryRegistryEvent.MANAGED_REPOS_INITIALIZED, this ) );
}
}
public void registerGroupHandler( RepositoryHandler<RepositoryGroup, RepositoryGroupConfiguration> groupHandler )
{ {
this.groupHandler = groupHandler; this.groupHandler = groupHandler;
registerRepositoryHandler( groupHandler );
initializeRepositoryGroups( ); initializeRepositoryGroups( );
if ( managed_initialized.get( ) && remote_initialized.get( ) && groups_initalized.get( ) ) if ( managed_initialized.get( ) && remote_initialized.get( ) && groups_initalized.get( ) )
{ {
@ -221,15 +235,22 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
} }
} }
public void registerManagedRepositoryHandler( RepositoryHandler<ManagedRepository, ManagedRepositoryConfiguration> managedRepositoryHandler )
{
this.managedRepositoryHandler = managedRepositoryHandler;
registerRepositoryHandler( managedRepositoryHandler );
initializeManagedRepositories();
if ( managed_initialized.get( ) && remote_initialized.get( ) && groups_initalized.get( ) )
{
pushEvent( new RepositoryRegistryEvent( RepositoryRegistryEvent.INITIALIZED, this ) );
}
}
@PreDestroy @PreDestroy
public void destroy( ) public void destroy( )
{ {
for ( ManagedRepository rep : managedRepositories.values( ) ) managedRepositoryHandler.close( );
{
rep.close( );
}
managedRepositories.clear( );
for ( RemoteRepository repo : remoteRepositories.values( ) ) for ( RemoteRepository repo : remoteRepositories.values( ) )
{ {
repo.close( ); repo.close( );
@ -266,100 +287,15 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
*/ */
private void updateManagedRepositoriesFromConfig( ) private void updateManagedRepositoriesFromConfig( )
{ {
try managedRepositoryHandler.initializeFromConfig( );
{
Set<String> configRepoIds = new HashSet<>( );
List<ManagedRepositoryConfiguration> managedRepoConfigs =
configurationHandler.getBaseConfiguration( ).getManagedRepositories( );
if ( managedRepoConfigs == null )
{
return;
} }
for ( ManagedRepositoryConfiguration repoConfig : managedRepoConfigs )
{
ManagedRepository repo = putRepository( repoConfig, null );
configRepoIds.add( repoConfig.getId( ) );
if ( repo.supportsFeature( StagingRepositoryFeature.class ) )
{
StagingRepositoryFeature stagF = repo.getFeature( StagingRepositoryFeature.class ).get( );
if ( stagF.getStagingRepository( ) != null )
{
configRepoIds.add( stagF.getStagingRepository( ).getId( ) );
}
}
}
List<String> toRemove = managedRepositories.keySet( ).stream( ).filter( id -> !configRepoIds.contains( id ) ).collect( Collectors.toList( ) );
for ( String id : toRemove )
{
ManagedRepository removed = managedRepositories.remove( id );
removed.close( );
}
}
catch ( Throwable e )
{
log.error( "Could not initialize repositories from config: {}", e.getMessage( ), e );
return;
}
}
private ManagedRepository createNewManagedRepository( RepositoryProvider provider, ManagedRepositoryConfiguration cfg ) throws RepositoryException
{
log.debug( "Creating repo {}", cfg.getId( ) );
ManagedRepository repo = provider.createManagedInstance( cfg );
repo.registerEventHandler( RepositoryEvent.ANY, this );
updateRepositoryReferences( provider, repo, cfg, null );
return repo;
}
private String getStagingId( String repoId ) private String getStagingId( String repoId )
{ {
return repoId + StagingRepositoryFeature.STAGING_REPO_POSTFIX; return repoId + StagingRepositoryFeature.STAGING_REPO_POSTFIX;
} }
@SuppressWarnings( "unchecked" )
private void updateRepositoryReferences( RepositoryProvider provider, ManagedRepository repo, ManagedRepositoryConfiguration cfg, Configuration configuration ) throws RepositoryException
{
log.debug( "Updating references of repo {}", repo.getId( ) );
if ( repo.supportsFeature( StagingRepositoryFeature.class ) )
{
StagingRepositoryFeature feature = repo.getFeature( StagingRepositoryFeature.class ).get( );
if ( feature.isStageRepoNeeded( ) && feature.getStagingRepository( ) == null )
{
ManagedRepository stageRepo = getManagedRepository( getStagingId( repo.getId( ) ) );
if ( stageRepo == null )
{
stageRepo = getStagingRepository( provider, cfg, configuration );
managedRepositories.put( stageRepo.getId( ), stageRepo );
if ( configuration != null )
{
replaceOrAddRepositoryConfig( provider.getManagedConfiguration( stageRepo ), configuration );
}
pushEvent( new LifecycleEvent( LifecycleEvent.REGISTERED, this, stageRepo ) );
}
feature.setStagingRepository( stageRepo );
}
}
if ( repo instanceof EditableManagedRepository )
{
EditableManagedRepository editableRepo = (EditableManagedRepository) repo;
if ( repo.getContent( ) == null )
{
editableRepo.setContent( repositoryContentFactory.getManagedRepositoryContent( repo ) );
editableRepo.getContent( ).setRepository( editableRepo );
}
log.debug( "Index repo: " + repo.hasIndex( ) );
if ( repo.hasIndex( ) && ( repo.getIndexingContext( ) == null || !repo.getIndexingContext( ).isOpen( ) ) )
{
log.debug( "Creating indexing context for {}", repo.getId( ) );
createIndexingContext( editableRepo );
}
}
repo.registerEventHandler( RepositoryEvent.ANY, this );
}
@Override @Override
public ArchivaIndexManager getIndexManager( RepositoryType type ) public ArchivaIndexManager getIndexManager( RepositoryType type )
@ -397,22 +333,6 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
} }
} }
private ManagedRepository getStagingRepository( RepositoryProvider provider, ManagedRepositoryConfiguration baseRepoCfg, Configuration configuration ) throws RepositoryException
{
ManagedRepository stageRepo = getManagedRepository( getStagingId( baseRepoCfg.getId( ) ) );
if ( stageRepo == null )
{
stageRepo = provider.createStagingInstance( baseRepoCfg );
if ( stageRepo.supportsFeature( StagingRepositoryFeature.class ) )
{
stageRepo.getFeature( StagingRepositoryFeature.class ).get( ).setStageRepoNeeded( false );
}
ManagedRepositoryConfiguration stageCfg = provider.getManagedConfiguration( stageRepo );
updateRepositoryReferences( provider, stageRepo, stageCfg, configuration );
}
return stageRepo;
}
private void updateRemoteRepositoriesFromConfig( ) private void updateRemoteRepositoriesFromConfig( )
{ {
@ -482,7 +402,7 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
rwLock.readLock( ).lock( ); rwLock.readLock( ).lock( );
try try
{ {
return Stream.concat( managedRepositories.values( ).stream( ), remoteRepositories.values( ).stream( ) ).collect( Collectors.toList( ) ); return Stream.concat( managedRepositoryHandler.getAll().stream( ), remoteRepositories.values( ).stream( ) ).collect( Collectors.toList( ) );
} }
finally finally
{ {
@ -501,7 +421,7 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
rwLock.readLock( ).lock( ); rwLock.readLock( ).lock( );
try try
{ {
return uManagedRepository.values( ); return managed_initialized.get() ? managedRepositoryHandler.getAll( ) : Collections.emptyList();
} }
finally finally
{ {
@ -556,10 +476,10 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
try try
{ {
log.debug( "getRepository {}", repoId ); log.debug( "getRepository {}", repoId );
if ( managedRepositories.containsKey( repoId ) ) if ( managedRepositoryHandler.hasRepository( repoId ) )
{ {
log.debug( "Managed repo" ); log.debug( "Managed repo" );
return managedRepositories.get( repoId ); return managedRepositoryHandler.get( repoId );
} }
else if ( remoteRepositories.containsKey( repoId ) ) else if ( remoteRepositories.containsKey( repoId ) )
{ {
@ -594,7 +514,7 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
rwLock.readLock( ).lock( ); rwLock.readLock( ).lock( );
try try
{ {
return managedRepositories.get( repoId ); return managed_initialized.get() ? managedRepositoryHandler.get( repoId ) : null;
} }
finally finally
{ {
@ -640,13 +560,15 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
@Override @Override
public boolean hasRepository( String repoId ) public boolean hasRepository( String repoId )
{ {
return this.managedRepositories.containsKey( repoId ) || this.remoteRepositories.containsKey( repoId ) || groupHandler.hasRepository( repoId ); return ( managedRepositoryHandler != null && managedRepositoryHandler.hasRepository( repoId ) )
|| ( this.remoteRepositories != null && this.remoteRepositories.containsKey( repoId ) )
|| ( this.groupHandler != null && groupHandler.hasRepository( repoId ) );
} }
@Override @Override
public boolean hasManagedRepository( String repoId ) public boolean hasManagedRepository( String repoId )
{ {
return this.managedRepositories.containsKey( repoId ); return managedRepositoryHandler.hasRepository( repoId );
} }
@Override @Override
@ -658,7 +580,7 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
@Override @Override
public boolean hasRepositoryGroup( String groupId ) public boolean hasRepositoryGroup( String groupId )
{ {
return groupHandler.hasRepository( groupId ); return this.groupHandler != null && groupHandler.hasRepository( groupId );
} }
protected void saveConfiguration( Configuration configuration ) throws IndeterminateConfigurationException, RegistryException protected void saveConfiguration( Configuration configuration ) throws IndeterminateConfigurationException, RegistryException
@ -680,53 +602,7 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
rwLock.writeLock( ).lock( ); rwLock.writeLock( ).lock( );
try try
{ {
final String id = managedRepository.getId( ); return managed_initialized.get() ? managedRepositoryHandler.put( managedRepository ) : null;
if ( remoteRepositories.containsKey( id ) )
{
throw new RepositoryException( "There exists a remote repository with id " + id + ". Could not update with managed repository." );
}
ManagedRepository originRepo = managedRepositories.put( id, managedRepository );
try
{
if ( originRepo != null && originRepo != managedRepository )
{
originRepo.close( );
}
RepositoryProvider provider = getProvider( managedRepository.getType( ) );
ManagedRepositoryConfiguration newCfg = provider.getManagedConfiguration( managedRepository );
Configuration configuration = configurationHandler.getBaseConfiguration( );
updateRepositoryReferences( provider, managedRepository, newCfg, configuration );
ManagedRepositoryConfiguration oldCfg = configuration.findManagedRepositoryById( id );
if ( oldCfg != null )
{
configuration.removeManagedRepository( oldCfg );
}
configuration.addManagedRepository( newCfg );
saveConfiguration( configuration );
if ( originRepo != managedRepository )
{
pushEvent( new LifecycleEvent( LifecycleEvent.REGISTERED, this, managedRepository ) );
}
else
{
pushEvent( new LifecycleEvent( LifecycleEvent.UPDATED, this, managedRepository ) );
}
return managedRepository;
}
catch ( Exception e )
{
// Rollback only partly, because repository is closed already
if ( originRepo != null )
{
managedRepositories.put( id, originRepo );
}
else
{
managedRepositories.remove( id );
}
log.error( "Exception during configuration update {}", e.getMessage( ), e );
throw new RepositoryException( "Could not save the configuration" + ( e.getMessage( ) == null ? "" : ": " + e.getMessage( ) ) );
}
} }
finally finally
{ {
@ -748,26 +624,7 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
rwLock.writeLock( ).lock( ); rwLock.writeLock( ).lock( );
try try
{ {
final String id = managedRepositoryConfiguration.getId( ); return managedRepositoryHandler.put( managedRepositoryConfiguration );
final RepositoryType repositoryType = RepositoryType.valueOf( managedRepositoryConfiguration.getType( ) );
Configuration configuration = configurationHandler.getBaseConfiguration( );
ManagedRepository repo = managedRepositories.get( id );
ManagedRepositoryConfiguration oldCfg = repo != null ? getProvider( repositoryType ).getManagedConfiguration( repo ) : null;
repo = putRepository( managedRepositoryConfiguration, configuration );
try
{
saveConfiguration( configuration );
}
catch ( IndeterminateConfigurationException | RegistryException e )
{
if ( oldCfg != null )
{
getProvider( repositoryType ).updateManagedInstance( (EditableManagedRepository) repo, oldCfg );
}
log.error( "Could not save the configuration for repository {}: {}", id, e.getMessage( ), e );
throw new RepositoryException( "Could not save the configuration for repository " + id + ": " + e.getMessage( ) );
}
return repo;
} }
finally finally
{ {
@ -791,39 +648,7 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
rwLock.writeLock( ).lock( ); rwLock.writeLock( ).lock( );
try try
{ {
final String id = managedRepositoryConfiguration.getId( ); return managedRepositoryHandler.put( managedRepositoryConfiguration, configuration );
final RepositoryType repoType = RepositoryType.valueOf( managedRepositoryConfiguration.getType( ) );
ManagedRepository repo;
boolean registeredNew = false;
repo = managedRepositories.get( id );
if ( repo != null && repo.isOpen( ) )
{
if ( repo instanceof EditableManagedRepository )
{
getProvider( repoType ).updateManagedInstance( (EditableManagedRepository) repo, managedRepositoryConfiguration );
}
else
{
throw new RepositoryException( "The repository is not editable " + id );
}
}
else
{
repo = getProvider( repoType ).createManagedInstance( managedRepositoryConfiguration );
managedRepositories.put( id, repo );
registeredNew = true;
}
updateRepositoryReferences( getProvider( repoType ), repo, managedRepositoryConfiguration, configuration );
replaceOrAddRepositoryConfig( managedRepositoryConfiguration, configuration );
if ( registeredNew )
{
pushEvent( new LifecycleEvent( LifecycleEvent.REGISTERED, this, repo ) );
}
else
{
pushEvent( new LifecycleEvent( LifecycleEvent.UPDATED, this, repo ) );
}
return repo;
} }
finally finally
{ {
@ -888,7 +713,7 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
rwLock.writeLock( ).lock( ); rwLock.writeLock( ).lock( );
try try
{ {
return groupHandler.putWithCheck( repositoryGroupConfiguration, groupHandler.getValidator() ); return groupHandler.putWithCheck( repositoryGroupConfiguration, groupHandler.getValidator( ) );
} }
finally finally
{ {
@ -919,19 +744,6 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
} }
} }
private void replaceOrAddRepositoryConfig( ManagedRepositoryConfiguration managedRepositoryConfiguration, Configuration configuration )
{
if ( configuration != null )
{
ManagedRepositoryConfiguration oldCfg = configuration.findManagedRepositoryById( managedRepositoryConfiguration.getId( ) );
if ( oldCfg != null )
{
configuration.removeManagedRepository( oldCfg );
}
configuration.addManagedRepository( managedRepositoryConfiguration );
}
}
private void replaceOrAddRepositoryConfig( RemoteRepositoryConfiguration remoteRepositoryConfiguration, Configuration configuration ) private void replaceOrAddRepositoryConfig( RemoteRepositoryConfiguration remoteRepositoryConfiguration, Configuration configuration )
{ {
if ( configuration != null ) if ( configuration != null )
@ -945,16 +757,6 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
} }
} }
private void replaceOrAddRepositoryConfig( RepositoryGroupConfiguration repositoryGroupConfiguration, Configuration configuration )
{
RepositoryGroupConfiguration oldCfg = configuration.findRepositoryGroupById( repositoryGroupConfiguration.getId( ) );
if ( oldCfg != null )
{
configuration.removeRepositoryGroup( oldCfg );
}
configuration.addRepositoryGroup( repositoryGroupConfiguration );
}
@Override @Override
public RemoteRepository putRepository( RemoteRepository remoteRepository, Configuration configuration ) throws RepositoryException public RemoteRepository putRepository( RemoteRepository remoteRepository, Configuration configuration ) throws RepositoryException
{ {
@ -962,7 +764,7 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
try try
{ {
final String id = remoteRepository.getId( ); final String id = remoteRepository.getId( );
if ( managedRepositories.containsKey( id ) ) if ( managedRepositoryHandler.hasRepository( id ) )
{ {
throw new RepositoryException( "There exists a managed repository with id " + id + ". Could not update with remote repository." ); throw new RepositoryException( "There exists a managed repository with id " + id + ". Could not update with remote repository." );
} }
@ -1206,41 +1008,16 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
{ {
return; return;
} }
final String id = managedRepository.getId( );
ManagedRepository repo = getManagedRepository( id );
if ( repo != null )
{
rwLock.writeLock( ).lock( ); rwLock.writeLock( ).lock( );
try try
{ {
repo = managedRepositories.remove( id ); if (managed_initialized.get() ) managedRepositoryHandler.remove( managedRepository.getId( ) );
if ( repo != null )
{
repo.close( );
this.groupHandler.removeRepositoryFromGroups( repo );
Configuration configuration = configurationHandler.getBaseConfiguration( );
ManagedRepositoryConfiguration cfg = configuration.findManagedRepositoryById( id );
if ( cfg != null )
{
configuration.removeManagedRepository( cfg );
}
saveConfiguration( configuration );
}
pushEvent( new LifecycleEvent( LifecycleEvent.UNREGISTERED, this, repo ) );
}
catch ( RegistryException | IndeterminateConfigurationException e )
{
// Rollback
log.error( "Could not save config after repository removal: {}", e.getMessage( ), e );
managedRepositories.put( repo.getId( ), repo );
throw new RepositoryException( "Could not save configuration after repository removal: " + e.getMessage( ) );
} }
finally finally
{ {
rwLock.writeLock( ).unlock( ); rwLock.writeLock( ).unlock( );
} }
} }
}
@Override @Override
@ -1250,31 +1027,15 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
{ {
return; return;
} }
final String id = managedRepository.getId( );
ManagedRepository repo = getManagedRepository( id );
if ( repo != null )
{
rwLock.writeLock( ).lock( ); rwLock.writeLock( ).lock( );
try try
{ {
repo = managedRepositories.remove( id ); if (managed_initialized.get()) managedRepositoryHandler.remove( managedRepository.getId( ), configuration );
if ( repo != null )
{
repo.close( );
this.groupHandler.removeRepositoryFromGroups( repo );
ManagedRepositoryConfiguration cfg = configuration.findManagedRepositoryById( id );
if ( cfg != null )
{
configuration.removeManagedRepository( cfg );
}
}
pushEvent( new LifecycleEvent( LifecycleEvent.UNREGISTERED, this, repo ) );
} }
finally finally
{ {
rwLock.writeLock( ).unlock( ); rwLock.writeLock( ).unlock( );
} }
}
} }
@ -1457,16 +1218,11 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
*/ */
public ManagedRepository clone( ManagedRepository repo, String newId ) throws RepositoryException public ManagedRepository clone( ManagedRepository repo, String newId ) throws RepositoryException
{ {
if ( managedRepositories.containsKey( newId ) || remoteRepositories.containsKey( newId ) ) if (isRegisteredId( newId )) {
{ throw new RepositoryException( "The new id exists already: " + newId );
throw new RepositoryException( "The given id exists already " + newId );
} }
RepositoryProvider provider = getProvider( repo.getType( ) ); EditableManagedRepository newRepo = (EditableManagedRepository) managedRepositoryHandler.clone( repo, newId );
ManagedRepositoryConfiguration cfg = provider.getManagedConfiguration( repo ); return newRepo;
cfg.setId( newId );
ManagedRepository cloned = provider.createManagedInstance( cfg );
cloned.registerEventHandler( RepositoryEvent.ANY, this );
return cloned;
} }
@Override @Override
@ -1495,7 +1251,7 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
*/ */
public RemoteRepository clone( RemoteRepository repo, String newId ) throws RepositoryException public RemoteRepository clone( RemoteRepository repo, String newId ) throws RepositoryException
{ {
if ( managedRepositories.containsKey( newId ) || remoteRepositories.containsKey( newId ) ) if ( isRegisteredId( newId ) )
{ {
throw new RepositoryException( "The given id exists already " + newId ); throw new RepositoryException( "The given id exists already " + newId );
} }
@ -1526,8 +1282,8 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
{ {
Map<String, List<ValidationError>> errorMap = this.validators.stream( ) Map<String, List<ValidationError>> errorMap = this.validators.stream( )
.filter( ( validator ) -> validator.getType( ).equals( RepositoryType.ALL ) || repository.getType( ).equals( validator.getType( ) ) ) .filter( ( validator ) -> validator.getType( ).equals( RepositoryType.ALL ) || repository.getType( ).equals( validator.getType( ) ) )
.filter( val -> val.isFlavour( repository.getClass() )) .filter( val -> val.isFlavour( repository.getClass( ) ) )
.flatMap( validator -> ((RepositoryValidator<R>)validator).apply( repository ).getResult().entrySet( ).stream( ) ) .flatMap( validator -> ( (RepositoryValidator<R>) validator ).apply( repository ).getResult( ).entrySet( ).stream( ) )
.collect( Collectors.toMap( .collect( Collectors.toMap(
entry -> entry.getKey( ), entry -> entry.getKey( ),
entry -> entry.getValue( ), entry -> entry.getValue( ),
@ -1541,8 +1297,8 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
{ {
Map<String, List<ValidationError>> errorMap = this.validators.stream( ) Map<String, List<ValidationError>> errorMap = this.validators.stream( )
.filter( ( validator ) -> validator.getType( ).equals( RepositoryType.ALL ) || repository.getType( ).equals( validator.getType( ) ) ) .filter( ( validator ) -> validator.getType( ).equals( RepositoryType.ALL ) || repository.getType( ).equals( validator.getType( ) ) )
.filter( val -> val.isFlavour( repository.getClass() )) .filter( val -> val.isFlavour( repository.getClass( ) ) )
.flatMap( validator -> ((RepositoryValidator<R>)validator).applyForUpdate( repository ).getResult().entrySet( ).stream( ) ) .flatMap( validator -> ( (RepositoryValidator<R>) validator ).applyForUpdate( repository ).getResult( ).entrySet( ).stream( ) )
.collect( Collectors.toMap( .collect( Collectors.toMap(
entry -> entry.getKey( ), entry -> entry.getKey( ),
entry -> entry.getValue( ), entry -> entry.getValue( ),
@ -1593,6 +1349,8 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
} }
private void handleIndexCreationEvent( RepositoryIndexEvent event ) private void handleIndexCreationEvent( RepositoryIndexEvent event )
{
if (!ignoreIndexing && !( event.getRepository() instanceof ManagedRepository ))
{ {
RepositoryIndexEvent idxEvent = event; RepositoryIndexEvent idxEvent = event;
EditableRepository repo = (EditableRepository) idxEvent.getRepository( ); EditableRepository repo = (EditableRepository) idxEvent.getRepository( );
@ -1628,6 +1386,7 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
} }
} }
} }
}
private boolean sameOriginator( Event event ) private boolean sameOriginator( Event event )
{ {
@ -1650,5 +1409,57 @@ public class ArchivaRepositoryRegistry implements ConfigurationListener, EventHa
eventManager.fireEvent( event ); eventManager.fireEvent( event );
} }
private <R extends Repository, C extends AbstractRepositoryConfiguration> void registerRepositoryHandler( RepositoryHandler<R, C> repositoryHandler )
{
repositoryHandler.setRepositoryProviders( this.repositoryProviders );
repositoryHandler.setRepositoryValidator( this.repositoryValidatorList );
}
@Override
public void registerHandler( RepositoryHandler<?, ?> handler )
{
if ( handler.getVariant( ).isAssignableFrom( RepositoryGroup.class ) )
{
registerGroupHandler( (RepositoryHandler<RepositoryGroup, RepositoryGroupConfiguration>) handler );
}
else if ( handler.getVariant( ).isAssignableFrom( ManagedRepository.class ) )
{
registerManagedRepositoryHandler( (RepositoryHandler<ManagedRepository, ManagedRepositoryConfiguration>) handler );
}
}
@Override
public boolean isRegisteredId( String id )
{
return hasRepository( id );
}
@Override
public <R extends Repository, C extends AbstractRepositoryConfiguration> RepositoryHandler<R, C> getHandler( Class<R> repositoryClazz, Class<C> configurationClazz )
{
if ( repositoryClazz.isAssignableFrom( RepositoryGroup.class ) )
{
return (RepositoryHandler<R, C>) this.groupHandler;
}
else if ( repositoryClazz.isAssignableFrom( ManagedRepository.class ) )
{
return (RepositoryHandler<R, C>) this.managedRepositoryHandler;
}
else
{
return null;
}
}
public boolean isIgnoreIndexing( )
{
return ignoreIndexing;
}
public void setIgnoreIndexing( boolean ignoreIndexing )
{
this.ignoreIndexing = ignoreIndexing;
}
} }

View File

@ -20,13 +20,9 @@ package org.apache.archiva.repository.base.group;
import org.apache.archiva.components.registry.RegistryException; import org.apache.archiva.components.registry.RegistryException;
import org.apache.archiva.configuration.Configuration; import org.apache.archiva.configuration.Configuration;
import org.apache.archiva.configuration.IndeterminateConfigurationException; import org.apache.archiva.configuration.IndeterminateConfigurationException;
import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
import org.apache.archiva.configuration.RepositoryGroupConfiguration; import org.apache.archiva.configuration.RepositoryGroupConfiguration;
import org.apache.archiva.indexer.merger.MergedRemoteIndexesScheduler; import org.apache.archiva.indexer.merger.MergedRemoteIndexesScheduler;
import org.apache.archiva.repository.RepositoryState;
import org.apache.archiva.repository.base.AbstractRepositoryHandler;
import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
import org.apache.archiva.repository.base.ConfigurationHandler;
import org.apache.archiva.repository.validation.CheckedResult;
import org.apache.archiva.repository.EditableRepository; import org.apache.archiva.repository.EditableRepository;
import org.apache.archiva.repository.EditableRepositoryGroup; import org.apache.archiva.repository.EditableRepositoryGroup;
import org.apache.archiva.repository.ManagedRepository; import org.apache.archiva.repository.ManagedRepository;
@ -34,14 +30,17 @@ import org.apache.archiva.repository.Repository;
import org.apache.archiva.repository.RepositoryException; import org.apache.archiva.repository.RepositoryException;
import org.apache.archiva.repository.RepositoryGroup; import org.apache.archiva.repository.RepositoryGroup;
import org.apache.archiva.repository.RepositoryHandler; import org.apache.archiva.repository.RepositoryHandler;
import org.apache.archiva.repository.RepositoryHandlerManager;
import org.apache.archiva.repository.RepositoryProvider; import org.apache.archiva.repository.RepositoryProvider;
import org.apache.archiva.repository.RepositoryState;
import org.apache.archiva.repository.RepositoryType; import org.apache.archiva.repository.RepositoryType;
import org.apache.archiva.repository.base.AbstractRepositoryHandler;
import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
import org.apache.archiva.repository.base.ConfigurationHandler;
import org.apache.archiva.repository.event.LifecycleEvent;
import org.apache.archiva.repository.event.RepositoryEvent; import org.apache.archiva.repository.event.RepositoryEvent;
import org.apache.archiva.repository.features.IndexCreationFeature; import org.apache.archiva.repository.features.IndexCreationFeature;
import org.apache.archiva.repository.storage.StorageAsset; import org.apache.archiva.repository.storage.StorageAsset;
import org.apache.archiva.repository.validation.RepositoryChecker;
import org.apache.archiva.repository.validation.RepositoryValidator;
import org.apache.archiva.repository.validation.ValidationError;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -53,14 +52,10 @@ import javax.inject.Named;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -79,13 +74,9 @@ public class RepositoryGroupHandler
{ {
private static final Logger log = LoggerFactory.getLogger( RepositoryGroupHandler.class ); private static final Logger log = LoggerFactory.getLogger( RepositoryGroupHandler.class );
private final ArchivaRepositoryRegistry repositoryRegistry; private final RepositoryHandlerManager repositoryRegistry;
private final ConfigurationHandler configurationHandler;
private final MergedRemoteIndexesScheduler mergedRemoteIndexesScheduler; private final MergedRemoteIndexesScheduler mergedRemoteIndexesScheduler;
private final Map<String, RepositoryGroup> repositoryGroups = new HashMap<>( );
private final RepositoryValidator<RepositoryGroup> validator;
private Path groupsDirectory; private Path groupsDirectory;
@ -95,18 +86,15 @@ public class RepositoryGroupHandler
* @param repositoryRegistry the registry. To avoid circular dependencies via DI, this class registers itself on the registry. * @param repositoryRegistry the registry. To avoid circular dependencies via DI, this class registers itself on the registry.
* @param configurationHandler the configuration handler is used to retrieve and save configuration. * @param configurationHandler the configuration handler is used to retrieve and save configuration.
* @param mergedRemoteIndexesScheduler the index scheduler is used for merging the indexes from all group members * @param mergedRemoteIndexesScheduler the index scheduler is used for merging the indexes from all group members
* @param repositoryValidatorList the list of validators that are registered
*/ */
public RepositoryGroupHandler( ArchivaRepositoryRegistry repositoryRegistry, public RepositoryGroupHandler( RepositoryHandlerManager repositoryRegistry,
ConfigurationHandler configurationHandler, ConfigurationHandler configurationHandler,
@Named( "mergedRemoteIndexesScheduler#default" ) MergedRemoteIndexesScheduler mergedRemoteIndexesScheduler, @Named( "mergedRemoteIndexesScheduler#default" ) MergedRemoteIndexesScheduler mergedRemoteIndexesScheduler
List<RepositoryValidator<? extends Repository>> repositoryValidatorList
) )
{ {
this.configurationHandler = configurationHandler; super( RepositoryGroup.class, RepositoryGroupConfiguration.class, configurationHandler );
this.mergedRemoteIndexesScheduler = mergedRemoteIndexesScheduler; this.mergedRemoteIndexesScheduler = mergedRemoteIndexesScheduler;
this.repositoryRegistry = repositoryRegistry; this.repositoryRegistry = repositoryRegistry;
this.validator = getCombinedValidatdor( RepositoryGroup.class, repositoryValidatorList );
} }
@Override @Override
@ -116,15 +104,15 @@ public class RepositoryGroupHandler
log.debug( "Initializing repository group handler " + repositoryRegistry.toString( ) ); log.debug( "Initializing repository group handler " + repositoryRegistry.toString( ) );
initializeStorage( ); initializeStorage( );
// We are registering this class on the registry. This is necessary to avoid circular dependencies via injection. // We are registering this class on the registry. This is necessary to avoid circular dependencies via injection.
this.repositoryRegistry.registerGroupHandler( this ); this.repositoryRegistry.registerHandler( this );
} }
@Override @Override
public void initializeFromConfig( ) public void initializeFromConfig( )
{ {
this.repositoryGroups.clear( ); getRepositories().clear( );
this.repositoryGroups.putAll( newInstancesFromConfig( ) ); getRepositories().putAll( newInstancesFromConfig( ) );
for ( RepositoryGroup group : this.repositoryGroups.values( ) ) for ( RepositoryGroup group : getRepositories().values( ) )
{ {
activateRepository( group ); activateRepository( group );
} }
@ -132,7 +120,7 @@ public class RepositoryGroupHandler
private void initializeStorage( ) private void initializeStorage( )
{ {
Path baseDir = this.configurationHandler.getArchivaConfiguration( ).getRepositoryGroupBaseDir( ); Path baseDir = this.getConfigurationHandler().getArchivaConfiguration( ).getRepositoryGroupBaseDir( );
if ( !Files.exists( baseDir ) ) if ( !Files.exists( baseDir ) )
{ {
try try
@ -179,6 +167,14 @@ public class RepositoryGroupHandler
setLastState( repositoryGroup, RepositoryState.INITIALIZED ); setLastState( repositoryGroup, RepositoryState.INITIALIZED );
} }
@Override
public void deactivateRepository( RepositoryGroup repository )
{
mergedRemoteIndexesScheduler.unschedule( repository );
repository.close();
setLastState( repository, RepositoryState.DEACTIVATED );
}
public StorageAsset getMergedIndexDirectory( RepositoryGroup group ) public StorageAsset getMergedIndexDirectory( RepositoryGroup group )
{ {
if ( group != null ) if ( group != null )
@ -198,7 +194,7 @@ public class RepositoryGroupHandler
try try
{ {
List<RepositoryGroupConfiguration> repositoryGroupConfigurations = List<RepositoryGroupConfiguration> repositoryGroupConfigurations =
this.configurationHandler.getBaseConfiguration( ).getRepositoryGroups( ); this.getConfigurationHandler().getBaseConfiguration( ).getRepositoryGroups( );
if ( repositoryGroupConfigurations == null ) if ( repositoryGroupConfigurations == null )
{ {
@ -207,11 +203,10 @@ public class RepositoryGroupHandler
Map<String, RepositoryGroup> repositoryGroupMap = new LinkedHashMap<>( repositoryGroupConfigurations.size( ) ); Map<String, RepositoryGroup> repositoryGroupMap = new LinkedHashMap<>( repositoryGroupConfigurations.size( ) );
Map<RepositoryType, RepositoryProvider> providerMap = repositoryRegistry.getRepositoryProviderMap( );
for ( RepositoryGroupConfiguration repoConfig : repositoryGroupConfigurations ) for ( RepositoryGroupConfiguration repoConfig : repositoryGroupConfigurations )
{ {
RepositoryType repositoryType = RepositoryType.valueOf( repoConfig.getType( ) ); RepositoryType repositoryType = RepositoryType.valueOf( repoConfig.getType( ) );
if ( providerMap.containsKey( repositoryType ) ) if ( super.providerMap.containsKey( repositoryType ) )
{ {
try try
{ {
@ -236,7 +231,7 @@ public class RepositoryGroupHandler
@Override @Override
public RepositoryGroup newInstance( final RepositoryType type, String id ) throws RepositoryException public RepositoryGroup newInstance( final RepositoryType type, String id ) throws RepositoryException
{ {
RepositoryProvider provider = repositoryRegistry.getProvider( type ); RepositoryProvider provider = getProvider( type );
RepositoryGroupConfiguration config = new RepositoryGroupConfiguration( ); RepositoryGroupConfiguration config = new RepositoryGroupConfiguration( );
config.setId( id ); config.setId( id );
return createNewRepositoryGroup( provider, config ); return createNewRepositoryGroup( provider, config );
@ -246,7 +241,7 @@ public class RepositoryGroupHandler
public RepositoryGroup newInstance( final RepositoryGroupConfiguration repositoryConfiguration ) throws RepositoryException public RepositoryGroup newInstance( final RepositoryGroupConfiguration repositoryConfiguration ) throws RepositoryException
{ {
RepositoryType type = RepositoryType.valueOf( repositoryConfiguration.getType( ) ); RepositoryType type = RepositoryType.valueOf( repositoryConfiguration.getType( ) );
RepositoryProvider provider = repositoryRegistry.getProvider( type ); RepositoryProvider provider = getProvider( type );
return createNewRepositoryGroup( provider, repositoryConfiguration ); return createNewRepositoryGroup( provider, repositoryConfiguration );
} }
@ -258,6 +253,7 @@ public class RepositoryGroupHandler
{ {
( (EditableRepository) repositoryGroup ).setLastState( RepositoryState.REFERENCES_SET ); ( (EditableRepository) repositoryGroup ).setLastState( RepositoryState.REFERENCES_SET );
} }
repositoryGroup.registerEventHandler( RepositoryEvent.ANY, repositoryRegistry );
return repositoryGroup; return repositoryGroup;
} }
@ -273,21 +269,21 @@ public class RepositoryGroupHandler
public RepositoryGroup put( final RepositoryGroup repositoryGroup ) throws RepositoryException public RepositoryGroup put( final RepositoryGroup repositoryGroup ) throws RepositoryException
{ {
final String id = repositoryGroup.getId( ); final String id = repositoryGroup.getId( );
RepositoryGroup originRepoGroup = repositoryGroups.remove( id ); RepositoryGroup originRepoGroup = getRepositories().remove( id );
try try
{ {
if ( originRepoGroup != null && originRepoGroup != repositoryGroup ) if ( originRepoGroup != null && originRepoGroup != repositoryGroup )
{ {
this.mergedRemoteIndexesScheduler.unschedule( originRepoGroup ); deactivateRepository( originRepoGroup );
originRepoGroup.close( ); pushEvent( new LifecycleEvent( LifecycleEvent.UNREGISTERED, this, originRepoGroup ) );
} }
RepositoryProvider provider = repositoryRegistry.getProvider( repositoryGroup.getType( ) ); RepositoryProvider provider = getProvider( repositoryGroup.getType( ) );
RepositoryGroupConfiguration newCfg = provider.getRepositoryGroupConfiguration( repositoryGroup ); RepositoryGroupConfiguration newCfg = provider.getRepositoryGroupConfiguration( repositoryGroup );
ReentrantReadWriteLock.WriteLock configLock = this.configurationHandler.getLock( ).writeLock( ); ReentrantReadWriteLock.WriteLock configLock = this.getConfigurationHandler().getLock( ).writeLock( );
configLock.lock( ); configLock.lock( );
try try
{ {
Configuration configuration = this.configurationHandler.getBaseConfiguration( ); Configuration configuration = this.getConfigurationHandler().getBaseConfiguration( );
updateReferences( repositoryGroup, newCfg ); updateReferences( repositoryGroup, newCfg );
RepositoryGroupConfiguration oldCfg = configuration.findRepositoryGroupById( id ); RepositoryGroupConfiguration oldCfg = configuration.findRepositoryGroupById( id );
if ( oldCfg != null ) if ( oldCfg != null )
@ -295,7 +291,7 @@ public class RepositoryGroupHandler
configuration.removeRepositoryGroup( oldCfg ); configuration.removeRepositoryGroup( oldCfg );
} }
configuration.addRepositoryGroup( newCfg ); configuration.addRepositoryGroup( newCfg );
configurationHandler.save( configuration, ConfigurationHandler.REGISTRY_EVENT_TAG ); getConfigurationHandler().save( configuration, ConfigurationHandler.REGISTRY_EVENT_TAG );
setLastState( repositoryGroup, RepositoryState.SAVED ); setLastState( repositoryGroup, RepositoryState.SAVED );
activateRepository( repositoryGroup ); activateRepository( repositoryGroup );
} }
@ -303,7 +299,7 @@ public class RepositoryGroupHandler
{ {
configLock.unlock( ); configLock.unlock( );
} }
repositoryGroups.put( id, repositoryGroup ); getRepositories().put( id, repositoryGroup );
setLastState( repositoryGroup, RepositoryState.REGISTERED ); setLastState( repositoryGroup, RepositoryState.REGISTERED );
return repositoryGroup; return repositoryGroup;
} }
@ -312,11 +308,11 @@ public class RepositoryGroupHandler
// Rollback // Rollback
if ( originRepoGroup != null ) if ( originRepoGroup != null )
{ {
repositoryGroups.put( id, originRepoGroup ); getRepositories().put( id, originRepoGroup );
} }
else else
{ {
repositoryGroups.remove( id ); getRepositories().remove( id );
} }
log.error( "Exception during configuration update {}", e.getMessage( ), e ); log.error( "Exception during configuration update {}", e.getMessage( ), e );
throw new RepositoryException( "Could not save the configuration" + ( e.getMessage( ) == null ? "" : ": " + e.getMessage( ) ), e); throw new RepositoryException( "Could not save the configuration" + ( e.getMessage( ) == null ? "" : ": " + e.getMessage( ) ), e);
@ -336,31 +332,28 @@ public class RepositoryGroupHandler
{ {
final String id = repositoryGroupConfiguration.getId( ); final String id = repositoryGroupConfiguration.getId( );
final RepositoryType repositoryType = RepositoryType.valueOf( repositoryGroupConfiguration.getType( ) ); final RepositoryType repositoryType = RepositoryType.valueOf( repositoryGroupConfiguration.getType( ) );
final RepositoryProvider provider = repositoryRegistry.getProvider( repositoryType ); final RepositoryProvider provider = getProvider( repositoryType );
RepositoryGroup currentRepository; RepositoryGroup currentRepository;
ReentrantReadWriteLock.WriteLock configLock = this.configurationHandler.getLock( ).writeLock( ); ReentrantReadWriteLock.WriteLock configLock = this.getConfigurationHandler().getLock( ).writeLock( );
configLock.lock( ); configLock.lock( );
try try
{ {
Configuration configuration = this.configurationHandler.getBaseConfiguration( ); Configuration configuration = this.getConfigurationHandler().getBaseConfiguration( );
currentRepository = repositoryRegistry.getRepositoryGroup( id ); currentRepository = getRepositories().get( id );
RepositoryGroup oldRepository = currentRepository == null ? null : clone( currentRepository ); RepositoryGroup oldRepository = currentRepository == null ? null : clone( currentRepository, id );
try try
{ {
boolean updated = false;
if (currentRepository==null) { if (currentRepository==null) {
currentRepository = put( repositoryGroupConfiguration, configuration ); currentRepository = put( repositoryGroupConfiguration, configuration );
} else } else
{ {
setRepositoryGroupDefaults( repositoryGroupConfiguration ); setRepositoryGroupDefaults( repositoryGroupConfiguration );
provider.updateRepositoryGroupInstance( (EditableRepositoryGroup) currentRepository, repositoryGroupConfiguration ); provider.updateRepositoryGroupInstance( (EditableRepositoryGroup) currentRepository, repositoryGroupConfiguration );
updated = true;
pushEvent( LifecycleEvent.UPDATED, currentRepository );
} }
configurationHandler.save( configuration, ConfigurationHandler.REGISTRY_EVENT_TAG ); registerNewRepository( repositoryGroupConfiguration, currentRepository, configuration, updated );
updateReferences( currentRepository, repositoryGroupConfiguration );
setLastState( currentRepository, RepositoryState.REFERENCES_SET );
activateRepository( currentRepository );
this.repositoryGroups.put( id, currentRepository );
setLastState( currentRepository, RepositoryState.REGISTERED );
} }
catch ( IndeterminateConfigurationException | RegistryException | RepositoryException e ) catch ( IndeterminateConfigurationException | RegistryException | RepositoryException e )
{ {
@ -368,23 +361,10 @@ public class RepositoryGroupHandler
if ( oldRepository != null ) if ( oldRepository != null )
{ {
RepositoryGroupConfiguration oldCfg = provider.getRepositoryGroupConfiguration( oldRepository ); RepositoryGroupConfiguration oldCfg = provider.getRepositoryGroupConfiguration( oldRepository );
provider.updateRepositoryGroupInstance( (EditableRepositoryGroup) currentRepository, oldCfg); provider.updateRepositoryGroupInstance( (EditableRepositoryGroup) currentRepository, oldCfg );
replaceOrAddRepositoryConfig( oldCfg, configuration ); rollback( configuration, oldRepository, e, oldCfg );
try
{
configurationHandler.save( configuration, ConfigurationHandler.REGISTRY_EVENT_TAG );
}
catch ( IndeterminateConfigurationException | RegistryException indeterminateConfigurationException )
{
log.error( "Fatal error, config save during rollback failed: {}", e.getMessage( ), e );
}
updateReferences( oldRepository, oldCfg );
setLastState( oldRepository, RepositoryState.REFERENCES_SET );
activateRepository( oldRepository );
repositoryGroups.put( id, oldRepository );
setLastState( oldRepository, RepositoryState.REGISTERED );
} else { } else {
repositoryGroups.remove( id ); getRepositories().remove( id );
} }
log.error( "Could not save the configuration for repository group {}: {}", id, e.getMessage( ), e ); log.error( "Could not save the configuration for repository group {}: {}", id, e.getMessage( ), e );
if (e instanceof RepositoryException) { if (e instanceof RepositoryException) {
@ -409,12 +389,12 @@ public class RepositoryGroupHandler
final RepositoryType repoType = RepositoryType.valueOf( repositoryGroupConfiguration.getType( ) ); final RepositoryType repoType = RepositoryType.valueOf( repositoryGroupConfiguration.getType( ) );
RepositoryGroup repo; RepositoryGroup repo;
setRepositoryGroupDefaults( repositoryGroupConfiguration ); setRepositoryGroupDefaults( repositoryGroupConfiguration );
if ( repositoryGroups.containsKey( id ) ) if ( getRepositories().containsKey( id ) )
{ {
repo = clone( repositoryGroups.get( id ) ); repo = clone( getRepositories().get( id ), id );
if ( repo instanceof EditableRepositoryGroup ) if ( repo instanceof EditableRepositoryGroup )
{ {
repositoryRegistry.getProvider( repoType ).updateRepositoryGroupInstance( (EditableRepositoryGroup) repo, repositoryGroupConfiguration ); getProvider( repoType ).updateRepositoryGroupInstance( (EditableRepositoryGroup) repo, repositoryGroupConfiguration );
} }
else else
{ {
@ -423,7 +403,7 @@ public class RepositoryGroupHandler
} }
else else
{ {
repo = repositoryRegistry.getProvider( repoType ).createRepositoryGroup( repositoryGroupConfiguration ); repo = getProvider( repoType ).createRepositoryGroup( repositoryGroupConfiguration );
setLastState( repo, RepositoryState.CREATED ); setLastState( repo, RepositoryState.CREATED );
} }
replaceOrAddRepositoryConfig( repositoryGroupConfiguration, configuration ); replaceOrAddRepositoryConfig( repositoryGroupConfiguration, configuration );
@ -432,29 +412,6 @@ public class RepositoryGroupHandler
return repo; return repo;
} }
@Override
public <D> CheckedResult<RepositoryGroup, D> putWithCheck( RepositoryGroupConfiguration repositoryConfiguration, RepositoryChecker<RepositoryGroup, D> checker ) throws RepositoryException
{
final String id = repositoryConfiguration.getId( );
RepositoryGroup currentGroup = repositoryGroups.get( id );
RepositoryGroup repositoryGroup = newInstance( repositoryConfiguration );
CheckedResult<RepositoryGroup, D> result;
if ( currentGroup == null )
{
result = checker.apply( repositoryGroup );
}
else
{
result = checker.applyForUpdate( repositoryGroup );
}
if ( result.isValid( ) )
{
put( result.getRepository() );
}
return result;
}
private void setRepositoryGroupDefaults( RepositoryGroupConfiguration repositoryGroupConfiguration ) private void setRepositoryGroupDefaults( RepositoryGroupConfiguration repositoryGroupConfiguration )
{ {
if ( StringUtils.isEmpty( repositoryGroupConfiguration.getMergedIndexPath( ) ) ) if ( StringUtils.isEmpty( repositoryGroupConfiguration.getMergedIndexPath( ) ) )
@ -471,106 +428,23 @@ public class RepositoryGroupHandler
} }
} }
private void replaceOrAddRepositoryConfig( RepositoryGroupConfiguration repositoryGroupConfiguration, Configuration configuration )
{
RepositoryGroupConfiguration oldCfg = configuration.findRepositoryGroupById( repositoryGroupConfiguration.getId( ) );
if ( oldCfg != null )
{
configuration.removeRepositoryGroup( oldCfg );
}
configuration.addRepositoryGroup( repositoryGroupConfiguration );
}
public void removeRepositoryFromGroups( ManagedRepository repo )
{
if ( repo != null )
{
repositoryGroups.values( ).stream( ).filter( repoGroup -> repoGroup instanceof EditableRepository ).
map( repoGroup -> (EditableRepositoryGroup) repoGroup ).forEach( repoGroup -> repoGroup.removeRepository( repo ) );
}
}
/**
* Removes a repository group from the registry and configuration, if it exists.
* The change is saved to the configuration immediately.
*
* @param id the id of the repository group to remove
* @throws RepositoryException if a error occurs during configuration save
*/
@Override @Override
public void remove( final String id ) throws RepositoryException public void processOtherVariantRemoval( Repository repo )
{ {
RepositoryGroup repo = get( id ); if ( repo instanceof ManagedRepository )
if ( repo != null )
{ {
try getRepositories().values( ).stream( ).filter( repoGroup -> repoGroup instanceof EditableRepository ).
{ map( repoGroup -> (EditableRepositoryGroup) repoGroup ).forEach( repoGroup -> repoGroup.removeRepository( (ManagedRepository) repo ) );
repo = repositoryGroups.remove( id );
if ( repo != null )
{
this.mergedRemoteIndexesScheduler.unschedule( repo );
repo.close( );
Configuration configuration = this.configurationHandler.getBaseConfiguration( );
RepositoryGroupConfiguration cfg = configuration.findRepositoryGroupById( id );
if ( cfg != null )
{
configuration.removeRepositoryGroup( cfg );
} }
this.configurationHandler.save( configuration, ConfigurationHandler.REGISTRY_EVENT_TAG );
setLastState( repo, RepositoryState.UNREGISTERED );
} }
}
catch ( RegistryException | IndeterminateConfigurationException e )
{
// Rollback
log.error( "Could not save config after repository removal: {}", e.getMessage( ), e );
repositoryGroups.put( repo.getId( ), repo );
throw new RepositoryException( "Could not save configuration after repository removal: " + e.getMessage( ) );
}
}
}
@Override @Override
public void remove( String id, Configuration configuration ) throws RepositoryException public RepositoryGroup clone( RepositoryGroup repo, String newId ) throws RepositoryException
{ {
RepositoryGroup repo = repositoryGroups.get( id ); RepositoryProvider provider = getProvider( repo.getType( ) );
if ( repo != null )
{
repo = repositoryGroups.remove( id );
if ( repo != null )
{
this.mergedRemoteIndexesScheduler.unschedule( repo );
repo.close( );
RepositoryGroupConfiguration cfg = configuration.findRepositoryGroupById( id );
if ( cfg != null )
{
configuration.removeRepositoryGroup( cfg );
}
setLastState( repo, RepositoryState.UNREGISTERED );
}
}
Iterator<RepositoryGroupConfiguration> cfgIter = configuration.getRepositoryGroups( ).iterator( );
while(cfgIter.hasNext()) {
RepositoryGroupConfiguration el = cfgIter.next( );
if (id.equals( el.getId() )) {
cfgIter.remove( );
break;
}
}
}
@Override
public RepositoryGroup get( String groupId )
{
return repositoryGroups.get( groupId );
}
@Override
public RepositoryGroup clone( RepositoryGroup repo ) throws RepositoryException
{
RepositoryProvider provider = repositoryRegistry.getProvider( repo.getType( ) );
RepositoryGroupConfiguration cfg = provider.getRepositoryGroupConfiguration( repo ); RepositoryGroupConfiguration cfg = provider.getRepositoryGroupConfiguration( repo );
cfg.setId( newId );
RepositoryGroup cloned = provider.createRepositoryGroup( cfg ); RepositoryGroup cloned = provider.createRepositoryGroup( cfg );
cloned.registerEventHandler( RepositoryEvent.ANY, repositoryRegistry ); cloned.registerEventHandler( RepositoryEvent.ANY, repositoryRegistry );
setLastState( cloned, RepositoryState.CREATED ); setLastState( cloned, RepositoryState.CREATED );
@ -578,46 +452,18 @@ public class RepositoryGroupHandler
} }
@Override @Override
public void updateReferences( RepositoryGroup repo, RepositoryGroupConfiguration repositoryConfiguration ) throws RepositoryException public void updateReferences( RepositoryGroup repo, RepositoryGroupConfiguration repositoryConfiguration )
{ {
if ( repo instanceof EditableRepositoryGroup && repositoryConfiguration!=null) if ( repo instanceof EditableRepositoryGroup && repositoryConfiguration!=null)
{ {
EditableRepositoryGroup eGroup = (EditableRepositoryGroup) repo; EditableRepositoryGroup eGroup = (EditableRepositoryGroup) repo;
RepositoryHandler<ManagedRepository, ManagedRepositoryConfiguration> managedHandler = repositoryRegistry.getHandler( ManagedRepository.class, ManagedRepositoryConfiguration.class );
eGroup.setRepositories( repositoryConfiguration.getRepositories( ).stream( ) eGroup.setRepositories( repositoryConfiguration.getRepositories( ).stream( )
.map( repositoryRegistry::getManagedRepository ).collect( Collectors.toList( ) ) ); .map( managedHandler::get ).collect( Collectors.toList( ) ) );
} }
} }
@Override
public Collection<RepositoryGroup> getAll( )
{
return Collections.unmodifiableCollection( repositoryGroups.values( ) );
}
@Override
public RepositoryValidator<RepositoryGroup> getValidator( )
{
return this.validator;
}
@Override
public CheckedResult<RepositoryGroup, Map<String, List<ValidationError>>> validateRepository( RepositoryGroup repository )
{
return this.validator.apply( repository );
}
@Override
public CheckedResult<RepositoryGroup,Map<String, List<ValidationError>>> validateRepositoryForUpdate( RepositoryGroup repository )
{
return this.validator.applyForUpdate( repository );
}
@Override
public boolean hasRepository( String id )
{
return repositoryGroups.containsKey( id );
}
@PreDestroy @PreDestroy
private void destroy( ) private void destroy( )
@ -626,21 +472,20 @@ public class RepositoryGroupHandler
} }
@Override @Override
public void close( ) protected RepositoryGroupConfiguration findRepositoryConfiguration( Configuration configuration, String id )
{ {
for ( RepositoryGroup group : repositoryGroups.values( ) ) return configuration.findRepositoryGroupById( id );
{
try
{
mergedRemoteIndexesScheduler.unschedule( group );
group.close( );
}
catch ( Throwable e )
{
log.error( "Could not close repository group {}: {}", group.getId( ), e.getMessage( ) );
}
}
this.repositoryGroups.clear( );
} }
@Override
protected void removeRepositoryConfiguration( Configuration configuration, RepositoryGroupConfiguration cfg )
{
configuration.removeRepositoryGroup( cfg );
}
@Override
protected void addRepositoryConfiguration( Configuration configuration, RepositoryGroupConfiguration repoConfiguration )
{
configuration.addRepositoryGroup( repoConfiguration );
}
} }

View File

@ -17,75 +17,103 @@ package org.apache.archiva.repository.base.managed;
* under the License. * under the License.
*/ */
import org.apache.archiva.components.registry.RegistryException;
import org.apache.archiva.configuration.Configuration; import org.apache.archiva.configuration.Configuration;
import org.apache.archiva.configuration.IndeterminateConfigurationException;
import org.apache.archiva.configuration.ManagedRepositoryConfiguration; import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
import org.apache.archiva.indexer.ArchivaIndexManager;
import org.apache.archiva.indexer.IndexCreationFailedException;
import org.apache.archiva.indexer.IndexManagerFactory;
import org.apache.archiva.repository.EditableManagedRepository;
import org.apache.archiva.repository.EditableRepository;
import org.apache.archiva.repository.ManagedRepository; import org.apache.archiva.repository.ManagedRepository;
import org.apache.archiva.repository.Repository; import org.apache.archiva.repository.RepositoryContentFactory;
import org.apache.archiva.repository.RepositoryException; import org.apache.archiva.repository.RepositoryException;
import org.apache.archiva.repository.RepositoryHandler; import org.apache.archiva.repository.RepositoryHandler;
import org.apache.archiva.repository.RepositoryHandlerManager;
import org.apache.archiva.repository.RepositoryProvider;
import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.RepositoryState;
import org.apache.archiva.repository.RepositoryType; import org.apache.archiva.repository.RepositoryType;
import org.apache.archiva.repository.base.AbstractRepositoryHandler; import org.apache.archiva.repository.base.AbstractRepositoryHandler;
import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
import org.apache.archiva.repository.base.ConfigurationHandler; import org.apache.archiva.repository.base.ConfigurationHandler;
import org.apache.archiva.repository.event.LifecycleEvent;
import org.apache.archiva.repository.event.RepositoryEvent;
import org.apache.archiva.repository.features.IndexCreationFeature;
import org.apache.archiva.repository.features.StagingRepositoryFeature; import org.apache.archiva.repository.features.StagingRepositoryFeature;
import org.apache.archiva.repository.validation.CheckedResult;
import org.apache.archiva.repository.validation.RepositoryChecker;
import org.apache.archiva.repository.validation.RepositoryValidator;
import org.apache.archiva.repository.validation.ValidationResponse;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Collection; import javax.annotation.PostConstruct;
import javax.inject.Named;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;
/** /**
* Handler implementation for managed repositories. * Handler implementation for managed repositories.
* *
* @author Martin Stockhammer <martin_s@apache.org> * @author Martin Stockhammer <martin_s@apache.org>
*/ */
@Service( "managedRepositoryHandler#default" )
public class ManagedRepositoryHandler public class ManagedRepositoryHandler
extends AbstractRepositoryHandler<ManagedRepository, ManagedRepositoryConfiguration> extends AbstractRepositoryHandler<ManagedRepository, ManagedRepositoryConfiguration>
implements RepositoryHandler<ManagedRepository, ManagedRepositoryConfiguration> implements RepositoryHandler<ManagedRepository, ManagedRepositoryConfiguration>
{ {
private static final Logger log = LoggerFactory.getLogger( ManagedRepositoryHandler.class ); private static final Logger log = LoggerFactory.getLogger( ManagedRepositoryHandler.class );
private final ConfigurationHandler configurationHandler; private final RepositoryHandlerManager repositoryRegistry;
private final ArchivaRepositoryRegistry repositoryRegistry; private final RepositoryContentFactory repositoryContentFactory;
private final RepositoryValidator<ManagedRepository> validator;
private Map<String, ManagedRepository> managedRepositories = new HashMap<>( );
private Map<String, ManagedRepository> uManagedRepositories = Collections.unmodifiableMap( managedRepositories );
public ManagedRepositoryHandler( ArchivaRepositoryRegistry repositoryRegistry, IndexManagerFactory indexManagerFactory;
ConfigurationHandler configurationHandler,
List<RepositoryValidator<? extends Repository>> repositoryValidatorList )
public ManagedRepositoryHandler( RepositoryHandlerManager repositoryRegistry,
ConfigurationHandler configurationHandler, IndexManagerFactory indexManagerFactory,
@Named( "repositoryContentFactory#default" )
RepositoryContentFactory repositoryContentFactory
)
{ {
this.configurationHandler = configurationHandler; super( ManagedRepository.class, ManagedRepositoryConfiguration.class, configurationHandler );
this.repositoryRegistry = repositoryRegistry; this.repositoryRegistry = repositoryRegistry;
this.validator = getCombinedValidatdor( ManagedRepository.class, repositoryValidatorList ); this.indexManagerFactory = indexManagerFactory;
this.repositoryContentFactory = repositoryContentFactory;
}
@Override
@PostConstruct
public void init( )
{
log.debug( "Initializing managed repository handler " + repositoryRegistry.toString( ) );
initializeStorage( );
// We are registering this class on the registry. This is necessary to avoid circular dependencies via injection.
this.repositoryRegistry.registerHandler( this );
}
private void initializeStorage( )
{
} }
@Override @Override
public void initializeFromConfig( ) public void initializeFromConfig( )
{ {
this.managedRepositories.clear( ); Map<String, ManagedRepository> currentInstances = new HashMap<>( getRepositories( ) );
this.managedRepositories.putAll( newInstancesFromConfig( ) ); getRepositories().clear();
for ( ManagedRepository managedRepository : this.managedRepositories.values( ) ) getRepositories( ).putAll( newOrUpdateInstancesFromConfig( currentInstances ) );
for ( ManagedRepository managedRepository : getRepositories( ).values( ) )
{ {
activateRepository( managedRepository ); activateRepository( managedRepository );
} }
for (ManagedRepository managedRepository : currentInstances.values()) {
deactivateRepository( managedRepository );
} }
@Override
public void activateRepository( ManagedRepository repository )
{
} }
@Override @Override
@ -93,148 +121,437 @@ implements RepositoryHandler<ManagedRepository, ManagedRepositoryConfiguration>
{ {
try try
{ {
Set<String> configRepoIds = new HashSet<>( );
List<ManagedRepositoryConfiguration> managedRepoConfigs = List<ManagedRepositoryConfiguration> managedRepoConfigs =
configurationHandler.getBaseConfiguration( ).getManagedRepositories( ); new ArrayList<>(
getConfigurationHandler( ).getBaseConfiguration( ).getManagedRepositories( ) );
if ( managedRepoConfigs == null ) if ( managedRepoConfigs == null )
{ {
return managedRepositories; return Collections.emptyMap( );
} }
Map<String, ManagedRepository> result = new HashMap<>( );
for ( ManagedRepositoryConfiguration repoConfig : managedRepoConfigs ) for ( ManagedRepositoryConfiguration repoConfig : managedRepoConfigs )
{ {
ManagedRepository repo = put( repoConfig, null ); ManagedRepository repo = newInstance( repoConfig );
configRepoIds.add( repoConfig.getId( ) ); result.put( repo.getId( ), repo );
if ( repo.supportsFeature( StagingRepositoryFeature.class ) ) if ( repo.supportsFeature( StagingRepositoryFeature.class ) )
{ {
StagingRepositoryFeature stagF = repo.getFeature( StagingRepositoryFeature.class ).get( ); StagingRepositoryFeature stagF = repo.getFeature( StagingRepositoryFeature.class ).get( );
if ( stagF.getStagingRepository( ) != null ) if ( stagF.getStagingRepository( ) != null )
{ {
configRepoIds.add( stagF.getStagingRepository( ).getId( ) ); ManagedRepository stagingRepo = getStagingRepository( repo );
} if ( stagingRepo != null )
}
}
List<String> toRemove = managedRepositories.keySet( ).stream( ).filter( id -> !configRepoIds.contains( id ) ).collect( Collectors.toList( ) );
for ( String id : toRemove )
{ {
ManagedRepository removed = managedRepositories.remove( id ); result.put( stagingRepo.getId( ), stagingRepo );
removed.close( );
} }
} }
}
}
return result;
}
catch ( Throwable e ) catch ( Throwable e )
{ {
log.error( "Could not initialize repositories from config: {}", e.getMessage( ), e ); log.error( "Could not initialize repositories from config: {}", e.getMessage( ), e );
return managedRepositories; return new HashMap<>( );
} }
return managedRepositories;
} }
public Map<String, ManagedRepository> newOrUpdateInstancesFromConfig( Map<String, ManagedRepository> currentInstances)
{
try
{
List<ManagedRepositoryConfiguration> managedRepoConfigs =
new ArrayList<>(
getConfigurationHandler( ).getBaseConfiguration( ).getManagedRepositories( ) );
if ( managedRepoConfigs == null )
{
return Collections.emptyMap( );
}
Map<String, ManagedRepository> result = new HashMap<>( );
for ( ManagedRepositoryConfiguration repoConfig : managedRepoConfigs )
{
String id = repoConfig.getId( );
ManagedRepository repo;
if ( currentInstances.containsKey( id ) )
{
repo = currentInstances.remove( id );
getProvider( repo.getType() ).updateManagedInstance( (EditableManagedRepository) repo, repoConfig );
updateReferences( repo, repoConfig );
}
else
{
repo = newInstance( repoConfig );
}
result.put( id, repo );
if ( repo.supportsFeature( StagingRepositoryFeature.class ) )
{
StagingRepositoryFeature stagF = repo.getFeature( StagingRepositoryFeature.class ).get( );
if ( stagF.getStagingRepository( ) != null )
{
String stagingId = getStagingId( id );
ManagedRepository stagingRepo;
if ( currentInstances.containsKey( stagingId ) )
{
stagingRepo = currentInstances.remove( stagingId );
managedRepoConfigs.stream( ).filter( cfg -> stagingId.equals( cfg.getId( ) ) ).findFirst( ).ifPresent(
stagingRepoConfig ->
{
try
{
getProvider( stagingRepo.getType() ).updateManagedInstance( (EditableManagedRepository) stagingRepo, stagingRepoConfig );
updateReferences( stagingRepo, stagingRepoConfig );
}
catch ( RepositoryException e )
{
log.error( "Could not update staging repo {}: {}", stagingId, e.getMessage( ) );
}
}
);
}
else
{
stagingRepo = getStagingRepository( repo );
}
if ( stagingRepo != null )
{
result.put( stagingRepo.getId( ), stagingRepo );
}
}
}
}
return result;
}
catch ( Throwable e )
{
log.error( "Could not initialize repositories from config: {}", e.getMessage( ), e );
return new HashMap<>( );
}
}
@Override @Override
public ManagedRepository newInstance( RepositoryType type, String id ) throws RepositoryException public ManagedRepository newInstance( RepositoryType type, String id ) throws RepositoryException
{ {
return null; log.debug( "Creating repo {}", id );
RepositoryProvider provider = getProvider( type );
EditableManagedRepository repo;
try
{
repo = provider.createManagedInstance( id, id );
} }
catch ( IOException e )
{
throw new RepositoryException( "Could not create repository '" + id + "': " + e.getMessage( ) );
}
repo.registerEventHandler( RepositoryEvent.ANY, repositoryRegistry );
updateReferences( repo, null );
repo.setLastState( RepositoryState.REFERENCES_SET );
return repo;
}
private String getStagingId( String repoId )
{
return repoId + StagingRepositoryFeature.STAGING_REPO_POSTFIX;
}
private ManagedRepository getStagingRepository( ManagedRepository baseRepo ) throws RepositoryException
{
ManagedRepository stageRepo = get( getStagingId( baseRepo.getId( ) ) );
final RepositoryType type = baseRepo.getType( );
if ( stageRepo == null )
{
RepositoryProvider provider = getProvider( type );
ManagedRepositoryConfiguration cfg = provider.getManagedConfiguration( baseRepo );
stageRepo = provider.createStagingInstance( cfg );
if ( stageRepo.supportsFeature( StagingRepositoryFeature.class ) )
{
stageRepo.getFeature( StagingRepositoryFeature.class ).get( ).setStageRepoNeeded( false );
}
updateReferences( stageRepo, cfg );
}
return stageRepo;
}
public ArchivaIndexManager getIndexManager( RepositoryType type )
{
return indexManagerFactory.getIndexManager( type );
}
private void createIndexingContext( EditableRepository editableRepo ) throws RepositoryException
{
if ( editableRepo.supportsFeature( IndexCreationFeature.class ) )
{
ArchivaIndexManager idxManager = getIndexManager( editableRepo.getType( ) );
try
{
editableRepo.setIndexingContext( idxManager.createContext( editableRepo ) );
idxManager.updateLocalIndexPath( editableRepo );
}
catch ( IndexCreationFailedException e )
{
throw new RepositoryException( "Could not create index for repository " + editableRepo.getId( ) + ": " + e.getMessage( ), e );
}
}
}
@Override @Override
public ManagedRepository newInstance( ManagedRepositoryConfiguration repositoryConfiguration ) throws RepositoryException public ManagedRepository newInstance( ManagedRepositoryConfiguration repositoryConfiguration ) throws RepositoryException
{ {
return null; RepositoryType type = RepositoryType.valueOf( repositoryConfiguration.getType( ) );
RepositoryProvider provider = getProvider( type );
if ( provider == null )
{
throw new RepositoryException( "Provider not found for repository type: " + repositoryConfiguration.getType( ) );
}
final ManagedRepository repo = provider.createManagedInstance( repositoryConfiguration );
repo.registerEventHandler( RepositoryEvent.ANY, repositoryRegistry );
updateReferences( repo, null );
if ( repo instanceof EditableRepository )
{
( (EditableRepository) repo ).setLastState( RepositoryState.REFERENCES_SET );
}
return repo;
} }
@Override @Override
public ManagedRepository put( ManagedRepository repository ) throws RepositoryException protected ManagedRepositoryConfiguration findRepositoryConfiguration( final Configuration configuration, final String id )
{ {
return null; return configuration.findManagedRepositoryById( id );
} }
@Override @Override
public ManagedRepository put( ManagedRepositoryConfiguration repositoryConfiguration ) throws RepositoryException protected void removeRepositoryConfiguration( final Configuration configuration, final ManagedRepositoryConfiguration repoConfiguration )
{ {
return null; configuration.removeManagedRepository( repoConfiguration );
}
@Override
protected void addRepositoryConfiguration( Configuration configuration, ManagedRepositoryConfiguration repoConfiguration )
{
configuration.addManagedRepository( repoConfiguration );
}
@Override
public ManagedRepository put( ManagedRepository managedRepository ) throws RepositoryException
{
final String id = managedRepository.getId( );
ManagedRepository originRepo = getRepositories( ).remove( id );
if ( originRepo == null && repositoryRegistry.isRegisteredId( id ) )
{
throw new RepositoryException( "There exists a repository with id " + id + ". Could not update with managed repository." );
}
try
{
if ( originRepo != null && managedRepository != originRepo )
{
deactivateRepository( originRepo );
pushEvent( LifecycleEvent.UNREGISTERED, originRepo );
}
RepositoryProvider provider = getProvider( managedRepository.getType( ) );
ManagedRepositoryConfiguration newCfg = provider.getManagedConfiguration( managedRepository );
getConfigurationHandler( ).getLock( ).writeLock( ).lock( );
try
{
Configuration configuration = getConfigurationHandler( ).getBaseConfiguration( );
updateReferences( managedRepository, newCfg );
ManagedRepositoryConfiguration oldCfg = configuration.findManagedRepositoryById( id );
if ( oldCfg != null )
{
configuration.removeManagedRepository( oldCfg );
}
configuration.addManagedRepository( newCfg );
getConfigurationHandler( ).save( configuration, ConfigurationHandler.REGISTRY_EVENT_TAG );
setLastState( managedRepository, RepositoryState.SAVED );
activateRepository( managedRepository );
}
finally
{
getConfigurationHandler( ).getLock( ).writeLock( ).unlock( );
}
getRepositories( ).put( id, managedRepository );
setLastState( managedRepository, RepositoryState.REGISTERED );
return managedRepository;
}
catch ( Exception e )
{
// Rollback only partly, because repository is closed already
if ( originRepo != null )
{
getRepositories( ).put( id, originRepo );
}
else
{
getRepositories( ).remove( id );
}
log.error( "Exception during configuration update {}", e.getMessage( ), e );
throw new RepositoryException( "Could not save the configuration" + ( e.getMessage( ) == null ? "" : ": " + e.getMessage( ) ) );
}
}
@Override
public ManagedRepository put( ManagedRepositoryConfiguration managedRepositoryConfiguration ) throws RepositoryException
{
final String id = managedRepositoryConfiguration.getId( );
final RepositoryType repositoryType = RepositoryType.valueOf( managedRepositoryConfiguration.getType( ) );
final RepositoryProvider provider = getProvider( repositoryType );
ReentrantReadWriteLock.WriteLock configLock = this.getConfigurationHandler( ).getLock( ).writeLock( );
configLock.lock( );
ManagedRepository repo = null;
ManagedRepository oldRepository = null;
Configuration configuration = null;
try
{
boolean updated = false;
configuration = getConfigurationHandler( ).getBaseConfiguration( );
repo = getRepositories( ).get( id );
oldRepository = repo == null ? null : clone( repo, id );
if ( repo == null )
{
repo = put( managedRepositoryConfiguration, configuration );
}
else
{
setManagedRepositoryDefaults( managedRepositoryConfiguration );
provider.updateManagedInstance( (EditableManagedRepository) repo, managedRepositoryConfiguration );
updated = true;
pushEvent( LifecycleEvent.UPDATED, repo );
}
registerNewRepository( managedRepositoryConfiguration, repo, configuration, updated );
}
catch ( IndeterminateConfigurationException | RegistryException e )
{
if ( oldRepository != null )
{
ManagedRepositoryConfiguration oldCfg = provider.getManagedConfiguration( oldRepository );
provider.updateManagedInstance( (EditableManagedRepository) repo, oldCfg );
rollback( configuration, oldRepository, e, oldCfg );
}
else
{
getRepositories( ).remove( id );
}
log.error( "Could not save the configuration for repository {}: {}", id, e.getMessage( ), e );
throw new RepositoryException( "Could not save the configuration for repository " + id + ": " + e.getMessage( ) );
}
finally
{
configLock.unlock( );
}
return repo;
} }
@Override @Override
public ManagedRepository put( ManagedRepositoryConfiguration repositoryConfiguration, Configuration configuration ) throws RepositoryException public ManagedRepository put( ManagedRepositoryConfiguration repositoryConfiguration, Configuration configuration ) throws RepositoryException
{ {
return null; final String id = repositoryConfiguration.getId( );
final RepositoryType repoType = RepositoryType.valueOf( repositoryConfiguration.getType( ) );
ManagedRepository repo;
setManagedRepositoryDefaults( repositoryConfiguration );
if ( getRepositories( ).containsKey( id ) )
{
repo = clone( getRepositories( ).get( id ), id );
if ( repo instanceof EditableManagedRepository )
{
getProvider( repoType ).updateManagedInstance( (EditableManagedRepository) repo, repositoryConfiguration );
}
else
{
throw new RepositoryException( "The repository is not editable " + id );
}
}
else
{
repo = getProvider( repoType ).createManagedInstance( repositoryConfiguration );
setLastState( repo, RepositoryState.CREATED );
}
if ( configuration != null )
{
replaceOrAddRepositoryConfig( repositoryConfiguration, configuration );
}
updateReferences( repo, repositoryConfiguration );
setLastState( repo, RepositoryState.REFERENCES_SET );
return repo;
}
@SuppressWarnings( "unused" )
private void setManagedRepositoryDefaults( ManagedRepositoryConfiguration repositoryConfiguration )
{
// We do nothing here
} }
@Override @Override
public <D> CheckedResult<ManagedRepository, D> putWithCheck( ManagedRepositoryConfiguration repositoryConfiguration, RepositoryChecker<ManagedRepository, D> checker ) throws RepositoryException public ManagedRepository clone( ManagedRepository repo, String id ) throws RepositoryException
{ {
return null; RepositoryProvider provider = getProvider( repo.getType( ) );
ManagedRepositoryConfiguration cfg = provider.getManagedConfiguration( repo );
cfg.setId( id );
ManagedRepository cloned = provider.createManagedInstance( cfg );
cloned.registerEventHandler( RepositoryEvent.ANY, repositoryRegistry );
setLastState( cloned, RepositoryState.CREATED );
return cloned;
} }
@Override
public void remove( String id ) throws RepositoryException
{
}
@Override
public void remove( String id, Configuration configuration ) throws RepositoryException
{
}
@Override
public ManagedRepository get( String id )
{
return null;
}
@Override
public ManagedRepository clone( ManagedRepository repo ) throws RepositoryException
{
return null;
}
@Override @Override
public void updateReferences( ManagedRepository repo, ManagedRepositoryConfiguration repositoryConfiguration ) throws RepositoryException public void updateReferences( ManagedRepository repo, ManagedRepositoryConfiguration repositoryConfiguration ) throws RepositoryException
{ {
log.debug( "Updating references of repo {}", repo.getId( ) );
} if ( repo.supportsFeature( StagingRepositoryFeature.class ) )
@Override
public Collection<ManagedRepository> getAll( )
{ {
return null; Configuration configuration = getConfigurationHandler( ).getBaseConfiguration( );
} RepositoryProvider provider = getProvider( repo.getType( ) );
StagingRepositoryFeature feature = repo.getFeature( StagingRepositoryFeature.class ).get( );
@Override if ( feature.isStageRepoNeeded( ) && feature.getStagingRepository( ) == null )
public RepositoryValidator<ManagedRepository> getValidator( )
{ {
return null; ManagedRepository stageRepo = get( getStagingId( repo.getId( ) ) );
} if ( stageRepo == null )
@Override
public ValidationResponse<ManagedRepository> validateRepository( ManagedRepository repository )
{ {
return null; stageRepo = getStagingRepository( repo );
} getRepositories( ).put( stageRepo.getId( ), stageRepo );
if ( configuration != null )
@Override
public ValidationResponse<ManagedRepository> validateRepositoryForUpdate( ManagedRepository repository )
{ {
return null; replaceOrAddRepositoryConfig( provider.getManagedConfiguration( stageRepo ), configuration );
} }
pushEvent( new LifecycleEvent( LifecycleEvent.REGISTERED, this, stageRepo ) );
@Override
public boolean hasRepository( String id )
{
return false;
} }
feature.setStagingRepository( stageRepo );
@Override }
public void init( ) }
if ( repo instanceof EditableManagedRepository )
{ {
EditableManagedRepository editableRepo = (EditableManagedRepository) repo;
if ( repo.getContent( ) == null )
{
editableRepo.setContent( repositoryContentFactory.getManagedRepositoryContent( repo ) );
editableRepo.getContent( ).setRepository( editableRepo );
}
log.debug( "Index repo: " + repo.hasIndex( ) );
if ( repo.hasIndex( ) && ( repo.getIndexingContext( ) == null || !repo.getIndexingContext( ).isOpen( ) ) )
{
log.debug( "Creating indexing context for {}", repo.getId( ) );
createIndexingContext( editableRepo );
}
}
repo.registerEventHandler( RepositoryEvent.ANY, repositoryRegistry );
} }
@Override @Override
public void close( ) public void close( )
{ {
getRepositories( ).values( ).stream( ).forEach(
r -> deactivateRepository( r )
);
}
@Override
public void deactivateRepository( ManagedRepository repository )
{
repository.close( );
} }
} }

View File

@ -32,6 +32,7 @@ import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.RepositoryType; import org.apache.archiva.repository.RepositoryType;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.BasicManagedRepository; import org.apache.archiva.repository.base.managed.BasicManagedRepository;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.repository.base.remote.BasicRemoteRepository; import org.apache.archiva.repository.base.remote.BasicRemoteRepository;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
@ -51,6 +52,7 @@ import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@ -73,6 +75,9 @@ public class ArchivaRepositoryRegistryTest
@Inject @Inject
RepositoryGroupHandler repositoryGroupHandler; RepositoryGroupHandler repositoryGroupHandler;
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
private static final Path userCfg = Paths.get(System.getProperty( "user.home" ), ".m2/archiva.xml"); private static final Path userCfg = Paths.get(System.getProperty( "user.home" ), ".m2/archiva.xml");
private static Path cfgCopy; private static Path cfgCopy;
@ -269,30 +274,31 @@ public class ArchivaRepositoryRegistryTest
public void putManagedRepositoryFromConfigWithoutSave( ) throws Exception public void putManagedRepositoryFromConfigWithoutSave( ) throws Exception
{ {
Configuration configuration = archivaConfiguration.getConfiguration(); Configuration configuration = archivaConfiguration.getConfiguration();
int actualSize = configuration.getManagedRepositories( ).size( );
Configuration newConfiguration = new Configuration( );
ManagedRepositoryConfiguration cfg = new ManagedRepositoryConfiguration(); ManagedRepositoryConfiguration cfg = new ManagedRepositoryConfiguration();
cfg.setId("test002"); cfg.setId("test002");
cfg.setName("This is test 002"); cfg.setName("This is test 002");
ManagedRepository repo = repositoryRegistry.putRepository( cfg, configuration ); ManagedRepository repo = repositoryRegistry.putRepository( cfg, newConfiguration );
assertNotNull(repo); assertNotNull(repo);
assertEquals("test002", repo.getId()); assertEquals("test002", repo.getId());
assertEquals("This is test 002", repo.getName()); assertEquals("This is test 002", repo.getName());
assertNotNull(repo.getContent()); assertNotNull(repo.getContent());
archivaConfiguration.reload(); archivaConfiguration.reload();
assertEquals(3, archivaConfiguration.getConfiguration().getManagedRepositories().size()); assertEquals(actualSize, configuration.getManagedRepositories().size());
Collection<ManagedRepository> repos = repositoryRegistry.getManagedRepositories(); List<ManagedRepositoryConfiguration> repos = newConfiguration.getManagedRepositories( );
assertEquals(5, repos.size()); assertEquals(1, repos.size());
ManagedRepository internalRepo = repositoryRegistry.getManagedRepository( "internal" ); ManagedRepository internalRepo = repositoryRegistry.getManagedRepository( "internal" );
cfg = new ManagedRepositoryConfiguration(); cfg = new ManagedRepositoryConfiguration();
cfg.setId("internal"); cfg.setId("internal");
cfg.setName("This is internal test 002"); cfg.setName("This is internal test 002");
repo = repositoryRegistry.putRepository( cfg, configuration ); repo = repositoryRegistry.putRepository( cfg, newConfiguration );
assertSame( internalRepo, repo );
assertEquals("This is internal test 002",repo.getName()); assertEquals("This is internal test 002",repo.getName());
assertEquals(5, repositoryRegistry.getManagedRepositories().size()); assertEquals(2, newConfiguration.getManagedRepositories().size());
repositoryRegistry.reload(); repositoryRegistry.reload();
assertEquals(4, repositoryRegistry.getManagedRepositories().size()); assertEquals(actualSize, configuration.getManagedRepositories().size());
} }
@Test @Test

View File

@ -18,8 +18,6 @@ package org.apache.archiva.repository.base.group;
* under the License. * under the License.
*/ */
import org.apache.archiva.common.filelock.DefaultFileLockManager;
import org.apache.archiva.common.filelock.FileLockManager;
import org.apache.archiva.repository.EditableManagedRepository; import org.apache.archiva.repository.EditableManagedRepository;
import org.apache.archiva.repository.EditableRepositoryGroup; import org.apache.archiva.repository.EditableRepositoryGroup;
import org.apache.archiva.repository.ManagedRepository; import org.apache.archiva.repository.ManagedRepository;
@ -28,9 +26,8 @@ import org.apache.archiva.repository.RepositoryGroup;
import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.ConfigurationHandler; import org.apache.archiva.repository.base.ConfigurationHandler;
import org.apache.archiva.repository.base.managed.BasicManagedRepository; import org.apache.archiva.repository.base.managed.BasicManagedRepository;
import org.apache.archiva.repository.base.managed.BasicManagedRepositoryValidator; import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.repository.mock.ManagedRepositoryContentMock; import org.apache.archiva.repository.mock.ManagedRepositoryContentMock;
import org.apache.archiva.repository.storage.fs.FilesystemStorage;
import org.apache.archiva.repository.validation.ValidationResponse; import org.apache.archiva.repository.validation.ValidationResponse;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -64,6 +61,9 @@ class BasicRepositoryGroupValidatorTest
@Inject @Inject
RepositoryGroupHandler repositoryGroupHandler; RepositoryGroupHandler repositoryGroupHandler;
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
Path repoBaseDir; Path repoBaseDir;
@AfterEach @AfterEach

View File

@ -21,29 +21,29 @@ package org.apache.archiva.repository.base.group;
import org.apache.archiva.common.filelock.DefaultFileLockManager; import org.apache.archiva.common.filelock.DefaultFileLockManager;
import org.apache.archiva.common.filelock.FileLockManager; import org.apache.archiva.common.filelock.FileLockManager;
import org.apache.archiva.common.utils.FileUtils; import org.apache.archiva.common.utils.FileUtils;
import org.apache.archiva.common.utils.PathUtil;
import org.apache.archiva.components.registry.RegistryException;
import org.apache.archiva.configuration.ArchivaConfiguration; import org.apache.archiva.configuration.ArchivaConfiguration;
import org.apache.archiva.configuration.Configuration; import org.apache.archiva.configuration.Configuration;
import org.apache.archiva.configuration.IndeterminateConfigurationException; import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
import org.apache.archiva.configuration.RepositoryGroupConfiguration; import org.apache.archiva.configuration.RepositoryGroupConfiguration;
import org.apache.archiva.indexer.merger.MergedRemoteIndexesScheduler; import org.apache.archiva.indexer.merger.MergedRemoteIndexesScheduler;
import org.apache.archiva.repository.EditableRepositoryGroup; import org.apache.archiva.repository.EditableRepositoryGroup;
import org.apache.archiva.repository.Repository; import org.apache.archiva.repository.ManagedRepository;
import org.apache.archiva.repository.RepositoryException; import org.apache.archiva.repository.RepositoryException;
import org.apache.archiva.repository.RepositoryGroup; import org.apache.archiva.repository.RepositoryGroup;
import org.apache.archiva.repository.RepositoryHandler;
import org.apache.archiva.repository.RepositoryState; import org.apache.archiva.repository.RepositoryState;
import org.apache.archiva.repository.RepositoryType; import org.apache.archiva.repository.RepositoryType;
import org.apache.archiva.repository.base.ArchivaRepositoryRegistry; import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
import org.apache.archiva.repository.base.ConfigurationHandler; import org.apache.archiva.repository.base.ConfigurationHandler;
import org.apache.archiva.repository.base.managed.BasicManagedRepository;
import org.apache.archiva.repository.storage.fs.FilesystemStorage; import org.apache.archiva.repository.storage.fs.FilesystemStorage;
import org.apache.archiva.repository.validation.CheckedResult; import org.apache.archiva.repository.validation.CheckedResult;
import org.apache.archiva.repository.validation.RepositoryValidator;
import org.apache.archiva.repository.validation.ValidationError; import org.apache.archiva.repository.validation.ValidationError;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.junit.jupiter.SpringExtension;
@ -87,8 +87,8 @@ class RepositoryGroupHandlerTest
// @Named( "mergedRemoteIndexesScheduler#default" ) // @Named( "mergedRemoteIndexesScheduler#default" )
MergedRemoteIndexesScheduler mergedRemoteIndexesScheduler; MergedRemoteIndexesScheduler mergedRemoteIndexesScheduler;
@Inject @Mock
List<RepositoryValidator<? extends Repository>> repositoryValidatorList; RepositoryHandler<ManagedRepository, ManagedRepositoryConfiguration> managedRepositoryHandler;
@Inject @Inject
ArchivaConfiguration archivaConfiguration; ArchivaConfiguration archivaConfiguration;
@ -142,7 +142,19 @@ class RepositoryGroupHandlerTest
private RepositoryGroupHandler createHandler( ) private RepositoryGroupHandler createHandler( )
{ {
RepositoryGroupHandler groupHandler = new RepositoryGroupHandler( repositoryRegistry, configurationHandler, mergedRemoteIndexesScheduler, repositoryValidatorList ); Mockito.when( managedRepositoryHandler.getVariant( ) ).thenReturn( ManagedRepository.class );
final ManagedRepository internalRepo;
try
{
internalRepo = getManaged( "internal", "internal");
}
catch ( IOException e )
{
throw new Error( e );
}
Mockito.when( managedRepositoryHandler.get( ArgumentMatchers.eq("internal") ) ).thenReturn( internalRepo );
repositoryRegistry.registerHandler( managedRepositoryHandler );
RepositoryGroupHandler groupHandler = new RepositoryGroupHandler( repositoryRegistry, configurationHandler, mergedRemoteIndexesScheduler);
groupHandler.init( ); groupHandler.init( );
return groupHandler; return groupHandler;
} }
@ -156,6 +168,13 @@ class RepositoryGroupHandlerTest
return repoBaseDir; return repoBaseDir;
} }
protected ManagedRepository getManaged(String id, String name) throws IOException
{
Path path = getRepoBaseDir().resolve( "../managed" );
FileLockManager lockManager = new DefaultFileLockManager();
FilesystemStorage storage = new FilesystemStorage(path.toAbsolutePath(), lockManager);
return new BasicManagedRepository( id, name, storage );
}
protected EditableRepositoryGroup createRepository( String id, String name, Path location ) throws IOException protected EditableRepositoryGroup createRepository( String id, String name, Path location ) throws IOException
@ -200,9 +219,8 @@ class RepositoryGroupHandlerTest
@Test @Test
void newInstancesFromConfig( ) void newInstancesFromConfig( )
{ {
RepositoryGroupHandler groupHandler = new RepositoryGroupHandler( repositoryRegistry, configurationHandler, mergedRemoteIndexesScheduler, repositoryValidatorList ); RepositoryGroupHandler groupHandler = createHandler( );
Map<String, RepositoryGroup> instances = groupHandler.newInstancesFromConfig( ); Map<String, RepositoryGroup> instances = groupHandler.newInstancesFromConfig( );
assertFalse( groupHandler.hasRepository( "test-group-01" ) );
assertTrue( instances.containsKey( "test-group-01" ) ); assertTrue( instances.containsKey( "test-group-01" ) );
assertEquals( RepositoryState.REFERENCES_SET, instances.get( "test-group-01" ).getLastState( ) ); assertEquals( RepositoryState.REFERENCES_SET, instances.get( "test-group-01" ).getLastState( ) );
} }

View File

@ -0,0 +1,427 @@
package org.apache.archiva.repository.base.managed;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.common.filelock.DefaultFileLockManager;
import org.apache.archiva.common.filelock.FileLockManager;
import org.apache.archiva.common.utils.FileUtils;
import org.apache.archiva.configuration.ArchivaConfiguration;
import org.apache.archiva.configuration.Configuration;
import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
import org.apache.archiva.indexer.IndexManagerFactory;
import org.apache.archiva.indexer.merger.MergedRemoteIndexesScheduler;
import org.apache.archiva.repository.EditableManagedRepository;
import org.apache.archiva.repository.ManagedRepository;
import org.apache.archiva.repository.Repository;
import org.apache.archiva.repository.RepositoryContentFactory;
import org.apache.archiva.repository.RepositoryException;
import org.apache.archiva.repository.RepositoryState;
import org.apache.archiva.repository.RepositoryType;
import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
import org.apache.archiva.repository.base.ConfigurationHandler;
import org.apache.archiva.repository.storage.fs.FilesystemStorage;
import org.apache.archiva.repository.validation.CheckedResult;
import org.apache.archiva.repository.validation.RepositoryValidator;
import org.apache.archiva.repository.validation.ValidationError;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static org.apache.archiva.repository.validation.ErrorKeys.ISEMPTY;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author Martin Stockhammer <martin_s@apache.org>
*/
@ExtendWith( {MockitoExtension.class, SpringExtension.class} )
@ContextConfiguration( locations = {"classpath*:/META-INF/spring-context.xml", "classpath:/spring-context-managed.xml"} )
class ManagedRepositoryHandlerTest
{
static {
initialize();
}
@Inject
@Named( "repositoryRegistry" )
ArchivaRepositoryRegistry repositoryRegistry;
@Inject
@Named( "repositoryContentFactory#default" )
RepositoryContentFactory repositoryContentFactory;
@Inject
IndexManagerFactory indexManagerFactory;
@Inject
ConfigurationHandler configurationHandler;
@Inject
List<RepositoryValidator<? extends Repository>> repositoryValidatorList;
@Inject
ArchivaConfiguration archivaConfiguration;
Path repoBaseDir;
private static void initialize() {
Path baseDir = Paths.get( FileUtils.getBasedir( ) );
Path config = baseDir.resolve( "src/test/resources/archiva-managed.xml" );
if ( Files.exists( config ) )
{
Path destConfig = baseDir.resolve( "target/test-classes/archiva-managed.xml" );
try
{
Files.copy( config, destConfig );
}
catch ( IOException e )
{
System.err.println( "Could not copy file: " + e.getMessage( ) );
}
}
}
// Helper method that removes a repo from the configuration
private void removeRepositoryFromConfig( String id) {
Configuration configuration = configurationHandler.getBaseConfiguration( );
Iterator<ManagedRepositoryConfiguration> iter = configuration.getManagedRepositories().iterator();
while(iter.hasNext()) {
ManagedRepositoryConfiguration repo = iter.next( );
if (id.equals(repo.getId())) {
iter.remove();
break;
}
}
try
{
configurationHandler.save( configuration );
}
catch ( Throwable e )
{
System.err.println( "Could not remove repo from config "+id );
}
}
private boolean hasRepositoryInConfig( String id) {
assertNotNull( configurationHandler.getBaseConfiguration( ).getManagedRepositories() );
return configurationHandler.getBaseConfiguration( ).getManagedRepositories( ).stream( ).anyMatch( g -> g != null && id.equals( g.getId( ) ) ) ;
}
private ManagedRepositoryHandler createHandler( )
{
ManagedRepositoryHandler repositoryHandler = new ManagedRepositoryHandler( repositoryRegistry, configurationHandler, indexManagerFactory, repositoryContentFactory );
repositoryHandler.init( );
return repositoryHandler;
}
private Path getRepoBaseDir() throws IOException
{
if (repoBaseDir==null) {
this.repoBaseDir = archivaConfiguration.getRepositoryBaseDir( ).resolve( "managed" );
Files.createDirectories( this.repoBaseDir );
}
return repoBaseDir;
}
protected EditableManagedRepository createRepository( String id, String name, Path location ) throws IOException
{
FileLockManager lockManager = new DefaultFileLockManager();
FilesystemStorage storage = new FilesystemStorage(location.toAbsolutePath(), lockManager);
BasicManagedRepository repo = new BasicManagedRepository(id, name, storage);
repo.setLocation( location.toAbsolutePath().toUri());
return repo;
}
protected EditableManagedRepository createRepository( String id, String name) throws IOException
{
Path dir = getRepoBaseDir( ).resolve( id );
Files.createDirectories( dir );
return createRepository( id, name, dir );
}
@Test
void initializeFromConfig( )
{
ManagedRepositoryHandler repoHandler = createHandler( );
repoHandler.initializeFromConfig( );
assertEquals( 5, repoHandler.getAll( ).size( ) );
assertNotNull( repoHandler.get( "test-repo-01" ) );
assertEquals( "n-test-repo-01", repoHandler.get( "test-repo-01" ).getName() );
}
@Test
void activateRepository( ) throws RepositoryException
{
String id = "test-repo-02";
ManagedRepositoryHandler repoHandler = createHandler( );
ManagedRepository repo = repoHandler.newInstance( RepositoryType.MAVEN, id );
repoHandler.activateRepository( repo );
assertFalse( hasRepositoryInConfig( id ));
assertNull( repoHandler.get( id ) );
}
@Test
void newInstancesFromConfig( ) throws RepositoryException
{
final String id = "test-repo-01";
ManagedRepositoryHandler repoHandler = createHandler( );
Configuration configuration = new Configuration( );
repoHandler.remove( "test-repo-01", configuration );
Map<String, ManagedRepository> instances = repoHandler.newInstancesFromConfig( );
assertFalse( repoHandler.hasRepository( id ) );
assertTrue( instances.containsKey( id ) );
assertEquals( RepositoryState.REFERENCES_SET, instances.get( id ).getLastState( ) );
}
@Test
void newInstance( ) throws RepositoryException
{
String id = "test-repo-03";
ManagedRepositoryHandler repoHandler = createHandler( );
ManagedRepository instance = repoHandler.newInstance( RepositoryType.MAVEN, id );
assertNotNull( instance );
assertEquals( id, instance.getId( ) );
assertFalse( repoHandler.hasRepository( id ) );
assertEquals( RepositoryState.REFERENCES_SET, instance.getLastState( ) );
assertFalse( hasRepositoryInConfig( id ) );
}
@Test
void put( ) throws IOException, RepositoryException
{
final String id = "test-repo-04";
try
{
ManagedRepositoryHandler repoHandler = createHandler( );
EditableManagedRepository repository = createRepository( id, "n-"+id );
repoHandler.put( repository );
ManagedRepository storedRepository = repoHandler.get( id );
assertNotNull( storedRepository );
assertEquals( id, storedRepository.getId( ) );
assertEquals( "n-"+id, storedRepository.getName( ) );
EditableManagedRepository repository2 = createRepository( id, "n2-"+id );
repoHandler.put( repository2 );
storedRepository = repoHandler.get( id );
assertNotNull( storedRepository );
assertEquals( id, storedRepository.getId( ) );
assertEquals( "n2-"+id, storedRepository.getName( ) );
assertTrue( hasRepositoryInConfig( id ));
} finally {
removeRepositoryFromConfig( id );
}
}
@Test
void putWithConfiguration( ) throws RepositoryException
{
String id = "test-repo-05";
try
{
ManagedRepositoryHandler repoHandler = createHandler( );
ManagedRepositoryConfiguration configuration = new ManagedRepositoryConfiguration( );
configuration.setId( id );
configuration.setName( "n-" + id );
repoHandler.put( configuration );
ManagedRepository repo = repoHandler.get( id );
assertNotNull( repo );
assertEquals( id, repo.getId( ) );
assertEquals( "n-" + id, repo.getName( ) );
assertTrue( hasRepositoryInConfig( id ) );
}
finally
{
removeRepositoryFromConfig( id );
}
}
@Test
void testPutWithoutRegister( ) throws RepositoryException
{
final String id = "test-repo-06";
ManagedRepositoryHandler repoHandler = createHandler( );
Configuration aCfg = new Configuration( );
ManagedRepositoryConfiguration configuration = new ManagedRepositoryConfiguration( );
configuration.setId( id );
configuration.setName( "n-"+id );
repoHandler.put( configuration, aCfg );
ManagedRepository repo = repoHandler.get( id );
assertNull( repo );
assertFalse( hasRepositoryInConfig( id ) );
assertTrue( aCfg.getManagedRepositories( ).stream( ).anyMatch( g -> g!=null && id.equals( g.getId( ) ) ) );
}
@Test
void putWithCheck_invalid( ) throws RepositoryException
{
final String id = "test-repo-07";
final String name = "n-"+id;
try
{
ManagedRepositoryHandler repoHandler = createHandler( );
BasicManagedRepositoryValidator checker = new BasicManagedRepositoryValidator( configurationHandler );
checker.setRepositoryRegistry( repositoryRegistry );
ManagedRepositoryConfiguration configuration = new ManagedRepositoryConfiguration();
configuration.setId( "" );
configuration.setName( name );
CheckedResult<ManagedRepository, Map<String, List<ValidationError>>> result = repoHandler.putWithCheck( configuration, checker );
assertNull( repoHandler.get( id ) );
assertNotNull( result.getResult( ) );
assertNotNull( result.getResult( ).get( "id" ) );
assertEquals( 2, result.getResult( ).get( "id" ).size( ) );
assertEquals( ISEMPTY, result.getResult( ).get( "id" ).get( 0 ).getType( ) );
assertFalse( hasRepositoryInConfig( id ) );
assertFalse( hasRepositoryInConfig( "" ) );
} finally
{
removeRepositoryFromConfig( id );
}
}
@Test
void remove( ) throws RepositoryException
{
final String id = "test-repo-08";
ManagedRepositoryHandler repoHandler = createHandler( );
ManagedRepositoryConfiguration configuration = new ManagedRepositoryConfiguration( );
configuration.setId( id );
configuration.setName( "n-"+id );
repoHandler.put( configuration );
assertTrue( hasRepositoryInConfig( id ) );
assertNotNull( repoHandler.get( id ) );
repoHandler.remove( id );
assertNull( repoHandler.get( id ) );
assertFalse( hasRepositoryInConfig( id ) );
}
@Test
void removeWithoutSave( ) throws RepositoryException
{
final String id = "test-repo-09";
ManagedRepositoryHandler repoHandler = createHandler( );
Configuration aCfg = new Configuration( );
ManagedRepositoryConfiguration configuration = new ManagedRepositoryConfiguration( );
configuration.setId( id );
configuration.setName( "n-"+id );
repoHandler.put( configuration, aCfg );
assertTrue( aCfg.getManagedRepositories( ).stream( ).anyMatch( g -> g != null && id.equals( g.getId( ) ) ) );
repoHandler.remove( id, aCfg );
assertNull( repoHandler.get( id ) );
assertTrue( aCfg.getManagedRepositories( ).stream( ).noneMatch( g -> g != null && id.equals( g.getId( ) ) ) );
assertNull( repoHandler.get( id ) );
}
@Test
void validateRepository( ) throws IOException
{
final String id = "test-repo-10";
ManagedRepositoryHandler repoHandler = createHandler( );
EditableManagedRepository repository = createRepository( id, "n-"+id );
CheckedResult<ManagedRepository, Map<String, List<ValidationError>>> result = repoHandler.validateRepository( repository );
assertNotNull( result );
assertEquals( 0, result.getResult( ).size( ) );
repository = createRepository( id, "n-test-repo-10###" );
result = repoHandler.validateRepository( repository );
assertNotNull( result );
assertEquals( 1, result.getResult( ).size( ) );
assertNotNull( result.getResult().get( "name" ) );
}
@Test
void validateRepositoryIfExisting( ) throws IOException, RepositoryException
{
final String id = "test-repo-11";
try
{
ManagedRepositoryHandler repoHandler = createHandler( );
EditableManagedRepository repository = createRepository( id, "n-" + id );
repoHandler.put( repository );
CheckedResult<ManagedRepository, Map<String, List<ValidationError>>> result = repoHandler.validateRepository( repository );
assertNotNull( result );
assertEquals( 1, result.getResult( ).size( ) );
} finally
{
removeRepositoryFromConfig( id );
}
}
@Test
void validateRepositoryForUpdate( ) throws IOException, RepositoryException
{
final String id = "test-repo-12";
try
{
ManagedRepositoryHandler repoHandler = createHandler( );
EditableManagedRepository repository = createRepository( id, "n-" + id );
repoHandler.put( repository );
CheckedResult<ManagedRepository, Map<String, List<ValidationError>>> result = repoHandler.validateRepositoryForUpdate( repository );
assertNotNull( result );
assertEquals( 0, result.getResult( ).size( ) );
} finally
{
removeRepositoryFromConfig( id );
}
}
@Test
void has( ) throws IOException, RepositoryException
{
final String id = "test-repo-13";
try
{
ManagedRepositoryHandler repoHandler = createHandler( );
EditableManagedRepository repository = createRepository( id, "n-" + id );
assertFalse( repoHandler.hasRepository( id ) );
repoHandler.put( repository );
assertTrue( repoHandler.hasRepository( id ) );
} finally
{
removeRepositoryFromConfig( id );
}
}
}

View File

@ -0,0 +1,225 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<configuration>
<version>3.0.0</version>
<managedRepositories>
<managedRepository>
<id>internal</id>
<name>Archiva Managed Internal Repository</name>
<description>This is internal repository.</description>
<location>${appserver.base}/repositories/internal</location>
<indexDir>${appserver.base}/repositories/internal/.indexer</indexDir>
<layout>default</layout>
<releases>true</releases>
<snapshots>false</snapshots>
<blockRedeployments>true</blockRedeployments>
<scanned>true</scanned>
<refreshCronExpression>0 0 * * * ?</refreshCronExpression>
<retentionPeriod>30</retentionPeriod>
</managedRepository>
<managedRepository>
<id>staging</id>
<name>Repository with staging</name>
<description>This is repository with staging.</description>
<location>${appserver.base}/repositories/internal</location>
<indexDir>${appserver.base}/repositories/internal/.indexer</indexDir>
<layout>default</layout>
<releases>true</releases>
<snapshots>false</snapshots>
<blockRedeployments>true</blockRedeployments>
<scanned>true</scanned>
<refreshCronExpression>0 0 * * * ?</refreshCronExpression>
<retentionPeriod>30</retentionPeriod>
<stageRepoNeeded>true</stageRepoNeeded>
</managedRepository>
<managedRepository>
<id>snapshots</id>
<name>Archiva Managed Snapshot Repository</name>
<location>${appserver.base}/repositories/snapshots</location>
<indexDir>${appserver.base}/repositories/snapshots/.indexer</indexDir>
<layout>default</layout>
<releases>false</releases>
<snapshots>true</snapshots>
<blockRedeployments>false</blockRedeployments>
<scanned>true</scanned>
<refreshCronExpression>0 0\,30 * * * ?</refreshCronExpression>
<retentionPeriod>30</retentionPeriod>
</managedRepository>
<managedRepository>
<id>test-repo-01</id>
<name>n-test-repo-01</name>
<location>${appserver.base}/repositories/test-repo-01</location>
<indexDir>${appserver.base}/repositories/test-repo-01/.indexer</indexDir>
<layout>default</layout>
<releases>true</releases>
<snapshots>false</snapshots>
<blockRedeployments>false</blockRedeployments>
<scanned>true</scanned>
<refreshCronExpression>0 0\,30 * * * ?</refreshCronExpression>
<retentionPeriod>30</retentionPeriod>
</managedRepository>
</managedRepositories>
<remoteRepositories>
<remoteRepository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<timeout>35</timeout>
</remoteRepository>
</remoteRepositories>
<repositoryGroups>
<repositoryGroup>
<id>test-group-01</id>
<name>Test Group 01</name>
<type>MAVEN</type>
<repositories>
<repository>internal</repository>
</repositories>
</repositoryGroup>
</repositoryGroups>
<proxyConnectors>
<proxyConnector>
<sourceRepoId>internal</sourceRepoId>
<targetRepoId>central</targetRepoId>
<proxyId/>
<policies>
<snapshots>disabled</snapshots>
<releases>once</releases>
<checksum>fix</checksum>
<cache-failures>cached</cache-failures>
</policies>
<whiteListPatterns>
<whiteListPattern>**/*</whiteListPattern>
</whiteListPatterns>
</proxyConnector>
</proxyConnectors>
<legacyArtifactPaths>
<legacyArtifactPath>
<path>jaxen/jars/jaxen-1.0-FCS-full.jar</path>
<artifact>jaxen:jaxen:1.0-FCS:full:jar</artifact>
</legacyArtifactPath>
</legacyArtifactPaths>
<repositoryScanning>
<fileTypes>
<fileType>
<id>artifacts</id>
<patterns>
<pattern>**/*.pom</pattern>
<pattern>**/*.jar</pattern>
<pattern>**/*.ear</pattern>
<pattern>**/*.war</pattern>
<pattern>**/*.car</pattern>
<pattern>**/*.sar</pattern>
<pattern>**/*.mar</pattern>
<pattern>**/*.rar</pattern>
<pattern>**/*.dtd</pattern>
<pattern>**/*.tld</pattern>
<pattern>**/*.tar.gz</pattern>
<pattern>**/*.tar.bz2</pattern>
<pattern>**/*.zip</pattern>
</patterns>
</fileType>
<fileType>
<id>indexable-content</id>
<patterns>
<pattern>**/*.txt</pattern>
<pattern>**/*.TXT</pattern>
<pattern>**/*.block</pattern>
<pattern>**/*.config</pattern>
<pattern>**/*.pom</pattern>
<pattern>**/*.xml</pattern>
<pattern>**/*.xsd</pattern>
<pattern>**/*.dtd</pattern>
<pattern>**/*.tld</pattern>
</patterns>
</fileType>
<fileType>
<id>auto-remove</id>
<patterns>
<pattern>**/*.bak</pattern>
<pattern>**/*~</pattern>
<pattern>**/*-</pattern>
</patterns>
</fileType>
<fileType>
<id>ignored</id>
<patterns>
<pattern>**/.htaccess</pattern>
<pattern>**/KEYS</pattern>
<pattern>**/*.rb</pattern>
<pattern>**/*.sh</pattern>
<pattern>**/.svn/**</pattern>
<pattern>**/.DAV/**</pattern>
<pattern>.index/**</pattern>
<pattern>.indexer/**</pattern>
</patterns>
</fileType>
</fileTypes>
<knownContentConsumers>
<knownContentConsumer>create-missing-checksums</knownContentConsumer>
<knownContentConsumer>validate-checksum</knownContentConsumer>
<knownContentConsumer>validate-signature</knownContentConsumer>
<knownContentConsumer>index-content</knownContentConsumer>
<knownContentConsumer>auto-remove</knownContentConsumer>
<knownContentConsumer>auto-rename</knownContentConsumer>
<knownContentConsumer>metadata-updater</knownContentConsumer>
<knownContentConsumer>create-archiva-metadata</knownContentConsumer>
<knownContentConsumer>duplicate-artifacts</knownContentConsumer>
<!--knownContentConsumer>repository-purge</knownContentConsumer-->
</knownContentConsumers>
<invalidContentConsumers>
<invalidContentConsumer>update-db-bad-content</invalidContentConsumer>
</invalidContentConsumers>
</repositoryScanning>
<webapp>
<ui>
<showFindArtifacts>true</showFindArtifacts>
<appletFindEnabled>true</appletFindEnabled>
</ui>
</webapp>
<redbackRuntimeConfiguration>
<userManagerImpls>
<userManagerImpl>jpa</userManagerImpl>
</userManagerImpls>
<rbacManagerImpls>
<rbacManagerImpl>cached</rbacManagerImpl>
</rbacManagerImpls>
</redbackRuntimeConfiguration>
<archivaDefaultConfiguration>
<defaultCheckPaths>
<defaultCheckPath>
<url>http://download.oracle.com/maven</url>
<path>com/sleepycat/je/license.txt</path>
</defaultCheckPath>
<defaultCheckPath>
<url>https://download.oracle.com/maven</url>
<path>com/sleepycat/je/license.txt</path>
</defaultCheckPath>
</defaultCheckPaths>
</archivaDefaultConfiguration>
</configuration>

View File

@ -0,0 +1,57 @@
<?xml version="1.0"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
default-lazy-init="true">
<context:annotation-config/>
<context:component-scan base-package="org.apache.archiva.repository.mock"/>
<bean name="commons-configuration" class="org.apache.archiva.components.registry.commons.CommonsConfigurationRegistry">
<property name="initialConfiguration">
<value>
<![CDATA[
<configuration>
<system/>
<xml fileName="archiva-managed.xml" config-forceCreate="true"
config-optional="true"
config-name="org.apache.archiva.base" config-at="org.apache.archiva"/>
</configuration>
]]>
</value>
</property>
</bean>
<bean name="taskScheduler#mergeRemoteIndexes"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
<property name="poolSize" value="4"/>
<property name="threadGroupName" value="mergeRemoteIndexes"/>
</bean>
</beans>

View File

@ -50,11 +50,6 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId> <artifactId>mockito-core</artifactId>

View File

@ -25,6 +25,7 @@ import org.apache.archiva.indexer.IndexCreationFailedException;
import org.apache.archiva.repository.base.ArchivaRepositoryRegistry; import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
import org.apache.archiva.repository.RepositoryType; import org.apache.archiva.repository.RepositoryType;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.repository.features.IndexCreationFeature; import org.apache.archiva.repository.features.IndexCreationFeature;
import org.apache.archiva.repository.features.RemoteIndexFeature; import org.apache.archiva.repository.features.RemoteIndexFeature;
import org.apache.archiva.repository.maven.MavenManagedRepository; import org.apache.archiva.repository.maven.MavenManagedRepository;
@ -62,6 +63,11 @@ public class MavenIndexManagerTest {
@Inject @Inject
ArchivaRepositoryRegistry repositoryRegistry; ArchivaRepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
@SuppressWarnings( "unused" )
@Inject @Inject
RepositoryGroupHandler groupHandler; RepositoryGroupHandler groupHandler;

View File

@ -32,6 +32,7 @@ import org.apache.archiva.proxy.ProxyRegistry;
import org.apache.archiva.repository.base.ArchivaRepositoryRegistry; import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
import org.apache.archiva.repository.Repository; import org.apache.archiva.repository.Repository;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.repository.features.IndexCreationFeature; import org.apache.archiva.repository.features.IndexCreationFeature;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.apache.commons.lang3.SystemUtils; import org.apache.commons.lang3.SystemUtils;
@ -46,6 +47,7 @@ import org.apache.maven.index.Scanner;
import org.apache.maven.index.ScanningRequest; import org.apache.maven.index.ScanningRequest;
import org.apache.maven.index.ScanningResult; import org.apache.maven.index.ScanningResult;
import org.apache.maven.index.context.IndexingContext; import org.apache.maven.index.context.IndexingContext;
import org.apache.maven.index_shaded.lucene.index.IndexUpgrader;
import org.easymock.EasyMock; import org.easymock.EasyMock;
import org.easymock.IMocksControl; import org.easymock.IMocksControl;
import org.junit.After; import org.junit.After;
@ -93,8 +95,14 @@ public abstract class AbstractMavenRepositorySearch
@Inject @Inject
ArchivaRepositoryRegistry repositoryRegistry; ArchivaRepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject @Inject
RepositoryGroupHandler repositoryGroupHandler; ManagedRepositoryHandler managedRepositoryHandler;
@SuppressWarnings( "unused" )
@Inject
RepositoryGroupHandler groupHandler;
@Inject @Inject
ProxyRegistry proxyRegistry; ProxyRegistry proxyRegistry;
@ -124,9 +132,11 @@ public abstract class AbstractMavenRepositorySearch
FileUtils.deleteDirectory( Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_1 + "/.indexer" ) ); FileUtils.deleteDirectory( Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_1 + "/.indexer" ) );
assertFalse( Files.exists(Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_1 + "/.indexer" )) ); assertFalse( Files.exists(Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_1 + "/.indexer" )) );
Files.createDirectories( Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_1 + "/.indexer" ) );
FileUtils.deleteDirectory( Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_2 + "/.indexer" ) ); FileUtils.deleteDirectory( Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_2 + "/.indexer" ) );
assertFalse( Files.exists(Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_2 + "/.indexer" )) ); assertFalse( Files.exists(Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_2 + "/.indexer" )) );
Files.createDirectories( Paths.get( org.apache.archiva.common.utils.FileUtils.getBasedir(), "/target/repos/" + TEST_REPO_2 + "/.indexer" ) );
archivaConfigControl = EasyMock.createControl(); archivaConfigControl = EasyMock.createControl();
@ -212,7 +222,7 @@ public abstract class AbstractMavenRepositorySearch
protected void createIndex( String repository, List<Path> filesToBeIndexed, boolean scan, Path indexDir, boolean copyFiles) protected void createIndex( String repository, List<Path> filesToBeIndexed, boolean scan, Path indexDir, boolean copyFiles)
throws Exception throws Exception
{ {
Repository rRepo = repositoryRegistry.getRepository(repository); final Repository rRepo = repositoryRegistry.getRepository(repository);
IndexCreationFeature icf = rRepo.getFeature(IndexCreationFeature.class).get(); IndexCreationFeature icf = rRepo.getFeature(IndexCreationFeature.class).get();
@ -228,12 +238,12 @@ public abstract class AbstractMavenRepositorySearch
Path indexerDirectory = repoDir.resolve(".indexer" ); Path indexerDirectory = repoDir.resolve(".indexer" );
if ( Files.exists(indexerDirectory) ) if ( indexDir == null && Files.exists(indexerDirectory) )
{ {
FileUtils.deleteDirectory( indexerDirectory ); FileUtils.deleteDirectory( indexerDirectory );
assertFalse( Files.exists(indexerDirectory) );
} }
assertFalse( Files.exists(indexerDirectory) );
Path lockFile = repoDir.resolve(".indexer/write.lock" ); Path lockFile = repoDir.resolve(".indexer/write.lock" );
if ( Files.exists(lockFile) ) if ( Files.exists(lockFile) )
@ -247,10 +257,21 @@ public abstract class AbstractMavenRepositorySearch
indexDirectory.toFile().deleteOnExit(); indexDirectory.toFile().deleteOnExit();
FileUtils.deleteDirectory(indexDirectory); FileUtils.deleteDirectory(indexDirectory);
icf.setIndexPath(indexDirectory.toUri()); icf.setIndexPath(indexDirectory.toUri());
config.getManagedRepositories( ).stream( ).filter( r -> r.getId( ).equals( rRepo.getId( ) ) ).findFirst( ).ifPresent( r ->
r.setIndexDir( indexDirectory.toAbsolutePath( ).toString( ) )
);
// IndexUpgrader.main(new String[]{indexDirectory.toAbsolutePath().toString()});
} else { } else {
icf.setIndexPath(indexDir.toUri()); icf.setIndexPath(indexDir.toUri());
Files.createDirectories( indexDir );
config.getManagedRepositories( ).stream( ).filter( r -> r.getId( ).equals( rRepo.getId( ) ) ).findFirst( ).ifPresent( r ->
r.setIndexDir( indexDir.toAbsolutePath( ).toString( ) )
);
IndexUpgrader.main(new String[]{indexDir.toAbsolutePath().toString()});
} }
if (copyFiles) { if (copyFiles) {
Path repo = Paths.get(org.apache.archiva.common.utils.FileUtils.getBasedir(), "src/test/" + repository); Path repo = Paths.get(org.apache.archiva.common.utils.FileUtils.getBasedir(), "src/test/" + repository);
assertTrue(Files.exists(repo)); assertTrue(Files.exists(repo));
@ -269,11 +290,11 @@ public abstract class AbstractMavenRepositorySearch
repositoryRegistry.reload(); repositoryRegistry.reload();
archivaConfigControl.reset(); archivaConfigControl.reset();
rRepo = repositoryRegistry.getRepository(repository); Repository rRepo2 = repositoryRegistry.getRepository( repository );
icf = rRepo.getFeature(IndexCreationFeature.class).get(); icf = rRepo2.getFeature(IndexCreationFeature.class).get();
archivaCtx = rRepo.getIndexingContext(); archivaCtx = rRepo2.getIndexingContext();
context = archivaCtx.getBaseContext(IndexingContext.class); context = archivaCtx.getBaseContext(IndexingContext.class);

View File

@ -24,6 +24,7 @@ import org.apache.archiva.indexer.search.SearchResultHit;
import org.apache.archiva.indexer.search.SearchResults; import org.apache.archiva.indexer.search.SearchResults;
import org.apache.archiva.repository.base.ArchivaRepositoryRegistry; import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.easymock.EasyMock; import org.easymock.EasyMock;
import org.junit.After; import org.junit.After;
import org.junit.Test; import org.junit.Test;
@ -44,8 +45,14 @@ public class MavenRepositorySearchOSGITest
@Inject @Inject
ArchivaRepositoryRegistry repositoryRegistry; ArchivaRepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject @Inject
RepositoryGroupHandler repositoryGroupHandler; ManagedRepositoryHandler managedRepositoryHandler;
@SuppressWarnings( "unused" )
@Inject
RepositoryGroupHandler groupHandler;
@After @After
@Override @Override

View File

@ -25,6 +25,7 @@ import org.apache.archiva.indexer.search.SearchResults;
import org.apache.archiva.indexer.util.SearchUtil; import org.apache.archiva.indexer.util.SearchUtil;
import org.apache.archiva.repository.base.ArchivaRepositoryRegistry; import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.junit.After; import org.junit.After;
import org.junit.Test; import org.junit.Test;
@ -46,8 +47,14 @@ public class MavenRepositorySearchPaginateTest
@Inject @Inject
ArchivaRepositoryRegistry repositoryRegistry; ArchivaRepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject @Inject
RepositoryGroupHandler repositoryGroupHandler; ManagedRepositoryHandler managedRepositoryHandler;
@SuppressWarnings( "unused" )
@Inject
RepositoryGroupHandler groupHandler;
@After @After
public void endTests() { public void endTests() {

View File

@ -33,6 +33,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
@ -895,12 +896,12 @@ public class MavenRepositorySearchTest
throws Exception throws Exception
{ {
Path repo = Paths.get("target/repo-release"); Path repo = Paths.get("target/repo-release-index-test/repo-release");
try { try {
Path indexDirectory = repo.resolve(".indexer"); Path indexDirectory = repo.resolve(".indexer");
Path zipFile = Paths.get(Thread.currentThread().getContextClassLoader().getResource("repo-release.zip").toURI()); Path zipFile = Paths.get(Thread.currentThread().getContextClassLoader().getResource("repo-release.zip").toURI());
FileUtils.unzip(zipFile, repo.getParent()); FileUtils.unzip(zipFile, repo.getParent());
IndexUpgrader.main(new String[]{indexDirectory.toAbsolutePath().toString()}); // IndexUpgrader.main(new String[]{indexDirectory.toAbsolutePath().toString(), "-delete-prior-commits"});
createIndex(REPO_RELEASE, Collections.emptyList(), false, indexDirectory, false); createIndex(REPO_RELEASE, Collections.emptyList(), false, indexDirectory, false);
// indexer.addIndexingContext( REPO_RELEASE, REPO_RELEASE, repo.toFile(), indexDirectory.toFile(), // indexer.addIndexingContext( REPO_RELEASE, REPO_RELEASE, repo.toFile(), indexDirectory.toFile(),

View File

@ -25,6 +25,7 @@ import org.apache.archiva.policies.*;
import org.apache.archiva.proxy.model.RepositoryProxyHandler; import org.apache.archiva.proxy.model.RepositoryProxyHandler;
import org.apache.archiva.repository.*; import org.apache.archiva.repository.*;
import org.apache.archiva.repository.base.managed.BasicManagedRepository; import org.apache.archiva.repository.base.managed.BasicManagedRepository;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.repository.storage.StorageAsset; import org.apache.archiva.repository.storage.StorageAsset;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.Wagon;
@ -70,6 +71,11 @@ public abstract class AbstractProxyTestCase
@Inject @Inject
RepositoryRegistry repositoryRegistry; RepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
protected static final String ID_PROXIED1 = "proxied1"; protected static final String ID_PROXIED1 = "proxied1";
protected static final String ID_PROXIED1_TARGET = "proxied1-target"; protected static final String ID_PROXIED1_TARGET = "proxied1-target";

View File

@ -25,6 +25,7 @@ import org.apache.archiva.policies.ChecksumPolicy;
import org.apache.archiva.policies.ReleasesPolicy; import org.apache.archiva.policies.ReleasesPolicy;
import org.apache.archiva.policies.SnapshotsPolicy; import org.apache.archiva.policies.SnapshotsPolicy;
import org.apache.archiva.policies.urlcache.UrlFailureCache; import org.apache.archiva.policies.urlcache.UrlFailureCache;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.repository.content.BaseRepositoryContentLayout; import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
import org.apache.archiva.repository.content.Artifact; import org.apache.archiva.repository.content.Artifact;
import org.apache.archiva.repository.storage.StorageAsset; import org.apache.archiva.repository.storage.StorageAsset;
@ -53,6 +54,7 @@ public class CacheFailuresTransferTest
@Inject @Inject
UrlFailureCache urlFailureCache; UrlFailureCache urlFailureCache;
@Test @Test
public void testGetWithCacheFailuresOn( ) public void testGetWithCacheFailuresOn( )
throws Exception throws Exception

View File

@ -30,6 +30,7 @@ import org.apache.archiva.policies.PropagateErrorsOnUpdateDownloadPolicy;
import org.apache.archiva.policies.ReleasesPolicy; import org.apache.archiva.policies.ReleasesPolicy;
import org.apache.archiva.policies.SnapshotsPolicy; import org.apache.archiva.policies.SnapshotsPolicy;
import org.apache.archiva.proxy.model.RepositoryProxyHandler; import org.apache.archiva.proxy.model.RepositoryProxyHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.repository.content.BaseRepositoryContentLayout; import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
import org.apache.archiva.repository.ManagedRepository; import org.apache.archiva.repository.ManagedRepository;
import org.apache.archiva.repository.ManagedRepositoryContent; import org.apache.archiva.repository.ManagedRepositoryContent;
@ -100,6 +101,11 @@ public class HttpProxyTransferTest
@Inject @Inject
private ProxyRegistry proxyRegistry; private ProxyRegistry proxyRegistry;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
private Server server; private Server server;
protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout ) protected ManagedRepositoryContent createRepository( String id, String name, String path, String layout )

View File

@ -497,7 +497,12 @@ public class MavenRepositoryProvider implements RepositoryProvider {
if (StringUtils.isNotBlank(repository.getIndexDir())) { if (StringUtils.isNotBlank(repository.getIndexDir())) {
Path indexDir; Path indexDir;
try { try {
indexDir = Paths.get(new URI(repository.getIndexDir().startsWith("file://") ? repository.getIndexDir() : "file://" + repository.getIndexDir())); if (repository.getIndexDir().startsWith( "file:" )) {
indexDir = Paths.get( new URI( repository.getIndexDir( ) ) );
} else
{
indexDir = Paths.get( repository.getIndexDir( ) );
}
if (indexDir.isAbsolute()) { if (indexDir.isAbsolute()) {
Path newDir = indexDir.getParent().resolve(indexDir.getFileName() + StagingRepositoryFeature.STAGING_REPO_POSTFIX); Path newDir = indexDir.getParent().resolve(indexDir.getFileName() + StagingRepositoryFeature.STAGING_REPO_POSTFIX);
log.debug("Changing index directory {} -> {}", indexDir, newDir); log.debug("Changing index directory {} -> {}", indexDir, newDir);

View File

@ -36,6 +36,7 @@ import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest;
import org.apache.archiva.proxy.maven.WagonFactory; import org.apache.archiva.proxy.maven.WagonFactory;
import org.apache.archiva.proxy.maven.WagonFactoryRequest; import org.apache.archiva.proxy.maven.WagonFactoryRequest;
import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.Wagon;
@ -100,6 +101,11 @@ public class Maven2RepositoryMetadataResolverMRM1411RepoGroupTest
@Inject @Inject
RepositoryRegistry repositoryRegistry; RepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
private WagonFactory wagonFactory; private WagonFactory wagonFactory;
ManagedRepositoryConfiguration testRepo; ManagedRepositoryConfiguration testRepo;

View File

@ -37,6 +37,7 @@ import org.apache.archiva.proxy.maven.WagonFactory;
import org.apache.archiva.proxy.maven.WagonFactoryRequest; import org.apache.archiva.proxy.maven.WagonFactoryRequest;
import org.apache.archiva.repository.ReleaseScheme; import org.apache.archiva.repository.ReleaseScheme;
import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.Wagon;
@ -97,6 +98,11 @@ public class Maven2RepositoryMetadataResolverMRM1411Test
@Inject @Inject
RepositoryRegistry repositoryRegistry; RepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
private WagonFactory wagonFactory; private WagonFactory wagonFactory;
ManagedRepositoryConfiguration testRepo; ManagedRepositoryConfiguration testRepo;
@ -141,6 +147,7 @@ public class Maven2RepositoryMetadataResolverMRM1411Test
wagonFactory = mock( WagonFactory.class ); wagonFactory = mock( WagonFactory.class );
assertNotNull( storage );
storage.setWagonFactory( wagonFactory ); storage.setWagonFactory( wagonFactory );
Wagon wagon = new MockWagon(); Wagon wagon = new MockWagon();
@ -153,6 +160,7 @@ public class Maven2RepositoryMetadataResolverMRM1411Test
public void testGetProjectVersionMetadataWithParentSuccessful() public void testGetProjectVersionMetadataWithParentSuccessful()
throws Exception throws Exception
{ {
assertNotNull( storage );
copyTestArtifactWithParent( "target/test-classes/com/example/test/test-artifact-module-a", copyTestArtifactWithParent( "target/test-classes/com/example/test/test-artifact-module-a",
"target/test-repository/com/example/test/test-artifact-module-a" ); "target/test-repository/com/example/test/test-artifact-module-a" );
copyTestArtifactWithParent( "src/test/resources/com/example/test/test-artifact-parent", copyTestArtifactWithParent( "src/test/resources/com/example/test/test-artifact-parent",
@ -201,12 +209,14 @@ public class Maven2RepositoryMetadataResolverMRM1411Test
public void testGetProjectVersionMetadataWithParentNoRemoteReposConfigured() public void testGetProjectVersionMetadataWithParentNoRemoteReposConfigured()
throws Exception throws Exception
{ {
assertNotNull( storage );
// remove configuration // remove configuration
Configuration config = configuration.getConfiguration(); Configuration config = configuration.getConfiguration();
RemoteRepositoryConfiguration remoteRepo = config.findRemoteRepositoryById( TEST_REMOTE_REPO_ID ); RemoteRepositoryConfiguration remoteRepo = config.findRemoteRepositoryById( TEST_REMOTE_REPO_ID );
config.removeRemoteRepository( remoteRepo ); config.removeRemoteRepository( remoteRepo );
configuration.save( config ); configuration.save( config );
assertNotNull( storage );
copyTestArtifactWithParent( "target/test-classes/com/example/test/test-artifact-module-a", copyTestArtifactWithParent( "target/test-classes/com/example/test/test-artifact-module-a",
"target/test-repository/com/example/test/test-artifact-module-a" ); "target/test-repository/com/example/test/test-artifact-module-a" );
@ -233,6 +243,7 @@ public class Maven2RepositoryMetadataResolverMRM1411Test
public void testGetProjectVersionMetadataWithParentNotInAnyRemoteRepo() public void testGetProjectVersionMetadataWithParentNotInAnyRemoteRepo()
throws Exception throws Exception
{ {
assertNotNull( storage );
copyTestArtifactWithParent( "target/test-classes/com/example/test/test-artifact-module-a", copyTestArtifactWithParent( "target/test-classes/com/example/test/test-artifact-module-a",
"target/test-repository/com/example/test/test-artifact-module-a" ); "target/test-repository/com/example/test/test-artifact-module-a" );

View File

@ -25,6 +25,7 @@ import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest;
import org.apache.archiva.metadata.repository.storage.RepositoryStorageRuntimeException; import org.apache.archiva.metadata.repository.storage.RepositoryStorageRuntimeException;
import org.apache.archiva.proxy.maven.WagonFactory; import org.apache.archiva.proxy.maven.WagonFactory;
import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -44,6 +45,11 @@ public class Maven2RepositoryMetadataResolverManagedReleaseTest
@Inject @Inject
RepositoryRegistry repositoryRegistry; RepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
private static final String TEST_REPO_ID = "test"; private static final String TEST_REPO_ID = "test";
private static final String TEST_REMOTE_REPO_ID = "central"; private static final String TEST_REMOTE_REPO_ID = "central";

View File

@ -24,6 +24,7 @@ import org.apache.archiva.metadata.model.ProjectVersionMetadata;
import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest; import org.apache.archiva.metadata.repository.storage.ReadMetadataRequest;
import org.apache.archiva.metadata.repository.storage.RepositoryStorageRuntimeException; import org.apache.archiva.metadata.repository.storage.RepositoryStorageRuntimeException;
import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -42,6 +43,11 @@ public class Maven2RepositoryMetadataResolverManagedSnapshotTest
@Inject @Inject
RepositoryRegistry repositoryRegistry; RepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
private static final String TEST_REPO_ID = "test"; private static final String TEST_REPO_ID = "test";
private static final String TEST_REMOTE_REPO_ID = "central"; private static final String TEST_REMOTE_REPO_ID = "central";

View File

@ -40,6 +40,7 @@ import org.apache.archiva.metadata.repository.storage.RepositoryStorageMetadataN
import org.apache.archiva.proxy.maven.WagonFactory; import org.apache.archiva.proxy.maven.WagonFactory;
import org.apache.archiva.proxy.maven.WagonFactoryRequest; import org.apache.archiva.proxy.maven.WagonFactoryRequest;
import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.Wagon;
@ -80,6 +81,11 @@ public class Maven2RepositoryMetadataResolverTest
@Inject @Inject
RepositoryRegistry repositoryRegistry; RepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
private static final String TEST_REPO_ID = "test"; private static final String TEST_REPO_ID = "test";
private static final String TEST_REMOTE_REPO_ID = "central"; private static final String TEST_REMOTE_REPO_ID = "central";

View File

@ -27,6 +27,7 @@ import org.apache.archiva.repository.base.managed.BasicManagedRepository;
import org.apache.archiva.repository.ManagedRepository; import org.apache.archiva.repository.ManagedRepository;
import org.apache.archiva.repository.ReleaseScheme; import org.apache.archiva.repository.ReleaseScheme;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.repository.storage.StorageAsset; import org.apache.archiva.repository.storage.StorageAsset;
import org.apache.archiva.repository.features.IndexCreationFeature; import org.apache.archiva.repository.features.IndexCreationFeature;
import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask; import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask;
@ -74,6 +75,11 @@ public class ArchivaIndexingTaskExecutorTest
@Inject @Inject
ArchivaRepositoryRegistry repositoryRegistry; ArchivaRepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
@SuppressWarnings( "unused" )
@Inject @Inject
RepositoryGroupHandler repositoryGroupHandler; RepositoryGroupHandler repositoryGroupHandler;

View File

@ -29,6 +29,8 @@ import org.apache.archiva.repository.RepositoryProvider;
import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.RepositoryType; import org.apache.archiva.repository.RepositoryType;
import org.apache.archiva.repository.UnsupportedURIException; import org.apache.archiva.repository.UnsupportedURIException;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.repository.features.IndexCreationFeature; import org.apache.archiva.repository.features.IndexCreationFeature;
import org.apache.archiva.repository.features.RemoteIndexFeature; import org.apache.archiva.repository.features.RemoteIndexFeature;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
@ -90,6 +92,15 @@ public class DownloadRemoteIndexTaskTest
@Inject @Inject
RepositoryRegistry repositoryRegistry; RepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
@SuppressWarnings( "unused" )
@Inject
RepositoryGroupHandler repositoryGroupHandler;
@Inject @Inject
RepositoryProvider repositoryProvider; RepositoryProvider repositoryProvider;

View File

@ -30,6 +30,7 @@ import org.apache.archiva.components.taskqueue.execution.TaskExecutor;
import org.apache.archiva.repository.ManagedRepository; import org.apache.archiva.repository.ManagedRepository;
import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.scheduler.repository.model.RepositoryTask; import org.apache.archiva.scheduler.repository.model.RepositoryTask;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.junit.After; import org.junit.After;
@ -66,6 +67,11 @@ public abstract class AbstractArchivaRepositoryScanningTaskExecutorTest
@Inject @Inject
RepositoryRegistry repositoryRegistry; RepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
@SuppressWarnings( "unused" )
@Inject @Inject
RepositoryGroupHandler groupHandler; RepositoryGroupHandler groupHandler;

View File

@ -27,10 +27,12 @@ import org.apache.archiva.configuration.Configuration;
import org.apache.archiva.configuration.ManagedRepositoryConfiguration; import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
import org.apache.archiva.configuration.RemoteRepositoryConfiguration; import org.apache.archiva.configuration.RemoteRepositoryConfiguration;
import org.apache.archiva.indexer.ArchivaIndexingContext; import org.apache.archiva.indexer.ArchivaIndexingContext;
import org.apache.archiva.repository.RepositoryException;
import org.apache.archiva.repository.base.ArchivaRepositoryRegistry; import org.apache.archiva.repository.base.ArchivaRepositoryRegistry;
import org.apache.archiva.repository.ManagedRepository; import org.apache.archiva.repository.ManagedRepository;
import org.apache.archiva.repository.RepositoryType; import org.apache.archiva.repository.RepositoryType;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
import org.apache.archiva.webdav.httpunit.MkColMethodWebRequest; import org.apache.archiva.webdav.httpunit.MkColMethodWebRequest;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
@ -104,6 +106,10 @@ public abstract class AbstractRepositoryServletTestCase
@Inject @Inject
RepositoryGroupHandler repositoryGroupHandler; RepositoryGroupHandler repositoryGroupHandler;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
@Inject @Inject
ArchivaRepositoryRegistry repositoryRegistry; ArchivaRepositoryRegistry repositoryRegistry;
@ -166,8 +172,16 @@ public abstract class AbstractRepositoryServletTestCase
System.setProperty( "appserver.base", getAppserverBase().toAbsolutePath().toString()); System.setProperty( "appserver.base", getAppserverBase().toAbsolutePath().toString());
log.info("setUp appserverBase={}, projectBase={}, workingDir={}", getAppserverBase(), getProjectBase(), Paths.get("").toString()); log.info("setUp appserverBase={}, projectBase={}, workingDir={}", getAppserverBase(), getProjectBase(), Paths.get("").toString());
repositoryRegistry.getRepositories().stream().forEach(r -> r.close()); repositoryRegistry.getRepositories().stream().forEach(r -> {
try
{
repositoryRegistry.removeRepository( r );
}
catch ( RepositoryException e )
{
e.printStackTrace( );
}
} );
org.apache.archiva.common.utils.FileUtils.deleteDirectory( getAppserverBase() ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( getAppserverBase() );
Path testConf = getProjectBase().resolve( "src/test/resources/repository-archiva.xml" ); Path testConf = getProjectBase().resolve( "src/test/resources/repository-archiva.xml" );
@ -191,20 +205,21 @@ public abstract class AbstractRepositoryServletTestCase
config.getRemoteRepositories().clear(); config.getRemoteRepositories().clear();
saveConfiguration( archivaConfiguration ); saveConfiguration( archivaConfiguration );
// repositoryRegistry.reload();
ArchivaIndexingContext ctx = repositoryRegistry.getManagedRepository( REPOID_INTERNAL ).getIndexingContext( ); // ArchivaIndexingContext ctx = repositoryRegistry.getManagedRepository( REPOID_INTERNAL ).getIndexingContext( );
try // try
{ // {
if (repositoryRegistry.getIndexManager(RepositoryType.MAVEN)!=null) { // if (repositoryRegistry.getIndexManager(RepositoryType.MAVEN)!=null) {
repositoryRegistry.getIndexManager(RepositoryType.MAVEN).pack(ctx); // repositoryRegistry.getIndexManager(RepositoryType.MAVEN).pack(ctx);
} // }
} finally // } finally
{ // {
if (ctx!=null) // if (ctx!=null)
{ // {
ctx.close( ); // ctx.close( );
} // }
} // }
CacheManager.getInstance().clearAll(); CacheManager.getInstance().clearAll();
@ -856,8 +871,8 @@ public abstract class AbstractRepositoryServletTestCase
repo.setLocation( location.toAbsolutePath().toString() ); repo.setLocation( location.toAbsolutePath().toString() );
repo.setBlockRedeployments( blockRedeployments ); repo.setBlockRedeployments( blockRedeployments );
repo.setType( "MAVEN" ); repo.setType( "MAVEN" );
repo.setIndexDir(".indexer"); repo.setIndexDir(location.resolve( ".indexer" ).toAbsolutePath().toString());
repo.setPackedIndexDir(".index"); repo.setPackedIndexDir( location.resolve( ".index" ).toAbsolutePath( ).toString( ) );
return repo; return repo;
} }
@ -891,13 +906,16 @@ public abstract class AbstractRepositoryServletTestCase
protected void setupCleanRepo( Path repoRootDir ) protected void setupCleanRepo( Path repoRootDir )
throws IOException throws IOException
{
if (repoRootDir!=null)
{ {
org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoRootDir ); org.apache.archiva.common.utils.FileUtils.deleteDirectory( repoRootDir );
if ( !Files.exists(repoRootDir) ) if ( !Files.exists( repoRootDir ) )
{ {
Files.createDirectories( repoRootDir ); Files.createDirectories( repoRootDir );
} }
} }
}
protected void assertManagedFileNotExists( Path repoRootInternal, String resourcePath ) protected void assertManagedFileNotExists( Path repoRootInternal, String resourcePath )
{ {

View File

@ -35,6 +35,7 @@ import org.apache.archiva.configuration.RepositoryGroupConfiguration;
import org.apache.archiva.metadata.repository.storage.RepositoryPathTranslator; import org.apache.archiva.metadata.repository.storage.RepositoryPathTranslator;
import org.apache.archiva.repository.ManagedRepositoryContent; import org.apache.archiva.repository.ManagedRepositoryContent;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler; import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.base.managed.ManagedRepositoryHandler;
import org.apache.archiva.repository.maven.content.MavenContentHelper; import org.apache.archiva.repository.maven.content.MavenContentHelper;
import org.apache.archiva.repository.maven.metadata.storage.ArtifactMappingProvider; import org.apache.archiva.repository.maven.metadata.storage.ArtifactMappingProvider;
import org.apache.archiva.proxy.ProxyRegistry; import org.apache.archiva.proxy.ProxyRegistry;
@ -163,6 +164,10 @@ public class ArchivaDavResourceFactoryTest
@Inject @Inject
RepositoryGroupHandler repositoryGroupHandler; RepositoryGroupHandler repositoryGroupHandler;
@SuppressWarnings( "unused" )
@Inject
ManagedRepositoryHandler managedRepositoryHandler;
public Path getProjectBase() { public Path getProjectBase() {
if (this.projectBase.get()==null) { if (this.projectBase.get()==null) {
String pathVal = System.getProperty("mvn.project.base.dir"); String pathVal = System.getProperty("mvn.project.base.dir");
@ -195,7 +200,7 @@ public class ArchivaDavResourceFactoryTest
archivaConfiguration = archivaConfigurationControl.createMock( ArchivaConfiguration.class ); archivaConfiguration = archivaConfigurationControl.createMock( ArchivaConfiguration.class );
config = new Configuration(); config = new Configuration();
expect( archivaConfiguration.getConfiguration() ).andReturn( config ).times( 2, 20 ); expect( archivaConfiguration.getConfiguration() ).andReturn( config ).times( 2, 25 );
expect (archivaConfiguration.getDefaultLocale()).andReturn( Locale.getDefault() ).anyTimes(); expect (archivaConfiguration.getDefaultLocale()).andReturn( Locale.getDefault() ).anyTimes();
archivaConfiguration.addListener( EasyMock.anyObject( ) ); archivaConfiguration.addListener( EasyMock.anyObject( ) );
expectLastCall().times(0, 4); expectLastCall().times(0, 4);

View File

@ -24,8 +24,19 @@ import org.apache.archiva.checksum.ChecksumAlgorithm;
import org.apache.archiva.metadata.QueryParameter; import org.apache.archiva.metadata.QueryParameter;
import org.apache.archiva.metadata.generic.GenericMetadataFacet; import org.apache.archiva.metadata.generic.GenericMetadataFacet;
import org.apache.archiva.metadata.generic.GenericMetadataFacetFactory; import org.apache.archiva.metadata.generic.GenericMetadataFacetFactory;
import org.apache.archiva.metadata.model.*; import org.apache.archiva.metadata.model.ArtifactMetadata;
import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner; import org.apache.archiva.metadata.model.CiManagement;
import org.apache.archiva.metadata.model.Dependency;
import org.apache.archiva.metadata.model.IssueManagement;
import org.apache.archiva.metadata.model.License;
import org.apache.archiva.metadata.model.MailingList;
import org.apache.archiva.metadata.model.MetadataFacet;
import org.apache.archiva.metadata.model.MetadataFacetFactory;
import org.apache.archiva.metadata.model.Organization;
import org.apache.archiva.metadata.model.ProjectMetadata;
import org.apache.archiva.metadata.model.ProjectVersionMetadata;
import org.apache.archiva.metadata.model.ProjectVersionReference;
import org.apache.archiva.metadata.model.Scm;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -36,7 +47,17 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.util.*; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;

View File

@ -31,7 +31,7 @@
<properties> <properties>
<site.staging.base>${project.parent.parent.basedir}</site.staging.base> <site.staging.base>${project.parent.parent.basedir}</site.staging.base>
<cassandraVersion>3.11.10</cassandraVersion> <cassandraVersion>3.11.11</cassandraVersion>
</properties> </properties>
<dependencies> <dependencies>