1 package org.apache.maven.archiva.configuration;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.commons.collections.CollectionUtils;
23 import org.apache.commons.collections.MapUtils;
24 import org.apache.commons.configuration.BaseConfiguration;
25 import org.apache.commons.io.FileUtils;
26 import org.apache.commons.lang.StringUtils;
27 import org.apache.maven.archiva.configuration.functors.ProxyConnectorConfigurationOrderComparator;
28 import org.apache.maven.archiva.configuration.io.registry.ConfigurationRegistryReader;
29 import org.apache.maven.archiva.configuration.io.registry.ConfigurationRegistryWriter;
30 import org.apache.maven.archiva.policies.AbstractUpdatePolicy;
31 import org.apache.maven.archiva.policies.CachedFailuresPolicy;
32 import org.apache.maven.archiva.policies.ChecksumPolicy;
33 import org.apache.maven.archiva.policies.Policy;
34 import org.apache.maven.archiva.policies.PostDownloadPolicy;
35 import org.apache.maven.archiva.policies.PreDownloadPolicy;
36 import org.codehaus.plexus.evaluator.DefaultExpressionEvaluator;
37 import org.codehaus.plexus.evaluator.EvaluatorException;
38 import org.codehaus.plexus.evaluator.ExpressionEvaluator;
39 import org.codehaus.plexus.evaluator.sources.SystemPropertyExpressionSource;
40 import org.codehaus.plexus.registry.Registry;
41 import org.codehaus.plexus.registry.RegistryException;
42 import org.codehaus.plexus.registry.RegistryListener;
43 import org.codehaus.redback.components.registry.commons.CommonsConfigurationRegistry;
44 import org.codehaus.redback.components.springutils.ComponentContainer;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.stereotype.Service;
49 import javax.annotation.PostConstruct;
50 import javax.inject.Inject;
51 import javax.inject.Named;
53 import java.io.IOException;
54 import java.util.ArrayList;
55 import java.util.Collection;
56 import java.util.Collections;
57 import java.util.HashMap;
58 import java.util.HashSet;
59 import java.util.Iterator;
60 import java.util.List;
62 import java.util.Map.Entry;
67 * Implementation of configuration holder that retrieves it from the registry.
70 * The registry layers and merges the 2 configuration files: user, and application server.
73 * Instead of relying on the model defaults, if the registry is empty a default configuration file is loaded and
74 * applied from a resource. The defaults are not loaded into the registry as the lists (eg repositories) could no longer
75 * be removed if that was the case.
78 * When saving the configuration, it is saved to the location it was read from. If it was read from the defaults, it
79 * will be saved to the user location.
80 * However, if the configuration contains information from both sources, an exception is raised as this is currently
81 * unsupported. The reason for this is that it is not possible to identify where to re-save elements, and can result
82 * in list configurations (eg repositories) becoming inconsistent.
85 * If the configuration is outdated, it will be upgraded when it is loaded. This is done by checking the version flag
86 * before reading it from the registry.
89 @Service( "archivaConfiguration#default" )
90 public class DefaultArchivaConfiguration
91 implements ArchivaConfiguration, RegistryListener
93 private Logger log = LoggerFactory.getLogger( DefaultArchivaConfiguration.class );
96 * Plexus registry to read the configuration from.
100 @Named( value = "commons-configuration" )
101 private Registry registry;
104 private ComponentContainer componentContainer;
107 * The configuration that has been converted.
109 private Configuration configuration;
114 * @todo these don't strictly belong in here
116 private Map<String, PreDownloadPolicy> prePolicies;
121 * @todo these don't strictly belong in here
123 private Map<String, PostDownloadPolicy> postPolicies;
127 * default-value="${user.home}/.m2/archiva.xml"
129 private String userConfigFilename = "${user.home}/.m2/archiva.xml";
133 * default-value="${appserver.base}/conf/archiva.xml"
135 private String altConfigFilename = "${appserver.base}/conf/archiva.xml";
138 * Configuration Listeners we've registered.
140 private Set<ConfigurationListener> listeners = new HashSet<ConfigurationListener>();
143 * Registry Listeners we've registered.
145 private Set<RegistryListener> registryListeners = new HashSet<RegistryListener>();
148 * Boolean to help determine if the configuration exists as a result of pulling in
149 * the default-archiva.xml
151 private boolean isConfigurationDefaulted = false;
153 private static final String KEY = "org.apache.maven.archiva";
155 public Configuration getConfiguration()
157 return loadConfiguration();
160 private synchronized Configuration loadConfiguration()
162 if ( configuration == null )
164 configuration = load();
165 configuration = unescapeExpressions( configuration );
166 if ( isConfigurationDefaulted )
168 configuration = checkRepositoryLocations( configuration );
172 return configuration;
175 @SuppressWarnings( "unchecked" )
176 private Configuration load()
178 // TODO: should this be the same as section? make sure unnamed sections still work (eg, sys properties)
179 Registry subset = registry.getSubset( KEY );
180 if ( subset.getString( "version" ) == null )
182 // a little autodetection of v1, even if version is omitted (this was previously allowed)
183 if ( subset.getSubset( "repositoryScanning" ).isEmpty() )
185 // only for empty, or v < 1
186 subset = readDefaultConfiguration();
190 Configuration config = new ConfigurationRegistryReader().read( subset );
192 config.getRepositoryGroups();
193 config.getRepositoryGroupsAsMap();
194 if ( !config.getRepositories().isEmpty() )
196 for ( Iterator<V1RepositoryConfiguration> i = config.getRepositories().iterator(); i.hasNext(); )
198 V1RepositoryConfiguration r = i.next();
199 r.setScanned( r.isIndexed() );
201 if ( r.getUrl().startsWith( "file://" ) )
203 r.setLocation( r.getUrl().substring( 7 ) );
204 config.addManagedRepository( r );
206 else if ( r.getUrl().startsWith( "file:" ) )
208 r.setLocation( r.getUrl().substring( 5 ) );
209 config.addManagedRepository( r );
213 RemoteRepositoryConfiguration repo = new RemoteRepositoryConfiguration();
214 repo.setId( r.getId() );
215 repo.setLayout( r.getLayout() );
216 repo.setName( r.getName() );
217 repo.setUrl( r.getUrl() );
218 config.addRemoteRepository( repo );
222 // Prevent duplicate repositories from showing up.
223 config.getRepositories().clear();
225 registry.removeSubset( KEY + ".repositories" );
228 if ( !CollectionUtils.isEmpty( config.getRemoteRepositories() ) )
230 List<RemoteRepositoryConfiguration> remoteRepos = config.getRemoteRepositories();
231 for ( RemoteRepositoryConfiguration repo : remoteRepos )
233 // [MRM-582] Remote Repositories with empty <username> and <password> fields shouldn't be created in configuration.
234 if ( StringUtils.isBlank( repo.getUsername() ) )
236 repo.setUsername( null );
239 if ( StringUtils.isBlank( repo.getPassword() ) )
241 repo.setPassword( null );
246 if ( !config.getProxyConnectors().isEmpty() )
248 // Fix Proxy Connector Settings.
250 List<ProxyConnectorConfiguration> proxyConnectorList = new ArrayList<ProxyConnectorConfiguration>();
251 // Create a copy of the list to read from (to prevent concurrent modification exceptions)
252 proxyConnectorList.addAll( config.getProxyConnectors() );
253 // Remove the old connector list.
254 config.getProxyConnectors().clear();
256 for ( ProxyConnectorConfiguration connector : proxyConnectorList )
259 boolean connectorValid = true;
261 Map<String, String> policies = new HashMap<String, String>();
262 // Make copy of policies
263 policies.putAll( connector.getPolicies() );
264 // Clear out policies
265 connector.getPolicies().clear();
267 // Work thru policies. cleaning them up.
268 for ( Entry<String, String> entry : policies.entrySet() )
270 String policyId = entry.getKey();
271 String setting = entry.getValue();
273 // Upgrade old policy settings.
274 if ( "releases".equals( policyId ) || "snapshots".equals( policyId ) )
276 if ( "ignored".equals( setting ) )
278 setting = AbstractUpdatePolicy.ALWAYS;
280 else if ( "disabled".equals( setting ) )
282 setting = AbstractUpdatePolicy.NEVER;
285 else if ( "cache-failures".equals( policyId ) )
287 if ( "ignored".equals( setting ) )
289 setting = CachedFailuresPolicy.NO;
291 else if ( "cached".equals( setting ) )
293 setting = CachedFailuresPolicy.YES;
296 else if ( "checksum".equals( policyId ) )
298 if ( "ignored".equals( setting ) )
300 setting = ChecksumPolicy.IGNORE;
304 // Validate existance of policy key.
305 if ( policyExists( policyId ) )
307 Policy policy = findPolicy( policyId );
308 // Does option exist?
309 if ( !policy.getOptions().contains( setting ) )
311 setting = policy.getDefaultOption();
313 connector.addPolicy( policyId, setting );
317 // Policy key doesn't exist. Don't add it to golden version.
318 log.warn( "Policy [" + policyId + "] does not exist." );
322 if ( connectorValid )
324 config.addProxyConnector( connector );
328 // Normalize the order fields in the proxy connectors.
329 Map<String, java.util.List<ProxyConnectorConfiguration>> proxyConnectorMap =
330 config.getProxyConnectorAsMap();
332 for ( List<ProxyConnectorConfiguration> connectors : proxyConnectorMap.values() )
334 // Sort connectors by order field.
335 Collections.sort( connectors, ProxyConnectorConfigurationOrderComparator.getInstance() );
337 // Normalize the order field values.
339 for ( ProxyConnectorConfiguration connector : connectors )
341 connector.setOrder( order++ );
349 private Policy findPolicy( String policyId )
351 if ( MapUtils.isEmpty( prePolicies ) )
353 log.error( "No PreDownloadPolicies found!" );
357 if ( MapUtils.isEmpty( postPolicies ) )
359 log.error( "No PostDownloadPolicies found!" );
365 policy = prePolicies.get( policyId );
366 if ( policy != null )
371 policy = postPolicies.get( policyId );
372 if ( policy != null )
380 private boolean policyExists( String policyId )
382 if ( MapUtils.isEmpty( prePolicies ) )
384 log.error( "No PreDownloadPolicies found!" );
388 if ( MapUtils.isEmpty( postPolicies ) )
390 log.error( "No PostDownloadPolicies found!" );
394 return ( prePolicies.containsKey( policyId ) || postPolicies.containsKey( policyId ) );
397 private Registry readDefaultConfiguration()
399 // if it contains some old configuration, remove it (Archiva 0.9)
400 registry.removeSubset( KEY );
404 registry.addConfigurationFromResource( "org/apache/maven/archiva/configuration/default-archiva.xml", KEY );
405 this.isConfigurationDefaulted = true;
407 catch ( RegistryException e )
409 throw new ConfigurationRuntimeException(
410 "Fatal error: Unable to find the built-in default configuration and load it into the registry", e );
412 return registry.getSubset( KEY );
415 @SuppressWarnings( "unchecked" )
416 public synchronized void save( Configuration configuration )
417 throws IndeterminateConfigurationException, RegistryException
419 Registry section = registry.getSection( KEY + ".user" );
420 Registry baseSection = registry.getSection( KEY + ".base" );
421 if ( section == null )
423 section = baseSection;
424 if ( section == null )
426 section = createDefaultConfigurationFile();
429 else if ( baseSection != null )
431 Collection<String> keys = baseSection.getKeys();
432 boolean foundList = false;
433 for ( Iterator<String> i = keys.iterator(); i.hasNext() && !foundList; )
435 String key = i.next();
437 // a little aggressive with the repositoryScanning and databaseScanning - should be no need to split
438 // that configuration
439 if ( key.startsWith( "repositories" ) || key.startsWith( "proxyConnectors" )
440 || key.startsWith( "networkProxies" ) || key.startsWith( "repositoryScanning" )
441 || key.startsWith( "databaseScanning" ) || key.startsWith( "remoteRepositories" )
442 || key.startsWith( "managedRepositories" ) || key.startsWith( "repositoryGroups" ) )
450 this.configuration = null;
452 throw new IndeterminateConfigurationException(
453 "Configuration can not be saved when it is loaded from two sources" );
457 // escape all cron expressions to handle ','
458 escapeCronExpressions( configuration );
460 // [MRM-661] Due to a bug in the modello registry writer, we need to take these out by hand. They'll be put back by the writer.
461 if ( configuration.getManagedRepositories().isEmpty() && section != null )
463 section.removeSubset( "managedRepositories" );
465 if ( configuration.getRemoteRepositories().isEmpty() && section != null )
467 section.removeSubset( "remoteRepositories" );
470 if ( configuration.getProxyConnectors().isEmpty() && section != null )
472 section.removeSubset( "proxyConnectors" );
474 if ( configuration.getNetworkProxies().isEmpty() && section != null )
476 section.removeSubset( "networkProxies" );
478 if ( configuration.getLegacyArtifactPaths().isEmpty() && section != null )
480 section.removeSubset( "legacyArtifactPaths" );
482 if ( configuration.getRepositoryGroups().isEmpty() && section != null )
484 section.removeSubset( "repositoryGroups" );
486 if ( configuration.getRepositoryScanning() != null )
488 if ( configuration.getRepositoryScanning().getKnownContentConsumers().isEmpty() && section != null )
490 section.removeSubset( "repositoryScanning.knownContentConsumers" );
492 if ( configuration.getRepositoryScanning().getInvalidContentConsumers().isEmpty() && section != null )
494 section.removeSubset( "repositoryScanning.invalidContentConsumers" );
499 new ConfigurationRegistryWriter().write( configuration, section );
502 this.configuration = unescapeExpressions( configuration );
504 triggerEvent( ConfigurationEvent.SAVED );
507 private void escapeCronExpressions( Configuration configuration )
509 for ( ManagedRepositoryConfiguration c : (List<ManagedRepositoryConfiguration>) configuration.getManagedRepositories() )
511 c.setRefreshCronExpression( escapeCronExpression( c.getRefreshCronExpression() ) );
517 private Registry createDefaultConfigurationFile()
518 throws RegistryException
520 // TODO: may not be needed under commons-configuration 1.4 - check
521 // UPDATE: Upgrading to commons-configuration 1.4 breaks half the unit tests. 2007-10-11 (joakime)
523 String contents = "<configuration />";
525 String fileLocation = userConfigFilename;
527 if ( !writeFile( "user configuration", userConfigFilename, contents ) )
529 fileLocation = altConfigFilename;
530 if ( !writeFile( "alternative configuration", altConfigFilename, contents ) )
532 throw new RegistryException(
533 "Unable to create configuration file in either user [" + userConfigFilename + "] or alternative ["
535 + "] locations on disk, usually happens when not allowed to write to those locations." );
539 // olamy hackish I know :-)
540 contents = "<configuration><xml fileName=\"" + fileLocation +"\" config-forceCreate=\"true\" config-name=\"org.apache.maven.archiva.user\"/>"
541 + "</configuration>";
544 ( (CommonsConfigurationRegistry) registry ).setProperties( contents );
546 ( (CommonsConfigurationRegistry) registry ).initialize();
548 for ( RegistryListener regListener : registryListeners )
550 addRegistryChangeListener( regListener );
553 triggerEvent( ConfigurationEvent.SAVED );
555 Registry section = registry.getSection( KEY + ".user" );
556 return section == null ? new CommonsConfigurationRegistry( new BaseConfiguration() ) : section;
560 * Attempts to write the contents to a file, if an IOException occurs, return false.
562 * The file will be created if the directory to the file exists, otherwise this will return false.
564 * @param filetype the filetype (freeform text) to use in logging messages when failure to write.
565 * @param path the path to write to.
566 * @param contents the contents to write.
567 * @return true if write successful.
569 private boolean writeFile( String filetype, String path, String contents )
571 File file = new File( path );
575 // Check parent directory (if it is declared)
576 if ( file.getParentFile() != null )
578 // Check that directory exists
579 if ( ( file.getParentFile().exists() == false ) || ( file.getParentFile().isDirectory() == false ) )
581 // Directory to file must exist for file to be created
586 FileUtils.writeStringToFile( file, contents, "UTF-8" );
589 catch ( IOException e )
591 log.error( "Unable to create " + filetype + " file: " + e.getMessage(), e );
596 private void triggerEvent( int type )
598 ConfigurationEvent evt = new ConfigurationEvent( type );
599 for ( ConfigurationListener listener : listeners )
601 listener.configurationEvent( evt );
605 public void addListener( ConfigurationListener listener )
607 if ( listener == null )
612 listeners.add( listener );
615 public void removeListener( ConfigurationListener listener )
617 if ( listener == null )
622 listeners.remove( listener );
625 public void addChangeListener( RegistryListener listener )
627 addRegistryChangeListener( listener );
629 // keep track for later
630 registryListeners.add( listener );
633 private void addRegistryChangeListener( RegistryListener listener )
635 Registry section = registry.getSection( KEY + ".user" );
636 if ( section != null )
638 section.addChangeListener( listener );
640 section = registry.getSection( KEY + ".base" );
641 if ( section != null )
643 section.addChangeListener( listener );
648 public void initialize()
651 this.postPolicies = componentContainer.buildMapWithRole( PostDownloadPolicy.class );
652 this.prePolicies = componentContainer.buildMapWithRole( PreDownloadPolicy.class );
653 // Resolve expressions in the userConfigFilename and altConfigFilename
656 ExpressionEvaluator expressionEvaluator = new DefaultExpressionEvaluator();
657 expressionEvaluator.addExpressionSource( new SystemPropertyExpressionSource() );
658 userConfigFilename = expressionEvaluator.expand( userConfigFilename );
659 altConfigFilename = expressionEvaluator.expand( altConfigFilename );
662 catch ( EvaluatorException e )
664 throw new RuntimeException(
665 "Unable to evaluate expressions found in " + "userConfigFilename or altConfigFilename." );
667 registry.addChangeListener( this );
672 this.configuration = null;
675 this.registry.initialize();
677 catch ( RegistryException e )
679 throw new ConfigurationRuntimeException( e.getMessage(), e );
684 public void beforeConfigurationChange( Registry registry, String propertyName, Object propertyValue )
686 // nothing to do here
689 public synchronized void afterConfigurationChange( Registry registry, String propertyName, Object propertyValue )
691 configuration = null;
694 private String removeExpressions( String directory )
696 String value = StringUtils.replace( directory, "${appserver.base}",
697 registry.getString( "appserver.base", "${appserver.base}" ) );
698 value = StringUtils.replace( value, "${appserver.home}",
699 registry.getString( "appserver.home", "${appserver.home}" ) );
703 private String unescapeCronExpression( String cronExpression )
705 return StringUtils.replace( cronExpression, "\\,", "," );
708 private String escapeCronExpression( String cronExpression )
710 return StringUtils.replace( cronExpression, ",", "\\," );
713 private Configuration unescapeExpressions( Configuration config )
715 // TODO: for commons-configuration 1.3 only
716 for ( Iterator<ManagedRepositoryConfiguration> i = config.getManagedRepositories().iterator(); i.hasNext(); )
718 ManagedRepositoryConfiguration c = i.next();
719 c.setLocation( removeExpressions( c.getLocation() ) );
720 c.setRefreshCronExpression( unescapeCronExpression( c.getRefreshCronExpression() ) );
728 private Configuration checkRepositoryLocations( Configuration config )
730 // additional check for [MRM-789], ensure that the location of the default repositories
731 // are not installed in the server installation
732 for ( ManagedRepositoryConfiguration repo : (List<ManagedRepositoryConfiguration>) config.getManagedRepositories() )
734 String repoPath = repo.getLocation();
735 File repoLocation = new File( repoPath );
737 if ( repoLocation.exists() && repoLocation.isDirectory() && !repoPath.endsWith(
738 "data/repositories/" + repo.getId() ) )
740 repo.setLocation( repoPath + "/data/repositories/" + repo.getId() );
747 public String getUserConfigFilename()
749 return userConfigFilename;
752 public String getAltConfigFilename()
754 return altConfigFilename;
757 public boolean isDefaulted()
759 return this.isConfigurationDefaulted;
762 public Registry getRegistry()
767 public void setRegistry( Registry registry )
769 this.registry = registry;
773 public void setUserConfigFilename( String userConfigFilename )
775 this.userConfigFilename = userConfigFilename;
778 public void setAltConfigFilename( String altConfigFilename )
780 this.altConfigFilename = altConfigFilename;