fix NullPointer in CommonsConfiguration.initialize (must call enableLogger() before initialize())

add support for Plexus List<components for role> injection (RepositoryContentConsumers)
remove spring support classes from archiva-commons
PlexusInSpringTestCase to replace PlexusTestCase with as fiew as possible changes
apply plexus-spring on archiva-policies
apply plexus-spring on archiva-proxy (some test failure to investigate)


git-svn-id: https://svn.apache.org/repos/asf/maven/archiva/branches@630773 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Nicolas De Loof 2008-02-25 09:20:06 +00:00
parent b0fac565d6
commit 68f0ed16f7
23 changed files with 324 additions and 1156 deletions

View File

@ -1,119 +0,0 @@
package org.apache.maven.archiva.common.spring;
/*
* 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 java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.AbstractFactoryBean;
/**
* A FactoryBean to port to Spring the plexus "get all components with role ..." feature.
* <p>
* Plexus allows to define a requirement this way :
* <pre>
* \/**
* * @plexus.requirement role="org.apache.maven.archiva.policies.PreDownloadPolicy"
* *\/
* private Map<String, PreDownloadPolicy> prePolicies;
* </pre>
* This FactoryBean generates the expected Map from a ListableBeanFactory, based on the role
* to be the FQCN of the component interface.
*
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
* @since 1.1
*/
public class BeansOfTypeFactoryBean
extends AbstractFactoryBean
implements InitializingBean
{
private Class type;
private Map<String, Object> beansOfType;
/**
* {@inheritDoc}
* @see org.springframework.beans.factory.config.AbstractFactoryBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet()
throws Exception
{
beansOfType = new HashMap<String, Object>();
if ( !( getBeanFactory() instanceof ListableBeanFactory ) )
{
String error = "A ListableBeanFactory bean factory is required to create a bean-of-types Map";
logger.error( error );
throw new BeanInitializationException( error );
}
Map beans = ((ListableBeanFactory) getBeanFactory()).getBeansOfType( type );
for ( Iterator iterator = beans.entrySet().iterator(); iterator.hasNext(); )
{
Map.Entry entry = (Map.Entry) iterator.next();
beansOfType.put( getRoleHint( (String) entry.getKey() ), entry.getValue() );
}
}
/**
* @param key
* @return
*/
private String getRoleHint( String key )
{
int i =key.indexOf( '#' );
if (i >= 0 )
{
return key.substring( i + 1 );
}
return key;
}
/**
* {@inheritDoc}
* @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance()
*/
@Override
protected Object createInstance()
throws Exception
{
return beansOfType;
}
/**
* {@inheritDoc}
* @see org.springframework.beans.factory.config.AbstractFactoryBean#getObjectType()
*/
@Override
public Class getObjectType()
{
return Map.class;
}
public void setType( Class type )
{
this.type = type;
}
}

View File

@ -1,73 +0,0 @@
package org.apache.maven.archiva.common.spring;
/*
* 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 java.util.List;
import java.util.StringTokenizer;
import javax.xml.namespace.QName;
import javax.xml.xpath.XPathFunction;
import javax.xml.xpath.XPathFunctionException;
import javax.xml.xpath.XPathFunctionResolver;
import org.apache.commons.lang.ClassUtils;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Disposable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
/**
* XPathFunction to convert plexus property-name to Spring propertyName.
*
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
* @since 1.1
*/
public class CamelCaseXpathFunction
implements XPathFunction, XPathFunctionResolver
{
private static final QName name = new QName( "http://plexus.codehaus.org/", "camelCase" );
/**
* {@inheritDoc}
*
* @see javax.xml.xpath.XPathFunctionResolver#resolveFunction(javax.xml.namespace.QName,
* int)
*/
public XPathFunction resolveFunction( QName functionName, int arity )
{
if ( name.equals( functionName.getLocalPart() ) && arity >= 1 )
{
return new CamelCaseXpathFunction();
}
return null;
}
/**
* {@inheritDoc}
*
* @see javax.xml.xpath.XPathFunction#evaluate(java.util.List)
*/
public Object evaluate( List args )
throws XPathFunctionException
{
return PlexusToSpringUtils.toCamelCase( (String) args.get( 0 ) );
}
}

View File

