avalon-framework/ 40755 0 0 0 10051530442 11355 5 ustar 0 0 avalon-framework/api/ 40755 0 0 0 10051530441 12125 5 ustar 0 0 avalon-framework/api/src/ 40755 0 0 0 10051530441 12714 5 ustar 0 0 avalon-framework/api/src/java/ 40755 0 0 0 10051530441 13635 5 ustar 0 0 avalon-framework/api/src/java/org/ 40755 0 0 0 10051530441 14424 5 ustar 0 0 avalon-framework/api/src/java/org/apache/ 40755 0 0 0 10051530441 15645 5 ustar 0 0 avalon-framework/api/src/java/org/apache/avalon/ 40755 0 0 0 10051530441 17125 5 ustar 0 0 avalon-framework/api/src/java/org/apache/avalon/framework/ 40755 0 0 0 10051530442 21123 5 ustar 0 0 avalon-framework/api/src/java/org/apache/avalon/framework/activity/ 40755 0 0 0 10051530442 22757 5 ustar 0 0 avalon-framework/api/src/java/org/apache/avalon/framework/component/ 40755 0 0 0 10051530442 23125 5 ustar 0 0 avalon-framework/api/src/java/org/apache/avalon/framework/configuration/ 40755 0 0 0 10051530442 23772 5 ustar 0 0 avalon-framework/api/src/java/org/apache/avalon/framework/context/ 40755 0 0 0 10051530442 22607 5 ustar 0 0 avalon-framework/api/src/java/org/apache/avalon/framework/logger/ 40755 0 0 0 10051530442 22402 5 ustar 0 0 avalon-framework/api/src/java/org/apache/avalon/framework/parameters/ 40755 0 0 0 10051530442 23266 5 ustar 0 0 avalon-framework/api/src/java/org/apache/avalon/framework/service/ 40755 0 0 0 10051530442 22563 5 ustar 0 0 avalon-framework/api/src/java/org/apache/avalon/framework/thread/ 40755 0 0 0 10051530442 22372 5 ustar 0 0 avalon-framework/api/src/test/ 40755 0 0 0 10051530441 13673 5 ustar 0 0 avalon-framework/api/src/test/org/ 40755 0 0 0 10051530441 14462 5 ustar 0 0 avalon-framework/api/src/test/org/apache/ 40755 0 0 0 10051530441 15703 5 ustar 0 0 avalon-framework/api/src/test/org/apache/avalon/ 40755 0 0 0 10051530441 17163 5 ustar 0 0 avalon-framework/api/src/test/org/apache/avalon/framework/ 40755 0 0 0 10051530441 21160 5 ustar 0 0 avalon-framework/api/src/test/org/apache/avalon/framework/test/ 40755 0 0 0 10051530442 22140 5 ustar 0 0 avalon-framework/docs/ 40755 0 0 0 10051530442 12305 5 ustar 0 0 avalon-framework/impl/ 40755 0 0 0 10051530441 12315 5 ustar 0 0 avalon-framework/impl/src/ 40755 0 0 0 10051530441 13104 5 ustar 0 0 avalon-framework/impl/src/java/ 40755 0 0 0 10051530441 14025 5 ustar 0 0 avalon-framework/impl/src/java/org/ 40755 0 0 0 10051530441 14614 5 ustar 0 0 avalon-framework/impl/src/java/org/apache/ 40755 0 0 0 10051530441 16035 5 ustar 0 0 avalon-framework/impl/src/java/org/apache/avalon/ 40755 0 0 0 10051530441 17315 5 ustar 0 0 avalon-framework/impl/src/java/org/apache/avalon/framework/ 40755 0 0 0 10051530442 21313 5 ustar 0 0 avalon-framework/impl/src/java/org/apache/avalon/framework/component/ 40755 0 0 0 10051530442 23315 5 ustar 0 0 avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/ 40755 0 0 0 10051530442 24162 5 ustar 0 0 avalon-framework/impl/src/java/org/apache/avalon/framework/container/ 40755 0 0 0 10051530442 23275 5 ustar 0 0 avalon-framework/impl/src/java/org/apache/avalon/framework/context/ 40755 0 0 0 10051530441 22776 5 ustar 0 0 avalon-framework/impl/src/java/org/apache/avalon/framework/logger/ 40755 0 0 0 10051530442 22572 5 ustar 0 0 avalon-framework/impl/src/java/org/apache/avalon/framework/service/ 40755 0 0 0 10051530442 22753 5 ustar 0 0 avalon-framework/impl/src/test/ 40755 0 0 0 10051530441 14063 5 ustar 0 0 avalon-framework/impl/src/test/org/ 40755 0 0 0 10051530441 14652 5 ustar 0 0 avalon-framework/impl/src/test/org/apache/ 40755 0 0 0 10051530441 16073 5 ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/ 40755 0 0 0 10051530441 17353 5 ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/ 40755 0 0 0 10051530442 21351 5 ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/component/ 40755 0 0 0 10051530442 23353 5 ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/component/test/ 40755 0 0 0 10051530442 24332 5 ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/configuration/ 40755 0 0 0 10051530441 24217 5 ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/configuration/test/ 40755 0 0 0 10051530442 25177 5 ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/context/ 40755 0 0 0 10051530441 23034 5 ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/context/test/ 40755 0 0 0 10051530441 24013 5 ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/parameters/ 40755 0 0 0 10051530441 23513 5 ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/parameters/test/ 40755 0 0 0 10051530441 24472 5 ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/service/ 40755 0 0 0 10051530441 23010 5 ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/service/test/ 40755 0 0 0 10051530442 23770 5 ustar 0 0 avalon-framework/api/src/java/org/apache/avalon/framework/activity/Disposable.java 100644 0 0 2452 10051530442 26007 0 ustar 0 0 /* * Copyright 1997-2004 The Apache Software Foundation * * Licensed 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. */ package org.apache.avalon.framework.activity; /** * The Disposable interface is used when components need to * deallocate and dispose resources prior to their destruction. * * @author Avalon Development Team * @version CVS $Revision: 1.17 $ $Date: 2004/02/11 14:34:24 $ */ public interface Disposable { /** * The dispose operation is called at the end of a components lifecycle. * This method will be called after Startable.stop() method (if implemented * by component). Components use this method to release and destroy any * resources that the Component owns. */ void dispose(); } avalon-framework/api/src/java/org/apache/avalon/framework/activity/Executable.java 100644 0 0 2530 10051530441 25777 0 ustar 0 0 /* * Copyright 1997-2004 The Apache Software Foundation * * Licensed 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. */ package org.apache.avalon.framework.activity; /** * The Executable can be implemented by components that need to perform * some work. In many respects it is similar to Runnable except that it * also allows an application to throw a non-Runtime Exception. * *
The work done may be short lived (ie a simple task) or it could * be a long running.
* * @author Avalon Development Team * @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:24 $ */ public interface Executable { /** * Execute the action associated with this component. * * @throws Exception if an error occurs */ void execute() throws Exception; } avalon-framework/api/src/java/org/apache/avalon/framework/activity/Initializable.java 100644 0 0 2365 10051530442 26505 0 ustar 0 0 /* * Copyright 1997-2004 The Apache Software Foundation * * Licensed 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. */ package org.apache.avalon.framework.activity; /** * The Initializable interface is used by components that need to * allocate resources prior to them becoming active. * * @author Avalon Development Team * @version CVS $Revision: 1.17 $ $Date: 2004/02/11 14:34:24 $ */ public interface Initializable { /** * Initialize the component. Initialization includes * allocating any resources required throughout the * component's lifecycle. * * @throws Exception if an error occurs */ void initialize() throws Exception; } avalon-framework/api/src/java/org/apache/avalon/framework/activity/Startable.java 100644 0 0 2716 10051530442 25646 0 ustar 0 0 /* * Copyright 1997-2004 The Apache Software Foundation * * Licensed 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. */ package org.apache.avalon.framework.activity; /** * The Startable interface is used when components need to * be "running" to be active. It provides a method through * which components can be "started" and "stopped" without * requiring a thread. * Note that these methods should start the component but return * imediately. * * @author Avalon Development Team * @version CVS $Revision: 1.16 $ $Date: 2004/02/11 14:34:24 $ */ public interface Startable { /** * Starts the component. * * @throws Exception if Component can not be started */ void start() throws Exception; /** * Stops the component. * * @throws Exception if the Component can not be Stopped. */ void stop() throws Exception; } avalon-framework/api/src/java/org/apache/avalon/framework/activity/Suspendable.java 100644 0 0 2326 10051530442 26167 0 ustar 0 0 /* * Copyright 1997-2004 The Apache Software Foundation * * Licensed 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. */ package org.apache.avalon.framework.activity; /** * The Suspendable interface is used when a component * will need to temporarily halt execution of a component. * The execution may be halted so that you can reconfigure/ * recompose/recontextualize component. * * @author Avalon Development Team * @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:24 $ */ public interface Suspendable { /** * Suspends the component. */ void suspend(); /** * Resumes the component. */ void resume(); } avalon-framework/api/src/java/org/apache/avalon/framework/CascadingError.java 100644 0 0 3111 10051530441 24744 0 ustar 0 0 /* * Copyright 1997-2004 The Apache Software Foundation * * Licensed 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. */ package org.apache.avalon.framework; /** * Class from which all exceptions should inherit. * Allows recording of nested exceptions. * * @author Avalon Development Team * @version CVS $Revision: 1.14 $ $Date: 2004/02/11 14:34:24 $ */ public class CascadingError extends Error implements CascadingThrowable { private final Throwable m_throwable; /** * Construct a newCascadingError
instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public CascadingError( final String message, final Throwable throwable )
{
super( message );
m_throwable = throwable;
}
/**
* Retrieve root cause of the exception.
*
* @return the root cause
*/
public final Throwable getCause()
{
return m_throwable;
}
}
avalon-framework/api/src/java/org/apache/avalon/framework/CascadingException.java 100644 0 0 3653 10051530441 25624 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework;
/**
* Class from which all exceptions should inherit.
* Allows recording of nested exceptions.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:24 $
*/
public class CascadingException
extends Exception
implements CascadingThrowable
{
/**
* The Throwable that caused this exception to be thrown.
*/
private final Throwable m_throwable;
/**
* Construct a new CascadingException
instance.
*
* @param message The detail message for this exception.
*/
public CascadingException( final String message )
{
this( message, null );
}
/**
* Construct a new CascadingException
instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public CascadingException( final String message, final Throwable throwable )
{
super( message );
m_throwable = throwable;
}
/**
* Retrieve root cause of the exception.
*
* @return the root cause
*/
public final Throwable getCause()
{
return m_throwable;
}
}
avalon-framework/api/src/java/org/apache/avalon/framework/CascadingRuntimeException.java 100644 0 0 3165 10051530442 27167 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework;
/**
* Class from which all exceptions should inherit.
* Allows recording of nested exceptions.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.14 $ $Date: 2004/02/11 14:34:24 $
*/
public class CascadingRuntimeException
extends RuntimeException
implements CascadingThrowable
{
private final Throwable m_throwable;
/**
* Construct a new CascadingRuntimeException
instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public CascadingRuntimeException( final String message, final Throwable throwable )
{
super( message );
m_throwable = throwable;
}
/**
* Retrieve root cause of the exception.
*
* @return the root cause
*/
public final Throwable getCause()
{
return m_throwable;
}
}
avalon-framework/api/src/java/org/apache/avalon/framework/CascadingThrowable.java 100644 0 0 2164 10051530441 25611 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework;
/**
* Interface which all cascadign throwables should implement.
* Allows recording of nested exceptions.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:24 $
*/
public interface CascadingThrowable
{
/**
* Returns the root cause of this Throwable
.
*
* @return a Throwable
*/
Throwable getCause();
}
avalon-framework/api/src/java/org/apache/avalon/framework/component/Component.java 100644 0 0 5574 10051530441 26041 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.component;
/**
* This interface identifies classes that can be used as Components
* by a Composable
.
*
*
* The contract surrounding the Component
is that it is
* used, but not a user. When a class implements this interface, it
* is stating that other entities may use that class.
*
* A Component
is the basic building block of the Avalon Framework.
* When a class implements this interface, it allows itself to be
* managed by a ComponentManager
and used by an outside
* element called a Composable
. The Composable
* must know what type of Component
it is accessing, so
* it will re-cast the Component
into the type it needs.
*
* In order for a Component
to be useful you must either
* extend this interface, or implement this interface in conjunction
* with one that actually has methods. The new interface is the contract
* with the Composable
that this is a particular type of
* component, and as such it can perform those functions on that type
* of component.
*
* For example, we want a component that performs a logging function
* so we extend the Component
to be a LoggingComponent
.
*
* interface LoggingComponent * extends Component * { * log(String message); * } ** *
* Now all Composable
s that want to use this type of component,
* will re-cast the Component
into a LoggingComponent
* and the Composable
will be able to use the log
* method.
*
* Deprecated:
* Deprecated without replacement. Should only be used while migrating away
* from a system based on Composable/ComponentManager. A generic java.lang.Object
* can be used as a replacement.
*
*
* Deprecated: * Use {@link org.apache.avalon.framework.service.ServiceException} instead. * *
* * @author Avalon Development Team * @version CVS $Revision: 1.22 $ $Date: 2004/02/11 14:34:24 $ */ public class ComponentException extends CascadingException { private final String m_key; /** * Construct a newComponentException
instance.
* @param key the lookup key
* @param message the exception message
* @param throwable the throwable
*/
public ComponentException( final String key,
final String message,
final Throwable throwable )
{
super( message, throwable );
m_key = key;
}
/**
* Construct a new ComponentException
instance.
*
* @deprecated use the String, String, Throwable version to record the role
* @param message the exception message
* @param throwable the throwable
*/
public ComponentException( final String message, final Throwable throwable )
{
this( null, message, throwable );
}
/**
* Construct a new ComponentException
instance.
*
* @deprecated use the String, String version to record the role
* @param message the exception message
*/
public ComponentException( final String message )
{
this( null, message, null );
}
/**
* Construct a new ComponentException
instance.
* @param key the lookup key
* @param message the exception message
*/
public ComponentException( final String key, final String message )
{
this( key, message, null );
}
/**
* Get the key which let to the exception. May be null.
*
* @return The key which let to the exception.
*/
public final String getKey()
{
return m_key;
}
/**
* Get the key which let to the exception. May be null.
*
* @return The key which let to the exception.
* @deprecated Use getKey instead
*/
public final String getRole()
{
return getKey();
}
/**
* Return a message describing the exception.
*
* @return exception message.
*/
public String getMessage()
{
if( m_key == null )
{
return super.getMessage();
}
else
{
return super.getMessage() + " (key [" + m_key + "])";
}
}
}
avalon-framework/api/src/java/org/apache/avalon/framework/component/ComponentManager.java 100644 0 0 7631 10051530442 27331 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.component;
/**
* A ComponentManager
selects Component
s based on a
* role. The contract is that all the Component
s implement the
* differing roles and there is one Component
per role. If you
* need to select on of many Component
s that implement the same
* role, then you need to use a ComponentSelector
. Roles are
* usually the full interface name.
*
* * A role is better understood by the analogy of a play. There are many * different roles in a script. Any actor or actress can play any given part * and you get the same results (phrases said, movements made, etc.). The exact * nuances of the performance is different. *
* ** Below is a list of things that might be considered the different roles: *
* *
* The ComponentManager
does not specify the methodology of
* getting the Component
, merely the interface used to get it.
* Therefore the ComponentManager
can be implemented with a
* factory pattern, an object pool, or a simple Hashtable.
*
* Deprecated: * Use {@link org.apache.avalon.framework.service.ServiceManager} instead. * *
* * @see org.apache.avalon.framework.component.Component * @see org.apache.avalon.framework.component.Composable * @see org.apache.avalon.framework.component.ComponentSelector * * @author Avalon Development Team * @version CVS $Revision: 1.21 $ $Date: 2004/02/11 14:34:24 $ */ public interface ComponentManager { /** * Get theComponent
associated with the given key. For
* instance, If the ComponentManager
had a
* LoggerComponent
stored and referenced by key, I would use
* the following call:
* * try * { * LoggerComponent log; * myComponent = (LoggerComponent) m_manager.lookup(LoggerComponent.ROLE); * } * catch (...) * { * ... * } ** * @param key The key name of the
Component
to retrieve.
* @return the desired component
* @throws ComponentException if an error occurs
*/
Component lookup( String key )
throws ComponentException;
/**
* Check to see if a Component
exists for a key.
*
* @param key a string identifying the key to check.
* @return True if the component exists, False if it does not.
*/
boolean hasComponent( String key );
/**
* Return the Component
when you are finished with it. This
* allows the ComponentManager
to handle the End-Of-Life Lifecycle
* events associated with the Component. Please note, that no Exceptions
* should be thrown at this point. This is to allow easy use of the
* ComponentManager system without having to trap Exceptions on a release.
*
* @param component The Component we are releasing.
*/
void release( Component component );
}
avalon-framework/api/src/java/org/apache/avalon/framework/component/ComponentSelector.java 100644 0 0 7651 10051530441 27540 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.component;
/**
* A ComponentSelector
selects Component
s based on a
* hint. The contract is that all the Component
s implement the
* same role.
*
* * A role is better understood by the analogy of a play. There are many * different roles in a script. Any actor or actress can play any given part * and you get the same results (phrases said, movements made, etc.). The exact * nuances of the performance is different. *
* ** Below is a list of things that might be considered the same role: *
* *
* The ComponentSelector
does not specify the methodology of
* getting the Component
, merely the interface used to get it.
* Therefore the ComponentSelector
can be implemented with a
* factory pattern, an object pool, or a simple Hashtable.
*
* Deprecated: * Use {@link org.apache.avalon.framework.service.ServiceSelector} instead. * *
* * @see org.apache.avalon.framework.component.Component * @see org.apache.avalon.framework.component.Composable * @see org.apache.avalon.framework.component.ComponentManager * * @author Avalon Development Team * @version CVS $Revision: 1.21 $ $Date: 2004/02/11 14:34:24 $ */ public interface ComponentSelector extends Component { /** * Select theComponent
associated with the given hint.
* For instance, If the ComponentSelector
has a
* Generator
stored and referenced by a URL, I would use the
* following call:
*
* * try * { * Generator input; * input = (Generator)selector.select( new URL("foo://demo/url") ); * } * catch (...) * { * ... * } ** * @param hint A hint to retrieve the correct
Component
.
* @return the desired component
* @throws ComponentException If the given role is not associated
* with a Component
, or a
* Component
instance cannot
* be created.
*/
Component select( Object hint )
throws ComponentException;
/**
* Check to see if a Component
exists for a hint.
*
* @param hint a string identifying the role to check.
* @return True if the component exists, False if it does not.
*/
boolean hasComponent( Object hint );
/**
* Return the Component
when you are finished with it. This
* allows the ComponentSelector
to handle the End-Of-Life Lifecycle
* events associated with the Component. Please note, that no Exceptions
* should be thrown at this point. This is to allow easy use of the
* ComponentSelector system without having to trap Exceptions on a release.
*
* @param component The Component we are releasing.
*/
void release( Component component );
}
avalon-framework/api/src/java/org/apache/avalon/framework/component/Composable.java 100644 0 0 4307 10051530442 26155 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.component;
/**
* A Composable
class is one that needs to connect to software
* components using a "role" abstraction, thus not depending on particular
* implementations but on behavioral interfaces.
*
*
* The contract surrounding a Composable
is that it is a user.
* The Composable
is able to use Components
managed
* by the ComponentManager
it was initialized with. As part
* of the contract with the system, the instantiating entity must call
* the compose
method before the Composable
* can be considered valid.
*
* Deprecated: * Use {@link org.apache.avalon.framework.service.Serviceable} instead. * *
* * @author Avalon Development Team * @version CVS $Revision: 1.21 $ $Date: 2004/02/11 14:34:24 $ */ public interface Composable { /** * Pass theComponentManager
to the composer
.
* The Composable
implementation should use the specified
* ComponentManager
to acquire the components it needs for
* execution.
*
* @param componentManager The ComponentManager
which this
* Composable
uses. Must not be null
.
* @throws ComponentException if an error occurs
*/
void compose( ComponentManager componentManager )
throws ComponentException;
}
avalon-framework/api/src/java/org/apache/avalon/framework/component/Recomposable.java 100644 0 0 3453 10051530442 26505 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.component;
/**
* Extends composer to allow recomposing.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.22 $ $Date: 2004/02/11 14:34:24 $
* @deprecated Deprecated with no replacement. The Recomposable interface is a legacy
* interface with no concrete contracts. Rather than copy the design mistake
* to the "service" package, we no longer support this class.
*/
public interface Recomposable
extends Composable
{
/**
* Repass the ComponentManager
to the composer
.
* The Composable
implementation should use the specified
* ComponentManager
to acquire the components it needs for
* execution. It should also drop references to any components it
* retrieved from old ComponentManager.
*
* @param componentManager The ComponentManager
which this
* Composable
uses.
* @throws ComponentException if an error occurs
*/
void recompose( ComponentManager componentManager )
throws ComponentException;
}
avalon-framework/api/src/java/org/apache/avalon/framework/configuration/Configurable.java 100644 0 0 3132 10051530442 27331 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration;
/**
* This interface should be implemented by classes that need to be
* configured with custom parameters before initialization.
* Configurable
is that the
* instantiating entity must call the configure
* method before it is valid.
* Configuration
to the Configurable
* class.
*
* @param configuration the class configurations. Must not be null
.
* @throws ConfigurationException if an error occurs
*/
void configure( Configuration configuration )
throws ConfigurationException;
}
avalon-framework/api/src/java/org/apache/avalon/framework/configuration/Configuration.java 100644 0 0 45252 10051530442 27571 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration;
/**
* Configuration
is a interface encapsulating a configuration node
* used to retrieve configuration values.
*
* * This is a "read only" interface preventing applications from modifying their * own configurations. Once it is created, the information never changes. *
*
* The data model is a subset of XML's; a single-rooted hierarchical tree where each
* node can contain multiple attributes, and leaf nodes can also
* contain a value. Reflecting this, Configuration
s are
* usually built from an XML file by the {@link DefaultConfigurationBuilder}
* class, or directly by a SAX parser using a {@link SAXConfigurationHandler} or
* {@link NamespacedSAXConfigurationHandler} event handler.
*
* Since version 4.1, each Configuration
node has a namespace
* associated with it, in the form of a string, accessible through {@link
* #getNamespace}. If no namespace is present, getNamespace
will
* return blank (""). See {@link DefaultConfigurationBuilder} for details on how
* XML namespaces are mapped to Configuration
namespaces.
*
* As an example, consider two Configuration
s (with and without
* namespaces) built from this XML:
*
* <my-system version="1.3" xmlns:doc="http://myco.com/documentation"> * <doc:desc>This is a highly fictitious config file</doc:desc> * <widget name="fooWidget" initOrder="1" threadsafe="true"/> * </my-system> **
If namespace support is enabled (eg through {@link
* DefaultConfigurationBuilder#DefaultConfigurationBuilder(boolean) new
* DefaultConfigurationBuilder(true)}), then the xmlns:doc
element
* will not translate into a Configuration attribute, and the
* doc:desc
element will become a Configuration
node
* with name "desc" and namespace "http://myco.com/documentation". The
* widget
element will have namespace "".
*
If namespace support is disabled (the default for {@link
* DefaultConfigurationBuilder}), the above XML will translate directly to
* Configuration
nodes. The my-system
node will have
* an attribute named "xmlns:doc", and a child called "doc:desc".
*
* Assuming the Configuration
object is named conf
,
* here is how the data could be retrieved:
*
Code | No namespaces | With namespaces |
---|---|---|
* conf.{@link #getName getName}() | my-system | |
* conf.{@link #getAttributeNames getAttributeNames}().length
* | 2 | 1 |
* conf.{@link #getChildren getChildren}().length
* | 2 | |
* conf.{@link #getAttributeAsFloat getAttributeAsFloat}("version")
* | 1.3 | |
* conf.{@link #getChild getChild}("widget").{@link #getAttribute getAttribute}("name")
* | fooWidget | |
* conf.{@link #getChild getChild}("widget")
* .{@link #getAttributeAsBoolean getAttributeAsBoolean}("threadsafe") |
* true | |
* conf.{@link #getChild getChild}("widget").{@link #getLocation getLocation}()
* | file:///home/jeff/tmp/java/avalon/src/java/new.xconf:4:60 | |
* conf.{@link #getChild getChild}("desc").{@link #getName getName}()
* | desc (see {@link #getChild(String)}) | desc |
* conf.{@link #getChild getChild}("doc:desc").{@link #getName getName}()
* | doc:desc | doc:desc (see {@link #getChild(String)}) |
* conf.{@link #getChild getChild}("desc").{@link #getValue getValue}()
* | {@link ConfigurationException} | This is a highly fictitious config file |
* conf.{@link #getChild getChild}("doc:desc").{@link #getValue getValue}()
* | This is a highly fictitious config file | {@link ConfigurationException} |
* conf.{@link #getChild getChild}("desc").{@link #getNamespace getNamespace}()
* | http://myco.com/documentation" |
* Type-safe utility methods are provided for retrieving attribute and element
* values as String
, int
, long
,
* float
and boolean
.
*
* Currently, the configuration tree can only be traversed one node at a time, * eg., through {@link #getChild getChild("foo")} or {@link #getChildren}. In * a future release, it may be possible to access child nodes with an XPath-like * syntax. *
** Checking for the existence of an attribute can be done as follows: *
**String value = conf.getAttribute( "myAttribute", null ); * if ( null == value ) * { * // Do the processing applicable if the attribute isn't present. * } ** * @author Avalon Development Team * @version CVS $Revision: 1.29 $ $Date: 2004/02/11 14:34:24 $ */ public interface Configuration { /** * Return the name of the node. * * @return name of the
Configuration
node.
*/
String getName();
/**
* Return a string describing location of Configuration.
* Location can be different for different mediums (ie "file:line" for normal XML files or
* "table:primary-key" for DB based configurations);
*
* @return a string describing location of Configuration
*/
String getLocation();
/**
* Returns a string indicating which namespace this Configuration node
* belongs to.
*
* * What this returns is dependent on the configuration file and the * Configuration builder. If the Configuration builder does not support * namespaces, this method will return a blank string. *
*In the case of {@link DefaultConfigurationBuilder}, the namespace will * be the URI associated with the XML element. Eg.,:
** <foo xmlns:x="http://blah.com"> * <x:bar/> * </foo> **
The namespace of foo
will be "", and the namespace of
* bar
will be "http://blah.com".
Configuration
instance encapsulating the
* specified child node.
*
* If no such child node exists, an empty Configuration
will be
* returned, allowing constructs such as
* conf.getChild("foo").getChild("bar").getChild("baz").{@link
* #getValue(String) getValue}("default");
*
* If you wish to get a null
return when no element is present,
* use {@link #getChild(String, boolean) getChild("foo", false)}.
*
Configuration
instance encapsulating the specified
* child node.
*
* @param child The name of the child node.
* @param createNew If true
, a new Configuration
* will be created and returned if the specified child does not exist. If
* false
, null
will be returned when the specified
* child doesn't exist.
* @return Configuration
*/
Configuration getChild( String child, boolean createNew );
/**
* Return an Array
of Configuration
* elements containing all node children. The array order will reflect the
* order in the source config file.
*
* @return All child nodes
*/
Configuration[] getChildren();
/**
* Return an Array
of Configuration
* elements containing all node children with the specified name. The array
* order will reflect the order in the source config file.
*
* @param name The name of the children to get.
* @return The child nodes with name name
*/
Configuration[] getChildren( String name );
/**
* Return an array of all attribute names.
*
* The order of attributes in this array can not be relied on. As
* with XML, a Configuration
's attributes are an
* unordered set. If your code relies on order, eg
* conf.getAttributeNames()[0], then it is liable to break if a
* different XML parser is used.
*
String[]
value
*/
String[] getAttributeNames();
/**
* Return the value of specified attribute.
*
* @param paramName The name of the parameter you ask the value of.
* @return String value of attribute.
* @throws ConfigurationException If no attribute with that name exists.
*/
String getAttribute( String paramName ) throws ConfigurationException;
/**
* Return the int
value of the specified attribute contained
* in this node.
*
* @param paramName The name of the parameter you ask the value of.
* @return int value of attribute
* @throws ConfigurationException If no parameter with that name exists.
* or if conversion to int
fails.
*
*/
int getAttributeAsInteger( String paramName ) throws ConfigurationException;
/**
* Returns the value of the attribute specified by its name as a
* long
.
*
* @param name The name of the parameter you ask the value of.
* @return long value of attribute
* @throws ConfigurationException If no parameter with that name exists.
* or if conversion to long
fails.
*/
long getAttributeAsLong( String name ) throws ConfigurationException;
/**
* Return the float
value of the specified parameter contained
* in this node.
*
* @param paramName The name of the parameter you ask the value of.
* @return float value of attribute
* @throws ConfigurationException If no parameter with that name exists.
* or if conversion to float
fails.
*/
float getAttributeAsFloat( String paramName ) throws ConfigurationException;
/**
* Return the boolean
value of the specified parameter contained
* in this node.
*
* @param paramName The name of the parameter you ask the value of.
* @return boolean value of attribute
* @throws ConfigurationException If no parameter with that name exists.
* or if conversion to boolean
fails.
*/
boolean getAttributeAsBoolean( String paramName ) throws ConfigurationException;
/**
* Return the String
value of the node.
*
* @return the value of the node.
* @throws ConfigurationException if an error occurs
*/
String getValue() throws ConfigurationException;
/**
* Return the int
value of the node.
*
* @return the value of the node.
*
* @throws ConfigurationException If conversion to int
fails.
*/
int getValueAsInteger() throws ConfigurationException;
/**
* Return the float
value of the node.
*
* @return the value of the node.
* @throws ConfigurationException If conversion to float
fails.
*/
float getValueAsFloat() throws ConfigurationException;
/**
* Return the boolean
value of the node.
*
* @return the value of the node.
* @throws ConfigurationException If conversion to boolean
fails.
*/
boolean getValueAsBoolean() throws ConfigurationException;
/**
* Return the long
value of the node.
*
* @return the value of the node.
* @throws ConfigurationException If conversion to long
fails.
*/
long getValueAsLong() throws ConfigurationException;
/**
* Returns the value of the configuration element as a String
.
* If the configuration value is not set, the default value will be
* used.
*
* @param defaultValue The default value desired.
* @return String value of the Configuration
, or default
* if none specified.
*/
String getValue( String defaultValue );
/**
* Returns the value of the configuration element as an int
.
* If the configuration value is not set, the default value will be
* used.
*
* @param defaultValue The default value desired.
* @return int value of the Configuration
, or default
* if none specified.
*/
int getValueAsInteger( int defaultValue );
/**
* Returns the value of the configuration element as a long
.
* If the configuration value is not set, the default value will be
* used.
*
* @param defaultValue The default value desired.
* @return long value of the Configuration
, or default
* if none specified.
*/
long getValueAsLong( long defaultValue );
/**
* Returns the value of the configuration element as a float
.
* If the configuration value is not set, the default value will be
* used.
*
* @param defaultValue The default value desired.
* @return float value of the Configuration
, or default
* if none specified.
*/
float getValueAsFloat( float defaultValue );
/**
* Returns the value of the configuration element as a boolean
.
* If the configuration value is not set, the default value will be
* used.
*
* @param defaultValue The default value desired.
* @return boolean value of the Configuration
, or default
* if none specified.
*/
boolean getValueAsBoolean( boolean defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* String
, or the default value if no attribute by
* that name exists or is empty.
*
* @param name The name of the attribute you ask the value of.
* @param defaultValue The default value desired.
* @return String value of attribute. It will return the default
* value if the named attribute does not exist, or if
* the value is not set.
*/
String getAttribute( String name, String defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* int
, or the default value if no attribute by
* that name exists or is empty.
*
* @param name The name of the attribute you ask the value of.
* @param defaultValue The default value desired.
* @return int value of attribute. It will return the default
* value if the named attribute does not exist, or if
* the value is not set.
*/
int getAttributeAsInteger( String name, int defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* long
, or the default value if no attribute by
* that name exists or is empty.
*
* @param name The name of the attribute you ask the value of.
* @param defaultValue The default value desired.
* @return long value of attribute. It will return the default
* value if the named attribute does not exist, or if
* the value is not set.
*/
long getAttributeAsLong( String name, long defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* float
, or the default value if no attribute by
* that name exists or is empty.
*
* @param name The name of the attribute you ask the value of.
* @param defaultValue The default value desired.
* @return float value of attribute. It will return the default
* value if the named attribute does not exist, or if
* the value is not set.
*/
float getAttributeAsFloat( String name, float defaultValue );
/**
* Returns the value of the attribute specified by its name as a
* boolean
, or the default value if no attribute by
* that name exists or is empty.
*
* @param name The name of the attribute you ask the value of.
* @param defaultValue The default value desired.
* @return boolean value of attribute. It will return the default
* value if the named attribute does not exist, or if
* the value is not set.
*/
boolean getAttributeAsBoolean( String name, boolean defaultValue );
}
avalon-framework/api/src/java/org/apache/avalon/framework/configuration/ConfigurationException.java 100644 0 0 6267 10051530442 31433 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration;
import org.apache.avalon.framework.CascadingException;
/**
* Thrown when a Configurable
component cannot be configured
* properly, or if a value cannot be retrieved properly.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.14 $ $Date: 2004/02/11 14:34:24 $
*/
public class ConfigurationException
extends CascadingException
{
private final Configuration m_config;
/**
* Construct a new ConfigurationException
instance.
*
* @param config The offending configuration object
*/
public ConfigurationException( final Configuration config )
{
this( "Bad configuration: " + config.toString(), config );
}
/**
* Construct a new ConfigurationException
instance.
*
* @param message The detail message for this exception.
*/
public ConfigurationException( final String message )
{
this( message, (Configuration) null );
}
/**
* Construct a new ConfigurationException
instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public ConfigurationException( final String message, final Throwable throwable )
{
this( message, null, throwable );
}
/**
* Construct a new ConfigurationException
instance.
*
* @param message The detail message for this exception.
* @param config The configuration object
*/
public ConfigurationException( final String message, final Configuration config )
{
this( message, config, null );
}
/**
* Construct a new ConfigurationException
instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public ConfigurationException( final String message, final Configuration config, final Throwable throwable )
{
super( message, throwable );
m_config = config;
}
public Configuration getOffendingConfiguration()
{
return m_config;
}
public String getMessage()
{
StringBuffer message = new StringBuffer(super.getMessage());
if (null != m_config)
{
message.append("@");
message.append(m_config.getLocation());
}
return message.toString();
}
}
avalon-framework/api/src/java/org/apache/avalon/framework/configuration/Reconfigurable.java 100644 0 0 2406 10051530442 27663 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration;
/**
* Extends Configurable
to allow reconfiguration at runtime.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.18 $ $Date: 2004/02/11 14:34:24 $
*/
public interface Reconfigurable
extends Configurable
{
/**
* Describe reconfigure
method here.
*
* @param configuration a Configuration
value
* @throws ConfigurationException if an error occurs
*/
void reconfigure( Configuration configuration )
throws ConfigurationException;
}
avalon-framework/api/src/java/org/apache/avalon/framework/context/Context.java 100644 0 0 12557 10051530441 25224 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.context;
/**
* * The context is the interface through which the component and its * container communicate. *
* ** Note: In the text below there are several requirements that a * component may set up for a container. It is understood that a container * does not have to satisfy those requirements in order to be Avalon-compliant. * If a component says "I require X to run" a container may reply with "I don't * have any X, so I'm not running you". The requirements here are the maximum * that a component may ask for, not the minimum a container must deliver. * However, a container should document what it is and isn't capable of * delivering. *
* *Each Container-Component relationship involves defining a contract * between the two entities. A Context contract is defined by (1) an optional * target class, and (2) a set of context entries. *
* *
* The optional target class is an interface, called T
below.
* It is required that the component should be able to perform
* the following operation:
*
public void contextualize( Context context )
* throws ContextException
* {
* T tContext = (T) context;
* }
*
*
* The container may choose any method to supply the component
* with a context instance cast-able to T
.
*
* There is no requirement for T
to extend the Context
* interface.
*
* Warning: A component that specifies this requirement will not * be as portable as one that doesn't. Few containers * support it. It is therefore discouraged for components * to require a castable context. *
*
* The second part of the context contract defines the set
* of entries the component can access via the Context.get()
* method, where an entry consists of the key passed to get()
* and the expected return type (the class or interface).
* Optionally, an alias for the key name can be specified. The
* contract associated with a particular entry is defined in the
* container documentation.
*
* The class/interface T
above may also have associated
* meta-info that specifies entries, in which case these entries must
* be supplied by the container in addition to any entries the
* component itself requires.
*
* See: Context Meta-Info * Specification *
* ** Standard Avalon context entries, their keys, types and and * associated semantics are defined under the framework standard * attributes table. *
* ** See: * Avalon Standard Context Entries Specification *
* ** When a component specifies: *
* * <entry key="avalon:work" type="java.io.File"/>
*
* * It should be able to do: *
* * File workDirectory = (File) context.get( "avalon:work" );
*
* * in order to obtain the value. *
* ** When a component specifies: *
* * <entry alias="work" key="avalon:work" type="java.io.File"/>
*
* * It should be able to do: *
* * File workDirectory = (File) context.get( "work" );
* ContextException
instance.
*
* @param message The detail message for this exception.
*/
public ContextException( final String message )
{
this( message, null );
}
/**
* Construct a new ContextException
instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public ContextException( final String message, final Throwable throwable )
{
super( message, throwable );
}
}
avalon-framework/api/src/java/org/apache/avalon/framework/context/Contextualizable.java 100644 0 0 2647 10051530442 27075 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.context;
/**
* This inteface should be implemented by components that need
* a Context to work. Context contains runtime generated object
* provided by the Container to this Component.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:25 $
*/
public interface Contextualizable
{
/**
* Pass the Context to the component.
* This method is called after the Loggable.setLogger() (if present)
* method and before any other method.
*
* @param context the context. Must not be null
.
* @throws ContextException if context is invalid
*/
void contextualize( Context context )
throws ContextException;
}
avalon-framework/api/src/java/org/apache/avalon/framework/context/Recontextualizable.java 100644 0 0 2622 10051530441 27414 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.context;
/**
* Extends Contextualizable to allow recontextualizing.
* This allows a component to re-receive it's context if
* container environment has changed.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.17 $ $Date: 2004/02/11 14:34:25 $
*/
public interface Recontextualizable
extends Contextualizable
{
/**
* Pass the new Context to the component.
* This method is usually called when component is suspended via use of
* Suspendable.suspend() method.
*
* @param context the context
* @throws ContextException if context is invalid
*/
void recontextualize( Context context )
throws ContextException;
}
avalon-framework/api/src/java/org/apache/avalon/framework/context/Resolvable.java 100644 0 0 2365 10051530442 25653 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.context;
/**
* This interface is used to indicate objects that need to be
* resolved in some particular context.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.17 $ $Date: 2004/02/11 14:34:25 $
*/
public interface Resolvable
{
/**
* Resolve a object to a value.
*
* @param context the contextwith respect which to resolve
* @return the resolved object
* @throws ContextException if an error occurs
*/
Object resolve( Context context )
throws ContextException;
}
avalon-framework/api/src/java/org/apache/avalon/framework/Enum.java 100644 0 0 12100 10051530442 23001 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework;
import java.util.Map;
/**
* Basic enum class for type-safe enums. Should be used as an abstract base. For example:
*
* * import org.apache.avalon.framework.Enum; * * public final class Color extends Enum { * public static final Color RED = new Color( "Red" ); * public static final Color GREEN = new Color( "Green" ); * public static final Color BLUE = new Color( "Blue" ); * * private Color( final String color ) * { * super( color ); * } * } ** * If further operations, such as iterating over all items, are required, the * {@link #Enum(String, Map)} constructor can be used to populate a
Map
, from which
* further functionality can be derived:
* * public final class Color extends Enum { * static final Map map = new HashMap(); * * public static final Color RED = new Color( "Red", map ); * public static final Color GREEN = new Color( "Green", map ); * public static final Color BLUE = new Color( "Blue", map ); * * private Color( final String color, final Map map ) * { * super( color, map ); * } * * public static Iterator iterator() * { * return map.values().iterator(); * } * } ** *
* NOTE: between 4.0 and 4.1, the constructors' access has been changed
* from public
to protected
. This is to prevent users
* of the Enum breaking type-safety by defining new Enum items. All Enum items
* should be defined in the Enum class, as shown above.
*
* Note: access changed from public
to
* protected
after 4.0. See class description.
*
* Note: access changed from public
to
* protected
after 4.0. See class description.
*
Map
, to which will be added a pointer to the newly constructed
* object.
*/
protected Enum( final String name, final Map map )
{
m_name = name;
if( null != map )
{
map.put( name, this );
}
}
/**
* Tests for equality. Two Enum:s are considered equal
* if they are of the same class and have the same names.
* The method is also declared final - I (LSutic) did this to
* allow the JIT to inline it easily.
*
* @param o the other object
* @return the equality status
*/
public final boolean equals( Object o )
{
if( this == o )
return true;
if( !(o instanceof Enum) )
return false;
final Enum enum = (Enum)o;
if( !getClass().equals( enum.getClass() ) )
return false;
if( m_name != null ? !m_name.equals( enum.m_name ) : enum.m_name != null )
return false;
return true;
}
public int hashCode()
{
int result;
result = (m_name != null ? m_name.hashCode() : 0);
result = 29 * result + getClass().hashCode();
return result;
}
/**
* Returns a hash code value for the object.
*
* @return a hash code value for this object
*/
/*public int hashCode()
{
return m_name.hashCode() ^ this.getClass().getName().hashCode();
}*/
/**
* Retrieve the name of this Enum item, set in the constructor.
* @return the name String
of this Enum item
*/
public final String getName()
{
return m_name;
}
/**
* Human readable description of this Enum item. For use when debugging.
* @return String in the form type[name]
, eg.:
* Color[Red]
.
*/
public String toString()
{
return getClass().getName() + "[" + m_name + "]";
}
}
avalon-framework/api/src/java/org/apache/avalon/framework/logger/AbstractLogEnabled.java 100644 0 0 5746 10051530442 27036 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.logger;
/**
* Utility class to allow easy construction of components that will perform
* logging.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.4 $ $Date: 2004/02/11 14:34:25 $
*/
public abstract class AbstractLogEnabled
implements LogEnabled
{
///Base Logger instance
private Logger m_logger;
/**
* Set the components logger.
*
* @param logger the logger
*/
public void enableLogging( final Logger logger )
{
m_logger = logger;
}
/**
* Helper method to allow sub-classes to aquire logger.
* This method exists rather than exposing a member variable
* because it protects other users against future changes. It
* also means they do not have to use our naming convention.
*
* There is no performance penalty as this is a final method * and will be inlined by the JVM.
* * @return the Logger */ protected final Logger getLogger() { return m_logger; } /** * Helper method to setup other components with same logger. * * @param component the component to pass logger object to */ protected void setupLogger( final Object component ) { setupLogger( component, (String)null ); } /** * Helper method to setup other components with logger. * The logger has the subcategory of this components logger. * * @param component the component to pass logger object to * @param subCategory the subcategory to use (may be null) */ protected void setupLogger( final Object component, final String subCategory ) { Logger logger = m_logger; if( null != subCategory ) { logger = m_logger.getChildLogger( subCategory ); } setupLogger( component, logger ); } /** * Helper method to setup other components with logger. * * @param component the component to pass logger object to * @param logger the Logger */ protected void setupLogger( final Object component, final Logger logger ) { if( component instanceof LogEnabled ) { ( (LogEnabled)component ).enableLogging( logger ); } } } avalon-framework/api/src/java/org/apache/avalon/framework/logger/LogEnabled.java 100644 0 0 2163 10051530442 25340 0 ustar 0 0 /* * Copyright 1997-2004 The Apache Software Foundation * * Licensed 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. */ package org.apache.avalon.framework.logger; /** * Components that need to log can implement this interface to * be provided Loggers. * * @author Avalon Development Team * @version CVS $Revision: 1.16 $ $Date: 2004/02/11 14:34:25 $ */ public interface LogEnabled { /** * Provide component with a logger. * * @param logger the logger. Must not benull
.
*/
void enableLogging( Logger logger );
}
avalon-framework/api/src/java/org/apache/avalon/framework/logger/Loggable.java 100644 0 0 2220 10051530442 25052 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.logger;
/**
* Components that need to log can implement this interface to
* be provided Loggers.
*
* @deprecated Use {@link LogEnabled} instead.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.18 $ $Date: 2004/02/11 14:34:25 $
*/
public interface Loggable
{
/**
* Provide component with a logger.
*
* @param logger the logger
*/
void setLogger( org.apache.log.Logger logger );
}
avalon-framework/api/src/java/org/apache/avalon/framework/logger/Logger.java 100644 0 0 7471 10051530441 24571 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.logger;
/**
* This is a facade for the different logging subsystems.
* It offers a simplified interface that follows IOC patterns
* and a simplified priority/level/severity abstraction.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.16 $ $Date: 2004/02/11 14:34:25 $
*/
public interface Logger
{
/**
* Log a debug message.
*
* @param message the message
*/
void debug( String message );
/**
* Log a debug message.
*
* @param message the message
* @param throwable the throwable
*/
void debug( String message, Throwable throwable );
/**
* Determine if messages of priority "debug" will be logged.
*
* @return true if "debug" messages will be logged
*/
boolean isDebugEnabled();
/**
* Log a info message.
*
* @param message the message
*/
void info( String message );
/**
* Log a info message.
*
* @param message the message
* @param throwable the throwable
*/
void info( String message, Throwable throwable );
/**
* Determine if messages of priority "info" will be logged.
*
* @return true if "info" messages will be logged
*/
boolean isInfoEnabled();
/**
* Log a warn message.
*
* @param message the message
*/
void warn( String message );
/**
* Log a warn message.
*
* @param message the message
* @param throwable the throwable
*/
void warn( String message, Throwable throwable );
/**
* Determine if messages of priority "warn" will be logged.
*
* @return true if "warn" messages will be logged
*/
boolean isWarnEnabled();
/**
* Log a error message.
*
* @param message the message
*/
void error( String message );
/**
* Log a error message.
*
* @param message the message
* @param throwable the throwable
*/
void error( String message, Throwable throwable );
/**
* Determine if messages of priority "error" will be logged.
*
* @return true if "error" messages will be logged
*/
boolean isErrorEnabled();
/**
* Log a fatalError message.
*
* @param message the message
*/
void fatalError( String message );
/**
* Log a fatalError message.
*
* @param message the message
* @param throwable the throwable
*/
void fatalError( String message, Throwable throwable );
/**
* Determine if messages of priority "fatalError" will be logged.
*
* @return true if "fatalError" messages will be logged
*/
boolean isFatalErrorEnabled();
/**
* Create a new child logger.
* The name of the child logger is [current-loggers-name].[passed-in-name]
* Throws IllegalArgumentException
if name has an empty element name
*
* @param name the subname of this logger
* @return the new logger
*/
Logger getChildLogger( String name );
}
avalon-framework/api/src/java/org/apache/avalon/framework/parameters/ParameterException.java 100644 0 0 3271 10051530441 30027 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.parameters;
import org.apache.avalon.framework.CascadingException;
/**
* Thrown when a Parameterizable
component cannot be parameterized
* properly, or if a value cannot be retrieved properly.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:25 $
*/
public final class ParameterException
extends CascadingException
{
/**
* Construct a new ParameterException
instance.
*
* @param message The detail message for this exception.
*/
public ParameterException( final String message )
{
this( message, null );
}
/**
* Construct a new ParameterException
instance.
*
* @param message The detail message for this exception.
* @param throwable the root cause of the exception
*/
public ParameterException( final String message, final Throwable throwable )
{
super( message, throwable );
}
}
avalon-framework/api/src/java/org/apache/avalon/framework/parameters/Parameterizable.java 100644 0 0 3315 10051530442 27337 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.parameters;
/**
* Components should implement this interface if they wish to
* be provided with parameters during startup.
*
* The Parameterizable interface is a light-weight alternative to the
* {@link org.apache.avalon.framework.configuration.Configurable}
* interface. As such, the Parameterizable
interface and
* the Configurable
interface are not
* compatible.
*
* This interface will be called after
* Composable.compose()
and before
* Initializable.initialize()
.
*
null
.
* @throws ParameterException if parameters are invalid
*/
void parameterize( Parameters parameters )
throws ParameterException;
}
avalon-framework/api/src/java/org/apache/avalon/framework/parameters/Parameters.java 100644 0 0 47743 10051530442 26370 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.parameters;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
/**
* The Parameters
class represents a set of key-value
* pairs.
*
* The Parameters
object provides a mechanism to obtain
* values based on a String
name. There are convenience
* methods that allow you to use defaults if the value does not exist,
* as well as obtain the value in any of the same formats that are in
* the {@link Configuration} interface.
*
* While there are similarities between the Parameters
* object and the java.util.Properties object, there are some
* important semantic differences. First, Parameters
are
* read-only. Second, Parameters
are easily
* derived from {@link Configuration} objects. Lastly, the
* Parameters
object is derived from XML fragments that
* look like this:
*
* <parameter name="param-name" value="param-value" />
*
* * Note: this class is not thread safe by default. If you * require thread safety please synchronize write access to this class to * prevent potential data corruption. *
* * @author Avalon Development Team * @version CVS $Revision: 1.41 $ $Date: 2004/02/11 14:34:25 $ */ public class Parameters implements Serializable { /** * Empty Parameters object * * @since 4.1.2 */ public static final Parameters EMPTY_PARAMETERS; /** Static initializer to initialize the empty Parameters object */ static { EMPTY_PARAMETERS = new Parameters(); EMPTY_PARAMETERS.makeReadOnly(); } ///Underlying store of parameters private Map m_parameters = new HashMap(); private boolean m_readOnly; /** * Set theString
value of a specified parameter.
*
* If the specified value is null the parameter is removed.
*
* @param name a String
value
* @param value a String
value
* @return The previous value of the parameter or null.
* @throws IllegalStateException if the Parameters object is read-only
*/
public String setParameter( final String name, final String value )
throws IllegalStateException
{
checkWriteable();
if( null == name )
{
return null;
}
if( null == value )
{
return (String)m_parameters.remove( name );
}
return (String)m_parameters.put( name, value );
}
/**
* Remove a parameter from the parameters object
* @param name a String
value
* @since 4.1
*/
public void removeParameter( final String name )
{
setParameter( name, null );
}
/**
* Return an Iterator
view of all parameter names.
*
* @return a iterator of parameter names
* @deprecated Use getNames() instead
*/
public Iterator getParameterNames()
{
return m_parameters.keySet().iterator();
}
/**
* Retrieve an array of all parameter names.
*
* @return the parameters names
*/
public String[] getNames()
{
return (String[])m_parameters.keySet().toArray( new String[ 0 ] );
}
/**
* Test if the specified parameter can be retrieved.
*
* @param name the parameter name
* @return true if parameter is a name
*/
public boolean isParameter( final String name )
{
return m_parameters.containsKey( name );
}
/**
* Retrieve the String
value of the specified parameter.
*
* If the specified parameter cannot be found, an exception is thrown.
*
* @param name the name of parameter
* @return the value of parameter
* @throws ParameterException if the specified parameter cannot be found
*/
public String getParameter( final String name )
throws ParameterException
{
if( null == name )
{
throw new ParameterException( "You cannot lookup a null parameter" );
}
final String test = (String)m_parameters.get( name );
if( null == test )
{
throw new ParameterException( "The parameter '" + name
+ "' does not contain a value" );
}
else
{
return test;
}
}
/**
* Retrieve the String
value of the specified parameter.
*
* If the specified parameter cannot be found, defaultValue
* is returned.
*
* @param name the name of parameter
* @param defaultValue the default value, returned if parameter does not exist
* or parameter's name is null
* @return the value of parameter
*/
public String getParameter( final String name, final String defaultValue )
{
if( name == null )
{
return defaultValue;
}
final String test = (String)m_parameters.get( name );
if( test == null )
{
return defaultValue;
}
else
{
return test;
}
}
/**
* Parses string represenation of the int
value.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param value the value to parse
* @return the integer value
* @throws NumberFormatException if the specified value can not be parsed
*/
private int parseInt( final String value )
throws NumberFormatException
{
if( value.startsWith( "0x" ) )
{
return Integer.parseInt( value.substring( 2 ), 16 );
}
else if( value.startsWith( "0o" ) )
{
return Integer.parseInt( value.substring( 2 ), 8 );
}
else if( value.startsWith( "0b" ) )
{
return Integer.parseInt( value.substring( 2 ), 2 );
}
else
{
return Integer.parseInt( value );
}
}
/**
* Retrieve the int
value of the specified parameter.
*
* If the specified parameter cannot be found, an exception is thrown.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of parameter
* @return the integer parameter type
* @throws ParameterException if the specified parameter cannot be found
* or is not an Integer value
*/
public int getParameterAsInteger( final String name )
throws ParameterException
{
try
{
return parseInt( getParameter( name ) );
}
catch( final NumberFormatException e )
{
throw new ParameterException( "Could not return an integer value", e );
}
}
/**
* Retrieve the int
value of the specified parameter.
*
* If the specified parameter cannot be found, defaultValue
* is returned.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of parameter
* @param defaultValue value returned if parameter does not exist or is of wrong type
* @return the integer parameter type
*/
public int getParameterAsInteger( final String name, final int defaultValue )
{
try
{
final String value = getParameter( name, null );
if( value == null )
{
return defaultValue;
}
return parseInt( value );
}
catch( final NumberFormatException e )
{
return defaultValue;
}
}
/**
* Parses string represenation of the long
value.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param value the value to parse
* @return the long value
* @throws NumberFormatException if the specified value can not be parsed
*/
private long parseLong( final String value )
throws NumberFormatException
{
if( value.startsWith( "0x" ) )
{
return Long.parseLong( value.substring( 2 ), 16 );
}
else if( value.startsWith( "0o" ) )
{
return Long.parseLong( value.substring( 2 ), 8 );
}
else if( value.startsWith( "0b" ) )
{
return Long.parseLong( value.substring( 2 ), 2 );
}
else
{
return Long.parseLong( value );
}
}
/**
* Retrieve the long
value of the specified parameter.
*
* If the specified parameter cannot be found, an exception is thrown.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of parameter
* @return the long parameter type
* @throws ParameterException if the specified parameter cannot be found
* or is not a Long value.
*/
public long getParameterAsLong( final String name )
throws ParameterException
{
try
{
return parseLong( getParameter( name ) );
}
catch( final NumberFormatException e )
{
throw new ParameterException( "Could not return a long value", e );
}
}
/**
* Retrieve the long
value of the specified parameter.
*
* If the specified parameter cannot be found, defaultValue
* is returned.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of parameter
* @param defaultValue value returned if parameter does not exist or is of wrong type
* @return the long parameter type
*/
public long getParameterAsLong( final String name, final long defaultValue )
{
try
{
final String value = getParameter( name, null );
if( value == null )
{
return defaultValue;
}
return parseLong( value );
}
catch( final NumberFormatException e )
{
return defaultValue;
}
}
/**
* Retrieve the float
value of the specified parameter.
*
* If the specified parameter cannot be found, an exception is thrown.
*
* @param name the parameter name
* @return the value
* @throws ParameterException if the specified parameter cannot be found
* or is not a Float value
*/
public float getParameterAsFloat( final String name )
throws ParameterException
{
try
{
return Float.parseFloat( getParameter( name ) );
}
catch( final NumberFormatException e )
{
throw new ParameterException( "Could not return a float value", e );
}
}
/**
* Retrieve the float
value of the specified parameter.
*
* If the specified parameter cannot be found, defaultValue
* is returned.
*
* @param name the parameter name
* @param defaultValue the default value if parameter does not exist or is of wrong type
* @return the value
*/
public float getParameterAsFloat( final String name, final float defaultValue )
{
try
{
final String value = getParameter( name, null );
if( value == null )
{
return defaultValue;
}
return Float.parseFloat( value );
}
catch( final NumberFormatException pe )
{
return defaultValue;
}
}
/**
* Retrieve the boolean
value of the specified parameter.
*
* If the specified parameter cannot be found, an exception is thrown.
*
* @param name the parameter name
* @return the value
* @throws ParameterException if an error occurs
* @throws ParameterException
*/
public boolean getParameterAsBoolean( final String name )
throws ParameterException
{
final String value = getParameter( name );
if( value.equalsIgnoreCase( "true" ) )
{
return true;
}
else if( value.equalsIgnoreCase( "false" ) )
{
return false;
}
else
{
throw new ParameterException( "Could not return a boolean value" );
}
}
/**
* Retrieve the boolean
value of the specified parameter.
*
* If the specified parameter cannot be found, defaultValue
* is returned.
*
* @param name the parameter name
* @param defaultValue the default value if parameter does not exist or is of wrong type
* @return the value
*/
public boolean getParameterAsBoolean( final String name, final boolean defaultValue )
{
final String value = getParameter( name, null );
if( value == null )
{
return defaultValue;
}
if( value.equalsIgnoreCase( "true" ) )
{
return true;
}
else if( value.equalsIgnoreCase( "false" ) )
{
return false;
}
else
{
return defaultValue;
}
}
/**
* Merge parameters from another Parameters
instance
* into this.
*
* @param other the other Parameters
* @return This Parameters
instance.
*/
public Parameters merge( final Parameters other )
{
checkWriteable();
final String[] names = other.getNames();
for( int i = 0; i < names.length; i++ )
{
final String name = names[ i ];
String value = null;
try
{
value = other.getParameter( name );
}
catch( final ParameterException pe )
{
value = null;
}
setParameter( name, value );
}
return this;
}
/**
* Make this Parameters read-only so that it will throw a
* IllegalStateException
if someone tries to
* modify it.
*/
public void makeReadOnly()
{
m_readOnly = true;
}
/**
* Checks is this Parameters
object is writeable.
*
* @throws IllegalStateException if this Parameters
object is read-only
*/
protected final void checkWriteable()
throws IllegalStateException
{
if( m_readOnly )
{
throw new IllegalStateException( "Context is read only and can not be modified" );
}
}
/**
* Create a Parameters
object from a Configuration
* object. This acts exactly like the following method call:
* * Parameters.fromConfiguration(configuration, "parameter"); ** * @param configuration the Configuration * @return This
Parameters
instance.
* @throws ConfigurationException if an error occurs
*/
public static Parameters fromConfiguration( final Configuration configuration )
throws ConfigurationException
{
return fromConfiguration( configuration, "parameter" );
}
/**
* Create a Parameters
object from a Configuration
* object using the supplied element name.
*
* @param configuration the Configuration
* @param elementName the element name for the parameters
* @return This Parameters
instance.
* @throws ConfigurationException if an error occurs
* @since 4.1
*/
public static Parameters fromConfiguration( final Configuration configuration,
final String elementName )
throws ConfigurationException
{
if( null == configuration )
{
throw new ConfigurationException(
"You cannot convert to parameters with a null Configuration" );
}
final Configuration[] parameters = configuration.getChildren( elementName );
final Parameters params = new Parameters();
for( int i = 0; i < parameters.length; i++ )
{
try
{
final String name = parameters[ i ].getAttribute( "name" );
final String value = parameters[ i ].getAttribute( "value" );
params.setParameter( name, value );
}
catch( final Exception e )
{
throw new ConfigurationException( "Cannot process Configurable", e );
}
}
return params;
}
/**
* Create a Parameters
object from a Properties
* object.
*
* @param properties the Properties
* @return This Parameters
instance.
*/
public static Parameters fromProperties( final Properties properties )
{
final Parameters parameters = new Parameters();
final Enumeration names = properties.propertyNames();
while( names.hasMoreElements() )
{
final String key = names.nextElement().toString();
final String value = properties.getProperty( key );
parameters.setParameter( key, value );
}
return parameters;
}
/**
* Creates a java.util.Properties
object from an Avalon
* Parameters object.
*
* @param params a Parameters
instance
* @return a Properties
instance
*/
public static Properties toProperties( final Parameters params )
{
final Properties properties = new Properties();
final String[] names = params.getNames();
for( int i = 0; i < names.length; ++i )
{
// "" is the default value, since getNames() proves it will exist
properties.setProperty( names[ i ], params.getParameter( names[ i ], "" ) );
}
return properties;
}
}
avalon-framework/api/src/java/org/apache/avalon/framework/parameters/Reparameterizable.java 100644 0 0 2631 10051530442 27666 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.parameters;
/**
* Components should implement this interface if they wish to
* be provided with parameters during its lifetime. This interface
* will be called after Startable.start() and before
* Startable.stop(). It is incompatible with the
* Reconfigurable interface.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.13 $ $Date: 2004/02/11 14:34:25 $
*/
public interface Reparameterizable extends Parameterizable
{
/**
* Provide component with parameters.
*
* @param parameters the parameters
* @throws ParameterException if parameters are invalid
*/
void reparameterize( Parameters parameters )
throws ParameterException;
}
avalon-framework/api/src/java/org/apache/avalon/framework/service/Serviceable.java 100644 0 0 4066 10051530441 25754 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.service;
/**
* A Serviceable is a class that need to connect to software components using
* a "role" abstraction, thus not depending on particular implementations
* but on behavioral interfaces.
* Serviceable
is that it is a user.
* The Serviceable
is able to use Object
s managed
* by the ServiceManager
it was initialized with. As part
* of the contract with the system, the instantiating entity must call
* the service
method before the Serviceable
* can be considered valid.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.19 $ $Date: 2004/02/11 14:34:25 $
* @see org.apache.avalon.framework.service.ServiceManager
*
*/
public interface Serviceable
{
/**
* Pass the ServiceManager
to the Serviceable
.
* The Serviceable
implementation should use the specified
* ServiceManager
to acquire the components it needs for
* execution.
*
* @param manager The ServiceManager
which this
* Serviceable
uses. Must not be null
.
* @throws ServiceException if an error occurs
*/
void service( ServiceManager manager )
throws ServiceException;
}
avalon-framework/api/src/java/org/apache/avalon/framework/service/ServiceException.java 100644 0 0 6304 10051530441 27004 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.service;
import org.apache.avalon.framework.CascadingException;
/**
* The exception thrown to indicate a problem with service.
* It is usually thrown by ServiceManager or ServiceSelector.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.21 $ $Date: 2004/02/11 14:34:25 $
*/
public class ServiceException
extends CascadingException
{
private final String m_key;
/**
* Construct a new ServiceException
instance.
*
* @deprecated use the String,String,Throwable version instead
* @param message the exception message
* @param throwable the throwable
*/
public ServiceException( final String message, final Throwable throwable )
{
this( null, message, throwable );
}
/**
* Construct a new ServiceException
instance.
*
* @param key the lookup key
* @param message the exception message
* @param throwable the throwable
*/
public ServiceException( final String key, final String message, final Throwable throwable )
{
super( message, throwable );
m_key = key;
}
/**
* Construct a new ServiceException
instance.
*
* @deprecated use the String,String version instead
* @param message the exception message
*/
public ServiceException( final String message )
{
this( null, message, null );
}
/**
* Construct a new ServiceException
instance.
*
* @param key the lookup key
* @param message the exception message
*/
public ServiceException( final String key, final String message )
{
this( key, message, null );
}
/**
* Return the key that caused the exception.
* @return the lookup key triggering the exception
*/
public String getKey()
{
return m_key;
}
/**
* Return the role that caused the exception
*
* @deprecated Use getKey() instead
* @return the the lookup key triggering the exception
*/
public String getRole()
{
return getKey();
}
/**
* Override super's message to add role if applicable.
* @return a message.
*/
public String getMessage()
{
if( m_key == null )
{
return super.getMessage();
}
else
{
return super.getMessage() + " (Key='" + m_key + "')";
}
}
}
avalon-framework/api/src/java/org/apache/avalon/framework/service/ServiceManager.java 100644 0 0 7227 10051530442 26426 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.service;
/**
* A ServiceManager
selects Object
s based on a
* role. The contract is that all the Object
s implement the
* differing roles and there is one Object
per role. If you
* need to select on of many Object
s that implement the same
* role, then you need to use a ServiceSelector
. Roles are
* usually the full interface name.
*
* A role is better understood by the analogy of a play. There are many
* different roles in a script. Any actor or actress can play any given part
* and you get the same results (phrases said, movements made, etc.). The exact
* nuances of the performance is different.
*
* Below is a list of things that might be considered the different roles:
*
* ServiceManager
does not specify the methodology of
* getting the Object
, merely the interface used to get it.
* Therefore the ServiceManager
can be implemented with a
* factory pattern, an object pool, or a simple Hashtable.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.17 $ $Date: 2004/02/11 14:34:25 $
* @see org.apache.avalon.framework.service.Serviceable
* @see org.apache.avalon.framework.service.ServiceSelector
*/
public interface ServiceManager
{
/**
* Get the Object
associated with the given key. For
* instance, If the ServiceManager
had a
* LoggerComponent
stored and referenced by key,
* the following could be used:
* * try * { * LoggerComponent log; * myComponent = (LoggerComponent) manager.lookup( LoggerComponent.ROLE ); * } * catch (...) * { * ... * } ** * @param key The lookup key of the
Object
to retrieve.
* @return an Object
value
* @throws ServiceException if an error occurs
*/
Object lookup( String key )
throws ServiceException;
/**
* Check to see if a Object
exists for a key.
*
* @param key a string identifying the key to check.
* @return True if the object exists, False if it does not.
*/
boolean hasService( String key );
/**
* Return the Object
when you are finished with it. This
* allows the ServiceManager
to handle the End-Of-Life Lifecycle
* events associated with the Object
. Please note, that no
* Exception should be thrown at this point. This is to allow easy use of the
* ServiceManager system without having to trap Exceptions on a release.
*
* @param object The Object
we are releasing, may also be
* a null
reference
*/
void release( Object object );
}
avalon-framework/api/src/java/org/apache/avalon/framework/service/ServiceSelector.java 100644 0 0 5363 10051530442 26633 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.service;
/**
* A ServiceSelector
selects {@link Object}s based on a
* supplied policy. The contract is that all the {@link Object}s implement the
* same role.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.16 $ $Date: 2004/02/11 14:34:25 $
* @see org.apache.avalon.framework.service.Serviceable
* @see org.apache.avalon.framework.service.ServiceSelector
*/
public interface ServiceSelector
{
/**
* Select the {@link Object} associated with the given policy.
* For instance, If the {@link ServiceSelector} has a
* Generator
stored and referenced by a URL, the
* following call could be used:
*
* * try * { * Generator input; * input = (Generator)selector.select( new URL("foo://demo/url") ); * } * catch (...) * { * ... * } ** * @param policy A criteria against which a {@link Object} is selected. * * @return an {@link Object} value * @throws ServiceException If the requested {@link Object} cannot be supplied */ Object select( Object policy ) throws ServiceException; /** * Check to see if a {@link Object} exists relative to the supplied policy. * * @param policy a {@link Object} containing the selection criteria * @return True if the component is available, False if it not. */ boolean isSelectable( Object policy ); /** * Return the {@link Object} when you are finished with it. This * allows the {@link ServiceSelector} to handle the End-Of-Life Lifecycle * events associated with the {@link Object}. Please note, that no * Exception should be thrown at this point. This is to allow easy use of the * ServiceSelector system without having to trap Exceptions on a release. * * @param object The {@link Object} we are releasing, may also be a *
null
reference
*/
void release( Object object );
}
avalon-framework/api/src/java/org/apache/avalon/framework/thread/SingleThreaded.java 100644 0 0 1733 10051530441 26217 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.thread;
/**
* A interface to mark a component as SingleThreaded.
* This interface is incompatible with ThreadSafe.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:25 $
*/
public interface SingleThreaded
{
}
avalon-framework/api/src/java/org/apache/avalon/framework/thread/ThreadSafe.java 100644 0 0 1744 10051530442 25346 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.thread;
/**
* A interface to mark a component as ThreadSafe or reentrant.
* This interface is incompatible with SingleThreaded.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:25 $
*/
public interface ThreadSafe
{
}
avalon-framework/api/src/java/org/apache/avalon/framework/ValuedEnum.java 100644 0 0 13726 10051530442 24161 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework;
import java.util.Map;
/**
* Basic enum class for type-safe enums with values. Valued enum items can be compared and ordered
* with the provided methods. Should be used as an abstract base. For example:
*
* * import org.apache.avalon.framework.ValuedEnum; * * public final class JavaVersion * extends ValuedEnum * { * //standard enums for version of JVM * public static final JavaVersion JAVA1_0 = new JavaVersion( "Java 1.0", 100 ); * public static final JavaVersion JAVA1_1 = new JavaVersion( "Java 1.1", 110 ); * public static final JavaVersion JAVA1_2 = new JavaVersion( "Java 1.2", 120 ); * public static final JavaVersion JAVA1_3 = new JavaVersion( "Java 1.3", 130 ); * * private JavaVersion( final String name, final int value ) * { * super( name, value ); * } * } ** * The above class could then be used as follows: *
* import org.apache.avalon.framework.context.Context; * import org.apache.avalon.framework.context.Contextualizable; * import org.apache.avalon.framework.context.ContextException; * * public class MyComponent implements Contextualizable * { * JavaVersion requiredVer = JavaVersion.JAVA1_2; * * public void contextualize(Context context) * throws ContextException * { * JavaVersion ver = (JavaVersion)context.get("java.version"); * if ( ver.isLessThan( requiredVer ) ) * { * throw new RuntimeException( requiredVer.getName()+" or higher required" ); * } * } * } ** * As with
Enum
, the {@link #ValuedEnum(String, int, Map)} constructor can be used to
* populate a Map
, from which further functionality can be derived.
*
*
* NOTE: between 4.0 and 4.1, the constructors' access has been changed
* from public
to protected
. This is to prevent users
* of the Enum breaking type-safety by defining new Enum items. All Enum items
* should be defined in the Enum class, as shown above.
*
* Note: access changed from public
to
* protected
after 4.0. See class description.
*
public
to
* protected
after 4.0. See class description.
*
*
* @param name the name of enum item.
* @param value the value of enum item.
* @param map the Map
to add enum item to.
*/
protected ValuedEnum( final String name, final int value, final Map map )
{
super( name, map );
m_value = value;
}
/**
* Get value of enum item.
*
* @return the enum item's value.
*/
public final int getValue()
{
return m_value;
}
/**
* Test if enum item is equal in value to other enum.
*
* @param other the other enum
* @return true if equal
*/
public final boolean isEqualTo( final ValuedEnum other )
{
return m_value == other.m_value;
}
/**
* Test if enum item is greater than in value to other enum.
*
* @param other the other enum
* @return true if greater than
*/
public final boolean isGreaterThan( final ValuedEnum other )
{
return m_value > other.m_value;
}
/**
* Test if enum item is greater than or equal in value to other enum.
*
* @param other the other enum
* @return true if greater than or equal
*/
public final boolean isGreaterThanOrEqual( final ValuedEnum other )
{
return m_value >= other.m_value;
}
/**
* Test if enum item is less than in value to other enum.
*
* @param other the other enum
* @return true if less than
*/
public final boolean isLessThan( final ValuedEnum other )
{
return m_value < other.m_value;
}
/**
* Test if enum item is less than or equal in value to other enum.
*
* @param other the other enum
* @return true if less than or equal
*/
public final boolean isLessThanOrEqual( final ValuedEnum other )
{
return m_value <= other.m_value;
}
/**
* Override toString method to produce human readable description.
*
* @return String in the form type[name=value]
, eg.:
* JavaVersion[Java 1.0=100]
.
*/
public String toString()
{
return getClass().getName() + "[" + getName() + "=" + m_value + "]";
}
}
avalon-framework/api/src/java/org/apache/avalon/framework/Version.java 100644 0 0 23235 10051530441 23534 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework;
import java.io.Serializable;
import java.util.StringTokenizer;
/**
* This class is used to hold version information pertaining to a Component or interface.
*
*
* The version number of a Component
is made up of three
* dot-separated fields:
*
* "major.minor.micro"
*
* The major, minor and micro fields are
* integer numbers represented in decimal notation and have the
* following meaning:
* null
* @since 4.1
*/
public static Version getVersion( final String version )
throws NumberFormatException, IllegalArgumentException
{
if( version == null )
throw new NullPointerException( "version" );
final StringTokenizer tokenizer = new StringTokenizer( version, "." );
final String[] levels = new String[ tokenizer.countTokens() ];
for( int i = 0; i < levels.length; i++ )
{
levels[ i ] = tokenizer.nextToken();
}
int major = -1;
if( 0 < levels.length )
{
major = Integer.parseInt( levels[ 0 ] );
}
int minor = 0;
if( 1 < levels.length )
{
minor = Integer.parseInt( levels[ 1 ] );
}
int micro = 0;
if( 2 < levels.length )
{
micro = Integer.parseInt( levels[ 2 ] );
}
return new Version( major, minor, micro );
}
/**
* Create a new instance of a Version
object with the
* specified version numbers.
*
* @param major This Version
major number.
* @param minor This Version
minor number.
* @param micro This Version
micro number.
*/
public Version( final int major, final int minor, final int micro )
{
m_major = major;
m_minor = minor;
m_micro = micro;
}
/**
* Retrieve major component of version.
*
* @return the major component of version
* @since 4.1
*/
public int getMajor()
{
return m_major;
}
/**
* Retrieve minor component of version.
*
* @return the minor component of version
* @since 4.1
*/
public int getMinor()
{
return m_minor;
}
/**
* Retrieve micro component of version.
*
* @return the micro component of version.
* @since 4.1
*/
public int getMicro()
{
return m_micro;
}
/**
* Check this Version
against another for equality.
*
* If this Version
is compatible with the specified one, then
* true is returned, otherwise false.
*
* @param other The other Version
object to be compared with this
* for equality.
* @return true if this Version
is compatible with the specified one
* @since 4.1
*/
public boolean equals( final Version other )
{
if( other == null )
return false;
boolean isEqual = ( getMajor() == other.getMajor() );
if ( isEqual )
{
isEqual = ( getMinor() == other.getMinor() );
}
if ( isEqual )
{
isEqual = ( getMicro() == other.getMicro() );
}
return isEqual;
}
/**
* Indicates whether some other object is "equal to" this Version
.
* Returns true if the other object is an instance of Version
* and has the same major, minor, and micro components.
*
* @param other an Object
value
* @return true if the other object is equal to this Version
*/
public boolean equals( final Object other )
{
boolean isEqual = false;
if( other instanceof Version )
{
isEqual = equals( (Version)other );
}
return isEqual;
}
/**
* Add a hashing function to ensure the Version object is
* treated as expected in hashmaps and sets. NOTE: any
* time the equals() is overridden, hashCode() should also
* be overridden.
*
* @return the hashCode
*/
public int hashCode()
{
int hash = getMajor();
hash >>>= 17;
hash += getMinor();
hash >>>= 17;
hash += getMicro();
return hash;
}
/**
* Check this Version
against another for compliancy
* (compatibility).
*
* If this Version
is compatible with the specified one, then
* true is returned, otherwise false. Be careful when using
* this method since, in example, version 1.3.7 is compliant to version
* 1.3.6, while the opposite is not.
*
* The following example displays the expected behaviour and results of version.
* * final Version v1 = new Version( 1, 3 , 6 ); * final Version v2 = new Version( 1, 3 , 7 ); * final Version v3 = new Version( 1, 4 , 0 ); * final Version v4 = new Version( 2, 0 , 1 ); * * assert( v1.complies( v1 ) ); * assert( ! v1.complies( v2 ) ); * assert( v2.complies( v1 ) ); * assert( ! v1.complies( v3 ) ); * assert( v3.complies( v1 ) ); * assert( ! v1.complies( v4 ) ); * assert( ! v4.complies( v1 ) ); ** * @param other The other
Version
object to be compared with this
* for compliancy (compatibility).
* @return true if this Version
is compatible with the specified one
*/
public boolean complies( final Version other )
{
if( other == null )
return false;
if( other.m_major == -1 )
{
return true;
}
if( m_major != other.m_major )
{
return false;
}
else if( m_minor < other.m_minor )
{
//If of major version but lower minor version then incompatible
return false;
}
else if( m_minor == other.m_minor
&& m_micro < other.m_micro )
{
//If same major version, same minor version but lower micro level
//then incompatible
return false;
}
else
{
return true;
}
}
/**
* Overload toString to report version correctly.
*
* @return the dot seperated version string
*/
public String toString()
{
return m_major + "." + m_minor + "." + m_micro;
}
/**
* Compare two versions together according to the
* {@link Comparable} interface.
*
* @return number indicating relative value (-1, 0, 1)
*/
public int compareTo(Object o) {
if( o == null )
throw new NullPointerException( "o" );
Version other = (Version)o;
int val = 0;
if ( getMajor() < other.getMajor() ) val = -1;
if ( 0 == val && getMajor() > other.getMajor() ) val = 1;
if ( 0 == val && getMinor() < other.getMinor() ) val = -1;
if ( 0 == val && getMinor() > other.getMinor() ) val = 1;
if ( 0 == val && getMicro() < other.getMicro() ) val = -1;
if ( 0 == val && getMicro() > other.getMicro() ) val = 1;
return val;
}
}
avalon-framework/api/src/test/org/apache/avalon/framework/test/CascadingErrorTestCase.java 100644 0 0 5005 10051530441 27421 0 ustar 0 0 /*
* Copyright 2004 Apache Software Foundation
* Licensed 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.
*/
package org.apache.avalon.framework.test;
import org.apache.avalon.framework.CascadingError;
import org.apache.avalon.framework.CascadingThrowable;
import junit.framework.TestCase;
/**
* TestCase for {@link CascadingError}.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.2 $ $Date: 2004/02/21 13:27:02 $
*/
public class CascadingErrorTestCase extends TestCase
{
public void testConstructor()
{
assertNotNull( new CascadingError( null, null ) );
assertNotNull( new CascadingError( "msg", null ) );
assertNotNull( new CascadingError( "msg", new RuntimeException() ) );
assertNotNull( new CascadingError( null, new RuntimeException() ) );
//assertNotNull( new CascadingError( "msg" ) );
//ambiguous assertNotNull( new CascadingError( null ) );
//assertNotNull( new CascadingError() );
}
public void testGetCause()
{
RuntimeException re = new RuntimeException();
CascadingError e = new CascadingError( "msg", re );
assertEquals( re, e.getCause() );
e = new CascadingError( "msg", null );
assertNull( e.getCause() );
// default to jdk 1.3 cause (not that it seems to help,
// but it still makes sense)
/*Exception exc = new Exception("blah");
try
{
try
{
throw exc;
}
catch( Exception ex )
{
throw new CascadingError();
}
}
catch( CascadingError ex )
{
ex.getCause();
}*/
}
public void testCasts()
{
CascadingError e = new CascadingError( "msg", null );
assertTrue( e instanceof Error );
assertTrue( e instanceof CascadingThrowable );
}
}
avalon-framework/api/src/test/org/apache/avalon/framework/test/CascadingExceptionTestCase.java 100644 0 0 5133 10051530442 30271 0 ustar 0 0 /*
* Copyright 2004 Apache Software Foundation
* Licensed 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.
*/
package org.apache.avalon.framework.test;
import org.apache.avalon.framework.CascadingException;
import org.apache.avalon.framework.CascadingThrowable;
import junit.framework.TestCase;
/**
* TestCase for {@link CascadingException}.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.2 $ $Date: 2004/02/21 13:27:02 $
*/
public class CascadingExceptionTestCase extends TestCase
{
public void testConstructor()
{
assertNotNull( new CascadingException( null, null ) );
assertNotNull( new CascadingException( "msg", null ) );
assertNotNull(
new CascadingException( "msg", new RuntimeException() ) );
assertNotNull( new CascadingException( null, new RuntimeException() ) );
assertNotNull( new CascadingException( "msg" ) );
// ambiguous assertNotNull( new CascadingException( null ) );
//assertNotNull( new CascadingException() );
}
public void testGetCause()
{
RuntimeException re = new RuntimeException();
CascadingException e = new CascadingException( "msg", re );
assertEquals( re, e.getCause() );
e = new CascadingException( "msg", null );
assertNull( e.getCause() );
// default to jdk 1.3 cause (not that it seems to help,
// but it still makes sense)
/*Exception exc = new Exception("blah");
try
{
try
{
throw exc;
}
catch( Exception ex )
{
throw new CascadingException();
}
}
catch( CascadingException ex )
{
ex.getCause();
}*/
}
public void testCasts()
{
CascadingException e = new CascadingException( "msg", null );
assertTrue( e instanceof Exception );
assertTrue( e instanceof CascadingThrowable );
}
}
././@LongLink 100644 0 0 146 10051530443 10247 L ustar 0 0 avalon-framework/api/src/test/org/apache/avalon/framework/test/CascadingRuntimeExceptionTestCase.java avalon-framework/api/src/test/org/apache/avalon/framework/test/CascadingRuntimeExceptionTestCase.jav100644 0 0 5075 10051530442 31501 0 ustar 0 0 /*
* Copyright 2004 Apache Software Foundation
* Licensed 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.
*/
package org.apache.avalon.framework.test;
import org.apache.avalon.framework.CascadingRuntimeException;
import org.apache.avalon.framework.CascadingThrowable;
import junit.framework.TestCase;
/**
* TestCase for {@link CascadingRuntimeException}.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.2 $ $Date: 2004/02/21 13:27:02 $
*/
public class CascadingRuntimeExceptionTestCase extends TestCase
{
public void testConstructor()
{
assertNotNull( new CascadingRuntimeException( null, null ) );
assertNotNull( new CascadingRuntimeException( "msg", null ) );
assertNotNull(
new CascadingRuntimeException( "msg", new RuntimeException() ) );
assertNotNull(
new CascadingRuntimeException( null, new RuntimeException() ) );
}
public void testGetCause()
{
RuntimeException re = new RuntimeException();
CascadingRuntimeException e = new CascadingRuntimeException( "msg",
re );
assertEquals( re, e.getCause() );
e = new CascadingRuntimeException( "msg", null );
assertNull( e.getCause() );
// default to jdk 1.3 cause (not that it seems to help,
// but it still makes sense)
/*Exception exc = new Exception("blah");
try
{
try
{
throw exc;
}
catch( Exception ex )
{
throw new CascadingRuntimeException();
}
}
catch( CascadingRuntimeException ex )
{
ex.getCause();
}*/
}
public void testCasts()
{
CascadingRuntimeException e = new CascadingRuntimeException( "msg",
null );
assertTrue( e instanceof RuntimeException );
assertTrue( e instanceof CascadingThrowable );
}
}
avalon-framework/api/src/test/org/apache/avalon/framework/test/EnumTestCase.java 100644 0 0 11742 10051530441 25464 0 ustar 0 0 /*
* Copyright 2004 Apache Software Foundation
* Licensed 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.
*/
package org.apache.avalon.framework.test;
import junit.framework.TestCase;
import org.apache.avalon.framework.Enum;
import java.util.Map;
import java.util.HashMap;
/**
* TestCase for {@link Enum}.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.3 $ $Date: 2004/02/21 13:27:02 $
*/
public class EnumTestCase
extends TestCase
{
private final static class Color extends Enum
{
public static final Color RED = new Color( "Red" );
public static final Color GREEN = new Color( "Green" );
public static final Color BLUE = new Color( "Blue" );
public Color( final String color )
{
super( color );
}
public Color( final String color, Map stuff )
{
super( color, stuff );
}
}
private final static class OtherColor extends Enum
{
public static final OtherColor RED = new OtherColor( "Red" );
public static final OtherColor GREEN = new OtherColor( "Green" );
public static final OtherColor BLUE = new OtherColor( "Blue" );
public OtherColor( final String color )
{
super( color );
}
public OtherColor( final String color, Map stuff )
{
super( color, stuff );
}
}
public EnumTestCase( final String name )
{
super( name );
}
public void testConstructor()
{
assertNotNull( new Color( "blah", null ) );
Map entries = new HashMap();
Color c = new Color( "blah", entries );
assertTrue( entries.containsKey("blah") );
assertTrue( entries.containsValue(c) );
OtherColor c2 = new OtherColor( "blah", entries );
assertTrue( entries.containsKey("blah") );
assertFalse( entries.containsValue(c) );
assertTrue( entries.containsValue(c2) );
}
public void testEquals()
{
assertTrue( Color.RED.equals( Color.RED ) );
assertTrue( Color.GREEN.equals( Color.GREEN ) );
assertTrue( Color.BLUE.equals( Color.BLUE ) );
assertTrue( !OtherColor.RED.equals( Color.RED ) );
assertTrue( !OtherColor.GREEN.equals( Color.GREEN ) );
assertTrue( !OtherColor.BLUE.equals( Color.BLUE ) );
assertTrue( !Color.RED.equals( OtherColor.RED ) );
assertTrue( !Color.GREEN.equals( OtherColor.GREEN ) );
assertTrue( !Color.BLUE.equals( OtherColor.BLUE ) );
assertTrue( !Color.RED.equals( Color.GREEN ) );
assertTrue( !Color.GREEN.equals( Color.BLUE ) );
assertTrue( !Color.BLUE.equals( Color.RED ) );
assertTrue( !Color.BLUE.equals( null ) );
assertTrue( new Color(null).equals( new Color( null ) ) );
assertFalse( new Color(null).equals( new Color( "hi" ) ) );
assertFalse( new Color("hi").equals( new Color( null ) ) );
}
public void testHashCode()
{
assertTrue( Color.RED.hashCode() == Color.RED.hashCode() );
assertTrue( Color.GREEN.hashCode() == Color.GREEN.hashCode() );
assertTrue( Color.BLUE.hashCode() == Color.BLUE.hashCode() );
assertTrue( OtherColor.RED.hashCode() != Color.RED.hashCode() );
assertTrue( OtherColor.GREEN.hashCode() != Color.GREEN.hashCode() );
assertTrue( OtherColor.BLUE.hashCode() != Color.BLUE.hashCode() );
assertTrue( Color.RED.hashCode() != OtherColor.RED.hashCode() );
assertTrue( Color.GREEN.hashCode() != OtherColor.GREEN.hashCode() );
assertTrue( Color.BLUE.hashCode() != OtherColor.BLUE.hashCode() );
assertTrue( Color.RED.hashCode() != Color.GREEN.hashCode() );
assertTrue( Color.GREEN.hashCode() != Color.BLUE.hashCode() );
assertTrue( Color.BLUE.hashCode() != Color.RED.hashCode() );
}
public void testGet()
{
assertEquals( "Red", Color.RED.getName() );
assertNull( (new Color(null)).getName() );
}
public void testToString()
{
assertTrue( Color.RED.toString().indexOf( "Red") != -1 );
assertTrue( Color.RED.toString().indexOf( Color.class.getName() ) != -1 );
Color c = new Color(null);
assertTrue( c.toString().indexOf( "null") != -1 );
}
}
avalon-framework/api/src/test/org/apache/avalon/framework/test/ValuedEnumTestCase.java 100644 0 0 13660 10051530442 26627 0 ustar 0 0 /*
* Copyright 2004 Apache Software Foundation
* Licensed 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.
*/
package org.apache.avalon.framework.test;
import org.apache.avalon.framework.ValuedEnum;
import junit.framework.TestCase;
import java.util.Map;
import java.util.HashMap;
/**
*
* @author Avalon Development Team
* @version $Id: ValuedEnumTestCase.java,v 1.3 2004/02/24 22:31:22 niclas Exp $
*/
public class ValuedEnumTestCase extends TestCase
{
private final static class Color extends ValuedEnum
{
public static final Color RED = new Color( "Red", 0 );
public static final Color RED_NEGATIVE = new Color( "Red", -1 );
public static final Color GREEN = new Color( "Green", 1 );
public static final Color BLUE = new Color( "Blue", 2 );
public Color( final String color, final int value )
{
super( color, value );
}
public Color( final String color, final int value, Map stuff )
{
super( color, value, stuff );
}
}
private final static class OtherColor extends ValuedEnum
{
public static final OtherColor RED = new OtherColor( "Red", 0 );
public static final OtherColor RED_NEGATIVE = new OtherColor( "Red", -1 );
public static final OtherColor GREEN = new OtherColor( "Green", 1 );
public static final OtherColor BLUE = new OtherColor( "Blue", 2 );
public OtherColor( final String color, final int value )
{
super( color, value );
}
public OtherColor( final String color, final int value, Map stuff )
{
super( color, value, stuff );
}
}
public ValuedEnumTestCase( final String name )
{
super( name );
}
public void testConstructor()
{
assertNotNull( new Color( "blah", 0, null ) );
Map entries = new HashMap();
Color c = new Color( "blah", 0, entries );
assertTrue( entries.containsKey("blah") );
assertTrue( entries.containsValue(c) );
OtherColor c2 = new OtherColor( "blah", 0, entries );
assertTrue( entries.containsKey("blah") );
assertFalse( entries.containsValue(c) );
assertTrue( entries.containsValue(c2) );
}
public void testEquals()
{
assertTrue( Color.RED.equals( Color.RED ) );
assertTrue( Color.GREEN.equals( Color.GREEN ) );
assertTrue( Color.BLUE.equals( Color.BLUE ) );
assertTrue( !OtherColor.RED.equals( Color.RED ) );
assertTrue( !OtherColor.GREEN.equals( Color.GREEN ) );
assertTrue( !OtherColor.BLUE.equals( Color.BLUE ) );
assertTrue( !Color.RED.equals( OtherColor.RED ) );
assertTrue( !Color.GREEN.equals( OtherColor.GREEN ) );
assertTrue( !Color.BLUE.equals( OtherColor.BLUE ) );
assertTrue( !Color.RED.equals( Color.GREEN ) );
assertTrue( !Color.GREEN.equals( Color.BLUE ) );
assertTrue( !Color.BLUE.equals( Color.RED ) );
assertTrue( !Color.BLUE.equals( null ) );
assertTrue( new Color(null,0).equals( new Color( null,0 ) ) );
assertFalse( new Color(null,0).equals( new Color( "hi",0 ) ) );
assertFalse( new Color("hi",0).equals( new Color( null,0 ) ) );
// todo: is this _really_ desired?
assertTrue( Color.RED.equals( Color.RED_NEGATIVE ) );
assertTrue( Color.RED_NEGATIVE.equals( Color.RED ) );
assertTrue( OtherColor.RED.equals( OtherColor.RED_NEGATIVE ) );
assertTrue( OtherColor.RED_NEGATIVE.equals( OtherColor.RED ) );
}
public void testHashCode()
{
assertTrue( Color.RED.hashCode() == Color.RED.hashCode() );
assertTrue( Color.GREEN.hashCode() == Color.GREEN.hashCode() );
assertTrue( Color.BLUE.hashCode() == Color.BLUE.hashCode() );
assertTrue( OtherColor.RED.hashCode() != Color.RED.hashCode() );
assertTrue( OtherColor.GREEN.hashCode() != Color.GREEN.hashCode() );
assertTrue( OtherColor.BLUE.hashCode() != Color.BLUE.hashCode() );
assertTrue( Color.RED.hashCode() != OtherColor.RED.hashCode() );
assertTrue( Color.GREEN.hashCode() != OtherColor.GREEN.hashCode() );
assertTrue( Color.BLUE.hashCode() != OtherColor.BLUE.hashCode() );
assertTrue( Color.RED.hashCode() != Color.GREEN.hashCode() );
assertTrue( Color.GREEN.hashCode() != Color.BLUE.hashCode() );
assertTrue( Color.BLUE.hashCode() != Color.RED.hashCode() );
// todo: is this _really_ desired?
assertTrue( Color.RED.hashCode() ==Color.RED_NEGATIVE.hashCode() );
assertTrue( Color.RED_NEGATIVE.hashCode() ==Color.RED.hashCode() );
assertTrue( OtherColor.RED.hashCode() ==OtherColor.RED_NEGATIVE.hashCode() );
assertTrue( OtherColor.RED_NEGATIVE.hashCode() ==OtherColor.RED.hashCode() );
}
public void testGet()
{
assertEquals( "Red", Color.RED.getName() );
assertNull( (new Color(null,0)).getName() );
}
public void testToString()
{
assertTrue( Color.RED.toString().indexOf( "Red") != -1 );
assertTrue( Color.RED.toString().indexOf( Color.class.getName() ) != -1 );
Color c = new Color(null,0);
assertTrue( c.toString().indexOf( "null") != -1 );
}
}
avalon-framework/api/src/test/org/apache/avalon/framework/test/VersionTestCase.java 100644 0 0 12131 10051530442 26177 0 ustar 0 0 /*
* Copyright 2004 Apache Software Foundation
* Licensed 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.
*/
package org.apache.avalon.framework.test;
import junit.framework.TestCase;
import org.apache.avalon.framework.Version;
/**
* TestCase for {@link Version}.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.3 $ $Date: 2004/02/21 13:27:02 $
*/
public class VersionTestCase
extends TestCase
{
public VersionTestCase( final String name )
{
super( name );
}
public void testValidVersionString()
{
final Version v1 = Version.getVersion( "1" );
assertTrue( new Version( 1, 0, 0 ).equals( v1 ) );
final Version v2 = Version.getVersion( "0.3" );
assertTrue( new Version( 0, 3, 0 ).equals( v2 ) );
final Version v3 = Version.getVersion( "78.10.03" );
assertTrue( new Version( 78, 10, 3 ).equals( v3 ) );
try
{
final Version v4 = Version.getVersion( null );
fail( "Expected an exception!" );
}
catch( NullPointerException th )
{}
}
public void testInvalidVersionString()
{
try
{
assertEquals( -1, Version.getVersion( "" ).getMajor() );
}
catch ( final IllegalArgumentException iae )
{
fail( "Empty string is legal version string" );
}
try
{
Version.getVersion( "1.F" );
Version.getVersion( "1.0-dev" );
fail( "Version string do contains only '.' and number" );
}
catch ( final NumberFormatException nfe )
{
//OK
}
}
public void testComplies()
{
final Version v0 = new Version( -1, 0 , 0 );
final Version v1 = new Version( 1, 3 , 6 );
final Version v2 = new Version( 1, 3 , 7 );
final Version v3 = new Version( 1, 4 , 0 );
final Version v4 = new Version( 2, 0 , 1 );
assertTrue( v1.complies( v0 ) );
assertTrue( v4.complies( v0 ) );
assertTrue( ! v0.complies( v1 ) );
assertTrue( ! v0.complies( v4 ) );
assertTrue( v1.complies( v1 ) );
assertTrue( ! v1.complies( v2 ) );
assertTrue( v2.complies( v1 ) );
assertTrue( ! v1.complies( v3 ) );
assertTrue( v3.complies( v1 ) );
assertTrue( ! v1.complies( v4 ) );
assertTrue( ! v4.complies( v1 ) );
assertTrue( ! v4.complies( null ) );
}
public void testHashCode()
{
final Version v1 = new Version( 5, 1, 0 );
final Version v2 = new Version( 1, 0, 3 );
final Version v3 = new Version( 1, 0, 3 );
assertEquals( calculateHash(v1), v1.hashCode() );
assertEquals( calculateHash(v2), v2.hashCode() );
assertTrue( v1.hashCode() != v2.hashCode() );
assertTrue( ! v1.equals(v2) );
assertEquals( v2.hashCode(), v3.hashCode() );
assertEquals( v2, v3 );
}
public void testComparable()
{
final Version v1 = new Version( 1, 0, 0 );
final Version v2 = new Version( 2, 0, 0 );
final Version v3 = new Version( 2, 1, 0 );
final Version v4 = new Version( 2, 1, 1 );
final Version v5 = new Version( 1, 0, 0 );
assertEquals( 0, v1.compareTo(v5) );
assertEquals( 0, v5.compareTo(v1) );
assertEquals( -1, v1.compareTo(v2) );
assertEquals( 1, v2.compareTo(v1) );
assertEquals( -1, v2.compareTo(v3) );
assertEquals( 1, v3.compareTo(v2) );
assertEquals( -1, v3.compareTo(v4) );
assertEquals( 1, v4.compareTo(v3) );
try
{
v4.compareTo(null);
fail( "Expected an exception!" );
}
catch( NullPointerException th )
{}
}
public void testEquals()
{
assertFalse( new Version( 1, 0, 0 ).equals( this ) );
assertFalse( new Version( 1, 0, 0 ).equals( null ) );
}
public void testToString()
{
assertEquals( "1.0.0", new Version( 1, 0, 0 ).toString() );
assertEquals( "230.21.-123456", new Version( 230, 21, -123456 ).toString() );
}
private int calculateHash(final Version v) {
int hash = v.getMajor();
hash >>>= 17;
hash += v.getMinor();
hash >>>= 17;
hash += v.getMicro();
return hash;
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/component/DefaultComponentManager.java 100644 0 0 12553 10051530442 31045 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.component;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* This class is a static implementation of a ComponentManager. Allow ineritance
* and extension so you can generate a tree of ComponentManager each defining
* Component scope.
*
* * Deprecated: * Use {@link org.apache.avalon.framework.service.DefaultServiceManager} instead. * *
* * @author Avalon Development Team * @version CVS $Revision: 1.26 $ $Date: 2004/02/11 14:34:25 $ */ public class DefaultComponentManager implements ComponentManager { private final HashMap m_components = new HashMap(); private final ComponentManager m_parent; private boolean m_readOnly; /** * Construct ComponentManager with no parent. * */ public DefaultComponentManager() { this( null ); } /** * Construct ComponentManager with specified parent. * * @param parent the ComponentManagers parent */ public DefaultComponentManager( final ComponentManager parent ) { m_parent = parent; } /** * Retrieve Component by key from ComponentManager. * * @param key the key * @return the Component * @throws ComponentException if an error occurs */ public Component lookup( final String key ) throws ComponentException { final Component component = (Component)m_components.get( key ); if( null != component ) { return component; } else if( null != m_parent ) { return m_parent.lookup( key ); } else { throw new ComponentException( key, "Unable to provide implementation." ); } } /** * Returnstrue
if the component m_manager is managing a component
* with the specified key, false
otherwise.
*
* @param key key of the component you are lokking for
* @return true
if the component m_manager has a component with that key
*/
public boolean hasComponent( final String key )
{
boolean componentExists = false;
try
{
this.release( this.lookup( key ) );
componentExists = true;
}
catch( Throwable t )
{
// Ignore all throwables--we want a yes or no answer.
}
return componentExists;
}
/**
* Place Component into ComponentManager.
*
* @param key the components key
* @param component the component
*/
public void put( final String key, final Component component )
{
checkWriteable();
m_components.put( key, component );
}
/**
* Release component.
*
* @param component the component
*/
public void release( final Component component )
{
// if the ComponentManager handled pooling, it would be
// returned to the pool here.
}
/**
* Build a human readable representation of ComponentManager.
*
* @return the description of ComponentManager
*/
public String toString()
{
final StringBuffer buffer = new StringBuffer();
final Iterator components = m_components.keySet().iterator();
buffer.append( "Components:" );
while( components.hasNext() )
{
buffer.append( "[" );
buffer.append( components.next() );
buffer.append( "]" );
}
return buffer.toString();
}
/**
* Helper method for subclasses to retrieve parent.
*
* @return the parent ComponentManager
*/
protected final ComponentManager getParent()
{
return m_parent;
}
/**
* Helper method for subclasses to retrieve component map.
*
* @return the component map
*/
protected final Map getComponentMap()
{
return m_components;
}
/**
* Make this component m_manager read only.
*/
public void makeReadOnly()
{
m_readOnly = true;
}
/**
* Check if this component m_manager is writeable.
*
* @throws IllegalStateException if this component m_manager is read-only
*/
protected final void checkWriteable()
throws IllegalStateException
{
if( m_readOnly )
{
final String message =
"ComponentManager is read only and can not be modified";
throw new IllegalStateException( message );
}
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/component/DefaultComponentSelector.java 100644 0 0 7440 10051530442 31232 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.component;
import java.util.HashMap;
import java.util.Map;
/**
* This is the default implementation of the ComponentSelector.
*
* * Deprecated: * Use {@link org.apache.avalon.framework.service.DefaultServiceSelector} instead. * *
* * @author Avalon Development Team * @version CVS $Revision: 1.23 $ $Date: 2004/02/11 14:34:25 $ */ public class DefaultComponentSelector implements ComponentSelector { private final HashMap m_components = new HashMap(); private boolean m_readOnly; /** * Select the desired component. It does not cascade, neither * should it. * * @param hint the hint to retrieve Component * @return the Component * @throws ComponentException if an error occurs */ public Component select( Object hint ) throws ComponentException { final Component component = (Component)m_components.get( hint ); if( null != component ) { return component; } else { throw new ComponentException( hint.toString(), "Unable to provide implementation." ); } } /** * Returns whether a Component exists or not * @param hint the hint to retrieve Component * @returntrue
if the Component exists
*/
public boolean hasComponent( final Object hint )
{
boolean componentExists = false;
try
{
this.release( this.select( hint ) );
componentExists = true;
}
catch( Throwable t )
{
// Ignore all throwables--we want a yes or no answer.
}
return componentExists;
}
/**
* Release component.
*
* @param component the component
*/
public void release( final Component component )
{
// if the ComponentManager handled pooling, it would be
// returned to the pool here.
}
/**
* Populate the ComponentSelector.
* @param hint the hint to retrieve Component
* @param component the component to add
*/
public void put( final Object hint, final Component component )
{
checkWriteable();
m_components.put( hint, component );
}
/**
* Helper method for subclasses to retrieve component map.
*
* @return the component map
*/
protected final Map getComponentMap()
{
return m_components;
}
/**
* Make this component selector read-only.
*/
public void makeReadOnly()
{
m_readOnly = true;
}
/**
* Check if this component m_manager is writeable.
*
* @throws IllegalStateException if this component m_manager is read-only
*/
protected final void checkWriteable()
throws IllegalStateException
{
if( m_readOnly )
{
throw new IllegalStateException
( "ComponentSelector is read only and can not be modified" );
}
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/component/WrapperComponentManager.java 100644 0 0 10665 10051530441 31102 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.component;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceSelector;
/**
* This is a {@link ComponentManager} implementation that can wrap around a
* {@link ServiceManager} object effectively adapting a {@link ServiceManager}
* interface to a {@link ComponentManager} interface.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.18 $ $Date: 2004/02/11 14:34:25 $
* @since 4.1.4
*/
public class WrapperComponentManager
implements ComponentManager
{
/**
* The service manager we are adapting.
*/
private final ServiceManager m_manager;
/**
* Creation of a new wrapper component manger using a supplied
* service manager as a source backing the wrapped. This implementation
* redirects lookup requests to the supplied service manager provided under
* this constructor. No attempt is made to proxy object supplied by the
* primary manager as Component instances - as such, it is the responsibility
* of the application establishing the wrapper to ensure that objects
* accessed via the primary manager implement the Component interface.
*
* @param manager the service manager backing the wrapper.
*/
public WrapperComponentManager( final ServiceManager manager )
{
if( null == manager )
{
throw new NullPointerException( "manager" );
}
m_manager = manager;
}
/**
* Retrieve a component via a key.
*
* @param key the key
* @return the component
* @throws ComponentException if unable to aquire component
*/
public Component lookup( final String key )
throws ComponentException
{
try
{
final Object object = m_manager.lookup( key );
if( object instanceof ServiceSelector )
{
return new WrapperComponentSelector( key, (ServiceSelector)object );
}
else if( object instanceof Component )
{
return (Component)object;
}
}
catch( final ServiceException se )
{
throw new ComponentException( se.getKey(), se.getMessage(), se.getCause() );
}
final String message = "Role does not implement the Component " +
"interface and thus can not be accessed via ComponentManager";
throw new ComponentException( key, message );
}
/**
* Check to see if a Component
exists for a key.
*
* @param key a string identifying the key to check.
* @return True if the component exists, False if it does not.
*/
public boolean hasComponent( final String key )
{
return m_manager.hasService( key );
}
/**
* Return the Component
when you are finished with it. This
* allows the ComponentManager
to handle the End-Of-Life Lifecycle
* events associated with the Component. Please note, that no Exceptions
* should be thrown at this point. This is to allow easy use of the
* ComponentManager system without having to trap Exceptions on a release.
*
* @param component The Component we are releasing.
*/
public void release( final Component component )
{
if( component instanceof WrapperComponentSelector )
{
final WrapperComponentSelector selector = (WrapperComponentSelector)component;
m_manager.release( selector.getWrappedSelector() );
}
else
{
m_manager.release( component );
}
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/component/WrapperComponentSelector.java 100644 0 0 10366 10051530441 31306 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.component;
import org.apache.avalon.framework.service.ServiceSelector;
import org.apache.avalon.framework.service.ServiceException;
/**
* This is a {@link ServiceSelector} implementation that can wrap around a legacy
* {@link ComponentSelector} object effectively adapting a {@link ComponentSelector}
* interface to a {@link ServiceSelector} interface.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.11 $ $Date: 2004/02/11 14:34:25 $
* @since 4.1.4
*/
public class WrapperComponentSelector
implements ComponentSelector
{
/**
* The Selector we are wrapping.
*/
private final ServiceSelector m_selector;
/**
* The role that this selector was aquired via.
*/
private final String m_key;
/**
* This constructor is a constructor for a WrapperComponentSelector.
*
* @param key the key used to aquire this selector
* @param selector the selector to wrap
*/
public WrapperComponentSelector( final String key,
final ServiceSelector selector )
{
if( null == key )
{
throw new NullPointerException( "key" );
}
if( null == selector )
{
throw new NullPointerException( "selector" );
}
m_key = key + "/";
m_selector = selector;
}
/**
* Select a Component based on a policy.
*
* @param policy the policy
* @return the Component
* @throws ComponentException if unable to select service
*/
public Component select( final Object policy )
throws ComponentException
{
try
{
final Object object = m_selector.select( policy );
if( object instanceof Component )
{
return (Component)object;
}
}
catch( final ServiceException se )
{
throw new ComponentException( m_key + policy, se.getMessage(), se );
}
final String message = "Role does not implement the Component "
+ "interface and thus can not be accessed via ComponentSelector";
throw new ComponentException( m_key + policy, message );
}
/**
* Check to see if a {@link Component} exists relative to the supplied policy.
*
* @param policy a {@link Object} containing the selection criteria
* @return True if the component is available, False if it not.
*/
public boolean hasComponent( final Object policy )
{
return m_selector.isSelectable( policy );
}
/**
* Return the {@link Object} when you are finished with it. This
* allows the {@link ServiceSelector} to handle the End-Of-Life Lifecycle
* events associated with the {@link Object}. Please note, that no
* Exception should be thrown at this point. This is to allow easy use of the
* ServiceSelector system without having to trap Exceptions on a release.
*
* @param object The {@link Object} we are releasing.
*/
public void release( final Component object )
{
m_selector.release( object );
}
/**
* The {@link WrapperComponentManager} wraps ServiceSelectors in
* WrapperServiceSelectors when they are looked up. This method
* makes it possible to release the original component selector.
*
* @return The {@link ServiceSelector} being wrapped.
*/
ServiceSelector getWrappedSelector()
{
return m_selector;
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/AbstractConfiguration.java 100644 0 0 44235 10051530441 31444 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration;
/**
* This is an abstract Configuration
implementation that deals
* with methods that can be abstracted away from underlying implementations.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.31 $ $Date: 2004/02/11 14:34:25 $
*/
public abstract class AbstractConfiguration
implements Configuration
{
/**
* Returns the prefix of the namespace. This is only used as a serialization
* hint, therefore is not part of the client API. It should be included in
* all Configuration implementations though.
* @return A non-null String (defaults to "")
* @throws ConfigurationException if no prefix was defined (prefix is
* null
.
* @since 4.1
*/
protected abstract String getPrefix() throws ConfigurationException;
/**
* Returns the value of the configuration element as an int
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @throws ConfigurationException if an error occurs
* @return the value
*/
public int getValueAsInteger()
throws ConfigurationException
{
final String value = getValue().trim();
try
{
if( value.startsWith( "0x" ) )
{
return Integer.parseInt( value.substring( 2 ), 16 );
}
else if( value.startsWith( "0o" ) )
{
return Integer.parseInt( value.substring( 2 ), 8 );
}
else if( value.startsWith( "0b" ) )
{
return Integer.parseInt( value.substring( 2 ), 2 );
}
else
{
return Integer.parseInt( value );
}
}
catch( final Exception nfe )
{
final String message =
"Cannot parse the value \"" + value
+ "\" as an integer in the configuration element \""
+ getName() + "\" at " + getLocation();
throw new ConfigurationException( message );
}
}
/**
* Returns the value of the configuration element as an int
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public int getValueAsInteger( final int defaultValue )
{
try
{
return getValueAsInteger();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a long
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @throws ConfigurationException if an error occurs
* @return the value
*/
public long getValueAsLong()
throws ConfigurationException
{
final String value = getValue().trim();
try
{
if( value.startsWith( "0x" ) )
{
return Long.parseLong( value.substring( 2 ), 16 );
}
else if( value.startsWith( "0o" ) )
{
return Long.parseLong( value.substring( 2 ), 8 );
}
else if( value.startsWith( "0b" ) )
{
return Long.parseLong( value.substring( 2 ), 2 );
}
else
{
return Long.parseLong( value );
}
}
catch( final Exception nfe )
{
final String message =
"Cannot parse the value \"" + value
+ "\" as a long in the configuration element \""
+ getName() + "\" at " + getLocation();
throw new ConfigurationException( message );
}
}
/**
* Returns the value of the configuration element as a long
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public long getValueAsLong( final long defaultValue )
{
try
{
return getValueAsLong();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a float
.
*
* @throws ConfigurationException if an error occurs
* @return the value
*/
public float getValueAsFloat()
throws ConfigurationException
{
final String value = getValue().trim();
try
{
return Float.parseFloat( value );
}
catch( final Exception nfe )
{
final String message =
"Cannot parse the value \"" + value
+ "\" as a float in the configuration element \""
+ getName() + "\" at " + getLocation();
throw new ConfigurationException( message );
}
}
/**
* Returns the value of the configuration element as a float
.
*
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public float getValueAsFloat( final float defaultValue )
{
try
{
return getValueAsFloat();
}
catch( final ConfigurationException ce )
{
return ( defaultValue );
}
}
/**
* Returns the value of the configuration element as a boolean
.
*
* @throws ConfigurationException if an error occurs
* @return the value
*/
public boolean getValueAsBoolean()
throws ConfigurationException
{
final String value = getValue().trim();
if( isTrue( value ) )
{
return true;
}
else if( isFalse( value ) )
{
return false;
}
else
{
final String message =
"Cannot parse the value \"" + value
+ "\" as a boolean in the configuration element \""
+ getName() + "\" at " + getLocation();
throw new ConfigurationException( message );
}
}
/**
* Returns the value of the configuration element as a boolean
.
*
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public boolean getValueAsBoolean( final boolean defaultValue )
{
try
{
return getValueAsBoolean();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a String
.
*
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public String getValue( final String defaultValue )
{
try
{
return getValue();
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the attribute specified by its name as an
* int
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of the attribute
* @throws ConfigurationException if an error occurs
* @return the value
*/
public int getAttributeAsInteger( final String name )
throws ConfigurationException
{
final String value = getAttribute( name ).trim();
try
{
if( value.startsWith( "0x" ) )
{
return Integer.parseInt( value.substring( 2 ), 16 );
}
else if( value.startsWith( "0o" ) )
{
return Integer.parseInt( value.substring( 2 ), 8 );
}
else if( value.startsWith( "0b" ) )
{
return Integer.parseInt( value.substring( 2 ), 2 );
}
else
{
return Integer.parseInt( value );
}
}
catch( final Exception nfe )
{
final String message =
"Cannot parse the value \"" + value
+ "\" as an integer in the attribute \""
+ name + "\" at " + getLocation();
throw new ConfigurationException( message );
}
}
/**
* Returns the value of the attribute specified by its name as an
* int
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of the attribute
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public int getAttributeAsInteger( final String name, final int defaultValue )
{
try
{
return getAttributeAsInteger( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the attribute specified by its name as a
* long
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of the attribute
* @throws ConfigurationException if an error occurs
* @return the value
*/
public long getAttributeAsLong( final String name )
throws ConfigurationException
{
final String value = getAttribute( name );
try
{
if( value.startsWith( "0x" ) )
{
return Long.parseLong( value.substring( 2 ), 16 );
}
else if( value.startsWith( "0o" ) )
{
return Long.parseLong( value.substring( 2 ), 8 );
}
else if( value.startsWith( "0b" ) )
{
return Long.parseLong( value.substring( 2 ), 2 );
}
else
{
return Long.parseLong( value );
}
}
catch( final Exception nfe )
{
final String message =
"Cannot parse the value \"" + value
+ "\" as a long in the attribute \""
+ name + "\" at " + getLocation();
throw new ConfigurationException( message );
}
}
/**
* Returns the value of the attribute specified by its name as a
* long
.
*
* Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
* numbers begin with 0b, all other values are assumed to be decimal.
*
* @param name the name of the attribute
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public long getAttributeAsLong( final String name, final long defaultValue )
{
try
{
return getAttributeAsLong( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the attribute specified by its name as a
* float
.
*
* @param name the name of the attribute
* @throws ConfigurationException if an error occurs
* @return the value
*/
public float getAttributeAsFloat( final String name )
throws ConfigurationException
{
final String value = getAttribute( name );
try
{
return Float.parseFloat( value );
}
catch( final Exception e )
{
final String message =
"Cannot parse the value \"" + value
+ "\" as a float in the attribute \""
+ name + "\" at " + getLocation();
throw new ConfigurationException( message );
}
}
/**
* Returns the value of the attribute specified by its name as a
* float
.
*
* @param name the name of the attribute
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public float getAttributeAsFloat( final String name, final float defaultValue )
{
try
{
return getAttributeAsFloat( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the attribute specified by its name as a
* boolean
.
*
* @param name the name of the attribute
* @throws ConfigurationException if an error occurs
* @return the value
*/
public boolean getAttributeAsBoolean( final String name )
throws ConfigurationException
{
final String value = getAttribute( name );
if( isTrue( value ) )
{
return true;
}
else if( isFalse( value ) )
{
return false;
}
else
{
final String message =
"Cannot parse the value \"" + value
+ "\" as a boolean in the attribute \""
+ name + "\" at " + getLocation();
throw new ConfigurationException( message );
}
}
private boolean isTrue( final String value )
{
return value.equalsIgnoreCase( "true" )
|| value.equalsIgnoreCase( "yes" )
|| value.equalsIgnoreCase( "on" )
|| value.equalsIgnoreCase( "1" );
}
private boolean isFalse( final String value )
{
return value.equalsIgnoreCase( "false" )
|| value.equalsIgnoreCase( "no" )
|| value.equalsIgnoreCase( "off" )
|| value.equalsIgnoreCase( "0" );
}
/**
* Returns the value of the attribute specified by its name as a
* boolean
.
*
* @param name the name of the attribute
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public boolean getAttributeAsBoolean( final String name, final boolean defaultValue )
{
try
{
return getAttributeAsBoolean( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Returns the value of the attribute specified by its name as a
* String
.
*
* @param name the name of the attribute
* @param defaultValue the default value to return if value malformed or empty
* @return the value
*/
public String getAttribute( final String name, final String defaultValue )
{
try
{
return getAttribute( name );
}
catch( final ConfigurationException ce )
{
return defaultValue;
}
}
/**
* Return the first Configuration
object child of this
* associated with the given name. If no such child exists, a new one
* will be created.
*
* @param name the name of the child
* @return the child Configuration
*/
public Configuration getChild( final String name )
{
return getChild( name, true );
}
/**
* Return the first Configuration
object child of this
* associated with the given name.
*
* @param name the name of the child
* @param createNew true if you want to create a new Configuration object if none exists
* @return the child Configuration
*/
public Configuration getChild( final String name, final boolean createNew )
{
final Configuration[] children = getChildren( name );
if( children.length > 0 )
{
return children[ 0 ];
}
else
{
if( createNew )
{
return new DefaultConfiguration( name, "-" );
}
else
{
return null;
}
}
}
/**
* The toString() operation is used for debugging information. It does
* not create a deep reproduction of this configuration and all child configurations,
* instead it displays the name, value, and location.
*
* @return getName() + "::" + getValue() + ":@" + getLocation();
*/
public String toString()
{
return getName() + "::" + getValue("Configuration
,
* or an error message.
* @since 12 March, 2003
*/
public static String toString( final Configuration configuration )
{
DefaultConfigurationSerializer ser = new DefaultConfigurationSerializer();
try
{
return ser.serialize( configuration );
}
catch( Exception e )
{
return e.getMessage();
}
}
/**
* Test to see if two Configuration's can be considered the same. Name, value, attributes
* and children are test. The order of children is not taken into consideration
* for equality.
*
* @param c1 Configuration to test
* @param c2 Configuration to test
* @return true if the configurations can be considered equals
*/
public static boolean equals( final Configuration c1, final Configuration c2 )
{
return c1.getName().equals( c2.getName() ) && areValuesEqual( c1, c2 ) &&
areAttributesEqual( c1, c2 ) && areChildrenEqual( c1, c2 );
}
/**
* Return true if the children of both configurations are equal.
*
* @param c1 configuration1
* @param c2 configuration2
* @return true if the children of both configurations are equal.
*/
private static boolean areChildrenEqual( final Configuration c1,
final Configuration c2 )
{
final Configuration[] kids1 = c1.getChildren();
final ArrayList kids2 = new ArrayList( Arrays.asList( c2.getChildren() ) );
if( kids1.length != kids2.size() )
{
return false;
}
for( int i = 0; i < kids1.length; i++ )
{
if( !findMatchingChild( kids1[ i ], kids2 ) )
{
return false;
}
}
return kids2.isEmpty() ? true : false;
}
/**
* Return true if find a matching child and remove child from list.
*
* @param c the configuration
* @param matchAgainst the list of items to match against
* @return true if the found.
*/
private static boolean findMatchingChild( final Configuration c,
final ArrayList matchAgainst )
{
final Iterator i = matchAgainst.iterator();
while( i.hasNext() )
{
if( equals( c, (Configuration)i.next() ) )
{
i.remove();
return true;
}
}
return false;
}
/**
* Return true if the attributes of both configurations are equal.
*
* @param c1 configuration1
* @param c2 configuration2
* @return true if the attributes of both configurations are equal.
*/
private static boolean areAttributesEqual( final Configuration c1,
final Configuration c2 )
{
final String[] names1 = c1.getAttributeNames();
final String[] names2 = c2.getAttributeNames();
if( names1.length != names2.length )
{
return false;
}
for( int i = 0; i < names1.length; i++ )
{
final String name = names1[ i ];
final String value1 = c1.getAttribute( name, null );
final String value2 = c2.getAttribute( name, null );
if( !value1.equals( value2 ) )
{
return false;
}
}
return true;
}
/**
* Return true if the values of two configurations are equal.
*
* @param c1 configuration1
* @param c2 configuration2
* @return true if the values of two configurations are equal.
*/
private static boolean areValuesEqual( final Configuration c1,
final Configuration c2 )
{
final String value1 = c1.getValue( null );
final String value2 = c2.getValue( null );
return ( value1 == null && value2 == null ) ||
( value1 != null && value1.equals( value2 ) );
}
/**
* Create an DOM {@link Element} from a {@link Configuration}
* object.
*
* @param document the DOM document
* @param configuration the configuration to convert
* @return the DOM Element
*/
private static Element createElement( final Document document,
final Configuration configuration )
{
final Element element = document.createElement( configuration.getName() );
final String content = configuration.getValue( null );
if( null != content )
{
final Text child = document.createTextNode( content );
element.appendChild( child );
}
final String[] names = configuration.getAttributeNames();
for( int i = 0; i < names.length; i++ )
{
final String name = names[ i ];
final String value = configuration.getAttribute( name, null );
element.setAttribute( name, value );
}
final Configuration[] children = configuration.getChildren();
for( int i = 0; i < children.length; i++ )
{
final Element child = createElement( document, children[ i ] );
element.appendChild( child );
}
return element;
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/DefaultConfiguration.java 100644 0 0 55612 10051530441 31266 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
/**
* This is the default Configuration
implementation.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.43 $ $Date: 2004/02/11 14:34:25 $
*/
public class DefaultConfiguration
extends AbstractConfiguration
implements MutableConfiguration, Serializable
{
/**
* An empty (length zero) array of configuration objects.
*/
protected static final Configuration[] EMPTY_ARRAY = new Configuration[ 0 ];
private final String m_name;
private final String m_location;
private final String m_namespace;
private final String m_prefix;
private HashMap m_attributes;
private ArrayList m_children;
private String m_value;
private boolean m_readOnly;
/**
* Shallow copy constructor, suitable for craeting a writable clone of
* a read-only configuration. To modify children, use getChild()
,
* removeChild()
and addChild()
.
*
* @param config the Configuration
to copy
* @throws ConfigurationException if an error occurs when copying
*/
public DefaultConfiguration( Configuration config ) throws ConfigurationException
{
this( config.getName(), config.getLocation(), config.getNamespace(),
( (config instanceof AbstractConfiguration) ? ((AbstractConfiguration)config).getPrefix() : "") );
addAll( config );
}
/**
* Create a new DefaultConfiguration
instance.
* @param name a String
value
*/
public DefaultConfiguration( final String name )
{
this( name, null, "", "" );
}
/**
* Create a new DefaultConfiguration
instance.
* @param name a String
value
* @param location a String
value
*/
public DefaultConfiguration( final String name, final String location )
{
this( name, location, "", "" );
}
/**
* Create a new DefaultConfiguration
instance.
* @param name config node name
* @param location Builder-specific locator string
* @param ns Namespace string (typically a URI). Should not be null; use ""
* if no namespace.
* @param prefix A short string prefixed to element names, associating
* elements with a longer namespace string. Should not be null; use "" if no
* namespace.
* @since 4.1
*/
public DefaultConfiguration( final String name,
final String location,
final String ns,
final String prefix )
{
m_name = name;
m_location = location;
m_namespace = ns;
m_prefix = prefix; // only used as a serialization hint. Cannot be null
}
/**
* Returns the name of this configuration element.
* @return a String
value
*/
public String getName()
{
return m_name;
}
/**
* Returns the namespace of this configuration element
* @return a String
value
* @throws ConfigurationException if an error occurs
* @since 4.1
*/
public String getNamespace() throws ConfigurationException
{
if( null != m_namespace )
{
return m_namespace;
}
else
{
throw new ConfigurationException
( "No namespace (not even default \"\") is associated with the "
+ "configuration element \"" + getName()
+ "\" at " + getLocation() );
}
}
/**
* Returns the prefix of the namespace
* @return a String
value
* @throws ConfigurationException if prefix is not present (null
).
* @since 4.1
*/
protected String getPrefix() throws ConfigurationException
{
if( null != m_prefix )
{
return m_prefix;
}
else
{
throw new ConfigurationException
( "No prefix (not even default \"\") is associated with the "
+ "configuration element \"" + getName()
+ "\" at " + getLocation() );
}
}
/**
* Returns a description of location of element.
* @return a String
value
*/
public String getLocation()
{
return m_location;
}
/**
* Returns the value of the configuration element as a String
.
*
* @param defaultValue the default value to return if value malformed or empty
* @return a String
value
*/
public String getValue( final String defaultValue )
{
if( null != m_value )
{
return m_value;
}
else
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a String
.
*
* @return a String
value
* @throws ConfigurationException If the value is not present.
*/
public String getValue() throws ConfigurationException
{
if( null != m_value )
{
return m_value;
}
else
{
throw new ConfigurationException( "No value is associated with the "
+ "configuration element \"" + getName()
+ "\" at " + getLocation() );
}
}
/**
* Return an array of all attribute names.
* @return a String[]
value
*/
public String[] getAttributeNames()
{
if( null == m_attributes )
{
return new String[ 0 ];
}
else
{
return (String[])m_attributes.keySet().toArray( new String[ 0 ] );
}
}
/**
* Return an array of Configuration
* elements containing all node children.
*
* @return The child nodes with name
*/
public Configuration[] getChildren()
{
if( null == m_children )
{
return new Configuration[ 0 ];
}
else
{
return (Configuration[])m_children.toArray( new Configuration[ 0 ] );
}
}
/**
* Returns the value of the attribute specified by its name as a
* String
.
*
* @param name a String
value
* @return a String
value
* @throws ConfigurationException If the attribute is not present.
*/
public String getAttribute( final String name )
throws ConfigurationException
{
final String value =
( null != m_attributes ) ? (String)m_attributes.get( name ) : null;
if( null != value )
{
return value;
}
else
{
throw new ConfigurationException(
"No attribute named \"" + name + "\" is "
+ "associated with the configuration element \""
+ getName() + "\" at " + getLocation() );
}
}
/**
* Return the first Configuration
object child of this
* associated with the given name.
* @param name a String
value
* @param createNew a boolean
value
* @return a Configuration
value
*/
public Configuration getChild( final String name, final boolean createNew )
{
if( null != m_children )
{
final int size = m_children.size();
for( int i = 0; i < size; i++ )
{
final Configuration configuration = (Configuration)m_children.get( i );
if( name.equals( configuration.getName() ) )
{
return configuration;
}
}
}
if( createNew )
{
return new DefaultConfiguration( name, "Configuration
objects
* children of this associated with the given name.
* null
.
*
* @param name The name of the required children Configuration
.
* @return a Configuration[]
value
*/
public Configuration[] getChildren( final String name )
{
if( null == m_children )
{
return new Configuration[ 0 ];
}
else
{
final ArrayList children = new ArrayList();
final int size = m_children.size();
for( int i = 0; i < size; i++ )
{
final Configuration configuration = (Configuration)m_children.get( i );
if( name.equals( configuration.getName() ) )
{
children.add( configuration );
}
}
return (Configuration[])children.toArray( new Configuration[ 0 ] );
}
}
/**
* Append data to the value of this configuration element.
*
* @param value a String
value
* @deprecated Use setValue() instead
*/
public void appendValueData( final String value )
{
checkWriteable();
if( null == m_value )
{
m_value = value;
}
else
{
m_value += value;
}
}
/**
* Set the value of this Configuration
object to the specified string.
*
* @param value a String
value
*/
public void setValue( final String value )
{
checkWriteable();
m_value = value;
}
/**
* Set the value of this Configuration
object to the specified int.
*
* @param value a int
value
*/
public void setValue( final int value )
{
setValue( String.valueOf( value ) );
}
/**
* Set the value of this Configuration
object to the specified long.
*
* @param value a long
value
*/
public void setValue( final long value )
{
setValue( String.valueOf( value ) );
}
/**
* Set the value of this Configuration
object to the specified boolean.
*
* @param value a boolean
value
*/
public void setValue( final boolean value )
{
setValue( String.valueOf( value ) );
}
/**
* Set the value of this Configuration
object to the specified float.
*
* @param value a float
value
*/
public void setValue( final float value )
{
setValue( String.valueOf( value ) );
}
/**
* Set the value of the specified attribute to the specified string.
*
* @param name name of the attribute to set
* @param value a String
value
*/
public void setAttribute( final String name, final String value )
{
checkWriteable();
if( null != value )
{
if( null == m_attributes )
{
m_attributes = new HashMap();
}
m_attributes.put( name, value );
}
else
{
if( null != m_attributes )
{
m_attributes.remove( name );
}
}
}
/**
* Set the value of the specified attribute to the specified int.
*
* @param name name of the attribute to set
* @param value an int
value
*/
public void setAttribute( final String name, final int value )
{
setAttribute( name, String.valueOf( value ) );
}
/**
* Set the value of the specified attribute to the specified long.
*
* @param name name of the attribute to set
* @param value an long
value
*/
public void setAttribute( final String name, final long value )
{
setAttribute( name, String.valueOf( value ) );
}
/**
* Set the value of the specified attribute to the specified boolean.
*
* @param name name of the attribute to set
* @param value an boolean
value
*/
public void setAttribute( final String name, final boolean value )
{
setAttribute( name, String.valueOf( value ) );
}
/**
* Set the value of the specified attribute to the specified float.
*
* @param name name of the attribute to set
* @param value an float
value
*/
public void setAttribute( final String name, final float value )
{
setAttribute( name, String.valueOf( value ) );
}
/**
* Add an attribute to this configuration element, returning its old
* value or null.
*
* @param name a String
value
* @param value a String
value
* @return a String
value
* @deprecated Use setAttribute() instead
*/
public String addAttribute( final String name, String value )
{
checkWriteable();
if( null == m_attributes )
{
m_attributes = new HashMap();
}
return (String)m_attributes.put( name, value );
}
/**
* Add a child Configuration
to this configuration element.
* @param configuration a Configuration
value
*/
public void addChild( final Configuration configuration )
{
checkWriteable();
if( null == m_children )
{
m_children = new ArrayList();
}
m_children.add( configuration );
}
/**
* Add all the attributes, children and value
* from specified configuration element to current
* configuration element.
*
* @param other the {@link Configuration} element
*/
public void addAll( final Configuration other )
{
checkWriteable();
setValue( other.getValue( null ) );
addAllAttributes( other );
addAllChildren( other );
}
/**
* Add all attributes from specified configuration
* element to current configuration element.
*
* @param other the {@link Configuration} element
*/
public void addAllAttributes( final Configuration other )
{
checkWriteable();
final String[] attributes = other.getAttributeNames();
for( int i = 0; i < attributes.length; i++ )
{
final String name = attributes[ i ];
final String value = other.getAttribute( name, null );
setAttribute( name, value );
}
}
/**
* Add all child Configuration
objects from specified
* configuration element to current configuration element.
*
* @param other the other {@link Configuration} value
*/
public void addAllChildren( final Configuration other )
{
checkWriteable();
final Configuration[] children = other.getChildren();
for( int i = 0; i < children.length; i++ )
{
addChild( children[ i ] );
}
}
/**
* Remove a child Configuration
to this configuration element.
* @param configuration a Configuration
value
*/
public void removeChild( final Configuration configuration )
{
checkWriteable();
if( null == m_children )
{
return;
}
m_children.remove( configuration );
}
/**
* Return count of children.
* @return an int
value
*/
public int getChildCount()
{
if( null == m_children )
{
return 0;
}
return m_children.size();
}
/**
* Make this configuration read-only.
*
*/
public void makeReadOnly()
{
m_readOnly = true;
}
/**
* heck if this configuration is writeable.
*
* @throws IllegalStateException if this configuration s read-only
*/
protected final void checkWriteable()
throws IllegalStateException
{
if( m_readOnly )
{
throw new IllegalStateException
( "Configuration is read only and can not be modified" );
}
}
/**
* Returns true iff this DefaultConfiguration has been made read-only.
*/
protected final boolean isReadOnly()
{
return m_readOnly;
}
/**
* Convenience function to convert a child to a mutable configuration.
* If the child is-a MutableConfiguration, and it isn't a read-only DefaultConfiguration
* (which isn't really mutable), the child is cast to MutableConfiguration and returned.
* If not, the child is replaced in the m_children array with a new writable DefaultConfiguration
* that is a shallow copy of the child, and the new child is returned.
*/
private MutableConfiguration toMutable( Configuration child ) throws ConfigurationException
{
if (child instanceof MutableConfiguration &&
!( child instanceof DefaultConfiguration && ((DefaultConfiguration) child).isReadOnly() ))
{
// Child is already mutable - return it.
return (MutableConfiguration) child;
}
// Child isn't mutable. (This is a mutating operation, so let's check
// if we're writable.)
checkWriteable();
DefaultConfiguration config = new DefaultConfiguration( child );
// Replace the old child.
for( int i = 0; i < m_children.size(); i++)
{
if( m_children.get(i) == child )
{
m_children.set( i, config );
break;
}
}
return config;
}
public MutableConfiguration getMutableChild( final String name ) throws ConfigurationException
{
return getMutableChild( name, true );
}
public MutableConfiguration getMutableChild( final String name, boolean autoCreate ) throws ConfigurationException
{
Configuration child = getChild( name, false );
if( child == null )
{
// No child. Create?
if( autoCreate )
{
DefaultConfiguration config = new DefaultConfiguration( name, "-" );
addChild( config );
return config;
}
else
{
return null;
}
}
// Child exists
return toMutable( child );
}
public MutableConfiguration[] getMutableChildren() throws ConfigurationException
{
if( null == m_children )
{
return new MutableConfiguration[ 0 ];
}
else
{
final ArrayList children = new ArrayList();
final int size = m_children.size();
for( int i = 0; i < size; i++ )
{
final Configuration configuration = (Configuration)m_children.get( i );
children.add( toMutable( configuration ) );
}
return (MutableConfiguration[])children.toArray( new MutableConfiguration[ 0 ] );
}
}
public MutableConfiguration[] getMutableChildren( final String name ) throws ConfigurationException
{
if( null == m_children )
{
return new MutableConfiguration[ 0 ];
}
else
{
final ArrayList children = new ArrayList();
final int size = m_children.size();
for( int i = 0; i < size; i++ )
{
final Configuration configuration = (Configuration)m_children.get( i );
if( name.equals( configuration.getName() ) )
{
children.add( toMutable( configuration ) );
}
}
return (MutableConfiguration[])children.toArray( new MutableConfiguration[ 0 ] );
}
}
/**
* Compare if this configuration is equal to another.
*
* @param other The other configuration
* @return true
if they are the same.
*/
public boolean equals( Object other )
{
if( other == null ) return false;
if( !( other instanceof Configuration ) ) return false;
return ConfigurationUtil.equals( this, (Configuration) other );
}
/**
* Obtaine the hashcode for this configuration.
*
* @return the hashcode.
*/
public int hashCode()
{
int hash = m_prefix.hashCode();
if( m_name != null ) hash ^= m_name.hashCode();
hash >>>= 7;
if( m_location != null ) hash ^= m_location.hashCode();
hash >>>= 7;
if( m_namespace != null ) hash ^= m_namespace.hashCode();
hash >>>= 7;
if( m_attributes != null ) hash ^= m_attributes.hashCode();
hash >>>= 7;
if( m_children != null ) hash ^= m_children.hashCode();
hash >>>= 7;
if( m_value != null ) hash ^= m_value.hashCode();
hash >>>= 7;
hash ^= ( m_readOnly ) ? 1 : 3;
return hash;
}
}
././@LongLink 100644 0 0 152 10051530443 10244 L ustar 0 0 avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/DefaultConfigurationBuilder.java avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/DefaultConfigurationBuilder100644 0 0 23126 10051530441 31650 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* A DefaultConfigurationBuilder builds Configuration
s from XML,
* via a SAX2 compliant parser.
*
*
* XML namespace support is optional, and disabled by default to preserve
* backwards-compatibility. To enable it, pass the {@link
* #DefaultConfigurationBuilder(boolean)} constructor the flag true
, or pass
* a namespace-enabled XMLReader
to the {@link
* #DefaultConfigurationBuilder(XMLReader)} constructor.
*
* The mapping from XML namespaces to {@link Configuration} namespaces is pretty * straightforward, with one caveat: attribute namespaces are (deliberately) not * supported. Enabling namespace processing has the following effects:
*xmlns:
are interpreted as
* declaring a prefix:namespaceURI mapping, and won't result in the creation of
* xmlns
-prefixed attributes in the Configuration
.
* Configuration
with {@link
* Configuration#getName getName()}.equals("title")
and {@link
* Configuration#getNamespace getNamespace()}.equals("http://foo.com")
.
*
* Whitespace handling. Since mixed content is not allowed in the
* configurations, whitespace is completely discarded in non-leaf nodes.
* For the leaf nodes the default behavior is to trim the space
* surrounding the value. This can be changed by specifying
* xml:space
attribute with value of preserve
* in that case the whitespace is left intact.
*
true
, a namespace-aware
* SAXParser
is used. If false
, the default JAXP
* SAXParser
(without namespace support) is used.
* @since 4.1
*/
public DefaultConfigurationBuilder( final boolean enableNamespaces )
{
//yaya the bugs with some compilers and final variables ..
try
{
final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
if( enableNamespaces )
{
saxParserFactory.setNamespaceAware( true );
}
final SAXParser saxParser = saxParserFactory.newSAXParser();
setParser( saxParser.getXMLReader() );
}
catch( final Exception se )
{
throw new Error( "Unable to setup SAX parser" + se );
}
}
/**
* Create a Configuration Builder with your own XMLReader.
* @param parser an XMLReader
*/
public DefaultConfigurationBuilder( XMLReader parser )
{
setParser( parser );
}
/**
* Internally sets up the XMLReader
*/
private void setParser( XMLReader parser )
{
m_parser = parser;
m_handler = getHandler();
m_parser.setContentHandler( m_handler );
m_parser.setErrorHandler( m_handler );
}
/**
* Get a SAXConfigurationHandler for your configuration reading.
* @return a SAXConfigurationHandler
*/
protected SAXConfigurationHandler getHandler()
{
try
{
if( m_parser.getFeature( "http://xml.org/sax/features/namespaces" ) )
{
return new NamespacedSAXConfigurationHandler();
}
}
catch( Exception e )
{
// ignore error and fall through to the non-namespaced version
}
return new SAXConfigurationHandler();
}
/**
* Build a configuration object from a file using a filename.
* @param filename name of the file
* @return a Configuration
object
* @throws SAXException if a parsing error occurs
* @throws IOException if an I/O error occurs
* @throws ConfigurationException if an error occurs
*/
public Configuration buildFromFile( final String filename )
throws SAXException, IOException, ConfigurationException
{
return buildFromFile( new File( filename ) );
}
/**
* Build a configuration object from a file using a File object.
* @param file a File
object
* @return a Configuration
object
* @throws SAXException if a parsing error occurs
* @throws IOException if an I/O error occurs
* @throws ConfigurationException if an error occurs
*/
public Configuration buildFromFile( final File file )
throws SAXException, IOException, ConfigurationException
{
synchronized( this )
{
m_handler.clear();
m_parser.parse( file.toURL().toString() );
return m_handler.getConfiguration();
}
}
/**
* Build a configuration object using an InputStream.
* @param inputStream an InputStream
value
* @return a Configuration
object
* @throws SAXException if a parsing error occurs
* @throws IOException if an I/O error occurs
* @throws ConfigurationException if an error occurs
*/
public Configuration build( final InputStream inputStream )
throws SAXException, IOException, ConfigurationException
{
return build( new InputSource( inputStream ) );
}
/**
* Build a configuration object using an InputStream;
* supplying a systemId to make messages about all
* kinds of errors more meaningfull.
* @param inputStream an InputStream
value
* @param systemId the systemId to set on the intermediate sax
* inputSource
* @return a Configuration
object
* @throws SAXException if a parsing error occurs
* @throws IOException if an I/O error occurs
* @throws ConfigurationException if an error occurs
*/
public Configuration build( final InputStream inputStream,
final String systemId )
throws SAXException, IOException, ConfigurationException
{
final InputSource inputSource = new InputSource( inputStream );
inputSource.setSystemId( systemId );
return build( inputSource );
}
/**
* Build a configuration object using an URI
* @param uri a String
value
* @return a Configuration
object
* @throws SAXException if a parsing error occurs
* @throws IOException if an I/O error occurs
* @throws ConfigurationException if an error occurs
*/
public Configuration build( final String uri )
throws SAXException, IOException, ConfigurationException
{
return build( new InputSource( uri ) );
}
/**
* Build a configuration object using an XML InputSource object
* @param input an InputSource
value
* @return a Configuration
object
* @throws SAXException if a parsing error occurs
* @throws IOException if an I/O error occurs
* @throws ConfigurationException if an error occurs
*/
public Configuration build( final InputSource input )
throws SAXException, IOException, ConfigurationException
{
synchronized( this )
{
m_handler.clear();
m_parser.parse( input );
return m_handler.getConfiguration();
}
}
/**
* Sets the EntityResolver
to
* be used by parser. Useful when dealing with xml
* files that reference external entities.
*
* @param resolver implementation of EntityResolver
*/
public void setEntityResolver( final EntityResolver resolver )
{
synchronized( this )
{
m_parser.setEntityResolver( resolver );
}
}
}
././@LongLink 100644 0 0 155 10051530443 10247 L ustar 0 0 avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/DefaultConfigurationSerializer.java avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/DefaultConfigurationSeriali100644 0 0 25713 10051530442 31657 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.URL;
import java.util.Properties;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.NamespaceSupport;
/**
* A ConfigurationSerializer serializes configurations via SAX2 compliant parser.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.26 $ $Date: 2004/02/11 14:34:25 $
*/
public class DefaultConfigurationSerializer
{
private SAXTransformerFactory m_tfactory;
private Properties m_format = new Properties();
/**
* Sets the Serializer's use of indentation. This will cause linefeeds to be added
* after each element, but it does not add any indentation via spaces.
* @param indent a boolean
value
*/
public void setIndent( boolean indent )
{
if( indent )
{
m_format.put( OutputKeys.INDENT, "yes" );
}
else
{
m_format.put( OutputKeys.INDENT, "no" );
}
}
/**
* Create a ContentHandler for an OutputStream
* @param result the result
* @return contenthandler that goes to specified OutputStream
*/
protected ContentHandler createContentHandler( final Result result )
{
try
{
TransformerHandler handler = getTransformerFactory().newTransformerHandler();
m_format.put( OutputKeys.METHOD, "xml" );
handler.setResult( result );
handler.getTransformer().setOutputProperties( m_format );
return handler;
}
catch( final Exception e )
{
throw new RuntimeException( e.toString() );
}
}
/**
* Get the SAXTransformerFactory so we can get a serializer without being
* tied to one vendor.
* @return a SAXTransformerFactory
value
*/
protected SAXTransformerFactory getTransformerFactory()
{
if( m_tfactory == null )
{
m_tfactory = (SAXTransformerFactory)TransformerFactory.newInstance();
}
return m_tfactory;
}
/**
* Serialize the configuration to a ContentHandler
* @param handler a ContentHandler
to serialize to
* @param source a Configuration
value
* @throws SAXException if an error occurs
* @throws ConfigurationException if an error occurs
*/
public void serialize( final ContentHandler handler, final Configuration source )
throws SAXException, ConfigurationException
{
handler.startDocument();
serializeElement( handler, new NamespaceSupport(), source );
handler.endDocument();
}
/**
* Serialize each Configuration element. This method is called recursively.
* @param handler a ContentHandler
to use
* @param namespaceSupport a NamespaceSupport
to use
* @param element a Configuration
value
* @throws SAXException if an error occurs
* @throws ConfigurationException if an error occurs
*/
protected void serializeElement( final ContentHandler handler,
final NamespaceSupport namespaceSupport,
final Configuration element )
throws SAXException, ConfigurationException
{
namespaceSupport.pushContext();
AttributesImpl attr = new AttributesImpl();
String[] attrNames = element.getAttributeNames();
if( null != attrNames )
{
for( int i = 0; i < attrNames.length; i++ )
{
attr.addAttribute( "", // namespace URI
attrNames[ i ], // local name
attrNames[ i ], // qName
"CDATA", // type
element.getAttribute( attrNames[ i ], "" ) // value
);
}
}
final String nsURI = element.getNamespace();
String nsPrefix = "";
if( element instanceof AbstractConfiguration )
{
nsPrefix = ( (AbstractConfiguration)element ).getPrefix();
}
// nsPrefix is guaranteed to be non-null at this point.
boolean nsWasDeclared = false;
final String existingURI = namespaceSupport.getURI( nsPrefix );
// ie, there is no existing URI declared for this prefix or we're
// remapping the prefix to a different URI
if( existingURI == null || !existingURI.equals( nsURI ) )
{
nsWasDeclared = true;
if( nsPrefix.equals( "" ) && nsURI.equals( "" ) )
{
// implicit mapping; don't need to declare
}
else if( nsPrefix.equals( "" ) )
{
// (re)declare the default namespace
attr.addAttribute( "", "xmlns", "xmlns", "CDATA", nsURI );
}
else
{
// (re)declare a mapping from nsPrefix to nsURI
attr.addAttribute( "", "xmlns:" + nsPrefix, "xmlns:" + nsPrefix, "CDATA", nsURI );
}
handler.startPrefixMapping( nsPrefix, nsURI );
namespaceSupport.declarePrefix( nsPrefix, nsURI );
}
String localName = element.getName();
String qName = element.getName();
if( nsPrefix == null || nsPrefix.length() == 0 )
{
qName = localName;
}
else
{
qName = nsPrefix + ":" + localName;
}
handler.startElement( nsURI, localName, qName, attr );
String value = element.getValue( null );
if( null == value )
{
Configuration[] children = element.getChildren();
for( int i = 0; i < children.length; i++ )
{
serializeElement( handler, namespaceSupport, children[ i ] );
}
}
else
{
handler.characters( value.toCharArray(), 0, value.length() );
}
handler.endElement( nsURI, localName, qName );
if( nsWasDeclared )
{
handler.endPrefixMapping( nsPrefix );
}
namespaceSupport.popContext();
}
/**
* Serialize the configuration object to a file using a filename.
* @param filename a String
value
* @param source a Configuration
value
* @throws SAXException if an error occurs
* @throws IOException if an error occurs
* @throws ConfigurationException if an error occurs
*/
public void serializeToFile( final String filename, final Configuration source )
throws SAXException, IOException, ConfigurationException
{
serializeToFile( new File( filename ), source );
}
/**
* Serialize the configuration object to a file using a File object.
* @param file a File
value
* @param source a Configuration
value
* @throws SAXException if an error occurs
* @throws IOException if an error occurs
* @throws ConfigurationException if an error occurs
*/
public void serializeToFile( final File file, final Configuration source )
throws SAXException, IOException, ConfigurationException
{
OutputStream outputStream = null;
try
{
outputStream = new FileOutputStream( file );
serialize( outputStream, source );
}
finally
{
if( outputStream != null )
{
outputStream.close();
}
}
}
/**
* Serialize the configuration object to an output stream.
* @param outputStream an OutputStream
value
* @param source a Configuration
value
* @throws SAXException if an error occurs
* @throws IOException if an error occurs
* @throws ConfigurationException if an error occurs
*/
public void serialize( final OutputStream outputStream, final Configuration source )
throws SAXException, IOException, ConfigurationException
{
serialize( createContentHandler( new StreamResult( outputStream ) ), source );
}
/**
* Serialize the configuration object to an output stream derived from an
* URI. The URI must be resolveable by the java.net.URL
object.
* @param uri a String
value
* @param source a Configuration
value
* @throws SAXException if an error occurs
* @throws IOException if an error occurs
* @throws ConfigurationException if an error occurs
*/
public void serialize( final String uri, final Configuration source )
throws SAXException, IOException, ConfigurationException
{
OutputStream outputStream = null;
try
{
outputStream = new URL( uri ).openConnection().getOutputStream();
serialize( outputStream, source );
}
finally
{
if( outputStream != null )
{
outputStream.close();
}
}
}
/**
* Serialize the configuration object to a string
* @param source a Configuration
value
* @return configuration serialized as a string.
* @throws SAXException if an error occurs
* @throws ConfigurationException if an error occurs
*/
public String serialize( final Configuration source )
throws SAXException, ConfigurationException
{
final StringWriter writer = new StringWriter();
serialize( createContentHandler( new StreamResult( writer ) ), source );
return writer.toString();
}
}
././@LongLink 100644 0 0 154 10051530443 10246 L ustar 0 0 avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/DefaultImmutableConfiguration.java avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/DefaultImmutableConfigurati100644 0 0 25604 10051530441 31647 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
/**
* An immutable implementation of the Configuration
interface.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.2 $ $Date: 2004/02/11 14:34:25 $
*/
public class DefaultImmutableConfiguration
extends AbstractConfiguration
implements Serializable
{
/**
* An empty (length zero) array of configuration objects.
*/
protected static final Configuration[] EMPTY_ARRAY = new Configuration[ 0 ];
private final String m_name;
private final String m_location;
private final String m_namespace;
private final String m_prefix;
private final HashMap m_attributes;
private final ArrayList m_children;
private final String m_value;
/**
* Deep copy constructor.
*
* @param config the Configuration
to do a deep copy of.
* @throws ConfigurationException if an error occurs when copying
*/
public DefaultImmutableConfiguration( Configuration config ) throws ConfigurationException
{
m_name = config.getName();
m_location = config.getLocation();
m_namespace = config.getNamespace();
m_prefix = (config instanceof AbstractConfiguration) ? ((AbstractConfiguration)config).getPrefix() : "";
m_value = config.getValue( null );
final String[] attributes = config.getAttributeNames();
if( attributes.length > 0 )
{
m_attributes = new HashMap ();
for( int i = 0; i < attributes.length; i++ )
{
final String name = attributes[ i ];
final String value = config.getAttribute( name, null );
m_attributes.put( name, value );
}
}
else
{
m_attributes = null;
}
Configuration[] children = config.getChildren();
if( children.length > 0 )
{
m_children = new ArrayList ();
for( int i = 0; i < children.length; i++ )
{
// Deep copy
m_children.add( new DefaultImmutableConfiguration( children[i] ) );
}
}
else
{
m_children = null;
}
}
/**
* Returns the name of this configuration element.
* @return a String
value
*/
public String getName()
{
return m_name;
}
/**
* Returns the namespace of this configuration element
* @return a String
value
* @throws ConfigurationException if an error occurs
* @since 4.1
*/
public String getNamespace() throws ConfigurationException
{
if( null != m_namespace )
{
return m_namespace;
}
else
{
throw new ConfigurationException
( "No namespace (not even default \"\") is associated with the "
+ "configuration element \"" + getName()
+ "\" at " + getLocation() );
}
}
/**
* Returns the prefix of the namespace
* @return a String
value
* @throws ConfigurationException if prefix is not present (null
).
* @since 4.1
*/
protected String getPrefix() throws ConfigurationException
{
if( null != m_prefix )
{
return m_prefix;
}
else
{
throw new ConfigurationException
( "No prefix (not even default \"\") is associated with the "
+ "configuration element \"" + getName()
+ "\" at " + getLocation() );
}
}
/**
* Returns a description of location of element.
* @return a String
value
*/
public String getLocation()
{
return m_location;
}
/**
* Returns the value of the configuration element as a String
.
*
* @param defaultValue the default value to return if value malformed or empty
* @return a String
value
*/
public String getValue( final String defaultValue )
{
if( null != m_value )
{
return m_value;
}
else
{
return defaultValue;
}
}
/**
* Returns the value of the configuration element as a String
.
*
* @return a String
value
* @throws ConfigurationException If the value is not present.
*/
public String getValue() throws ConfigurationException
{
if( null != m_value )
{
return m_value;
}
else
{
throw new ConfigurationException( "No value is associated with the "
+ "configuration element \"" + getName()
+ "\" at " + getLocation() );
}
}
/**
* Return an array of all attribute names.
* @return a String[]
value
*/
public String[] getAttributeNames()
{
if( null == m_attributes )
{
return new String[ 0 ];
}
else
{
return (String[])m_attributes.keySet().toArray( new String[ 0 ] );
}
}
/**
* Return an array of Configuration
* elements containing all node children.
*
* @return The child nodes with name
*/
public Configuration[] getChildren()
{
if( null == m_children )
{
return new Configuration[ 0 ];
}
else
{
return (Configuration[])m_children.toArray( new Configuration[ 0 ] );
}
}
/**
* Returns the value of the attribute specified by its name as a
* String
.
*
* @param name a String
value
* @return a String
value
* @throws ConfigurationException If the attribute is not present.
*/
public String getAttribute( final String name )
throws ConfigurationException
{
final String value =
( null != m_attributes ) ? (String)m_attributes.get( name ) : null;
if( null != value )
{
return value;
}
else
{
throw new ConfigurationException(
"No attribute named \"" + name + "\" is "
+ "associated with the configuration element \""
+ getName() + "\" at " + getLocation() );
}
}
/**
* Return the first Configuration
object child of this
* associated with the given name.
* @param name a String
value
* @param createNew a boolean
value
* @return a Configuration
value
*/
public Configuration getChild( final String name, final boolean createNew )
{
if( null != m_children )
{
final int size = m_children.size();
for( int i = 0; i < size; i++ )
{
final Configuration configuration = (Configuration)m_children.get( i );
if( name.equals( configuration.getName() ) )
{
return configuration;
}
}
}
if( createNew )
{
return new DefaultConfiguration( name, "Configuration
objects
* children of this associated with the given name.
* null
.
*
* @param name The name of the required children Configuration
.
* @return a Configuration[]
value
*/
public Configuration[] getChildren( final String name )
{
if( null == m_children )
{
return new Configuration[ 0 ];
}
else
{
final ArrayList children = new ArrayList();
final int size = m_children.size();
for( int i = 0; i < size; i++ )
{
final Configuration configuration = (Configuration)m_children.get( i );
if( name.equals( configuration.getName() ) )
{
children.add( configuration );
}
}
return (Configuration[])children.toArray( new Configuration[ 0 ] );
}
}
/**
* Return count of children.
* @return an int
value
*/
public int getChildCount()
{
if( null == m_children )
{
return 0;
}
return m_children.size();
}
/**
* Compare if this configuration is equal to another.
*
* @param other The other configuration
* @return true
if they are the same.
*/
public boolean equals( Object other )
{
if( other == null ) return false;
if( !( other instanceof Configuration ) ) return false;
return ConfigurationUtil.equals( this, (Configuration) other );
}
/**
* Obtaine the hashcode for this configuration.
*
* @return the hashcode.
*/
public int hashCode()
{
int hash = m_prefix.hashCode();
if( m_name != null ) hash ^= m_name.hashCode();
hash >>>= 7;
if( m_location != null ) hash ^= m_location.hashCode();
hash >>>= 7;
if( m_namespace != null ) hash ^= m_namespace.hashCode();
hash >>>= 7;
if( m_attributes != null ) hash ^= m_attributes.hashCode();
hash >>>= 7;
if( m_children != null ) hash ^= m_children.hashCode();
hash >>>= 7;
if( m_value != null ) hash ^= m_value.hashCode();
hash >>>= 7;
return hash;
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/MutableConfiguration.java 100644 0 0 15072 10051530442 31270 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration;
/**
* A read/write extension of the Configuration interface.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.2 $ $Date: 2004/03/28 02:55:36 $
* @since 4.1.6
*/
public interface MutableConfiguration extends Configuration
{
/**
* Set the value of this Configuration
object to the specified string.
*
* @param value a String
value
*/
public void setValue( final String value );
/**
* Set the value of this Configuration
object to the specified int.
*
* @param value a int
value
*/
public void setValue( final int value );
/**
* Set the value of this Configuration
object to the specified long.
*
* @param value a long
value
*/
public void setValue( final long value );
/**
* Set the value of this Configuration
object to the specified boolean.
*
* @param value a boolean
value
*/
public void setValue( final boolean value );
/**
* Set the value of this Configuration
object to the specified float.
*
* @param value a float
value
*/
public void setValue( final float value );
/**
* Set the value of the specified attribute to the specified string.
*
* @param name name of the attribute to set
* @param value a String
value. If null, the attribute is removed.
*/
public void setAttribute( final String name, final String value );
/**
* Set the value of the specified attribute to the specified int.
*
* @param name name of the attribute to set
* @param value an int
value
*/
public void setAttribute( final String name, final int value );
/**
* Set the value of the specified attribute to the specified long.
*
* @param name name of the attribute to set
* @param value an long
value
*/
public void setAttribute( final String name, final long value );
/**
* Set the value of the specified attribute to the specified boolean.
*
* @param name name of the attribute to set
* @param value an boolean
value
*/
public void setAttribute( final String name, final boolean value );
/**
* Set the value of the specified attribute to the specified float.
*
* @param name name of the attribute to set
* @param value an float
value
*/
public void setAttribute( final String name, final float value );
/**
* Add a child Configuration
to this configuration element.
* @param configuration a Configuration
value
*/
public void addChild( final Configuration configuration );
/**
* Add all the attributes, children and value
* from specified configuration element to current
* configuration element.
*
* @param other the {@link Configuration} element
*/
public void addAll( final Configuration other );
/**
* Add all attributes from specified configuration
* element to current configuration element.
*
* @param other the {@link Configuration} element
*/
public void addAllAttributes( final Configuration other );
/**
* Add all child Configuration
objects from specified
* configuration element to current configuration element.
*
* @param other the other {@link Configuration} value
*/
public void addAllChildren( final Configuration other );
/**
* Remove a child Configuration
to this configuration element.
* @param configuration a Configuration
value
*/
public void removeChild( final Configuration configuration );
/**
* Equivalent to getMutableChild( name, true )
*/
public MutableConfiguration getMutableChild( final String name ) throws ConfigurationException;
/**
* Gets a child node of this configuration. If a mutable child with the
* given name exists, it is returned. If an immutable child with the
* given name exists, it is converted into a mutable child and returned.
* In this case, the immutable child will be replaced with the mutable
* child in this configuration (that is, it will be as if the child
* node always had been mutable).
* If no child with the given name exists, and autoCreate
* is true
, a new mutable child is created and added to
* this configuration before being returned.
*
* @return the child MutableConfiguration, or null
if autoCreate
* was false and no child by the given name existed.
* @param name the name of the child.
* @param autoCreate set to true to create the child node if it doesn't exist.
* @throws ConfigurationException if an error occurrs.
*/
public MutableConfiguration getMutableChild( final String name, boolean autoCreate ) throws ConfigurationException;
/**
* Returns an array of mutable children. Immutable children
* are converted just as for getMutableChild
.
* @throws ConfigurationException if an error occurrs.
*/
public MutableConfiguration[] getMutableChildren() throws ConfigurationException;
/**
* Returns an array of mutable children with the given name. Immutable children
* are converted just as for getMutableChild
.
* @throws ConfigurationException if an error occurrs.
*/
public MutableConfiguration[] getMutableChildren( final String name ) throws ConfigurationException;
}
././@LongLink 100644 0 0 160 10051530443 10243 L ustar 0 0 avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/NamespacedSAXConfigurationHandler.java avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/NamespacedSAXConfigurationH100644 0 0 30114 10051530442 31475 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Iterator;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.NamespaceSupport;
/**
* A SAXConfigurationHandler helps build Configurations out of sax events,
* including namespace information.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.20 $ $Date: 2004/02/11 14:34:25 $
*/
public class NamespacedSAXConfigurationHandler
extends SAXConfigurationHandler
{
/**
* Likely number of nested configuration items. If more is
* encountered the lists will grow automatically.
*/
private static final int EXPECTED_DEPTH = 5;
private final ArrayList m_elements = new ArrayList( EXPECTED_DEPTH );
private final ArrayList m_prefixes = new ArrayList( EXPECTED_DEPTH );
private final ArrayList m_values = new ArrayList( EXPECTED_DEPTH );
/**
* Contains true at index n if space in the configuration with
* depth n is to be preserved.
*/
private final BitSet m_preserveSpace = new BitSet();
private Configuration m_configuration;
private Locator m_locator;
private NamespaceSupport m_namespaceSupport = new NamespaceSupport();
/**
* Get the configuration object that was built.
*
* @return a Configuration
object
*/
public Configuration getConfiguration()
{
return m_configuration;
}
/**
* Clears all data from this configuration handler.
*/
public void clear()
{
m_elements.clear();
Iterator i = m_prefixes.iterator();
while( i.hasNext() )
{
( (ArrayList)i.next() ).clear();
}
m_prefixes.clear();
m_values.clear();
m_locator = null;
}
/**
* Set the document Locator
to use.
*
* @param locator a Locator
value
*/
public void setDocumentLocator( final Locator locator )
{
m_locator = locator;
}
/**
* Handling hook for starting the document parsing.
*
* @throws SAXException if an error occurs
*/
public void startDocument()
throws SAXException
{
m_namespaceSupport.reset();
super.startDocument();
}
/**
* Handling hook for ending the document parsing.
*
* @throws SAXException if an error occurs
*/
public void endDocument()
throws SAXException
{
super.endDocument();
m_namespaceSupport.reset();
}
/**
* Handling hook for character data.
*
* @param ch a char[]
of data
* @param start offset in the character array from which to start reading
* @param end length of character data
* @throws SAXException if an error occurs
*/
public void characters( final char[] ch, int start, int end )
throws SAXException
{
// it is possible to play micro-optimization here by doing
// manual trimming and thus preserve some precious bits
// of memory, but it's really not important enough to justify
// resulting code complexity
final int depth = m_values.size() - 1;
final StringBuffer valueBuffer = (StringBuffer)m_values.get( depth );
valueBuffer.append( ch, start, end );
}
/**
* Handling hook for finishing parsing of an element.
*
* @param namespaceURI a String
value
* @param localName a String
value
* @param rawName a String
value
* @throws SAXException if an error occurs
*/
public void endElement( final String namespaceURI,
final String localName,
final String rawName )
throws SAXException
{
final int depth = m_elements.size() - 1;
final DefaultConfiguration finishedConfiguration =
(DefaultConfiguration)m_elements.remove( depth );
final String accumulatedValue =
( (StringBuffer)m_values.remove( depth ) ).toString();
final ArrayList prefixes = (ArrayList)m_prefixes.remove( depth );
final Iterator i = prefixes.iterator();
while( i.hasNext() )
{
endPrefixMapping( (String)i.next() );
}
prefixes.clear();
if( finishedConfiguration.getChildren().length == 0 )
{
// leaf node
String finishedValue;
if( m_preserveSpace.get( depth ) )
{
finishedValue = accumulatedValue;
}
else if( 0 == accumulatedValue.length() )
{
finishedValue = null;
}
else
{
finishedValue = accumulatedValue.trim();
}
finishedConfiguration.setValue( finishedValue );
}
else
{
final String trimmedValue = accumulatedValue.trim();
if( trimmedValue.length() > 0 )
{
throw new SAXException( "Not allowed to define mixed content in the "
+ "element " + finishedConfiguration.getName() + " at "
+ finishedConfiguration.getLocation() );
}
}
if( 0 == depth )
{
m_configuration = finishedConfiguration;
}
m_namespaceSupport.popContext();
}
/**
* Create a new DefaultConfiguration
with the specified
* local name, namespace, and location.
*
* @param localName a String
value
* @param namespaceURI a String
value
* @param location a String
value
* @return a DefaultConfiguration
value
*/
protected DefaultConfiguration createConfiguration( final String localName,
final String namespaceURI,
final String location )
{
String prefix = m_namespaceSupport.getPrefix( namespaceURI );
if( prefix == null )
{
prefix = "";
}
return new DefaultConfiguration( localName, location, namespaceURI, prefix );
}
/**
* Handling hook for starting parsing of an element.
*
* @param namespaceURI a String
value
* @param localName a String
value
* @param rawName a String
value
* @param attributes an Attributes
value
* @throws SAXException if an error occurs
*/
public void startElement( final String namespaceURI,
final String localName,
final String rawName,
final Attributes attributes )
throws SAXException
{
m_namespaceSupport.pushContext();
final DefaultConfiguration configuration =
createConfiguration( localName, namespaceURI, getLocationString() );
// depth of new configuration (not decrementing here, configuration
// is to be added)
final int depth = m_elements.size();
boolean preserveSpace = false; // top level element trims space by default
if( depth > 0 )
{
final DefaultConfiguration parent =
(DefaultConfiguration)m_elements.get( depth - 1 );
parent.addChild( configuration );
// inherits parent's space preservation policy
preserveSpace = m_preserveSpace.get( depth - 1 );
}
m_elements.add( configuration );
m_values.add( new StringBuffer() );
final ArrayList prefixes = new ArrayList();
AttributesImpl componentAttr = new AttributesImpl();
for( int i = 0; i < attributes.getLength(); i++ )
{
if( attributes.getQName( i ).startsWith( "xmlns" ) )
{
prefixes.add( attributes.getLocalName( i ) );
this.startPrefixMapping( attributes.getLocalName( i ),
attributes.getValue( i ) );
}
else if( attributes.getQName( i ).equals( "xml:space" ) )
{
preserveSpace = attributes.getValue( i ).equals( "preserve" );
}
else
{
componentAttr.addAttribute( attributes.getURI( i ),
attributes.getLocalName( i ),
attributes.getQName( i ),
attributes.getType( i ),
attributes.getValue( i ) );
}
}
if( preserveSpace )
{
m_preserveSpace.set( depth );
}
else
{
m_preserveSpace.clear( depth );
}
m_prefixes.add( prefixes );
final int attributesSize = componentAttr.getLength();
for( int i = 0; i < attributesSize; i++ )
{
final String name = componentAttr.getQName( i );
final String value = componentAttr.getValue( i );
configuration.setAttribute( name, value );
}
}
/**
* This just throws an exception on a parse error.
* @param exception the parse error
* @throws SAXException if an error occurs
*/
public void error( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* This just throws an exception on a parse error.
* @param exception the parse error
* @throws SAXException if an error occurs
*/
public void warning( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* This just throws an exception on a parse error.
* @param exception the parse error
* @throws SAXException if an error occurs
*/
public void fatalError( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* Returns a string showing the current system ID, line number and column number.
*
* @return a String
value
*/
protected String getLocationString()
{
if( null == m_locator )
{
return "Unknown";
}
else
{
final int columnNumber = m_locator.getColumnNumber();
return
m_locator.getSystemId() + ":"
+ m_locator.getLineNumber()
+ ( columnNumber >= 0 ? ( ":" + columnNumber ) : "" );
}
}
/**
* Handling hook for starting prefix mapping.
*
* @param prefix a String
value
* @param uri a String
value
* @throws SAXException if an error occurs
*/
public void startPrefixMapping( String prefix, String uri )
throws SAXException
{
m_namespaceSupport.declarePrefix( prefix, uri );
super.startPrefixMapping( prefix, uri );
}
}
././@LongLink 100644 0 0 146 10051530443 10247 L ustar 0 0 avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/SAXConfigurationHandler.java avalon-framework/impl/src/java/org/apache/avalon/framework/configuration/SAXConfigurationHandler.jav100644 0 0 22216 10051530442 31465 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration;
import java.util.ArrayList;
import java.util.BitSet;
import org.xml.sax.Attributes;
import org.xml.sax.ErrorHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
* A SAXConfigurationHandler helps build Configurations out of sax events.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.32 $ $Date: 2004/02/11 14:34:26 $
*/
public class SAXConfigurationHandler
extends DefaultHandler
implements ErrorHandler
{
/**
* Likely number of nested configuration items. If more is
* encountered the lists will grow automatically.
*/
private static final int EXPECTED_DEPTH = 5;
private final ArrayList m_elements = new ArrayList( EXPECTED_DEPTH );
private final ArrayList m_values = new ArrayList( EXPECTED_DEPTH );
/**
* Contains true at index n if space in the configuration with
* depth n is to be preserved.
*/
private final BitSet m_preserveSpace = new BitSet();
private Configuration m_configuration;
private Locator m_locator;
/**
* Get the configuration object that was built.
*
* @return a Configuration
object
*/
public Configuration getConfiguration()
{
return m_configuration;
}
/**
* Clears all data from this configuration handler.
*/
public void clear()
{
m_elements.clear();
m_values.clear();
m_locator = null;
}
/**
* Set the document Locator
to use.
*
* @param locator a Locator
value
*/
public void setDocumentLocator( final Locator locator )
{
m_locator = locator;
}
/**
* Handling hook for character data.
*
* @param ch a char[]
of data
* @param start offset in the character array from which to start reading
* @param end length of character data
* @throws SAXException if an error occurs
*/
public void characters( final char[] ch, int start, int end )
throws SAXException
{
// it is possible to play micro-optimization here by doing
// manual trimming and thus preserve some precious bits
// of memory, but it's really not important enough to justify
// resulting code complexity
final int depth = m_values.size() - 1;
final StringBuffer valueBuffer = (StringBuffer)m_values.get( depth );
valueBuffer.append( ch, start, end );
}
/**
* Handling hook for finishing parsing of an element.
*
* @param namespaceURI a String
value
* @param localName a String
value
* @param rawName a String
value
* @throws SAXException if an error occurs
*/
public void endElement( final String namespaceURI,
final String localName,
final String rawName )
throws SAXException
{
final int depth = m_elements.size() - 1;
final DefaultConfiguration finishedConfiguration =
(DefaultConfiguration)m_elements.remove( depth );
final String accumulatedValue =
( (StringBuffer)m_values.remove( depth ) ).toString();
if( finishedConfiguration.getChildren().length == 0 )
{
// leaf node
String finishedValue;
if( m_preserveSpace.get( depth ) )
{
finishedValue = accumulatedValue;
}
else if( 0 == accumulatedValue.length() )
{
finishedValue = null;
}
else
{
finishedValue = accumulatedValue.trim();
}
finishedConfiguration.setValue( finishedValue );
}
else
{
final String trimmedValue = accumulatedValue.trim();
if( trimmedValue.length() > 0 )
{
throw new SAXException( "Not allowed to define mixed content in the "
+ "element " + finishedConfiguration.getName() + " at "
+ finishedConfiguration.getLocation() );
}
}
if( 0 == depth )
{
m_configuration = finishedConfiguration;
}
}
/**
* Create a new DefaultConfiguration
with the specified
* local name and location.
*
* @param localName a String
value
* @param location a String
value
* @return a DefaultConfiguration
value
*/
protected DefaultConfiguration createConfiguration( final String localName,
final String location )
{
return new DefaultConfiguration( localName, location );
}
/**
* Handling hook for starting parsing of an element.
*
* @param namespaceURI a String
value
* @param localName a String
value
* @param rawName a String
value
* @param attributes an Attributes
value
* @throws SAXException if an error occurs
*/
public void startElement( final String namespaceURI,
final String localName,
final String rawName,
final Attributes attributes )
throws SAXException
{
final DefaultConfiguration configuration =
createConfiguration( rawName, getLocationString() );
// depth of new configuration (not decrementing here, configuration
// is to be added)
final int depth = m_elements.size();
boolean preserveSpace = false; // top level element trims space by default
if( depth > 0 )
{
final DefaultConfiguration parent =
(DefaultConfiguration)m_elements.get( depth - 1 );
parent.addChild( configuration );
// inherits parent's space preservation policy
preserveSpace = m_preserveSpace.get( depth - 1 );
}
m_elements.add( configuration );
m_values.add( new StringBuffer() );
final int attributesSize = attributes.getLength();
for( int i = 0; i < attributesSize; i++ )
{
final String name = attributes.getQName( i );
final String value = attributes.getValue( i );
if( !name.equals( "xml:space" ) )
{
configuration.setAttribute( name, value );
}
else
{
preserveSpace = value.equals( "preserve" );
}
}
if( preserveSpace )
{
m_preserveSpace.set( depth );
}
else
{
m_preserveSpace.clear( depth );
}
}
/**
* This just throws an exception on a parse error.
* @param exception the parse error
* @throws SAXException if an error occurs
*/
public void error( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* This just throws an exception on a parse error.
* @param exception the parse error
* @throws SAXException if an error occurs
*/
public void warning( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* This just throws an exception on a parse error.
* @param exception the parse error
* @throws SAXException if an error occurs
*/
public void fatalError( final SAXParseException exception )
throws SAXException
{
throw exception;
}
/**
* Returns a string showing the current system ID, line number and column number.
*
* @return a String
value
*/
protected String getLocationString()
{
if( null == m_locator )
{
return "Unknown";
}
else
{
final int columnNumber = m_locator.getColumnNumber();
return
m_locator.getSystemId() + ":"
+ m_locator.getLineNumber()
+ ( columnNumber >= 0 ? ( ":" + columnNumber ) : "" );
}
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/container/ContainerUtil.java 100644 0 0 26062 10051530442 27043 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.container;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.activity.Initializable;
import org.apache.avalon.framework.activity.Startable;
import org.apache.avalon.framework.activity.Executable;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.component.Composable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.logger.LogEnabled;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.parameters.ParameterException;
import org.apache.avalon.framework.parameters.Parameterizable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
/**
* Utility class that makes it easier to transfer
* a component throught it's lifecycle stages.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.16 $ $Date: 2004/02/11 14:34:26 $
*/
public final class ContainerUtil
{
/**
* Private constructor to block instantiation.
*/
private ContainerUtil()
{
}
/**
* Run specified object through shutdown lifecycle stages
* (Stop and Dispose).
*
* @param object the object to shutdown
* @throws Exception if there is a problem stoppping object
*/
public static void shutdown( final Object object )
throws Exception
{
stop( object );
dispose( object );
}
/**
* Supply specified object with Logger if it implements the
* {@link LogEnabled} interface.
*
* @param object the object to Start
* @param logger the logger to enable component with. May be null
* in which case the specified object must not implement LogEnabled.
* @throws IllegalArgumentException if the object is LogEnabled but Logger is null
*/
public static void enableLogging( final Object object,
final Logger logger )
{
if( object instanceof LogEnabled )
{
if( null == logger )
{
final String message = "logger is null";
throw new IllegalArgumentException( message );
}
( (LogEnabled)object ).enableLogging( logger );
}
}
/**
* Supply specified object with a Context object if it implements the
* {@link Contextualizable} interface.
*
* @param object the object to contextualize
* @param context the context object to use for object.
* May be null in which case the specified object must not
* implement Contextualizable.
* @throws ContextException if there is a problem contextualizing object
* @throws IllegalArgumentException if the object is Contextualizable but
* context is null
*/
public static void contextualize( final Object object,
final Context context )
throws ContextException
{
if( object instanceof Contextualizable )
{
if( null == context )
{
final String message = "context is null";
throw new IllegalArgumentException( message );
}
( (Contextualizable)object ).contextualize( context );
}
}
/**
* Supply specified object with ServiceManager if it implements the
* {@link Serviceable} interface.
*
* @param object the object to service
* @param serviceManager the serviceManager object to use for object.
* May be null in which case the specified object must not
* implement Serviceable.
* @throws ServiceException if there is a problem servicing object
* @throws IllegalArgumentException if the object is Servicable but
* ServiceManager is null
*/
public static void service( final Object object,
final ServiceManager serviceManager )
throws ServiceException
{
if( object instanceof Serviceable )
{
if( null == serviceManager )
{
final String message = "ServiceManager is null";
throw new IllegalArgumentException( message );
}
( (Serviceable)object ).service( serviceManager );
}
}
/**
* Supply specified object with ComponentManager if it implements the
* {@link Composable} interface.
*
* @param object the object to compose
* @param componentManager the ComponentManager object to use for object.
* May be null in which case the specified object must not
* implement Composable.
* @throws ComponentException if there is a problem composing object
* @deprecated compose() is no longer the preferred method via
* which components will be supplied with Components. Please
* Use service() from Composable instead.
* @throws IllegalArgumentException if the object is Composable but
* ComponentManager is null
*/
public static void compose( final Object object,
final ComponentManager componentManager )
throws ComponentException
{
if( object instanceof Composable )
{
if( null == componentManager )
{
final String message = "componentManager is null";
throw new IllegalArgumentException( message );
}
( (Composable)object ).compose( componentManager );
}
}
/**
* Configure specified object if it implements the
* {@link Configurable} interface.
*
* @param object the object to Start
* @param configuration the configuration object to use during
* configuration. May be null in which case the specified object
* must not implement Configurable
* @throws ConfigurationException if there is a problem Configuring object,
* or the object is Configurable but Configuration is null
* @throws IllegalArgumentException if the object is Configurable but
* Configuration is null
*/
public static void configure( final Object object,
final Configuration configuration )
throws ConfigurationException
{
if( object instanceof Configurable )
{
if( null == configuration )
{
final String message = "configuration is null";
throw new IllegalArgumentException( message );
}
( (Configurable)object ).configure( configuration );
}
}
/**
* Parameterize specified object if it implements the
* {@link Parameterizable} interface.
*
* @param object the object to Parameterize.
* @param parameters the parameters object to use during Parameterization.
* May be null in which case the specified object must not
* implement Parameterizable.
* @throws ParameterException if there is a problem Parameterizing object
* @throws IllegalArgumentException if the object is Parameterizable but
* parameters is null
*/
public static void parameterize( final Object object,
final Parameters parameters )
throws ParameterException
{
if( object instanceof Parameterizable )
{
if( null == parameters )
{
final String message = "parameters is null";
throw new IllegalArgumentException( message );
}
( (Parameterizable)object ).parameterize( parameters );
}
}
/**
* Initialize specified object if it implements the
* {@link Initializable} interface.
*
* @param object the object to Initialize
* @throws Exception if there is a problem Initializing object
*/
public static void initialize( final Object object )
throws Exception
{
if( object instanceof Initializable )
{
( (Initializable)object ).initialize();
}
}
/**
* Start specified object if it implements the
* {@link Startable} interface.
*
* @param object the object to Start
* @throws Exception if there is a problem Starting object
*/
public static void start( final Object object )
throws Exception
{
if( object instanceof Startable )
{
( (Startable)object ).start();
}
}
/**
* Execute the specified object if it implements the
* {@link Executable} interface.
*
* @param object the object to execute
* @throws Exception if there is a problem executing object
*/
public static void execute( final Object object )
throws Exception
{
if( object instanceof Executable )
{
( (Executable)object ).execute();
}
}
/**
* Stop specified object if it implements the
* {@link Startable} interface.
*
* @param object the object to stop
* @throws Exception if there is a problem stoppping object
*/
public static void stop( final Object object )
throws Exception
{
if( object instanceof Startable )
{
( (Startable)object ).stop();
}
}
/**
* Dispose specified object if it implements the
* {@link Disposable} interface.
*
* @param object the object to dispose
*/
public static void dispose( final Object object )
{
if( object instanceof Disposable )
{
( (Disposable)object ).dispose();
}
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/context/DefaultContext.java 100644 0 0 12555 10051530441 26717 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.context;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Map;
/**
* Default implementation of Context.
* This implementation is a static hierarchial store.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.27 $ $Date: 2004/02/11 14:34:26 $
*/
public class DefaultContext
implements Context
{
private static final class Hidden implements Serializable
{
}
private static final Hidden HIDDEN_MAKER = new Hidden();
private final Map m_contextData;
private final Context m_parent;
private boolean m_readOnly;
/**
* Create a Context with specified data and parent.
*
* @param contextData the context data
* @param parent the parent Context (may be null)
*/
public DefaultContext( final Map contextData, final Context parent )
{
m_parent = parent;
m_contextData = contextData;
}
/**
* Create a Context with specified data.
*
* @param contextData the context data
*/
public DefaultContext( final Map contextData )
{
this( contextData, null );
}
/**
* Create a Context with specified parent.
*
* @param parent the parent Context (may be null)
*/
public DefaultContext( final Context parent )
{
this( new Hashtable(), parent );
}
/**
* Create a Context with no parent.
*
*/
public DefaultContext()
{
this( (Context)null );
}
/**
* Retrieve an item from the Context.
*
* @param key the key of item
* @return the item stored in context
* @throws ContextException if item not present
*/
public Object get( final Object key )
throws ContextException
{
final Object data = m_contextData.get( key );
if( null != data )
{
if( data instanceof Hidden )
{
// Always fail.
final String message = "Unable to locate " + key;
throw new ContextException( message );
}
if( data instanceof Resolvable )
{
return ( (Resolvable)data ).resolve( this );
}
return data;
}
// If data was null, check the parent
if( null == m_parent )
{
// There was no parent, and no data
final String message =
"Unable to resolve context key: " + key;
throw new ContextException( message );
}
return m_parent.get( key );
}
/**
* Helper method fo adding items to Context.
*
* @param key the items key
* @param value the item
* @throws IllegalStateException if context is read only
*/
public void put( final Object key, final Object value )
throws IllegalStateException
{
checkWriteable();
if( null == value )
{
m_contextData.remove( key );
}
else
{
m_contextData.put( key, value );
}
}
/**
* Hides the item in the context.
* After remove(key) has been called, a get(key)
* will always fail, even if the parent context
* has such a mapping.
*
* @param key the items key
* @throws IllegalStateException if context is read only
*/
public void hide( final Object key )
throws IllegalStateException
{
checkWriteable();
m_contextData.put( key, HIDDEN_MAKER );
}
/**
* Utility method to retrieve context data.
*
* @return the context data
*/
protected final Map getContextData()
{
return m_contextData;
}
/**
* Get parent context if any.
*
* @return the parent Context (may be null)
*/
protected final Context getParent()
{
return m_parent;
}
/**
* Make the context read-only.
* Any attempt to write to the context via put()
* will result in an IllegalStateException.
*/
public void makeReadOnly()
{
m_readOnly = true;
}
/**
* Utility method to check if context is writeable and if not throw exception.
*
* @throws IllegalStateException if context is read only
*/
protected final void checkWriteable()
throws IllegalStateException
{
if( m_readOnly )
{
final String message =
"Context is read only and can not be modified";
throw new IllegalStateException( message );
}
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/ExceptionUtil.java 100644 0 0 20564 10051530441 25075 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.StringTokenizer;
/**
* This class provides basic facilities for manipulating exceptions.
*
* Some exception handling stuff thieved from Turbine...
*
* @author Avalon Development Team
* @version CVS $Revision: 1.25 $ $Date: 2004/02/11 14:34:25 $
*/
public final class ExceptionUtil
{
private static final String LINE_SEPARATOR = System.getProperty( "line.separator" );
private static final String GET_CAUSE_NAME = "getCause";
private static final Class[] GET_CAUSE_PARAMTYPES = new Class[ 0 ];
/**
* Private constructor to prevent instantiation.
*/
private ExceptionUtil()
{
}
/**
* Generate string for specified exception and the cause of
* this exception (if any).
* @param throwable a Throwable
* @return the stack trace as a String
*/
public static String printStackTrace( final Throwable throwable )
{
return printStackTrace( throwable, 0, true );
}
/**
* Generate string for specified exception and if printCascading
* is true will print all cascading exceptions.
* @param throwable a Throwable
* @param printCascading if true
will print all cascading exceptions
* @return the stack trace as a String
*/
public static String printStackTrace( final Throwable throwable,
final boolean printCascading )
{
return printStackTrace( throwable, 0, printCascading );
}
/**
* Serialize the specified Throwable
to a string.
* Restrict the number of frames printed out to the specified depth.
* If the depth specified is 0
then all the frames are
* converted into a string.
* @param throwable a Throwable
* @param depth number of stack trace frames to show
* @return the stack trace as a String
*/
public static String printStackTrace( final Throwable throwable, final int depth )
{
int dp = depth;
final String[] lines = captureStackTrace( throwable );
if( 0 == dp || dp > lines.length )
{
dp = lines.length;
}
final StringBuffer sb = new StringBuffer();
for( int i = 0; i < dp; i++ )
{
sb.append( lines[ i ] );
sb.append( LINE_SEPARATOR );
}
return sb.toString();
}
/**
* Generate exception string for specified exception to specified depth
* and all Cascading exceptions if printCascading is true.
* @param throwable a Throwable
* @param depth number of stack trace frames to show
* @param printCascading if true
will print all cascading exceptions
* @return the stack trace as a String
*/
public static String printStackTrace( final Throwable throwable,
final int depth,
final boolean printCascading )
{
return printStackTrace( throwable, depth, printCascading, true );
}
/**
* Generate exception string for specified exception to specified depth
* and all Cascading exceptions if printCascading is true. If useReflection
* is true then the method will also attempt to use reflection to find a
* method with signature Throwable getCause()
. This makes
* it compatible with JDK1.4 mechanisms for nesting exceptions.
* @param throwable a Throwable
* @param depth number of stack trace frames to show
* @param printCascading if true
will print all cascading exceptions
* @param useReflection if true
will use reflection to handle JDK1.4
* nested exceptions
* @return the stack trace as a String
*/
public static String printStackTrace( final Throwable throwable,
final int depth,
final boolean printCascading,
final boolean useReflection )
{
final String result = printStackTrace( throwable, depth );
if( !printCascading )
{
return result;
}
else
{
final StringBuffer sb = new StringBuffer();
sb.append( result );
Throwable cause = getCause( throwable, useReflection );
while( null != cause )
{
sb.append( "rethrown from" );
sb.append( LINE_SEPARATOR );
sb.append( printStackTrace( cause, depth ) );
cause = getCause( cause, useReflection );
}
return sb.toString();
}
}
/**
* Utility method to get cause of exception.
* @param throwable a Throwable
* @param useReflection if true
will use reflection to handle JDK1.4
* nested exceptions
* @return cause of specified exception
*/
public static Throwable getCause( final Throwable throwable,
final boolean useReflection )
{
if( throwable instanceof CascadingThrowable )
{
final CascadingThrowable cascadingThrowable = (CascadingThrowable)throwable;
return cascadingThrowable.getCause();
}
else if( useReflection )
{
try
{
final Class clazz = throwable.getClass();
final Method method =
clazz.getMethod( GET_CAUSE_NAME, GET_CAUSE_PARAMTYPES );
return (Throwable)method.invoke( throwable, null );
}
catch( final Throwable t )
{
return null;
}
}
else
{
return null;
}
}
/**
* Captures the stack trace associated with this exception.
*
* @param throwable a Throwable
* @return an array of Strings describing stack frames.
*/
public static String[] captureStackTrace( final Throwable throwable )
{
final StringWriter sw = new StringWriter();
throwable.printStackTrace( new PrintWriter( sw, true ) );
return splitStringInternal( sw.toString(), LINE_SEPARATOR );
}
/**
* Splits the string on every token into an array of stack frames.
*
* @param string the string to split
* @param onToken the token to split on
* @return the resultant array
* @deprecated This is an internal utility method that should not be used
*/
public static String[] splitString( final String string, final String onToken )
{
return splitStringInternal( string, onToken );
}
/**
* Splits the string on every token into an array of stack frames.
*
* @param string the string to split
* @param onToken the token to split on
* @return the resultant array
*/
private static String[] splitStringInternal( final String string, final String onToken )
{
final StringTokenizer tokenizer = new StringTokenizer( string, onToken );
final String[] result = new String[ tokenizer.countTokens() ];
for( int i = 0; i < result.length; i++ )
{
result[ i ] = tokenizer.nextToken();
}
return result;
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/logger/AbstractLoggable.java 100644 0 0 6125 10051530442 26736 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.logger;
/**
* Utility class to allow construction of easy components that will perform logging.
*
* @author Avalon Development Team
* @deprecated Use {@link AbstractLogEnabled} instead.
* @version CVS $Revision: 1.19 $ $Date: 2004/02/11 14:34:26 $
*/
public abstract class AbstractLoggable
implements Loggable
{
///Base Logger instance
private org.apache.log.Logger m_logger;
/**
* Set the components logger.
*
* @param logger the logger
*/
public void setLogger( final org.apache.log.Logger logger )
{
m_logger = logger;
}
/**
* Helper method to allow sub-classes to aquire logger.
* This method exists rather than exposing a member variable
* because it protects other users against future changes. It
* also means they do not have to use our naming convention.
*
* There is no performance penalty as this is a final method * and will be inlined by the JVM.
* * @return the Logger */ protected final org.apache.log.Logger getLogger() { return m_logger; } /** * Helper method to setup other components with same logger. * * @param component the component to pass logger object to */ protected void setupLogger( final Object component ) { setupLogger( component, (String)null ); } /** * Helper method to setup other components with logger. * The logger has the subcategory of this components logger. * * @param component the component to pass logger object to * @param subCategory the subcategory to use (may be null) */ protected void setupLogger( final Object component, final String subCategory ) { org.apache.log.Logger logger = m_logger; if( null != subCategory ) { logger = m_logger.getChildLogger( subCategory ); } setupLogger( component, logger ); } /** * Helper method to setup other components with logger. * * @param component the component to pass logger object to * @param logger the Logger */ protected void setupLogger( final Object component, final org.apache.log.Logger logger ) { if( component instanceof Loggable ) { ( (Loggable)component ).setLogger( logger ); } } } avalon-framework/impl/src/java/org/apache/avalon/framework/logger/AvalonFormatter.java 100644 0 0 13146 10051530442 26663 0 ustar 0 0 /* * Copyright 1997-2004 The Apache Software Foundation * * Licensed 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. */ package org.apache.avalon.framework.logger; import org.apache.avalon.framework.ExceptionUtil; import org.apache.log.LogEvent; import org.apache.log.format.ExtendedPatternFormatter; import org.apache.log.format.PatternFormatter; import org.apache.log.util.StackIntrospector; /** * This formatter extends ExtendedPatternFormatter so that * CascadingExceptions are formatted with all nested exceptions. * *class
: outputs the name of the class that has logged the
* message. The optional short
subformat removes the
* package name. Warning : this pattern works only if formatting occurs in
* the same thread as the call to Logger, i.e. it won't work with
* AsyncLogTarget
.String
value
*/
public void debug( final String message )
{
debug( message, null );
}
/**
* Logs a debugging message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void debug( final String message, final Throwable throwable )
{
if( m_logLevel <= LEVEL_DEBUG )
{
System.out.print( "[DEBUG] " );
System.out.println( message );
if( null != throwable )
{
throwable.printStackTrace( System.out );
}
}
}
/**
* Returns true
if debug-level logging is enabled, false otherwise.
*
* @return true
if debug-level logging
*/
public boolean isDebugEnabled()
{
return m_logLevel <= LEVEL_DEBUG;
}
/**
* Logs an informational message.
*
* @param message a String
value
*/
public void info( final String message )
{
info( message, null );
}
/**
* Logs an informational message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void info( final String message, final Throwable throwable )
{
if( m_logLevel <= LEVEL_INFO )
{
System.out.print( "[INFO] " );
System.out.println( message );
if( null != throwable )
{
throwable.printStackTrace( System.out );
}
}
}
/**
* Returns true
if info-level logging is enabled, false otherwise.
*
* @return true
if info-level logging is enabled
*/
public boolean isInfoEnabled()
{
return m_logLevel <= LEVEL_INFO;
}
/**
* Logs a warning message.
*
* @param message a String
value
*/
public void warn( final String message )
{
warn( message, null );
}
/**
* Logs a warning message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void warn( final String message, final Throwable throwable )
{
if( m_logLevel <= LEVEL_WARN )
{
System.out.print( "[WARNING] " );
System.out.println( message );
if( null != throwable )
{
throwable.printStackTrace( System.out );
}
}
}
/**
* Returns true
if warn-level logging is enabled, false otherwise.
*
* @return true
if warn-level logging is enabled
*/
public boolean isWarnEnabled()
{
return m_logLevel <= LEVEL_WARN;
}
/**
* Logs an error message.
*
* @param message a String
value
*/
public void error( final String message )
{
error( message, null );
}
/**
* Logs an error message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void error( final String message, final Throwable throwable )
{
if( m_logLevel <= LEVEL_ERROR )
{
System.out.print( "[ERROR] " );
System.out.println( message );
if( null != throwable )
{
throwable.printStackTrace( System.out );
}
}
}
/**
* Returns true
if error-level logging is enabled, false otherwise.
*
* @return true
if error-level logging is enabled
*/
public boolean isErrorEnabled()
{
return m_logLevel <= LEVEL_ERROR;
}
/**
* Logs a fatal error message.
*
* @param message a String
value
*/
public void fatalError( final String message )
{
fatalError( message, null );
}
/**
* Logs a fatal error message and an exception.
*
* @param message a String
value
* @param throwable a Throwable
value
*/
public void fatalError( final String message, final Throwable throwable )
{
if( m_logLevel <= LEVEL_FATAL )
{
System.out.print( "[FATAL ERROR] " );
System.out.println( message );
if( null != throwable )
{
throwable.printStackTrace( System.out );
}
}
}
/**
* Returns true
if fatal-level logging is enabled, false otherwise.
*
* @return true
if fatal-level logging is enabled
*/
public boolean isFatalErrorEnabled()
{
return m_logLevel <= LEVEL_FATAL;
}
/**
* Just returns this logger (ConsoleLogger
is not hierarchical).
*
* @param name ignored
* @return this logger
*/
public Logger getChildLogger( final String name )
{
return this;
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/logger/Jdk14Logger.java 100644 0 0 14401 10051530442 25567 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.logger;
import java.util.logging.Level;
/**
* The default JDK 1.4 wrapper class for Logger. Please note that there is
* not an exact match to the priority levels that JDK 1.4 logging has and
* what LogKit or Log4J has. For that reason, the following priority level
* matching was used:
*
* * JDK 1.4 does allow you to have other levels like: CONFIG, FINER, and * FINEST. Most projects don't separate out configuration logging from * debugging information. Also, we wanted to maintain backwards * compatibility as much as possible. Unfortunately, with all the "fineness" * details, there is no equivalent to the "error" log level. *
* * @author Avalon Development Team * @version CVS $Revision: 1.18 $ $Date: 2004/02/11 14:34:26 $ */ public final class Jdk14Logger implements Logger { //The actual JDK1.4 logger implementation private final java.util.logging.Logger m_logger; /** * Construct a Logger with specified jdk1.4 logger instance as implementation. * * @param logImpl the jdk1.4 logger instance to delegate to */ public Jdk14Logger( java.util.logging.Logger logImpl ) { m_logger = logImpl; } /** * Log a debug message. * * @param message the message */ public final void debug( final String message ) { m_logger.log( Level.FINE, message ); } /** * Log a debug message. * * @param message the message * @param throwable the throwable */ public final void debug( final String message, final Throwable throwable ) { m_logger.log( Level.FINE, message, throwable ); } /** * Determine if messages of priority "debug" will be logged. * * @return true if "debug" messages will be logged */ public final boolean isDebugEnabled() { return m_logger.isLoggable( Level.FINE ); } /** * Log a info message. * * @param message the message */ public final void info( final String message ) { m_logger.log( Level.INFO, message ); } /** * Log a info message. * * @param message the message * @param throwable the throwable */ public final void info( final String message, final Throwable throwable ) { m_logger.log( Level.INFO, message, throwable ); } /** * Determine if messages of priority "info" will be logged. * * @return true if "info" messages will be logged */ public final boolean isInfoEnabled() { return m_logger.isLoggable( Level.INFO ); } /** * Log a warn message. * * @param message the message */ public final void warn( final String message ) { m_logger.log( Level.WARNING, message ); } /** * Log a warn message. * * @param message the message * @param throwable the throwable */ public final void warn( final String message, final Throwable throwable ) { m_logger.log( Level.WARNING, message, throwable ); } /** * Determine if messages of priority "warn" will be logged. * * @return true if "warn" messages will be logged */ public final boolean isWarnEnabled() { return m_logger.isLoggable( Level.WARNING ); } /** * Log a error message. * * @param message the message */ public final void error( final String message ) { m_logger.log( Level.SEVERE, message ); } /** * Log a error message. * * @param message the message * @param throwable the throwable */ public final void error( final String message, final Throwable throwable ) { m_logger.log( Level.SEVERE, message, throwable ); } /** * Determine if messages of priority "error" will be logged. * * @return true if "error" messages will be logged */ public final boolean isErrorEnabled() { return m_logger.isLoggable( Level.SEVERE ); } /** * Log a fatalError message. * * @param message the message */ public final void fatalError( final String message ) { m_logger.log( Level.SEVERE, message ); } /** * Log a fatalError message. * * @param message the message * @param throwable the throwable */ public final void fatalError( final String message, final Throwable throwable ) { m_logger.log( Level.SEVERE, message, throwable ); } /** * Determine if messages of priority "fatalError" will be logged. * * @return true if "fatalError" messages will be logged */ public final boolean isFatalErrorEnabled() { return m_logger.isLoggable( Level.SEVERE ); } /** * Create a new child logger. * The name of the child logger is [current-loggers-name].[passed-in-name] * ThrowsIllegalArgumentException
if name has an empty element name
*
* @param name the subname of this logger
* @return the new logger
*/
public final Logger getChildLogger( final String name )
{
return new Jdk14Logger( java.util.logging.Logger
.getLogger( m_logger.getName() + "." + name ) );
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/logger/Log4JLogger.java 100644 0 0 13270 10051530441 25633 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.logger;
import org.apache.log4j.Level;
/**
* The default Log4J wrapper class for Logger.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.19 $ $Date: 2004/02/11 14:34:26 $
*/
public final class Log4JLogger
implements Logger
{
/**
* Constant for name of class to use when recording caller
* of log method.
*/
private static final String FQCN = Log4JLogger.class.getName();
//underlying implementation
private final org.apache.log4j.Logger m_logger;
/**
* Create a logger that delegates to specified category.
*
* @param logImpl the category to delegate to
*/
public Log4JLogger( final org.apache.log4j.Logger logImpl )
{
m_logger = logImpl;
}
/**
* Log a debug message.
*
* @param message the message
*/
public final void debug( final String message )
{
m_logger.log( FQCN, Level.DEBUG, message, null );
}
/**
* Log a debug message.
*
* @param message the message
* @param throwable the throwable
*/
public final void debug( final String message, final Throwable throwable )
{
m_logger.log( FQCN, Level.DEBUG, message, throwable );
}
/**
* Determine if messages of priority "debug" will be logged.
*
* @return true if "debug" messages will be logged
*/
public final boolean isDebugEnabled()
{
return m_logger.isDebugEnabled();
}
/**
* Log a info message.
*
* @param message the message
*/
public final void info( final String message )
{
m_logger.log( FQCN, Level.INFO, message, null );
}
/**
* Log a info message.
*
* @param message the message
* @param throwable the throwable
*/
public final void info( final String message, final Throwable throwable )
{
m_logger.log( FQCN, Level.INFO, message, throwable );
}
/**
* Determine if messages of priority "info" will be logged.
*
* @return true if "info" messages will be logged
*/
public final boolean isInfoEnabled()
{
return m_logger.isInfoEnabled();
}
/**
* Log a warn message.
*
* @param message the message
*/
public final void warn( final String message )
{
m_logger.log( FQCN, Level.WARN, message, null );
}
/**
* Log a warn message.
*
* @param message the message
* @param throwable the throwable
*/
public final void warn( final String message, final Throwable throwable )
{
m_logger.log( FQCN, Level.WARN, message, throwable );
}
/**
* Determine if messages of priority "warn" will be logged.
*
* @return true if "warn" messages will be logged
*/
public final boolean isWarnEnabled()
{
return m_logger.isEnabledFor( Level.WARN );
}
/**
* Log a error message.
*
* @param message the message
*/
public final void error( final String message )
{
m_logger.log( FQCN, Level.ERROR, message, null );
}
/**
* Log a error message.
*
* @param message the message
* @param throwable the throwable
*/
public final void error( final String message, final Throwable throwable )
{
m_logger.log( FQCN, Level.ERROR, message, throwable );
}
/**
* Determine if messages of priority "error" will be logged.
*
* @return true if "error" messages will be logged
*/
public final boolean isErrorEnabled()
{
return m_logger.isEnabledFor( Level.ERROR );
}
/**
* Log a fatalError message.
*
* @param message the message
*/
public final void fatalError( final String message )
{
m_logger.log( FQCN, Level.FATAL, message, null );
}
/**
* Log a fatalError message.
*
* @param message the message
* @param throwable the throwable
*/
public final void fatalError( final String message, final Throwable throwable )
{
m_logger.log( FQCN, Level.ERROR, message, throwable );
}
/**
* Determine if messages of priority "fatalError" will be logged.
*
* @return true if "fatalError" messages will be logged
*/
public final boolean isFatalErrorEnabled()
{
return m_logger.isEnabledFor( Level.FATAL );
}
/**
* Create a new child logger.
* The name of the child logger is [current-loggers-name].[passed-in-name]
* Throws IllegalArgumentException
if name has an empty element name
*
* @param name the subname of this logger
* @return the new logger
*/
public final Logger getChildLogger( final String name )
{
return new Log4JLogger( org.apache.log4j.Logger.getLogger( m_logger.getName() + "." + name ) );
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/logger/LogKit2AvalonLoggerAdapter.java 100644 0 0 7540 10051530441 30614 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.logger;
import org.apache.log.Hierarchy;
import org.apache.log.LogEvent;
import org.apache.log.LogTarget;
import org.apache.log.Priority;
/**
* A basic adapter that adapts an Avalon Logger to a Logkit Logger.
* Useful when providing backwards compatability support for Loggable
* components.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.11 $ $Date: 2004/02/11 14:34:26 $
* @since 4.1.4
*/
public final class LogKit2AvalonLoggerAdapter
implements LogTarget
{
/**
* The Avalon Logger that we re-route to.
*/
private final Logger m_logger;
/**
* Create a Logkit {@link org.apache.log.Logger} instance that
* redirects to an Avalon {@link org.apache.avalon.framework.logger.Logger} instance.
*
* @param logger the Avalon Logger
* @return the LogKit Logger
*/
public static org.apache.log.Logger createLogger( final Logger logger )
{
final Hierarchy hierarchy = new Hierarchy();
final org.apache.log.Logger logKitLogger = hierarchy.getLoggerFor( "" );
final LogKit2AvalonLoggerAdapter target =
new LogKit2AvalonLoggerAdapter( logger );
logKitLogger.setLogTargets( new LogTarget[ ] { target } );
if ( logger.isDebugEnabled() )
{
logKitLogger.setPriority( Priority.DEBUG );
}
else if ( logger.isInfoEnabled() )
{
logKitLogger.setPriority( Priority.INFO );
}
else if ( logger.isWarnEnabled() )
{
logKitLogger.setPriority( Priority.WARN );
}
else if ( logger.isErrorEnabled() )
{
logKitLogger.setPriority( Priority.ERROR );
}
else if ( logger.isFatalErrorEnabled() )
{
logKitLogger.setPriority( Priority.FATAL_ERROR );
}
return logKitLogger;
}
/**
* Constructor for an Adaptor. Adapts to
* specified Avalon Logger.
*
* @param logger the avalon logger.
*/
public LogKit2AvalonLoggerAdapter( final Logger logger )
{
if( null == logger )
{
throw new NullPointerException( "logger" );
}
m_logger = logger;
}
/**
* Route a LogKit message to an avalon Logger.
*
* @param event the log message
*/
public void processEvent( LogEvent event )
{
final String message = event.getMessage();
final Throwable throwable = event.getThrowable();
final Priority priority = event.getPriority();
if( Priority.DEBUG == priority )
{
m_logger.debug( message, throwable );
}
else if( Priority.INFO == priority )
{
m_logger.info( message, throwable );
}
else if( Priority.WARN == priority )
{
m_logger.warn( message, throwable );
}
else if( Priority.ERROR == priority )
{
m_logger.error( message, throwable );
}
else
{
m_logger.fatalError( message, throwable );
}
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/logger/LogKitLogger.java 100644 0 0 12363 10051530442 26110 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.logger;
/**
* The default LogKit wrapper class for Logger.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.16 $ $Date: 2004/02/11 14:34:26 $
*/
public final class LogKitLogger
implements Logger
{
//underlying implementation to delegate to
private final org.apache.log.Logger m_logger;
/**
* Create a logger that delegates to specified logger.
*
* @param logImpl the LogKit logger to delegate to
*/
public LogKitLogger( org.apache.log.Logger logImpl )
{
m_logger = logImpl;
}
/**
* Log a debug message.
*
* @param message the message
*/
public final void debug( final String message )
{
m_logger.debug( message );
}
/**
* Log a debug message.
*
* @param message the message
* @param throwable the throwable
*/
public final void debug( final String message, final Throwable throwable )
{
m_logger.debug( message, throwable );
}
/**
* Determine if messages of priority "debug" will be logged.
*
* @return true if "debug" messages will be logged
*/
public final boolean isDebugEnabled()
{
return m_logger.isDebugEnabled();
}
/**
* Log a info message.
*
* @param message the message
*/
public final void info( final String message )
{
m_logger.info( message );
}
/**
* Log a info message.
*
* @param message the message
* @param throwable the throwable
*/
public final void info( final String message, final Throwable throwable )
{
m_logger.info( message, throwable );
}
/**
* Determine if messages of priority "info" will be logged.
*
* @return true if "info" messages will be logged
*/
public final boolean isInfoEnabled()
{
return m_logger.isInfoEnabled();
}
/**
* Log a warn message.
*
* @param message the message
*/
public final void warn( final String message )
{
m_logger.warn( message );
}
/**
* Log a warn message.
*
* @param message the message
* @param throwable the throwable
*/
public final void warn( final String message, final Throwable throwable )
{
m_logger.warn( message, throwable );
}
/**
* Determine if messages of priority "warn" will be logged.
*
* @return true if "warn" messages will be logged
*/
public final boolean isWarnEnabled()
{
return m_logger.isWarnEnabled();
}
/**
* Log a error message.
*
* @param message the message
*/
public final void error( final String message )
{
m_logger.error( message );
}
/**
* Log a error message.
*
* @param message the message
* @param throwable the throwable
*/
public final void error( final String message, final Throwable throwable )
{
m_logger.error( message, throwable );
}
/**
* Determine if messages of priority "error" will be logged.
*
* @return true if "error" messages will be logged
*/
public final boolean isErrorEnabled()
{
return m_logger.isErrorEnabled();
}
/**
* Log a fatalError message.
*
* @param message the message
*/
public final void fatalError( final String message )
{
m_logger.fatalError( message );
}
/**
* Log a fatalError message.
*
* @param message the message
* @param throwable the throwable
*/
public final void fatalError( final String message, final Throwable throwable )
{
m_logger.fatalError( message, throwable );
}
/**
* Determine if messages of priority "fatalError" will be logged.
*
* @return true if "fatalError" messages will be logged
*/
public final boolean isFatalErrorEnabled()
{
return m_logger.isFatalErrorEnabled();
}
/**
* Create a new child logger.
* The name of the child logger is [current-loggers-name].[passed-in-name]
* Throws IllegalArgumentException
if name has an empty element name
*
* @param name the subname of this logger
* @return the new logger
*/
public final Logger getChildLogger( final String name )
{
return new LogKitLogger( m_logger.getChildLogger( name ) );
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/logger/NullLogger.java 100644 0 0 7330 10051530441 25606 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.logger;
/**
* The Null Logger class. This is useful for implementations where you need
* to provide a logger to a utility class, but do not want any output from it.
* It also helps when you have a utility that does not have a logger to supply.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.13 $ $Date: 2004/02/11 14:34:26 $
*/
public final class NullLogger implements Logger
{
/**
* Creates a new NullLogger
.
*/
public NullLogger()
{
}
/**
* No-op.
*
* @param message ignored
*/
public void debug( String message )
{
}
/**
* No-op.
*
* @param message ignored
* @param throwable ignored
*/
public void debug( String message, Throwable throwable )
{
}
/**
* No-op.
*
* @return false
*/
public boolean isDebugEnabled()
{
return false;
}
/**
* No-op.
*
* @param message ignored
*/
public void info( String message )
{
}
/**
* No-op.
*
* @param message ignored
* @param throwable ignored
*/
public void info( String message, Throwable throwable )
{
}
/**
* No-op.
*
* @return false
*/
public boolean isInfoEnabled()
{
return false;
}
/**
* No-op.
*
* @param message ignored
*/
public void warn( String message )
{
}
/**
* No-op.
*
* @param message ignored
* @param throwable ignored
*/
public void warn( String message, Throwable throwable )
{
}
/**
* No-op.
*
* @return false
*/
public boolean isWarnEnabled()
{
return false;
}
/**
* No-op.
*
* @param message ignored
*/
public void error( String message )
{
}
/**
* No-op.
*
* @param message ignored
* @param throwable ignored
*/
public void error( String message, Throwable throwable )
{
}
/**
* No-op.
*
* @return false
*/
public boolean isErrorEnabled()
{
return false;
}
/**
* No-op.
*
* @param message ignored
*/
public void fatalError( String message )
{
}
/**
* No-op.
*
* @param message ignored
* @param throwable ignored
*/
public void fatalError( String message, Throwable throwable )
{
}
/**
* No-op.
*
* @return false
*/
public boolean isFatalErrorEnabled()
{
return false;
}
/**
* Returns this NullLogger
.
*
* @param name ignored
* @return this NullLogger
*/
public Logger getChildLogger( String name )
{
return this;
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/service/DefaultServiceManager.java 100644 0 0 12023 10051530442 30131 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.service;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* This class is a static implementation of a ServiceManager
. Allow ineritance
* and extension so you can generate a tree of ServiceManager
each defining
* Object scope.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.20 $ $Date: 2004/02/11 14:34:26 $
*/
public class DefaultServiceManager
implements ServiceManager
{
private final HashMap m_objects = new HashMap();
private final ServiceManager m_parent;
private boolean m_readOnly;
/**
* Construct ServiceManager
with no parent.
*
*/
public DefaultServiceManager()
{
this( null );
}
/**
* Construct ServiceManager
with specified parent.
*
* @param parent this ServiceManager
's parent
*/
public DefaultServiceManager( final ServiceManager parent )
{
m_parent = parent;
}
/**
* Retrieve Object
by key from ServiceManager
.
*
* @param key the key
* @return the Object
* @throws ServiceException if an error occurs
*/
public Object lookup( final String key )
throws ServiceException
{
final Object object = m_objects.get( key );
if( null != object )
{
return object;
}
else if( null != m_parent )
{
return m_parent.lookup( key );
}
else
{
final String message = "Unable to provide implementation for " + key;
throw new ServiceException( key, message, null );
}
}
/**
* Check to see if a Object
exists for a key.
*
* @param key a string identifying the key to check.
* @return True if the object exists, False if it does not.
*/
public boolean hasService( final String key )
{
try
{
lookup( key );
return true;
}
catch( final Throwable t )
{
return false;
}
}
/**
* Place Object
into ServiceManager
.
*
* @param key the object's key
* @param object an Object
value
*/
public void put( final String key, final Object object )
{
checkWriteable();
m_objects.put( key, object );
}
/**
* Build a human readable representation of this
* ServiceManager
.
*
* @return the description of this ServiceManager
*/
public String toString()
{
final StringBuffer buffer = new StringBuffer();
final Iterator objects = m_objects.keySet().iterator();
buffer.append( "Services:" );
while( objects.hasNext() )
{
buffer.append( "[" );
buffer.append( objects.next() );
buffer.append( "]" );
}
return buffer.toString();
}
/**
* Helper method for subclasses to retrieve parent.
*
* @return the parent ServiceManager
*/
protected final ServiceManager getParent()
{
return m_parent;
}
/**
* Helper method for subclasses to retrieve object map.
*
* @return the object map
*/
protected final Map getObjectMap()
{
return m_objects;
}
/**
* Makes this ServiceManager
read-only.
*
*/
public void makeReadOnly()
{
m_readOnly = true;
}
/**
* Checks if this ServiceManager
is writeable.
*
* @throws IllegalStateException if this ServiceManager
is
* read-only
*/
protected final void checkWriteable()
throws IllegalStateException
{
if( m_readOnly )
{
final String message =
"ServiceManager is read only and can not be modified";
throw new IllegalStateException( message );
}
}
/**
* Release the Object
.
* @param object The Object
to release.
*/
public void release( Object object )
{
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/service/DefaultServiceSelector.java 100644 0 0 10146 10051530442 30343 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.service;
import java.util.HashMap;
import java.util.Map;
/**
* This is the default implementation of the ServiceSelector
*
* @author Avalon Development Team
* @version CVS $Revision: 1.16 $ $Date: 2004/02/11 14:34:26 $
*/
public class DefaultServiceSelector
implements ServiceSelector
{
private final HashMap m_objects = new HashMap();
private boolean m_readOnly;
private final String m_role;
/**
* Create a DefaultServiceSelector with a default empty role.
*/
public DefaultServiceSelector()
{
this("");
}
/**
* Create a DefaultServiceSelector with a role for debug purposes.
*
* @param role The role for this selector.
*
* @throws NullPointerException if the role is null.
*/
public DefaultServiceSelector(String role)
{
if ( null==role )
{
throw new NullPointerException(role);
}
m_role = role;
}
/**
* Select the desired object.
*
* @param hint the hint to retrieve Object
* @return the Object
* @throws ServiceException if an error occurs
*/
public Object select( Object hint )
throws ServiceException
{
final Object object = m_objects.get( hint );
if( null != object )
{
return object;
}
else
{
throw new ServiceException( m_role + "/" + hint.toString(), "Unable to provide implementation" );
}
}
/**
* Returns whether a Object exists or not
* @param hint the hint to retrieve Object
* @return true
if the Object exists
*/
public boolean isSelectable( final Object hint )
{
boolean objectExists = false;
try
{
this.release( this.select( hint ) );
objectExists = true;
}
catch( Throwable t )
{
// Ignore all throwables--we want a yes or no answer.
}
return objectExists;
}
/**
* Release object.
*
* @param object the Object
to release
*/
public void release( final Object object )
{
// if the ServiceManager handled pooling, it would be
// returned to the pool here.
}
/**
* Populate the ServiceSelector.
* @param hint the hint to be used to retrieve the Object later
* @param object the Object to hold
*/
public void put( final Object hint, final Object object )
{
checkWriteable();
m_objects.put( hint, object );
}
/**
* Helper method for subclasses to retrieve object map.
*
* @return the object map
*/
protected final Map getObjectMap()
{
return m_objects;
}
/**
* Makes this service selector read-only.
*
*/
public void makeReadOnly()
{
m_readOnly = true;
}
/**
* Checks if this service selector is writeable.
*
* @throws IllegalStateException if this service selector is read-only
*/
protected final void checkWriteable()
throws IllegalStateException
{
if( m_readOnly )
{
throw new IllegalStateException
( "ServiceSelector is read only and can not be modified" );
}
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/service/WrapperServiceManager.java 100644 0 0 7066 10051530442 30160 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.service;
import org.apache.avalon.framework.component.Component;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.component.ComponentSelector;
/**
* This is a {@link ServiceManager} implementation that can wrap around a legacy
* {@link ComponentManager} object effectively adapting a {@link ComponentManager}
* interface to a {@link ServiceManager} interface.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.10 $ $Date: 2004/02/11 14:34:26 $
* @since 4.1.4
*/
public class WrapperServiceManager
implements ServiceManager
{
/**
* The component manager thaty this class wraps.
*/
private final ComponentManager m_componentManager;
/**
* This constructor is a constructor for a WrapperServiceManager.
*
* @param componentManager the ComponentManager instance that is being wrapped
*/
public WrapperServiceManager( final ComponentManager componentManager )
{
if( null == componentManager )
{
throw new NullPointerException( "componentManager" );
}
m_componentManager = componentManager;
}
/**
* Retrieve a service using specified key.
*
* @param key the key to use to lookup component
* @return the matching service
* @throws ServiceException if unable to provide the service
* @see ServiceManager#lookup
*/
public Object lookup( final String key )
throws ServiceException
{
try
{
final Object service = m_componentManager.lookup( key );
if( service instanceof ComponentSelector )
{
return new WrapperServiceSelector( key, (ComponentSelector)service );
}
else
{
return service;
}
}
catch( final ComponentException ce )
{
throw new ServiceException( key, ce.getMessage(), ce );
}
}
/**
* Return true if the component is available in ServiceManager.
*
* @param key the lookup
* @return true if the component is available in ServiceManager
*/
public boolean hasService( final String key )
{
return m_componentManager.hasComponent( key );
}
/**
* Release the service back to the ServiceManager.
*
* @param service the service
*/
public void release( final Object service )
{
if ( service instanceof WrapperServiceSelector )
{
m_componentManager.
release( ((WrapperServiceSelector)service).getWrappedSelector() );
}
else
{
m_componentManager.release( (Component)service );
}
}
}
avalon-framework/impl/src/java/org/apache/avalon/framework/service/WrapperServiceSelector.java 100644 0 0 10141 10051530442 30372 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.service;
import org.apache.avalon.framework.component.Component;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.ComponentSelector;
/**
* This is a {@link ServiceSelector} implementation that can wrap around a legacy
* {@link ComponentSelector} object effectively adapting a {@link ComponentSelector}
* interface to a {@link ServiceSelector} interface.
*
* This class implements the {@link Component} interface because it is used in
* environments which expect all components to implement Component.
*
* @author Avalon Development Team
* @version CVS $Revision: 1.10 $ $Date: 2004/02/11 14:34:26 $
* @since 4.1.4
*/
public class WrapperServiceSelector
implements ServiceSelector
{
/**
* The Selector we are wrapping.
*/
private final ComponentSelector m_selector;
/**
* The role that this selector was aquired via.
*/
private final String m_key;
/**
* This constructor is a constructor for a ComponentServiceManager
*
* @param key the key used to aquire this selector
* @param selector the selector to wrap
*/
public WrapperServiceSelector( final String key,
final ComponentSelector selector )
{
if( null == key )
{
throw new NullPointerException( "key" );
}
if( null == selector )
{
throw new NullPointerException( "selector" );
}
m_key = key + "/";
m_selector = selector;
}
/**
* Select a service based on a policy.
*
* @param policy the policy
* @return the service
* @throws ServiceException if unable to select service
*/
public Object select( final Object policy )
throws ServiceException
{
try
{
return m_selector.select( policy );
}
catch( final ComponentException ce )
{
throw new ServiceException( m_key + policy, ce.getMessage(), ce );
}
}
/**
* Check to see if a {@link Object} exists relative to the supplied policy.
*
* @param policy a {@link Object} containing the selection criteria
* @return True if the component is available, False if it not.
*/
public boolean isSelectable( final Object policy )
{
return m_selector.hasComponent( policy );
}
/**
* Return the {@link Object} when you are finished with it. This
* allows the {@link ServiceSelector} to handle the End-Of-Life Lifecycle
* events associated with the {@link Object}. Please note, that no
* Exception should be thrown at this point. This is to allow easy use of the
* ServiceSelector system without having to trap Exceptions on a release.
*
* @param object The {@link Object} we are releasing.
*/
public void release( Object object )
{
m_selector.release( (Component)object );
}
/**
* The {@link WrapperServiceManager} wraps ComponentSelectors in
* WrapperServiceSelectors when they are looked up. This method
* makes it possible to release the original component selector.
*
* @return The {@link ComponentSelector} being wrapped.
*/
ComponentSelector getWrappedSelector()
{
return m_selector;
}
}
././@LongLink 100644 0 0 157 10051530443 10251 L ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/component/test/DefaultComponentManagerTestCase.java avalon-framework/impl/src/test/org/apache/avalon/framework/component/test/DefaultComponentManagerTes100644 0 0 11272 10051530442 31613 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.component.test;
import junit.framework.TestCase;
import org.apache.avalon.framework.component.Component;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.DefaultComponentManager;
/**
* Test the basic public methods of DefaultComponentManager.
*
* @author Avalon Development Team
*/
public final class DefaultComponentManagerTestCase
extends TestCase
{
class DefaultRoleA
implements Component,RoleA
{
public DefaultRoleA()
{
}
}
class DefaultRoleB
implements Component,RoleB
{
public DefaultRoleB()
{
}
}
private DefaultComponentManager m_componentManager;
protected boolean m_exceptionThrown;
public DefaultComponentManagerTestCase()
{
this("DefaultComponentManager Test Case");
}
public DefaultComponentManagerTestCase( final String name )
{
super( name );
}
protected void setUp()
throws Exception
{
m_componentManager = new DefaultComponentManager();
m_exceptionThrown = false;
}
protected void tearDown()
throws Exception
{
m_componentManager = null;
}
/**
* lookup contract:
* return first component found for role
* search in hirarchy from current componentManager up.
* if no compnent exist for role a in hierarchy
* throw ComponentException
*/
public void testlookup1()
throws Exception
{
DefaultRoleB roleBinBase = new DefaultRoleB();
DefaultRoleB roleBinParent = new DefaultRoleB();
DefaultRoleA roleAinParent = new DefaultRoleA();
m_componentManager.put(RoleA.ROLE,roleAinParent);
m_componentManager.put(RoleB.ROLE,roleBinParent);
DefaultComponentManager baseComponentManager = new DefaultComponentManager(m_componentManager);
baseComponentManager.put(RoleB.ROLE,roleBinBase);
Object lookupAinBase = baseComponentManager.lookup(RoleA.ROLE);
Object lookupBinBase = baseComponentManager.lookup(RoleB.ROLE);
Object lookupBinParent = m_componentManager.lookup(RoleB.ROLE);
assertTrue( lookupAinBase instanceof RoleA);
assertEquals( lookupBinBase, roleBinBase );
assertEquals( lookupBinParent, roleBinParent );
assertEquals( lookupAinBase,roleAinParent);
}
public void testlookup2()
throws Exception
{
m_componentManager.put(RoleA.ROLE,new DefaultRoleA());
Object o = null;
try
{
o = m_componentManager.lookup(RoleB.ROLE);
}
catch (ComponentException ce)
{
m_exceptionThrown = true;
}
if (o == null)
assertTrue("ComponentException was not thrown when component was not found by lookup." ,m_exceptionThrown );
else
assertTrue("component was found by lookup ,when there was no component.",false);
}
public void testhasComponent()
throws Exception
{
m_componentManager.put(RoleA.ROLE,new DefaultRoleA());
assertTrue(m_componentManager.hasComponent(RoleA.ROLE));
assertTrue(!m_componentManager.hasComponent(RoleB.ROLE));
}
public void testmakeReadOnly()
throws Exception
{
//before read only
m_componentManager.put(RoleA.ROLE,new DefaultRoleA());
Object a = m_componentManager.lookup(RoleA.ROLE);
assertTrue( a instanceof RoleA);
m_componentManager.makeReadOnly();
//after read only
try
{
m_componentManager.put(RoleB.ROLE,new DefaultRoleB());
}
catch (IllegalStateException se)
{
m_exceptionThrown = true;
}
assertTrue("IllegalStateException was not thrown in put after makeReadOnly." , m_exceptionThrown );
}
}
././@LongLink 100644 0 0 160 10051530443 10243 L ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/component/test/DefaultComponentSelectorTestCase.java avalon-framework/impl/src/test/org/apache/avalon/framework/component/test/DefaultComponentSelectorTe100644 0 0 11063 10051530442 31634 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.component.test;
import junit.framework.TestCase;
import org.apache.avalon.framework.component.Component;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.DefaultComponentSelector;
/**
* Test the basic public methods of DefaultComponentSelector.
*
* @author Avalon Development Team
*/
public final class DefaultComponentSelectorTestCase
extends TestCase
{
class FeatureComponent
implements Component
{
Object m_feature;
public FeatureComponent( final Object feature )
{
m_feature = feature;
}
public Object getFeature()
{
return m_feature;
}
}
class Hint
{
String m_name;
public Hint( final String name )
{
m_name = name;
}
public String getName()
{
return m_name;
}
}
private DefaultComponentSelector m_componentSelector;
protected boolean m_exceptionThrown;
public DefaultComponentSelectorTestCase()
{
this("DefaultComponentSelector Test Case");
}
public DefaultComponentSelectorTestCase( final String name )
{
super( name );
}
protected void setUp()
throws Exception
{
m_componentSelector = new DefaultComponentSelector();
m_exceptionThrown =false;
}
protected void tearDown()
throws Exception
{
m_componentSelector = null;
}
/**
* lookup contract:
* return the component that was put with this hint
* if no compnent exist for hint
* throw ComponentException
*/
public void testlookup()
throws Exception
{
Hint hintA = new Hint("a");
Hint hintB = new Hint("b");
m_componentSelector.put(hintA,new FeatureComponent(hintA));
m_componentSelector.put(hintB,new FeatureComponent(hintB));
FeatureComponent fComponent = (FeatureComponent)m_componentSelector.select(hintA);
assertEquals( hintA, fComponent.getFeature() );
Object o = null;
try
{
o = (FeatureComponent)m_componentSelector.select(new Hint("no component"));
}
catch (ComponentException ce)
{
m_exceptionThrown = true;
}
if (o == null)
assertTrue("ComponentException was not thrown when component was not found by lookup." ,m_exceptionThrown );
else
assertTrue("component was found by lookup ,when there was no component.",false);
}
public void testhasComponent()
throws Exception
{
Hint hintA = new Hint("a");
Hint hintB = new Hint("b");
m_componentSelector.put(hintA,new FeatureComponent(hintA));
assertTrue(m_componentSelector.hasComponent(hintA));
assertTrue(!m_componentSelector.hasComponent(hintB));
}
//makeReadOnly contract:put after makeReadOnly throws IllegalStateException
public void testmakeReadOnly()
throws Exception
{
Hint hintA = new Hint("a");
Hint hintB = new Hint("b");
//before read only
m_componentSelector.put(hintA,new FeatureComponent(hintA));
FeatureComponent fComponent = (FeatureComponent)m_componentSelector.select(hintA);
assertEquals( hintA, fComponent.getFeature() );
m_componentSelector.makeReadOnly();
//after read only
try
{
m_componentSelector.put(hintB,new FeatureComponent(hintB));
}
catch (IllegalStateException se)
{
m_exceptionThrown = true;
}
assertTrue("IllegalStateException was not thrown in put after makeReadOnly." , m_exceptionThrown );
}
}
avalon-framework/impl/src/test/org/apache/avalon/framework/component/test/RoleA.java 100644 0 0 1525 10051530442 26277 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.component.test;
/**
* @author Avalon Development Team
*/
public interface RoleA
{
String ROLE = RoleA.class.getName();
}
avalon-framework/impl/src/test/org/apache/avalon/framework/component/test/RoleB.java 100644 0 0 1525 10051530442 26300 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.component.test;
/**
* @author Avalon Development Team
*/
public interface RoleB
{
String ROLE = RoleB.class.getName();
}
././@LongLink 100644 0 0 167 10051530443 10252 L ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/configuration/test/DefaultConfigurationBuilderTestCase.java avalon-framework/impl/src/test/org/apache/avalon/framework/configuration/test/DefaultConfigurationBu100644 0 0 45617 10051530442 31657 0 ustar 0 0 /*
* Copyright 1997-2004 Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration.test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import junit.framework.TestCase;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.InputSource;
import org.xml.sax.EntityResolver;
/**
* Test that the Configuration
s built by
* DefaultConfigurationBuilder
meet the stated API contracts.
*
* @author Avalon Development Team
*/
public final class DefaultConfigurationBuilderTestCase
extends TestCase
{
private static final String SIMPLE_FILE_NAME = "config_simple.xml";
private static final String NS_FILE_NAME = "config_namespaces.xml";
private static final String EXTERNAL_FILE_NAME = "config_usingexternal.xml";
private static final String INNER_FILE_NAME = "config_inner.xml";
private static final String TEST_PATH = "test/framework/io/";
private DefaultConfigurationBuilder m_builder;
private DefaultConfigurationBuilder m_nsBuilder;
private File m_file;
private File m_nsFile;
private File m_fileWithExternalEntity;
private File m_innerXmlFile;
private File m_testDirectory;
private final String SIMPLE_XML =
""+
"simpleXML
, ie namespace
* support is disabled.
*/
private void simpleAssertions(Configuration conf)
throws ConfigurationException
{
assertEquals( "config", conf.getName() );
assertEquals( "getNamespace() should default to \"\"", "", conf.getNamespace() );
try {
conf.getValue();
fail( "Should throw a ConfigurationException, as this element"+
"contains child elements, not a value" );
} catch ( ConfigurationException e )
{}
Configuration[] children;
children = conf.getChildren();
assertEquals( 4, children.length );
assertEquals( "elements-a", children[0].getName() );
assertEquals( "elements-b", children[1].getName() );
assertEquals( "b", children[1].getChild("element", false).getAttribute("name") );
assertEquals( "elements-b", children[2].getName() );
assertEquals( "elements-c", children[3].getName() );
final String[] attrNames = conf.getAttributeNames();
assertEquals( 2, attrNames.length );
assertEquals( "default", conf.getAttribute("nonexistent", "default") );
assertEquals( true, conf.getAttributeAsBoolean("boolAttr") );
assertEquals( (float)1.32, conf.getAttributeAsFloat("floatAttr"), 0.0 );
// Check that the auto-node-creation feature is working correctly.
assertEquals(
"When a non-existent child is requested, a blank node should be created",
"nonexistent",
conf.getChild( "nonexistent" ).getName()
);
assertEquals(
"When a non-existent child is requested, a blank node should be created",
"baz",
conf.getChild( "foo" ).getChild("bar").getChild("baz").getName()
);
try {
conf.getChild("nonexistent").getValue();
fail( "Auto-created child nodes should not have a value" );
} catch ( ConfigurationException e )
{}
assertEquals( "Turning auto-node-creation off failed", null, conf.getChild( "nonexistent", false )
);
assertEquals( "Standard getChild() lookup failed", "elements-b", conf.getChild( "elements-b", false ).getName() );
assertEquals( "Boolean value surrounded by whitespace failed", true, conf.getChild("elements-c").getValueAsBoolean( false ) );
assertEquals( "A value-containing element should have no child nodes", 0, conf.getChild("elements-c").getChildren().length );
}
private final String NS_XML =
""+
"nsXML
, ie namespace support is disabled,
* but the XML uses namespaces.
*/
private void simpleAssertionsNS(Configuration conf)
throws ConfigurationException
{
assertEquals( "conf:config", conf.getName() );
assertEquals( "getNamespace() should default to \"\"", "", conf.getNamespace() );
try {
conf.getValue();
fail( "Should throw a ConfigurationException, as this element"+
"contains child elements, not a value" );
} catch ( ConfigurationException e )
{}
Configuration[] children;
children = conf.getChildren();
assertEquals( 6, children.length );
assertEquals( "a:elements-a", children[0].getName() );
assertEquals( "elements-b", children[1].getName() );
assertEquals( "b", children[1].getChild("element", false).getAttribute("name") );
assertEquals( "b:elements-b", children[2].getName() );
assertEquals( "elements-c", children[3].getName() );
final String[] attrNames = conf.getAttributeNames();
assertEquals( 8, attrNames.length );
assertEquals( "true", conf.getAttribute("boolAttr", null) );
assertEquals( true, conf.getAttributeAsBoolean("boolAttr") );
assertEquals( (float)1.32, conf.getAttributeAsFloat("floatAttr"), 0.0 );
assertEquals( "http://conf.com", conf.getAttribute("xmlns:conf") );
assertEquals( "http://a.com", conf.getAttribute("xmlns:a") );
assertEquals( "http://b.com", conf.getAttribute("xmlns:b") );
assertEquals( "http://c.com", conf.getAttribute("xmlns:c") );
// Check that the auto-node-creation feature is working correctly.
assertEquals(
"When a non-existent child is requested, a blank node should be created",
"nonexistent",
conf.getChild( "nonexistent" ).getName()
);
assertEquals(
"When a non-existent child is requested, a blank node should be created",
"baz",
conf.getChild( "foo" ).getChild("bar").getChild("baz").getName()
);
try {
conf.getChild("nonexistent").getValue();
fail( "Auto-created child nodes should not have a value" );
} catch ( ConfigurationException e )
{}
assertEquals( "Turning auto-node-creation off failed", null, conf.getChild( "nonexistent", false )
);
assertEquals( "Standard getChild() lookup failed", "b:elements-b", conf.getChild( "b:elements-b", false ).getName() );
assertEquals( "Boolean value surrounded by whitespace failed", true, conf.getChild("elements-c").getValueAsBoolean( false ) );
assertEquals( "A value-containing element should have no child nodes", 0, conf.getChild("elements-c").getChildren().length );
assertEquals( "d:element", conf.getChild("d:element").getValue() );
assertEquals( "e:element", conf.getChild("e:element").getValue() );
}
/**
* These assertions apply when the namespace-enabled builder is used to
* create a Configuration from nsXML
, ie namespace support is
* enabled, and the XML uses namespaces.
*/
private void nsAssertions(Configuration conf)
throws ConfigurationException
{
assertEquals( "config", conf.getName() );
assertEquals( "Namespace not set correctly", "http://conf.com", conf.getNamespace() );
try {
conf.getValue();
fail( "Should throw a ConfigurationException, as this element"+
"contains child elements, not a value" );
} catch ( ConfigurationException e )
{}
Configuration[] children;
children = conf.getChildren();
assertEquals( 6, children.length );
assertEquals( "elements-a", children[0].getName() );
assertEquals( "http://a.com", children[0].getNamespace() );
assertEquals( "elements-b", children[1].getName() );
assertEquals( "http://defaultns.com", children[1].getNamespace() );
assertEquals( "b", children[1].getChild("element", false).getAttribute("name") );
assertEquals( "elements-b", children[2].getName() );
assertEquals( "http://b.com", children[2].getNamespace() );
assertEquals( "elements-c", children[3].getName() );
assertEquals( "", children[3].getNamespace() );
final String[] attrNames = conf.getAttributeNames();
assertEquals( 2, attrNames.length ); // the other 4 are xmlns and so shouldn't appear
assertEquals( "true", conf.getAttribute("boolAttr", null) );
assertEquals( true, conf.getAttributeAsBoolean("boolAttr") );
assertEquals( (float)1.32, conf.getAttributeAsFloat("floatAttr"), 0.0 );
// Check that the auto-node-creation feature is working correctly.
assertEquals(
"When a non-existent child is requested, a blank node should be created",
"nonexistent",
conf.getChild( "nonexistent" ).getName()
);
assertEquals(
"When a non-existent child is requested, a blank node should be created",
"baz",
conf.getChild( "foo" ).getChild("bar").getChild("baz").getName()
);
try {
conf.getChild("nonexistent").getValue();
fail( "Auto-created child nodes should not have a value" );
} catch ( ConfigurationException e )
{}
assertEquals( "Turning auto-node-creation off failed", null, conf.getChild( "nonexistent", false )
);
assertEquals( "Standard getChild() lookup failed", "elements-b", conf.getChild( "elements-b", false ).getName() );
assertEquals( "Boolean value surrounded by whitespace failed", true, conf.getChild("elements-c").getValueAsBoolean( false ) );
assertEquals( "A value-containing element should have no child nodes", 0, conf.getChild("elements-c").getChildren().length );
}
public DefaultConfigurationBuilderTestCase()
{
this("DefaultConfigurationBuilder Test Case");
}
public DefaultConfigurationBuilderTestCase( final String name )
{
super( name );
m_testDirectory = (new File( TEST_PATH )).getAbsoluteFile();
if( !m_testDirectory.exists() )
{
m_testDirectory.mkdirs();
}
}
protected void setUp()
throws Exception
{
m_file = new File( m_testDirectory, SIMPLE_FILE_NAME );
m_nsFile = new File( m_testDirectory, NS_FILE_NAME );
m_fileWithExternalEntity = new File( m_testDirectory, EXTERNAL_FILE_NAME );
m_innerXmlFile = new File( m_testDirectory, INNER_FILE_NAME );
FileWriter writer = new FileWriter( m_file );
writer.write( SIMPLE_XML );
writer.close();
writer = new FileWriter( m_nsFile );
writer.write( NS_XML );
writer.close();
writer = new FileWriter( m_fileWithExternalEntity );
writer.write( XML_WITH_EXTERNAL_ENTITY );
writer.close();
writer = new FileWriter( m_innerXmlFile );
writer.write( INNER_XML );
writer.close();
}
protected void tearDown()
throws Exception
{
m_builder = null;
m_nsBuilder = null;
}
public void testBuildFromFileName()
throws Exception
{
m_builder = new DefaultConfigurationBuilder();
m_nsBuilder = new DefaultConfigurationBuilder(true); // switch on namespace support
Configuration conf = m_builder.buildFromFile( TEST_PATH + SIMPLE_FILE_NAME );
simpleAssertions( conf );
conf = m_builder.buildFromFile( TEST_PATH + NS_FILE_NAME );
simpleAssertionsNS( conf );
conf = m_nsBuilder.buildFromFile( TEST_PATH + NS_FILE_NAME );
nsAssertions( conf );
}
public void testBuildFromFile()
throws Exception
{
m_builder = new DefaultConfigurationBuilder();
m_nsBuilder = new DefaultConfigurationBuilder(true); // switch on namespace support
Configuration conf = m_builder.buildFromFile( m_file );
simpleAssertions( conf );
conf = m_builder.buildFromFile( m_nsFile );
simpleAssertionsNS( conf );
conf = m_nsBuilder.buildFromFile( m_nsFile );
nsAssertions( conf );
}
public void testBuild()
throws Exception
{
m_builder = new DefaultConfigurationBuilder();
m_nsBuilder = new DefaultConfigurationBuilder(true); // switch on namespace support
Configuration conf = m_builder.build( m_file.toURL().toString() );
simpleAssertions( conf );
conf = m_builder.buildFromFile( m_nsFile );
simpleAssertionsNS( conf );
conf = m_nsBuilder.buildFromFile( m_nsFile );
nsAssertions( conf );
}
private final String spaceTrimmingCheckXML =
""+
" serializeToFile
method closes the output stream
* when it is done.
*/
public void testSerializeToFile() throws Exception
{
DefaultConfiguration config = new DefaultConfiguration("root", "");
config.setAttribute( "attribute", "value" );
File file = new File( testDirectory, "DefaultConfigurationSerializerTestCase.xml" );
DefaultConfigurationSerializer serializer = new DefaultConfigurationSerializer();
serializer.serializeToFile( file, config );
//
// This will not work if the serializeToFile method keeps the stream open.
//
assertTrue( testDirectory.renameTo( testDirectory2 ) );
assertTrue( testDirectory2.renameTo( testDirectory ) );
file.delete();
}
}
././@LongLink 100644 0 0 160 10051530443 10243 L ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/configuration/test/DefaultConfigurationTestCase.java avalon-framework/impl/src/test/org/apache/avalon/framework/configuration/test/DefaultConfigurationTe100644 0 0 22525 10051530441 31651 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration.test;
import junit.framework.TestCase;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.ConfigurationUtil;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.avalon.framework.configuration.MutableConfiguration;
/**
* Test the basic public methods of DefaultConfiguration.
*
* @author Avalon Development Team
*/
public final class DefaultConfigurationTestCase extends TestCase
{
private DefaultConfiguration m_configuration;
public DefaultConfigurationTestCase()
{
this("DefaultConfiguration Test Case");
}
public DefaultConfigurationTestCase( String name )
{
super( name );
}
public void setUp()
{
m_configuration = new DefaultConfiguration( "a", "b" );
}
public void tearDowm()
{
m_configuration = null;
}
public void testGetValue()
throws Exception
{
final String orgValue = "Original String";
m_configuration.setValue( orgValue );
assertEquals( orgValue, m_configuration.getValue() );
}
public void testGetValueAsInteger()
throws Exception
{
final int orgValue = 55;
final String strValue = Integer.toHexString( orgValue );
m_configuration.setValue( "0x" + strValue );
assertEquals( orgValue, m_configuration.getValueAsInteger() );
}
public void testGetValueAsBoolen()
throws Exception
{
final boolean b = true;
m_configuration.setValue("TrUe");
assertEquals( b, m_configuration.getValueAsBoolean() );
}
public void testGetAttribute()
throws Exception
{
final String key = "key";
final String value = "original value";
final String defaultStr = "default";
m_configuration.setAttribute( key, value );
assertEquals( value, m_configuration.getAttribute( key, defaultStr ) );
assertEquals(defaultStr , m_configuration.getAttribute( "newKey", defaultStr ) );
}
public void testMakeReadOnly()
{
final String key = "key";
final String value = "original value";
String exception = "exception not thrown";
final String exceptionStr ="Configuration is read only";
m_configuration.makeReadOnly();
try
{
m_configuration.setAttribute( key, value );
}
catch( final IllegalStateException ise )
{
exception = exceptionStr;
}
assertEquals( exception, exceptionStr );
}
public void testAddRemoveChild()
{
final String childName = "child";
final Configuration child = new DefaultConfiguration( childName, "child location" );
m_configuration.addChild( child );
assertEquals( child, m_configuration.getChild( childName ) );
m_configuration.removeChild( child );
assertEquals( null, m_configuration.getChild( childName, false ) );
}
public void testCopying() throws Exception
{
DefaultConfiguration root = new DefaultConfiguration( "root", "0:0", "http://root", "root" );
root.setAttribute( "attr1", "1" );
root.setAttribute( "attr2", "2" );
DefaultConfiguration child1 = new DefaultConfiguration( "child1", "0:1", "http://root/child1", "child1" );
DefaultConfiguration child2 = new DefaultConfiguration( "child2", "0:2", "http://root/child2", "child2" );
root.addChild( child1 );
root.addChild( child2 );
root.makeReadOnly();
DefaultConfiguration modifiableRoot = new DefaultConfiguration( root );
assertTrue( ConfigurationUtil.equals( root, modifiableRoot ) );
modifiableRoot.setAttribute( "attr1", "0" );
assertEquals( "0", modifiableRoot.getAttribute( "attr1" ) );
DefaultConfiguration modifiableChild1 = new DefaultConfiguration( root.getChild("child1") );
modifiableChild1.setValue( "1" );
modifiableRoot.removeChild( modifiableRoot.getChild("child1") );
modifiableRoot.addChild( modifiableChild1 );
assertEquals( "1", modifiableRoot.getChild( "child1" ).getValue() );
}
public void testConvenienceSetters() throws Exception
{
DefaultConfiguration config = new DefaultConfiguration( "root", "0:0", "http://root", "root" );
config.setAttribute( "integer", 12 );
config.setAttribute( "long", 8000000000L );
config.setAttribute( "float", 1.23f );
config.setAttribute( "boolean", true );
config.setAttribute( "string", "string" );
assertEquals( "12", config.getAttribute("integer") );
assertEquals( "8000000000", config.getAttribute("long") );
assertEquals( 1.23, config.getAttributeAsFloat("float"), 0.01 );
assertEquals( "string", config.getAttribute("string") );
assertEquals( "true", config.getAttribute("boolean") );
assertEquals( 12, config.getAttributeAsInteger("integer") );
assertEquals( 8000000000L, config.getAttributeAsLong("long") );
assertEquals( "string", config.getAttribute("string") );
assertEquals( true, config.getAttributeAsBoolean("boolean") );
}
public void testSetToNull() throws Exception
{
DefaultConfiguration config = new DefaultConfiguration( "root", "0:0", "http://root", "root" );
config.setAttribute( "integer", "12" );
assertEquals( "12", config.getAttribute("integer") );
config.setAttribute( "integer", null );
try
{
config.getAttribute("integer");
fail( "attribute 'integer' was present despite it being set to null" );
}
catch( ConfigurationException e )
{
// OK, this is what we expect - the attribute wasn't found.
}
}
public void testMutable() throws Exception
{
MutableConfiguration root = new DefaultConfiguration( "root", "-" );
root.setAttribute( "root1", "root1" );
root.setAttribute( "root2", "root2" );
root.getMutableChild( "child1" ).setAttribute( "child1-attr1", "child1-attr1" );
root.getMutableChild( "child1" ).setAttribute( "child1-attr2", "child1-attr2" );
root.getMutableChild( "child2" ).setAttribute( "child2-attr1", "child2-attr1" );
root.getMutableChild( "child2" ).setAttribute( "child2-attr2", "child2-attr2" );
assertEquals( "root1", root.getAttribute( "root1" ) );
assertEquals( "root2", root.getAttribute( "root2" ) );
assertEquals( "child1-attr1", root.getChild( "child1" ).getAttribute( "child1-attr1" ) );
assertEquals( "child1-attr2", root.getChild( "child1" ).getAttribute( "child1-attr2" ) );
assertEquals( "child2-attr1", root.getChild( "child2" ).getAttribute( "child2-attr1" ) );
assertEquals( "child2-attr2", root.getChild( "child2" ).getAttribute( "child2-attr2" ) );
assertEquals( null, root.getMutableChild( "child3", false ) );
assertEquals( 2, root.getChildren().length );
assertEquals( 2, root.getMutableChildren().length );
assertEquals( 1, root.getMutableChildren( "child1" ).length );
assertEquals( 1, root.getMutableChildren( "child2" ).length );
assertTrue( root.getMutableChildren( "child1" )[0] == root.getChild( "child1" ) );
// Add an immutable child.
DefaultConfiguration immutableChild = new DefaultConfiguration( "immutable-child", "-" );
immutableChild.makeReadOnly();
try
{
immutableChild.setAttribute( "attr", "attr" );
fail( "Read-only DefaultConfiguration wasn't read-only!" );
}
catch (IllegalStateException ise)
{
// expected
}
root.addChild( immutableChild );
// OK, ask to have it back.
root.getMutableChild( "immutable-child" ).setAttribute( "attr", "attr" );
assertEquals( 1, root.getChildren( "immutable-child" ).length );
assertEquals( "attr", root.getChild( "immutable-child" ).getAttribute( "attr" ) );
}
}
././@LongLink 100644 0 0 163 10051530443 10246 L ustar 0 0 avalon-framework/impl/src/test/org/apache/avalon/framework/configuration/test/SAXConfigurationHandlerTestCase.java avalon-framework/impl/src/test/org/apache/avalon/framework/configuration/test/SAXConfigurationHandle100644 0 0 13544 10051530441 31544 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.configuration.test;
import junit.framework.TestCase;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.NamespacedSAXConfigurationHandler;
import org.apache.avalon.framework.configuration.SAXConfigurationHandler;
import org.xml.sax.helpers.AttributesImpl;
/**
* Test the basic public methods of SAXConfigurationHandlerTestCase.
*
* @author Avalon Development Team
*/
public final class SAXConfigurationHandlerTestCase extends TestCase
{
public SAXConfigurationHandlerTestCase()
{
this("SAXConfigurationHandler Test Case ");
}
public SAXConfigurationHandlerTestCase( final String name )
{
super( name );
}
/**
* Test the ContentHandler. The XML created should look like this:
*
*
* <rawName attqName="attValue">
* <child:localName xmlns:child="namespaceURI">value</child:localName>
* <emptyElement/>
* </rawName>
*
*/
public void testDefaultHandling() throws Exception
{
SAXConfigurationHandler handler = new SAXConfigurationHandler( );
final String rootURI = "";
final String rootlocal = "rawName";
final String rootraw = "rawName";
final String childURI = "namespaceURI";
final String childlocal = "localName";
final String childraw = "child:" + childlocal;
final String childvalue = "value";
final String attqName = "attqName";
final String attValue = "attValue";
final String emptylocal = "emptyElement";
final String emptyraw = emptylocal;
final AttributesImpl emptyAttributes = new AttributesImpl();
final AttributesImpl attributes = new AttributesImpl();
attributes.addAttribute("",attqName,attqName,
"CDATA",attValue);
final AttributesImpl childAttributes = new AttributesImpl();
childAttributes.addAttribute("", "child", "xmlns:child", "CDATA", childURI);
handler.startDocument();
handler.startPrefixMapping( "child", childURI );
handler.startElement( rootURI, rootlocal, rootraw, attributes );
handler.startElement( childURI,
childlocal,
childraw,
childAttributes );
handler.characters( childvalue.toCharArray(), 0, childvalue.length() );
handler.endElement( childURI, childlocal, childraw );
handler.startElement( rootURI, emptylocal, emptyraw, emptyAttributes );
handler.endElement( rootURI, emptylocal, emptyraw );
handler.endElement( null, null, rootraw);
handler.endPrefixMapping( "child" );
handler.endDocument();
final Configuration configuration = handler.getConfiguration();
assertEquals( attValue, configuration.getAttribute(attqName));
assertEquals( childvalue, configuration.getChild(childraw).getValue());
assertEquals( "", configuration.getChild(childraw).getNamespace() );
assertEquals( rootraw, configuration.getName());
assertEquals( "test", configuration.getChild(emptyraw).getValue( "test" ) );
}
public void testNamespaceHandling() throws Exception
{
SAXConfigurationHandler handler = new NamespacedSAXConfigurationHandler( );
final String rootURI = "";
final String rootlocal = "rawName";
final String rootraw = "rawName";
final String childURI = "namespaceURI";
final String childlocal = "localName";
final String childraw = "child:" + childlocal;
final String childvalue = "value";
final String attqName = "attqName";
final String attValue = "attValue";
final AttributesImpl attributes = new AttributesImpl();
attributes.addAttribute("",attqName,attqName,
"CDATA",attValue);
final AttributesImpl childAttributes = new AttributesImpl();
childAttributes.addAttribute("", "child", "xmlns:child", "CDATA", childURI);
handler.startDocument();
handler.startPrefixMapping( "child", childURI );
handler.startElement( rootURI, rootlocal, rootraw, attributes );
handler.startElement( childURI,
childlocal,
childraw,
childAttributes );
handler.characters( childvalue.toCharArray(), 0, childvalue.length() );
handler.endElement( childURI, childlocal, childraw );
handler.endElement( null, null, rootraw);
handler.endPrefixMapping( "child" );
handler.endDocument();
final Configuration configuration = handler.getConfiguration();
assertEquals( attValue, configuration.getAttribute(attqName));
assertEquals( childvalue, configuration.getChild(childlocal).getValue());
assertEquals( childURI, configuration.getChild(childlocal).getNamespace() );
assertEquals( rootraw, configuration.getName());
}
}
avalon-framework/impl/src/test/org/apache/avalon/framework/context/test/ContextTestCase.java 100644 0 0 13756 10051530441 30067 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.context.test;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.DefaultContext;
import org.apache.avalon.framework.context.Resolvable;
/**
* TestCase for Context.
*
* @author Avalon Development Team
*/
public class ContextTestCase
extends TestCase
{
private static class ResolvableString implements Resolvable
{
private final String m_content;
public ResolvableString( final String content )
{
this.m_content = content;
}
public ResolvableString()
{
this( "This is a ${test}." );
}
public final Object resolve( final Context context )
throws ContextException
{
int index = this.m_content.indexOf( "${" );
if ( index < 0 )
{
return this.m_content;
}
StringBuffer buf = new StringBuffer( this.m_content.substring( 0, index ) );
while ( index >= 0 && index <= this.m_content.length() )
{
index += 2;
int end = this.m_content.indexOf( "}", index);
if ( end < 0 )
{
end = this.m_content.length();
}
buf.append( context.get( this.m_content.substring( index, end ) ) );
end++;
index = this.m_content.indexOf( "${", end ) + 2;
if ( index < 2 )
{
index = -1;
buf.append( this.m_content.substring( end, this.m_content.length() ) );
}
if ( index >=0 && index <= this.m_content.length() )
{
buf.append( this.m_content.substring( end, index ) );
}
}
return buf.toString();
}
}
public ContextTestCase( final String name )
{
super( name );
}
public void testAddContext()
throws Exception
{
final DefaultContext context = new DefaultContext();
context.put( "key1", "value1" );
assertTrue( "value1".equals( context.get( "key1" ) ) );
context.put( "key1", "" );
assertTrue( "".equals( context.get( "key1" ) ) );
context.put( "key1", "value1" );
context.makeReadOnly();
try
{
context.put( "key1", "" );
throw new AssertionFailedError( "You are not allowed to change a value after it has been made read only" );
}
catch ( IllegalStateException ise )
{
assertTrue( "Value is null", "value1".equals( context.get( "key1" ) ) );
}
}
public void testResolveableObject()
throws ContextException
{
final DefaultContext context = new DefaultContext();
context.put( "key1", new ResolvableString() );
context.put( "test", "Cool Test" );
context.makeReadOnly();
final Context newContext = (Context) context;
assertTrue( "Cool Test".equals( newContext.get( "test" ) ) );
assertTrue( ! "This is a ${test}.".equals( newContext.get( "key1" ) ) );
assertTrue( "This is a Cool Test.".equals( newContext.get( "key1" ) ) );
}
public void testCascadingContext()
throws ContextException
{
final DefaultContext parent = new DefaultContext();
parent.put( "test", "ok test" );
parent.makeReadOnly();
final DefaultContext child = new DefaultContext( parent );
child.put( "check", new ResolvableString("This is an ${test}.") );
child.makeReadOnly();
final Context context = (Context) child;
assertTrue ( "ok test".equals( context.get( "test" ) ) );
assertTrue ( ! "This is an ${test}.".equals( context.get( "check" ) ) );
assertTrue ( "This is an ok test.".equals( context.get( "check" ) ) );
}
public void testHiddenItems()
throws ContextException
{
final DefaultContext parent = new DefaultContext();
parent.put( "test", "test" );
parent.makeReadOnly();
final DefaultContext child = new DefaultContext( parent );
child.put( "check", "check" );
final Context context = (Context) child;
assertTrue ( "check".equals( context.get( "check" ) ) );
assertTrue ( "test".equals( context.get( "test" ) ) );
child.hide( "test" );
try
{
context.get( "test" );
fail( "The item \"test\" was hidden in the child context, but could still be retrieved via get()." );
}
catch (ContextException ce)
{
// Supposed to be thrown.
}
child.makeReadOnly();
try
{
child.hide( "test" );
fail( "hide() did not throw an exception, even though the context is supposed to be read-only." );
}
catch (IllegalStateException ise)
{
// Supposed to be thrown.
}
}
}
avalon-framework/impl/src/test/org/apache/avalon/framework/parameters/test/ParameterTestCase.java 100644 0 0 12150 10051530441 31025 0 ustar 0 0 /*
* Copyright 1997-2004 The Apache Software Foundation
*
* Licensed 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.
*/
package org.apache.avalon.framework.parameters.test;
import java.io.ByteArrayInputStream;
import java.util.Properties;
import junit.framework.TestCase;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.avalon.framework.parameters.ParameterException;
import org.apache.avalon.framework.parameters.Parameters;
/**
* TestCase for Parameter.
*
* @author Avalon Development Team
*/
public class ParameterTestCase
extends TestCase
{
private static final String EOL = "\n";
public ParameterTestCase( final String name )
{
super( name );
}
public void testRemoveParameter()
{
final Parameters parameters = new Parameters();
parameters.setParameter( "key1", "value1" );
assertEquals("Should only have one parameter", 1, parameters.getNames().length );
parameters.setParameter( "key1", null );
assertTrue( "key1 should no longer be a parameter", ! parameters.isParameter( "key1" ) );
assertEquals( 0, parameters.getNames().length );
}
public void testIsParameter()
{
final Parameters parameters = new Parameters();
parameters.setParameter( "key1", "value1" );
assertTrue( "key1 should be a parameter", parameters.isParameter( "key1" ) );
assertTrue( "key2 should not be a parameter", ! parameters.isParameter( "key2" ) );
}
public void testGetParameter()
{
final Parameters parameters = new Parameters();
parameters.setParameter( "key1", "value1" );
try
{
assertEquals( "key1 should equal value1", "value1", parameters.getParameter( "key1" ) );
}
catch ( final ParameterException pe )
{
fail( pe.getMessage() );
}
try
{
parameters.getParameter( "key2" );
fail( "Not inserted parameter 'key2' exists" );
}
catch( final ParameterException pe )
{
//OK
}
assertEquals( "key1 should use correct value1", "value1", parameters.getParameter( "key1", "value1-1" ) );
assertEquals( "key2 should use default value2", "value2", parameters.getParameter( "key2", "value2" ) );
}
public void testFromConfiguration()
{
final ByteArrayInputStream confInput = new ByteArrayInputStream( (
"" + EOL +
"