@ -1,82 +0,0 @@
package org.apache.maven.archiva.common.spring;
/*
* 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 java.io.InputStream;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import org.springframework.beans.factory.xml.BeanDefinitionDocumentReader;
import org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader;
import org.springframework.beans.factory.xml.XmlReaderContext;
import org.w3c.dom.Document;
/**
* A Spring {@link BeanDefinitionDocumentReader} that converts on the fly the
* Plexus components descriptor to a spring XML context.
*
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
* @since 1.1
*/
public class PlexusBeanDefinitionDocumentReader
extends DefaultBeanDefinitionDocumentReader
{
public void registerBeanDefinitions( Document doc, XmlReaderContext readerContext )
{
doc = convertPlexusDescriptorToSpringBeans( doc );
super.registerBeanDefinitions( doc, readerContext );
}
public Document convertPlexusDescriptorToSpringBeans( Document doc )
{
if ( ! "component-set".equals( doc.getDocumentElement().getNodeName() ) )
{
return doc;
}
try
{
Source xmlSource = new DOMSource( doc );
InputStream is = getClass().getResourceAsStream( "plexus2spring.xsl" );
Source xsltSource = new StreamSource( is );
DOMResult transResult = new DOMResult();
// FIXME : uses Xalan extension. need either to force Xalan as Transformer or
// register a XpathFunctionResolver (how ?)
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer( xsltSource );
t.transform( xmlSource, transResult );
return (Document) transResult.getNode();
}
catch ( Exception e )
{
// FIXME log the error;
return doc;
}
}
}

View File

@ -1,49 +0,0 @@
package org.apache.maven.archiva.common.spring;
/*
* 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.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.Resource;
/**
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
* @since 1.1
*/
public class PlexusBeanFactory
extends DefaultListableBeanFactory
{
private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader( this );
public PlexusBeanFactory( Resource resource )
{
this( resource, null );
}
public PlexusBeanFactory( Resource resource, BeanFactory parentBeanFactory )
{
super( parentBeanFactory );
this.reader.setDocumentReaderClass( PlexusBeanDefinitionDocumentReader.class );
this.reader.setValidationMode( XmlBeanDefinitionReader.VALIDATION_NONE );
this.reader.loadBeanDefinitions( resource );
}
}

View File

@ -1,137 +0,0 @@
package org.apache.maven.archiva.common.spring;
/*
* 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 java.io.IOException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
* @since 1.1
*/
public class PlexusClassPathXmlApplicationContext
extends ClassPathXmlApplicationContext
{
// TODO enable Field injection...
// @see http://forum.springframework.org/showthread.php?t=50181
public PlexusClassPathXmlApplicationContext( String path, Class clazz )
throws BeansException
{
super( path, clazz );
}
public PlexusClassPathXmlApplicationContext( String configLocation )
throws BeansException
{
super( configLocation );
}
public PlexusClassPathXmlApplicationContext( String[] configLocations, ApplicationContext parent )
throws BeansException
{
super( configLocations, parent );
}
public PlexusClassPathXmlApplicationContext( String[] configLocations, boolean refresh, ApplicationContext parent )
throws BeansException
{
super( configLocations, refresh, parent );
}
public PlexusClassPathXmlApplicationContext( String[] configLocations, boolean refresh )
throws BeansException
{
super( configLocations, refresh );
}
public PlexusClassPathXmlApplicationContext( String[] paths, Class clazz, ApplicationContext parent )
throws BeansException
{
super( paths, clazz, parent );
}
public PlexusClassPathXmlApplicationContext( String[] paths, Class clazz )
throws BeansException
{
super( paths, clazz );
}
public PlexusClassPathXmlApplicationContext( String[] configLocations )
throws BeansException
{
super( configLocations );
}
/**
* Register a custom BeanDefinitionDocumentReader to convert plexus
* descriptors to spring bean context format.
* <p>
* Implementation note : validation must be disabled as plexus descriptors
* don't use DTD / XML schemas {@inheritDoc}
*
* @see org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.xml.XmlBeanDefinitionReader)
*/
@Override
protected void loadBeanDefinitions( XmlBeanDefinitionReader reader )
throws BeansException, IOException
{
reader.setDocumentReaderClass( PlexusBeanDefinitionDocumentReader.class );
reader.setValidationMode( XmlBeanDefinitionReader.VALIDATION_NONE );
super.loadBeanDefinitions( reader );
}
/**
* Post-process the beanFactory to adapt plexus concepts to spring :
* <ul>
* <li>register a beanPostPorcessor to support LogEnabled interface in
* spring context
* </ul>
* {@inheritDoc}
*
* @see org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory)
*/
@Override
protected void prepareBeanFactory( ConfigurableListableBeanFactory beanFactory )
{
super.prepareBeanFactory( beanFactory );
if ( logger.isDebugEnabled() )
{
String[] beans = getBeanFactory().getBeanDefinitionNames();
logger.debug( "registered beans :" );
for ( int i = 0; i < beans.length; i++ )
{
logger.debug( beans[i] );
}
}
// Register a bean post-processor to handle plexus Logger injection
getBeanFactory().addBeanPostProcessor( new PlexusLogEnabledBeanPostProcessor() );
}
}

View File

@ -1,49 +0,0 @@
package org.apache.maven.archiva.common.spring;
/*
* 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.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
public class PlexusFactory
{
private PlexusContainer container;
private String role;
private String roleHint;
public PlexusFactory( String role, String roleHint )
{
this.role = role;
this.roleHint = roleHint;
}
public Object createInstance()
throws ComponentLookupException
{
return container.lookup( role, roleHint );
}
public void setContainer( PlexusContainer container )
{
this.container = container;
}
}

View File

@ -1,86 +0,0 @@
package org.apache.maven.archiva.common.spring;
/*
* 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.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.LoggerManager;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.codehaus.plexus.logging.slf4j.Slf4jLogger;
import org.codehaus.plexus.logging.slf4j.Slf4jLoggerManager;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
* A Spring bean postPorcessor to apply Plexu LogEnabled lifecycle interface
*
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
* @since 1.1
*/
public class PlexusLogEnabledBeanPostProcessor
implements BeanPostProcessor, InitializingBean
{
private LoggerManager loggerManager = new Slf4jLoggerManager();
/**
* {@inheritDoc}
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet()
throws Exception
{
if ( loggerManager instanceof Initializable )
{
( (Initializable) loggerManager ).initialize();
}
}
/**
* {@inheritDoc}
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object, java.lang.String)
*/
public Object postProcessAfterInitialization( Object bean, String beanName )
throws BeansException
{
return bean;
}
/**
* {@inheritDoc}
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object, java.lang.String)
*/
public Object postProcessBeforeInitialization( Object bean, String beanName )
throws BeansException
{
if ( bean instanceof LogEnabled )
{
( (LogEnabled) bean ).enableLogging( loggerManager.getLoggerForComponent( beanName ) );
}
return bean;
}
protected void setLoggerManager( LoggerManager loggerManager )
{
this.loggerManager = loggerManager;
}
}

View File

@ -1,131 +0,0 @@
package org.apache.maven.archiva.common.spring;
/*
* 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 java.lang.reflect.Field;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.lang.ClassUtils;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Disposable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
/**
* Utility method to convert plexus descriptors to spring bean context.
*
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
* @since 1.1
*/
public class PlexusToSpringUtils
{
public static String toSpringId( String string )
{
int i = string.lastIndexOf( '.' );
if (i >= 0 )
{
return Character.toLowerCase( string.charAt( i + 1 ) ) + string.substring( i + 2 );
}
return string;
}
public static String toCamelCase( String string )
{
StringBuilder camelCase = new StringBuilder();
boolean first = true;
StringTokenizer tokenizer = new StringTokenizer( string.toLowerCase(), "-" );
while ( tokenizer.hasMoreTokens() )
{
String token = tokenizer.nextToken();
if ( first )
{
camelCase.append( token.charAt( 0 ) );
first = false;
}
else
{
camelCase.append( Character.toUpperCase( token.charAt( 0 ) ) );
}
camelCase.append( token.substring( 1, token.length() ) );
}
return camelCase.toString();
}
public static boolean isInitializable( String className )
{
boolean initializable = false;
try
{
initializable = Initializable.class.isAssignableFrom( ClassUtils.getClass( className ) );
}
catch ( ClassNotFoundException e )
{
// ignored
}
return initializable;
}
public static boolean isLogEnabled( String className )
{
boolean logEnabled = false;
try
{
logEnabled = LogEnabled.class.isAssignableFrom( ClassUtils.getClass( className ) );
}
catch ( ClassNotFoundException e )
{
// ignored
}
return logEnabled;
}
public static boolean isDisposable( String className )
{
boolean disposable = false;
try
{
disposable = Disposable.class.isAssignableFrom( ClassUtils.getClass( className ) );
}
catch ( ClassNotFoundException e )
{
// ignored
}
return disposable;
}
public static boolean isMap( String className, String property )
{
boolean map = false;
try
{
Class clazz = ClassUtils.getClass( className );
Field f = clazz.getDeclaredField( property );
map = Map.class.isAssignableFrom( f.getType() );
}
catch ( Exception e )
{
// ignored
}
return map;
}
}

View File

@ -1,160 +0,0 @@
<?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.
-->
<xsl:stylesheet
version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:plexus="org.apache.maven.archiva.common.spring.PlexusToSpringUtils">
<!--
FIXME replace xalan extension mecanism to call static methods with XPathFunctions
@see http://www.ibm.com/developerworks/library/x-xalanextensions.html
-->
<xsl:output method="xml" indent="yes"
doctype-public="-//SPRING//DTD BEAN 2.0//EN"
doctype-system="http://www.springframework.org/dtd/spring-beans-2.0.dtd" />
<xsl:template match="/component-set">
<beans>
<xsl:for-each select="components/component">
<bean>
<xsl:choose>
<xsl:when test="role-hint">
<xsl:attribute name="id">
<xsl:value-of select="concat( role, '#', role-hint )" />
</xsl:attribute>
</xsl:when>
<xsl:otherwise>
<xsl:attribute name="id">
<xsl:value-of select="role" />
</xsl:attribute>
</xsl:otherwise>
</xsl:choose>
<xsl:attribute name="class">
<xsl:value-of select="implementation" />
</xsl:attribute>
<xsl:if test="instanciation-strategy/text() = 'per-lookup'">
<xsl:attribute name="scope">prototype</xsl:attribute>
</xsl:if>
<xsl:if test="plexus:isInitializable( implementation/text() )">
<xsl:attribute name="init-method">initialize</xsl:attribute>
</xsl:if>
<xsl:if test="plexus:isDisposable( implementation/text() )">
<xsl:attribute name="destroy-method">dispose</xsl:attribute>
</xsl:if>
<xsl:for-each select="requirements/requirement">
<property>
<xsl:attribute name="name">
<xsl:value-of select="field-name" />
</xsl:attribute>
<xsl:choose>
<xsl:when test="role-hint">
<xsl:attribute name="ref">
<xsl:value-of select="concat( plexus:toSpringId( role ), '#', role-hint )" />
</xsl:attribute>
</xsl:when>
<xsl:otherwise>
<xsl:attribute name="ref">
<xsl:value-of select="plexus:toSpringId( role )" />
</xsl:attribute>
</xsl:otherwise>
</xsl:choose>
</property>
</xsl:for-each>
<xsl:for-each select="configuration/*">
<property>
<xsl:attribute name="name">
<xsl:value-of select="plexus:toCamelCase( name(.) )" />
</xsl:attribute>
<xsl:attribute name="value">
<xsl:value-of select="." />
</xsl:attribute>
</property>
</xsl:for-each>
</bean>
<!--
Plexus can inject all implementations of an interface as a Map
-->
<xsl:for-each select="requirements/requirement">
<xsl:if test="plexus:isMap( ../../implementation, field-name )">
<bean class="org.apache.maven.archiva.common.spring.BeansOfTypeFactoryBean">
<xsl:attribute name="id">
<xsl:value-of select="plexus:toSpringId( role )" />
</xsl:attribute>
<property name="type">
<xsl:attribute name="value">
<xsl:value-of select="role" />
</xsl:attribute>
</property>
</bean>
</xsl:if>
</xsl:for-each>
<!--
Plexus convention is to use interface FQN as bean ID
Spring convention is to use interface simpleName as bean ID
To allow smooth migration, we define same bean with both IDs using an alias
-->
<alias>
<xsl:attribute name="alias">
<xsl:choose>
<xsl:when test="role-hint">
<xsl:value-of select="concat( plexus:toSpringId( role ), '#', role-hint )" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="plexus:toSpringId( role )" />
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
<xsl:attribute name="name">
<xsl:choose>
<xsl:when test="role-hint">
<xsl:value-of select="concat( role, '#', role-hint )" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="role" />
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
</alias>
<!--
Plexus "default" role-hint is used to get the component when no hint is specified.
This translates to spring context to a bean alias without '#role-hint' suffix
-->
<xsl:if test="role-hint/text() = 'default'">
<alias>
<xsl:attribute name="alias">
<xsl:value-of select="plexus:toSpringId( role )" />
</xsl:attribute>
<xsl:attribute name="name">
<xsl:value-of select="concat( role, '#', role-hint )" />
</xsl:attribute>
</alias>
</xsl:if>
</xsl:for-each>
</beans>
</xsl:template>
</xsl:stylesheet>

View File

@ -1,28 +0,0 @@
package org.apache.maven.archiva.common.spring;
import java.util.Arrays;
import javax.xml.xpath.XPathFunction;
import junit.framework.TestCase;
/**
* @author ndeloof
*
*/
public class CamelCaseXpathFunctionTest
extends TestCase
{
private XPathFunction function = new CamelCaseXpathFunction();
/**
* Test method for {@link org.apache.maven.archiva.common.spring.CamelCaseXpathFunction#toCamelCase(java.lang.String)}.
*/
public void testToCamelCase()
throws Exception
{
assertEquals( "aCamelCaseProperty", function.evaluate( Arrays.asList( new String[] { "a-camel-case-property" } ) ) );
}
}

View File

@ -1,73 +0,0 @@
package org.apache.maven.archiva.common.spring;
/*
* 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 java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import junit.framework.TestCase;
import org.dom4j.io.DOMReader;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.core.io.UrlResource;
import org.w3c.dom.Document;
/**
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
*/
public class PlexusBeanDefinitionDocumentReaderTest
extends TestCase
{
public void testXslt()
throws Exception
{
URL plexus = getClass().getResource( "components.xml" );
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse( plexus.openStream() );
PlexusBeanDefinitionDocumentReader reader = new PlexusBeanDefinitionDocumentReader();
doc = reader.convertPlexusDescriptorToSpringBeans( doc );
new XMLWriter( System.out, OutputFormat.createPrettyPrint() ).write( new DOMReader().read( doc ) );
}
/**
* Test conversion from a typical Plexus components descriptor to a spring beanFactory
* @throws Exception
*/
public void testConvertPlexusToSpring()
throws Exception
{
URL plexus = getClass().getResource( "components.xml" );
PlexusBeanFactory factory = new PlexusBeanFactory( new UrlResource( plexus ) );
assertEquals( 2, factory.getBeanDefinitionCount() );
BeanDefinition bd = factory.getBeanDefinition( "java.lang.Object#default" );
assertEquals( "java.lang.String", bd.getBeanClassName() );
assertEquals( "prototype", bd.getScope() );
assertEquals( 2, bd.getPropertyValues().size() );
}
}

View File

@ -1,35 +0,0 @@
<component-set>
<components>
<component>
<role>java.lang.Object</role>
<role-hint>default</role-hint>
<implementation>java.lang.String</implementation>
<instanciation-strategy>per-lookup</instanciation-strategy>
<description></description>
<configuration>
<user-config-filename>${user.home}</user-config-filename>
<alt-config-filename>${java.home}</alt-config-filename>
</configuration>
</component>
<component>
<role>org.codehaus.plexus.logging.LoggerManager</role>
<implementation>org.codehaus.plexus.logging.console.ConsoleLoggerManager</implementation>
<requirements>
<requirement>
<role>org.codehaus.plexus.digest.Digester</role>
<role-hint>sha1</role-hint>
<field-name>digestSha1</field-name>
</requirement>
<requirement>
<role>org.codehaus.plexus.digest.Digester</role>
<role-hint>md5</role-hint>
<field-name>digestMd5</field-name>
</requirement>
<requirement>
<role>org.codehaus.plexus.digest.ChecksumFile</role>
<field-name>checksumFile</field-name>
</requirement>
</requirements>
</component>
</components>
</component-set>

View File

@ -22,10 +22,11 @@
import java.io.File;
import java.util.Properties;
import org.codehaus.plexus.spring.PlexusClassPathXmlApplicationContext;
import org.apache.maven.archiva.policies.urlcache.UrlFailureCache;
import org.codehaus.plexus.PlexusTestCase;
import org.springframework.context.ApplicationContext;
import org.codehaus.plexus.spring.PlexusClassPathXmlApplicationContext;
import org.codehaus.plexus.spring.PlexusInSpringTestCase;
import org.springframework.context.ConfigurableApplicationContext;
/**
* CachedFailuresPolicyTest
@ -34,14 +35,12 @@
* @version $Id$
*/
public class CachedFailuresPolicyTest
extends PlexusTestCase
extends PlexusInSpringTestCase
{
private ApplicationContext factory;
private DownloadPolicy lookupPolicy()
throws Exception
{
return (DownloadPolicy) factory.getBean( "preDownloadPolicy#cache-failures" );
return (DownloadPolicy) lookup( PreDownloadPolicy.class, "cache-failures" );
}
private File getFile()
@ -89,7 +88,7 @@ public void testPolicyYesInCache()
String url = "http://a.bad.hostname.maven.org/path/to/resource.txt";
UrlFailureCache urlFailureCache = (UrlFailureCache) factory.getBean( "urlFailureCache" );
UrlFailureCache urlFailureCache = (UrlFailureCache) lookup( "urlFailureCache" );
urlFailureCache.cacheFailure( url );
request.setProperty( "url", url );
@ -104,16 +103,4 @@ public void testPolicyYesInCache()
// expected path.
}
}
protected void setUp()
throws Exception
{
super.setUp();
factory = new PlexusClassPathXmlApplicationContext(
new String[] {
"classpath*:META-INF/plexus/components.xml",
"classpath*:META-INF/plexus/components-fragment.xml",
"/org/apache/maven/archiva/policies/CachedFailuresPolicyTest-context.xml" } );
}
}

View File

@ -39,10 +39,10 @@
<level value="error"/>
</logger>
<logger name="org.springframewrok">
<logger name="org.springframework">
<level value="DEBUG"/>
</logger>
<root>
<priority value ="info" />
<appender-ref ref="console" />

View File

@ -28,6 +28,11 @@
<artifactId>archiva-proxy</artifactId>
<name>Archiva Base :: Proxy</name>
<dependencies>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-spring</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.maven.archiva</groupId>
<artifactId>archiva-configuration</artifactId>

View File

@ -19,25 +19,6 @@
* under the License.
*/
import org.apache.commons.io.FileUtils;
import org.apache.maven.archiva.common.spring.PlexusClassPathXmlApplicationContext;
import org.apache.maven.archiva.common.spring.PlexusFactory;
import org.apache.maven.archiva.configuration.ArchivaConfiguration;
import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
import org.apache.maven.archiva.configuration.ProxyConnectorConfiguration;
import org.apache.maven.archiva.configuration.RemoteRepositoryConfiguration;
import org.apache.maven.archiva.policies.CachedFailuresPolicy;
import org.apache.maven.archiva.policies.ChecksumPolicy;
import org.apache.maven.archiva.policies.ReleasesPolicy;
import org.apache.maven.archiva.policies.SnapshotsPolicy;
import org.apache.maven.archiva.repository.ManagedRepositoryContent;
import org.apache.maven.wagon.Wagon;
import org.codehaus.plexus.PlexusTestCase;
import org.easymock.MockControl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
@ -49,6 +30,22 @@
import java.util.Date;
import java.util.Locale;
import org.apache.commons.io.FileUtils;
import org.apache.maven.archiva.configuration.ArchivaConfiguration;
import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
import org.apache.maven.archiva.configuration.ProxyConnectorConfiguration;
import org.apache.maven.archiva.configuration.RemoteRepositoryConfiguration;
import org.apache.maven.archiva.policies.CachedFailuresPolicy;
import org.apache.maven.archiva.policies.ChecksumPolicy;
import org.apache.maven.archiva.policies.ReleasesPolicy;
import org.apache.maven.archiva.policies.SnapshotsPolicy;
import org.apache.maven.archiva.repository.ManagedRepositoryContent;
import org.apache.maven.wagon.Wagon;
import org.codehaus.plexus.spring.PlexusClassPathXmlApplicationContext;
import org.codehaus.plexus.spring.PlexusInSpringTestCase;
import org.easymock.MockControl;
import org.springframework.beans.factory.BeanFactory;
/**
* AbstractProxyTestCase
*
@ -56,7 +53,7 @@
* @version $Id$
*/
public abstract class AbstractProxyTestCase
extends PlexusTestCase
extends PlexusInSpringTestCase
{
protected static final String ID_LEGACY_PROXIED = "legacy-proxied";
@ -106,8 +103,6 @@ public abstract class AbstractProxyTestCase
protected MockConfiguration config;
protected BeanFactory factory;
protected void assertChecksums( File expectedFile, String expectedSha1Contents, String expectedMd5Contents )
throws Exception
{
@ -376,19 +371,23 @@ protected File saveTargetedRepositoryConfig( String id, String originalPath, Str
return repoLocation;
}
/**
* {@inheritDoc}
* @see org.codehaus.plexus.spring.PlexusInSpringTestCase#getConfigLocation()
*/
@Override
protected String getSpringConfigLocation()
throws Exception
{
return "org/apache/maven/archiva/proxy/spring-context.xml";
}
@Override
protected void setUp()
throws Exception
{
super.setUp();
factory = new PlexusClassPathXmlApplicationContext(
new String[] {
"classpath*:META-INF/plexus/components.xml",
"classpath*:META-INF/plexus/components-fragment.xml",
"classpath*:META-INF/spring/applicationContext.xml",
"classpath:/org/apache/maven/archiva/proxy/spring-context.xml" } );
config = (MockConfiguration) lookup( ArchivaConfiguration.class.getName(), "mock" );
// Setup source repository (using default layout)

View File

@ -49,9 +49,9 @@ public void testGetWithCacheFailuresOn()
String path = "org/apache/maven/test/get-in-second-proxy/1.0/get-in-second-proxy-1.0.jar";
File expectedFile = new File( managedDefaultDir.getAbsoluteFile(), path );
setupTestableManagedRepository( path );
assertNotExistsInManagedDefaultRepo( expectedFile );
ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
// Configure Repository (usually done within archiva.xml configuration)
@ -72,13 +72,13 @@ public void testGetWithCacheFailuresOn()
File downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
wagonMockControl.verify();
// Second attempt to download same artifact use cache
wagonMockControl.reset();
wagonMockControl.replay();
downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
wagonMockControl.verify();
assertNotDownloaded( downloadedFile );
assertNoTempFiles( expectedFile );
}
@ -91,7 +91,7 @@ public void testGetWithCacheFailuresOff()
setupTestableManagedRepository( path );
assertNotExistsInManagedDefaultRepo( expectedFile );
ArtifactReference artifact = managedDefaultRepository.toArtifactReference( path );
// Configure Repository (usually done within archiva.xml configuration)
@ -118,11 +118,11 @@ public void testGetWithCacheFailuresOff()
wagonMock.get( path, new File( expectedFile.getParentFile(), expectedFile.getName() + ".tmp" ) );
wagonMockControl.setThrowable( new ResourceDoesNotExistException( "resource does not exist." ), 2 );
wagonMockControl.replay();
downloadedFile = proxyHandler.fetchFromProxies( managedDefaultRepository, artifact );
wagonMockControl.verify();
assertNotDownloaded( downloadedFile );
assertNoTempFiles( expectedFile );
}
@ -160,7 +160,7 @@ public void testGetWhenInBothProxiedButFirstCacheFailure()
protected UrlFailureCache lookupUrlFailureCache()
throws Exception
{
UrlFailureCache urlFailureCache = (UrlFailureCache) factory.getBean( "urlFailureCache" );
UrlFailureCache urlFailureCache = (UrlFailureCache) lookup( "urlFailureCache" );
assertNotNull( "URL Failure Cache cannot be null.", urlFailureCache );
return urlFailureCache;
}

View File

@ -72,10 +72,6 @@
<role>org.apache.maven.archiva.policies.PostDownloadPolicy</role>
<field-name>postDownloadPolicies</field-name>
</requirement>
<requirement>
<role>org.apache.maven.archiva.common.spring.SpringFactory</role>
<role-hint>default</role-hint>
</requirement>
<requirement>
<role>org.apache.maven.archiva.repository.scanner.RepositoryContentConsumers</role>
<field-name>consumers</field-name>

View File

@ -4,6 +4,8 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="loggerManager" class="org.codehaus.plexus.logging.console.ConsoleLoggerManager" init-method="initialize"/>
<bean id="urlFailureCache" class="org.apache.maven.archiva.policies.urlcache.DefaultUrlFailureCache">
<constructor-arg ref="cache#url-failures-cache" type="org.codehaus.plexus.cache.Cache"/>
</bean>

View File

@ -14,45 +14,53 @@
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-spring</artifactId>
<version>1.0-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-spring</artifactId>
<version>1.0-SNAPSHOT</version>
<description>
Bridge utility to use plexus components in a SpringFramework context.
</description>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-component-api</artifactId>
<version>1.0-alpha-33</version>
</dependency>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-component-api</artifactId>
<version>1.0-alpha-33</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-log4j-logging</artifactId>
<version>1.1-alpha-3</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-log4j-logging</artifactId>
<version>1.1-alpha-3</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
<developers>
<developer>
<email>nicolas@apache.org</email>
<name>Nicolas De Loof</name>
</developer>
</developers>
</project>

View File

@ -20,6 +20,7 @@
*/
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
@ -31,6 +32,8 @@
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Disposable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.springframework.beans.BeansException;
import org.springframework.beans.SimpleTypeConverter;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanInitializationException;
@ -50,11 +53,11 @@
* </ul>
* If not set, the beanFActory will auto-detect the loggerManager to use by searching for the adequate bean in the
* spring context.
*
*
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
*/
public class PlexusComponentFactoryBean
implements FactoryBean, BeanFactoryAware, InitializingBean, DisposableBean
implements FactoryBean, BeanFactoryAware, DisposableBean
{
private Class role;
@ -68,29 +71,9 @@ public class PlexusComponentFactoryBean
private LoggerManager loggerManager;
private List instances = new LinkedList();
private TypeConverter typeConverter = new SimpleTypeConverter();
public void afterPropertiesSet()
throws Exception
{
if ( loggerManager == null )
{
if ( beanFactory.containsBean( "loggerManager" ) )
{
loggerManager = (LoggerManager) beanFactory.getBean( "loggerManager" );
}
Map loggers = beanFactory.getBeansOfType( LoggerManager.class );
if ( loggers.size() == 1 )
{
loggerManager = (LoggerManager) loggers.values().iterator().next();
}
else
{
throw new BeanInitializationException(
"You must explicitly set a LoggerManager or define a unique one in bean context" );
}
}
}
private List instances = new LinkedList();
public void destroy()
throws Exception
@ -148,6 +131,25 @@ public void doWith( Field field )
}
dependency = map;
}
else if ( Collection.class.isAssignableFrom( field.getType() ) )
{
List list = new LinkedList();
String mask = beanName + '#';
String[] beans = beanFactory.getBeanDefinitionNames();
for ( int i = 0; i < beans.length; i++ )
{
String name = beans[i];
if ( name.startsWith( mask ) )
{
list.add( beanFactory.getBean( name ) );
}
}
if ( beanFactory.containsBean( beanName ) )
{
list.add( beanFactory.getBean( beanName ) );
}
dependency = list;
}
else
{
dependency = beanFactory.getBean( beanName );
@ -155,6 +157,7 @@ public void doWith( Field field )
}
if ( dependency != null )
{
dependency = typeConverter.convertIfNecessary( dependency, field.getType() );
ReflectionUtils.makeAccessible( field );
ReflectionUtils.setField( field, component, dependency );
}
@ -162,17 +165,18 @@ public void doWith( Field field )
}, ReflectionUtils.COPYABLE_FIELDS );
}
if ( component instanceof LogEnabled )
{
( (LogEnabled) component ).enableLogging( getLoggerManager().getLoggerForComponent( role.getName() ) );
}
if ( component instanceof Initializable )
{
( (Initializable) component ).initialize();
}
// TODO handle Initializable, Startable, Stopable, Disposable
if ( component instanceof LogEnabled )
{
( (LogEnabled) component ).enableLogging( loggerManager.getLoggerForComponent( role.getName() ) );
}
// TODO add support for Startable, Stopable -> LifeCycle ?
return component;
}
@ -187,6 +191,28 @@ public boolean isSingleton()
return "per-lookup".equals( instanciationStrategy );
}
private LoggerManager getLoggerManager()
{
if ( loggerManager == null )
{
if ( beanFactory.containsBean( "loggerManager" ) )
{
loggerManager = (LoggerManager) beanFactory.getBean( "loggerManager" );
}
Map loggers = beanFactory.getBeansOfType( LoggerManager.class );
if ( loggers.size() == 1 )
{
loggerManager = (LoggerManager) loggers.values().iterator().next();
}
else
{
throw new BeanInitializationException(
"You must explicitly set a LoggerManager or define a unique one in bean context" );
}
}
return loggerManager;
}
public void setBeanFactory( BeanFactory beanFactory )
throws BeansException
{
@ -233,4 +259,9 @@ public void setRequirements( Map requirements )
this.requirements = requirements;
}
protected void setTypeConverter( TypeConverter typeConverter )
{
this.typeConverter = typeConverter;
}
}

View File

@ -0,0 +1,157 @@
package org.codehaus.plexus.spring;
/*
* 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 java.io.File;
import junit.framework.TestCase;
import org.springframework.context.ConfigurableApplicationContext;
;
/**
* Mimic org.codehaus.plexus.PlexusTestCase as simple replacement for test
* cases.
*
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
*/
public class PlexusInSpringTestCase
extends TestCase
{
private static String basedir;
private ConfigurableApplicationContext applicationContext;
protected void setUp()
throws Exception
{
basedir = getBasedir();
applicationContext =
new PlexusClassPathXmlApplicationContext( new String[] { "classpath*:META-INF/plexus/components.xml",
"classpath*:META-INF/plexus/components-fragment.xml",
"classpath*:" + getPlexusConfigLocation(),
"classpath*:" + getSpringConfigLocation()} );
}
protected String getSpringConfigLocation()
throws Exception
{
return getClass().getName().replace( '.', '/' ) + "-context.xml";
}
protected String getPlexusConfigLocation()
throws Exception
{
return getClass().getName().replace( '.', '/' ) + ".xml";
}
/**
* {@inheritDoc}
*
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown()
throws Exception
{
if ( applicationContext != null )
{
applicationContext.close();
}
}
public static String getBasedir()
{
if ( basedir != null )
{
return basedir;
}
basedir = System.getProperty( "basedir" );
if ( basedir == null )
{
basedir = new File( "" ).getAbsolutePath();
}
return basedir;
}
public String getTestConfiguration()
{
return getTestConfiguration( getClass() );
}
public static String getTestConfiguration( Class clazz )
{
String s = clazz.getName().replace( '.', '/' );
return s.substring( 0, s.indexOf( "$" ) ) + ".xml";
}
public Object lookup( Class role )
{
return lookup( role, null );
}
public Object lookup( Class role, String roleHint )
{
return lookup( role.getName(), roleHint );
}
public Object lookup( String role )
{
return lookup( role, null );
}
public Object lookup( String role, String roleHint )
{
return applicationContext.getBean( PlexusToSpringUtils.buildSpringId( role, roleHint ) );
}
public static File getTestFile( String path )
{
return new File( getBasedir(), path );
}
public static File getTestFile( String basedir,
String path )
{
File basedirFile = new File( basedir );
if ( !basedirFile.isAbsolute() )
{
basedirFile = getTestFile( basedir );
}
return new File( basedirFile, path );
}
public static String getTestPath( String path )
{
return getTestFile( path ).getAbsolutePath();
}
public static String getTestPath( String basedir,
String path )
{
return getTestFile( basedir, path ).getAbsolutePath();
}
}

View File

@ -27,7 +27,7 @@
/**
* Utility method to convert plexus descriptors to spring bean context.
*
*
* @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
* @since 1.1
*/
@ -103,6 +103,11 @@ public static String buildSpringId( String role, String roleHint )
i = 0;
}
String id = Character.toLowerCase( role.charAt( i ) ) + role.substring( i + 1 );
return ( roleHint.length() == 0 || "default".equals( roleHint ) ) ? id : id + '#' + roleHint;
return isDefaultHint( roleHint ) ? id : id + '#' + roleHint;
}
private static boolean isDefaultHint( String roleHint )
{
return roleHint == null || roleHint.length() == 0 || "default".equals( roleHint );
}
}