From 346da1bc40ecb85537435b943ef56541f06eb284 Mon Sep 17 00:00:00 2001 From: Sylwester Lachiewicz Date: Mon, 22 May 2023 22:57:01 +0200 Subject: [PATCH] Reformat code --- plexus-component-annotations/pom.xml | 7 +- .../component/annotations/Component.java | 8 +- .../component/annotations/Configuration.java | 8 +- .../component/annotations/Requirement.java | 13 +- plexus-component-metadata/pom.xml | 9 +- .../maven/plugin/AbstractDescriptorMojo.java | 22 +- .../maven/plugin/PlexusDescriptorMojo.java | 42 +- .../plexus/maven/plugin/PlexusMergeMojo.java | 41 +- .../plugin/PlexusTestDescriptorMojo.java | 42 +- .../ClassComponentDescriptorExtractor.java | 124 +- .../ComponentDescriptorExtractor.java | 15 +- .../ComponentDescriptorExtractorSupport.java | 34 +- .../ComponentDescriptorWriteException.java | 21 +- .../metadata/ComponentDescriptorWriter.java | 7 +- .../DefaultComponentDescriptorWriter.java | 212 +- .../metadata/DefaultMetadataGenerator.java | 144 +- .../metadata/MetadataGenerationRequest.java | 19 +- .../plexus/metadata/MetadataGenerator.java | 7 +- .../SourceComponentDescriptorExtractor.java | 56 +- .../org/codehaus/plexus/metadata/ann/Ann.java | 59 +- .../plexus/metadata/ann/AnnClass.java | 206 +- .../codehaus/plexus/metadata/ann/AnnEnum.java | 89 +- .../plexus/metadata/ann/AnnField.java | 78 +- .../metadata/ann/AnnInvocationHandler.java | 87 +- .../plexus/metadata/ann/AnnMethod.java | 108 +- .../plexus/metadata/ann/AnnReader.java | 193 +- .../gleaner/AnnotationComponentGleaner.java | 119 +- .../gleaner/ClassComponentGleaner.java | 9 +- .../gleaner/ComponentGleanerException.java | 21 +- .../gleaner/ComponentGleanerSupport.java | 5 +- .../gleaner/QDoxComponentGleaner.java | 157 +- .../gleaner/SourceComponentGleaner.java | 11 +- .../plexus/metadata/merge/AbstractMerger.java | 87 +- .../metadata/merge/ComponentsXmlMerger.java | 19 +- .../plexus/metadata/merge/Driver.java | 353 ++- .../plexus/metadata/merge/MXParser.java | 2415 ++++++++--------- .../plexus/metadata/merge/MergeException.java | 14 +- .../plexus/metadata/merge/MergeStrategy.java | 6 +- .../plexus/metadata/merge/Merger.java | 18 +- .../metadata/merge/PlexusXmlMerger.java | 20 +- .../support/AbstractMergeableElement.java | 88 +- .../support/AbstractMergeableElementList.java | 75 +- .../support/AbstractMergeableSupport.java | 356 +-- .../merge/support/ComponentElement.java | 42 +- .../merge/support/ComponentSetElement.java | 17 +- .../merge/support/ComponentsElement.java | 38 +- .../merge/support/ConfigurationElement.java | 15 +- .../metadata/merge/support/DescriptorTag.java | 82 +- .../merge/support/MergeStrategies.java | 26 +- .../metadata/merge/support/Mergeable.java | 9 +- .../merge/support/PlexusRootElement.java | 17 +- .../metadata/merge/support/PlexusXmlTag.java | 41 +- .../merge/support/RequirementElement.java | 28 +- .../merge/support/RequirementsElement.java | 29 +- .../DefaultComponentDescriptorWriterTest.java | 155 +- .../metadata/gleaner/AbstractClass.java | 4 +- .../gleaner/AbstractWithAnnoClass.java | 4 +- .../AnnotationComponentGleanerTest.java | 58 +- .../metadata/gleaner/ChildComponent.java | 4 +- .../plexus/metadata/gleaner/MyComponent.java | 3 +- .../metadata/gleaner/NoAnnotationsClass.java | 4 +- .../metadata/gleaner/NoAnnotationsIntf.java | 4 +- .../gleaner/QDoxComponentGleanerTest.java | 134 +- .../gleaner/ann/AnnotatedComponent.java | 17 +- .../ann/AnnotatedComponentDependency.java | 4 +- .../gleaner/ann/AnnotatedComponentRole.java | 4 +- .../merge/ComponentsXmlMergerTest.java | 399 ++- plexus-container-default/pom.xml | 11 +- .../org/codehaus/plexus/ClassRealmUtil.java | 45 +- .../codehaus/plexus/ComponentRegistry.java | 37 +- .../plexus/ContainerConfiguration.java | 42 +- .../plexus/DefaultComponentRegistry.java | 564 ++-- .../plexus/DefaultContainerConfiguration.java | 229 +- .../plexus/DefaultPlexusContainer.java | 770 ++---- .../DuplicateChildContainerException.java | 21 +- .../plexus/MutablePlexusContainer.java | 22 +- .../org/codehaus/plexus/PlexusConstants.java | 3 +- .../org/codehaus/plexus/PlexusContainer.java | 111 +- .../plexus/PlexusContainerException.java | 13 +- .../codehaus/plexus/PlexusJUnit4TestCase.java | 233 +- .../org/codehaus/plexus/PlexusTestCase.java | 196 +- .../codehaus/plexus/component/CastUtils.java | 8 +- .../component/MapOrientedComponent.java | 15 +- .../AbstractComponentBuildListener.java | 11 +- .../builder/ComponentBuildListener.java | 6 +- .../component/builder/ComponentBuilder.java | 3 +- .../builder/XBeanComponentBuilder.java | 235 +- .../AbstractComponentCollection.java | 110 +- .../component/collections/ComponentList.java | 207 +- .../component/collections/ComponentMap.java | 177 +- .../composition/CompositionResolver.java | 18 +- ...ycleDetectedInComponentGraphException.java | 18 +- .../DefaultCompositionResolver.java | 57 +- .../UndefinedComponentComposerException.java | 19 +- .../AbstractComponentConfigurator.java | 109 +- .../BasicComponentConfigurator.java | 24 +- .../ComponentConfigurationException.java | 48 +- .../configurator/ComponentConfigurator.java | 27 +- .../configurator/ConfigurationListener.java | 8 +- .../MapOrientedComponentConfigurator.java | 35 +- .../AbstractConfigurationConverter.java | 185 +- .../converters/ComponentValueSetter.java | 215 +- .../converters/ConfigurationConverter.java | 30 +- .../basic/AbstractBasicConverter.java | 114 +- .../converters/basic/BooleanConverter.java | 14 +- .../converters/basic/ByteConverter.java | 12 +- .../converters/basic/CharConverter.java | 12 +- .../converters/basic/ClassConverter.java | 24 +- .../converters/basic/Converter.java | 9 +- .../converters/basic/DateConverter.java | 20 +- .../converters/basic/DoubleConverter.java | 14 +- .../converters/basic/EnumConverter.java | 49 +- .../converters/basic/FileConverter.java | 47 +- .../converters/basic/FloatConverter.java | 14 +- .../converters/basic/IntConverter.java | 26 +- .../converters/basic/LongConverter.java | 14 +- .../converters/basic/ShortConverter.java | 14 +- .../basic/StringBufferConverter.java | 13 +- .../converters/basic/StringConverter.java | 12 +- .../converters/basic/UriConverter.java | 9 +- .../converters/basic/UrlConverter.java | 28 +- .../converters/composite/ArrayConverter.java | 129 +- .../composite/CollectionConverter.java | 171 +- .../converters/composite/MapConverter.java | 48 +- .../composite/ObjectWithFieldsConverter.java | 128 +- .../PlexusConfigurationConverter.java | 24 +- .../composite/PropertiesConverter.java | 73 +- .../converters/lookup/ConverterLookup.java | 8 +- .../lookup/DefaultConverterLookup.java | 116 +- .../special/ClassRealmConverter.java | 63 +- .../DefaultExpressionEvaluator.java | 10 +- .../ExpressionEvaluationException.java | 14 +- .../expression/ExpressionEvaluator.java | 12 +- .../TypeAwareExpressionEvaluator.java | 12 +- ...tractResourceBasedComponentDiscoverer.java | 61 +- .../AnnotationBasedComponentDiscoverer.java | 7 +- .../discovery/ComponentDiscoverer.java | 13 +- .../discovery/ComponentDiscovererManager.java | 11 +- .../discovery/ComponentDiscoveryEvent.java | 15 +- .../discovery/ComponentDiscoveryListener.java | 5 +- .../discovery/DefaultComponentDiscoverer.java | 68 +- .../DefaultComponentDiscovererManager.java | 46 +- .../DiscoveryListenerDescriptor.java | 9 +- .../PlexusXmlComponentDiscoverer.java | 54 +- .../ResourceBasedComponentDiscoverer.java | 6 +- .../factory/AbstractComponentFactory.java | 23 +- .../component/factory/ComponentFactory.java | 7 +- .../factory/ComponentFactoryManager.java | 6 +- .../ComponentInstantiationException.java | 21 +- .../DefaultComponentFactoryManager.java | 28 +- .../UndefinedComponentFactoryException.java | 21 +- .../factory/java/JavaComponentFactory.java | 80 +- .../manager/AbstractComponentManager.java | 177 +- .../component/manager/ComponentManager.java | 23 +- .../manager/ComponentManagerFactory.java | 14 +- .../manager/PerLookupComponentManager.java | 38 +- .../PerLookupComponentManagerFactory.java | 20 +- .../manager/SingletonComponentManager.java | 53 +- .../SingletonComponentManagerFactory.java | 20 +- .../UndefinedComponentManagerException.java | 9 +- .../repository/ComponentDependency.java | 46 +- .../repository/ComponentDescriptor.java | 271 +- .../repository/ComponentRepository.java | 23 +- .../repository/ComponentRequirement.java | 75 +- .../repository/ComponentRequirementList.java | 20 +- .../repository/ComponentSetDescriptor.java | 59 +- .../DefaultComponentRepository.java | 175 +- .../ComponentConfigurationException.java | 14 +- ...onentDescriptorUnmarshallingException.java | 14 +- ...ponentImplementationNotFoundException.java | 14 +- .../ComponentLifecycleException.java | 14 +- .../exception/ComponentLookupException.java | 63 +- .../ComponentLookupRuntimeException.java | 12 +- ...anagerImplementationNotFoundException.java | 14 +- .../exception/ComponentProfileException.java | 14 +- .../ComponentRepositoryException.java | 14 +- .../component/repository/io/PlexusTools.java | 192 +- .../DefaultPlexusConfiguration.java | 155 +- .../PlexusComponentDescriptorMerger.java | 95 +- .../configuration/PlexusConfiguration.java | 37 +- .../PlexusConfigurationException.java | 14 +- .../PlexusConfigurationMerger.java | 235 +- .../PlexusConfigurationResourceException.java | 9 +- .../io/PlexusConfigurationReader.java | 11 +- .../io/PlexusConfigurationWriter.java | 9 +- .../io/XmlPlexusConfigurationReader.java | 31 +- .../io/XmlPlexusConfigurationWriter.java | 137 +- .../source/ChainedConfigurationSource.java | 15 +- .../source/ConfigurationSource.java | 7 +- .../source/ContainerConfigurationSource.java | 12 +- .../xml/XmlPlexusConfiguration.java | 41 +- .../AbstractContainerInitializationPhase.java | 5 +- ...tractCoreComponentInitializationPhase.java | 14 +- .../ContainerInitializationContext.java | 30 +- .../ContainerInitializationException.java | 20 +- .../ContainerInitializationPhase.java | 6 +- ...ializeComponentDiscovererManagerPhase.java | 40 +- ...nitializeComponentFactoryManagerPhase.java | 33 +- .../InitializeComponentRegistryPhase.java | 78 +- ...lizeContainerConfigurationSourcePhase.java | 14 +- .../InitializeLoggerManagerPhase.java | 46 +- .../InitializeSystemPropertiesPhase.java | 13 +- ...nitializeUserConfigurationSourcePhase.java | 64 +- .../org/codehaus/plexus/context/Context.java | 14 +- .../plexus/context/ContextException.java | 15 +- .../plexus/context/ContextMapAdapter.java | 29 +- .../plexus/context/DefaultContext.java | 96 +- .../lifecycle/AbstractLifecycleHandler.java | 65 +- .../lifecycle/BasicLifecycleHandler.java | 14 +- .../DefaultLifecycleHandlerManager.java | 34 +- .../plexus/lifecycle/LifecycleHandler.java | 20 +- .../lifecycle/LifecycleHandlerManager.java | 11 +- .../UndefinedLifecycleHandlerException.java | 9 +- .../plexus/lifecycle/phase/AbstractPhase.java | 14 +- .../plexus/lifecycle/phase/Phase.java | 8 +- .../plexus/logging/AbstractLogEnabled.java | 35 +- .../plexus/logging/AbstractLogger.java | 82 +- .../plexus/logging/AbstractLoggerManager.java | 46 +- .../plexus/logging/BaseLoggerManager.java | 106 +- .../codehaus/plexus/logging/LogEnabled.java | 5 +- .../org/codehaus/plexus/logging/Logger.java | 27 +- .../plexus/logging/LoggerManager.java | 25 +- .../plexus/logging/console/ConsoleLogger.java | 87 +- .../logging/console/ConsoleLoggerManager.java | 172 +- .../lifecycle/phase/AutoConfigurePhase.java | 41 +- .../plexus/lifecycle/phase/Configurable.java | 7 +- .../lifecycle/phase/ConfigurablePhase.java | 24 +- .../lifecycle/phase/Contextualizable.java | 6 +- .../lifecycle/phase/ContextualizePhase.java | 31 +- .../plexus/lifecycle/phase/Disposable.java | 3 +- .../plexus/lifecycle/phase/DisposePhase.java | 12 +- .../plexus/lifecycle/phase/Initializable.java | 6 +- .../phase/InitializationException.java | 13 +- .../lifecycle/phase/InitializePhase.java | 23 +- .../lifecycle/phase/LogDisablePhase.java | 14 +- .../lifecycle/phase/LogEnablePhase.java | 17 +- .../phase/PhaseExecutionException.java | 8 +- .../phase/PlexusContainerLocator.java | 67 +- .../plexus/lifecycle/phase/ResumePhase.java | 12 +- .../lifecycle/phase/ServiceLocator.java | 42 +- .../plexus/lifecycle/phase/Serviceable.java | 7 +- .../lifecycle/phase/ServiceablePhase.java | 12 +- .../plexus/lifecycle/phase/StartPhase.java | 23 +- .../plexus/lifecycle/phase/Startable.java | 9 +- .../lifecycle/phase/StartingException.java | 14 +- .../plexus/lifecycle/phase/StopPhase.java | 23 +- .../lifecycle/phase/StoppingException.java | 14 +- .../plexus/lifecycle/phase/SuspendPhase.java | 12 +- .../plexus/lifecycle/phase/Suspendable.java | 3 +- .../DefaultComponentLookupManagerTest.java | 32 +- .../plexus/DyanamicComponentKungFuTest.java | 19 +- .../plexus/PlexusJUnit4TestCaseTest.java | 23 +- .../codehaus/plexus/PlexusTestCaseTest.java | 81 +- .../MapOrientedComponentProcessingTest.java | 48 +- .../plexus/component/PlexusTestCaseTest.java | 26 +- .../component/TestMapOrientedComponent.java | 26 +- .../composition/AbstractComponent.java | 9 +- .../AbstractCompositionResolverTest.java | 215 +- .../component/composition/Component.java | 6 +- .../component/composition/ComponentA.java | 3 +- .../component/composition/ComponentB.java | 6 +- .../component/composition/ComponentC.java | 4 +- .../component/composition/ComponentD.java | 4 +- .../component/composition/ComponentE.java | 4 +- .../component/composition/ComponentF.java | 33 +- .../ComponentRealmCompositionTest.java | 134 +- ...mponentWithSeveralFieldsOfTheSameType.java | 9 +- .../composition/DefaultComponent.java | 7 +- .../composition/DefaultComponentA.java | 8 +- .../composition/DefaultComponentB.java | 12 +- .../composition/DefaultComponentC.java | 4 +- .../DefaultComponentComposerManagerTest.java | 19 +- .../DefaultCompositionResolverTest.java | 7 +- .../configurator/AbstractComponent.java | 9 +- .../AbstractComponentConfiguratorTest.java | 712 +++-- .../component/configurator/AbstractThing.java | 5 +- .../BasicComponentConfiguratorTest.java | 11 +- .../component/configurator/Component.java | 6 +- .../ComponentWithArrayFields.java | 24 +- .../ComponentWithCollectionFields.java | 21 +- .../ComponentWithCompositeFields.java | 13 +- .../configurator/ComponentWithEnumFields.java | 19 +- .../configurator/ComponentWithMapField.java | 9 +- .../ComponentWithPropertiesField.java | 9 +- .../configurator/ComponentWithSetters.java | 52 +- .../configurator/ConfigurableComponent.java | 51 +- .../configurator/DefaultComponent.java | 9 +- .../configurator/ImportantThing.java | 9 +- .../configurator/ThingInterface.java | 4 +- .../XBeanComponentConfiguratorTest.java | 49 +- .../discovery/ComponentDiscovererTest.java | 48 +- .../discovery/DefaultDiscoveredComponent.java | 7 +- .../discovery/DiscoveredComponent.java | 5 +- .../plexus/component/factory/Component.java | 8 +- .../component/factory/ComponentImplA.java | 4 +- .../component/factory/ComponentImplB.java | 8 +- .../component/factory/ComponentImplC.java | 8 +- .../DiscoveredComponentFactoryTest.java | 51 +- .../factory/TestComponentFactory1.java | 13 +- .../factory/TestComponentFactory2.java | 13 +- .../factory/TestFactoryResultComponent.java | 10 +- .../java/JavaComponentFactoryTest.java | 65 +- .../nonjava/NonJavaComponentFactory.java | 18 +- .../nonjava/NonJavaComponentFactoryTest.java | 12 +- .../ClassicSingletonComponentManagerTest.java | 22 +- .../plexus/component/manager/Component.java | 3 +- .../component/manager/DefaultComponent.java | 5 +- .../component/manager/SlowComponent.java | 20 +- ...tClassicSingletonComponentManagerTest.java | 91 +- .../DefaultComponentRegistryTest.java | 46 +- .../registry/TestSynchronizedComponent.java | 26 +- .../repository/ComponentDescriptorTest.java | 90 +- .../repository/ComponentRequirementTest.java | 15 +- .../repository/ComponentSetTest.java | 115 +- .../DefaultComponentRepositoryTest.java | 12 +- .../ConfigurationResourceExceptionTest.java | 11 +- .../ConfigurationTestHelper.java | 61 +- .../DefaultPlexusConfigurationTest.java | 114 +- .../io/XmlPlexusConfigurationReaderTest.java | 16 +- .../io/XmlPlexusConfigurationWriterTest.java | 20 +- .../source/ADummyConfigurationSource.java | 8 +- .../AnotherDummyConfigurationSource.java | 9 +- .../DefaultConfigurationSourceTest.java | 15 +- .../ExtendingConfigurationSourceTest.java | 23 +- .../OverridingConfigurationSourceTest.java | 17 +- .../xml/XmlPlexusConfigurationTest.java | 77 +- .../plexus/context/ContextMapAdapterTest.java | 45 +- .../plexus/context/DefaultContextTest.java | 109 +- .../logging/AbstractLoggerManagerTest.java | 229 +- .../logging/CustomLoggerManagerTest.java | 16 +- .../plexus/logging/LogEnabledTest.java | 73 +- .../plexus/logging/MockLogEnabled.java | 5 +- .../codehaus/plexus/logging/MockLogger.java | 77 +- .../plexus/logging/MockLoggerManager.java | 46 +- .../console/ConsoleLoggerManagerTest.java | 22 +- .../logging/console/ConsoleLoggerTest.java | 99 +- .../test/AbstractStartableComponent.java | 50 +- .../java/org/codehaus/plexus/test/Action.java | 6 +- .../codehaus/plexus/test/AddUserAction.java | 7 +- .../plexus/test/CircularComponent.java | 5 +- .../org/codehaus/plexus/test/Component.java | 5 +- .../org/codehaus/plexus/test/ComponentA.java | 3 +- .../org/codehaus/plexus/test/ComponentB.java | 3 +- .../org/codehaus/plexus/test/ComponentC.java | 3 +- .../org/codehaus/plexus/test/ComponentD.java | 3 +- .../plexus/test/ComponentManager.java | 4 +- .../plexus/test/ComponentWithRoleDefault.java | 6 +- .../codehaus/plexus/test/ConcreteThing.java | 6 +- .../plexus/test/CountInstancesComponent.java | 14 +- .../plexus/test/DefaultCircularComponent.java | 24 +- .../plexus/test/DefaultComponent.java | 13 +- .../plexus/test/DefaultComponentA.java | 16 +- .../plexus/test/DefaultComponentB.java | 5 +- .../plexus/test/DefaultComponentC.java | 7 +- .../plexus/test/DefaultComponentD.java | 7 +- .../plexus/test/DefaultComponentManager.java | 11 +- ...faultComponentWithOptionalRequirement.java | 5 +- .../test/DefaultLoadOnStartService.java | 11 +- ...DefaultLoadOnStartServiceWithRoleHint.java | 6 +- .../codehaus/plexus/test/DefaultServiceB.java | 22 +- .../codehaus/plexus/test/DefaultServiceC.java | 10 +- .../codehaus/plexus/test/DefaultServiceD.java | 6 +- .../codehaus/plexus/test/DefaultServiceE.java | 22 +- .../codehaus/plexus/test/DefaultServiceH.java | 17 +- .../test/DefaultStartableComponentA.java | 5 +- .../test/DefaultStartableComponentB.java | 5 +- .../test/DefaultStartableComponentC.java | 5 +- .../test/DefaultStartableComponentD.java | 5 +- .../test/DefaultStartableComponentE.java | 5 +- .../plexus/test/DefaultThingUser.java | 5 +- .../codehaus/plexus/test/LiveComponent.java | 6 +- .../plexus/test/LoadOnStartService.java | 3 +- .../test/LoadOnStartServiceWithRoleHint.java | 3 +- .../plexus/test/PlexusContainerTest.java | 762 +++--- .../org/codehaus/plexus/test/ServiceB.java | 3 +- .../org/codehaus/plexus/test/ServiceC.java | 3 +- .../org/codehaus/plexus/test/ServiceD.java | 3 +- .../org/codehaus/plexus/test/ServiceE.java | 3 +- .../org/codehaus/plexus/test/ServiceH.java | 3 +- .../plexus/test/SimpleLifecycleHandler.java | 11 +- .../plexus/test/StartableComponent.java | 7 +- .../java/org/codehaus/plexus/test/Thing.java | 5 +- .../org/codehaus/plexus/test/ThingUser.java | 5 +- .../plexus/test/lifecycle/phase/Eeny.java | 3 +- .../test/lifecycle/phase/EenyPhase.java | 12 +- .../plexus/test/lifecycle/phase/Meeny.java | 3 +- .../test/lifecycle/phase/MeenyPhase.java | 12 +- .../plexus/test/lifecycle/phase/Miny.java | 3 +- .../test/lifecycle/phase/MinyPhase.java | 12 +- .../plexus/test/lifecycle/phase/Mo.java | 3 +- .../plexus/test/lifecycle/phase/MoPhase.java | 12 +- .../plexus/test/list/AbstractValve.java | 12 +- .../plexus/test/list/DefaultPipeline.java | 15 +- .../codehaus/plexus/test/list/Pipeline.java | 3 +- .../org/codehaus/plexus/test/list/Valve.java | 5 +- .../codehaus/plexus/test/list/ValveFour.java | 5 +- .../codehaus/plexus/test/list/ValveOne.java | 7 +- .../codehaus/plexus/test/list/ValveThree.java | 5 +- .../codehaus/plexus/test/list/ValveTwo.java | 7 +- .../plexus/test/map/AbstractActivity.java | 12 +- .../codehaus/plexus/test/map/Activity.java | 5 +- .../plexus/test/map/ActivityManager.java | 11 +- .../codehaus/plexus/test/map/ActivityOne.java | 7 +- .../codehaus/plexus/test/map/ActivityTwo.java | 7 +- .../test/map/DefaultActivityManager.java | 23 +- .../plexus/test/map/NoComponentsMapTest.java | 14 +- pom.xml | 6 +- 407 files changed, 8721 insertions(+), 12259 deletions(-) diff --git a/plexus-component-annotations/pom.xml b/plexus-component-annotations/pom.xml index 9ecdafa9e..de33969f4 100644 --- a/plexus-component-annotations/pom.xml +++ b/plexus-component-annotations/pom.xml @@ -1,5 +1,4 @@ - 4.0.0 @@ -12,8 +11,6 @@ plexus-component-annotations Plexus :: Component Annotations (deprecated) - - Plexus Component "Java 5" Annotations, to describe plexus components properties in java sources with - standard annotations instead of javadoc annotations. - + Plexus Component "Java 5" Annotations, to describe plexus components properties in java sources with + standard annotations instead of javadoc annotations. diff --git a/plexus-component-annotations/src/main/java/org/codehaus/plexus/component/annotations/Component.java b/plexus-component-annotations/src/main/java/org/codehaus/plexus/component/annotations/Component.java index 61d56f4c9..bebae06b1 100644 --- a/plexus-component-annotations/src/main/java/org/codehaus/plexus/component/annotations/Component.java +++ b/plexus-component-annotations/src/main/java/org/codehaus/plexus/component/annotations/Component.java @@ -17,12 +17,13 @@ package org.codehaus.plexus.component.annotations; import java.lang.annotation.Documented; -import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; -import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + /** * Marks a class as a Plexus component. * @@ -34,8 +35,7 @@ @Target(TYPE) @Inherited @Deprecated -public @interface Component -{ +public @interface Component { Class role(); String hint() default ""; diff --git a/plexus-component-annotations/src/main/java/org/codehaus/plexus/component/annotations/Configuration.java b/plexus-component-annotations/src/main/java/org/codehaus/plexus/component/annotations/Configuration.java index 19e196d99..d1bb9b55c 100644 --- a/plexus-component-annotations/src/main/java/org/codehaus/plexus/component/annotations/Configuration.java +++ b/plexus-component-annotations/src/main/java/org/codehaus/plexus/component/annotations/Configuration.java @@ -17,12 +17,13 @@ package org.codehaus.plexus.component.annotations; import java.lang.annotation.Documented; -import static java.lang.annotation.ElementType.FIELD; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; -import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + /** * Marks a field as a configuration element with a default value. * @@ -34,8 +35,7 @@ @Target(FIELD) @Inherited @Deprecated -public @interface Configuration -{ +public @interface Configuration { String name() default ""; String value(); diff --git a/plexus-component-annotations/src/main/java/org/codehaus/plexus/component/annotations/Requirement.java b/plexus-component-annotations/src/main/java/org/codehaus/plexus/component/annotations/Requirement.java index b4e718bef..5668fa22e 100644 --- a/plexus-component-annotations/src/main/java/org/codehaus/plexus/component/annotations/Requirement.java +++ b/plexus-component-annotations/src/main/java/org/codehaus/plexus/component/annotations/Requirement.java @@ -17,13 +17,14 @@ package org.codehaus.plexus.component.annotations; import java.lang.annotation.Documented; -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.METHOD; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; -import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + /** * Configures a requirement. * @@ -32,11 +33,10 @@ */ @Documented @Retention(RUNTIME) -@Target({ FIELD, METHOD }) +@Target({FIELD, METHOD}) @Inherited @Deprecated -public @interface Requirement -{ +public @interface Requirement { Class role() default Object.class; String hint() default ""; @@ -48,5 +48,4 @@ String[] hints() default {}; boolean optional() default false; - } diff --git a/plexus-component-metadata/pom.xml b/plexus-component-metadata/pom.xml index e290dbfb2..413efa87c 100644 --- a/plexus-component-metadata/pom.xml +++ b/plexus-component-metadata/pom.xml @@ -1,5 +1,5 @@ - + 4.0.0 @@ -57,7 +57,7 @@ asm 9.5 - + org.apache.maven.plugin-tools maven-plugin-annotations @@ -95,7 +95,7 @@ -Xdoclint:none false - + @@ -135,6 +135,5 @@ - - + diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/AbstractDescriptorMojo.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/AbstractDescriptorMojo.java index 97115bda5..d1f0bd508 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/AbstractDescriptorMojo.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/AbstractDescriptorMojo.java @@ -1,21 +1,19 @@ package org.codehaus.plexus.maven.plugin; -import java.util.List; - /* * The MIT License - * + * * Copyright (c) 2004-2006, The Codehaus - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, @@ -23,6 +21,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +import java.util.List; + import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; @@ -35,20 +35,18 @@ * * @author Jason van Zyl */ -public abstract class AbstractDescriptorMojo - extends AbstractMojo -{ +public abstract class AbstractDescriptorMojo extends AbstractMojo { /** * Current project */ - @Parameter( defaultValue = "${project}", required = true, readonly = true ) + @Parameter(defaultValue = "${project}", required = true, readonly = true) protected MavenProject mavenProject; /** * The file encoding of the source files. */ - @Parameter( defaultValue = "${project.build.sourceEncoding}" ) + @Parameter(defaultValue = "${project.build.sourceEncoding}") protected String sourceEncoding; /** @@ -61,7 +59,7 @@ public abstract class AbstractDescriptorMojo */ @Parameter protected List extractors; - + @Component protected MavenProjectHelper mavenProjectHelper; diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/PlexusDescriptorMojo.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/PlexusDescriptorMojo.java index fdce2f3a0..eac11b7b3 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/PlexusDescriptorMojo.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/PlexusDescriptorMojo.java @@ -2,16 +2,16 @@ /* * Copyright (c) 2004-2005, Codehaus.org - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, @@ -31,55 +31,51 @@ /** * Generates a Plexus {@code components.xml} component descriptor file from source (javadoc) or * class annotations and manually crafted descriptor files. - * + * * @author Jason van Zyl * @author Trygve Laugstøl */ -@Mojo( name = "generate-metadata", defaultPhase = LifecyclePhase.PROCESS_CLASSES, requiresDependencyResolution = ResolutionScope.COMPILE ) -public class PlexusDescriptorMojo - extends AbstractDescriptorMojo -{ +@Mojo( + name = "generate-metadata", + defaultPhase = LifecyclePhase.PROCESS_CLASSES, + requiresDependencyResolution = ResolutionScope.COMPILE) +public class PlexusDescriptorMojo extends AbstractDescriptorMojo { /** * The output location for the generated descriptor. */ - @Parameter( defaultValue = "${project.build.outputDirectory}/META-INF/plexus/components.xml", required = true ) + @Parameter(defaultValue = "${project.build.outputDirectory}/META-INF/plexus/components.xml", required = true) protected File generatedMetadata; /** * The location of manually crafted component descriptors. The contents of the descriptor files in this directory is * merged with the information extracted from the project's sources/classes. */ - @Parameter( defaultValue = "${basedir}/src/main/resources/META-INF/plexus", required = true ) + @Parameter(defaultValue = "${basedir}/src/main/resources/META-INF/plexus", required = true) protected File staticMetadataDirectory; /** * The output location for the intermediary descriptor. This descriptors contains only the information extracted * from the project's sources/classes. */ - @Parameter( defaultValue = "${project.build.directory}/components.xml", required = true ) + @Parameter(defaultValue = "${project.build.directory}/components.xml", required = true) protected File intermediaryMetadata; - public void execute() - throws MojoExecutionException - { + public void execute() throws MojoExecutionException { MetadataGenerationRequest request = new MetadataGenerationRequest(); - try - { + try { request.classpath = mavenProject.getCompileClasspathElements(); - request.classesDirectory = new File( mavenProject.getBuild().getOutputDirectory() ); + request.classesDirectory = new File(mavenProject.getBuild().getOutputDirectory()); request.sourceDirectories = mavenProject.getCompileSourceRoots(); request.sourceEncoding = sourceEncoding; request.componentDescriptorDirectory = staticMetadataDirectory; request.intermediaryFile = intermediaryMetadata; request.outputFile = generatedMetadata; request.extractors = extractors; - - metadataGenerator.generateDescriptor( request ); - } - catch ( Exception e ) - { - throw new MojoExecutionException( "Error generating metadata: ", e ); + + metadataGenerator.generateDescriptor(request); + } catch (Exception e) { + throw new MojoExecutionException("Error generating metadata: ", e); } } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/PlexusMergeMojo.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/PlexusMergeMojo.java index 8bfd4213f..815567db6 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/PlexusMergeMojo.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/PlexusMergeMojo.java @@ -2,16 +2,16 @@ /* * Copyright (c) 2004-2006, Codehaus.org - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, @@ -35,18 +35,16 @@ /** * Merges a set of Plexus descriptors into one descriptor file. - * + * * @author Jason van Zyl * @author Trygve Laugstøl */ -@Mojo( name = "merge-metadata", defaultPhase = LifecyclePhase.PROCESS_CLASSES ) -public class PlexusMergeMojo - extends AbstractMojo -{ +@Mojo(name = "merge-metadata", defaultPhase = LifecyclePhase.PROCESS_CLASSES) +public class PlexusMergeMojo extends AbstractMojo { /** * The destination for the merged descriptor. */ - @Parameter( defaultValue = "${project.build.outputDirectory}/META-INF/plexus/components.xml", required = true ) + @Parameter(defaultValue = "${project.build.outputDirectory}/META-INF/plexus/components.xml", required = true) private File output; /** @@ -55,31 +53,24 @@ public class PlexusMergeMojo @Parameter private File[] descriptors; - @Component( hint = "componentsXml" ) + @Component(hint = "componentsXml") private Merger merger; - public void execute() - throws MojoExecutionException - { + public void execute() throws MojoExecutionException { List files = new ArrayList(); - if ( descriptors != null ) - { - files.addAll( Arrays.asList( descriptors ) ); + if (descriptors != null) { + files.addAll(Arrays.asList(descriptors)); } - if ( files.isEmpty() ) - { + if (files.isEmpty()) { return; } - try - { - merger.mergeDescriptors( output, files ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Error while executing component descriptor creator.", e ); + try { + merger.mergeDescriptors(output, files); + } catch (IOException e) { + throw new MojoExecutionException("Error while executing component descriptor creator.", e); } } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/PlexusTestDescriptorMojo.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/PlexusTestDescriptorMojo.java index 3c7ab74ee..98ef477f7 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/PlexusTestDescriptorMojo.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/maven/plugin/PlexusTestDescriptorMojo.java @@ -2,16 +2,16 @@ /* * Copyright (c) 2004-2005, Codehaus.org - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, @@ -31,55 +31,51 @@ /** * Generates a Plexus {@code components.xml} component descriptor file from test source (javadoc) * or test class annotations and manually crafted descriptor files. - * + * * @author Jason van Zyl * @author Trygve Laugstøl */ -@Mojo( name = "generate-test-metadata", defaultPhase = LifecyclePhase.PROCESS_TEST_CLASSES, requiresDependencyResolution = ResolutionScope.TEST ) -public class PlexusTestDescriptorMojo - extends AbstractDescriptorMojo -{ +@Mojo( + name = "generate-test-metadata", + defaultPhase = LifecyclePhase.PROCESS_TEST_CLASSES, + requiresDependencyResolution = ResolutionScope.TEST) +public class PlexusTestDescriptorMojo extends AbstractDescriptorMojo { /** * The output location for the generated descriptor. */ - @Parameter( defaultValue = "${project.build.testOutputDirectory}/META-INF/plexus/components.xml", required = true ) + @Parameter(defaultValue = "${project.build.testOutputDirectory}/META-INF/plexus/components.xml", required = true) protected File testGeneratedMetadata; /** * The location of manually crafted component descriptors. The contents of the descriptor files in this directory is * merged with the information extracted from the project's sources/classes. */ - @Parameter( defaultValue = "${basedir}/src/test/resources/META-INF/plexus", required = true ) + @Parameter(defaultValue = "${basedir}/src/test/resources/META-INF/plexus", required = true) protected File testStaticMetadataDirectory; /** * The output location for the intermediary descriptor. This descriptors contains only the information extracted * from the project's sources/classes. */ - @Parameter( defaultValue = "${project.build.directory}/test-components.xml", required = true ) + @Parameter(defaultValue = "${project.build.directory}/test-components.xml", required = true) protected File testIntermediaryMetadata; - public void execute() - throws MojoExecutionException - { + public void execute() throws MojoExecutionException { MetadataGenerationRequest request = new MetadataGenerationRequest(); - try - { + try { request.classpath = mavenProject.getTestClasspathElements(); - request.classesDirectory = new File( mavenProject.getBuild().getTestOutputDirectory() ); + request.classesDirectory = new File(mavenProject.getBuild().getTestOutputDirectory()); request.sourceDirectories = mavenProject.getTestCompileSourceRoots(); request.sourceEncoding = sourceEncoding; request.componentDescriptorDirectory = testStaticMetadataDirectory; request.intermediaryFile = testIntermediaryMetadata; request.outputFile = testGeneratedMetadata; request.extractors = extractors; - - metadataGenerator.generateDescriptor( request ); - } - catch ( Exception e ) - { - throw new MojoExecutionException( "Error generating test metadata: ", e ); + + metadataGenerator.generateDescriptor(request); + } catch (Exception e) { + throw new MojoExecutionException("Error generating test metadata: ", e); } } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ClassComponentDescriptorExtractor.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ClassComponentDescriptorExtractor.java index 1426ae18d..b32125bf3 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ClassComponentDescriptorExtractor.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ClassComponentDescriptorExtractor.java @@ -1,11 +1,11 @@ /* * Copyright (C) 2007 the original author or authors. - * + * * 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 @@ -32,91 +32,74 @@ /** * Extracts {@link ComponentDescriptor} from class files. - * + * */ -@Component( role = ComponentDescriptorExtractor.class, hint = "class" ) -public class ClassComponentDescriptorExtractor - extends ComponentDescriptorExtractorSupport -{ +@Component(role = ComponentDescriptorExtractor.class, hint = "class") +public class ClassComponentDescriptorExtractor extends ComponentDescriptorExtractorSupport { private ClassComponentGleaner gleaner; - public ClassComponentDescriptorExtractor( final ClassComponentGleaner gleaner ) - { + public ClassComponentDescriptorExtractor(final ClassComponentGleaner gleaner) { this.gleaner = gleaner; } - public ClassComponentDescriptorExtractor() - { + public ClassComponentDescriptorExtractor() { this.gleaner = new AnnotationComponentGleaner(); } - public List> extract( MetadataGenerationRequest configuration, final ComponentDescriptor[] roleDefaults ) - throws Exception - { + public List> extract( + MetadataGenerationRequest configuration, final ComponentDescriptor[] roleDefaults) throws Exception { // We don't have a reasonable default to use, so just puke up - if ( gleaner == null ) - { - throw new IllegalStateException( "Gleaner is not bound" ); + if (gleaner == null) { + throw new IllegalStateException("Gleaner is not bound"); } - if ( !configuration.classesDirectory.exists() ) - { + if (!configuration.classesDirectory.exists()) { return Collections.emptyList(); } - if ( configuration.useContextClassLoader ) - { - return extract( configuration.classesDirectory, Thread.currentThread().getContextClassLoader(), getDefaultsByRole( roleDefaults ) ); - } - else - { + if (configuration.useContextClassLoader) { + return extract( + configuration.classesDirectory, + Thread.currentThread().getContextClassLoader(), + getDefaultsByRole(roleDefaults)); + } else { ClassLoader prev = Thread.currentThread().getContextClassLoader(); - ClassLoader cl = createClassLoader( configuration.classpath ); + ClassLoader cl = createClassLoader(configuration.classpath); - Thread.currentThread().setContextClassLoader( cl ); + Thread.currentThread().setContextClassLoader(cl); - try - { - return extract( configuration.classesDirectory, cl, getDefaultsByRole( roleDefaults ) ); - } - finally - { - Thread.currentThread().setContextClassLoader( prev ); + try { + return extract(configuration.classesDirectory, cl, getDefaultsByRole(roleDefaults)); + } finally { + Thread.currentThread().setContextClassLoader(prev); } } } - private ClassLoader createClassLoader( final List elements ) - throws Exception - { + private ClassLoader createClassLoader(final List elements) throws Exception { List list = new ArrayList(); // Add the projects dependencies - for ( String filename : elements ) - { - try - { - list.add( new File( filename ).toURI().toURL() ); - } - catch ( MalformedURLException e ) - { - throw new MojoExecutionException( "Invalid classpath entry: " + filename, e ); + for (String filename : elements) { + try { + list.add(new File(filename).toURI().toURL()); + } catch (MalformedURLException e) { + throw new MojoExecutionException("Invalid classpath entry: " + filename, e); } } - URL[] urls = list.toArray( new URL[list.size()] ); + URL[] urls = list.toArray(new URL[list.size()]); - //getLogger().debug( "Classpath:" ); + // getLogger().debug( "Classpath:" ); for (URL url : urls) { - //getLogger().debug( " " + urls[i] ); + // getLogger().debug( " " + urls[i] ); } - return new URLClassLoader( urls, null ); + return new URLClassLoader(urls, null); } - private List> extract( File classesDir, ClassLoader cl, Map> defaultsByRole ) - throws Exception - { + private List> extract( + File classesDir, ClassLoader cl, Map> defaultsByRole) throws Exception { assert classesDir != null; assert cl != null; assert defaultsByRole != null; @@ -124,41 +107,38 @@ private List> extract( File classesDir, ClassLoader cl, M List> descriptors = new ArrayList>(); DirectoryScanner scanner = new DirectoryScanner(); - scanner.setBasedir( classesDir ); + scanner.setBasedir(classesDir); scanner.addDefaultExcludes(); - scanner.setIncludes( new String[] { "**/*.class" } ); + scanner.setIncludes(new String[] {"**/*.class"}); // exclude special classes like module-info.class - scanner.setExcludes( new String[] { "**/*-*.class" } ); + scanner.setExcludes(new String[] {"**/*-*.class"}); - //getLogger().debug( "Scanning for classes in: " + classesDir ); + // getLogger().debug( "Scanning for classes in: " + classesDir ); scanner.scan(); String[] includes = scanner.getIncludedFiles(); - for ( String include : includes ) - { - String className = include.substring( 0, include.lastIndexOf( ".class" ) ).replace( '\\', '.' ).replace( '/', '.' ); + for (String include : includes) { + String className = include.substring(0, include.lastIndexOf(".class")) + .replace('\\', '.') + .replace('/', '.'); - try - { + try { // Class type = cl.loadClass( className ); - ComponentDescriptor descriptor = gleaner.glean( className, cl ); + ComponentDescriptor descriptor = gleaner.glean(className, cl); - if ( descriptor != null ) - { - applyDefaults( descriptor, defaultsByRole ); + if (descriptor != null) { + applyDefaults(descriptor, defaultsByRole); - descriptors.add( descriptor ); + descriptors.add(descriptor); } - } - catch ( VerifyError e ) - { + } catch (VerifyError e) { // getLogger().error( "Failed to load class: " + className + "; cause: " + e ); } } return descriptors; } -} \ No newline at end of file +} diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorExtractor.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorExtractor.java index 1778d5eca..fcc28954c 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorExtractor.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorExtractor.java @@ -1,11 +1,11 @@ /* * Copyright (C) 2007 the original author or authors. - * + * * 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 @@ -20,12 +20,11 @@ /** * An abstraction to allow pluggable {@link ComponentDescriptor} extraction to be dropped. - * + * */ -public interface ComponentDescriptorExtractor -{ +public interface ComponentDescriptorExtractor { String ROLE = ComponentDescriptorExtractor.class.getName(); - List> extract( MetadataGenerationRequest configuration, ComponentDescriptor[] roleDefaults ) - throws Exception; + List> extract(MetadataGenerationRequest configuration, ComponentDescriptor[] roleDefaults) + throws Exception; } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorExtractorSupport.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorExtractorSupport.java index e995ddabd..ac324f5b5 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorExtractorSupport.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorExtractorSupport.java @@ -1,11 +1,11 @@ /* * Copyright (C) 2007 the original author or authors. - * + * * 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 @@ -21,17 +21,13 @@ /** * Support for {@link ComponentDescriptorExtractor} implementations. - * + * */ -public abstract class ComponentDescriptorExtractorSupport - implements ComponentDescriptorExtractor -{ - protected Map> getDefaultsByRole( final ComponentDescriptor[] roleDefaults ) - { +public abstract class ComponentDescriptorExtractorSupport implements ComponentDescriptorExtractor { + protected Map> getDefaultsByRole(final ComponentDescriptor[] roleDefaults) { Map> defaultsByRole = new HashMap>(); - if ( roleDefaults != null ) - { + if (roleDefaults != null) { for (ComponentDescriptor roleDefault : roleDefaults) { String role = roleDefault.getRole(); @@ -46,19 +42,17 @@ protected Map> getDefaultsByRole( final Component return defaultsByRole; } - protected void applyDefaults( ComponentDescriptor descriptor, Map> defaultsByRole ) - { + protected void applyDefaults( + ComponentDescriptor descriptor, Map> defaultsByRole) { assert descriptor != null; assert defaultsByRole != null; - if ( defaultsByRole.containsKey( descriptor.getRole() ) ) - { - ComponentDescriptor defaults = defaultsByRole.get( descriptor.getRole() ); + if (defaultsByRole.containsKey(descriptor.getRole())) { + ComponentDescriptor defaults = defaultsByRole.get(descriptor.getRole()); - if ( descriptor.getInstantiationStrategy() == null ) - { - descriptor.setInstantiationStrategy( defaults.getInstantiationStrategy() ); + if (descriptor.getInstantiationStrategy() == null) { + descriptor.setInstantiationStrategy(defaults.getInstantiationStrategy()); } } } -} \ No newline at end of file +} diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorWriteException.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorWriteException.java index 7fb0455eb..97e4c25e6 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorWriteException.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorWriteException.java @@ -27,21 +27,16 @@ /** * @author Trygve Laugstøl */ -public class ComponentDescriptorWriteException - extends Exception -{ - public ComponentDescriptorWriteException( String message ) - { - super( message ); +public class ComponentDescriptorWriteException extends Exception { + public ComponentDescriptorWriteException(String message) { + super(message); } - public ComponentDescriptorWriteException( String message, Throwable cause ) - { - super( message, cause ); + public ComponentDescriptorWriteException(String message, Throwable cause) { + super(message, cause); } - public ComponentDescriptorWriteException( Throwable cause ) - { - super( cause ); + public ComponentDescriptorWriteException(Throwable cause) { + super(cause); } -} \ No newline at end of file +} diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorWriter.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorWriter.java index 0428d76db..521eebbcd 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorWriter.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ComponentDescriptorWriter.java @@ -32,8 +32,7 @@ /** * @author Kenney Westerhof */ -public interface ComponentDescriptorWriter -{ - void writeDescriptorSet( Writer writer, ComponentSetDescriptor componentSetDescriptor, boolean containerDescriptor ) - throws ComponentDescriptorWriteException, IOException; +public interface ComponentDescriptorWriter { + void writeDescriptorSet(Writer writer, ComponentSetDescriptor componentSetDescriptor, boolean containerDescriptor) + throws ComponentDescriptorWriteException, IOException; } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/DefaultComponentDescriptorWriter.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/DefaultComponentDescriptorWriter.java index e46349550..78dd99c35 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/DefaultComponentDescriptorWriter.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/DefaultComponentDescriptorWriter.java @@ -45,83 +45,74 @@ * @author Jason van Zyl * @author Trygve Laugstøl */ -public class DefaultComponentDescriptorWriter - implements ComponentDescriptorWriter -{ - private static final String LS = System.getProperty( "line.separator" ); +public class DefaultComponentDescriptorWriter implements ComponentDescriptorWriter { + private static final String LS = System.getProperty("line.separator"); - public void writeDescriptorSet( Writer writer, ComponentSetDescriptor componentSetDescriptor, boolean containerDescriptor ) - throws ComponentDescriptorWriteException, IOException - { - try - { - XMLWriter w = new PrettyPrintXMLWriter( writer ); + public void writeDescriptorSet( + Writer writer, ComponentSetDescriptor componentSetDescriptor, boolean containerDescriptor) + throws ComponentDescriptorWriteException, IOException { + try { + XMLWriter w = new PrettyPrintXMLWriter(writer); - w.startElement( containerDescriptor ? "plexus" : "component-set" ); + w.startElement(containerDescriptor ? "plexus" : "component-set"); - writeComponents( w, componentSetDescriptor.getComponents() ); + writeComponents(w, componentSetDescriptor.getComponents()); - writeDependencies( w, componentSetDescriptor.getDependencies() ); + writeDependencies(w, componentSetDescriptor.getDependencies()); w.endElement(); - writer.write( LS ); + writer.write(LS); // Flush, but don't close the writer... we are not its owner writer.flush(); + } catch (PlexusConfigurationException e) { + throw new ComponentDescriptorWriteException("Internal error while writing out the configuration", e); } - catch ( PlexusConfigurationException e ) - { - throw new ComponentDescriptorWriteException( "Internal error while writing out the configuration", e ); - } - } - private void writeComponents( XMLWriter w, List> componentDescriptors ) - throws ComponentDescriptorWriteException, PlexusConfigurationException - { - if ( componentDescriptors == null ) - { + private void writeComponents(XMLWriter w, List> componentDescriptors) + throws ComponentDescriptorWriteException, PlexusConfigurationException { + if (componentDescriptors == null) { return; } - w.startElement( "components" ); + w.startElement("components"); - for ( ComponentDescriptor cd : componentDescriptors ) - { - w.startElement( "component" ); + for (ComponentDescriptor cd : componentDescriptors) { + w.startElement("component"); - element( w, "role", cd.getRole() ); - - element( w, "role-hint", cd.getRoleHint() ); + element(w, "role", cd.getRole()); - element( w, "implementation", cd.getImplementation() ); + element(w, "role-hint", cd.getRoleHint()); - element( w, "version", cd.getVersion() ); + element(w, "implementation", cd.getImplementation()); - element( w, "component-type", cd.getComponentType() ); + element(w, "version", cd.getVersion()); - element( w, "instantiation-strategy", cd.getInstantiationStrategy() ); + element(w, "component-type", cd.getComponentType()); - element( w, "lifecycle-handler", cd.getLifecycleHandler() ); + element(w, "instantiation-strategy", cd.getInstantiationStrategy()); - element( w, "component-profile", cd.getComponentProfile() ); + element(w, "lifecycle-handler", cd.getLifecycleHandler()); - element( w, "component-composer", cd.getComponentComposer() ); + element(w, "component-profile", cd.getComponentProfile()); - element( w, "component-configurator", cd.getComponentConfigurator() ); + element(w, "component-composer", cd.getComponentComposer()); - element( w, "component-factory", cd.getComponentFactory() ); + element(w, "component-configurator", cd.getComponentConfigurator()); - element( w, "description", cd.getDescription() ); + element(w, "component-factory", cd.getComponentFactory()); - element( w, "alias", cd.getAlias() ); + element(w, "description", cd.getDescription()); - element( w, "isolated-realm", Boolean.toString( cd.isIsolatedRealm() ) ); + element(w, "alias", cd.getAlias()); - writeRequirements( w, cd.getRequirements() ); + element(w, "isolated-realm", Boolean.toString(cd.isIsolatedRealm())); - writeConfiguration( w, cd.getConfiguration() ); + writeRequirements(w, cd.getRequirements()); + + writeConfiguration(w, cd.getConfiguration()); w.endElement(); } @@ -129,93 +120,80 @@ private void writeComponents( XMLWriter w, List> componen w.endElement(); } - public void writeDependencies( XMLWriter w, List deps ) - { - if ( deps == null || deps.size() == 0 ) - { + public void writeDependencies(XMLWriter w, List deps) { + if (deps == null || deps.size() == 0) { return; } - w.startElement( "dependencies" ); + w.startElement("dependencies"); - for ( ComponentDependency dep : deps ) - { - writeDependencyElement( dep, w ); + for (ComponentDependency dep : deps) { + writeDependencyElement(dep, w); } w.endElement(); } - private void writeDependencyElement( ComponentDependency dependency, XMLWriter w ) - { - w.startElement( "dependency" ); + private void writeDependencyElement(ComponentDependency dependency, XMLWriter w) { + w.startElement("dependency"); String groupId = dependency.getGroupId(); - element( w, "groupId", groupId ); + element(w, "groupId", groupId); String artifactId = dependency.getArtifactId(); - element( w, "artifactId", artifactId ); + element(w, "artifactId", artifactId); String type = dependency.getType(); - if ( type != null ) - { - element( w, "type", type ); + if (type != null) { + element(w, "type", type); } String version = dependency.getVersion(); - element( w, "version", version ); + element(w, "version", version); w.endElement(); } - private void writeRequirements( XMLWriter w, List requirements ) - { - if ( requirements == null || requirements.size() == 0 ) - { + private void writeRequirements(XMLWriter w, List requirements) { + if (requirements == null || requirements.size() == 0) { return; } - w.startElement( "requirements" ); - - for ( ComponentRequirement cr : requirements ) - { - w.startElement( "requirement" ); + w.startElement("requirements"); + + for (ComponentRequirement cr : requirements) { + w.startElement("requirement"); - element( w, "role", cr.getRole() ); + element(w, "role", cr.getRole()); - if ( cr instanceof ComponentRequirementList ) - { - List hints = ( (ComponentRequirementList) cr ).getRoleHints(); + if (cr instanceof ComponentRequirementList) { + List hints = ((ComponentRequirementList) cr).getRoleHints(); - if ( hints != null ) - { - w.startElement( "role-hints" ); + if (hints != null) { + w.startElement("role-hints"); - for ( String roleHint : hints ) - { - w.startElement( "role-hint" ); + for (String roleHint : hints) { + w.startElement("role-hint"); - w.writeText( roleHint ); + w.writeText(roleHint); w.endElement(); } w.endElement(); } - } - else - { + } else { // ensure there's no written, which causes ComponentLookupException - element( w, "role-hint", "".equals( cr.getRoleHint() ) ? null : cr.getRoleHint() ); + element(w, "role-hint", "".equals(cr.getRoleHint()) ? null : cr.getRoleHint()); } - element( w, "field-name", cr.getFieldName() ); + element(w, "field-name", cr.getFieldName()); - element( w, "optional", cr.isOptional() ? Boolean.TRUE.toString() : null ); + element(w, "optional", cr.isOptional() ? Boolean.TRUE.toString() : null); w.endElement(); } @@ -223,31 +201,26 @@ private void writeRequirements( XMLWriter w, List requirem w.endElement(); } - private void writeConfiguration( XMLWriter w, PlexusConfiguration configuration ) - throws ComponentDescriptorWriteException, PlexusConfigurationException - { - if ( configuration == null || configuration.getChildCount() == 0 ) - { + private void writeConfiguration(XMLWriter w, PlexusConfiguration configuration) + throws ComponentDescriptorWriteException, PlexusConfigurationException { + if (configuration == null || configuration.getChildCount() == 0) { return; } - if ( !configuration.getName().equals( "configuration" ) ) - { - throw new ComponentDescriptorWriteException( "The root node of the configuration must be 'configuration'."); + if (!configuration.getName().equals("configuration")) { + throw new ComponentDescriptorWriteException("The root node of the configuration must be 'configuration'."); } - writePlexusConfiguration( w, configuration ); + writePlexusConfiguration(w, configuration); } - private void writePlexusConfiguration( XMLWriter xmlWriter, PlexusConfiguration c ) - throws PlexusConfigurationException - { - if ( c.getAttributeNames().length == 0 && c.getChildCount() == 0 && c.getValue() == null ) - { + private void writePlexusConfiguration(XMLWriter xmlWriter, PlexusConfiguration c) + throws PlexusConfigurationException { + if (c.getAttributeNames().length == 0 && c.getChildCount() == 0 && c.getValue() == null) { return; } - xmlWriter.startElement( c.getName() ); + xmlWriter.startElement(c.getName()); // ---------------------------------------------------------------------- // Write the attributes @@ -255,9 +228,8 @@ private void writePlexusConfiguration( XMLWriter xmlWriter, PlexusConfiguration String[] attributeNames = c.getAttributeNames(); - for ( String attributeName : attributeNames ) - { - xmlWriter.addAttribute( attributeName, c.getAttribute( attributeName ) ); + for (String attributeName : attributeNames) { + xmlWriter.addAttribute(attributeName, c.getAttribute(attributeName)); } // ---------------------------------------------------------------------- @@ -266,38 +238,30 @@ private void writePlexusConfiguration( XMLWriter xmlWriter, PlexusConfiguration PlexusConfiguration[] children = c.getChildren(); - if ( children.length > 0 ) - { - for ( PlexusConfiguration aChildren : children ) - { - writePlexusConfiguration( xmlWriter, aChildren ); + if (children.length > 0) { + for (PlexusConfiguration aChildren : children) { + writePlexusConfiguration(xmlWriter, aChildren); } - } - else - { + } else { String value = c.getValue(); - if ( value != null ) - { - xmlWriter.writeText( value ); + if (value != null) { + xmlWriter.writeText(value); } } xmlWriter.endElement(); } - private void element( XMLWriter w, String name, String value ) - { - if ( value == null ) - { + private void element(XMLWriter w, String name, String value) { + if (value == null) { return; } - w.startElement( name ); + w.startElement(name); - w.writeText( value ); + w.writeText(value); w.endElement(); } - } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/DefaultMetadataGenerator.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/DefaultMetadataGenerator.java index fe633e809..0299dd2c2 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/DefaultMetadataGenerator.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/DefaultMetadataGenerator.java @@ -2,18 +2,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2006, The Codehaus - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, @@ -39,7 +39,6 @@ import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.ComponentSetDescriptor; import org.codehaus.plexus.logging.AbstractLogEnabled; -import org.codehaus.plexus.metadata.gleaner.AnnotationComponentGleaner; import org.codehaus.plexus.metadata.merge.Merger; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; @@ -48,10 +47,7 @@ * @author Jason van Zyl */ @Component(role = MetadataGenerator.class) -public class DefaultMetadataGenerator - extends AbstractLogEnabled - implements MetadataGenerator -{ +public class DefaultMetadataGenerator extends AbstractLogEnabled implements MetadataGenerator { @Requirement private Merger merger; @@ -63,140 +59,110 @@ public class DefaultMetadataGenerator // should be a component private ComponentDescriptorWriter writer = new DefaultComponentDescriptorWriter(); - public void generateDescriptor( MetadataGenerationRequest request ) - throws Exception - { + public void generateDescriptor(MetadataGenerationRequest request) throws Exception { assert request.outputFile != null; List extractorHints = request.extractors; - + final Collection extractors; - if ( extractorHints == null || extractorHints.size() == 0 ) - { + if (extractorHints == null || extractorHints.size() == 0) { extractors = extractorMap.values(); - } - else - { - extractors = new ArrayList( extractorHints.size() ); - - for ( String hint : extractorHints ) - { - extractors.add( extractorMap.get( hint ) ); + } else { + extractors = new ArrayList(extractorHints.size()); + + for (String hint : extractorHints) { + extractors.add(extractorMap.get(hint)); } } List> descriptors = new ArrayList>(); - for ( ComponentDescriptorExtractor extractor : extractors ) - { - try - { - List> list = extractor.extract( request, roleDefaults ); - if ( list != null && !list.isEmpty() ) - { - descriptors.addAll( list ); + for (ComponentDescriptorExtractor extractor : extractors) { + try { + List> list = extractor.extract(request, roleDefaults); + if (list != null && !list.isEmpty()) { + descriptors.addAll(list); } - } - catch ( Exception e ) - { - throw new Exception( "Failed to extract descriptors", e ); + } catch (Exception e) { + throw new Exception("Failed to extract descriptors", e); } } // Sort the descriptors by key to make the output reproducible - Collections.sort( descriptors, new Comparator() - { - public int compare( ComponentDescriptor d1, ComponentDescriptor d2 ) - { - return d1.getHumanReadableKey().compareTo( d2.getHumanReadableKey() ); + Collections.sort(descriptors, new Comparator() { + public int compare(ComponentDescriptor d1, ComponentDescriptor d2) { + return d1.getHumanReadableKey().compareTo(d2.getHumanReadableKey()); } }); - List componentDescriptors = new ArrayList(); - + List componentDescriptors = new ArrayList(); + // // If we found descriptors, write out the discovered descriptors // - if ( descriptors.size() > 0 ) - { - getLogger().info( "Discovered " + descriptors.size() + " component descriptor(s)" ); + if (descriptors.size() > 0) { + getLogger().info("Discovered " + descriptors.size() + " component descriptor(s)"); ComponentSetDescriptor set = new ComponentSetDescriptor(); - set.setComponents( descriptors ); - set.setDependencies( Collections. emptyList() ); - - if ( request.componentDescriptorDirectory == null ) - { - writeDescriptor( set, request.outputFile ); - } - else - { - if ( request.intermediaryFile == null ) - { - request.intermediaryFile = File.createTempFile( "plexus-metadata", "xml" ); + set.setComponents(descriptors); + set.setDependencies(Collections.emptyList()); + + if (request.componentDescriptorDirectory == null) { + writeDescriptor(set, request.outputFile); + } else { + if (request.intermediaryFile == null) { + request.intermediaryFile = File.createTempFile("plexus-metadata", "xml"); request.intermediaryFile.deleteOnExit(); } - writeDescriptor( set, request.intermediaryFile ); - componentDescriptors.add( request.intermediaryFile ); + writeDescriptor(set, request.intermediaryFile); + componentDescriptors.add(request.intermediaryFile); } } - // // Deal with merging // - if ( request.componentDescriptorDirectory != null && request.componentDescriptorDirectory.isDirectory() ) - { + if (request.componentDescriptorDirectory != null && request.componentDescriptorDirectory.isDirectory()) { File[] files = request.componentDescriptorDirectory.listFiles(); // Sort the files by name to make the output reproducible - Arrays.sort( files, new Comparator() - { - public int compare( File f1, File f2 ) - { - return f1.getName().compareTo( f2.getName() ); + Arrays.sort(files, new Comparator() { + public int compare(File f1, File f2) { + return f1.getName().compareTo(f2.getName()); } }); int added = 0; - for ( File file : files ) - { - if ( file.getName().endsWith( ".xml" ) && !file.getName().equals( "plexus.xml" ) ) - { - componentDescriptors.add( file ); + for (File file : files) { + if (file.getName().endsWith(".xml") && !file.getName().equals("plexus.xml")) { + componentDescriptors.add(file); added++; } } - getLogger().info( "Merging " + added + " manually-crafted descriptor file(s)" ); + getLogger().info("Merging " + added + " manually-crafted descriptor file(s)"); } - if ( componentDescriptors.size() > 0 ) - { - merger.mergeDescriptors( request.outputFile, componentDescriptors ); + if (componentDescriptors.size() > 0) { + merger.mergeDescriptors(request.outputFile, componentDescriptors); } } - private void writeDescriptor( ComponentSetDescriptor desc, File outputFile ) - throws Exception - { + private void writeDescriptor(ComponentSetDescriptor desc, File outputFile) throws Exception { assert desc != null; assert outputFile != null; - FileUtils.forceMkdir( outputFile.getParentFile() ); + FileUtils.forceMkdir(outputFile.getParentFile()); - BufferedWriter output = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( outputFile ), "UTF-8" ) ); + BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); - try - { - writer.writeDescriptorSet( output, desc, false ); + try { + writer.writeDescriptorSet(output, desc, false); output.flush(); - } - finally - { - IOUtil.close( output ); + } finally { + IOUtil.close(output); } - getLogger().debug( "Wrote: " + outputFile ); + getLogger().debug("Wrote: " + outputFile); } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/MetadataGenerationRequest.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/MetadataGenerationRequest.java index 429c5b717..eb6c84814 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/MetadataGenerationRequest.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/MetadataGenerationRequest.java @@ -3,34 +3,33 @@ import java.io.File; import java.util.List; -public class MetadataGenerationRequest -{ +public class MetadataGenerationRequest { /** Source to examine for Javadoc annotions which are used to generate component metadata. */ - public List sourceDirectories; //todo: these should be files + public List sourceDirectories; // todo: these should be files /** The character encoding of the source files, may be {@code null} or empty to use platform's default encoding. */ public String sourceEncoding; /** Classes to examine for annotations which are used to generate component metadata. */ - public File classesDirectory; + public File classesDirectory; /** Supporting classpath required by class-based annotation processing. */ - public List classpath; //todo: these should be files + public List classpath; // todo: these should be files /** Flag to indicate using the context classloader for the supporting classpath required by annotation-based processing. */ public boolean useContextClassLoader; - + /** Directory where existing component descriptors live. */ public File componentDescriptorDirectory; - + /** Existing component descriptors that need to be merged. */ public List componentDescriptors; - + /** Where existing component descriptors are merged. */ public File intermediaryFile; - + /** Output file for the final component descriptor. */ public File outputFile; - + public List extractors; } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/MetadataGenerator.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/MetadataGenerator.java index 64c296509..e8d6e45e9 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/MetadataGenerator.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/MetadataGenerator.java @@ -1,8 +1,5 @@ package org.codehaus.plexus.metadata; -public interface MetadataGenerator -{ - void generateDescriptor( MetadataGenerationRequest configuration ) - throws Exception; - +public interface MetadataGenerator { + void generateDescriptor(MetadataGenerationRequest configuration) throws Exception; } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/SourceComponentDescriptorExtractor.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/SourceComponentDescriptorExtractor.java index afdd04b6d..5b81cbc1c 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/SourceComponentDescriptorExtractor.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/SourceComponentDescriptorExtractor.java @@ -1,11 +1,11 @@ /* * Copyright (C) 2007 the original author or authors. - * + * * 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 @@ -20,49 +20,43 @@ import java.util.List; import java.util.Map; +import com.thoughtworks.qdox.JavaProjectBuilder; +import com.thoughtworks.qdox.model.JavaClass; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.metadata.gleaner.QDoxComponentGleaner; import org.codehaus.plexus.metadata.gleaner.SourceComponentGleaner; import org.codehaus.plexus.util.StringUtils; -import com.thoughtworks.qdox.JavaProjectBuilder; -import com.thoughtworks.qdox.model.JavaClass; - /** * Extracts {@link ComponentDescriptor} from source files. - * + * * @version $Rev$ $Date$ */ -@Component( role = ComponentDescriptorExtractor.class, hint = "source" ) -public class SourceComponentDescriptorExtractor - extends ComponentDescriptorExtractorSupport -{ +@Component(role = ComponentDescriptorExtractor.class, hint = "source") +public class SourceComponentDescriptorExtractor extends ComponentDescriptorExtractorSupport { private SourceComponentGleaner gleaner; - public SourceComponentDescriptorExtractor() - { - } + public SourceComponentDescriptorExtractor() {} - public SourceComponentDescriptorExtractor( final SourceComponentGleaner gleaner ) - { + public SourceComponentDescriptorExtractor(final SourceComponentGleaner gleaner) { this.gleaner = gleaner; } - public List> extract( MetadataGenerationRequest configuration, final ComponentDescriptor[] roleDefaults ) - throws Exception - { - if ( gleaner == null ) - { + public List> extract( + MetadataGenerationRequest configuration, final ComponentDescriptor[] roleDefaults) throws Exception { + if (gleaner == null) { gleaner = new QDoxComponentGleaner(); } - return extract( configuration.sourceDirectories, configuration.sourceEncoding, getDefaultsByRole( roleDefaults ) ); + return extract(configuration.sourceDirectories, configuration.sourceEncoding, getDefaultsByRole(roleDefaults)); } - private List> extract( final List sourceDirectories, final String sourceEncoding, final Map> defaultsByRole ) - throws Exception - { + private List> extract( + final List sourceDirectories, + final String sourceEncoding, + final Map> defaultsByRole) + throws Exception { assert sourceDirectories != null; assert defaultsByRole != null; @@ -71,16 +65,14 @@ private List> extract( final List sourceDirectori // Scan the sources JavaProjectBuilder builder = new JavaProjectBuilder(); - if ( StringUtils.isNotEmpty( sourceEncoding ) ) - { - builder.setEncoding( sourceEncoding ); + if (StringUtils.isNotEmpty(sourceEncoding)) { + builder.setEncoding(sourceEncoding); } - for ( String sourceDirectory : sourceDirectories ) - { - File dir = new File( sourceDirectory ); + for (String sourceDirectory : sourceDirectories) { + File dir = new File(sourceDirectory); - builder.addSourceTree( dir ); + builder.addSourceTree(dir); } Collection classes = builder.getClasses(); diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/Ann.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/Ann.java index 6f6eb122b..b1d833a6e 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/Ann.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/Ann.java @@ -27,33 +27,34 @@ */ public class Ann { - private String desc; - private Map params = new LinkedHashMap(); - - public Ann(String desc) { - this.desc = desc; - } - - public void addParam(String name, Object value) { - params.put(name, value); - } - - public String getDesc() { - return desc; - } - - public String getType() { - return Type.getType(desc).getClassName(); - } - - public Map getParams() { - return params; - } - - @SuppressWarnings("unchecked") - public T getAnnotation(Class c, ClassLoader cl) { - return (T) Proxy.newProxyInstance(Ann.class.getClassLoader(), new Class[] { c }, // - new AnnInvocationHandler(this, cl, c)); - } - + private String desc; + private Map params = new LinkedHashMap(); + + public Ann(String desc) { + this.desc = desc; + } + + public void addParam(String name, Object value) { + params.put(name, value); + } + + public String getDesc() { + return desc; + } + + public String getType() { + return Type.getType(desc).getClassName(); + } + + public Map getParams() { + return params; + } + + @SuppressWarnings("unchecked") + public T getAnnotation(Class c, ClassLoader cl) { + return (T) Proxy.newProxyInstance( + Ann.class.getClassLoader(), + new Class[] {c}, // + new AnnInvocationHandler(this, cl, c)); + } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnClass.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnClass.java index 4ec05113c..e78971438 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnClass.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnClass.java @@ -26,109 +26,107 @@ * @author Eugene Kuleshov */ public class AnnClass { - - private int access; - private String name; - private String superName; - private String[] interfaces; - - private Map anns = new LinkedHashMap(); - private Map fields = new LinkedHashMap(); - private Map methods = new LinkedHashMap(); - private ClassLoader cl; - - // setters - - public AnnClass(ClassLoader cl) { - this.cl = cl; - } - - public void setName(String name) { - this.name = name; - } - - public void setAccess(int access) { - this.access = access; - } - - public void setSuperName(String superName) { - this.superName = superName; - } - - public void setInterfaces(String[] interfaces) { - this.interfaces = interfaces; - } - - public void addAnn(Ann ann) { - anns.put(ann.getDesc(), ann); - } - - public void addField(AnnField field) { - fields.put(field.getName(), field); - } - - public void addMethod(AnnMethod method) { - methods.put(method.getName() + method.getDesc(), method); - } - - // getters - - public ClassLoader getClassLoader() { - return cl; - } - - public int getAccess() { - return access; - } - - public String getName() { - return name; - } - - public String getSuperName() { - return superName; - } - - public String[] getInterfaces() { - return interfaces; - } - - public Map getAnns() { - return anns; - } - - public Map getFields() { - return fields; - } - - public Map getMethods() { - return methods; - } - - public Set getFieldNames() { - return fields.keySet(); - } - - public Set getMethodKeys() { - return methods.keySet(); - } - - // conversion to java.lang.Annotation - - public T getAnnotation(Class c) { - Ann ann = anns.get(Type.getDescriptor(c)); - return ann == null ? null : ann.getAnnotation(c, cl); - } - - public T getFieldAnnotation(String fieldName, Class c) { - AnnField field = fields.get(fieldName); - return field==null ? null : field.getAnnotation(c); - } - - public T getMethodAnnotation(String methodKey, Class c) { - AnnMethod method = methods.get(methodKey); - return method==null ? null : method.getAnnotation(c); - } -} + private int access; + private String name; + private String superName; + private String[] interfaces; + + private Map anns = new LinkedHashMap(); + private Map fields = new LinkedHashMap(); + private Map methods = new LinkedHashMap(); + private ClassLoader cl; + + // setters + + public AnnClass(ClassLoader cl) { + this.cl = cl; + } + + public void setName(String name) { + this.name = name; + } + + public void setAccess(int access) { + this.access = access; + } + + public void setSuperName(String superName) { + this.superName = superName; + } + + public void setInterfaces(String[] interfaces) { + this.interfaces = interfaces; + } + + public void addAnn(Ann ann) { + anns.put(ann.getDesc(), ann); + } + + public void addField(AnnField field) { + fields.put(field.getName(), field); + } + + public void addMethod(AnnMethod method) { + methods.put(method.getName() + method.getDesc(), method); + } + + // getters + + public ClassLoader getClassLoader() { + return cl; + } + public int getAccess() { + return access; + } + + public String getName() { + return name; + } + + public String getSuperName() { + return superName; + } + + public String[] getInterfaces() { + return interfaces; + } + + public Map getAnns() { + return anns; + } + + public Map getFields() { + return fields; + } + + public Map getMethods() { + return methods; + } + + public Set getFieldNames() { + return fields.keySet(); + } + + public Set getMethodKeys() { + return methods.keySet(); + } + + // conversion to java.lang.Annotation + + public T getAnnotation(Class c) { + Ann ann = anns.get(Type.getDescriptor(c)); + return ann == null ? null : ann.getAnnotation(c, cl); + } + + public T getFieldAnnotation(String fieldName, Class c) { + AnnField field = fields.get(fieldName); + return field == null ? null : field.getAnnotation(c); + } + + public T getMethodAnnotation(String methodKey, Class c) { + AnnMethod method = methods.get(methodKey); + return method == null ? null : method.getAnnotation(c); + } +} diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnEnum.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnEnum.java index 0d6a02d40..a753a9438 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnEnum.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnEnum.java @@ -23,56 +23,55 @@ */ public class AnnEnum { - private final String desc; - private final String value; + private final String desc; + private final String value; - public AnnEnum(String desc, String value) { - this.desc = desc; - this.value = value; - } - - public String getDesc() { - return desc; - } - - public String getValue() { - return value; - } - - public String getType() { - return Type.getType(desc).getClassName(); - } - - public int hashCode() { - return 31 * (31 + desc.hashCode()) + value.hashCode(); - } + public AnnEnum(String desc, String value) { + this.desc = desc; + this.value = value; + } - public boolean equals(Object obj) { - if (this == obj) { - return true; + public String getDesc() { + return desc; } - if (obj == null) { - return false; + + public String getValue() { + return value; } - if (getClass() != obj.getClass()) { - return false; + + public String getType() { + return Type.getType(desc).getClassName(); } - AnnEnum other = (AnnEnum) obj; - if (desc == null) { - if (other.desc != null) { - return false; - } - } else if (!desc.equals(other.desc)) { - return false; + + public int hashCode() { + return 31 * (31 + desc.hashCode()) + value.hashCode(); } - if (value == null) { - if (other.value != null) { - return false; - } - } else if (!value.equals(other.value)) { - return false; + + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + AnnEnum other = (AnnEnum) obj; + if (desc == null) { + if (other.desc != null) { + return false; + } + } else if (!desc.equals(other.desc)) { + return false; + } + if (value == null) { + if (other.value != null) { + return false; + } + } else if (!value.equals(other.value)) { + return false; + } + return true; } - return true; - } - } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnField.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnField.java index ac709b810..a0b523f12 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnField.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnField.java @@ -26,47 +26,45 @@ */ public class AnnField { - private final AnnClass owner; - private final int access; - private final String name; - private final String desc; - private Map anns = new LinkedHashMap(); - - public AnnField(AnnClass owner, int access, String name, String desc) { - this.owner = owner; - this.access = access; - this.desc = desc; - this.name = name; - } + private final AnnClass owner; + private final int access; + private final String name; + private final String desc; + private Map anns = new LinkedHashMap(); - public int getAccess() { - return access; - } - - public String getName() { - return name; - } - - public String getDesc() { - return desc; - } - - public Map getAnns() { - return anns; - } - - public String getType() { - return Type.getType(desc).getClassName(); - } + public AnnField(AnnClass owner, int access, String name, String desc) { + this.owner = owner; + this.access = access; + this.desc = desc; + this.name = name; + } - public void addAnn(Ann ann) { - anns.put(ann.getDesc(), ann); - } - - public T getAnnotation(Class c) { - Ann ann = anns.get(Type.getDescriptor(c)); - return ann == null ? null : ann.getAnnotation(c, owner.getClassLoader()); - } + public int getAccess() { + return access; + } -} + public String getName() { + return name; + } + + public String getDesc() { + return desc; + } + + public Map getAnns() { + return anns; + } + public String getType() { + return Type.getType(desc).getClassName(); + } + + public void addAnn(Ann ann) { + anns.put(ann.getDesc(), ann); + } + + public T getAnnotation(Class c) { + Ann ann = anns.get(Type.getDescriptor(c)); + return ann == null ? null : ann.getAnnotation(c, owner.getClassLoader()); + } +} diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnInvocationHandler.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnInvocationHandler.java index b711a6e9c..ef458abc3 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnInvocationHandler.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnInvocationHandler.java @@ -29,53 +29,52 @@ * @author Eugene Kuleshov */ public class AnnInvocationHandler implements InvocationHandler { - private final Ann ann; - private final ClassLoader cl; - private final Class c; + private final Ann ann; + private final ClassLoader cl; + private final Class c; - public AnnInvocationHandler(Ann ann, ClassLoader cl, Class c) { - this.ann = ann; - this.cl = cl; - this.c = c; - } + public AnnInvocationHandler(Ann ann, ClassLoader cl, Class c) { + this.ann = ann; + this.cl = cl; + this.c = c; + } - public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { - String name = m.getName(); + public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { + String name = m.getName(); - if("toString".equals(name)) { - StringBuilder sb = new StringBuilder(ann.getType()); - sb.append("["); - String sep = ""; - for(Map.Entry e : ann.getParams().entrySet()) { - // TODO conversion for class, array, enum, and annotation types - sb.append(sep).append(e.getKey()).append("=").append(e.getValue()); - sep = "; "; - } - sb.append("]"); - return sb.toString(); - } - - Object value = ann.getParams().get(name); - if(value!=null) { - if(value instanceof Type) { - String className = ((Type) value).getClassName(); - try { - return Class.forName(className, false, cl); - } catch(ClassNotFoundException ex) { - if(cl instanceof URLClassLoader) { - URL[] urls = ((URLClassLoader) cl).getURLs(); - throw new RuntimeException("Unable to load class " + className + " from " + Arrays.toString(urls), ex); - } - throw new RuntimeException("Unable to load class " + className + " from " + cl, ex); + if ("toString".equals(name)) { + StringBuilder sb = new StringBuilder(ann.getType()); + sb.append("["); + String sep = ""; + for (Map.Entry e : ann.getParams().entrySet()) { + // TODO conversion for class, array, enum, and annotation types + sb.append(sep).append(e.getKey()).append("=").append(e.getValue()); + sep = "; "; + } + sb.append("]"); + return sb.toString(); } - } - // TODO conversion for class, array, enum, and annotation types - return value; - } else { - Method am = c.getDeclaredMethod(m.getName(), m.getParameterTypes()); - return am.getDefaultValue(); - } - } + Object value = ann.getParams().get(name); + if (value != null) { + if (value instanceof Type) { + String className = ((Type) value).getClassName(); + try { + return Class.forName(className, false, cl); + } catch (ClassNotFoundException ex) { + if (cl instanceof URLClassLoader) { + URL[] urls = ((URLClassLoader) cl).getURLs(); + throw new RuntimeException( + "Unable to load class " + className + " from " + Arrays.toString(urls), ex); + } + throw new RuntimeException("Unable to load class " + className + " from " + cl, ex); + } + } + // TODO conversion for class, array, enum, and annotation types + return value; + } else { + Method am = c.getDeclaredMethod(m.getName(), m.getParameterTypes()); + return am.getDefaultValue(); + } + } } - diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnMethod.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnMethod.java index c64de132a..79605b51b 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnMethod.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnMethod.java @@ -27,66 +27,64 @@ */ public class AnnMethod { - private final AnnClass owner; - private final int access; - private final String name; - private final String desc; - private Map anns = new LinkedHashMap(); - private Map> paramAnns = new HashMap>(); + private final AnnClass owner; + private final int access; + private final String name; + private final String desc; + private Map anns = new LinkedHashMap(); + private Map> paramAnns = new HashMap>(); - public AnnMethod(AnnClass owner, int access, String name, String desc) { - this.owner = owner; - this.access = access; - this.name = name; - this.desc = desc; - } + public AnnMethod(AnnClass owner, int access, String name, String desc) { + this.owner = owner; + this.access = access; + this.name = name; + this.desc = desc; + } - public int getAccess() { - return access; - } - - public String getName() { - return name; - } - - public String getDesc() { - return desc; - } + public int getAccess() { + return access; + } - public Map getAnns() { - return anns; - } - - public Map> getParamAnns() { - return paramAnns; - } - - public void addAnn(Ann ann) { - anns.put(ann.getDesc(), ann); - } + public String getName() { + return name; + } - public void addParamAnn(int parameter, Ann ann) { - Map anns = paramAnns.get(parameter); - if(anns==null) { - anns = new LinkedHashMap(); - paramAnns.put(parameter, anns); + public String getDesc() { + return desc; } - anns.put(ann.getDesc(), ann); - } - - public T getAnnotation(Class c) { - Ann ann = anns.get(Type.getDescriptor(c)); - return ann == null ? null : ann.getAnnotation(c, owner.getClassLoader()); - } - - public T getParameterAnnotation(int parameter, Class c) { - Map anns = paramAnns.get(parameter); - if (anns == null) { - return null; + + public Map getAnns() { + return anns; } - Ann ann = anns.get(Type.getDescriptor(c)); - return ann == null ? null : ann.getAnnotation(c, owner.getClassLoader()); - } -} + public Map> getParamAnns() { + return paramAnns; + } + + public void addAnn(Ann ann) { + anns.put(ann.getDesc(), ann); + } + + public void addParamAnn(int parameter, Ann ann) { + Map anns = paramAnns.get(parameter); + if (anns == null) { + anns = new LinkedHashMap(); + paramAnns.put(parameter, anns); + } + anns.put(ann.getDesc(), ann); + } + public T getAnnotation(Class c) { + Ann ann = anns.get(Type.getDescriptor(c)); + return ann == null ? null : ann.getAnnotation(c, owner.getClassLoader()); + } + + public T getParameterAnnotation(int parameter, Class c) { + Map anns = paramAnns.get(parameter); + if (anns == null) { + return null; + } + Ann ann = anns.get(Type.getDescriptor(c)); + return ann == null ? null : ann.getAnnotation(c, owner.getClassLoader()); + } +} diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnReader.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnReader.java index 7dd5576fc..c5cb85a8a 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnReader.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/ann/AnnReader.java @@ -32,119 +32,118 @@ */ public class AnnReader extends ClassVisitor { - private final AnnClass annClass; - - private AnnReader(AnnClass annClass) { - super(Opcodes.ASM9); - this.annClass = annClass; - } - - public static AnnClass read(InputStream is, ClassLoader cl) throws IOException { - AnnClass annClass = new AnnClass(cl); - AnnReader cv = new AnnReader(annClass); - ClassReader r = new ClassReader(is); - r.accept(cv, ClassReader.SKIP_FRAMES | ClassReader.SKIP_CODE); - return annClass; - } - - public void visit(int version, int access, String name, String signature, - String superName, String[] interfaces) { - annClass.setName(name); - annClass.setAccess(access); - annClass.setSuperName(superName); - annClass.setInterfaces(interfaces); - } - - public AnnotationVisitor visitAnnotation(final String desc, boolean visible) { - Ann ann = new Ann(desc); - annClass.addAnn(ann); - return new AnnAnnReader(ann); - } - - public FieldVisitor visitField(int access, final String name, final String desc, String signature, Object value) { - final AnnField field = new AnnField(annClass, access, name, desc); - annClass.addField(field); - return new FieldVisitor(Opcodes.ASM9) { - - public AnnotationVisitor visitAnnotation(String desc, boolean visible) { - Ann ann = new Ann(desc); - field.addAnn(ann); - return new AnnAnnReader(ann); - } - }; - } - - public MethodVisitor visitMethod(int access, final String mname, final String mdesc, - String signature, String[] exceptions) { - final AnnMethod method = new AnnMethod(annClass, access, mname, mdesc); - annClass.addMethod(method); - - return new MethodVisitor(Opcodes.ASM9) { - - public AnnotationVisitor visitAnnotation(String desc, boolean visible) { - Ann ann = new Ann(desc); - method.addAnn(ann); - return new AnnAnnReader(ann); - } - - public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) { - Ann ann = new Ann(desc); - method.addParamAnn(parameter, ann); - return new AnnAnnReader(ann); - } - }; - } + private final AnnClass annClass; - static class AnnAnnReader extends AnnotationVisitor { - private Ann ann; + private AnnReader(AnnClass annClass) { + super(Opcodes.ASM9); + this.annClass = annClass; + } - public AnnAnnReader(Ann ann) { - super(Opcodes.ASM9); - this.ann = ann; + public static AnnClass read(InputStream is, ClassLoader cl) throws IOException { + AnnClass annClass = new AnnClass(cl); + AnnReader cv = new AnnReader(annClass); + ClassReader r = new ClassReader(is); + r.accept(cv, ClassReader.SKIP_FRAMES | ClassReader.SKIP_CODE); + return annClass; } - public void visit(String name, Object value) { - ann.addParam(name, value); + public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { + annClass.setName(name); + annClass.setAccess(access); + annClass.setSuperName(superName); + annClass.setInterfaces(interfaces); } - public void visitEnum(String name, String desc, String value) { - ann.addParam(name, new AnnEnum(desc, value)); + public AnnotationVisitor visitAnnotation(final String desc, boolean visible) { + Ann ann = new Ann(desc); + annClass.addAnn(ann); + return new AnnAnnReader(ann); } - - public AnnotationVisitor visitAnnotation(String name, String desc) { - Ann ann = new Ann(desc); - this.ann.addParam(name, ann); - return new AnnAnnReader(ann); + + public FieldVisitor visitField(int access, final String name, final String desc, String signature, Object value) { + final AnnField field = new AnnField(annClass, access, name, desc); + annClass.addField(field); + return new FieldVisitor(Opcodes.ASM9) { + + public AnnotationVisitor visitAnnotation(String desc, boolean visible) { + Ann ann = new Ann(desc); + field.addAnn(ann); + return new AnnAnnReader(ann); + } + }; } - public AnnotationVisitor visitArray(String name) { - return new AnnAnnArrayReader(ann, name); + public MethodVisitor visitMethod( + int access, final String mname, final String mdesc, String signature, String[] exceptions) { + final AnnMethod method = new AnnMethod(annClass, access, mname, mdesc); + annClass.addMethod(method); + + return new MethodVisitor(Opcodes.ASM9) { + + public AnnotationVisitor visitAnnotation(String desc, boolean visible) { + Ann ann = new Ann(desc); + method.addAnn(ann); + return new AnnAnnReader(ann); + } + + public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) { + Ann ann = new Ann(desc); + method.addParamAnn(parameter, ann); + return new AnnAnnReader(ann); + } + }; } - } - - static class AnnAnnArrayReader extends AnnotationVisitor { - private Ann ann; + static class AnnAnnReader extends AnnotationVisitor { + private Ann ann; - private String name; + public AnnAnnReader(Ann ann) { + super(Opcodes.ASM9); + this.ann = ann; + } - // TODO good enough for now, but does not cover general case - private ArrayList array = new ArrayList(); + public void visit(String name, Object value) { + ann.addParam(name, value); + } - public AnnAnnArrayReader(Ann ann, String name) { - super(Opcodes.ASM9); - this.ann = ann; - this.name = name; - } + public void visitEnum(String name, String desc, String value) { + ann.addParam(name, new AnnEnum(desc, value)); + } + + public AnnotationVisitor visitAnnotation(String name, String desc) { + Ann ann = new Ann(desc); + this.ann.addParam(name, ann); + return new AnnAnnReader(ann); + } - public void visit(String name, Object value) { - if(value instanceof String) { - array.add((String) value); - } + public AnnotationVisitor visitArray(String name) { + return new AnnAnnArrayReader(ann, name); + } } - public void visitEnd() { - ann.addParam(name, array.toArray(new String[array.size()])); + static class AnnAnnArrayReader extends AnnotationVisitor { + + private Ann ann; + + private String name; + + // TODO good enough for now, but does not cover general case + private ArrayList array = new ArrayList(); + + public AnnAnnArrayReader(Ann ann, String name) { + super(Opcodes.ASM9); + this.ann = ann; + this.name = name; + } + + public void visit(String name, Object value) { + if (value instanceof String) { + array.add((String) value); + } + } + + public void visitEnd() { + ann.addParam(name, array.toArray(new String[array.size()])); + } } - } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/AnnotationComponentGleaner.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/AnnotationComponentGleaner.java index 0b2ba6ede..6202c8ec7 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/AnnotationComponentGleaner.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/AnnotationComponentGleaner.java @@ -43,25 +43,20 @@ * and when found translates them into a {@link ComponentDescriptor}. * */ -public class AnnotationComponentGleaner - extends ComponentGleanerSupport - implements ClassComponentGleaner -{ +public class AnnotationComponentGleaner extends ComponentGleanerSupport implements ClassComponentGleaner { private static final String OBJECT_SLASHED_NAME = Object.class.getName().replace('.', '/'); - public ComponentDescriptor glean(String className, ClassLoader cl) throws ComponentGleanerException - { + public ComponentDescriptor glean(String className, ClassLoader cl) throws ComponentGleanerException { assert className != null; assert cl != null; AnnClass annClass = readClass(className.replace('.', '/'), cl); - + // Skip abstract classes if (Modifier.isAbstract(annClass.getAccess())) { return null; } - - + Component anno = annClass.getAnnotation(Component.class); if (anno == null) { @@ -69,7 +64,7 @@ public ComponentDescriptor glean(String className, ClassLoader cl) throws Com } ComponentDescriptor component = new ComponentDescriptor(); - + component.setRole(anno.role().getName()); component.setRoleHint(filterEmptyAsNull(anno.hint())); @@ -121,52 +116,39 @@ public ComponentDescriptor glean(String className, ClassLoader cl) throws Com return component; } - private AnnClass readClass(String className, ClassLoader cl) throws ComponentGleanerException - { - InputStream is = null; - - try - { - // only read annotation from project classes (not jars) - Enumeration en = cl.getResources( className + ".class" ); - while ( en.hasMoreElements() ) { - URL url = en.nextElement(); - if( url.toString().startsWith( "file:" ) ) - { - is = url.openStream(); - return AnnReader.read( is, cl ); - } - } - throw new ComponentGleanerException("Can't find class " + className); - } - catch (IOException ex) - { - throw new ComponentGleanerException("Can't read class " + className, ex); - } - finally - { - IOUtil.close(is); + private AnnClass readClass(String className, ClassLoader cl) throws ComponentGleanerException { + InputStream is = null; + + try { + // only read annotation from project classes (not jars) + Enumeration en = cl.getResources(className + ".class"); + while (en.hasMoreElements()) { + URL url = en.nextElement(); + if (url.toString().startsWith("file:")) { + is = url.openStream(); + return AnnReader.read(is, cl); + } + } + throw new ComponentGleanerException("Can't find class " + className); + } catch (IOException ex) { + throw new ComponentGleanerException("Can't read class " + className, ex); + } finally { + IOUtil.close(is); } } - private AnnClass readClass2(String className, ClassLoader cl) throws ComponentGleanerException - { + private AnnClass readClass2(String className, ClassLoader cl) throws ComponentGleanerException { InputStream is = null; - try - { - is = cl.getResourceAsStream(className + ".class"); - return AnnReader.read(is, cl); - } - catch (IOException ex) - { - throw new ComponentGleanerException("Can't read class " + className, ex); - } - finally - { - IOUtil.close(is); + try { + is = cl.getResourceAsStream(className + ".class"); + return AnnReader.read(is, cl); + } catch (IOException ex) { + throw new ComponentGleanerException("Can't read class " + className, ex); + } finally { + IOUtil.close(is); } } - + /** * Returns a list of all of the classes which the given type inherits from. */ @@ -175,13 +157,13 @@ private List getClasses(AnnClass annClass, ClassLoader cl) throws Comp List classes = new ArrayList(); - while(annClass!=null) { + while (annClass != null) { classes.add(annClass); String superName = annClass.getSuperName(); - if(superName!=null && !superName.equals(OBJECT_SLASHED_NAME)) { - annClass = readClass2(superName, cl); + if (superName != null && !superName.equals(OBJECT_SLASHED_NAME)) { + annClass = readClass2(superName, cl); } else { - break; + break; } // @@ -192,26 +174,25 @@ private List getClasses(AnnClass annClass, ClassLoader cl) throws Comp return classes; } - private ComponentRequirement findRequirement(final AnnField field, AnnClass annClass, ClassLoader cl) - throws ComponentGleanerException - { + private ComponentRequirement findRequirement(final AnnField field, AnnClass annClass, ClassLoader cl) + throws ComponentGleanerException { assert field != null; Requirement anno = field.getAnnotation(Requirement.class); - + if (anno == null) { return null; } String fieldType = field.getType(); - + // TODO implement type resolution without loading classes Class type; try { - type = Class.forName(fieldType, false, cl); + type = Class.forName(fieldType, false, cl); } catch (ClassNotFoundException ex) { - // TODO Auto-generated catch block - throw new ComponentGleanerException("Can't load class " + fieldType); + // TODO Auto-generated catch block + throw new ComponentGleanerException("Can't load class " + fieldType); } ComponentRequirement requirement; @@ -222,25 +203,23 @@ private ComponentRequirement findRequirement(final AnnField field, AnnClass annC String[] hints = anno.hints(); if (hints != null && hints.length > 0) { - ((ComponentRequirementList)requirement).setRoleHints(Arrays.asList(hints)); + ((ComponentRequirementList) requirement).setRoleHints(Arrays.asList(hints)); } // // TODO: See if we can glean any type details out of any generic information from the map or collection // - } - else { + } else { requirement = new ComponentRequirement(); requirement.setRoleHint(filterEmptyAsNull(anno.hint())); } - // TODO need to read default annotation values + // TODO need to read default annotation values // if (anno.role()==null || anno.role().isAssignableFrom(Object.class)) { if (anno.role().isAssignableFrom(Object.class)) { requirement.setRole(type.getName()); - } - else { + } else { requirement.setRole(anno.role().getName()); } @@ -248,7 +227,7 @@ private ComponentRequirement findRequirement(final AnnField field, AnnClass annC requirement.setFieldMappingType(type.getName()); - requirement.setOptional( anno.optional() ); + requirement.setOptional(anno.optional()); return requirement; } @@ -267,7 +246,7 @@ private PlexusConfiguration findConfiguration(AnnField field, AnnClass c, ClassL name = field.getName(); } name = deHump(name); - + XmlPlexusConfiguration config = new XmlPlexusConfiguration(name); String value = filterEmptyAsNull(anno.value()); diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/ClassComponentGleaner.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/ClassComponentGleaner.java index d92b3e626..6ac719505 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/ClassComponentGleaner.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/ClassComponentGleaner.java @@ -22,11 +22,8 @@ * Interface for component gleaners which glean off of compiled classes.. * */ -public interface ClassComponentGleaner -{ +public interface ClassComponentGleaner { String ROLE = ClassComponentGleaner.class.getName(); - ComponentDescriptor glean(String className, ClassLoader cl) - throws ComponentGleanerException; - -} \ No newline at end of file + ComponentDescriptor glean(String className, ClassLoader cl) throws ComponentGleanerException; +} diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/ComponentGleanerException.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/ComponentGleanerException.java index dd96babfd..d198f2657 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/ComponentGleanerException.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/ComponentGleanerException.java @@ -27,21 +27,16 @@ /** * @author Trygve Laugstøl */ -public class ComponentGleanerException - extends Exception -{ - public ComponentGleanerException( String message ) - { - super( message ); +public class ComponentGleanerException extends Exception { + public ComponentGleanerException(String message) { + super(message); } - public ComponentGleanerException( String message, Throwable cause ) - { - super( message, cause ); + public ComponentGleanerException(String message, Throwable cause) { + super(message, cause); } - public ComponentGleanerException( Throwable cause ) - { - super( cause ); + public ComponentGleanerException(Throwable cause) { + super(cause); } -} \ No newline at end of file +} diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/ComponentGleanerSupport.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/ComponentGleanerSupport.java index 8168011ca..f047235bd 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/ComponentGleanerSupport.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/ComponentGleanerSupport.java @@ -27,8 +27,7 @@ * Support for component gleaner implementations. * */ -public abstract class ComponentGleanerSupport -{ +public abstract class ComponentGleanerSupport { private static final String EMPTY_STRING = ""; protected String filterEmptyAsNull(final String value) { @@ -73,4 +72,4 @@ protected String deHump(final String string) { return buff.toString().trim().toLowerCase(); } -} \ No newline at end of file +} diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/QDoxComponentGleaner.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/QDoxComponentGleaner.java index aac9dc44b..1f5f26622 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/QDoxComponentGleaner.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/QDoxComponentGleaner.java @@ -26,6 +26,10 @@ import java.util.*; +import com.thoughtworks.qdox.JavaProjectBuilder; +import com.thoughtworks.qdox.model.DocletTag; +import com.thoughtworks.qdox.model.JavaClass; +import com.thoughtworks.qdox.model.JavaField; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.ComponentRequirement; import org.codehaus.plexus.component.repository.ComponentRequirementList; @@ -34,20 +38,12 @@ import org.codehaus.plexus.personality.plexus.lifecycle.phase.*; import org.codehaus.plexus.util.StringUtils; -import com.thoughtworks.qdox.JavaProjectBuilder; -import com.thoughtworks.qdox.model.DocletTag; -import com.thoughtworks.qdox.model.JavaClass; -import com.thoughtworks.qdox.model.JavaField; - /** * A source component gleaner which uses QDox to discover Javadoc annotations. - * + * * @author Trygve Laugstøl */ -public class QDoxComponentGleaner - extends ComponentGleanerSupport - implements SourceComponentGleaner -{ +public class QDoxComponentGleaner extends ComponentGleanerSupport implements SourceComponentGleaner { public static final String PLEXUS_COMPONENT_TAG = "plexus.component"; public static final String PLEXUS_REQUIREMENT_TAG = "plexus.requirement"; @@ -78,13 +74,11 @@ public class QDoxComponentGleaner // ComponentGleaner Implementation // ---------------------------------------------------------------------- - public ComponentDescriptor glean( JavaProjectBuilder classCache, JavaClass javaClass ) - throws ComponentGleanerException - { - DocletTag tag = javaClass.getTagByName( PLEXUS_COMPONENT_TAG ); + public ComponentDescriptor glean(JavaProjectBuilder classCache, JavaClass javaClass) + throws ComponentGleanerException { + DocletTag tag = javaClass.getTagByName(PLEXUS_COMPONENT_TAG); - if ( tag == null ) - { + if (tag == null) { return null; } @@ -96,24 +90,22 @@ public ComponentDescriptor glean( JavaProjectBuilder classCache, JavaClass ja String fqn = javaClass.getFullyQualifiedName(); - //log.debug( "Creating descriptor for component: {}", fqn ); + // log.debug( "Creating descriptor for component: {}", fqn ); ComponentDescriptor componentDescriptor = new ComponentDescriptor(); - componentDescriptor.setImplementation( fqn ); + componentDescriptor.setImplementation(fqn); // ---------------------------------------------------------------------- // Role // ---------------------------------------------------------------------- - String role = getParameter( parameters, PLEXUS_ROLE_PARAMETER ); + String role = getParameter(parameters, PLEXUS_ROLE_PARAMETER); - if ( role == null ) - { - role = findRole( javaClass ); + if (role == null) { + role = findRole(javaClass); - if ( role == null ) - { + if (role == null) { /* log.warn( "Could not figure out a role for the component '" + fqn + "'. " + "Please specify a role with a parameter '" + PLEXUS_ROLE_PARAMETER + "' " + "on the @" + @@ -124,62 +116,61 @@ public ComponentDescriptor glean( JavaProjectBuilder classCache, JavaClass ja } } - componentDescriptor.setRole( role ); + componentDescriptor.setRole(role); // ---------------------------------------------------------------------- // Role hint // ---------------------------------------------------------------------- - String roleHint = getParameter( parameters, PLEXUS_ROLE_HINT_PARAMETER ); + String roleHint = getParameter(parameters, PLEXUS_ROLE_HINT_PARAMETER); - if ( roleHint != null ) - { + if (roleHint != null) { // getLogger().debug( " Role hint: " + roleHint ); } - componentDescriptor.setRoleHint( roleHint ); + componentDescriptor.setRoleHint(roleHint); // ---------------------------------------------------------------------- // Version // ---------------------------------------------------------------------- - String version = getParameter( parameters, PLEXUS_VERSION_PARAMETER ); + String version = getParameter(parameters, PLEXUS_VERSION_PARAMETER); - componentDescriptor.setVersion( version ); + componentDescriptor.setVersion(version); // ---------------------------------------------------------------------- // Lifecycle handler // ---------------------------------------------------------------------- - String lifecycleHandler = getParameter( parameters, PLEXUS_LIFECYCLE_HANDLER_PARAMETER ); + String lifecycleHandler = getParameter(parameters, PLEXUS_LIFECYCLE_HANDLER_PARAMETER); - componentDescriptor.setLifecycleHandler( lifecycleHandler ); + componentDescriptor.setLifecycleHandler(lifecycleHandler); // ---------------------------------------------------------------------- // Lifecycle handler // ---------------------------------------------------------------------- - String instatiationStrategy = getParameter( parameters, PLEXUS_INSTANTIATION_STARTEGY_PARAMETER ); + String instatiationStrategy = getParameter(parameters, PLEXUS_INSTANTIATION_STARTEGY_PARAMETER); - componentDescriptor.setInstantiationStrategy( instatiationStrategy ); + componentDescriptor.setInstantiationStrategy(instatiationStrategy); // ---------------------------------------------------------------------- // Alias // ---------------------------------------------------------------------- - componentDescriptor.setAlias( getParameter( parameters, PLEXUS_ALIAS_PARAMETER ) ); + componentDescriptor.setAlias(getParameter(parameters, PLEXUS_ALIAS_PARAMETER)); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - findExtraParameters( PLEXUS_COMPONENT_TAG, parameters ); + findExtraParameters(PLEXUS_COMPONENT_TAG, parameters); // ---------------------------------------------------------------------- // Requirements // ---------------------------------------------------------------------- - findRequirements( classCache, componentDescriptor, javaClass ); + findRequirements(classCache, componentDescriptor, javaClass); // ---------------------------------------------------------------------- // Description @@ -187,27 +178,25 @@ public ComponentDescriptor glean( JavaProjectBuilder classCache, JavaClass ja String comment = javaClass.getComment(); - if ( comment != null ) - { - int i = comment.indexOf( '.' ); + if (comment != null) { + int i = comment.indexOf('.'); - if ( i > 0 ) - { - comment = comment.substring( 0, i + 1 ); // include the dot + if (i > 0) { + comment = comment.substring(0, i + 1); // include the dot } } - componentDescriptor.setDescription( comment ); + componentDescriptor.setDescription(comment); // ---------------------------------------------------------------------- // Configuration // ---------------------------------------------------------------------- - XmlPlexusConfiguration configuration = new XmlPlexusConfiguration( "configuration" ); + XmlPlexusConfiguration configuration = new XmlPlexusConfiguration("configuration"); - findConfiguration( configuration, javaClass ); + findConfiguration(configuration, javaClass); - componentDescriptor.setConfiguration( configuration ); + componentDescriptor.setConfiguration(configuration); return componentDescriptor; } @@ -216,41 +205,34 @@ public ComponentDescriptor glean( JavaProjectBuilder classCache, JavaClass ja // // ---------------------------------------------------------------------- - private final static List IGNORED_INTERFACES = Collections.unmodifiableList( Arrays.asList( new String[]{ + private static final List IGNORED_INTERFACES = Collections.unmodifiableList(Arrays.asList(new String[] { LogEnabled.class.getName(), Initializable.class.getName(), Configurable.class.getName(), Contextualizable.class.getName(), Disposable.class.getName(), Startable.class.getName(), - } ) ); + })); - private static String getPackage( JavaClass javaClass ) - { - if ( javaClass.getPackage() != null ) - { + private static String getPackage(JavaClass javaClass) { + if (javaClass.getPackage() != null) { return javaClass.getPackage().getName(); - } - else - { + } else { return ""; } } - private String findRole( JavaClass javaClass ) - { + private String findRole(JavaClass javaClass) { // ---------------------------------------------------------------------- // Remove any Plexus specific interfaces from the calculation // ---------------------------------------------------------------------- - List interfaces = new ArrayList( javaClass.getInterfaces() ); + List interfaces = new ArrayList(javaClass.getInterfaces()); - for ( Iterator it = interfaces.iterator(); it.hasNext(); ) - { + for (Iterator it = interfaces.iterator(); it.hasNext(); ) { JavaClass ifc = it.next(); - if ( IGNORED_INTERFACES.contains( ifc.getFullyQualifiedName() ) ) - { + if (IGNORED_INTERFACES.contains(ifc.getFullyQualifiedName())) { it.remove(); } } @@ -309,31 +291,27 @@ private String findRole( JavaClass javaClass ) } } - if ( role == null ) - { + if (role == null) { JavaClass superClass = javaClass.getSuperJavaClass(); - if ( superClass != null ) - { - role = findRole( superClass ); + if (superClass != null) { + role = findRole(superClass); } } return role; } - private void findRequirements( JavaProjectBuilder classCache, ComponentDescriptor componentDescriptor, - JavaClass javaClass ) - { + private void findRequirements( + JavaProjectBuilder classCache, ComponentDescriptor componentDescriptor, JavaClass javaClass) { List fields = javaClass.getFields(); // ---------------------------------------------------------------------- // Search the super class for requirements // ---------------------------------------------------------------------- - if ( javaClass.getSuperJavaClass() != null ) - { - findRequirements( classCache, componentDescriptor, javaClass.getSuperJavaClass() ); + if (javaClass.getSuperJavaClass() != null) { + findRequirements(classCache, componentDescriptor, javaClass.getSuperJavaClass()); } // ---------------------------------------------------------------------- @@ -355,8 +333,8 @@ private void findRequirements( JavaProjectBuilder classCache, ComponentDescripto String requirementClass = field.getType().getFullyQualifiedName(); - boolean isMap = requirementClass.equals(Map.class.getName()) || - requirementClass.equals(Collection.class.getName()); + boolean isMap = + requirementClass.equals(Map.class.getName()) || requirementClass.equals(Collection.class.getName()); try { isMap = isMap || Collection.class.isAssignableFrom(Class.forName(requirementClass)); @@ -440,18 +418,16 @@ private void findRequirements( JavaProjectBuilder classCache, ComponentDescripto } } - private void findConfiguration( XmlPlexusConfiguration configuration, JavaClass javaClass ) - throws ComponentGleanerException - { + private void findConfiguration(XmlPlexusConfiguration configuration, JavaClass javaClass) + throws ComponentGleanerException { List fields = javaClass.getFields(); // ---------------------------------------------------------------------- // Search the super class for configurable fields. // ---------------------------------------------------------------------- - if ( javaClass.getSuperJavaClass() != null ) - { - findConfiguration( configuration, javaClass.getSuperJavaClass() ); + if (javaClass.getSuperJavaClass() != null) { + findConfiguration(configuration, javaClass.getSuperJavaClass()); } // ---------------------------------------------------------------------- @@ -487,7 +463,7 @@ private void findConfiguration( XmlPlexusConfiguration configuration, JavaClass c.setValue(defaultValue); - //log.debug( " Configuration: {}={}", name, defaultValue ); + // log.debug( " Configuration: {}={}", name, defaultValue ); configuration.addChild(c); @@ -499,19 +475,16 @@ private void findConfiguration( XmlPlexusConfiguration configuration, JavaClass // // ---------------------------------------------------------------------- - private void findExtraParameters( String tagName, Map parameters ) - { + private void findExtraParameters(String tagName, Map parameters) { for (String s : parameters.keySet()) { - //log.warn( "Extra parameter on the '" + tagName + "' tag: '" + s + "'." ); + // log.warn( "Extra parameter on the '" + tagName + "' tag: '" + s + "'." ); } } - private String getParameter( Map parameters, String parameter ) - { - String value = parameters.remove( parameter ); + private String getParameter(Map parameters, String parameter) { + String value = parameters.remove(parameter); - if ( StringUtils.isEmpty( value ) ) - { + if (StringUtils.isEmpty(value)) { return null; } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/SourceComponentGleaner.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/SourceComponentGleaner.java index e3402fb49..63cd4b1ea 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/SourceComponentGleaner.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/gleaner/SourceComponentGleaner.java @@ -16,19 +16,16 @@ * limitations under the License. */ -import org.codehaus.plexus.component.repository.ComponentDescriptor; - import com.thoughtworks.qdox.JavaProjectBuilder; import com.thoughtworks.qdox.model.JavaClass; +import org.codehaus.plexus.component.repository.ComponentDescriptor; /** * Interface for component gleaners which glean off of source code. * */ -public interface SourceComponentGleaner -{ +public interface SourceComponentGleaner { String ROLE = SourceComponentGleaner.class.getName(); - ComponentDescriptor glean( JavaProjectBuilder classCache, JavaClass javaClass ) - throws ComponentGleanerException; -} \ No newline at end of file + ComponentDescriptor glean(JavaProjectBuilder classCache, JavaClass javaClass) throws ComponentGleanerException; +} diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/AbstractMerger.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/AbstractMerger.java index f20a06f1a..b1def85b8 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/AbstractMerger.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/AbstractMerger.java @@ -2,18 +2,18 @@ /* * The MIT License - * + * * Copyright (c) 2006, The Codehaus - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, @@ -32,86 +32,61 @@ import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; -import org.jdom2.input.sax.XMLReaderJDOMFactory; import org.jdom2.input.sax.XMLReaderSAX2Factory; import org.jdom2.output.XMLOutputter; -import org.xml.sax.XMLReader; /** * Base class for common mergers. - * + * * @author Brett Porter */ -public abstract class AbstractMerger - implements Merger -{ +public abstract class AbstractMerger implements Merger { /** * @see org.codehaus.plexus.metadata.merge.Merger#writeMergedDocument(org.jdom2.Document, * java.io.File) */ - public void writeMergedDocument( Document mergedDocument, File file ) - throws IOException - { - if ( !file.getParentFile().exists() ) - { + public void writeMergedDocument(Document mergedDocument, File file) throws IOException { + if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } XMLOutputter out = new XMLOutputter(); Writer fw = null; - try - { - fw = new OutputStreamWriter( new FileOutputStream( file ), "UTF-8" ); - out.output( mergedDocument, fw ); - } - finally - { - IOUtil.close( fw ); + try { + fw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); + out.output(mergedDocument, fw); + } finally { + IOUtil.close(fw); } } - public void mergeDescriptors( File outputDescriptor, List descriptors ) - throws IOException - { - SAXBuilder builder = new SAXBuilder( new XMLReaderSAX2Factory( false, Driver.class.getName() ) ); - + public void mergeDescriptors(File outputDescriptor, List descriptors) throws IOException { + SAXBuilder builder = new SAXBuilder(new XMLReaderSAX2Factory(false, Driver.class.getName())); + Document finalDoc = null; - for ( File f : descriptors ) - { - try - { - Document doc = builder.build( f ); + for (File f : descriptors) { + try { + Document doc = builder.build(f); - if ( finalDoc != null ) - { + if (finalDoc != null) { // Last specified has dominance - finalDoc = merge( doc, finalDoc ); - } - else - { + finalDoc = merge(doc, finalDoc); + } else { finalDoc = doc; } - } - catch ( JDOMException e ) - { - throw new IOException( "Invalid input descriptor for merge: " + f + " --> " + e.getMessage() ); - } - catch ( MergeException e ) - { - throw new IOException( "Error merging descriptor: " + f + " --> " + e.getMessage() ); + } catch (JDOMException e) { + throw new IOException("Invalid input descriptor for merge: " + f + " --> " + e.getMessage()); + } catch (MergeException e) { + throw new IOException("Error merging descriptor: " + f + " --> " + e.getMessage()); } } - if ( finalDoc != null ) - { - try - { - writeMergedDocument( finalDoc, outputDescriptor ); - } - catch ( IOException e ) - { - throw new IOException( "Error writing merged descriptor: " + outputDescriptor ); + if (finalDoc != null) { + try { + writeMergedDocument(finalDoc, outputDescriptor); + } catch (IOException e) { + throw new IOException("Error writing merged descriptor: " + outputDescriptor); } } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/ComponentsXmlMerger.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/ComponentsXmlMerger.java index 03f49bcec..dc1875542 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/ComponentsXmlMerger.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/ComponentsXmlMerger.java @@ -31,25 +31,20 @@ /** * @author Rahul Thakur */ -@Component(role=Merger.class,hint="componentsXml") -public class ComponentsXmlMerger - extends AbstractMerger -{ +@Component(role = Merger.class, hint = "componentsXml") +public class ComponentsXmlMerger extends AbstractMerger { /** * @see Merger#merge(Document, Document) */ - public Document merge( Document dDocument, Document rDocument ) - throws MergeException - { + public Document merge(Document dDocument, Document rDocument) throws MergeException { // TODO: Ideally we don't want to manipulate the original // dominant document but use its copy for merge. - //Document mDoc = (Document) dDocument.clone(); // doesn't merge properly + // Document mDoc = (Document) dDocument.clone(); // doesn't merge properly Document mDoc = dDocument; - ComponentSetElement dCSE = new ComponentSetElement( mDoc.getRootElement() ); - ComponentSetElement rCSE = new ComponentSetElement( rDocument.getRootElement() ); - dCSE.merge( rCSE ); + ComponentSetElement dCSE = new ComponentSetElement(mDoc.getRootElement()); + ComponentSetElement rCSE = new ComponentSetElement(rDocument.getRootElement()); + dCSE.merge(rCSE); // the contents are merged into the dominant document DOM. return mDoc; } - } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/Driver.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/Driver.java index e9ed66a3d..9edbdc16b 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/Driver.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/Driver.java @@ -3,32 +3,27 @@ package org.codehaus.plexus.metadata.merge; -import java.io.InputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; +import java.io.InputStream; import java.io.Reader; - -// not J2ME classes -- remove if you want to run in MIDP devices -import java.net.URL; import java.net.MalformedURLException; - - -// not J2ME classes -import java.io.FileInputStream; -import java.io.FileNotFoundException; +import java.net.URL; import org.codehaus.plexus.util.xml.pull.XmlPullParser; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.xml.sax.Attributes; -import org.xml.sax.DTDHandler; import org.xml.sax.ContentHandler; +import org.xml.sax.DTDHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; +import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; @@ -38,148 +33,152 @@ * * @author Aleksander Slominski */ - -public class Driver implements Locator, XMLReader, Attributes -{ +public class Driver implements Locator, XMLReader, Attributes { protected static final String EXTERNAL_GENERAL_ENTITIES_PROPERTY = - "http://xml.org/sax/features/external-general-entities"; + "http://xml.org/sax/features/external-general-entities"; - protected static final String DECLARATION_HANDLER_PROPERTY = - "http://xml.org/sax/properties/declaration-handler"; + protected static final String DECLARATION_HANDLER_PROPERTY = "http://xml.org/sax/properties/declaration-handler"; - protected static final String LEXICAL_HANDLER_PROPERTY = - "http://xml.org/sax/properties/lexical-handler"; + protected static final String LEXICAL_HANDLER_PROPERTY = "http://xml.org/sax/properties/lexical-handler"; - protected static final String NAMESPACES_FEATURE = - "http://xml.org/sax/features/namespaces"; + protected static final String NAMESPACES_FEATURE = "http://xml.org/sax/features/namespaces"; - protected static final String NAMESPACE_PREFIXES_FEATURE = - "http://xml.org/sax/features/namespace-prefixes"; + protected static final String NAMESPACE_PREFIXES_FEATURE = "http://xml.org/sax/features/namespace-prefixes"; - protected static final String VALIDATION_FEATURE = - "http://xml.org/sax/features/validation"; + protected static final String VALIDATION_FEATURE = "http://xml.org/sax/features/validation"; - protected static final String APACHE_SCHEMA_VALIDATION_FEATURE = - "http://apache.org/xml/features/validation/schema"; + protected static final String APACHE_SCHEMA_VALIDATION_FEATURE = "http://apache.org/xml/features/validation/schema"; protected static final String APACHE_DYNAMIC_VALIDATION_FEATURE = - "http://apache.org/xml/features/validation/dynamic"; + "http://apache.org/xml/features/validation/dynamic"; protected ContentHandler contentHandler = new DefaultHandler(); - protected ErrorHandler errorHandler = new DefaultHandler();; + protected ErrorHandler errorHandler = new DefaultHandler(); + ; protected String systemId; protected XmlPullParser pp; - public Driver() throws XmlPullParserException - { + public Driver() throws XmlPullParserException { pp = new MXParser(); - - try - { - setFeature( NAMESPACES_FEATURE, true ); - setFeature( NAMESPACE_PREFIXES_FEATURE, true ); - - } - catch ( Exception e ) - { + + try { + setFeature(NAMESPACES_FEATURE, true); + setFeature(NAMESPACE_PREFIXES_FEATURE, true); + + } catch (Exception e) { e.printStackTrace(); } } - + // -- Attributes interface - public int getLength() { return pp.getAttributeCount(); } - public String getURI(int index) { return pp.getAttributeNamespace(index); } - public String getLocalName(int index) { return pp.getAttributeName(index); } + public int getLength() { + return pp.getAttributeCount(); + } + + public String getURI(int index) { + return pp.getAttributeNamespace(index); + } + + public String getLocalName(int index) { + return pp.getAttributeName(index); + } + public String getQName(int index) { final String prefix = pp.getAttributePrefix(index); - if(prefix != null) { - return prefix+':'+pp.getAttributeName(index); + if (prefix != null) { + return prefix + ':' + pp.getAttributeName(index); } else { return pp.getAttributeName(index); } } - public String getType(int index) { return pp.getAttributeType(index); } - public String getValue(int index) { return pp.getAttributeValue(index); } + + public String getType(int index) { + return pp.getAttributeType(index); + } + + public String getValue(int index) { + return pp.getAttributeValue(index); + } public int getIndex(String uri, String localName) { - for (int i = 0; i < pp.getAttributeCount(); i++) - { - if(pp.getAttributeNamespace(i).equals(uri) - && pp.getAttributeName(i).equals(localName)) - { + for (int i = 0; i < pp.getAttributeCount(); i++) { + if (pp.getAttributeNamespace(i).equals(uri) + && pp.getAttributeName(i).equals(localName)) { return i; } - } return -1; } public int getIndex(String qName) { - for (int i = 0; i < pp.getAttributeCount(); i++) - { - if(pp.getAttributeName(i).equals(qName)) - { + for (int i = 0; i < pp.getAttributeCount(); i++) { + if (pp.getAttributeName(i).equals(qName)) { return i; } - } return -1; } public String getType(String uri, String localName) { - for (int i = 0; i < pp.getAttributeCount(); i++) - { - if(pp.getAttributeNamespace(i).equals(uri) - && pp.getAttributeName(i).equals(localName)) - { + for (int i = 0; i < pp.getAttributeCount(); i++) { + if (pp.getAttributeNamespace(i).equals(uri) + && pp.getAttributeName(i).equals(localName)) { return pp.getAttributeType(i); } - } return null; } + public String getType(String qName) { - for (int i = 0; i < pp.getAttributeCount(); i++) - { - if(pp.getAttributeName(i).equals(qName)) - { + for (int i = 0; i < pp.getAttributeCount(); i++) { + if (pp.getAttributeName(i).equals(qName)) { return pp.getAttributeType(i); } - } return null; } + public String getValue(String uri, String localName) { return pp.getAttributeValue(uri, localName); } + public String getValue(String qName) { return pp.getAttributeValue(null, qName); } // -- Locator interface - public String getPublicId() { return null; } - public String getSystemId() { return systemId; } - public int getLineNumber() { return pp.getLineNumber(); } - public int getColumnNumber() { return pp.getColumnNumber(); } + public String getPublicId() { + return null; + } + + public String getSystemId() { + return systemId; + } + + public int getLineNumber() { + return pp.getLineNumber(); + } + + public int getColumnNumber() { + return pp.getColumnNumber(); + } // --- XMLReader interface - //"http://xml.org/sax/features/namespaces", - //true - - public boolean getFeature(String name) - throws SAXNotRecognizedException, SAXNotSupportedException - { - if(NAMESPACES_FEATURE.equals(name)) { + // "http://xml.org/sax/features/namespaces", + // true + + public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { + if (NAMESPACES_FEATURE.equals(name)) { return pp.getFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES); - } else if(NAMESPACE_PREFIXES_FEATURE.equals(name)) { + } else if (NAMESPACE_PREFIXES_FEATURE.equals(name)) { return pp.getFeature(XmlPullParser.FEATURE_REPORT_NAMESPACE_ATTRIBUTES); - } else if(VALIDATION_FEATURE.equals(name)) { + } else if (VALIDATION_FEATURE.equals(name)) { return pp.getFeature(XmlPullParser.FEATURE_VALIDATION); // } else if(APACHE_SCHEMA_VALIDATION_FEATURE.equals(name)) { // return false; //TODO @@ -187,87 +186,87 @@ public boolean getFeature(String name) // return false; //TODO } else { return pp.getFeature(name); - //throw new SAXNotRecognizedException("unrecognized feature "+name); + // throw new SAXNotRecognizedException("unrecognized feature "+name); } } - public void setFeature (String name, boolean value) - throws SAXNotRecognizedException, SAXNotSupportedException - { + public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { try { - if(NAMESPACES_FEATURE.equals(name)) { + if (NAMESPACES_FEATURE.equals(name)) { pp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, value); - } else if(NAMESPACE_PREFIXES_FEATURE.equals(name)) { - if(pp.getFeature(XmlPullParser.FEATURE_REPORT_NAMESPACE_ATTRIBUTES) != value) { + } else if (NAMESPACE_PREFIXES_FEATURE.equals(name)) { + if (pp.getFeature(XmlPullParser.FEATURE_REPORT_NAMESPACE_ATTRIBUTES) != value) { pp.setFeature(XmlPullParser.FEATURE_REPORT_NAMESPACE_ATTRIBUTES, value); } - } else if(VALIDATION_FEATURE.equals(name)) { + } else if (VALIDATION_FEATURE.equals(name)) { pp.setFeature(XmlPullParser.FEATURE_VALIDATION, value); - } else if(EXTERNAL_GENERAL_ENTITIES_PROPERTY.equals(name)) { + } else if (EXTERNAL_GENERAL_ENTITIES_PROPERTY.equals(name)) { // ignore } else { pp.setFeature(name, value); - //throw new SAXNotRecognizedException("unrecognized feature "+name); + // throw new SAXNotRecognizedException("unrecognized feature "+name); } - } catch(XmlPullParserException ex) { - throw new SAXNotSupportedException("problem with setting feature "+name+": "+ex); + } catch (XmlPullParserException ex) { + throw new SAXNotSupportedException("problem with setting feature " + name + ": " + ex); } } - public Object getProperty (String name) - throws SAXNotRecognizedException, SAXNotSupportedException - { - if(DECLARATION_HANDLER_PROPERTY.equals(name)) { + public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException { + if (DECLARATION_HANDLER_PROPERTY.equals(name)) { return null; - } else if(LEXICAL_HANDLER_PROPERTY.equals(name)) { + } else if (LEXICAL_HANDLER_PROPERTY.equals(name)) { return null; } else { return pp.getProperty(name); - //throw new SAXNotRecognizedException("not recognized get property "+name); + // throw new SAXNotRecognizedException("not recognized get property "+name); } } - public void setProperty (String name, Object value) - throws SAXNotRecognizedException, SAXNotSupportedException - { + public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { // - if(DECLARATION_HANDLER_PROPERTY.equals(name)) { - throw new SAXNotSupportedException("not supported setting property "+name);//+" to "+value); - } else if(LEXICAL_HANDLER_PROPERTY.equals(name)) { - throw new SAXNotSupportedException("not supported setting property "+name);//+" to "+value); + if (DECLARATION_HANDLER_PROPERTY.equals(name)) { + throw new SAXNotSupportedException("not supported setting property " + name); // +" to "+value); + } else if (LEXICAL_HANDLER_PROPERTY.equals(name)) { + throw new SAXNotSupportedException("not supported setting property " + name); // +" to "+value); } else { try { pp.setProperty(name, value); - } catch(XmlPullParserException ex) { - throw new SAXNotSupportedException("not supported set property "+name+": "+ ex); + } catch (XmlPullParserException ex) { + throw new SAXNotSupportedException("not supported set property " + name + ": " + ex); } - //throw new SAXNotRecognizedException("not recognized set property "+name); + // throw new SAXNotRecognizedException("not recognized set property "+name); } } - public void setEntityResolver (EntityResolver resolver) {} + public void setEntityResolver(EntityResolver resolver) {} - public EntityResolver getEntityResolver () { return null; } + public EntityResolver getEntityResolver() { + return null; + } - public void setDTDHandler (DTDHandler handler) {} + public void setDTDHandler(DTDHandler handler) {} - public DTDHandler getDTDHandler () { return null; } + public DTDHandler getDTDHandler() { + return null; + } - public void setContentHandler (ContentHandler handler) - { + public void setContentHandler(ContentHandler handler) { this.contentHandler = handler; } - public ContentHandler getContentHandler() { return contentHandler; } + public ContentHandler getContentHandler() { + return contentHandler; + } public void setErrorHandler(ErrorHandler handler) { this.errorHandler = handler; } - public ErrorHandler getErrorHandler() { return errorHandler; } + public ErrorHandler getErrorHandler() { + return errorHandler; + } - public void parse(InputSource source) throws SAXException, IOException - { + public void parse(InputSource source) throws SAXException, IOException { systemId = source.getSystemId(); contentHandler.setDocumentLocator(this); @@ -280,9 +279,8 @@ public void parse(InputSource source) throws SAXException, IOException if (stream == null) { systemId = source.getSystemId(); - if(systemId == null) { - SAXParseException saxException = new SAXParseException( - "null source systemId" , this); + if (systemId == null) { + SAXParseException saxException = new SAXParseException("null source systemId", this); errorHandler.fatalError(saxException); return; } @@ -294,8 +292,8 @@ public void parse(InputSource source) throws SAXException, IOException try { stream = new FileInputStream(systemId); } catch (FileNotFoundException fnfe) { - final SAXParseException saxException = new SAXParseException( - "could not open file with systemId "+systemId, this, fnfe); + final SAXParseException saxException = + new SAXParseException("could not open file with systemId " + systemId, this, fnfe); errorHandler.fatalError(saxException); return; } @@ -305,10 +303,10 @@ public void parse(InputSource source) throws SAXException, IOException } else { pp.setInput(reader); } - } catch (XmlPullParserException ex) { - final SAXParseException saxException = new SAXParseException( - "parsing initialization error: "+ex, this, ex); - //if(DEBUG) ex.printStackTrace(); + } catch (XmlPullParserException ex) { + final SAXParseException saxException = + new SAXParseException("parsing initialization error: " + ex, this, ex); + // if(DEBUG) ex.printStackTrace(); errorHandler.fatalError(saxException); return; } @@ -319,17 +317,17 @@ public void parse(InputSource source) throws SAXException, IOException // get first event pp.next(); // it should be start tag... - if(pp.getEventType() != XmlPullParser.START_TAG) { - final SAXParseException saxException = new SAXParseException( - "expected start tag not"+pp.getPositionDescription(), this); - //throw saxException; + if (pp.getEventType() != XmlPullParser.START_TAG) { + final SAXParseException saxException = + new SAXParseException("expected start tag not" + pp.getPositionDescription(), this); + // throw saxException; errorHandler.fatalError(saxException); return; } - } catch (XmlPullParserException ex) { - final SAXParseException saxException = new SAXParseException( - "parsing initialization error: "+ex, this, ex); - //ex.printStackTrace(); + } catch (XmlPullParserException ex) { + final SAXParseException saxException = + new SAXParseException("parsing initialization error: " + ex, this, ex); + // ex.printStackTrace(); errorHandler.fatalError(saxException); return; } @@ -347,14 +345,12 @@ public void parse(String systemId) throws SAXException, IOException { parse(new InputSource(systemId)); } - public void parseSubTree(XmlPullParser pp) throws SAXException, IOException { this.pp = pp; final boolean namespaceAware = pp.getFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES); try { - if(pp.getEventType() != XmlPullParser.START_TAG) { - throw new SAXException( - "start tag must be read before skiping subtree"+pp.getPositionDescription()); + if (pp.getEventType() != XmlPullParser.START_TAG) { + throw new SAXException("start tag must be read before skiping subtree" + pp.getPositionDescription()); } final int[] holderForStartAndLength = new int[2]; final StringBuilder rawName = new StringBuilder(16); @@ -365,89 +361,71 @@ public void parseSubTree(XmlPullParser pp) throws SAXException, IOException { LOOP: do { - switch(type) { + switch (type) { case XmlPullParser.START_TAG: - if(namespaceAware) { + if (namespaceAware) { final int depth = pp.getDepth() - 1; - final int countPrev = - (level > depth) ? pp.getNamespaceCount(depth) : 0; - //int countPrev = pp.getNamespaceCount(pp.getDepth() - 1); + final int countPrev = (level > depth) ? pp.getNamespaceCount(depth) : 0; + // int countPrev = pp.getNamespaceCount(pp.getDepth() - 1); final int count = pp.getNamespaceCount(depth + 1); - for (int i = countPrev; i < count; i++) - { - contentHandler.startPrefixMapping( - pp.getNamespacePrefix(i), - pp.getNamespaceUri(i) - ); + for (int i = countPrev; i < count; i++) { + contentHandler.startPrefixMapping(pp.getNamespacePrefix(i), pp.getNamespaceUri(i)); } name = pp.getName(); prefix = pp.getPrefix(); - if(prefix != null) { + if (prefix != null) { rawName.setLength(0); rawName.append(prefix); rawName.append(':'); rawName.append(name); } - startElement(pp.getNamespace(), - name, - prefix != null ? name : rawName.toString()); + startElement(pp.getNamespace(), name, prefix != null ? name : rawName.toString()); } else { - startElement(pp.getNamespace(), - pp.getName(), - pp.getName()); + startElement(pp.getNamespace(), pp.getName(), pp.getName()); } - //++level; + // ++level; break; case XmlPullParser.TEXT: final char[] chars = pp.getTextCharacters(holderForStartAndLength); - contentHandler.characters(chars, - holderForStartAndLength[0], //start - holderForStartAndLength[1] //len - ); + contentHandler.characters( + chars, + holderForStartAndLength[0], // start + holderForStartAndLength[1] // len + ); break; case XmlPullParser.END_TAG: - //--level; - if(namespaceAware) { + // --level; + if (namespaceAware) { name = pp.getName(); prefix = pp.getPrefix(); - if(prefix != null) { + if (prefix != null) { rawName.setLength(0); rawName.append(prefix); rawName.append(':'); rawName.append(name); } - contentHandler.endElement(pp.getNamespace(), - name, - prefix != null ? name : rawName.toString() - ); + contentHandler.endElement( + pp.getNamespace(), name, prefix != null ? name : rawName.toString()); // when entering show prefixes for all levels!!!! final int depth = pp.getDepth(); - final int countPrev = - (level > depth) ? pp.getNamespaceCount(pp.getDepth()) : 0; + final int countPrev = (level > depth) ? pp.getNamespaceCount(pp.getDepth()) : 0; int count = pp.getNamespaceCount(pp.getDepth() - 1); // undeclare them in reverse order - for (int i = count - 1; i >= countPrev; i--) - { - contentHandler.endPrefixMapping( - pp.getNamespacePrefix(i) - ); + for (int i = count - 1; i >= countPrev; i--) { + contentHandler.endPrefixMapping(pp.getNamespacePrefix(i)); } } else { - contentHandler.endElement(pp.getNamespace(), - pp.getName(), - pp.getName() - ); - + contentHandler.endElement(pp.getNamespace(), pp.getName(), pp.getName()); } break; case XmlPullParser.END_DOCUMENT: break LOOP; } type = pp.next(); - } while(pp.getDepth() > level); - } catch (XmlPullParserException ex) { - final SAXParseException saxException = new SAXParseException("parsing error: "+ex, this, ex); + } while (pp.getDepth() > level); + } catch (XmlPullParserException ex) { + final SAXParseException saxException = new SAXParseException("parsing error: " + ex, this, ex); ex.printStackTrace(); errorHandler.fatalError(saxException); } @@ -467,5 +445,4 @@ public void parseSubTree(XmlPullParser pp) throws SAXException, IOException { protected void startElement(String namespace, String localName, String qName) throws SAXException { contentHandler.startElement(namespace, localName, qName, this); } - } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/MXParser.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/MXParser.java index 8ccf0085d..f8040f6c3 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/MXParser.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/MXParser.java @@ -18,14 +18,14 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParser; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -//import java.util.Hashtable; +// import java.util.Hashtable; -//TODO best handling of interning issues +// TODO best handling of interning issues // have isAllNewStringInterned ??? -//TODO handling surrogate pairs: http://www.unicode.org/unicode/faq/utf_bom.html#6 +// TODO handling surrogate pairs: http://www.unicode.org/unicode/faq/utf_bom.html#6 -//TODO review code for use of bufAbsoluteStart when keeping pos between next()/fillBuf() +// TODO review code for use of bufAbsoluteStart when keeping pos between next()/fillBuf() /** * Absolutely minimal implementation of XMLPULL V1 API. Encoding handling done with XmlReader @@ -33,30 +33,24 @@ * @see org.codehaus.plexus.util.xml.XmlReader * @author Aleksander Slominski */ - -public class MXParser - implements XmlPullParser -{ - //NOTE: no interning of those strings --> by Java leng spec they MUST be already interned - protected final static String XML_URI = "http://www.w3.org/XML/1998/namespace"; - protected final static String XMLNS_URI = "http://www.w3.org/2000/xmlns/"; - protected final static String FEATURE_XML_ROUNDTRIP= - //"http://xmlpull.org/v1/doc/features.html#xml-roundtrip"; - "http://xmlpull.org/v1/doc/features.html#xml-roundtrip"; - protected final static String FEATURE_NAMES_INTERNED = - "http://xmlpull.org/v1/doc/features.html#names-interned"; - protected final static String PROPERTY_XMLDECL_VERSION = - "http://xmlpull.org/v1/doc/properties.html#xmldecl-version"; - protected final static String PROPERTY_XMLDECL_STANDALONE = - "http://xmlpull.org/v1/doc/properties.html#xmldecl-standalone"; - protected final static String PROPERTY_XMLDECL_CONTENT = - "http://xmlpull.org/v1/doc/properties.html#xmldecl-content"; - protected final static String PROPERTY_LOCATION = - "http://xmlpull.org/v1/doc/properties.html#location"; - - - protected final static String REPORT_NAMESPACE_PREFIXES = - "http://xmlpull.org/v1/doc/features.html#report-namespace-prefixes"; +public class MXParser implements XmlPullParser { + // NOTE: no interning of those strings --> by Java leng spec they MUST be already interned + protected static final String XML_URI = "http://www.w3.org/XML/1998/namespace"; + protected static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/"; + protected static final String FEATURE_XML_ROUNDTRIP = + // "http://xmlpull.org/v1/doc/features.html#xml-roundtrip"; + "http://xmlpull.org/v1/doc/features.html#xml-roundtrip"; + protected static final String FEATURE_NAMES_INTERNED = "http://xmlpull.org/v1/doc/features.html#names-interned"; + protected static final String PROPERTY_XMLDECL_VERSION = + "http://xmlpull.org/v1/doc/properties.html#xmldecl-version"; + protected static final String PROPERTY_XMLDECL_STANDALONE = + "http://xmlpull.org/v1/doc/properties.html#xmldecl-standalone"; + protected static final String PROPERTY_XMLDECL_CONTENT = + "http://xmlpull.org/v1/doc/properties.html#xmldecl-content"; + protected static final String PROPERTY_LOCATION = "http://xmlpull.org/v1/doc/properties.html#location"; + + protected static final String REPORT_NAMESPACE_PREFIXES = + "http://xmlpull.org/v1/doc/features.html#report-namespace-prefixes"; /** * Implementation notice: * the is instance variable that controls if newString() is interning. @@ -104,20 +98,19 @@ public class MXParser protected String elName[]; protected String elPrefix[]; protected String elUri[]; - //protected String elValue[]; + // protected String elValue[]; protected int elNamespaceCount[]; // input buffer management - protected static final int READ_CHUNK_SIZE = 8*1024; //max data chars in one read() call + protected static final int READ_CHUNK_SIZE = 8 * 1024; // max data chars in one read() call protected Reader reader; protected String inputEncoding; - - protected int bufLoadFactor = 95; // 99% - //protected int bufHardLimit; // only matters when expanding + protected int bufLoadFactor = 95; // 99% + // protected int bufHardLimit; // only matters when expanding protected char buf[] = new char[READ_CHUNK_SIZE]; - protected int bufSoftLimit = ( bufLoadFactor * buf.length ) /100; + protected int bufSoftLimit = (bufLoadFactor * buf.length) / 100; protected boolean preventBufferCompaction; protected int bufAbsoluteStart; // this is buf @@ -132,7 +125,7 @@ public class MXParser protected int pcEnd; protected void resetStringCache() { - //System.out.println("resetStringCache() minimum called"); + // System.out.println("resetStringCache() minimum called"); } protected String newString(char[] cbuf, int off, int len) { @@ -145,34 +138,33 @@ protected String newStringIntern(char[] cbuf, int off, int len) { private static final boolean TRACE_SIZING = false; - /** * Make sure that we have enough space to keep element stack if passed size. * It will always create one additional slot then current depth */ protected void ensureElementsCapacity() { final int elStackSize = elName != null ? elName.length : 0; - if( (depth + 1) >= elStackSize) { + if ((depth + 1) >= elStackSize) { // we add at least one extra slot ... final int newSize = (depth >= 7 ? 2 * depth : 8) + 2; // = lucky 7 + 1 //25 - if(TRACE_SIZING) { - System.err.println("TRACE_SIZING elStackSize "+elStackSize+" ==> "+newSize); + if (TRACE_SIZING) { + System.err.println("TRACE_SIZING elStackSize " + elStackSize + " ==> " + newSize); } final boolean needsCopying = elStackSize > 0; String[] arr = null; // resue arr local variable slot arr = new String[newSize]; - if(needsCopying) System.arraycopy(elName, 0, arr, 0, elStackSize); + if (needsCopying) System.arraycopy(elName, 0, arr, 0, elStackSize); elName = arr; arr = new String[newSize]; - if(needsCopying) System.arraycopy(elPrefix, 0, arr, 0, elStackSize); + if (needsCopying) System.arraycopy(elPrefix, 0, arr, 0, elStackSize); elPrefix = arr; arr = new String[newSize]; - if(needsCopying) System.arraycopy(elUri, 0, arr, 0, elStackSize); + if (needsCopying) System.arraycopy(elUri, 0, arr, 0, elStackSize); elUri = arr; int[] iarr = new int[newSize]; - if(needsCopying) { + if (needsCopying) { System.arraycopy(elNamespaceCount, 0, iarr, 0, elStackSize); } else { // special initialization @@ -180,21 +172,21 @@ protected void ensureElementsCapacity() { } elNamespaceCount = iarr; - //TODO: avoid using element raw name ... + // TODO: avoid using element raw name ... iarr = new int[newSize]; - if(needsCopying) { + if (needsCopying) { System.arraycopy(elRawNameEnd, 0, iarr, 0, elStackSize); } elRawNameEnd = iarr; iarr = new int[newSize]; - if(needsCopying) { + if (needsCopying) { System.arraycopy(elRawNameLine, 0, iarr, 0, elStackSize); } elRawNameLine = iarr; final char[][] carr = new char[newSize][]; - if(needsCopying) { + if (needsCopying) { System.arraycopy(elRawName, 0, carr, 0, elStackSize); } elRawName = carr; @@ -211,58 +203,55 @@ protected void ensureElementsCapacity() { // iarr[i] = (i > 0) ? -1 : 0; // } // elNsStackPos = iarr; - //assert depth < elName.length; + // assert depth < elName.length; } } - - // attribute stack protected int attributeCount; protected String attributeName[]; protected int attributeNameHash[]; - //protected int attributeNameStart[]; - //protected int attributeNameEnd[]; + // protected int attributeNameStart[]; + // protected int attributeNameEnd[]; protected String attributePrefix[]; protected String attributeUri[]; protected String attributeValue[]; - //protected int attributeValueStart[]; - //protected int attributeValueEnd[]; - + // protected int attributeValueStart[]; + // protected int attributeValueEnd[]; /** * Make sure that in attributes temporary array is enough space. * @param size The size. */ - protected void ensureAttributesCapacity(int size) { + protected void ensureAttributesCapacity(int size) { final int attrPosSize = attributeName != null ? attributeName.length : 0; - if(size >= attrPosSize) { + if (size >= attrPosSize) { final int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25 - if(TRACE_SIZING) { - System.err.println("TRACE_SIZING attrPosSize "+attrPosSize+" ==> "+newSize); + if (TRACE_SIZING) { + System.err.println("TRACE_SIZING attrPosSize " + attrPosSize + " ==> " + newSize); } final boolean needsCopying = attrPosSize > 0; String[] arr = null; arr = new String[newSize]; - if(needsCopying) System.arraycopy(attributeName, 0, arr, 0, attrPosSize); + if (needsCopying) System.arraycopy(attributeName, 0, arr, 0, attrPosSize); attributeName = arr; arr = new String[newSize]; - if(needsCopying) System.arraycopy(attributePrefix, 0, arr, 0, attrPosSize); + if (needsCopying) System.arraycopy(attributePrefix, 0, arr, 0, attrPosSize); attributePrefix = arr; arr = new String[newSize]; - if(needsCopying) System.arraycopy(attributeUri, 0, arr, 0, attrPosSize); + if (needsCopying) System.arraycopy(attributeUri, 0, arr, 0, attrPosSize); attributeUri = arr; arr = new String[newSize]; - if(needsCopying) System.arraycopy(attributeValue, 0, arr, 0, attrPosSize); + if (needsCopying) System.arraycopy(attributeValue, 0, arr, 0, attrPosSize); attributeValue = arr; - if( ! allStringsInterned ) { + if (!allStringsInterned) { final int[] iarr = new int[newSize]; - if(needsCopying) System.arraycopy(attributeNameHash, 0, iarr, 0, attrPosSize); + if (needsCopying) System.arraycopy(attributeNameHash, 0, iarr, 0, attrPosSize); attributeNameHash = iarr; } @@ -279,32 +268,28 @@ protected void ensureAttributesCapacity(int size) { protected void ensureNamespacesCapacity(int size) { final int namespaceSize = namespacePrefix != null ? namespacePrefix.length : 0; - if(size >= namespaceSize) { + if (size >= namespaceSize) { final int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25 - if(TRACE_SIZING) { - System.err.println("TRACE_SIZING namespaceSize "+namespaceSize+" ==> "+newSize); + if (TRACE_SIZING) { + System.err.println("TRACE_SIZING namespaceSize " + namespaceSize + " ==> " + newSize); } final String[] newNamespacePrefix = new String[newSize]; final String[] newNamespaceUri = new String[newSize]; - if(namespacePrefix != null) { - System.arraycopy( - namespacePrefix, 0, newNamespacePrefix, 0, namespaceEnd); - System.arraycopy( - namespaceUri, 0, newNamespaceUri, 0, namespaceEnd); + if (namespacePrefix != null) { + System.arraycopy(namespacePrefix, 0, newNamespacePrefix, 0, namespaceEnd); + System.arraycopy(namespaceUri, 0, newNamespaceUri, 0, namespaceEnd); } namespacePrefix = newNamespacePrefix; namespaceUri = newNamespaceUri; - - if( ! allStringsInterned ) { + if (!allStringsInterned) { final int[] newNamespacePrefixHash = new int[newSize]; - if(namespacePrefixHash != null) { - System.arraycopy( - namespacePrefixHash, 0, newNamespacePrefixHash, 0, namespaceEnd); + if (namespacePrefixHash != null) { + System.arraycopy(namespacePrefixHash, 0, newNamespacePrefixHash, 0, namespaceEnd); } namespacePrefixHash = newNamespacePrefixHash; } - //prefixesSize = newSize; + // prefixesSize = newSize; // //assert nsPrefixes.length > size && nsPrefixes.length == newSize } } @@ -318,22 +303,22 @@ protected void ensureNamespacesCapacity(int size) { * @param len The length. * @return the hash. */ - protected static final int fastHash( char ch[], int off, int len ) { - if(len == 0) return 0; - //assert len >0 + protected static final int fastHash(char ch[], int off, int len) { + if (len == 0) return 0; + // assert len >0 int hash = ch[off]; // hash at beginning - //try { - hash = (hash << 7) + ch[ off + len - 1 ]; // hash at the end - //} catch(ArrayIndexOutOfBoundsException aie) { + // try { + hash = (hash << 7) + ch[off + len - 1]; // hash at the end + // } catch(ArrayIndexOutOfBoundsException aie) { // aie.printStackTrace(); //should never happen ... // throw new RuntimeException("this is violation of pre-condition"); - //} - if(len > 16) hash = (hash << 7) + ch[ off + (len / 4)]; // 1/4 from beginning - if(len > 8) hash = (hash << 7) + ch[ off + (len / 2)]; // 1/2 of string size ... + // } + if (len > 16) hash = (hash << 7) + ch[off + (len / 4)]; // 1/4 from beginning + if (len > 8) hash = (hash << 7) + ch[off + (len / 2)]; // 1/2 of string size ... // notice that hash is at most done 3 times <<7 so shifted by 21 bits 8 bit value // so max result == 29 bits so it is quite just below 31 bits for long (2^32) ... - //assert hash >= 0; - return hash; + // assert hash >= 0; + return hash; } // entity replacement stack @@ -348,16 +333,16 @@ protected static final int fastHash( char ch[], int off, int len ) { protected void ensureEntityCapacity() { final int entitySize = entityReplacementBuf != null ? entityReplacementBuf.length : 0; - if(entityEnd >= entitySize) { + if (entityEnd >= entitySize) { final int newSize = entityEnd > 7 ? 2 * entityEnd : 8; // = lucky 7 + 1 //25 - if(TRACE_SIZING) { - System.err.println("TRACE_SIZING entitySize "+entitySize+" ==> "+newSize); + if (TRACE_SIZING) { + System.err.println("TRACE_SIZING entitySize " + entitySize + " ==> " + newSize); } final String[] newEntityName = new String[newSize]; final char[] newEntityNameBuf[] = new char[newSize][]; final String[] newEntityReplacement = new String[newSize]; final char[] newEntityReplacementBuf[] = new char[newSize][]; - if(entityName != null) { + if (entityName != null) { System.arraycopy(entityName, 0, newEntityName, 0, entityEnd); System.arraycopy(entityNameBuf, 0, newEntityNameBuf, 0, entityEnd); System.arraycopy(entityReplacement, 0, newEntityReplacement, 0, entityEnd); @@ -368,18 +353,17 @@ protected void ensureEntityCapacity() { entityReplacement = newEntityReplacement; entityReplacementBuf = newEntityReplacementBuf; - if( ! allStringsInterned ) { + if (!allStringsInterned) { final int[] newEntityNameHash = new int[newSize]; - if(entityNameHash != null) { + if (entityNameHash != null) { System.arraycopy(entityNameHash, 0, newEntityNameHash, 0, entityEnd); } entityNameHash = newEntityNameHash; } } } - - protected void reset() - { + + protected void reset() { location = null; lineNumber = 1; columnNumber = 0; @@ -422,9 +406,7 @@ protected void reset() resetStringCache(); } - public MXParser() { - } - + public MXParser() {} /** * Method setFeature @@ -432,132 +414,114 @@ public MXParser() { * @param name a String * @param state a boolean * - * @throws XmlPullParserException in case of an error. + * @throws XmlPullParserException in case of an error. * */ - public void setFeature(String name, - boolean state) throws XmlPullParserException - { - if(name == null) throw new IllegalArgumentException("feature name should not be null"); - if(FEATURE_PROCESS_NAMESPACES.equals(name)) { - if(eventType != START_DOCUMENT) throw new XmlPullParserException( - "namespace processing feature can only be changed before parsing", this, null); + public void setFeature(String name, boolean state) throws XmlPullParserException { + if (name == null) throw new IllegalArgumentException("feature name should not be null"); + if (FEATURE_PROCESS_NAMESPACES.equals(name)) { + if (eventType != START_DOCUMENT) + throw new XmlPullParserException( + "namespace processing feature can only be changed before parsing", this, null); processNamespaces = state; // } else if(FEATURE_REPORT_NAMESPACE_ATTRIBUTES.equals(name)) { // if(type != START_DOCUMENT) throw new XmlPullParserException( // "namespace reporting feature can only be changed before parsing", this, null); // reportNsAttribs = state; - } else if(FEATURE_NAMES_INTERNED.equals(name)) { - if(state != false) { - throw new XmlPullParserException( - "interning names in this implementation is not supported"); + } else if (FEATURE_NAMES_INTERNED.equals(name)) { + if (state != false) { + throw new XmlPullParserException("interning names in this implementation is not supported"); } - } else if(FEATURE_PROCESS_DOCDECL.equals(name)) { - if(state != false) { - throw new XmlPullParserException( - "processing DOCDECL is not supported"); + } else if (FEATURE_PROCESS_DOCDECL.equals(name)) { + if (state != false) { + throw new XmlPullParserException("processing DOCDECL is not supported"); } - //} else if(REPORT_DOCDECL.equals(name)) { + // } else if(REPORT_DOCDECL.equals(name)) { // paramNotifyDoctype = state; - } else if(FEATURE_XML_ROUNDTRIP.equals(name)) { - //if(state == false) { + } else if (FEATURE_XML_ROUNDTRIP.equals(name)) { + // if(state == false) { // throw new XmlPullParserException( // "roundtrip feature can not be switched off"); - //} + // } roundtripSupported = state; - } else if (FEATURE_VALIDATION.equals( name ) && !state) { + } else if (FEATURE_VALIDATION.equals(name) && !state) { // noop, is already the default. JDom wants to set it anyway } else { - throw new XmlPullParserException("unsupporte feature "+name); + throw new XmlPullParserException("unsupporte feature " + name); } } /** {@inheritDoc} * Unknown properties are always returned as false */ - public boolean getFeature(String name) - { - if(name == null) throw new IllegalArgumentException("feature name should not be nulll"); - if(FEATURE_PROCESS_NAMESPACES.equals(name)) { + public boolean getFeature(String name) { + if (name == null) throw new IllegalArgumentException("feature name should not be nulll"); + if (FEATURE_PROCESS_NAMESPACES.equals(name)) { return processNamespaces; // } else if(FEATURE_REPORT_NAMESPACE_ATTRIBUTES.equals(name)) { // return reportNsAttribs; - } else if(FEATURE_NAMES_INTERNED.equals(name)) { + } else if (FEATURE_NAMES_INTERNED.equals(name)) { return false; - } else if(FEATURE_PROCESS_DOCDECL.equals(name)) { + } else if (FEATURE_PROCESS_DOCDECL.equals(name)) { return false; - //} else if(REPORT_DOCDECL.equals(name)) { + // } else if(REPORT_DOCDECL.equals(name)) { // return paramNotifyDoctype; - } else if(FEATURE_XML_ROUNDTRIP.equals(name)) { - //return true; + } else if (FEATURE_XML_ROUNDTRIP.equals(name)) { + // return true; return roundtripSupported; - } - else if( REPORT_NAMESPACE_PREFIXES.equals( name ) ) { + } else if (REPORT_NAMESPACE_PREFIXES.equals(name)) { return processNamespaces; } - + return false; } - public void setProperty(String name, - Object value) - throws XmlPullParserException - { - if(PROPERTY_LOCATION.equals(name)) { + public void setProperty(String name, Object value) throws XmlPullParserException { + if (PROPERTY_LOCATION.equals(name)) { location = (String) value; } else { - throw new XmlPullParserException("unsupported property: '"+name+"'"); + throw new XmlPullParserException("unsupported property: '" + name + "'"); } } - - public Object getProperty(String name) - { - if(name == null) throw new IllegalArgumentException("property name should not be nulll"); - if(PROPERTY_XMLDECL_VERSION.equals(name)) { + public Object getProperty(String name) { + if (name == null) throw new IllegalArgumentException("property name should not be nulll"); + if (PROPERTY_XMLDECL_VERSION.equals(name)) { return xmlDeclVersion; - } else if(PROPERTY_XMLDECL_STANDALONE.equals(name)) { + } else if (PROPERTY_XMLDECL_STANDALONE.equals(name)) { return xmlDeclStandalone; - } else if(PROPERTY_XMLDECL_CONTENT.equals(name)) { + } else if (PROPERTY_XMLDECL_CONTENT.equals(name)) { return xmlDeclContent; - } else if(PROPERTY_LOCATION.equals(name)) { + } else if (PROPERTY_LOCATION.equals(name)) { return location; } return null; } - - public void setInput(Reader in) throws XmlPullParserException - { + public void setInput(Reader in) throws XmlPullParserException { reset(); reader = in; } - - public void setInput(java.io.InputStream inputStream, String inputEncoding) - throws XmlPullParserException - { - if(inputStream == null) { + public void setInput(java.io.InputStream inputStream, String inputEncoding) throws XmlPullParserException { + if (inputStream == null) { throw new IllegalArgumentException("input stream can not be null"); } Reader reader; try { - if(inputEncoding != null) { + if (inputEncoding != null) { reader = ReaderFactory.newReader(inputStream, inputEncoding); } else { reader = ReaderFactory.newXmlReader(inputStream); } } catch (UnsupportedEncodingException une) { throw new XmlPullParserException( - "could not create reader for encoding "+inputEncoding+" : "+une, this, une); - } - catch ( IOException e ) - { - throw new XmlPullParserException( - "could not create reader : "+e, this, e); + "could not create reader for encoding " + inputEncoding + " : " + une, this, une); + } catch (IOException e) { + throw new XmlPullParserException("could not create reader : " + e, this, e); } setInput(reader); - //must be here as reset() was called in setInput() and has set this.inputEncoding to null ... + // must be here as reset() was called in setInput() and has set this.inputEncoding to null ... this.inputEncoding = inputEncoding; } @@ -565,13 +529,10 @@ public String getInputEncoding() { return inputEncoding; } - public void defineEntityReplacementText(String entityName, - String replacementText) - throws XmlPullParserException - { + public void defineEntityReplacementText(String entityName, String replacementText) throws XmlPullParserException { // throw new XmlPullParserException("not allowed"); - //protected char[] entityReplacement[]; + // protected char[] entityReplacement[]; ensureEntityCapacity(); // this is to make sure that if interning works we will take advantage of it ... @@ -580,178 +541,159 @@ public void defineEntityReplacementText(String entityName, entityReplacement[entityEnd] = replacementText; entityReplacementBuf[entityEnd] = replacementText.toCharArray(); - if(!allStringsInterned) { - entityNameHash[ entityEnd ] = - fastHash(entityNameBuf[entityEnd], 0, entityNameBuf[entityEnd].length); + if (!allStringsInterned) { + entityNameHash[entityEnd] = fastHash(entityNameBuf[entityEnd], 0, entityNameBuf[entityEnd].length); } ++entityEnd; - //TODO disallow < or & in entity replacement text (or ]]>???) + // TODO disallow < or & in entity replacement text (or ]]>???) // TOOD keepEntityNormalizedForAttributeValue cached as well ... } - public int getNamespaceCount(int depth) - throws XmlPullParserException - { - if(processNamespaces == false || depth == 0) { + public int getNamespaceCount(int depth) throws XmlPullParserException { + if (processNamespaces == false || depth == 0) { return 0; } - //int maxDepth = eventType == END_TAG ? this.depth + 1 : this.depth; - //if(depth < 0 || depth > maxDepth) throw new IllegalArgumentException( - if(depth < 0 || depth > this.depth) throw new IllegalArgumentException( - "napespace count mayt be for depth 0.."+this.depth+" not "+depth); - return elNamespaceCount[ depth ]; + // int maxDepth = eventType == END_TAG ? this.depth + 1 : this.depth; + // if(depth < 0 || depth > maxDepth) throw new IllegalArgumentException( + if (depth < 0 || depth > this.depth) + throw new IllegalArgumentException("napespace count mayt be for depth 0.." + this.depth + " not " + depth); + return elNamespaceCount[depth]; } - public String getNamespacePrefix(int pos) - throws XmlPullParserException - { + public String getNamespacePrefix(int pos) throws XmlPullParserException { - //int end = eventType == END_TAG ? elNamespaceCount[ depth + 1 ] : namespaceEnd; - //if(pos < end) { - if(pos < namespaceEnd) { - return namespacePrefix[ pos ]; + // int end = eventType == END_TAG ? elNamespaceCount[ depth + 1 ] : namespaceEnd; + // if(pos < end) { + if (pos < namespaceEnd) { + return namespacePrefix[pos]; } else { throw new XmlPullParserException( - "position "+pos+" exceeded number of available namespaces "+namespaceEnd); + "position " + pos + " exceeded number of available namespaces " + namespaceEnd); } } - public String getNamespaceUri(int pos) throws XmlPullParserException - { - //int end = eventType == END_TAG ? elNamespaceCount[ depth + 1 ] : namespaceEnd; - //if(pos < end) { - if(pos < namespaceEnd) { - return namespaceUri[ pos ]; + public String getNamespaceUri(int pos) throws XmlPullParserException { + // int end = eventType == END_TAG ? elNamespaceCount[ depth + 1 ] : namespaceEnd; + // if(pos < end) { + if (pos < namespaceEnd) { + return namespaceUri[pos]; } else { throw new XmlPullParserException( - "position "+pos+" exceedded number of available namespaces "+namespaceEnd); + "position " + pos + " exceedded number of available namespaces " + namespaceEnd); } } - public String getNamespace( String prefix ) - //throws XmlPullParserException - { - //int count = namespaceCount[ depth ]; - if(prefix != null) { - for( int i = namespaceEnd -1; i >= 0; i--) { - if( prefix.equals( namespacePrefix[ i ] ) ) { - return namespaceUri[ i ]; + public String getNamespace(String prefix) + // throws XmlPullParserException + { + // int count = namespaceCount[ depth ]; + if (prefix != null) { + for (int i = namespaceEnd - 1; i >= 0; i--) { + if (prefix.equals(namespacePrefix[i])) { + return namespaceUri[i]; } } - if("xml".equals( prefix )) { + if ("xml".equals(prefix)) { return XML_URI; - } else if("xmlns".equals( prefix )) { + } else if ("xmlns".equals(prefix)) { return XMLNS_URI; } } else { - for( int i = namespaceEnd -1; i >= 0; i--) { - if( namespacePrefix[ i ] == null) { //"") { //null ) { //TODO check FIXME Alek - return namespaceUri[ i ]; + for (int i = namespaceEnd - 1; i >= 0; i--) { + if (namespacePrefix[i] == null) { // "") { //null ) { //TODO check FIXME Alek + return namespaceUri[i]; } } - } return null; } - - public int getDepth() - { + public int getDepth() { return depth; } - private static int findFragment(int bufMinPos, char[] b, int start, int end) { - //System.err.println("bufStart="+bufStart+" b="+printable(new String(b, start, end - start))+" start="+start+" end="+end); - if(start < bufMinPos) { + // System.err.println("bufStart="+bufStart+" b="+printable(new String(b, start, end - start))+" start="+start+" + // end="+end); + if (start < bufMinPos) { start = bufMinPos; - if(start > end) start = end; + if (start > end) start = end; return start; } - if(end - start > 65) { + if (end - start > 65) { start = end - 10; // try to find good location } int i = start + 1; - while(--i > bufMinPos) { - if((end - i) > 65) break; + while (--i > bufMinPos) { + if ((end - i) > 65) break; final char c = b[i]; - if(c == '<' && (start - i) > 10) break; + if (c == '<' && (start - i) > 10) break; } return i; } - /** * Return string describing current position of parsers as * text 'STATE [seen %s...] @line:column'. */ - public String getPositionDescription () - { + public String getPositionDescription() { String fragment = null; - if(posStart <= pos) { + if (posStart <= pos) { final int start = findFragment(0, buf, posStart, pos); - //System.err.println("start="+start); - if(start < pos) { + // System.err.println("start="+start); + if (start < pos) { fragment = new String(buf, start, pos - start); } - if(bufAbsoluteStart > 0 || start > 0) fragment = "..." + fragment; + if (bufAbsoluteStart > 0 || start > 0) fragment = "..." + fragment; } // return " at line "+tokenizerPosRow // +" and column "+(tokenizerPosCol-1) // +(fragment != null ? " seen "+printable(fragment)+"..." : ""); - return " "+TYPES[ eventType ] + - (fragment != null ? " seen "+printable(fragment)+"..." : "") - +" "+(location != null ? location : "") - +"@"+getLineNumber()+":"+getColumnNumber(); + return " " + TYPES[eventType] + (fragment != null ? " seen " + printable(fragment) + "..." : "") + + " " + (location != null ? location : "") + + "@" + getLineNumber() + ":" + getColumnNumber(); } - public int getLineNumber() - { + public int getLineNumber() { return lineNumber; } - public int getColumnNumber() - { + public int getColumnNumber() { return columnNumber; } - - public boolean isWhitespace() throws XmlPullParserException - { - if(eventType == TEXT || eventType == CDSECT) { - if(usePC) { - for (int i = pcStart; i = attributeCount) throw new IndexOutOfBoundsException( - "attribute position must be 0.."+(attributeCount-1)+" and not "+index); - return attributeUri[ index ]; + public String getAttributeNamespace(int index) { + if (eventType != START_TAG) throw new IndexOutOfBoundsException("only START_TAG can have attributes"); + if (processNamespaces == false) return NO_NAMESPACE; + if (index < 0 || index >= attributeCount) + throw new IndexOutOfBoundsException( + "attribute position must be 0.." + (attributeCount - 1) + " and not " + index); + return attributeUri[index]; } - public String getAttributeName(int index) - { - if(eventType != START_TAG) throw new IndexOutOfBoundsException( - "only START_TAG can have attributes"); - if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException( - "attribute position must be 0.."+(attributeCount-1)+" and not "+index); - return attributeName[ index ]; + public String getAttributeName(int index) { + if (eventType != START_TAG) throw new IndexOutOfBoundsException("only START_TAG can have attributes"); + if (index < 0 || index >= attributeCount) + throw new IndexOutOfBoundsException( + "attribute position must be 0.." + (attributeCount - 1) + " and not " + index); + return attributeName[index]; } - public String getAttributePrefix(int index) - { - if(eventType != START_TAG) throw new IndexOutOfBoundsException( - "only START_TAG can have attributes"); - if(processNamespaces == false) return null; - if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException( - "attribute position must be 0.."+(attributeCount-1)+" and not "+index); - return attributePrefix[ index ]; + public String getAttributePrefix(int index) { + if (eventType != START_TAG) throw new IndexOutOfBoundsException("only START_TAG can have attributes"); + if (processNamespaces == false) return null; + if (index < 0 || index >= attributeCount) + throw new IndexOutOfBoundsException( + "attribute position must be 0.." + (attributeCount - 1) + " and not " + index); + return attributePrefix[index]; } public String getAttributeType(int index) { - if(eventType != START_TAG) throw new IndexOutOfBoundsException( - "only START_TAG can have attributes"); - if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException( - "attribute position must be 0.."+(attributeCount-1)+" and not "+index); + if (eventType != START_TAG) throw new IndexOutOfBoundsException("only START_TAG can have attributes"); + if (index < 0 || index >= attributeCount) + throw new IndexOutOfBoundsException( + "attribute position must be 0.." + (attributeCount - 1) + " and not " + index); return "CDATA"; } public boolean isAttributeDefault(int index) { - if(eventType != START_TAG) throw new IndexOutOfBoundsException( - "only START_TAG can have attributes"); - if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException( - "attribute position must be 0.."+(attributeCount-1)+" and not "+index); + if (eventType != START_TAG) throw new IndexOutOfBoundsException("only START_TAG can have attributes"); + if (index < 0 || index >= attributeCount) + throw new IndexOutOfBoundsException( + "attribute position must be 0.." + (attributeCount - 1) + " and not " + index); return false; } - public String getAttributeValue(int index) - { - if(eventType != START_TAG) throw new IndexOutOfBoundsException( - "only START_TAG can have attributes"); - if(index < 0 || index >= attributeCount) throw new IndexOutOfBoundsException( - "attribute position must be 0.."+(attributeCount-1)+" and not "+index); - return attributeValue[ index ]; + public String getAttributeValue(int index) { + if (eventType != START_TAG) throw new IndexOutOfBoundsException("only START_TAG can have attributes"); + if (index < 0 || index >= attributeCount) + throw new IndexOutOfBoundsException( + "attribute position must be 0.." + (attributeCount - 1) + " and not " + index); + return attributeValue[index]; } - public String getAttributeValue(String namespace, - String name) - { - if(eventType != START_TAG) throw new IndexOutOfBoundsException( - "only START_TAG can have attributes"+getPositionDescription()); - if(name == null) { + public String getAttributeValue(String namespace, String name) { + if (eventType != START_TAG) + throw new IndexOutOfBoundsException("only START_TAG can have attributes" + getPositionDescription()); + if (name == null) { throw new IllegalArgumentException("attribute name can not be null"); } // TODO make check if namespace is interned!!! etc. for names!!! - if(processNamespaces) { - if(namespace == null) { + if (processNamespaces) { + if (namespace == null) { namespace = ""; } - for(int i = 0; i < attributeCount; ++i) { - if((namespace == attributeUri[ i ] || - namespace.equals(attributeUri[ i ]) ) - //(namespace != null && namespace.equals(attributeUri[ i ])) - // taking advantage of String.intern() - && name.equals(attributeName[ i ]) ) - { + for (int i = 0; i < attributeCount; ++i) { + if ((namespace == attributeUri[i] || namespace.equals(attributeUri[i])) + // (namespace != null && namespace.equals(attributeUri[ i ])) + // taking advantage of String.intern() + && name.equals(attributeName[i])) { return attributeValue[i]; } } } else { - if(namespace != null && namespace.length() == 0) { + if (namespace != null && namespace.length() == 0) { namespace = null; } - if(namespace != null) throw new IllegalArgumentException( - "when namespaces processing is disabled attribute namespace must be null"); - for(int i = 0; i < attributeCount; ++i) { - if(name.equals(attributeName[i])) - { + if (namespace != null) + throw new IllegalArgumentException( + "when namespaces processing is disabled attribute namespace must be null"); + for (int i = 0; i < attributeCount; ++i) { + if (name.equals(attributeName[i])) { return attributeValue[i]; } } @@ -970,46 +894,41 @@ public String getAttributeValue(String namespace, return null; } - - public int getEventType() - throws XmlPullParserException - { + public int getEventType() throws XmlPullParserException { return eventType; } - public void require(int type, String namespace, String name) - throws XmlPullParserException, IOException - { - if(processNamespaces == false && namespace != null) { - throw new XmlPullParserException( - "processing namespaces must be enabled on parser (or factory)"+ - " to have possible namespaces delcared on elements" - +(" (postion:"+ getPositionDescription())+")"); + public void require(int type, String namespace, String name) throws XmlPullParserException, IOException { + if (processNamespaces == false && namespace != null) { + throw new XmlPullParserException("processing namespaces must be enabled on parser (or factory)" + + " to have possible namespaces delcared on elements" + + (" (postion:" + getPositionDescription()) + ")"); } if (type != getEventType() - || (namespace != null && !namespace.equals (getNamespace())) - || (name != null && !name.equals (getName ())) ) - { - throw new XmlPullParserException ( - "expected event "+TYPES[ type ] - +(name != null ? " with name '"+name+"'" : "") - +(namespace != null && name != null ? " and" : "") - +(namespace != null ? " with namespace '"+namespace+"'" : "") - +" but got" - +(type != getEventType() ? " "+TYPES[ getEventType() ] : "") - +(name != null && getName() != null && !name.equals (getName ()) - ? " name '"+getName()+"'" : "") - +(namespace != null && name != null - && getName() != null && !name.equals (getName ()) - && getNamespace() != null && !namespace.equals (getNamespace()) - ? " and" : "") - +(namespace != null && getNamespace() != null && !namespace.equals (getNamespace()) - ? " namespace '"+getNamespace()+"'" : "") - +(" (postion:"+ getPositionDescription())+")"); + || (namespace != null && !namespace.equals(getNamespace())) + || (name != null && !name.equals(getName()))) { + throw new XmlPullParserException("expected event " + TYPES[type] + + (name != null ? " with name '" + name + "'" : "") + + (namespace != null && name != null ? " and" : "") + + (namespace != null ? " with namespace '" + namespace + "'" : "") + + " but got" + + (type != getEventType() ? " " + TYPES[getEventType()] : "") + + (name != null && getName() != null && !name.equals(getName()) ? " name '" + getName() + "'" : "") + + (namespace != null + && name != null + && getName() != null + && !name.equals(getName()) + && getNamespace() != null + && !namespace.equals(getNamespace()) + ? " and" + : "") + + (namespace != null && getNamespace() != null && !namespace.equals(getNamespace()) + ? " namespace '" + getNamespace() + "'" + : "") + + (" (postion:" + getPositionDescription()) + ")"); } } - /** * Skip sub tree that is currently porser positioned on. *

@@ -1018,16 +937,14 @@ && getNamespace() != null && !namespace.equals (getNamespace()) * @throws XmlPullParserException in case of an error. * @throws IOException in case of an error. */ - public void skipSubTree() - throws XmlPullParserException, IOException - { + public void skipSubTree() throws XmlPullParserException, IOException { require(START_TAG, null, null); int level = 1; - while(level > 0) { + while (level > 0) { int eventType = next(); - if(eventType == END_TAG) { + if (eventType == END_TAG) { --level; - } else if(eventType == START_TAG) { + } else if (eventType == START_TAG) { ++level; } } @@ -1041,8 +958,7 @@ public void skipSubTree() // return result; // } - public String nextText() throws XmlPullParserException, IOException - { + public String nextText() throws XmlPullParserException, IOException { // String result = null; // boolean onStartTag = false; // if(eventType == START_TAG) { @@ -1063,82 +979,70 @@ public String nextText() throws XmlPullParserException, IOException // "event TEXT it must be immediately followed by END_TAG", this, null); // } // return result; - if(getEventType() != START_TAG) { - throw new XmlPullParserException( - "parser must be on START_TAG to read next text", this, null); + if (getEventType() != START_TAG) { + throw new XmlPullParserException("parser must be on START_TAG to read next text", this, null); } int eventType = next(); - if(eventType == TEXT) { + if (eventType == TEXT) { final String result = getText(); eventType = next(); - if(eventType != END_TAG) { + if (eventType != END_TAG) { throw new XmlPullParserException( - "TEXT must be immediately followed by END_TAG and not " - +TYPES[ getEventType() ], this, null); + "TEXT must be immediately followed by END_TAG and not " + TYPES[getEventType()], this, null); } return result; - } else if(eventType == END_TAG) { + } else if (eventType == END_TAG) { return ""; } else { - throw new XmlPullParserException( - "parser must be on START_TAG or TEXT to read text", this, null); + throw new XmlPullParserException("parser must be on START_TAG or TEXT to read text", this, null); } } - public int nextTag() throws XmlPullParserException, IOException - { + public int nextTag() throws XmlPullParserException, IOException { next(); - if(eventType == TEXT && isWhitespace()) { // skip whitespace + if (eventType == TEXT && isWhitespace()) { // skip whitespace next(); } if (eventType != START_TAG && eventType != END_TAG) { - throw new XmlPullParserException("expected START_TAG or END_TAG not " - +TYPES[ getEventType() ], this, null); + throw new XmlPullParserException("expected START_TAG or END_TAG not " + TYPES[getEventType()], this, null); } return eventType; } - public int next() - throws XmlPullParserException, IOException - { + public int next() throws XmlPullParserException, IOException { tokenize = false; return nextImpl(); } - public int nextToken() - throws XmlPullParserException, IOException - { + public int nextToken() throws XmlPullParserException, IOException { tokenize = true; return nextImpl(); } - - protected int nextImpl() - throws XmlPullParserException, IOException - { + protected int nextImpl() throws XmlPullParserException, IOException { text = null; pcEnd = pcStart = 0; usePC = false; bufStart = posEnd; - if(pastEndTag) { + if (pastEndTag) { pastEndTag = false; --depth; - namespaceEnd = elNamespaceCount[ depth ]; // less namespaces available + namespaceEnd = elNamespaceCount[depth]; // less namespaces available } - if(emptyElementTag) { + if (emptyElementTag) { emptyElementTag = false; pastEndTag = true; return eventType = END_TAG; } // [1] document ::= prolog element Misc* - if(depth > 0) { + if (depth > 0) { - if(seenStartTag) { + if (seenStartTag) { seenStartTag = false; return eventType = parseStartTag(); } - if(seenEndTag) { + if (seenEndTag) { seenEndTag = false; return eventType = parseEndTag(); } @@ -1146,10 +1050,10 @@ protected int nextImpl() // ASSUMPTION: we are _on_ first character of content or markup!!!! // [43] content ::= CharData? ((element | Reference | CDSect | PI | Comment) CharData?)* char ch; - if(seenMarkup) { // we have read ahead ... + if (seenMarkup) { // we have read ahead ... seenMarkup = false; ch = '<'; - } else if(seenAmpersand) { + } else if (seenAmpersand) { seenAmpersand = false; ch = '&'; } else { @@ -1164,50 +1068,49 @@ protected int nextImpl() boolean needsMerging = false; MAIN_LOOP: - while(true) { + while (true) { // work on MARKUP - if(ch == '<') { - if(hadCharData) { - //posEnd = pos - 1; - if(tokenize) { + if (ch == '<') { + if (hadCharData) { + // posEnd = pos - 1; + if (tokenize) { seenMarkup = true; return eventType = TEXT; } } ch = more(); - if(ch == '/') { - if(!tokenize && hadCharData) { + if (ch == '/') { + if (!tokenize && hadCharData) { seenEndTag = true; - //posEnd = pos - 2; + // posEnd = pos - 2; return eventType = TEXT; } return eventType = parseEndTag(); - } else if(ch == '!') { + } else if (ch == '!') { ch = more(); - if(ch == '-') { + if (ch == '-') { // note: if(tokenize == false) posStart/End is NOT changed!!!! parseComment(); - if(tokenize) return eventType = COMMENT; - if( !usePC && hadCharData ) { + if (tokenize) return eventType = COMMENT; + if (!usePC && hadCharData) { needsMerging = true; } else { - posStart = pos; //completely ignore comment + posStart = pos; // completely ignore comment } - } else if(ch == '[') { - //posEnd = pos - 3; + } else if (ch == '[') { + // posEnd = pos - 3; // must remember previous posStart/End as it merges with content of CDATA - //int oldStart = posStart + bufAbsoluteStart; - //int oldEnd = posEnd + bufAbsoluteStart; + // int oldStart = posStart + bufAbsoluteStart; + // int oldEnd = posEnd + bufAbsoluteStart; parseCDSect(hadCharData); - if(tokenize) return eventType = CDSECT; + if (tokenize) return eventType = CDSECT; final int cdStart = posStart; final int cdEnd = posEnd; final int cdLen = cdEnd - cdStart; - - if(cdLen > 0) { // was there anything inside CDATA section? + if (cdLen > 0) { // was there anything inside CDATA section? hadCharData = true; - if(!usePC) { + if (!usePC) { needsMerging = true; } } @@ -1218,17 +1121,24 @@ protected int nextImpl() // if(hadCharData) { // // do merging if there was anything in CDSect!!!! // // if(!usePC) { - // // // posEnd is correct already!!! - // // if(posEnd > posStart) { + // // // posEnd is + // correct already!!! + // // if(posEnd > + // posStart) { // // joinPC(); // // } else { - // // usePC = true; - // // pcStart = pcEnd = 0; + // // usePC = + // true; + // // pcStart = + // pcEnd = 0; // // } // // } - // // if(pcEnd + cdLen >= pc.length) ensurePC(pcEnd + cdLen); - // // // copy [cdStart..cdEnd) into PC - // // System.arraycopy(buf, cdStart, pc, pcEnd, cdLen); + // // if(pcEnd + cdLen + // >= pc.length) ensurePC(pcEnd + cdLen); + // // // copy + // [cdStart..cdEnd) into PC + // // + // System.arraycopy(buf, cdStart, pc, pcEnd, cdLen); // // pcEnd += cdLen; // if(!usePC) { // needsMerging = true; @@ -1251,56 +1161,54 @@ protected int nextImpl() // } } else { throw new XmlPullParserException( - "unexpected character in markup "+printable(ch), this, null); + "unexpected character in markup " + printable(ch), this, null); } - } else if(ch == '?') { + } else if (ch == '?') { parsePI(); - if(tokenize) return eventType = PROCESSING_INSTRUCTION; - if( !usePC && hadCharData ) { + if (tokenize) return eventType = PROCESSING_INSTRUCTION; + if (!usePC && hadCharData) { needsMerging = true; } else { - posStart = pos; //completely ignore PI + posStart = pos; // completely ignore PI } - } else if( isNameStartChar(ch) ) { - if(!tokenize && hadCharData) { + } else if (isNameStartChar(ch)) { + if (!tokenize && hadCharData) { seenStartTag = true; - //posEnd = pos - 2; + // posEnd = pos - 2; return eventType = TEXT; } return eventType = parseStartTag(); } else { - throw new XmlPullParserException( - "unexpected character in markup "+printable(ch), this, null); + throw new XmlPullParserException("unexpected character in markup " + printable(ch), this, null); } // do content comapctation if it makes sense!!!! - } else if(ch == '&') { + } else if (ch == '&') { // work on ENTITTY - //posEnd = pos - 1; - if(tokenize && hadCharData) { + // posEnd = pos - 1; + if (tokenize && hadCharData) { seenAmpersand = true; return eventType = TEXT; } final int oldStart = posStart + bufAbsoluteStart; final int oldEnd = posEnd + bufAbsoluteStart; final char[] resolvedEntity = parseEntityRef(); - if(tokenize) return eventType = ENTITY_REF; + if (tokenize) return eventType = ENTITY_REF; // check if replacement text can be resolved !!! - if(resolvedEntity == null) { - if(entityRefName == null) { + if (resolvedEntity == null) { + if (entityRefName == null) { entityRefName = newString(buf, posStart, posEnd - posStart); } throw new XmlPullParserException( - "could not resolve entity named '"+printable(entityRefName)+"'", - this, null); + "could not resolve entity named '" + printable(entityRefName) + "'", this, null); } - //int entStart = posStart; - //int entEnd = posEnd; + // int entStart = posStart; + // int entEnd = posEnd; posStart = oldStart - bufAbsoluteStart; posEnd = oldEnd - bufAbsoluteStart; - if(!usePC) { - if(hadCharData) { + if (!usePC) { + if (hadCharData) { joinPC(); // posEnd is already set correctly!!! needsMerging = false; } else { @@ -1308,32 +1216,27 @@ protected int nextImpl() pcStart = pcEnd = 0; } } - //assert usePC == true; + // assert usePC == true; // write into PC replacement text - do merge for replacement text!!!! for (char aResolvedEntity : resolvedEntity) { if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = aResolvedEntity; - } hadCharData = true; - //assert needsMerging == false; + // assert needsMerging == false; } else { - if(needsMerging) { - //assert usePC == false; - joinPC(); // posEnd is already set correctly!!! - //posStart = pos - 1; + if (needsMerging) { + // assert usePC == false; + joinPC(); // posEnd is already set correctly!!! + // posStart = pos - 1; needsMerging = false; } - - //no MARKUP not ENTITIES so work on character data ... - - + // no MARKUP not ENTITIES so work on character data ... // [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*) - hadCharData = true; boolean normalizedCR = false; @@ -1344,48 +1247,47 @@ protected int nextImpl() do { // check that ]]> does not show in - if(ch == ']') { - if(seenBracket) { + if (ch == ']') { + if (seenBracket) { seenBracketBracket = true; } else { seenBracket = true; } - } else if(seenBracketBracket && ch == '>') { - throw new XmlPullParserException( - "characters ]]> are not allowed in content", this, null); + } else if (seenBracketBracket && ch == '>') { + throw new XmlPullParserException("characters ]]> are not allowed in content", this, null); } else { - if(seenBracket) { + if (seenBracket) { seenBracketBracket = seenBracket = false; } // assert seenTwoBrackets == seenBracket == false; } - if(normalizeInput) { + if (normalizeInput) { // deal with normalization issues ... - if(ch == '\r') { + if (ch == '\r') { normalizedCR = true; - posEnd = pos -1; + posEnd = pos - 1; // posEnd is already set - if(!usePC) { - if(posEnd > posStart) { + if (!usePC) { + if (posEnd > posStart) { joinPC(); } else { usePC = true; pcStart = pcEnd = 0; } } - //assert usePC == true; - if(pcEnd >= pc.length) ensurePC(pcEnd); + // assert usePC == true; + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; - } else if(ch == '\n') { + } else if (ch == '\n') { // if(!usePC) { joinPC(); } else { if(pcEnd >= pc.length) ensurePC(); } - if(!normalizedCR && usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + if (!normalizedCR && usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; } normalizedCR = false; } else { - if(usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + if (usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = ch; } normalizedCR = false; @@ -1393,14 +1295,14 @@ protected int nextImpl() } ch = more(); - } while(ch != '<' && ch != '&'); + } while (ch != '<' && ch != '&'); posEnd = pos - 1; - continue MAIN_LOOP; // skip ch = more() from below - we are already ahead ... + continue MAIN_LOOP; // skip ch = more() from below - we are already ahead ... } ch = more(); } // endless while(true) } else { - if(seenRoot) { + if (seenRoot) { return parseEpilog(); } else { return parseProlog(); @@ -1408,29 +1310,27 @@ protected int nextImpl() } } - - protected int parseProlog() - throws XmlPullParserException, IOException - { + protected int parseProlog() throws XmlPullParserException, IOException { // [2] prolog: ::= XMLDecl? Misc* (doctypedecl Misc*)? and look for [39] element char ch; - if(seenMarkup) { - ch = buf[ pos - 1 ]; + if (seenMarkup) { + ch = buf[pos - 1]; } else { ch = more(); } - if(eventType == START_DOCUMENT) { + if (eventType == START_DOCUMENT) { // bootstrap parsing with getting first character input! // deal with BOM // detect BOM and crop it (Unicode int Order Mark) - if(ch == '\uFFFE') { + if (ch == '\uFFFE') { throw new XmlPullParserException( - "first character in input was UNICODE noncharacter (0xFFFE)"+ - "- input requires int swapping", this, null); + "first character in input was UNICODE noncharacter (0xFFFE)" + "- input requires int swapping", + this, + null); } - if(ch == '\uFEFF') { + if (ch == '\uFEFF') { // skipping UNICODE int Order Mark (so called BOM) ch = more(); } @@ -1440,84 +1340,80 @@ protected int parseProlog() posStart = pos - 1; final boolean normalizeIgnorableWS = tokenize == true && roundtripSupported == false; boolean normalizedCR = false; - while(true) { + while (true) { // deal with Misc // [27] Misc ::= Comment | PI | S // deal with docdecl --> mark it! // else parseStartTag seen <[^/] - if(ch == '<') { - if(gotS && tokenize) { + if (ch == '<') { + if (gotS && tokenize) { posEnd = pos - 1; seenMarkup = true; return eventType = IGNORABLE_WHITESPACE; } ch = more(); - if(ch == '?') { + if (ch == '?') { // check if it is 'xml' // deal with XMLDecl boolean isXMLDecl = parsePI(); - if(tokenize) { + if (tokenize) { if (isXMLDecl) { return eventType = START_DOCUMENT; } return eventType = PROCESSING_INSTRUCTION; } - } else if(ch == '!') { + } else if (ch == '!') { ch = more(); - if(ch == 'D') { - if(seenDocdecl) { - throw new XmlPullParserException( - "only one docdecl allowed in XML document", this, null); + if (ch == 'D') { + if (seenDocdecl) { + throw new XmlPullParserException("only one docdecl allowed in XML document", this, null); } seenDocdecl = true; parseDocdecl(); - if(tokenize) return eventType = DOCDECL; - } else if(ch == '-') { + if (tokenize) return eventType = DOCDECL; + } else if (ch == '-') { parseComment(); - if(tokenize) return eventType = COMMENT; + if (tokenize) return eventType = COMMENT; } else { - throw new XmlPullParserException( - "unexpected markup posStart) { + if (!usePC) { + posEnd = pos - 1; + if (posEnd > posStart) { joinPC(); } else { usePC = true; pcStart = pcEnd = 0; } } - //assert usePC == true; - if(pcEnd >= pc.length) ensurePC(pcEnd); + // assert usePC == true; + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; - } else if(ch == '\n') { - if(!normalizedCR && usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + } else if (ch == '\n') { + if (!normalizedCR && usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; } normalizedCR = false; } else { - if(usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + if (usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = ch; } normalizedCR = false; @@ -1525,20 +1421,17 @@ protected int parseProlog() } } else { throw new XmlPullParserException( - "only whitespace content allowed before start tag and not "+printable(ch), - this, null); + "only whitespace content allowed before start tag and not " + printable(ch), this, null); } ch = more(); } } - protected int parseEpilog() - throws XmlPullParserException, IOException - { - if(eventType == END_DOCUMENT) { + protected int parseEpilog() throws XmlPullParserException, IOException { + if (eventType == END_DOCUMENT) { throw new XmlPullParserException("already reached end of XML input", this, null); } - if(reachedEnd) { + if (reachedEnd) { return eventType = END_DOCUMENT; } boolean gotS = false; @@ -1547,88 +1440,86 @@ protected int parseEpilog() try { // epilog: Misc* char ch; - if(seenMarkup) { - ch = buf[ pos - 1 ]; + if (seenMarkup) { + ch = buf[pos - 1]; } else { ch = more(); } seenMarkup = false; posStart = pos - 1; - if(!reachedEnd) { - while(true) { + if (!reachedEnd) { + while (true) { // deal with Misc // [27] Misc ::= Comment | PI | S - if(ch == '<') { - if(gotS && tokenize) { + if (ch == '<') { + if (gotS && tokenize) { posEnd = pos - 1; seenMarkup = true; return eventType = IGNORABLE_WHITESPACE; } ch = more(); - if(reachedEnd) { + if (reachedEnd) { break; } - if(ch == '?') { + if (ch == '?') { // check if it is 'xml' // deal with XMLDecl parsePI(); - if(tokenize) return eventType = PROCESSING_INSTRUCTION; + if (tokenize) return eventType = PROCESSING_INSTRUCTION; - } else if(ch == '!') { + } else if (ch == '!') { ch = more(); - if(reachedEnd) { + if (reachedEnd) { break; } - if(ch == 'D') { - parseDocdecl(); //FIXME - if(tokenize) return eventType = DOCDECL; - } else if(ch == '-') { + if (ch == 'D') { + parseDocdecl(); // FIXME + if (tokenize) return eventType = DOCDECL; + } else if (ch == '-') { parseComment(); - if(tokenize) return eventType = COMMENT; + if (tokenize) return eventType = COMMENT; } else { - throw new XmlPullParserException( - "unexpected markup posStart) { + if (!usePC) { + posEnd = pos - 1; + if (posEnd > posStart) { joinPC(); } else { usePC = true; pcStart = pcEnd = 0; } } - //assert usePC == true; - if(pcEnd >= pc.length) ensurePC(pcEnd); + // assert usePC == true; + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; - } else if(ch == '\n') { - if(!normalizedCR && usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + } else if (ch == '\n') { + if (!normalizedCR && usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; } normalizedCR = false; } else { - if(usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + if (usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = ch; } normalizedCR = false; @@ -1636,25 +1527,23 @@ protected int parseEpilog() } } else { throw new XmlPullParserException( - "in epilog non whitespace content is not allowed but got "+printable(ch), - this, null); + "in epilog non whitespace content is not allowed but got " + printable(ch), this, null); } ch = more(); - if(reachedEnd) { + if (reachedEnd) { break; } - } } // throw Exception("unexpected content in epilog // catch EOFException return END_DOCUMENT - //try { - } catch(EOFException ex) { + // try { + } catch (EOFException ex) { reachedEnd = true; } - if(reachedEnd) { - if(tokenize && gotS) { + if (reachedEnd) { + if (tokenize && gotS) { posEnd = pos; // well - this is LAST available character pos return eventType = IGNORABLE_WHITESPACE; } @@ -1664,61 +1553,64 @@ protected int parseEpilog() } } - public int parseEndTag() throws XmlPullParserException, IOException { - //ASSUMPTION ch is past "' char ch = more(); - if(!isNameStartChar(ch)) { - throw new XmlPullParserException( - "expected name start and not "+printable(ch), this, null); + if (!isNameStartChar(ch)) { + throw new XmlPullParserException("expected name start and not " + printable(ch), this, null); } posStart = pos - 3; final int nameStart = pos - 1 + bufAbsoluteStart; do { ch = more(); - } while(isNameChar(ch)); + } while (isNameChar(ch)); // now we go one level down -- do checks - //--depth; //FIXME + // --depth; //FIXME // check that end tag name is the same as start tag - //String name = new String(buf, nameStart - bufAbsoluteStart, + // String name = new String(buf, nameStart - bufAbsoluteStart, // (pos - 1) - (nameStart - bufAbsoluteStart)); - //int last = pos - 1; + // int last = pos - 1; int off = nameStart - bufAbsoluteStart; - //final int len = last - off; + // final int len = last - off; final int len = (pos - 1) - off; final char[] cbuf = elRawName[depth]; - if(elRawNameEnd[depth] != len) { + if (elRawNameEnd[depth] != len) { // construct strings for exception final String startname = new String(cbuf, 0, elRawNameEnd[depth]); final String endname = new String(buf, off, len); throw new XmlPullParserException( - "end tag name must match start tag name <"+startname+">" - +" from line "+elRawNameLine[depth], this, null); + "end tag name must match start tag name <" + startname + ">" + " from line " + + elRawNameLine[depth], + this, + null); } - for (int i = 0; i < len; i++) - { - if(buf[off++] != cbuf[i]) { + for (int i = 0; i < len; i++) { + if (buf[off++] != cbuf[i]) { // construct strings for exception final String startname = new String(cbuf, 0, len); final String endname = new String(buf, off - i - 1, len); throw new XmlPullParserException( - "end tag name must be the same as start tag <"+startname+">" - +" from line "+elRawNameLine[depth], this, null); + "end tag name must be the same as start tag <" + startname + ">" + + " from line " + elRawNameLine[depth], + this, + null); } } - while(isS(ch)) { ch = more(); } // skip additional white spaces - if(ch != '>') { + while (isS(ch)) { + ch = more(); + } // skip additional white spaces + if (ch != '>') { throw new XmlPullParserException( - "expected > to finsh end tag not "+printable(ch) - +" from line "+elRawNameLine[depth], this, null); + "expected > to finsh end tag not " + printable(ch) + " from line " + elRawNameLine[depth], + this, + null); } - - //namespaceEnd = elNamespaceCount[ depth ]; //FIXME + // namespaceEnd = elNamespaceCount[ depth ]; //FIXME posEnd = pos; pastEndTag = true; @@ -1726,10 +1618,10 @@ public int parseEndTag() throws XmlPullParserException, IOException { } public int parseStartTag() throws XmlPullParserException, IOException { - //ASSUMPTION ch is past ' // [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>' - ++depth; //FIXME + ++depth; // FIXME posStart = pos - 2; @@ -1738,17 +1630,17 @@ public int parseStartTag() throws XmlPullParserException, IOException { // retrieve name final int nameStart = pos - 1 + bufAbsoluteStart; int colonPos = -1; - char ch = buf[ pos - 1]; - if(ch == ':' && processNamespaces) throw new XmlPullParserException( - "when namespaces processing enabled colon can not be at element name start", - this, null); - while(true) { + char ch = buf[pos - 1]; + if (ch == ':' && processNamespaces) + throw new XmlPullParserException( + "when namespaces processing enabled colon can not be at element name start", this, null); + while (true) { ch = more(); - if(!isNameChar(ch)) break; - if(ch == ':' && processNamespaces) { - if(colonPos != -1) throw new XmlPullParserException( - "only one colon is allowed in name of element when namespaces are enabled", - this, null); + if (!isNameChar(ch)) break; + if (ch == ':' && processNamespaces) { + if (colonPos != -1) + throw new XmlPullParserException( + "only one colon is allowed in name of element when namespaces are enabled", this, null); colonPos = pos - 1 + bufAbsoluteStart; } } @@ -1756,160 +1648,144 @@ public int parseStartTag() throws XmlPullParserException, IOException { // retrieve name ensureElementsCapacity(); - - //TODO check for efficient interning and then use elRawNameInterned!!!! + // TODO check for efficient interning and then use elRawNameInterned!!!! int elLen = (pos - 1) - (nameStart - bufAbsoluteStart); - if(elRawName[ depth ] == null || elRawName[ depth ].length < elLen) { - elRawName[ depth ] = new char[ 2 * elLen ]; + if (elRawName[depth] == null || elRawName[depth].length < elLen) { + elRawName[depth] = new char[2 * elLen]; } - System.arraycopy(buf, nameStart - bufAbsoluteStart, elRawName[ depth ], 0, elLen); - elRawNameEnd[ depth ] = elLen; - elRawNameLine[ depth ] = lineNumber; + System.arraycopy(buf, nameStart - bufAbsoluteStart, elRawName[depth], 0, elLen); + elRawNameEnd[depth] = elLen; + elRawNameLine[depth] = lineNumber; String name = null; // work on prefixes and namespace URI String prefix = null; - if(processNamespaces) { - if(colonPos != -1) { - prefix = elPrefix[ depth ] = newString(buf, nameStart - bufAbsoluteStart, - colonPos - nameStart); - name = elName[ depth ] = newString(buf, colonPos + 1 - bufAbsoluteStart, - //(pos -1) - (colonPos + 1)); - pos - 2 - (colonPos - bufAbsoluteStart)); + if (processNamespaces) { + if (colonPos != -1) { + prefix = elPrefix[depth] = newString(buf, nameStart - bufAbsoluteStart, colonPos - nameStart); + name = elName[depth] = newString( + buf, + colonPos + 1 - bufAbsoluteStart, + // (pos -1) - (colonPos + 1)); + pos - 2 - (colonPos - bufAbsoluteStart)); } else { - prefix = elPrefix[ depth ] = null; - name = elName[ depth ] = newString(buf, nameStart - bufAbsoluteStart, elLen); + prefix = elPrefix[depth] = null; + name = elName[depth] = newString(buf, nameStart - bufAbsoluteStart, elLen); } } else { - name = elName[ depth ] = newString(buf, nameStart - bufAbsoluteStart, elLen); - + name = elName[depth] = newString(buf, nameStart - bufAbsoluteStart, elLen); } + while (true) { - while(true) { - - while(isS(ch)) { ch = more(); } // skip additional white spaces + while (isS(ch)) { + ch = more(); + } // skip additional white spaces - if(ch == '>') { + if (ch == '>') { break; - } else if(ch == '/') { - if(emptyElementTag) throw new XmlPullParserException( - "repeated / in tag declaration", this, null); + } else if (ch == '/') { + if (emptyElementTag) throw new XmlPullParserException("repeated / in tag declaration", this, null); emptyElementTag = true; ch = more(); - if(ch != '>') throw new XmlPullParserException( - "expected > to end empty tag not "+printable(ch), this, null); + if (ch != '>') + throw new XmlPullParserException("expected > to end empty tag not " + printable(ch), this, null); break; - } else if(isNameStartChar(ch)) { + } else if (isNameStartChar(ch)) { ch = parseAttribute(); ch = more(); continue; } else { - throw new XmlPullParserException( - "start tag unexpected character "+printable(ch), this, null); + throw new XmlPullParserException("start tag unexpected character " + printable(ch), this, null); } - //ch = more(); // skip space + // ch = more(); // skip space } // now when namespaces were declared we can resolve them - if(processNamespaces) { + if (processNamespaces) { String uri = getNamespace(prefix); - if(uri == null) { - if(prefix == null) { // no prefix and no uri => use default namespace + if (uri == null) { + if (prefix == null) { // no prefix and no uri => use default namespace uri = NO_NAMESPACE; } else { throw new XmlPullParserException( - "could not determine namespace bound to element prefix "+prefix, - this, null); + "could not determine namespace bound to element prefix " + prefix, this, null); } - } - elUri[ depth ] = uri; - + elUri[depth] = uri; - //String uri = getNamespace(prefix); - //if(uri == null && prefix == null) { // no prefix and no uri => use default namespace + // String uri = getNamespace(prefix); + // if(uri == null && prefix == null) { // no prefix and no uri => use default namespace // uri = ""; - //} + // } // resolve attribute namespaces - for (int i = 0; i < attributeCount; i++) - { - final String attrPrefix = attributePrefix[ i ]; - if(attrPrefix != null) { + for (int i = 0; i < attributeCount; i++) { + final String attrPrefix = attributePrefix[i]; + if (attrPrefix != null) { final String attrUri = getNamespace(attrPrefix); - if(attrUri == null) { + if (attrUri == null) { throw new XmlPullParserException( - "could not determine namespace bound to attribute prefix "+attrPrefix, - this, null); - + "could not determine namespace bound to attribute prefix " + attrPrefix, this, null); } - attributeUri[ i ] = attrUri; + attributeUri[i] = attrUri; } else { - attributeUri[ i ] = NO_NAMESPACE; + attributeUri[i] = NO_NAMESPACE; } } - //TODO - //[ WFC: Unique Att Spec ] + // TODO + // [ WFC: Unique Att Spec ] // check namespaced attribute uniqueness contraint!!! - for (int i = 1; i < attributeCount; i++) - { - for (int j = 0; j < i; j++) - { - if( attributeUri[j] == attributeUri[i] - && (allStringsInterned && attributeName[j].equals(attributeName[i]) - || (!allStringsInterned - && attributeNameHash[ j ] == attributeNameHash[ i ] - && attributeName[j].equals(attributeName[i])) ) - - ) { + for (int i = 1; i < attributeCount; i++) { + for (int j = 0; j < i; j++) { + if (attributeUri[j] == attributeUri[i] + && (allStringsInterned && attributeName[j].equals(attributeName[i]) + || (!allStringsInterned + && attributeNameHash[j] == attributeNameHash[i] + && attributeName[j].equals(attributeName[i])))) { + // prepare data for nice error messgae? String attr1 = attributeName[j]; - if(attributeUri[j] != null) attr1 = attributeUri[j]+":"+attr1; + if (attributeUri[j] != null) attr1 = attributeUri[j] + ":" + attr1; String attr2 = attributeName[i]; - if(attributeUri[i] != null) attr2 = attributeUri[i]+":"+attr2; + if (attributeUri[i] != null) attr2 = attributeUri[i] + ":" + attr2; throw new XmlPullParserException( - "duplicated attributes "+attr1+" and "+attr2, this, null); + "duplicated attributes " + attr1 + " and " + attr2, this, null); } } } - } else { // ! processNamespaces - //[ WFC: Unique Att Spec ] + // [ WFC: Unique Att Spec ] // check raw attribute uniqueness contraint!!! - for (int i = 1; i < attributeCount; i++) - { - for (int j = 0; j < i; j++) - { - if((allStringsInterned && attributeName[j].equals(attributeName[i]) + for (int i = 1; i < attributeCount; i++) { + for (int j = 0; j < i; j++) { + if ((allStringsInterned && attributeName[j].equals(attributeName[i]) || (!allStringsInterned - && attributeNameHash[ j ] == attributeNameHash[ i ] - && attributeName[j].equals(attributeName[i])) ) + && attributeNameHash[j] == attributeNameHash[i] + && attributeName[j].equals(attributeName[i])))) { - ) { // prepare data for nice error messgae? final String attr1 = attributeName[j]; final String attr2 = attributeName[i]; throw new XmlPullParserException( - "duplicated attributes "+attr1+" and "+attr2, this, null); + "duplicated attributes " + attr1 + " and " + attr2, this, null); } } } } - elNamespaceCount[ depth ] = namespaceEnd; + elNamespaceCount[depth] = namespaceEnd; posEnd = pos; return eventType = START_TAG; } - protected char parseAttribute() throws XmlPullParserException, IOException - { + protected char parseAttribute() throws XmlPullParserException, IOException { // parse attribute // [41] Attribute ::= Name Eq AttValue // [WFC: No External Entity References] @@ -1917,35 +1793,42 @@ protected char parseAttribute() throws XmlPullParserException, IOException final int prevPosStart = posStart + bufAbsoluteStart; final int nameStart = pos - 1 + bufAbsoluteStart; int colonPos = -1; - char ch = buf[ pos - 1 ]; - if(ch == ':' && processNamespaces) throw new XmlPullParserException( - "when namespaces processing enabled colon can not be at attribute name start", - this, null); - + char ch = buf[pos - 1]; + if (ch == ':' && processNamespaces) + throw new XmlPullParserException( + "when namespaces processing enabled colon can not be at attribute name start", this, null); boolean startsWithXmlns = processNamespaces && ch == 'x'; int xmlnsPos = 0; ch = more(); - while(isNameChar(ch)) { - if(processNamespaces) { - if(startsWithXmlns && xmlnsPos < 5) { + while (isNameChar(ch)) { + if (processNamespaces) { + if (startsWithXmlns && xmlnsPos < 5) { ++xmlnsPos; - if(xmlnsPos == 1) { if(ch != 'm') startsWithXmlns = false; } - else if(xmlnsPos == 2) { if(ch != 'l') startsWithXmlns = false; } - else if(xmlnsPos == 3) { if(ch != 'n') startsWithXmlns = false; } - else if(xmlnsPos == 4) { if(ch != 's') startsWithXmlns = false; } - else if(xmlnsPos == 5) { - if(ch != ':') throw new XmlPullParserException( - "after xmlns in attribute name must be colon" - +"when namespaces are enabled", this, null); - //colonPos = pos - 1 + bufAbsoluteStart; + if (xmlnsPos == 1) { + if (ch != 'm') startsWithXmlns = false; + } else if (xmlnsPos == 2) { + if (ch != 'l') startsWithXmlns = false; + } else if (xmlnsPos == 3) { + if (ch != 'n') startsWithXmlns = false; + } else if (xmlnsPos == 4) { + if (ch != 's') startsWithXmlns = false; + } else if (xmlnsPos == 5) { + if (ch != ':') + throw new XmlPullParserException( + "after xmlns in attribute name must be colon" + "when namespaces are enabled", + this, + null); + // colonPos = pos - 1 + bufAbsoluteStart; } } - if(ch == ':') { - if(colonPos != -1) throw new XmlPullParserException( - "only one colon is allowed in attribute name" - +" when namespaces are enabled", this, null); + if (ch == ':') { + if (colonPos != -1) + throw new XmlPullParserException( + "only one colon is allowed in attribute name" + " when namespaces are enabled", + this, + null); colonPos = pos - 1 + bufAbsoluteStart; } } @@ -1958,91 +1841,91 @@ else if(xmlnsPos == 5) { String name = null; String prefix = null; // work on prefixes and namespace URI - if(processNamespaces) { - if(xmlnsPos < 4) startsWithXmlns = false; - if(startsWithXmlns) { - if(colonPos != -1) { - //prefix = attributePrefix[ attributeCount ] = null; + if (processNamespaces) { + if (xmlnsPos < 4) startsWithXmlns = false; + if (startsWithXmlns) { + if (colonPos != -1) { + // prefix = attributePrefix[ attributeCount ] = null; final int nameLen = pos - 2 - (colonPos - bufAbsoluteStart); - if(nameLen == 0) { + if (nameLen == 0) { throw new XmlPullParserException( - "namespace prefix is required after xmlns: " - +" when namespaces are enabled", this, null); + "namespace prefix is required after xmlns: " + " when namespaces are enabled", + this, + null); } - name = //attributeName[ attributeCount ] = - newString(buf, colonPos - bufAbsoluteStart + 1, nameLen); - //pos - 1 - (colonPos + 1 - bufAbsoluteStart) + name = // attributeName[ attributeCount ] = + newString(buf, colonPos - bufAbsoluteStart + 1, nameLen); + // pos - 1 - (colonPos + 1 - bufAbsoluteStart) } } else { - if(colonPos != -1) { + if (colonPos != -1) { int prefixLen = colonPos - nameStart; - prefix = attributePrefix[ attributeCount ] = - newString(buf, nameStart - bufAbsoluteStart,prefixLen); - //colonPos - (nameStart - bufAbsoluteStart)); + prefix = attributePrefix[attributeCount] = newString(buf, nameStart - bufAbsoluteStart, prefixLen); + // colonPos - (nameStart - bufAbsoluteStart)); int nameLen = pos - 2 - (colonPos - bufAbsoluteStart); - name = attributeName[ attributeCount ] = - newString(buf, colonPos - bufAbsoluteStart + 1, nameLen); - //pos - 1 - (colonPos + 1 - bufAbsoluteStart)); + name = attributeName[attributeCount] = newString(buf, colonPos - bufAbsoluteStart + 1, nameLen); + // pos - 1 - (colonPos + 1 - bufAbsoluteStart)); - //name.substring(0, colonPos-nameStart); + // name.substring(0, colonPos-nameStart); } else { - prefix = attributePrefix[ attributeCount ] = null; - name = attributeName[ attributeCount ] = - newString(buf, nameStart - bufAbsoluteStart, - pos - 1 - (nameStart - bufAbsoluteStart)); + prefix = attributePrefix[attributeCount] = null; + name = attributeName[attributeCount] = + newString(buf, nameStart - bufAbsoluteStart, pos - 1 - (nameStart - bufAbsoluteStart)); } - if(!allStringsInterned) { - attributeNameHash[ attributeCount ] = name.hashCode(); + if (!allStringsInterned) { + attributeNameHash[attributeCount] = name.hashCode(); } } } else { // retrieve name - name = attributeName[ attributeCount ] = - newString(buf, nameStart - bufAbsoluteStart, - pos - 1 - (nameStart - bufAbsoluteStart)); - ////assert name != null; - if(!allStringsInterned) { - attributeNameHash[ attributeCount ] = name.hashCode(); + name = attributeName[attributeCount] = + newString(buf, nameStart - bufAbsoluteStart, pos - 1 - (nameStart - bufAbsoluteStart)); + //// assert name != null; + if (!allStringsInterned) { + attributeNameHash[attributeCount] = name.hashCode(); } } // [25] Eq ::= S? '=' S? - while(isS(ch)) { ch = more(); } // skip additional spaces - if(ch != '=') throw new XmlPullParserException( - "expected = after attribute name", this, null); + while (isS(ch)) { + ch = more(); + } // skip additional spaces + if (ch != '=') throw new XmlPullParserException("expected = after attribute name", this, null); ch = more(); - while(isS(ch)) { ch = more(); } // skip additional spaces + while (isS(ch)) { + ch = more(); + } // skip additional spaces // [10] AttValue ::= '"' ([^<&"] | Reference)* '"' // | "'" ([^<&'] | Reference)* "'" final char delimit = ch; - if(delimit != '"' && delimit != '\'') throw new XmlPullParserException( - "attribute value must start with quotation or apostrophe not " - +printable(delimit), this, null); + if (delimit != '"' && delimit != '\'') + throw new XmlPullParserException( + "attribute value must start with quotation or apostrophe not " + printable(delimit), this, null); // parse until delimit or < and resolve Reference - //[67] Reference ::= EntityRef | CharRef - //int valueStart = pos + bufAbsoluteStart; - + // [67] Reference ::= EntityRef | CharRef + // int valueStart = pos + bufAbsoluteStart; boolean normalizedCR = false; usePC = false; pcStart = pcEnd; posStart = pos; - while(true) { + while (true) { ch = more(); - if(ch == delimit) { + if (ch == delimit) { break; - } if(ch == '<') { - throw new XmlPullParserException( - "markup not allowed inside attribute value - illegal < ", this, null); - } if(ch == '&') { + } + if (ch == '<') { + throw new XmlPullParserException("markup not allowed inside attribute value - illegal < ", this, null); + } + if (ch == '&') { // extractEntityRef posEnd = pos - 1; - if(!usePC) { + if (!usePC) { final boolean hadCharData = posEnd > posStart; - if(hadCharData) { + if (hadCharData) { // posEnd is already set correctly!!! joinPC(); } else { @@ -2050,106 +1933,100 @@ else if(xmlnsPos == 5) { pcStart = pcEnd = 0; } } - //assert usePC == true; + // assert usePC == true; final char[] resolvedEntity = parseEntityRef(); // check if replacement text can be resolved !!! - if(resolvedEntity == null) { - if(entityRefName == null) { + if (resolvedEntity == null) { + if (entityRefName == null) { entityRefName = newString(buf, posStart, posEnd - posStart); } throw new XmlPullParserException( - "could not resolve entity named '"+printable(entityRefName)+"'", - this, null); + "could not resolve entity named '" + printable(entityRefName) + "'", this, null); } // write into PC replacement text - do merge for replacement text!!!! for (char aResolvedEntity : resolvedEntity) { if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = aResolvedEntity; } - } else if(ch == '\t' || ch == '\n' || ch == '\r') { + } else if (ch == '\t' || ch == '\n' || ch == '\r') { // do attribute value normalization // as described in http://www.w3.org/TR/REC-xml#AVNormalize // TODO add test for it form spec ... // handle EOL normalization ... - if(!usePC) { + if (!usePC) { posEnd = pos - 1; - if(posEnd > posStart) { + if (posEnd > posStart) { joinPC(); } else { usePC = true; pcEnd = pcStart = 0; } } - //assert usePC == true; - if(pcEnd >= pc.length) ensurePC(pcEnd); - if(ch != '\n' || !normalizedCR) { - pc[pcEnd++] = ' '; //'\n'; + // assert usePC == true; + if (pcEnd >= pc.length) ensurePC(pcEnd); + if (ch != '\n' || !normalizedCR) { + pc[pcEnd++] = ' '; // '\n'; } } else { - if(usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + if (usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = ch; } } normalizedCR = ch == '\r'; } - - if(processNamespaces && startsWithXmlns) { + if (processNamespaces && startsWithXmlns) { String ns = null; - if(!usePC) { + if (!usePC) { ns = newStringIntern(buf, posStart, pos - 1 - posStart); } else { ns = newStringIntern(pc, pcStart, pcEnd - pcStart); } ensureNamespacesCapacity(namespaceEnd); int prefixHash = -1; - if(colonPos != -1) { - if(ns.length() == 0) { + if (colonPos != -1) { + if (ns.length() == 0) { throw new XmlPullParserException( - "non-default namespace can not be declared to be empty string", this, null); + "non-default namespace can not be declared to be empty string", this, null); } // declare new namespace - namespacePrefix[ namespaceEnd ] = name; - if(!allStringsInterned) { - prefixHash = namespacePrefixHash[ namespaceEnd ] = name.hashCode(); + namespacePrefix[namespaceEnd] = name; + if (!allStringsInterned) { + prefixHash = namespacePrefixHash[namespaceEnd] = name.hashCode(); } } else { // declare new default namespace... - namespacePrefix[ namespaceEnd ] = null; //""; //null; //TODO check FIXME Alek - if(!allStringsInterned) { - prefixHash = namespacePrefixHash[ namespaceEnd ] = -1; + namespacePrefix[namespaceEnd] = null; // ""; //null; //TODO check FIXME Alek + if (!allStringsInterned) { + prefixHash = namespacePrefixHash[namespaceEnd] = -1; } } - namespaceUri[ namespaceEnd ] = ns; + namespaceUri[namespaceEnd] = ns; // detect duplicate namespace declarations!!! - final int startNs = elNamespaceCount[ depth - 1 ]; - for (int i = namespaceEnd - 1; i >= startNs; --i) - { - if(((allStringsInterned || name == null) && namespacePrefix[ i ] == name) - || (!allStringsInterned && name != null && - namespacePrefixHash[ i ] == prefixHash - && name.equals(namespacePrefix[ i ]) - )) - { - final String s = name == null ? "default" : "'"+name+"'"; + final int startNs = elNamespaceCount[depth - 1]; + for (int i = namespaceEnd - 1; i >= startNs; --i) { + if (((allStringsInterned || name == null) && namespacePrefix[i] == name) + || (!allStringsInterned + && name != null + && namespacePrefixHash[i] == prefixHash + && name.equals(namespacePrefix[i]))) { + final String s = name == null ? "default" : "'" + name + "'"; throw new XmlPullParserException( - "duplicated namespace declaration for "+s+" prefix", this, null); + "duplicated namespace declaration for " + s + " prefix", this, null); } } ++namespaceEnd; } else { - if(!usePC) { - attributeValue[ attributeCount ] = - new String(buf, posStart, pos - 1 - posStart); + if (!usePC) { + attributeValue[attributeCount] = new String(buf, posStart, pos - 1 - posStart); } else { - attributeValue[ attributeCount ] = - new String(pc, pcStart, pcEnd - pcStart); + attributeValue[attributeCount] = new String(pc, pcStart, pcEnd - pcStart); } ++attributeCount; } @@ -2159,9 +2036,7 @@ else if(xmlnsPos == 5) { protected char[] charRefOneCharBuf = new char[1]; - protected char[] parseEntityRef() - throws XmlPullParserException, IOException - { + protected char[] parseEntityRef() throws XmlPullParserException, IOException { // entity reference http://www.w3.org/TR/2000/REC-xml-20001006#NT-Reference // [67] Reference ::= EntityRef | CharRef @@ -2169,165 +2044,157 @@ protected char[] parseEntityRef() entityRefName = null; posStart = pos; char ch = more(); - if(ch == '#') { + if (ch == '#') { // parse character reference char charRef = 0; ch = more(); - if(ch == 'x') { - //encoded in hex - while(true) { + if (ch == 'x') { + // encoded in hex + while (true) { ch = more(); - if(ch >= '0' && ch <= '9') { - charRef = (char)(charRef * 16 + (ch - '0')); - } else if(ch >= 'a' && ch <= 'f') { - charRef = (char)(charRef * 16 + (ch - ('a' - 10))); - } else if(ch >= 'A' && ch <= 'F') { - charRef = (char)(charRef * 16 + (ch - ('A' - 10))); - } else if(ch == ';') { + if (ch >= '0' && ch <= '9') { + charRef = (char) (charRef * 16 + (ch - '0')); + } else if (ch >= 'a' && ch <= 'f') { + charRef = (char) (charRef * 16 + (ch - ('a' - 10))); + } else if (ch >= 'A' && ch <= 'F') { + charRef = (char) (charRef * 16 + (ch - ('A' - 10))); + } else if (ch == ';') { break; } else { throw new XmlPullParserException( - "character reference (with hex value) may not contain " - +printable(ch), this, null); + "character reference (with hex value) may not contain " + printable(ch), this, null); } } } else { // encoded in decimal - while(true) { - if(ch >= '0' && ch <= '9') { - charRef = (char)(charRef * 10 + (ch - '0')); - } else if(ch == ';') { + while (true) { + if (ch >= '0' && ch <= '9') { + charRef = (char) (charRef * 10 + (ch - '0')); + } else if (ch == ';') { break; } else { throw new XmlPullParserException( - "character reference (with decimal value) may not contain " - +printable(ch), this, null); + "character reference (with decimal value) may not contain " + printable(ch), + this, + null); } ch = more(); } } posEnd = pos - 1; charRefOneCharBuf[0] = charRef; - if(tokenize) { + if (tokenize) { text = newString(charRefOneCharBuf, 0, 1); } return charRefOneCharBuf; } else { // [68] EntityRef ::= '&' Name ';' // scan anem until ; - if(!isNameStartChar(ch)) { + if (!isNameStartChar(ch)) { throw new XmlPullParserException( - "entity reference names can not start with character '" - +printable(ch)+"'", this, null); + "entity reference names can not start with character '" + printable(ch) + "'", this, null); } - while(true) { + while (true) { ch = more(); - if(ch == ';') { + if (ch == ';') { break; } - if(!isNameChar(ch)) { + if (!isNameChar(ch)) { throw new XmlPullParserException( - "entity reference name can not contain character " - +printable(ch)+"'", this, null); + "entity reference name can not contain character " + printable(ch) + "'", this, null); } } posEnd = pos - 1; // determine what name maps to final int len = posEnd - posStart; - if(len == 2 && buf[posStart] == 'l' && buf[posStart+1] == 't') { - if(tokenize) { + if (len == 2 && buf[posStart] == 'l' && buf[posStart + 1] == 't') { + if (tokenize) { text = "<"; } charRefOneCharBuf[0] = '<'; return charRefOneCharBuf; - //if(paramPC || isParserTokenizing) { + // if(paramPC || isParserTokenizing) { // if(pcEnd >= pc.length) ensurePC(); // pc[pcEnd++] = '<'; - //} - } else if(len == 3 && buf[posStart] == 'a' - && buf[posStart+1] == 'm' && buf[posStart+2] == 'p') { - if(tokenize) { + // } + } else if (len == 3 && buf[posStart] == 'a' && buf[posStart + 1] == 'm' && buf[posStart + 2] == 'p') { + if (tokenize) { text = "&"; } charRefOneCharBuf[0] = '&'; return charRefOneCharBuf; - } else if(len == 2 && buf[posStart] == 'g' && buf[posStart+1] == 't') { - if(tokenize) { + } else if (len == 2 && buf[posStart] == 'g' && buf[posStart + 1] == 't') { + if (tokenize) { text = ">"; } charRefOneCharBuf[0] = '>'; return charRefOneCharBuf; - } else if(len == 4 && buf[posStart] == 'a' && buf[posStart+1] == 'p' - && buf[posStart+2] == 'o' && buf[posStart+3] == 's') - { - if(tokenize) { + } else if (len == 4 + && buf[posStart] == 'a' + && buf[posStart + 1] == 'p' + && buf[posStart + 2] == 'o' + && buf[posStart + 3] == 's') { + if (tokenize) { text = "'"; } charRefOneCharBuf[0] = '\''; return charRefOneCharBuf; - } else if(len == 4 && buf[posStart] == 'q' && buf[posStart+1] == 'u' - && buf[posStart+2] == 'o' && buf[posStart+3] == 't') - { - if(tokenize) { + } else if (len == 4 + && buf[posStart] == 'q' + && buf[posStart + 1] == 'u' + && buf[posStart + 2] == 'o' + && buf[posStart + 3] == 't') { + if (tokenize) { text = "\""; } charRefOneCharBuf[0] = '"'; return charRefOneCharBuf; } else { final char[] result = lookuEntityReplacement(len); - if(result != null) { + if (result != null) { return result; } } - if(tokenize) text = null; + if (tokenize) text = null; return null; } } - protected char[] lookuEntityReplacement(int entitNameLen) - throws XmlPullParserException, IOException + protected char[] lookuEntityReplacement(int entitNameLen) throws XmlPullParserException, IOException { - { - if(!allStringsInterned) { + if (!allStringsInterned) { final int hash = fastHash(buf, posStart, posEnd - posStart); LOOP: - for (int i = entityEnd - 1; i >= 0; --i) - { - if(hash == entityNameHash[ i ] && entitNameLen == entityNameBuf[ i ].length) { - final char[] entityBuf = entityNameBuf[ i ]; - for (int j = 0; j < entitNameLen; j++) - { - if(buf[posStart + j] != entityBuf[j]) continue LOOP; + for (int i = entityEnd - 1; i >= 0; --i) { + if (hash == entityNameHash[i] && entitNameLen == entityNameBuf[i].length) { + final char[] entityBuf = entityNameBuf[i]; + for (int j = 0; j < entitNameLen; j++) { + if (buf[posStart + j] != entityBuf[j]) continue LOOP; } - if(tokenize) text = entityReplacement[ i ]; - return entityReplacementBuf[ i ]; + if (tokenize) text = entityReplacement[i]; + return entityReplacementBuf[i]; } } } else { entityRefName = newString(buf, posStart, posEnd - posStart); - for (int i = entityEnd - 1; i >= 0; --i) - { + for (int i = entityEnd - 1; i >= 0; --i) { // take advantage that interning for newStirng is enforced - if(entityRefName == entityName[ i ]) { - if(tokenize) text = entityReplacement[ i ]; - return entityReplacementBuf[ i ]; + if (entityRefName == entityName[i]) { + if (tokenize) text = entityReplacement[i]; + return entityReplacementBuf[i]; } } } return null; } - - protected void parseComment() - throws XmlPullParserException, IOException - { + protected void parseComment() throws XmlPullParserException, IOException { // implements XML 1.0 Section 2.5 Comments - //ASSUMPTION: seen ch = more(); - if(seenDashDash && ch != '>') { + if (seenDashDash && ch != '>') { throw new XmlPullParserException( - "in comment after two dashes (--) next character must be >" - +" not "+printable(ch), this, null); + "in comment after two dashes (--) next character must be >" + " not " + printable(ch), + this, + null); } - if(ch == '-') { - if(!seenDash) { + if (ch == '-') { + if (!seenDash) { seenDash = true; } else { seenDashDash = true; seenDash = false; } - } else if(ch == '>') { - if(seenDashDash) { - break; // found end sequence!!!! + } else if (ch == '>') { + if (seenDashDash) { + break; // found end sequence!!!! } else { seenDashDash = false; } @@ -2362,33 +2230,33 @@ protected void parseComment() } else { seenDash = false; } - if(normalizeIgnorableWS) { - if(ch == '\r') { + if (normalizeIgnorableWS) { + if (ch == '\r') { normalizedCR = true; - //posEnd = pos -1; - //joinPC(); + // posEnd = pos -1; + // joinPC(); // posEnd is alreadys set - if(!usePC) { - posEnd = pos -1; - if(posEnd > posStart) { + if (!usePC) { + posEnd = pos - 1; + if (posEnd > posStart) { joinPC(); } else { usePC = true; pcStart = pcEnd = 0; } } - //assert usePC == true; - if(pcEnd >= pc.length) ensurePC(pcEnd); + // assert usePC == true; + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; - } else if(ch == '\n') { - if(!normalizedCR && usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + } else if (ch == '\n') { + if (!normalizedCR && usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; } normalizedCR = false; } else { - if(usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + if (usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = ch; } normalizedCR = false; @@ -2396,29 +2264,26 @@ protected void parseComment() } } - } catch(EOFException ex) { + } catch (EOFException ex) { // detect EOF and create meaningful error ... throw new XmlPullParserException( - "comment started on line "+curLine+" and column "+curColumn+" was not closed", - this, ex); + "comment started on line " + curLine + " and column " + curColumn + " was not closed", this, ex); } - if(tokenize) { + if (tokenize) { posEnd = pos - 3; - if(usePC) { + if (usePC) { pcEnd -= 2; } } } - protected boolean parsePI() - throws XmlPullParserException, IOException - { + protected boolean parsePI() throws XmlPullParserException, IOException { // implements XML 1.0 Section 2.6 Processing Instructions // [16] PI ::= '' Char*)))? '?>' // [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l')) - //ASSUMPTION: seen - //ch = more(); + // ch = more(); - if(ch == '?') { + if (ch == '?') { seenQ = true; - } else if(ch == '>') { - if(seenQ) { - break; // found end sequence!!!! + } else if (ch == '>') { + if (seenQ) { + break; // found end sequence!!!! } seenQ = false; } else { - if(piTargetEnd == -1 && isS(ch)) { + if (piTargetEnd == -1 && isS(ch)) { piTargetEnd = pos - 1 + bufAbsoluteStart; // [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l')) - if((piTargetEnd - piTargetStart) == 3) { - if((buf[piTargetStart] == 'x' || buf[piTargetStart] == 'X') - && (buf[piTargetStart+1] == 'm' || buf[piTargetStart+1] == 'M') - && (buf[piTargetStart+2] == 'l' || buf[piTargetStart+2] == 'L') - ) - { - if(piTargetStart > 3) { // 3) { // posStart) { + if (!usePC) { + posEnd = pos - 1; + if (posEnd > posStart) { joinPC(); } else { usePC = true; pcStart = pcEnd = 0; } } - //assert usePC == true; - if(pcEnd >= pc.length) ensurePC(pcEnd); + // assert usePC == true; + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; - } else if(ch == '\n') { - if(!normalizedCR && usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + } else if (ch == '\n') { + if (!normalizedCR && usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; } normalizedCR = false; } else { - if(usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + if (usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = ch; } normalizedCR = false; @@ -2515,23 +2378,24 @@ protected boolean parsePI() } ch = more(); } - } catch(EOFException ex) { + } catch (EOFException ex) { // detect EOF and create meaningful error ... throw new XmlPullParserException( - "processing instruction started on line "+curLine+" and column "+curColumn - +" was not closed", - this, ex); + "processing instruction started on line " + curLine + " and column " + curColumn + + " was not closed", + this, + ex); } - if(piTargetEnd == -1) { + if (piTargetEnd == -1) { piTargetEnd = pos - 2 + bufAbsoluteStart; - //throw new XmlPullParserException( + // throw new XmlPullParserException( // "processing instruction must have PITarget name", this, null); } piTargetStart -= bufAbsoluteStart; piTargetEnd -= bufAbsoluteStart; - if(tokenize) { + if (tokenize) { posEnd = pos - 2; - if(normalizeIgnorableWS) { + if (normalizeIgnorableWS) { --pcEnd; } } @@ -2544,17 +2408,13 @@ protected boolean parsePI() // protected final static char[] YES = {'y','e','s'}; // protected final static char[] NO = {'n','o'}; - protected final static char[] VERSION = "version".toCharArray(); - protected final static char[] NCODING = "ncoding".toCharArray(); - protected final static char[] TANDALONE = "tandalone".toCharArray(); - protected final static char[] YES = "yes".toCharArray(); - protected final static char[] NO = "no".toCharArray(); + protected static final char[] VERSION = "version".toCharArray(); + protected static final char[] NCODING = "ncoding".toCharArray(); + protected static final char[] TANDALONE = "tandalone".toCharArray(); + protected static final char[] YES = "yes".toCharArray(); + protected static final char[] NO = "no".toCharArray(); - - - protected void parseXmlDecl(char ch) - throws XmlPullParserException, IOException - { + protected void parseXmlDecl(char ch) throws XmlPullParserException, IOException { // [23] XMLDecl ::= '' // first make sure that relative positions will stay OK @@ -2569,29 +2429,35 @@ protected void parseXmlDecl(char ch) ch = requireInput(ch, VERSION); // [25] Eq ::= S? '=' S? ch = skipS(ch); - if(ch != '=') { + if (ch != '=') { throw new XmlPullParserException( - "expected equals sign (=) after version and not "+printable(ch), this, null); + "expected equals sign (=) after version and not " + printable(ch), this, null); } ch = more(); ch = skipS(ch); - if(ch != '\'' && ch != '"') { + if (ch != '\'' && ch != '"') { throw new XmlPullParserException( - "expected apostrophe (') or quotation mark (\") after version and not " - +printable(ch), this, null); + "expected apostrophe (') or quotation mark (\") after version and not " + printable(ch), + this, + null); } final char quotChar = ch; - //int versionStart = pos + bufAbsoluteStart; // required if preventBufferCompaction==false + // int versionStart = pos + bufAbsoluteStart; // required if preventBufferCompaction==false final int versionStart = pos; ch = more(); // [26] VersionNum ::= ([a-zA-Z0-9_.:] | '-')+ - while(ch != quotChar) { - if((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z') && (ch < '0' || ch > '9') - && ch != '_' && ch != '.' && ch != ':' && ch != '-') - { + while (ch != quotChar) { + if ((ch < 'a' || ch > 'z') + && (ch < 'A' || ch > 'Z') + && (ch < '0' || ch > '9') + && ch != '_' + && ch != '.' + && ch != ':' + && ch != '-') { throw new XmlPullParserException( - " 'z') && (ch < 'A' || ch > 'Z')) - { + if ((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z')) { throw new XmlPullParserException( - " 'z') && (ch < 'A' || ch > 'Z') && (ch < '0' || ch > '9') - && ch != '.' && ch != '_' && ch != '-') - { + while (ch != quotChar) { + if ((ch < 'a' || ch > 'z') + && (ch < 'A' || ch > 'Z') + && (ch < '0' || ch > '9') + && ch != '.' + && ch != '_' + && ch != '-') { throw new XmlPullParserException( - " as last part of as last part of ') { - throw new XmlPullParserException( - "expected ?> as last part of ') { + throw new XmlPullParserException("expected ?> as last part of ' && bracketLevel == 0) break; - if(normalizeIgnorableWS) { - if(ch == '\r') { + if (ch == '[') ++bracketLevel; + if (ch == ']') --bracketLevel; + if (ch == '>' && bracketLevel == 0) break; + if (normalizeIgnorableWS) { + if (ch == '\r') { normalizedCR = true; - //posEnd = pos -1; - //joinPC(); + // posEnd = pos -1; + // joinPC(); // posEnd is alreadys set - if(!usePC) { - posEnd = pos -1; - if(posEnd > posStart) { + if (!usePC) { + posEnd = pos - 1; + if (posEnd > posStart) { joinPC(); } else { usePC = true; pcStart = pcEnd = 0; } } - //assert usePC == true; - if(pcEnd >= pc.length) ensurePC(pcEnd); + // assert usePC == true; + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; - } else if(ch == '\n') { - if(!normalizedCR && usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + } else if (ch == '\n') { + if (!normalizedCR && usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; } normalizedCR = false; } else { - if(usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + if (usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = ch; } normalizedCR = false; } } - } posEnd = pos - 1; } - protected void parseCDSect(boolean hadCharData) - throws XmlPullParserException, IOException - { + protected void parseCDSect(boolean hadCharData) throws XmlPullParserException, IOException { // implements XML 1.0 Section 2.7 CDATA Sections // [18] CDSect ::= CDStart CData CDEnd @@ -2802,37 +2652,31 @@ protected void parseCDSect(boolean hadCharData) // [20] CData ::= (Char* - (Char* ']]>' Char*)) // [21] CDEnd ::= ']]>' - //ASSUMPTION: seen posStart) { + if (posEnd > posStart) { joinPC(); } else { usePC = true; @@ -2844,68 +2688,69 @@ protected void parseCDSect(boolean hadCharData) boolean seenBracket = false; boolean seenBracketBracket = false; boolean normalizedCR = false; - while(true) { + while (true) { // scan until it hits "]]>" ch = more(); - if(ch == ']') { - if(!seenBracket) { + if (ch == ']') { + if (!seenBracket) { seenBracket = true; } else { seenBracketBracket = true; - //seenBracket = false; + // seenBracket = false; } - } else if(ch == '>') { - if(seenBracket && seenBracketBracket) { - break; // found end sequence!!!! + } else if (ch == '>') { + if (seenBracket && seenBracketBracket) { + break; // found end sequence!!!! } else { seenBracketBracket = false; } seenBracket = false; } else { - if(seenBracket) { + if (seenBracket) { seenBracket = false; } } - if(normalizeInput) { + if (normalizeInput) { // deal with normalization issues ... - if(ch == '\r') { + if (ch == '\r') { normalizedCR = true; posStart = cdStart - bufAbsoluteStart; posEnd = pos - 1; // posEnd is alreadys set - if(!usePC) { - if(posEnd > posStart) { + if (!usePC) { + if (posEnd > posStart) { joinPC(); } else { usePC = true; pcStart = pcEnd = 0; } } - //assert usePC == true; - if(pcEnd >= pc.length) ensurePC(pcEnd); + // assert usePC == true; + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; - } else if(ch == '\n') { - if(!normalizedCR && usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + } else if (ch == '\n') { + if (!normalizedCR && usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = '\n'; } normalizedCR = false; } else { - if(usePC) { - if(pcEnd >= pc.length) ensurePC(pcEnd); + if (usePC) { + if (pcEnd >= pc.length) ensurePC(pcEnd); pc[pcEnd++] = ch; } normalizedCR = false; } } } - } catch(EOFException ex) { + } catch (EOFException ex) { // detect EOF and create meaningful error ... throw new XmlPullParserException( - "CDATA section started on line "+curLine+" and column "+curColumn+" was not closed", - this, ex); + "CDATA section started on line " + curLine + " and column " + curColumn + " was not closed", + this, + ex); } - if(normalizeInput) { - if(usePC) { + if (normalizeInput) { + if (usePC) { pcEnd = pcEnd - 2; } } @@ -2914,21 +2759,20 @@ protected void parseCDSect(boolean hadCharData) } protected void fillBuf() throws IOException, XmlPullParserException { - if(reader == null) throw new XmlPullParserException( - "reader must be set before parsing is started"); + if (reader == null) throw new XmlPullParserException("reader must be set before parsing is started"); // see if we are in compaction area - if(bufEnd > bufSoftLimit) { + if (bufEnd > bufSoftLimit) { // expand buffer it makes sense!!!! boolean compact = bufStart > bufSoftLimit; boolean expand = false; - if(preventBufferCompaction) { + if (preventBufferCompaction) { compact = false; expand = true; - } else if(!compact) { - //freeSpace - if(bufStart < buf.length / 2) { + } else if (!compact) { + // freeSpace + if (bufStart < buf.length / 2) { // less then half buffer available forcompactin --> expand instead!!! expand = true; } else { @@ -2938,25 +2782,25 @@ protected void fillBuf() throws IOException, XmlPullParserException { } // if buffer almost full then compact it - if(compact) { - //TODO: look on trashing + if (compact) { + // TODO: look on trashing // //assert bufStart > 0 System.arraycopy(buf, bufStart, buf, 0, bufEnd - bufStart); - if(TRACE_SIZING) System.out.println( - "TRACE_SIZING fillBuf() compacting "+bufStart - +" bufEnd="+bufEnd - +" pos="+pos+" posStart="+posStart+" posEnd="+posEnd - +" buf first 100 chars:"+new String(buf, bufStart, - bufEnd - bufStart < 100 ? bufEnd - bufStart : 100 )); - - } else if(expand) { + if (TRACE_SIZING) + System.out.println("TRACE_SIZING fillBuf() compacting " + bufStart + + " bufEnd=" + bufEnd + + " pos=" + pos + " posStart=" + posStart + " posEnd=" + posEnd + + " buf first 100 chars:" + + new String(buf, bufStart, bufEnd - bufStart < 100 ? bufEnd - bufStart : 100)); + + } else if (expand) { final int newSize = 2 * buf.length; - final char newBuf[] = new char[ newSize ]; - if(TRACE_SIZING) System.out.println("TRACE_SIZING fillBuf() "+buf.length+" => "+newSize); + final char newBuf[] = new char[newSize]; + if (TRACE_SIZING) System.out.println("TRACE_SIZING fillBuf() " + buf.length + " => " + newSize); System.arraycopy(buf, bufStart, newBuf, 0, bufEnd - bufStart); buf = newBuf; - if(bufLoadFactor > 0) { - bufSoftLimit = ( bufLoadFactor * buf.length ) /100; + if (bufLoadFactor > 0) { + bufSoftLimit = (bufLoadFactor * buf.length) / 100; } } else { @@ -2968,76 +2812,81 @@ protected void fillBuf() throws IOException, XmlPullParserException { posEnd -= bufStart; bufAbsoluteStart += bufStart; bufStart = 0; - if(TRACE_SIZING) System.out.println( - "TRACE_SIZING fillBuf() after bufEnd="+bufEnd - +" pos="+pos+" posStart="+posStart+" posEnd="+posEnd - +" buf first 100 chars:"+new String(buf, 0, bufEnd < 100 ? bufEnd : 100)); + if (TRACE_SIZING) + System.out.println("TRACE_SIZING fillBuf() after bufEnd=" + bufEnd + + " pos=" + pos + " posStart=" + posStart + " posEnd=" + posEnd + + " buf first 100 chars:" + new String(buf, 0, bufEnd < 100 ? bufEnd : 100)); } // at least one charcter must be read or error final int len = buf.length - bufEnd > READ_CHUNK_SIZE ? READ_CHUNK_SIZE : buf.length - bufEnd; final int ret = reader.read(buf, bufEnd, len); - if(ret > 0) { + if (ret > 0) { bufEnd += ret; - if(TRACE_SIZING) System.out.println( - "TRACE_SIZING fillBuf() after filling in buffer" - +" buf first 100 chars:"+new String(buf, 0, bufEnd < 100 ? bufEnd : 100)); + if (TRACE_SIZING) + System.out.println("TRACE_SIZING fillBuf() after filling in buffer" + " buf first 100 chars:" + + new String(buf, 0, bufEnd < 100 ? bufEnd : 100)); return; } - if(ret == -1) { - if(bufAbsoluteStart == 0 && pos == 0) { + if (ret == -1) { + if (bufAbsoluteStart == 0 && pos == 0) { throw new EOFException("input contained no data"); } else { - if(seenRoot && depth == 0) { // inside parsing epilog!!! + if (seenRoot && depth == 0) { // inside parsing epilog!!! reachedEnd = true; return; } else { StringBuilder expectedTagStack = new StringBuilder(); - if(depth > 0) { - //final char[] cbuf = elRawName[depth]; - //final String startname = new String(cbuf, 0, elRawNameEnd[depth]); + if (depth > 0) { + // final char[] cbuf = elRawName[depth]; + // final String startname = new String(cbuf, 0, elRawNameEnd[depth]); expectedTagStack.append(" - expected end tag"); - if(depth > 1) { - expectedTagStack.append("s"); //more than one end tag + if (depth > 1) { + expectedTagStack.append("s"); // more than one end tag } expectedTagStack.append(" "); - for (int i = depth; i > 0; i--) - { + for (int i = depth; i > 0; i--) { String tagName = new String(elRawName[i], 0, elRawNameEnd[i]); expectedTagStack.append("'); } expectedTagStack.append(" to close"); - for (int i = depth; i > 0; i--) - { - if(i != depth) { - expectedTagStack.append(" and"); //more than one end tag + for (int i = depth; i > 0; i--) { + if (i != depth) { + expectedTagStack.append(" and"); // more than one end tag } String tagName = new String(elRawName[i], 0, elRawNameEnd[i]); - expectedTagStack.append(" start tag <").append(tagName).append(">"); + expectedTagStack + .append(" start tag <") + .append(tagName) + .append(">"); expectedTagStack.append(" from line ").append(elRawNameLine[i]); } expectedTagStack.append(", parser stopped on"); } - throw new EOFException("no more data available" - +expectedTagStack.toString()+getPositionDescription()); + throw new EOFException( + "no more data available" + expectedTagStack.toString() + getPositionDescription()); } } } else { - throw new IOException("error reading input, returned "+ret); + throw new IOException("error reading input, returned " + ret); } } protected char more() throws IOException, XmlPullParserException { - if(pos >= bufEnd) { + if (pos >= bufEnd) { fillBuf(); // this return value should be ignonored as it is used in epilog parsing ... - if(reachedEnd) return (char)-1; + if (reachedEnd) return (char) -1; } final char ch = buf[pos++]; - //line/columnNumber - if(ch == '\n') { ++lineNumber; columnNumber = 1; } - else { ++columnNumber; } - //System.out.print(ch); + // line/columnNumber + if (ch == '\n') { + ++lineNumber; + columnNumber = 1; + } else { + ++columnNumber; + } + // System.out.print(ch); return ch; } @@ -3052,74 +2901,76 @@ protected char more() throws IOException, XmlPullParserException { // } protected void ensurePC(int end) { - //assert end >= pc.length; + // assert end >= pc.length; final int newSize = end > READ_CHUNK_SIZE ? 2 * end : 2 * READ_CHUNK_SIZE; - final char[] newPC = new char[ newSize ]; - if(TRACE_SIZING) System.out.println("TRACE_SIZING ensurePC() "+pc.length+" ==> "+newSize+" end="+end); + final char[] newPC = new char[newSize]; + if (TRACE_SIZING) + System.out.println("TRACE_SIZING ensurePC() " + pc.length + " ==> " + newSize + " end=" + end); System.arraycopy(pc, 0, newPC, 0, pcEnd); pc = newPC; - //assert end < pc.length; + // assert end < pc.length; } protected void joinPC() { - //assert usePC == false; - //assert posEnd > posStart; + // assert usePC == false; + // assert posEnd > posStart; final int len = posEnd - posStart; final int newEnd = pcEnd + len + 1; - if(newEnd >= pc.length) ensurePC(newEnd); // add 1 for extra space for one char - //assert newEnd < pc.length; + if (newEnd >= pc.length) ensurePC(newEnd); // add 1 for extra space for one char + // assert newEnd < pc.length; System.arraycopy(buf, posStart, pc, pcEnd, len); pcEnd += len; usePC = true; - } - protected char requireInput(char ch, char[] input) - throws XmlPullParserException, IOException - { + protected char requireInput(char ch, char[] input) throws XmlPullParserException, IOException { for (char anInput : input) { if (ch != anInput) { throw new XmlPullParserException( - "expected " + printable(anInput) + " in " + new String(input) - + " and not " + printable(ch), this, null); + "expected " + printable(anInput) + " in " + new String(input) + " and not " + printable(ch), + this, + null); } ch = more(); } return ch; } - protected char requireNextS() - throws XmlPullParserException, IOException - { + protected char requireNextS() throws XmlPullParserException, IOException { final char ch = more(); - if(!isS(ch)) { - throw new XmlPullParserException( - "white space is required and not "+printable(ch), this, null); + if (!isS(ch)) { + throw new XmlPullParserException("white space is required and not " + printable(ch), this, null); } return skipS(ch); } - protected char skipS(char ch) - throws XmlPullParserException, IOException - { - while(isS(ch)) { ch = more(); } // skip additional spaces + protected char skipS(char ch) throws XmlPullParserException, IOException { + while (isS(ch)) { + ch = more(); + } // skip additional spaces return ch; } // nameStart / name lookup tables based on XML 1.1 http://www.w3.org/TR/2001/WD-xml11-20011213/ protected static final int LOOKUP_MAX = 0x400; - protected static final char LOOKUP_MAX_CHAR = (char)LOOKUP_MAX; + protected static final char LOOKUP_MAX_CHAR = (char) LOOKUP_MAX; // protected static int lookupNameStartChar[] = new int[ LOOKUP_MAX_CHAR / 32 ]; // protected static int lookupNameChar[] = new int[ LOOKUP_MAX_CHAR / 32 ]; - protected static boolean lookupNameStartChar[] = new boolean[ LOOKUP_MAX ]; - protected static boolean lookupNameChar[] = new boolean[ LOOKUP_MAX ]; + protected static boolean lookupNameStartChar[] = new boolean[LOOKUP_MAX]; + protected static boolean lookupNameChar[] = new boolean[LOOKUP_MAX]; private static final void setName(char ch) - //{ lookupNameChar[ (int)ch / 32 ] |= (1 << (ch % 32)); } - { lookupNameChar[ ch ] = true; } + // { lookupNameChar[ (int)ch / 32 ] |= (1 << (ch % 32)); } + { + lookupNameChar[ch] = true; + } + private static final void setNameStart(char ch) - //{ lookupNameStartChar[ (int)ch / 32 ] |= (1 << (ch % 32)); setName(ch); } - { lookupNameStartChar[ ch ] = true; setName(ch); } + // { lookupNameStartChar[ (int)ch / 32 ] |= (1 << (ch % 32)); setName(ch); } + { + lookupNameStartChar[ch] = true; + setName(ch); + } static { setNameStart(':'); @@ -3137,20 +2988,19 @@ private static final void setNameStart(char ch) for (char ch = '\u0300'; ch <= '\u036f'; ++ch) setName(ch); } - //private final static boolean isNameStartChar(char ch) { + // private final static boolean isNameStartChar(char ch) { protected boolean isNameStartChar(char ch) { - return (ch < LOOKUP_MAX_CHAR && lookupNameStartChar[ ch ]) - || (ch >= LOOKUP_MAX_CHAR && ch <= '\u2027') - || (ch >= '\u202A' && ch <= '\u218F') - || (ch >= '\u2800' && ch <= '\uFFEF') - ; + return (ch < LOOKUP_MAX_CHAR && lookupNameStartChar[ch]) + || (ch >= LOOKUP_MAX_CHAR && ch <= '\u2027') + || (ch >= '\u202A' && ch <= '\u218F') + || (ch >= '\u2800' && ch <= '\uFFEF'); // if(ch < LOOKUP_MAX_CHAR) return lookupNameStartChar[ ch ]; // else return ch <= '\u2027' // || (ch >= '\u202A' && ch <= '\u218F') // || (ch >= '\u2800' && ch <= '\uFFEF') // ; - //return false; + // return false; // return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == ':' // || (ch >= '0' && ch <= '9'); // if(ch < LOOKUP_MAX_CHAR) return (lookupNameStartChar[ (int)ch / 32 ] & (1 << (ch % 32))) != 0; @@ -3163,27 +3013,25 @@ protected boolean isNameStartChar(char ch) { // if(ch <= '\uFFEF') return true; // return false; - // else return (supportXml11 && ( (ch < '\u2027') || (ch > '\u2029' && ch < '\u2200') ... } - //private final static boolean isNameChar(char ch) { + // private final static boolean isNameChar(char ch) { protected boolean isNameChar(char ch) { - //return isNameStartChar(ch); + // return isNameStartChar(ch); // if(ch < LOOKUP_MAX_CHAR) return (lookupNameChar[ (int)ch / 32 ] & (1 << (ch % 32))) != 0; - return (ch < LOOKUP_MAX_CHAR && lookupNameChar[ ch ]) - || (ch >= LOOKUP_MAX_CHAR && ch <= '\u2027') - || (ch >= '\u202A' && ch <= '\u218F') - || (ch >= '\u2800' && ch <= '\uFFEF') - ; - //return false; + return (ch < LOOKUP_MAX_CHAR && lookupNameChar[ch]) + || (ch >= LOOKUP_MAX_CHAR && ch <= '\u2027') + || (ch >= '\u202A' && ch <= '\u218F') + || (ch >= '\u2800' && ch <= '\uFFEF'); + // return false; // return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == ':' // || (ch >= '0' && ch <= '9'); // if(ch < LOOKUP_MAX_CHAR) return (lookupNameStartChar[ (int)ch / 32 ] & (1 << (ch % 32))) != 0; - //else return + // else return // else if(ch <= '\u2027') return true; // //[#x202A-#x218F] // else if(ch < '\u202A') return false; @@ -3191,7 +3039,7 @@ protected boolean isNameChar(char ch) { // // added pairts [#x2800-#xD7FF] | [#xE000-#xFDCF] | [#xFDE0-#xFFEF] | [#x10000-#x10FFFF] // else if(ch < '\u2800') return false; // else if(ch <= '\uFFEF') return true; - //else return false; + // else return false; } protected boolean isS(char ch) { @@ -3199,31 +3047,31 @@ protected boolean isS(char ch) { // || (supportXml11 && (ch == '\u0085' || ch == '\u2028'); } - //protected boolean isChar(char ch) { return (ch < '\uD800' || ch > '\uDFFF') + // protected boolean isChar(char ch) { return (ch < '\uD800' || ch > '\uDFFF') // ch != '\u0000' ch < '\uFFFE' - - //protected char printable(char ch) { return ch; } + // protected char printable(char ch) { return ch; } protected String printable(char ch) { - if(ch == '\n') { + if (ch == '\n') { return "\\n"; - } else if(ch == '\r') { + } else if (ch == '\r') { return "\\r"; - } else if(ch == '\t') { + } else if (ch == '\t') { return "\\t"; - } else if(ch == '\'') { + } else if (ch == '\'') { return "\\'"; - } if(ch > 127 || ch < 32) { - return "\\u"+Integer.toHexString((int)ch); } - return ""+ch; + if (ch > 127 || ch < 32) { + return "\\u" + Integer.toHexString((int) ch); + } + return "" + ch; } protected String printable(String s) { - if(s == null) return null; + if (s == null) return null; final int sLen = s.length(); StringBuilder buf = new StringBuilder(sLen + 10); - for(int i = 0; i < sLen; ++i) { + for (int i = 0; i < sLen; ++i) { buf.append(printable(s.charAt(i))); } s = buf.toString(); @@ -3231,7 +3079,6 @@ protected String printable(String s) { } } - /* * Indiana University Extreme! Lab Software License, Version 1.2 * @@ -3290,9 +3137,3 @@ protected String printable(String s) { * AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION GENERATED USING * SOFTWARE. */ - - - - - - diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/MergeException.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/MergeException.java index 745b33da6..2eff96499 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/MergeException.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/MergeException.java @@ -27,16 +27,12 @@ /** * @author Rahul Thakur */ -public class MergeException - extends Exception -{ - public MergeException( String message, Throwable cause ) - { - super( message, cause ); +public class MergeException extends Exception { + public MergeException(String message, Throwable cause) { + super(message, cause); } - public MergeException( String message ) - { - super( message ); + public MergeException(String message) { + super(message); } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/MergeStrategy.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/MergeStrategy.java index 5b398c3b9..0ae853e3a 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/MergeStrategy.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/MergeStrategy.java @@ -29,8 +29,7 @@ /** * @author Rahul Thakur */ -public interface MergeStrategy -{ +public interface MergeStrategy { /** * Merges a dominant {@link Mergeable} instance with a recessive one. * @@ -38,6 +37,5 @@ public interface MergeStrategy * @param rElt Recessive {@link Mergeable} instance. * @throws MergeException TODO */ - void apply( Mergeable dElt, Mergeable rElt ) - throws MergeException; + void apply(Mergeable dElt, Mergeable rElt) throws MergeException; } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/Merger.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/Merger.java index 2323ef16f..58284e56a 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/Merger.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/Merger.java @@ -33,32 +33,28 @@ /** * @author Rahul Thakur */ -public interface Merger -{ +public interface Merger { String ROLE = Merger.class.getName(); /** * Merge with the recessive document. - * + * * @param dDocument the dominant document. * @param rDocument the recessive document. * @return the merged {@link Document} instance. * * @throws MergeException if there was an error in merge. */ - Document merge( Document dDocument, Document rDocument ) - throws MergeException; + Document merge(Document dDocument, Document rDocument) throws MergeException; /** * Allows writing out a merged JDom Document to the specified file. - * + * * @param mergedDocument the merged {@link Document} instance. * @param file File to write the merged contents to. * @throws IOException if there was an error while writing merged contents to the specified file. */ - void writeMergedDocument( Document mergedDocument, File file ) - throws IOException; - - void mergeDescriptors( File outputDescriptor, List descriptors ) - throws IOException; + void writeMergedDocument(Document mergedDocument, File file) throws IOException; + + void mergeDescriptors(File outputDescriptor, List descriptors) throws IOException; } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/PlexusXmlMerger.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/PlexusXmlMerger.java index 74bf72c31..0882b4053 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/PlexusXmlMerger.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/PlexusXmlMerger.java @@ -33,21 +33,17 @@ * * @author Rahul Thakur */ -@Component(role=Merger.class,hint="plexusXml") -public class PlexusXmlMerger - extends AbstractMerger -{ +@Component(role = Merger.class, hint = "plexusXml") +public class PlexusXmlMerger extends AbstractMerger { /** {@inheritDoc} */ - public Document merge( Document dDocument, Document rDocument ) - throws MergeException - { + public Document merge(Document dDocument, Document rDocument) throws MergeException { // TODO: Ideally we don't want to manipulate the original - // dominant document but use its copy for merge. - //Document mDoc = (Document) dDocument.clone(); // doesn't merge properly + // dominant document but use its copy for merge. + // Document mDoc = (Document) dDocument.clone(); // doesn't merge properly Document mDoc = dDocument; - PlexusRootElement dCSE = new PlexusRootElement( mDoc.getRootElement() ); - PlexusRootElement rCSE = new PlexusRootElement( rDocument.getRootElement() ); - dCSE.merge( rCSE ); + PlexusRootElement dCSE = new PlexusRootElement(mDoc.getRootElement()); + PlexusRootElement rCSE = new PlexusRootElement(rDocument.getRootElement()); + dCSE.merge(rCSE); // the contents are merged into the dominant document DOM. return mDoc; } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/AbstractMergeableElement.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/AbstractMergeableElement.java index 91463a918..5c5ad8af8 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/AbstractMergeableElement.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/AbstractMergeableElement.java @@ -37,12 +37,9 @@ /** * @author Rahul Thakur */ -public abstract class AbstractMergeableElement - extends AbstractMergeableSupport -{ - public AbstractMergeableElement( Element element ) - { - super( element ); +public abstract class AbstractMergeableElement extends AbstractMergeableSupport { + public AbstractMergeableElement(Element element) { + super(element); } /** @@ -56,12 +53,11 @@ public AbstractMergeableElement( Element element ) * @return true if there was a conflict of element. * @deprecated use {@link #isRecessiveElementInConflict(AbstractMergeableElement,List)} instead. */ - protected boolean isRecessiveElementInConflict( AbstractMergeableElement re, String eltName ) - { + protected boolean isRecessiveElementInConflict(AbstractMergeableElement re, String eltName) { // return (null != getChild (eltName) && null != re.getChild (eltName)); List l = new ArrayList(); - l.add( eltName ); - return isRecessiveElementInConflict( re, l ); + l.add(eltName); + return isRecessiveElementInConflict(re, l); } /** @@ -77,14 +73,12 @@ protected boolean isRecessiveElementInConflict( AbstractMergeableElement re, Str * @param eltNameList List of elements that will be checked for values in both dominant and recessive sets. * @return true/false. */ - protected boolean isRecessiveElementInConflict( AbstractMergeableElement re, List eltNameList ) - { + protected boolean isRecessiveElementInConflict(AbstractMergeableElement re, List eltNameList) { // give opportunity to subclasses to provide any custom Composite keys // for conflict checks. - eltNameList = getElementNamesForConflictResolution( eltNameList ); + eltNameList = getElementNamesForConflictResolution(eltNameList); - if ( null == eltNameList || eltNameList.size() == 0 ) - { + if (null == eltNameList || eltNameList.size() == 0) { return false; } @@ -108,9 +102,8 @@ protected boolean isRecessiveElementInConflict( AbstractMergeableElement re, Lis * @param eltName Element name to test for. * @return true/false. */ - protected boolean mergeableElementComesFromRecessive( AbstractMergeableElement re, String eltName ) - { - return null == getChildText( eltName ) && null != re.getChildText( eltName ); + protected boolean mergeableElementComesFromRecessive(AbstractMergeableElement re, String eltName) { + return null == getChildText(eltName) && null != re.getChildText(eltName); } /** @@ -118,58 +111,49 @@ protected boolean mergeableElementComesFromRecessive( AbstractMergeableElement r * * @see Mergeable#merge(Mergeable,org.codehaus.plexus.metadata.merge.MergeStrategy) */ - public void merge( Mergeable me, MergeStrategy strategy ) - throws MergeException - { + public void merge(Mergeable me, MergeStrategy strategy) throws MergeException { // TODO set up a unit test for this! - strategy.apply( this, me ); + strategy.apply(this, me); } - public void merge( Mergeable me ) - throws MergeException - { - if ( !isExpectedElementType( me ) ) - { + public void merge(Mergeable me) throws MergeException { + if (!isExpectedElementType(me)) { // if (getLogger().isErrorEnabled) - // getLogger().error ("Cannot Merge dissimilar elements. (Expected : '" + getClass ().getName () + "', found '" + me.getClass ().getName () + "')"); - throw new MergeException( "Cannot Merge dissimilar elements. " + "(Expected : '" + getClass().getName() + - "', found '" + me.getClass().getName() + "')" ); + // getLogger().error ("Cannot Merge dissimilar elements. (Expected : '" + getClass ().getName () + "', + // found '" + me.getClass ().getName () + "')"); + throw new MergeException("Cannot Merge dissimilar elements. " + "(Expected : '" + + getClass().getName() + "', found '" + me.getClass().getName() + "')"); } // recessive Component Element. AbstractMergeableElement rce = (AbstractMergeableElement) me; Set allowedTags = new HashSet(); - for ( int i = 0; i < getAllowedTags().length; i++ ) - { + for (int i = 0; i < getAllowedTags().length; i++) { String tagName = getAllowedTags()[i].getTagName(); - allowedTags.add( tagName ); + allowedTags.add(tagName); List defaultConflictChecklist = new ArrayList(); - defaultConflictChecklist.add( tagName ); + defaultConflictChecklist.add(tagName); - if ( !isRecessiveElementInConflict( rce, defaultConflictChecklist ) && - mergeableElementComesFromRecessive( rce, tagName ) ) - { - this.addContent( (Element) rce.getChild( tagName ).clone() ); + if (!isRecessiveElementInConflict(rce, defaultConflictChecklist) + && mergeableElementComesFromRecessive(rce, tagName)) { + this.addContent((Element) rce.getChild(tagName).clone()); // else dominant wins in anycase! - } - else - if ( getAllowedTags()[i].isMergeable() && isRecessiveElementInConflict( rce, defaultConflictChecklist ) ) - { + } else if (getAllowedTags()[i].isMergeable() + && isRecessiveElementInConflict(rce, defaultConflictChecklist)) { // this allows for merging multiple/list of elements. - try - { - getAllowedTags()[i].createMergeable( this.getChild( tagName ) ) - .merge( getAllowedTags()[i].createMergeable( rce.getChild( tagName ) ), - getDefaultMergeStrategy() ); - } - catch ( Exception e ) - { + try { + getAllowedTags()[i] + .createMergeable(this.getChild(tagName)) + .merge( + getAllowedTags()[i].createMergeable(rce.getChild(tagName)), + getDefaultMergeStrategy()); + } catch (Exception e) { // TODO log to error throw new MergeException( - "Unable to create Mergeable instance for tag " + "'" + getAllowedTags()[i] + "'.", e ); + "Unable to create Mergeable instance for tag " + "'" + getAllowedTags()[i] + "'.", e); } } } @@ -182,7 +166,5 @@ public void merge( Mergeable me ) element.addContent((Content) child.clone()); } } - } - } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/AbstractMergeableElementList.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/AbstractMergeableElementList.java index 6747f0aeb..fef6efb59 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/AbstractMergeableElementList.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/AbstractMergeableElementList.java @@ -42,12 +42,9 @@ * * @author Rahul Thakur */ -public abstract class AbstractMergeableElementList - extends AbstractMergeableElement -{ - public AbstractMergeableElementList( Element element ) - { - super( element ); +public abstract class AbstractMergeableElementList extends AbstractMergeableElement { + public AbstractMergeableElementList(Element element) { + super(element); } /** @@ -61,11 +58,10 @@ public AbstractMergeableElementList( Element element ) * {@link #getElementNamesForConflictResolution(java.util.List)} * @throws Exception if there was an error parsing and registering {@link Mergeable} instances */ - protected Map parseRecurringMergeables( String tagName, List compositeKeyList, Mergeable parentElement ) - throws Exception - { + protected Map parseRecurringMergeables(String tagName, List compositeKeyList, Mergeable parentElement) + throws Exception { Map mergeables = new LinkedHashMap(); - List list = this.getChildren( tagName ); + List list = this.getChildren(tagName); for (Object aList : list) { Element ce = (Element) aList; @@ -95,14 +91,11 @@ protected Map parseRecurringMergeables( String tagName, List compositeKeyList, M * @return {@link DescriptorTag} instance whose name matches the name specified. * Returns null if no match is found. */ - private DescriptorTag lookupTagInstanceByName( String name, DescriptorTag[] values ) - { + private DescriptorTag lookupTagInstanceByName(String name, DescriptorTag[] values) { DescriptorTag value = null; - for ( int i = 0; i < values.length && value == null; i++ ) - { - if ( values[i].getTagName().equals( name ) ) - { + for (int i = 0; i < values.length && value == null; i++) { + if (values[i].getTagName().equals(name)) { value = values[i]; } } @@ -110,25 +103,21 @@ private DescriptorTag lookupTagInstanceByName( String name, DescriptorTag[] valu return value; } - public void merge( Mergeable me ) - throws MergeException - { - try - { - Map dRequirementsMap = parseRecurringMergeables( getTagNameForRecurringMergeable(), - getElementNamesForConflictResolution( new ArrayList() ), me ); - Map rRequirementsMap = ( (AbstractMergeableElementList) me ) - .parseRecurringMergeables( getTagNameForRecurringMergeable(), - getElementNamesForConflictResolution( new ArrayList() ), me ); - merge( getElement(), dRequirementsMap, rRequirementsMap ); - } - catch ( Exception e ) - { + public void merge(Mergeable me) throws MergeException { + try { + Map dRequirementsMap = parseRecurringMergeables( + getTagNameForRecurringMergeable(), getElementNamesForConflictResolution(new ArrayList()), me); + Map rRequirementsMap = ((AbstractMergeableElementList) me) + .parseRecurringMergeables( + getTagNameForRecurringMergeable(), + getElementNamesForConflictResolution(new ArrayList()), + me); + merge(getElement(), dRequirementsMap, rRequirementsMap); + } catch (Exception e) { // TODO: log to error // TODO: better error message - throw new MergeException( "Unable to merge Mergeable lists for element '" + getName() + "'.", e ); + throw new MergeException("Unable to merge Mergeable lists for element '" + getName() + "'.", e); } - } /** @@ -143,14 +132,11 @@ public void merge( Mergeable me ) * {@link #getElementNamesForConflictResolution(List)} * @throws Exception if there was an error merging both the maps. */ - protected void merge( Element parent, Map dMap, Map rMap ) - throws Exception - { + protected void merge(Element parent, Map dMap, Map rMap) throws Exception { Set dKeySet = dMap.keySet(); Set rKeySet = rMap.keySet(); // check if there are any entities to merge - if ( !isMergeRequired( dKeySet, rKeySet ) ) - { + if (!isMergeRequired(dKeySet, rKeySet)) { return; } @@ -158,7 +144,7 @@ protected void merge( Element parent, Map dMap, Map rMap ) for (Object aDKeySet : dKeySet) { String dKey = (String) aDKeySet; if (rMap.containsKey(dKey)) { - // conflict ! merge this component + // conflict ! merge this component Mergeable dMeregeable = (Mergeable) dMap.get(dKey); Mergeable rMergeable = (Mergeable) rMap.get(dKey); @@ -170,13 +156,13 @@ protected void merge( Element parent, Map dMap, Map rMap ) } // check if any unmerged components are left in the recessive map. - if ( rMap.keySet().size() > 0 ) - { + if (rMap.keySet().size() > 0) { // add them to results for (Object aRKeySet : rKeySet) { String rKey = (String) aRKeySet; // add to parent - parent.addContent((Element) ((Mergeable) rMap.get(rKey)).getElement().clone()); + parent.addContent( + (Element) ((Mergeable) rMap.get(rKey)).getElement().clone()); } } } @@ -188,9 +174,8 @@ protected void merge( Element parent, Map dMap, Map rMap ) * @param rKeySet the recessive set of elements. * @return true if a merge operation was required. */ - private boolean isMergeRequired( Set dKeySet, Set rKeySet ) - { - return ( dKeySet.size() > 0 || rKeySet.size() > 0 ); + private boolean isMergeRequired(Set dKeySet, Set rKeySet) { + return (dKeySet.size() > 0 || rKeySet.size() > 0); } /** @@ -208,5 +193,5 @@ private boolean isMergeRequired( Set dKeySet, Set rKeySet ) */ protected abstract String getTagNameForRecurringMergeable(); - protected abstract List getElementNamesForConflictResolution( List defaultList ); + protected abstract List getElementNamesForConflictResolution(List defaultList); } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/AbstractMergeableSupport.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/AbstractMergeableSupport.java index 38b23cfc3..721f68ea4 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/AbstractMergeableSupport.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/AbstractMergeableSupport.java @@ -45,9 +45,7 @@ * @author khmarbaise * */ -public abstract class AbstractMergeableSupport - implements Mergeable -{ +public abstract class AbstractMergeableSupport implements Mergeable { /** * Wrapped JDOM element. */ @@ -61,14 +59,12 @@ public abstract class AbstractMergeableSupport /** * @param element {@link Element} */ - public AbstractMergeableSupport( Element element ) - { + public AbstractMergeableSupport(Element element) { this.element = element; } /** {@inheritDoc} */ - public abstract void merge( Mergeable me ) - throws MergeException; + public abstract void merge(Mergeable me) throws MergeException; /** * Determines if the passed in {@link Mergeable} was of same type as this @@ -78,7 +74,7 @@ public abstract void merge( Mergeable me ) * @return true if the passed in Mergeable can be merged with * the current Mergeable. */ - protected abstract boolean isExpectedElementType( Mergeable me ); + protected abstract boolean isExpectedElementType(Mergeable me); // ---------------------------------------------------------------------- // Methods delegated on wrapped JDOM element. @@ -88,18 +84,16 @@ public abstract void merge( Mergeable me ) * @param collection {@link Collection} * @return {@link Element}. */ - public Element addContent( Collection collection ) - { - return element.addContent( collection ); + public Element addContent(Collection collection) { + return element.addContent(collection); } /** * @param child {@link Content} * @return {@link Element}. */ - public Element addContent( Content child ) - { - return element.addContent( child ); + public Element addContent(Content child) { + return element.addContent(child); } /** @@ -107,9 +101,8 @@ public Element addContent( Content child ) * @param c {@link Collection} * @return {@link Element}. */ - public Element addContent( int index, Collection c ) - { - return element.addContent( index, c ); + public Element addContent(int index, Collection c) { + return element.addContent(index, c); } /** @@ -117,54 +110,46 @@ public Element addContent( int index, Collection c ) * @param child {@link Content} * @return {@link Element}. */ - public Element addContent( int index, Content child ) - { - return element.addContent( index, child ); + public Element addContent(int index, Content child) { + return element.addContent(index, child); } /** * @param str The content to be added. * @return {@link Element}. */ - public Element addContent( String str ) - { - return element.addContent( str ); + public Element addContent(String str) { + return element.addContent(str); } /** * @param additional {@link Namespace} */ - public void addNamespaceDeclaration( Namespace additional ) - { - element.addNamespaceDeclaration( additional ); + public void addNamespaceDeclaration(Namespace additional) { + element.addNamespaceDeclaration(additional); } - public Object clone() - { + public Object clone() { return element.clone(); } - public List cloneContent() - { + public List cloneContent() { return element.cloneContent(); } - public Content detach() - { + public Content detach() { return element.detach(); } /** {@inheritDoc} */ - public boolean equals( Object obj ) - { - return element.equals( obj ); + public boolean equals(Object obj) { + return element.equals(obj); } /** * @return list of Namespaces. */ - public List getAdditionalNamespaces() - { + public List getAdditionalNamespaces() { return element.getAdditionalNamespaces(); } @@ -173,25 +158,22 @@ public List getAdditionalNamespaces() * @param ns {@link Namespace} * @return {@link Attribute} */ - public Attribute getAttribute( String name, Namespace ns ) - { - return element.getAttribute( name, ns ); + public Attribute getAttribute(String name, Namespace ns) { + return element.getAttribute(name, ns); } /** * @param name The name of the attribute. * @return {@link Attribute} */ - public Attribute getAttribute( String name ) - { - return element.getAttribute( name ); + public Attribute getAttribute(String name) { + return element.getAttribute(name); } /** * @return list {@link Attribute} */ - public List getAttributes() - { + public List getAttributes() { return element.getAttributes(); } @@ -202,9 +184,8 @@ public List getAttributes() * @param def the default value. * @return The value of the attribute. */ - public String getAttributeValue( String name, Namespace ns, String def ) - { - return element.getAttributeValue( name, ns, def ); + public String getAttributeValue(String name, Namespace ns, String def) { + return element.getAttributeValue(name, ns, def); } /** @@ -213,9 +194,8 @@ public String getAttributeValue( String name, Namespace ns, String def ) * @param ns The {@link Namespace} * @return The value of the attribute. */ - public String getAttributeValue( String name, Namespace ns ) - { - return element.getAttributeValue( name, ns ); + public String getAttributeValue(String name, Namespace ns) { + return element.getAttributeValue(name, ns); } /** @@ -224,9 +204,8 @@ public String getAttributeValue( String name, Namespace ns ) * @param def the default value. * @return The value of the attribute. */ - public String getAttributeValue( String name, String def ) - { - return element.getAttributeValue( name, def ); + public String getAttributeValue(String name, String def) { + return element.getAttributeValue(name, def); } /** @@ -234,9 +213,8 @@ public String getAttributeValue( String name, String def ) * @param name The name of the attribute. * @return The value of the attribute. */ - public String getAttributeValue( String name ) - { - return element.getAttributeValue( name ); + public String getAttributeValue(String name) { + return element.getAttributeValue(name); } /** @@ -245,9 +223,8 @@ public String getAttributeValue( String name ) * @return {@link Element} * @see org.jdom2.Element#getChild(java.lang.String,org.jdom2.Namespace) */ - public Element getChild( String name, Namespace ns ) - { - return element.getChild( name, ns ); + public Element getChild(String name, Namespace ns) { + return element.getChild(name, ns); } /** @@ -255,17 +232,15 @@ public Element getChild( String name, Namespace ns ) * @return {@link Element} * @see org.jdom2.Element#getChild(java.lang.String) */ - public Element getChild( String name ) - { - return element.getChild( name ); + public Element getChild(String name) { + return element.getChild(name); } /** * @return list of {@link Element} * @see org.jdom2.Element#getChildren() */ - public List getChildren() - { + public List getChildren() { return element.getChildren(); } @@ -275,9 +250,8 @@ public List getChildren() * @return list {@link Element} * @see org.jdom2.Element#getChildren(java.lang.String,org.jdom2.Namespace) */ - public List getChildren( String name, Namespace ns ) - { - return element.getChildren( name, ns ); + public List getChildren(String name, Namespace ns) { + return element.getChildren(name, ns); } /** @@ -285,9 +259,8 @@ public List getChildren( String name, Namespace ns ) * @return list {@link Element} * @see org.jdom2.Element#getChildren(java.lang.String) */ - public List getChildren( String name ) - { - return element.getChildren( name ); + public List getChildren(String name) { + return element.getChildren(name); } /** @@ -296,9 +269,8 @@ public List getChildren( String name ) * @return the child text. * @see org.jdom2.Element#getChildText(java.lang.String,org.jdom2.Namespace) */ - public String getChildText( String name, Namespace ns ) - { - return element.getChildText( name, ns ); + public String getChildText(String name, Namespace ns) { + return element.getChildText(name, ns); } /** @@ -306,9 +278,8 @@ public String getChildText( String name, Namespace ns ) * @return the child text. * @see org.jdom2.Element#getChildText(java.lang.String) */ - public String getChildText( String name ) - { - return element.getChildText( name ); + public String getChildText(String name) { + return element.getChildText(name); } /** @@ -317,9 +288,8 @@ public String getChildText( String name ) * @return the child text. * @see org.jdom2.Element#getChildTextNormalize(java.lang.String,org.jdom2.Namespace) */ - public String getChildTextNormalize( String name, Namespace ns ) - { - return element.getChildTextNormalize( name, ns ); + public String getChildTextNormalize(String name, Namespace ns) { + return element.getChildTextNormalize(name, ns); } /** @@ -327,9 +297,8 @@ public String getChildTextNormalize( String name, Namespace ns ) * @return the child text. * @see org.jdom2.Element#getChildTextNormalize(java.lang.String) */ - public String getChildTextNormalize( String name ) - { - return element.getChildTextNormalize( name ); + public String getChildTextNormalize(String name) { + return element.getChildTextNormalize(name); } /** @@ -338,9 +307,8 @@ public String getChildTextNormalize( String name ) * @return the child text. * @see org.jdom2.Element#getChildTextTrim(java.lang.String,org.jdom2.Namespace) */ - public String getChildTextTrim( String name, Namespace ns ) - { - return element.getChildTextTrim( name, ns ); + public String getChildTextTrim(String name, Namespace ns) { + return element.getChildTextTrim(name, ns); } /** @@ -348,17 +316,15 @@ public String getChildTextTrim( String name, Namespace ns ) * @return the child text. * @see org.jdom2.Element#getChildTextTrim(java.lang.String) */ - public String getChildTextTrim( String name ) - { - return element.getChildTextTrim( name ); + public String getChildTextTrim(String name) { + return element.getChildTextTrim(name); } /** * @see org.jdom2.Element#getContent() * @return list of content. */ - public List getContent() - { + public List getContent() { return element.getContent(); } @@ -367,9 +333,8 @@ public List getContent() * @return list of content. * @see org.jdom2.Element#getContent(org.jdom2.filter.Filter) */ - public List getContent( Filter filter ) - { - return element.getContent( filter ); + public List getContent(Filter filter) { + return element.getContent(filter); } /** @@ -377,17 +342,15 @@ public List getContent( Filter filter ) * @return the content. * @see org.jdom2.Element#getContent(int) */ - public Content getContent( int index ) - { - return element.getContent( index ); + public Content getContent(int index) { + return element.getContent(index); } /** * @return The content size. * @see org.jdom2.Element#getContentSize() */ - public int getContentSize() - { + public int getContentSize() { return element.getContentSize(); } @@ -395,8 +358,7 @@ public int getContentSize() * @return {@link Iterator} of descendants. * @see org.jdom2.Element#getDescendants() */ - public Iterator getDescendants() - { + public Iterator getDescendants() { return element.getDescendants(); } @@ -405,17 +367,15 @@ public Iterator getDescendants() * @return {@link Iterator} of descendants. * @see org.jdom2.Element#getDescendants(org.jdom2.filter.Filter) */ - public Iterator getDescendants( Filter filter ) - { - return element.getDescendants( filter ); + public Iterator getDescendants(Filter filter) { + return element.getDescendants(filter); } /** * @return the document. * @see org.jdom2.Content#getDocument() */ - public Document getDocument() - { + public Document getDocument() { return element.getDocument(); } @@ -423,8 +383,7 @@ public Document getDocument() * @return The name of the element. * @see org.jdom2.Element#getName() */ - public String getName() - { + public String getName() { return element.getName(); } @@ -432,8 +391,7 @@ public String getName() * @return {@link Namespace} * @see org.jdom2.Element#getNamespace() */ - public Namespace getNamespace() - { + public Namespace getNamespace() { return element.getNamespace(); } @@ -442,17 +400,15 @@ public Namespace getNamespace() * @return {@link Namespace} * @see org.jdom2.Element#getNamespace(java.lang.String) */ - public Namespace getNamespace( String prefix ) - { - return element.getNamespace( prefix ); + public Namespace getNamespace(String prefix) { + return element.getNamespace(prefix); } /** * @return the namespace prefix. * @see org.jdom2.Element#getNamespacePrefix() */ - public String getNamespacePrefix() - { + public String getNamespacePrefix() { return element.getNamespacePrefix(); } @@ -460,8 +416,7 @@ public String getNamespacePrefix() * @return the namespace URI. * @see org.jdom2.Element#getNamespaceURI() */ - public String getNamespaceURI() - { + public String getNamespaceURI() { return element.getNamespaceURI(); } @@ -469,8 +424,7 @@ public String getNamespaceURI() * @return The parent. * @see org.jdom2.Content#getParent() */ - public Parent getParent() - { + public Parent getParent() { return element.getParent(); } @@ -478,8 +432,7 @@ public Parent getParent() * @return the parent {@link Element} * @see org.jdom2.Content#getParentElement() */ - public Element getParentElement() - { + public Element getParentElement() { return element.getParentElement(); } @@ -487,8 +440,7 @@ public Element getParentElement() * @return The qualified name. * @see org.jdom2.Element#getQualifiedName() */ - public String getQualifiedName() - { + public String getQualifiedName() { return element.getQualifiedName(); } @@ -496,8 +448,7 @@ public String getQualifiedName() * @return The text. * @see org.jdom2.Element#getText() */ - public String getText() - { + public String getText() { return element.getText(); } @@ -505,8 +456,7 @@ public String getText() * @return the normalized text. * @see org.jdom2.Element#getTextNormalize() */ - public String getTextNormalize() - { + public String getTextNormalize() { return element.getTextNormalize(); } @@ -514,8 +464,7 @@ public String getTextNormalize() * @return the trimmed text. * @see org.jdom2.Element#getTextTrim() */ - public String getTextTrim() - { + public String getTextTrim() { return element.getTextTrim(); } @@ -523,16 +472,14 @@ public String getTextTrim() * @return the element value. * @see org.jdom2.Element#getValue() */ - public String getValue() - { + public String getValue() { return element.getValue(); } /** * @see java.lang.Object#hashCode() */ - public int hashCode() - { + public int hashCode() { return element.hashCode(); } @@ -541,9 +488,8 @@ public int hashCode() * @return the index. * @see org.jdom2.Element#indexOf(org.jdom2.Content) */ - public int indexOf( Content child ) - { - return element.indexOf( child ); + public int indexOf(Content child) { + return element.indexOf(child); } /** @@ -551,17 +497,15 @@ public int indexOf( Content child ) * @param element {@link Element}. * @return true/false. */ - public boolean isAncestor( Element element ) - { - return element.isAncestor( element ); + public boolean isAncestor(Element element) { + return element.isAncestor(element); } /** * @see org.jdom2.Element#isRootElement() * @return true/false. */ - public boolean isRootElement() - { + public boolean isRootElement() { return element.isRootElement(); } @@ -570,9 +514,8 @@ public boolean isRootElement() * @param attribute {@link Attribute} * @return true/false. */ - public boolean removeAttribute( Attribute attribute ) - { - return element.removeAttribute( attribute ); + public boolean removeAttribute(Attribute attribute) { + return element.removeAttribute(attribute); } /** @@ -581,9 +524,8 @@ public boolean removeAttribute( Attribute attribute ) * @param ns The {@link Namespace} * @return true/false. */ - public boolean removeAttribute( String name, Namespace ns ) - { - return element.removeAttribute( name, ns ); + public boolean removeAttribute(String name, Namespace ns) { + return element.removeAttribute(name, ns); } /** @@ -591,9 +533,8 @@ public boolean removeAttribute( String name, Namespace ns ) * @param name The mame of the attribute. * @return true/false. */ - public boolean removeAttribute( String name ) - { - return element.removeAttribute( name ); + public boolean removeAttribute(String name) { + return element.removeAttribute(name); } /** @@ -602,9 +543,8 @@ public boolean removeAttribute( String name ) * @param ns {@link Namespace} * @return true/false. */ - public boolean removeChild( String name, Namespace ns ) - { - return element.removeChild( name, ns ); + public boolean removeChild(String name, Namespace ns) { + return element.removeChild(name, ns); } /** @@ -612,9 +552,8 @@ public boolean removeChild( String name, Namespace ns ) * @param name The name of the child. * @return true/false. */ - public boolean removeChild( String name ) - { - return element.removeChild( name ); + public boolean removeChild(String name) { + return element.removeChild(name); } /** @@ -623,9 +562,8 @@ public boolean removeChild( String name ) * @param ns {@link Namespace} * @return true/false. */ - public boolean removeChildren( String name, Namespace ns ) - { - return element.removeChildren( name, ns ); + public boolean removeChildren(String name, Namespace ns) { + return element.removeChildren(name, ns); } /** @@ -633,17 +571,15 @@ public boolean removeChildren( String name, Namespace ns ) * @param name name of the child. * @return true/false. */ - public boolean removeChildren( String name ) - { - return element.removeChildren( name ); + public boolean removeChildren(String name) { + return element.removeChildren(name); } /** * @see org.jdom2.Element#removeContent() * @return list of elements. */ - public List removeContent() - { + public List removeContent() { return element.removeContent(); } @@ -652,9 +588,8 @@ public List removeContent() * @param child {@link Content} * @return true/false. */ - public boolean removeContent( Content child ) - { - return element.removeContent( child ); + public boolean removeContent(Content child) { + return element.removeContent(child); } /** @@ -662,9 +597,8 @@ public boolean removeContent( Content child ) * @param filter {@link Filter}. * @return list of elements. */ - public List removeContent( Filter filter ) - { - return element.removeContent( filter ); + public List removeContent(Filter filter) { + return element.removeContent(filter); } /** @@ -672,18 +606,16 @@ public List removeContent( Filter filter ) * @param index The index. * @return {@link Content} */ - public Content removeContent( int index ) - { - return element.removeContent( index ); + public Content removeContent(int index) { + return element.removeContent(index); } /** * @see org.jdom2.Element#removeNamespaceDeclaration(org.jdom2.Namespace) * @param additionalNamespace {@link Namespace}. */ - public void removeNamespaceDeclaration( Namespace additionalNamespace ) - { - element.removeNamespaceDeclaration( additionalNamespace ); + public void removeNamespaceDeclaration(Namespace additionalNamespace) { + element.removeNamespaceDeclaration(additionalNamespace); } /** @@ -691,9 +623,8 @@ public void removeNamespaceDeclaration( Namespace additionalNamespace ) * @return {@link Element}. * @see org.jdom2.Element#setAttribute(org.jdom2.Attribute) */ - public Element setAttribute( Attribute attribute ) - { - return element.setAttribute( attribute ); + public Element setAttribute(Attribute attribute) { + return element.setAttribute(attribute); } /** @@ -703,9 +634,8 @@ public Element setAttribute( Attribute attribute ) * @param ns {@link Namespace}. * @return {@link Element} */ - public Element setAttribute( String name, String value, Namespace ns ) - { - return element.setAttribute( name, value, ns ); + public Element setAttribute(String name, String value, Namespace ns) { + return element.setAttribute(name, value, ns); } /** @@ -714,18 +644,16 @@ public Element setAttribute( String name, String value, Namespace ns ) * @return {@link Element} * @see org.jdom2.Element#setAttribute(java.lang.String,java.lang.String) */ - public Element setAttribute( String name, String value ) - { - return element.setAttribute( name, value ); + public Element setAttribute(String name, String value) { + return element.setAttribute(name, value); } /** - * @param newAttributes list of new attributes. + * @param newAttributes list of new attributes. * @return {@link Element} */ - public Element setAttributes( List newAttributes ) - { - return element.setAttributes( newAttributes ); + public Element setAttributes(List newAttributes) { + return element.setAttributes(newAttributes); } /** @@ -733,9 +661,8 @@ public Element setAttributes( List newAttributes ) * @return {@link Element} * @see org.jdom2.Element#setContent(java.util.Collection) */ - public Element setContent( Collection newContent ) - { - return element.setContent( newContent ); + public Element setContent(Collection newContent) { + return element.setContent(newContent); } /** @@ -743,9 +670,8 @@ public Element setContent( Collection newContent ) * @return {@link Element} * @see org.jdom2.Element#setContent(org.jdom2.Content) */ - public Element setContent( Content child ) - { - return element.setContent( child ); + public Element setContent(Content child) { + return element.setContent(child); } /** @@ -754,9 +680,8 @@ public Element setContent( Content child ) * @return {@link Parent} * @see org.jdom2.Element#setContent(int,java.util.Collection) */ - public Parent setContent( int index, Collection collection ) - { - return element.setContent( index, collection ); + public Parent setContent(int index, Collection collection) { + return element.setContent(index, collection); } /** @@ -765,9 +690,8 @@ public Parent setContent( int index, Collection collection ) * @return {@link Element} * @see org.jdom2.Element#setContent(int,org.jdom2.Content) */ - public Element setContent( int index, Content child ) - { - return element.setContent( index, child ); + public Element setContent(int index, Content child) { + return element.setContent(index, child); } /** @@ -775,9 +699,8 @@ public Element setContent( int index, Content child ) * @return {@link Element} * @see org.jdom2.Element#setName(java.lang.String) */ - public Element setName( String name ) - { - return element.setName( name ); + public Element setName(String name) { + return element.setName(name); } /** @@ -785,9 +708,8 @@ public Element setName( String name ) * @see org.jdom2.Element#setNamespace(org.jdom2.Namespace) * @return {@link Element} */ - public Element setNamespace( Namespace namespace ) - { - return element.setNamespace( namespace ); + public Element setNamespace(Namespace namespace) { + return element.setNamespace(namespace); } /** @@ -795,17 +717,15 @@ public Element setNamespace( Namespace namespace ) * @param text The text to be set. * @return {@link Element} */ - public Element setText( String text ) - { - return element.setText( text ); + public Element setText(String text) { + return element.setText(text); } /** * {@link org.jdom2.Element#toString()} * {@inheritDoc} */ - public String toString() - { + public String toString() { return element.toString(); } @@ -813,19 +733,17 @@ public String toString() * Returns the wrapped up JDom {@link Element} instance. * {@inheritDoc} */ - public Element getElement() - { + public Element getElement() { return this.element; } /** * Sub classes should override if they wish to provide a different * combination of composite keys for determining conflicts. - * @param defaultList the default list. + * @param defaultList the default list. * @return the default list. */ - protected List getElementNamesForConflictResolution( List defaultList ) - { + protected List getElementNamesForConflictResolution(List defaultList) { return defaultList; } @@ -833,9 +751,7 @@ protected List getElementNamesForConflictResolution( List defaultList ) * Returns the default {@link MergeStrategy} instance. * @return {@link MergeStrategy} */ - protected MergeStrategy getDefaultMergeStrategy() - { + protected MergeStrategy getDefaultMergeStrategy() { return DEFAULT_MERGE_STRATEGY; } - } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ComponentElement.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ComponentElement.java index 077655978..056e930e5 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ComponentElement.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ComponentElement.java @@ -29,9 +29,7 @@ /** * @author Rahul Thakur */ -public class ComponentElement - extends AbstractMergeableElement -{ +public class ComponentElement extends AbstractMergeableElement { /** * Allowed elements/tags that we can expect under this element. */ @@ -45,40 +43,38 @@ public class ComponentElement DESCRIPTION, ISOLATION_REALM, CONFIGURATION, - RequirementsElement.TAG }; + RequirementsElement.TAG + }; - static final DescriptorTag TAG = new DescriptorTag( "component", true, ComponentElement.class ); + static final DescriptorTag TAG = new DescriptorTag("component", true, ComponentElement.class); - static final DescriptorTag ROLE = new DescriptorTag( "role" ); + static final DescriptorTag ROLE = new DescriptorTag("role"); - static final DescriptorTag ROLE_HINT = new DescriptorTag( "role-hint" ); + static final DescriptorTag ROLE_HINT = new DescriptorTag("role-hint"); - static final DescriptorTag OPTIONAL = new DescriptorTag( "optional" ); - - static final DescriptorTag ISOLATION_REALM = new DescriptorTag( "isolated-realm" ); + static final DescriptorTag OPTIONAL = new DescriptorTag("optional"); - private static final DescriptorTag DESCRIPTION = new DescriptorTag( "description" ); - - private static final DescriptorTag CONFIGURATION = new DescriptorTag( "configuration" ); + static final DescriptorTag ISOLATION_REALM = new DescriptorTag("isolated-realm"); - static final DescriptorTag FIELD_NAME = new DescriptorTag( "field-name" ); + private static final DescriptorTag DESCRIPTION = new DescriptorTag("description"); - private static final DescriptorTag IMPLEMENTATION = new DescriptorTag( "implementation" ); + private static final DescriptorTag CONFIGURATION = new DescriptorTag("configuration"); - private static final DescriptorTag LIFECYCLE_HANDLER = new DescriptorTag( "lifecycle-handler", false, null ); + static final DescriptorTag FIELD_NAME = new DescriptorTag("field-name"); - public ComponentElement( Element element ) - { - super( element ); + private static final DescriptorTag IMPLEMENTATION = new DescriptorTag("implementation"); + + private static final DescriptorTag LIFECYCLE_HANDLER = new DescriptorTag("lifecycle-handler", false, null); + + public ComponentElement(Element element) { + super(element); } - protected boolean isExpectedElementType( Mergeable me ) - { + protected boolean isExpectedElementType(Mergeable me) { return me instanceof ComponentElement; } - public DescriptorTag[] getAllowedTags() - { + public DescriptorTag[] getAllowedTags() { return allowedTags; } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ComponentSetElement.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ComponentSetElement.java index 1e1146198..95c5a6b33 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ComponentSetElement.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ComponentSetElement.java @@ -29,21 +29,16 @@ /** * @author Rahul Thakur */ -public class ComponentSetElement - extends AbstractMergeableElement -{ - public ComponentSetElement( Element element ) - { - super( element ); +public class ComponentSetElement extends AbstractMergeableElement { + public ComponentSetElement(Element element) { + super(element); } - public DescriptorTag[] getAllowedTags() - { - return new DescriptorTag[]{ComponentsElement.TAG}; + public DescriptorTag[] getAllowedTags() { + return new DescriptorTag[] {ComponentsElement.TAG}; } - protected boolean isExpectedElementType( Mergeable me ) - { + protected boolean isExpectedElementType(Mergeable me) { return me instanceof ComponentSetElement; } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ComponentsElement.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ComponentsElement.java index 5510312c9..885797d68 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ComponentsElement.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ComponentsElement.java @@ -32,48 +32,40 @@ /** * @author Rahul Thakur */ -public class ComponentsElement - extends AbstractMergeableElementList -{ - static final DescriptorTag TAG = new DescriptorTag( "components", true, ComponentsElement.class ); +public class ComponentsElement extends AbstractMergeableElementList { + static final DescriptorTag TAG = new DescriptorTag("components", true, ComponentsElement.class); private List conflictVerificationkeys = new ArrayList(); - public ComponentsElement( Element element ) - { - super( element ); + public ComponentsElement(Element element) { + super(element); - conflictVerificationkeys.add( ComponentElement.ROLE.getTagName() ); - conflictVerificationkeys.add( ComponentElement.ROLE_HINT.getTagName() ); + conflictVerificationkeys.add(ComponentElement.ROLE.getTagName()); + conflictVerificationkeys.add(ComponentElement.ROLE_HINT.getTagName()); } - public DescriptorTag[] getAllowedTags() - { - return new DescriptorTag[]{ComponentElement.TAG}; + public DescriptorTag[] getAllowedTags() { + return new DescriptorTag[] {ComponentElement.TAG}; } - protected boolean isExpectedElementType( Mergeable me ) - { - return ( me instanceof ComponentsElement ); + protected boolean isExpectedElementType(Mergeable me) { + return (me instanceof ComponentsElement); } - protected List getElementNamesForConflictChecks( List defaultList ) - { + protected List getElementNamesForConflictChecks(List defaultList) { // Allow to return custom keys for conflict checks/resolution. return this.conflictVerificationkeys; } - protected String getTagNameForRecurringMergeable() - { + protected String getTagNameForRecurringMergeable() { return ComponentElement.TAG.getTagName(); } - protected List getElementNamesForConflictResolution( List defaultList ) - { + protected List getElementNamesForConflictResolution(List defaultList) { // TODO: how is this different from getElementNamesForConflictChecks? List l = new ArrayList(); - l.add( ComponentElement.ROLE.getTagName() ); - l.add( ComponentElement.ROLE_HINT.getTagName() ); + l.add(ComponentElement.ROLE.getTagName()); + l.add(ComponentElement.ROLE_HINT.getTagName()); return l; } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ConfigurationElement.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ConfigurationElement.java index 0c2dec2ac..2d7010f13 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ConfigurationElement.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/ConfigurationElement.java @@ -31,21 +31,16 @@ * * @author Rahul Thakur */ -public class ConfigurationElement - extends AbstractMergeableElement -{ - public ConfigurationElement( Element element ) - { - super( element ); +public class ConfigurationElement extends AbstractMergeableElement { + public ConfigurationElement(Element element) { + super(element); } - protected boolean isExpectedElementType( Mergeable me ) - { + protected boolean isExpectedElementType(Mergeable me) { return me instanceof ConfigurationElement; } - public DescriptorTag[] getAllowedTags() - { + public DescriptorTag[] getAllowedTags() { // TODO Implement! return new DescriptorTag[0]; } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/DescriptorTag.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/DescriptorTag.java index 9e8ea1ce5..5737d85de 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/DescriptorTag.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/DescriptorTag.java @@ -1,25 +1,25 @@ package org.codehaus.plexus.metadata.merge.support; -/* +/* * ======================================================================== - * - * Copyright 2003 The Apache Software Foundation. Code from this file + * + * Copyright 2003 The Apache Software Foundation. Code from this file * was originally imported from the Jakarta Cactus project. - * + * * Copyright 2004-2006 Vincent Massol. * * 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. - * + * * ======================================================================== */ @@ -31,8 +31,7 @@ * Represents the various top-level tags in a deployment descriptor as a typesafe enumeration. * */ -public class DescriptorTag -{ +public class DescriptorTag { /** * The tag name. */ @@ -53,9 +52,8 @@ public class DescriptorTag * * @param tagName The tag name of the element */ - public DescriptorTag( String tagName ) - { - this( tagName, false, null ); + public DescriptorTag(String tagName) { + this(tagName, false, null); } /** @@ -65,9 +63,8 @@ public DescriptorTag( String tagName ) * @param isMultipleAllowed Whether the element may occur multiple times in the descriptor * @deprecated Use {@link #DescriptorTag(String,boolean,Class)} instead */ - public DescriptorTag( String tagName, boolean isMultipleAllowed ) - { - this( tagName, isMultipleAllowed, null ); + public DescriptorTag(String tagName, boolean isMultipleAllowed) { + this(tagName, isMultipleAllowed, null); } /** @@ -77,34 +74,28 @@ public DescriptorTag( String tagName, boolean isMultipleAllowed ) * @param isMultipleAllowed Whether the element may occur multiple times in the descriptor * @param mergeableClass Concrete implementation of {@link Mergeable} that is bound this tag. */ - public DescriptorTag( String tagName, boolean isMultipleAllowed, Class mergeableClass ) - { + public DescriptorTag(String tagName, boolean isMultipleAllowed, Class mergeableClass) { this.tagName = tagName; this.multipleAllowed = isMultipleAllowed; this.mergeableClass = mergeableClass; } - public boolean equals( Object other ) - { + public boolean equals(Object other) { boolean eq = false; - if ( other instanceof DescriptorTag ) - { + if (other instanceof DescriptorTag) { DescriptorTag tag = (DescriptorTag) other; - if ( tag.getTagName().equals( this.tagName ) ) - { + if (tag.getTagName().equals(this.tagName)) { eq = true; } } return eq; } - public int hashCode() - { + public int hashCode() { return this.getTagName().hashCode(); } - public String getTagName() - { + public String getTagName() { return this.tagName; } @@ -113,8 +104,7 @@ public String getTagName() * * @return Whether multiple occurrences are allowed */ - public boolean isMultipleAllowed() - { + public boolean isMultipleAllowed() { return this.multipleAllowed; } @@ -125,13 +115,11 @@ public boolean isMultipleAllowed() * * @return true if this tag is mergeable. */ - public boolean isMergeable() - { + public boolean isMergeable() { return null != this.mergeableClass; } - public String toString() - { + public String toString() { return getTagName(); } @@ -143,26 +131,20 @@ public String toString() * @return instance of {@link Mergeable}. * @throws Exception if there was an error creating an instance. */ - public Mergeable createMergeable( Element element ) - throws Exception - { - Constructor cons = this.mergeableClass.getConstructor( new Class[] { Element.class } ); + public Mergeable createMergeable(Element element) throws Exception { + Constructor cons = this.mergeableClass.getConstructor(new Class[] {Element.class}); // XXX Is there a better way to determine this? - if ( this.mergeableClass.getSuperclass().equals( AbstractMergeableElementList.class ) ) - { - return (AbstractMergeableElementList) cons.newInstance( new Object[] { element } ); - } - else if ( this.mergeableClass.getSuperclass().equals( AbstractMergeableElement.class ) ) - { - return (AbstractMergeableElement) cons.newInstance( new Object[] { element } ); - } - else - { + if (this.mergeableClass.getSuperclass().equals(AbstractMergeableElementList.class)) { + return (AbstractMergeableElementList) cons.newInstance(new Object[] {element}); + } else if (this.mergeableClass.getSuperclass().equals(AbstractMergeableElement.class)) { + return (AbstractMergeableElement) cons.newInstance(new Object[] {element}); + } else { // TODO set up Logger // if (getLogger ().isErrorEnabled ()) - // getLogger.error ( "Could not create Mergeable instance for specified class '" + this.mergeableClass + "'" ); - throw new Exception( "Could not create Mergeable instance for specified class " + "'" + this.mergeableClass - + "'" ); + // getLogger.error ( "Could not create Mergeable instance for specified class '" + this.mergeableClass + + // "'" ); + throw new Exception( + "Could not create Mergeable instance for specified class " + "'" + this.mergeableClass + "'"); } } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/MergeStrategies.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/MergeStrategies.java index 6aa2b5914..819c1a5fc 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/MergeStrategies.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/MergeStrategies.java @@ -36,18 +36,14 @@ * * @author Rahul Thakur */ -public class MergeStrategies -{ +public class MergeStrategies { /** * {@link MergeStrategy} implementation wherein the elements are merged * down to the deepest available {@link Mergeable} instance in the DOM tree. */ - public static final MergeStrategy DEEP = new MergeStrategy() - { - public void apply( Mergeable dElt, Mergeable rElt ) - throws MergeException - { - dElt.merge( rElt ); + public static final MergeStrategy DEEP = new MergeStrategy() { + public void apply(Mergeable dElt, Mergeable rElt) throws MergeException { + dElt.merge(rElt); } }; @@ -56,25 +52,21 @@ public void apply( Mergeable dElt, Mergeable rElt ) * which the merge operation is called is 'merged'. The merge does not * traverse the DOM tree any further. */ - public static final MergeStrategy SHALLOW = new MergeStrategy() - { + public static final MergeStrategy SHALLOW = new MergeStrategy() { /** * @throws MergeException * @see org.codehaus.plexus.metadata.merge.MergeStrategy#apply(Mergeable,Mergeable) */ - public void apply( Mergeable dElt, Mergeable rElt ) - throws MergeException - { + public void apply(Mergeable dElt, Mergeable rElt) throws MergeException { AbstractMergeableElement dame = (AbstractMergeableElement) dElt; AbstractMergeableElement rame = (AbstractMergeableElement) rElt; // check if the dominant was in conflict with recessive. - List elementNames = dame.getElementNamesForConflictResolution( Collections.EMPTY_LIST ); + List elementNames = dame.getElementNamesForConflictResolution(Collections.EMPTY_LIST); - if ( !dame.isRecessiveElementInConflict( rame, elementNames ) ) - { + if (!dame.isRecessiveElementInConflict(rame, elementNames)) { // no conflict, simply add recessive to dominant's parent - dame.getElement().addContent( rame.getElement() ); + dame.getElement().addContent(rame.getElement()); } } }; diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/Mergeable.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/Mergeable.java index 5457d9614..d4d26eb9d 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/Mergeable.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/Mergeable.java @@ -35,16 +35,14 @@ * * @author Rahul Thakur */ -public interface Mergeable -{ +public interface Mergeable { /** * Merges an element of same type. * * @param me Another entity that is mergeable. * @throws MergeException if there was an error merging the mergeables. */ - void merge( Mergeable me ) - throws MergeException; + void merge(Mergeable me) throws MergeException; /** * Applies the passed in {@link MergeStrategy} to merge two {@link Mergeable} instance.

@@ -53,8 +51,7 @@ void merge( Mergeable me ) * @param strategy {@link MergeStrategy} to apply for merging. * @throws MergeException if there was an error while merging. */ - void merge( Mergeable me, MergeStrategy strategy ) - throws MergeException; + void merge(Mergeable me, MergeStrategy strategy) throws MergeException; /** * Returns the wrapped up JDom {@link Element} instance that was used to create this Mergeable. diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/PlexusRootElement.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/PlexusRootElement.java index 5d6f964d1..f814e0f14 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/PlexusRootElement.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/PlexusRootElement.java @@ -29,22 +29,17 @@ /** * @author Rahul Thakur */ -public class PlexusRootElement - extends AbstractMergeableElement -{ - public PlexusRootElement( Element element ) - { - super( element ); +public class PlexusRootElement extends AbstractMergeableElement { + public PlexusRootElement(Element element) { + super(element); } - public DescriptorTag[] getAllowedTags() - { + public DescriptorTag[] getAllowedTags() { // TODO: add the managers, etc - return new DescriptorTag[]{ComponentsElement.TAG}; + return new DescriptorTag[] {ComponentsElement.TAG}; } - protected boolean isExpectedElementType( Mergeable me ) - { + protected boolean isExpectedElementType(Mergeable me) { return me instanceof PlexusRootElement; } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/PlexusXmlTag.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/PlexusXmlTag.java index 849715b4a..b149a4ff7 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/PlexusXmlTag.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/PlexusXmlTag.java @@ -10,44 +10,38 @@ * * @author Rahul Thakur */ -public class PlexusXmlTag - extends DescriptorTag -{ - public static final PlexusXmlTag COMPONENT_SET = new PlexusXmlTag( "component-set", - false, ComponentSetElement.class ); +public class PlexusXmlTag extends DescriptorTag { + public static final PlexusXmlTag COMPONENT_SET = + new PlexusXmlTag("component-set", false, ComponentSetElement.class); - public static final PlexusXmlTag COMPONENTS = new PlexusXmlTag( "components", - true, ComponentsElement.class ); + public static final PlexusXmlTag COMPONENTS = new PlexusXmlTag("components", true, ComponentsElement.class); - public static final PlexusXmlTag COMPONENT = new PlexusXmlTag( "component", true, ComponentElement.class ); + public static final PlexusXmlTag COMPONENT = new PlexusXmlTag("component", true, ComponentElement.class); - public static final PlexusXmlTag ROLE = new PlexusXmlTag( "role" ); + public static final PlexusXmlTag ROLE = new PlexusXmlTag("role"); - public static final PlexusXmlTag ROLE_HINT = new PlexusXmlTag( "role-hint" ); + public static final PlexusXmlTag ROLE_HINT = new PlexusXmlTag("role-hint"); - public static final PlexusXmlTag FIELD_NAME = new PlexusXmlTag( "field-name" ); + public static final PlexusXmlTag FIELD_NAME = new PlexusXmlTag("field-name"); - public static final PlexusXmlTag IMPLEMENTATION = new PlexusXmlTag( "implementation" ); + public static final PlexusXmlTag IMPLEMENTATION = new PlexusXmlTag("implementation"); - public static final PlexusXmlTag LIFECYCLE_HANDLER = new PlexusXmlTag( "lifecycle-handler", false, null ); + public static final PlexusXmlTag LIFECYCLE_HANDLER = new PlexusXmlTag("lifecycle-handler", false, null); - public static final PlexusXmlTag REQUIREMENTS = - new PlexusXmlTag( "requirements", true, RequirementsElement.class ); + public static final PlexusXmlTag REQUIREMENTS = new PlexusXmlTag("requirements", true, RequirementsElement.class); public static final PlexusXmlTag CONFIGURATION = - new PlexusXmlTag( "configuration", true, ConfigurationElement.class ); + new PlexusXmlTag("configuration", true, ConfigurationElement.class); - public static final PlexusXmlTag REQUIREMENT = - new PlexusXmlTag( "requirement", true, RequirementElement.class ); + public static final PlexusXmlTag REQUIREMENT = new PlexusXmlTag("requirement", true, RequirementElement.class); /** * @param tagName * @param isMultipleAllowed * @param mergeableClass Class that wraps this tag (as JDom element) and provides for merging same tags. */ - private PlexusXmlTag( String tagName, boolean isMultipleAllowed, Class mergeableClass ) - { - super( tagName, isMultipleAllowed, mergeableClass ); + private PlexusXmlTag(String tagName, boolean isMultipleAllowed, Class mergeableClass) { + super(tagName, isMultipleAllowed, mergeableClass); } /** @@ -55,8 +49,7 @@ private PlexusXmlTag( String tagName, boolean isMultipleAllowed, Class mergeable * * @param tagName */ - private PlexusXmlTag( String tagName ) - { - super( tagName, false, null ); + private PlexusXmlTag(String tagName) { + super(tagName, false, null); } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/RequirementElement.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/RequirementElement.java index 6a32a2139..a086f3a1e 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/RequirementElement.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/RequirementElement.java @@ -30,30 +30,24 @@ /** * @author Rahul Thakur */ -public class RequirementElement - extends AbstractMergeableElement -{ - static final DescriptorTag TAG = new DescriptorTag( "requirement", true, RequirementElement.class ); +public class RequirementElement extends AbstractMergeableElement { + static final DescriptorTag TAG = new DescriptorTag("requirement", true, RequirementElement.class); - public RequirementElement( Element element ) - { - super( element ); + public RequirementElement(Element element) { + super(element); } - public DescriptorTag[] getAllowedTags() - { - return new DescriptorTag[] { ComponentElement.ROLE, ComponentElement.ROLE_HINT, ComponentElement.FIELD_NAME, - ComponentElement.OPTIONAL }; + public DescriptorTag[] getAllowedTags() { + return new DescriptorTag[] { + ComponentElement.ROLE, ComponentElement.ROLE_HINT, ComponentElement.FIELD_NAME, ComponentElement.OPTIONAL + }; } - public void merge( Mergeable me ) - throws MergeException - { - super.merge( me ); + public void merge(Mergeable me) throws MergeException { + super.merge(me); } - protected boolean isExpectedElementType( Mergeable me ) - { + protected boolean isExpectedElementType(Mergeable me) { return me instanceof RequirementElement; } } diff --git a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/RequirementsElement.java b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/RequirementsElement.java index 391d596c7..64eb17e2a 100644 --- a/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/RequirementsElement.java +++ b/plexus-component-metadata/src/main/java/org/codehaus/plexus/metadata/merge/support/RequirementsElement.java @@ -32,39 +32,32 @@ /** * @author Rahul Thakur */ -public class RequirementsElement - extends AbstractMergeableElementList -{ - public static final DescriptorTag TAG = new DescriptorTag( "requirements", true, RequirementsElement.class ); +public class RequirementsElement extends AbstractMergeableElementList { + public static final DescriptorTag TAG = new DescriptorTag("requirements", true, RequirementsElement.class); - public RequirementsElement( Element element ) - { - super( element ); + public RequirementsElement(Element element) { + super(element); } - protected boolean isExpectedElementType( Mergeable me ) - { + protected boolean isExpectedElementType(Mergeable me) { return me instanceof RequirementsElement; } - public DescriptorTag[] getAllowedTags() - { - return new DescriptorTag[]{RequirementElement.TAG}; + public DescriptorTag[] getAllowedTags() { + return new DescriptorTag[] {RequirementElement.TAG}; } - protected List getElementNamesForConflictResolution( List defaultList ) - { + protected List getElementNamesForConflictResolution(List defaultList) { // we return the keys that we know we want to lookup to identify and // resolve conflicts. List l = new ArrayList(); - l.add( ComponentElement.ROLE.getTagName() ); + l.add(ComponentElement.ROLE.getTagName()); // TODO: add this back, but a test will fail (based on a role with no hint, which shouldn't be legal) -// l.add( ComponentElement.ROLE_HINT.getTagName() ); + // l.add( ComponentElement.ROLE_HINT.getTagName() ); return l; } - protected String getTagNameForRecurringMergeable() - { + protected String getTagNameForRecurringMergeable() { return RequirementElement.TAG.getTagName(); } } diff --git a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/DefaultComponentDescriptorWriterTest.java b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/DefaultComponentDescriptorWriterTest.java index 4c27b34ee..c25dc7ec9 100644 --- a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/DefaultComponentDescriptorWriterTest.java +++ b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/DefaultComponentDescriptorWriterTest.java @@ -43,9 +43,7 @@ * * @version $Rev$ $Date$ */ -public class DefaultComponentDescriptorWriterTest - extends PlexusTestCase -{ +public class DefaultComponentDescriptorWriterTest extends PlexusTestCase { private DefaultComponentDescriptorWriter descriptorWriter; // @Override @@ -78,16 +76,16 @@ public void testBasic() throws Exception { descriptorWriter.writeDescriptorSet(writer, set, false); writer.flush(); writer.close(); - + String xml = writer.toString(); assertTrue(xml.length() != 0); PlexusConfiguration config = new XmlPlexusConfiguration(Xpp3DomBuilder.build(new StringReader(xml))); assertNotNull(config); - - ClassWorld classWorld = new ClassWorld( "test", Thread.currentThread().getContextClassLoader() ); - ClassRealm realm = classWorld.getRealm( "test" ); + + ClassWorld classWorld = new ClassWorld("test", Thread.currentThread().getContextClassLoader()); + ClassRealm realm = classWorld.getRealm("test"); ComponentSetDescriptor set2 = buildComponentSet(config, realm); assertNotNull(set2); @@ -97,7 +95,7 @@ public void testBasic() throws Exception { ComponentDescriptor component2 = components.get(0); assertNotNull(component2); - + assertEquals(component.getRole(), component2.getRole()); assertEquals(component.getRoleHint(), component2.getRoleHint()); assertEquals(component.getComponentFactory(), component2.getComponentFactory()); @@ -128,34 +126,63 @@ public void testComponentsOrder() throws Exception { List components = doc.getRootElement().getChild("components").getChildren(); assertEquals("Number of components", 5, components.size()); - assertEquals("Component 1 role", ComponentDescriptorExtractor.class.getName(), components.get(0).getChild("role").getText()); - assertEquals("Component 1 impl", ClassComponentDescriptorExtractor.class.getName(), components.get(0).getChild("implementation").getText()); - - assertEquals("Component 2 role", ComponentDescriptorExtractor.class.getName(), components.get(1).getChild("role").getText()); - assertEquals("Component 2 impl", SourceComponentDescriptorExtractor.class.getName(), components.get(1).getChild("implementation").getText()); - - assertEquals("Component 3 role", MetadataGenerator.class.getName(), components.get(2).getChild("role").getText()); - assertEquals("Component 3 impl", DefaultMetadataGenerator.class.getName(), components.get(2).getChild("implementation").getText()); - - assertEquals("Component 4 role", Merger.class.getName(), components.get(3).getChild("role").getText()); - assertEquals("Component 4 impl", ComponentsXmlMerger.class.getName(), components.get(3).getChild("implementation").getText()); - - assertEquals("Component 5 role", Merger.class.getName(), components.get(4).getChild("role").getText()); - assertEquals("Component 5 impl", PlexusXmlMerger.class.getName(), components.get(4).getChild("implementation").getText()); + assertEquals( + "Component 1 role", + ComponentDescriptorExtractor.class.getName(), + components.get(0).getChild("role").getText()); + assertEquals( + "Component 1 impl", + ClassComponentDescriptorExtractor.class.getName(), + components.get(0).getChild("implementation").getText()); + + assertEquals( + "Component 2 role", + ComponentDescriptorExtractor.class.getName(), + components.get(1).getChild("role").getText()); + assertEquals( + "Component 2 impl", + SourceComponentDescriptorExtractor.class.getName(), + components.get(1).getChild("implementation").getText()); + + assertEquals( + "Component 3 role", + MetadataGenerator.class.getName(), + components.get(2).getChild("role").getText()); + assertEquals( + "Component 3 impl", + DefaultMetadataGenerator.class.getName(), + components.get(2).getChild("implementation").getText()); + + assertEquals( + "Component 4 role", + Merger.class.getName(), + components.get(3).getChild("role").getText()); + assertEquals( + "Component 4 impl", + ComponentsXmlMerger.class.getName(), + components.get(3).getChild("implementation").getText()); + + assertEquals( + "Component 5 role", + Merger.class.getName(), + components.get(4).getChild("role").getText()); + assertEquals( + "Component 5 impl", + PlexusXmlMerger.class.getName(), + components.get(4).getChild("implementation").getText()); } // TODO copied from PlexusTools.buildConfiguration() - find a better way to do this // we have duplication here, but we don't want to depend on plexus-container-default // similar code in AnnotationComponentGleaner.glean() and QDoxComponentGleaner.findRequirements() - private static ComponentSetDescriptor buildComponentSet( PlexusConfiguration c, ClassRealm realm ) - throws PlexusConfigurationException - { + private static ComponentSetDescriptor buildComponentSet(PlexusConfiguration c, ClassRealm realm) + throws PlexusConfigurationException { ComponentSetDescriptor csd = new ComponentSetDescriptor(); - for (PlexusConfiguration component : c.getChild( "components" ).getChildren( "component" )) { + for (PlexusConfiguration component : c.getChild("components").getChildren("component")) { csd.addComponentDescriptor(buildComponentDescriptorImpl(component, realm)); } - for (PlexusConfiguration d : c.getChild( "dependencies" ).getChildren( "dependency" )) { + for (PlexusConfiguration d : c.getChild("dependencies").getChildren("dependency")) { ComponentDependency cd = new ComponentDependency(); cd.setArtifactId(d.getChild("artifact-id").getValue()); cd.setGroupId(d.getChild("group-id").getValue()); @@ -169,51 +196,43 @@ private static ComponentSetDescriptor buildComponentSet( PlexusConfiguration c, return csd; } - private static ComponentDescriptor buildComponentDescriptorImpl( PlexusConfiguration configuration, - ClassRealm realm ) - throws PlexusConfigurationException - { - String implementation = configuration.getChild( "implementation" ).getValue(); - if (implementation == null) - { - throw new PlexusConfigurationException( "implementation is null" ); + private static ComponentDescriptor buildComponentDescriptorImpl( + PlexusConfiguration configuration, ClassRealm realm) throws PlexusConfigurationException { + String implementation = configuration.getChild("implementation").getValue(); + if (implementation == null) { + throw new PlexusConfigurationException("implementation is null"); } ComponentDescriptor cd; - try - { - if ( realm != null ) - { - Class implementationClass = realm.loadClass( implementation ); + try { + if (realm != null) { + Class implementationClass = realm.loadClass(implementation); cd = new ComponentDescriptor<>(implementationClass, realm); - } - else - { + } else { cd = new ComponentDescriptor<>(); - cd.setImplementation( implementation ); + cd.setImplementation(implementation); } + } catch (Throwable e) { + throw new PlexusConfigurationException( + "Can not load implementation class " + implementation + " from realm " + realm, e); } - catch ( Throwable e ) - { - throw new PlexusConfigurationException("Can not load implementation class " + implementation + - " from realm " + realm, e); - } - cd.setRole( configuration.getChild( "role" ).getValue() ); - cd.setRoleHint( configuration.getChild( "role-hint" ).getValue() ); - cd.setVersion( configuration.getChild( "version" ).getValue() ); - cd.setComponentType( configuration.getChild( "component-type" ).getValue() ); - cd.setInstantiationStrategy( configuration.getChild( "instantiation-strategy" ).getValue() ); - cd.setLifecycleHandler( configuration.getChild( "lifecycle-handler" ).getValue() ); - cd.setComponentProfile( configuration.getChild( "component-profile" ).getValue() ); - cd.setComponentComposer( configuration.getChild( "component-composer" ).getValue() ); - cd.setComponentConfigurator( configuration.getChild( "component-configurator" ).getValue() ); - cd.setComponentFactory( configuration.getChild( "component-factory" ).getValue() ); - cd.setDescription( configuration.getChild( "description" ).getValue() ); - cd.setAlias( configuration.getChild( "alias" ).getValue() ); - String s = configuration.getChild( "isolated-realm" ).getValue(); - - if ( s != null ) - { + cd.setRole(configuration.getChild("role").getValue()); + cd.setRoleHint(configuration.getChild("role-hint").getValue()); + cd.setVersion(configuration.getChild("version").getValue()); + cd.setComponentType(configuration.getChild("component-type").getValue()); + cd.setInstantiationStrategy( + configuration.getChild("instantiation-strategy").getValue()); + cd.setLifecycleHandler(configuration.getChild("lifecycle-handler").getValue()); + cd.setComponentProfile(configuration.getChild("component-profile").getValue()); + cd.setComponentComposer(configuration.getChild("component-composer").getValue()); + cd.setComponentConfigurator( + configuration.getChild("component-configurator").getValue()); + cd.setComponentFactory(configuration.getChild("component-factory").getValue()); + cd.setDescription(configuration.getChild("description").getValue()); + cd.setAlias(configuration.getChild("alias").getValue()); + String s = configuration.getChild("isolated-realm").getValue(); + + if (s != null) { cd.setIsolatedRealm(s.equals("true")); } @@ -221,12 +240,12 @@ private static ComponentDescriptor buildComponentDescriptorImpl( PlexusConfig // Here we want to look for directives for inlining external // configurations. we probably want to take them from files or URLs. // ---------------------------------------------------------------------- - cd.setConfiguration( configuration.getChild( "configuration" ) ); + cd.setConfiguration(configuration.getChild("configuration")); // ---------------------------------------------------------------------- // Requirements // ---------------------------------------------------------------------- - for (PlexusConfiguration requirement : configuration.getChild( "requirements" ) - .getChildren( "requirement" )) { + for (PlexusConfiguration requirement : + configuration.getChild("requirements").getChildren("requirement")) { ComponentRequirement cr; PlexusConfiguration[] hints = requirement.getChild("role-hints").getChildren("role-hint"); diff --git a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/AbstractClass.java b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/AbstractClass.java index 9f8d49590..11a83b772 100644 --- a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/AbstractClass.java +++ b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/AbstractClass.java @@ -20,6 +20,4 @@ * ??? * */ -public abstract class AbstractClass -{ -} +public abstract class AbstractClass {} diff --git a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/AbstractWithAnnoClass.java b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/AbstractWithAnnoClass.java index 1bcaf06b3..3de94fdcb 100644 --- a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/AbstractWithAnnoClass.java +++ b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/AbstractWithAnnoClass.java @@ -21,6 +21,4 @@ * @plexus.component role="foo" * */ -public abstract class AbstractWithAnnoClass -{ -} +public abstract class AbstractWithAnnoClass {} diff --git a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/AnnotationComponentGleanerTest.java b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/AnnotationComponentGleanerTest.java index e152526a2..ff5425351 100644 --- a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/AnnotationComponentGleanerTest.java +++ b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/AnnotationComponentGleanerTest.java @@ -18,6 +18,7 @@ import java.util.List; +import junit.framework.TestCase; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.ComponentRequirement; import org.codehaus.plexus.component.repository.ComponentRequirementList; @@ -25,39 +26,36 @@ import org.codehaus.plexus.metadata.gleaner.ann.AnnotatedComponent; import org.codehaus.plexus.metadata.gleaner.ann.AnnotatedComponentRole; -import junit.framework.TestCase; - /** * @author Eugene Kuleshov */ public class AnnotationComponentGleanerTest extends TestCase { - public void testGlean() throws Exception { - AnnotationComponentGleaner gleaner = new AnnotationComponentGleaner(); - Class c = AnnotatedComponent.class; - ComponentDescriptor descriptor = gleaner.glean(c.getName(), c.getClassLoader()); - - assertEquals("foo", descriptor.getComponentType()); - assertEquals(AnnotatedComponentRole.class.getName(), descriptor.getRole()); - - List requirements = descriptor.getRequirements(); - assertEquals(requirements.toString(), 2, requirements.size()); - - ComponentRequirement requirement = requirements.get(0); - assertEquals("dependency", requirement.getFieldName()); - assertEquals("default", requirement.getRoleHint()); - - ComponentRequirement requirement2 = requirements.get(1); - assertEquals("dependency2", requirement2.getFieldName()); - assertTrue(requirement2 instanceof ComponentRequirementList); - assertEquals("release,latest,snapshot", - String.join(",", ((ComponentRequirementList) requirement2).getRoleHints())); - - PlexusConfiguration configuration = descriptor.getConfiguration(); - assertEquals(1, configuration.getChildCount()); - PlexusConfiguration child = configuration.getChild(0); - assertEquals("param", child.getName()); - assertEquals("value", child.getValue()); - } - + public void testGlean() throws Exception { + AnnotationComponentGleaner gleaner = new AnnotationComponentGleaner(); + Class c = AnnotatedComponent.class; + ComponentDescriptor descriptor = gleaner.glean(c.getName(), c.getClassLoader()); + + assertEquals("foo", descriptor.getComponentType()); + assertEquals(AnnotatedComponentRole.class.getName(), descriptor.getRole()); + + List requirements = descriptor.getRequirements(); + assertEquals(requirements.toString(), 2, requirements.size()); + + ComponentRequirement requirement = requirements.get(0); + assertEquals("dependency", requirement.getFieldName()); + assertEquals("default", requirement.getRoleHint()); + + ComponentRequirement requirement2 = requirements.get(1); + assertEquals("dependency2", requirement2.getFieldName()); + assertTrue(requirement2 instanceof ComponentRequirementList); + assertEquals( + "release,latest,snapshot", String.join(",", ((ComponentRequirementList) requirement2).getRoleHints())); + + PlexusConfiguration configuration = descriptor.getConfiguration(); + assertEquals(1, configuration.getChildCount()); + PlexusConfiguration child = configuration.getChild(0); + assertEquals("param", child.getName()); + assertEquals("value", child.getValue()); + } } diff --git a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ChildComponent.java b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ChildComponent.java index fa25f8fc4..8432cb56b 100644 --- a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ChildComponent.java +++ b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ChildComponent.java @@ -22,6 +22,4 @@ * @plexus.component role="org.codehaus.plexus.metadata.gleaner.ChildComponent" * */ -public class ChildComponent -{ -} +public class ChildComponent {} diff --git a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/MyComponent.java b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/MyComponent.java index fa3df171c..2b9cfefb7 100644 --- a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/MyComponent.java +++ b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/MyComponent.java @@ -23,8 +23,7 @@ * * @version $Rev: 7691 $ $Date$ */ -public class MyComponent -{ +public class MyComponent { /** * @plexus.requirement */ diff --git a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/NoAnnotationsClass.java b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/NoAnnotationsClass.java index 626ee494c..9869ab04d 100644 --- a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/NoAnnotationsClass.java +++ b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/NoAnnotationsClass.java @@ -20,6 +20,4 @@ * ??? * */ -public class NoAnnotationsClass -{ -} +public class NoAnnotationsClass {} diff --git a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/NoAnnotationsIntf.java b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/NoAnnotationsIntf.java index 99cee94fe..3e318258b 100644 --- a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/NoAnnotationsIntf.java +++ b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/NoAnnotationsIntf.java @@ -20,6 +20,4 @@ * ??? * */ -public interface NoAnnotationsIntf -{ -} +public interface NoAnnotationsIntf {} diff --git a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/QDoxComponentGleanerTest.java b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/QDoxComponentGleanerTest.java index 117a2eff7..aaa71ffcd 100644 --- a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/QDoxComponentGleanerTest.java +++ b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/QDoxComponentGleanerTest.java @@ -1,11 +1,11 @@ /* * Copyright (C) 2007 the original author or authors. - * + * * 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 @@ -18,31 +18,26 @@ import java.io.IOException; import java.util.List; +import com.thoughtworks.qdox.JavaProjectBuilder; +import com.thoughtworks.qdox.model.JavaClass; +import com.thoughtworks.qdox.model.JavaSource; import org.codehaus.plexus.PlexusTestCase; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.ComponentRequirement; import org.codehaus.plexus.configuration.PlexusConfiguration; -import com.thoughtworks.qdox.JavaProjectBuilder; -import com.thoughtworks.qdox.model.JavaClass; -import com.thoughtworks.qdox.model.JavaSource; - /** * Tests for the {@link QDoxComponentGleaner} class. - * + * * @version $Rev$ $Date$ */ -public class QDoxComponentGleanerTest - extends PlexusTestCase -{ +public class QDoxComponentGleanerTest extends PlexusTestCase { private QDoxComponentGleaner gleaner; private JavaProjectBuilder builder; // @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); gleaner = new QDoxComponentGleaner(); @@ -50,71 +45,56 @@ protected void setUp() } // @Override - protected void tearDown() - throws Exception - { + protected void tearDown() throws Exception { gleaner = null; builder = null; super.tearDown(); } - private JavaSource addSource( final String name ) - throws IOException - { - File url = new File( getBasedir(), "src/test/java/" + getClass().getPackage().getName().replace( '.', '/' ) + "/" + name ); - assertTrue( url.exists() ); - return builder.addSource( url ); + private JavaSource addSource(final String name) throws IOException { + File url = new File( + getBasedir(), + "src/test/java/" + getClass().getPackage().getName().replace('.', '/') + "/" + name); + assertTrue(url.exists()); + return builder.addSource(url); } - - private JavaClass loadJavaClass( final String name ) - throws IOException - { - JavaSource source = addSource( name ); - assertNotNull( source ); + private JavaClass loadJavaClass(final String name) throws IOException { + JavaSource source = addSource(name); + assertNotNull(source); List classes = source.getClasses(); - assertNotNull( classes ); - assertEquals( 1, classes.size() ); + assertNotNull(classes); + assertEquals(1, classes.size()); - assertNotNull( classes.get(0) ); + assertNotNull(classes.get(0)); return classes.get(0); } - private ComponentDescriptor glean( final String name, final String[] supporting ) - throws Exception - { - if ( supporting != null ) - { - for ( String aSupporting : supporting ) - { - addSource( aSupporting ); + private ComponentDescriptor glean(final String name, final String[] supporting) throws Exception { + if (supporting != null) { + for (String aSupporting : supporting) { + addSource(aSupporting); } } - return gleaner.glean( builder, loadJavaClass( name ) ); + return gleaner.glean(builder, loadJavaClass(name)); } - private ComponentDescriptor glean( final String name ) - throws Exception - { - return glean( name, null ); + private ComponentDescriptor glean(final String name) throws Exception { + return glean(name, null); } - public void testNoAnnotationsClass() - throws Exception - { - ComponentDescriptor component = glean( "NoAnnotationsClass.java" ); - assertNull( component ); + public void testNoAnnotationsClass() throws Exception { + ComponentDescriptor component = glean("NoAnnotationsClass.java"); + assertNull(component); } - public void testAbstractClass() - throws Exception - { - ComponentDescriptor component = glean( "AbstractClass.java" ); - assertNull( component ); + public void testAbstractClass() throws Exception { + ComponentDescriptor component = glean("AbstractClass.java"); + assertNull(component); } /* @@ -124,38 +104,34 @@ public void testAbstractWithAnnoClass() throws Exception { } */ - public void testNoAnnotationsIntf() - throws Exception - { - ComponentDescriptor component = glean( "NoAnnotationsIntf.java" ); - assertNull( component ); + public void testNoAnnotationsIntf() throws Exception { + ComponentDescriptor component = glean("NoAnnotationsIntf.java"); + assertNull(component); } - public void testMyComponent() - throws Exception - { - addSource( "ChildComponent.java" ); - ComponentDescriptor component = glean( "MyComponent.java" ); - assertNotNull( component ); + public void testMyComponent() throws Exception { + addSource("ChildComponent.java"); + ComponentDescriptor component = glean("MyComponent.java"); + assertNotNull(component); - assertEquals( MyComponent.class.getName(), component.getRole() ); - assertEquals( "foo", component.getRoleHint() ); + assertEquals(MyComponent.class.getName(), component.getRole()); + assertEquals("foo", component.getRoleHint()); List requirements = component.getRequirements(); - assertNotNull( requirements ); - assertEquals( 1, requirements.size() ); + assertNotNull(requirements); + assertEquals(1, requirements.size()); - ComponentRequirement requirement = requirements.get( 0 ); - assertNotNull( requirement ); - assertEquals( ChildComponent.class.getName(), requirement.getRole() ); + ComponentRequirement requirement = requirements.get(0); + assertNotNull(requirement); + assertEquals(ChildComponent.class.getName(), requirement.getRole()); PlexusConfiguration config = component.getConfiguration(); - assertNotNull( config ); - assertEquals( 1, config.getChildCount() ); + assertNotNull(config); + assertEquals(1, config.getChildCount()); - PlexusConfiguration child = config.getChild( 0 ); - assertNotNull( child ); - assertEquals( "foo", child.getName() ); - assertEquals( "bar", child.getValue() ); + PlexusConfiguration child = config.getChild(0); + assertNotNull(child); + assertEquals("foo", child.getName()); + assertEquals("bar", child.getValue()); } } diff --git a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ann/AnnotatedComponent.java b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ann/AnnotatedComponent.java index 982e458f8..830497f2f 100644 --- a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ann/AnnotatedComponent.java +++ b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ann/AnnotatedComponent.java @@ -25,14 +25,15 @@ /** * @author Eugene Kuleshov */ -@Component(type="foo", role=AnnotatedComponentRole.class) +@Component(type = "foo", role = AnnotatedComponentRole.class) public class AnnotatedComponent implements AnnotatedComponentRole { - @Requirement(hint="default") - @Configuration(name="param", value="value") - AnnotatedComponentDependency dependency; - - @Requirement(role=AnnotatedComponentDependency.class, hints={"release", "latest", "snapshot"}) - List dependency2; - + @Requirement(hint = "default") + @Configuration(name = "param", value = "value") + AnnotatedComponentDependency dependency; + + @Requirement( + role = AnnotatedComponentDependency.class, + hints = {"release", "latest", "snapshot"}) + List dependency2; } diff --git a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ann/AnnotatedComponentDependency.java b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ann/AnnotatedComponentDependency.java index 2e13057a5..6d0a197bb 100644 --- a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ann/AnnotatedComponentDependency.java +++ b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ann/AnnotatedComponentDependency.java @@ -19,6 +19,4 @@ /** * @author Eugene Kuleshov */ -public class AnnotatedComponentDependency { - -} +public class AnnotatedComponentDependency {} diff --git a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ann/AnnotatedComponentRole.java b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ann/AnnotatedComponentRole.java index 8710d27a9..73a03070a 100644 --- a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ann/AnnotatedComponentRole.java +++ b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/gleaner/ann/AnnotatedComponentRole.java @@ -16,6 +16,4 @@ package org.codehaus.plexus.metadata.gleaner.ann; -public interface AnnotatedComponentRole { - -} +public interface AnnotatedComponentRole {} diff --git a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/merge/ComponentsXmlMergerTest.java b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/merge/ComponentsXmlMergerTest.java index e3b2ff567..97dcab216 100644 --- a/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/merge/ComponentsXmlMergerTest.java +++ b/plexus-component-metadata/src/test/java/org/codehaus/plexus/metadata/merge/ComponentsXmlMergerTest.java @@ -44,87 +44,84 @@ * * @author Rahul Thakur */ -public class ComponentsXmlMergerTest - extends PlexusTestCase -{ - public void testBasic() - throws Exception - { - ComponentsXmlMerger merger = (ComponentsXmlMerger) lookup( Merger.class, "componentsXml" ); - assertNotNull( merger ); +public class ComponentsXmlMergerTest extends PlexusTestCase { + public void testBasic() throws Exception { + ComponentsXmlMerger merger = (ComponentsXmlMerger) lookup(Merger.class, "componentsXml"); + assertNotNull(merger); } - public void testComponentsXmlFileMerge() - throws Exception - { - File dominantXml = getTestFile( "src/test/resources/org/codehaus/plexus/metadata/merge/dominant.xml" ); - File recessiveXml = getTestFile( "src/test/resources/org/codehaus/plexus/metadata/merge/recessive.xml" ); - Document dDoc = new SAXBuilder().build( dominantXml ); - Document rDoc = new SAXBuilder().build( recessiveXml ); + public void testComponentsXmlFileMerge() throws Exception { + File dominantXml = getTestFile("src/test/resources/org/codehaus/plexus/metadata/merge/dominant.xml"); + File recessiveXml = getTestFile("src/test/resources/org/codehaus/plexus/metadata/merge/recessive.xml"); + Document dDoc = new SAXBuilder().build(dominantXml); + Document rDoc = new SAXBuilder().build(recessiveXml); // ComponentsXmlMerger merger = new ComponentsXmlMerger (dDoc); - Merger merger = lookup( Merger.class, "componentsXml" ); - assertNotNull( merger ); - merger.merge( dDoc, rDoc ); + Merger merger = lookup(Merger.class, "componentsXml"); + assertNotNull(merger); + merger.merge(dDoc, rDoc); - File merged_xml = getTestFile( "target/merged.xml" ); - if ( merged_xml.exists() ) - { - FileUtils.forceDelete( merged_xml ); + File merged_xml = getTestFile("target/merged.xml"); + if (merged_xml.exists()) { + FileUtils.forceDelete(merged_xml); } - merger.writeMergedDocument( dDoc, merged_xml ); - assertTrue( merged_xml.exists() ); - // read merged xml and verify it was merged as expected - Document mDoc = new SAXBuilder().build( merged_xml ); + merger.writeMergedDocument(dDoc, merged_xml); + assertTrue(merged_xml.exists()); + // read merged xml and verify it was merged as expected + Document mDoc = new SAXBuilder().build(merged_xml); Element mRootElt = mDoc.getRootElement(); - assertTrue( mRootElt.getName().equals( "component-set" ) ); - assertEquals( 1, mRootElt.getChildren( "components" ).size() ); - List componentEltList = mRootElt.getChild( "components" ).getChildren( "component" ); - assertEquals( 2, componentEltList.size() ); - Element cElt = (Element) componentEltList.get( 0 ); + assertTrue(mRootElt.getName().equals("component-set")); + assertEquals(1, mRootElt.getChildren("components").size()); + List componentEltList = mRootElt.getChild("components").getChildren("component"); + assertEquals(2, componentEltList.size()); + Element cElt = (Element) componentEltList.get(0); - assertEquals( "org.codehaus.plexus.metadata.component.IComponent", cElt.getChildTextTrim( "role" ) ); - assertEquals( "org.codehaus.plexus.metadata.component.DominantComponent", cElt.getChildTextTrim( "implementation" ) ); + assertEquals("org.codehaus.plexus.metadata.component.IComponent", cElt.getChildTextTrim("role")); + assertEquals( + "org.codehaus.plexus.metadata.component.DominantComponent", cElt.getChildTextTrim("implementation")); - assertEquals( "Should only have 1 description element.", 1, cElt.getChildren( "description" ).size() ); - assertEquals( "Description for Dominant component", cElt.getChildTextTrim( "description" ) ); + assertEquals( + "Should only have 1 description element.", + 1, + cElt.getChildren("description").size()); + assertEquals("Description for Dominant component", cElt.getChildTextTrim("description")); - assertEquals( "Should only have 1 configuration element.", 1, cElt.getChildren( "configuration" ).size() ); + assertEquals( + "Should only have 1 configuration element.", + 1, + cElt.getChildren("configuration").size()); // assert Merged configuration properties - Element configurationElt = cElt.getChild( "configuration" ); - assertNotNull( configurationElt ); - assertEquals( 1, configurationElt.getChildren( "prop1" ).size() ); - assertEquals( "Dominant Property1 value", configurationElt.getChildTextTrim( "prop1" ) ); - assertEquals( 1, configurationElt.getChildren( "prop2" ).size() ); - assertEquals( 0, configurationElt.getChildren( "prop3" ).size() ); + Element configurationElt = cElt.getChild("configuration"); + assertNotNull(configurationElt); + assertEquals(1, configurationElt.getChildren("prop1").size()); + assertEquals("Dominant Property1 value", configurationElt.getChildTextTrim("prop1")); + assertEquals(1, configurationElt.getChildren("prop2").size()); + assertEquals(0, configurationElt.getChildren("prop3").size()); // now for the second component - cElt = (Element) componentEltList.get( 1 ); - assertEquals( "org.codehaus.plexus.metadata.component.INonConflictingComponent", cElt.getChildTextTrim( "role" ) ); - assertEquals( "org.codehaus.plexus.metadata.component.RecessiveComponent", cElt.getChildTextTrim( "implementation" ) ); + cElt = (Element) componentEltList.get(1); + assertEquals("org.codehaus.plexus.metadata.component.INonConflictingComponent", cElt.getChildTextTrim("role")); + assertEquals( + "org.codehaus.plexus.metadata.component.RecessiveComponent", cElt.getChildTextTrim("implementation")); - assertEquals( 1, mRootElt.getChildren( "lifecycle-handler-manager" ).size() ); - assertEquals( "org.codehaus.plexus.lifecycle.DefaultLifecycleHandlerManager", mRootElt - .getChild( "lifecycle-handler-manager" ).getAttributeValue( "implementation" ) ); + assertEquals(1, mRootElt.getChildren("lifecycle-handler-manager").size()); + assertEquals( + "org.codehaus.plexus.lifecycle.DefaultLifecycleHandlerManager", + mRootElt.getChild("lifecycle-handler-manager").getAttributeValue("implementation")); } - public void testInvalidMergeableElements() - throws Exception - { + public void testInvalidMergeableElements() throws Exception { // dominant Component Element - AbstractMergeableElement dCE = new ComponentElement( new Element( "component" ) ); - Element roleElt = new Element( "role" ); - roleElt.setText( "org.codehaus.plexus.ISampleRole" ); - dCE.addContent( roleElt ); + AbstractMergeableElement dCE = new ComponentElement(new Element("component")); + Element roleElt = new Element("role"); + roleElt.setText("org.codehaus.plexus.ISampleRole"); + dCE.addContent(roleElt); - AbstractMergeableElementList reqElt = new RequirementsElement( new Element( "requirement" ) ); + AbstractMergeableElementList reqElt = new RequirementsElement(new Element("requirement")); // attempt and invalid merge - try - { - dCE.merge( reqElt ); - fail( "Expected MergeException!" ); - } - catch ( MergeException e ) - { + try { + dCE.merge(reqElt); + fail("Expected MergeException!"); + } catch (MergeException e) { // do nothing. } } @@ -134,63 +131,67 @@ public void testInvalidMergeableElements() * * @throws Exception if there was an unexpected error. */ - public void testComponentsMerge() - throws Exception - { + public void testComponentsMerge() throws Exception { // dominant Components Element - AbstractMergeableElement dParent = new ComponentsElement( new Element( "components" ) ); - Element dCE = new Element( "component" ); - dParent.addContent( dCE ); - Element roleElt = new Element( "role" ); - roleElt.setText( "org.codehaus.plexus.ISampleRole" ); - dCE.addContent( roleElt ); - Element roleHintElt = new Element( "role-hint" ); - roleHintElt.setText( "sample-role-hint" ); - dCE.addContent( roleHintElt ); - Element implElt = new Element( "implementation" ); - implElt.setText( "org.codehaus.plexus.DominantImplementation" ); - dCE.addContent( implElt ); - Element requirementsElt = new Element( "requirements" ); - Element reqElt = new Element( "requirement" ); - Element reqRoleElt = new Element( "role" ); - reqRoleElt.setText( "org.codehaus.plexus.IRequiredRole" ); - reqElt.addContent( reqRoleElt ); - requirementsElt.addContent( reqElt ); - dCE.addContent( requirementsElt ); + AbstractMergeableElement dParent = new ComponentsElement(new Element("components")); + Element dCE = new Element("component"); + dParent.addContent(dCE); + Element roleElt = new Element("role"); + roleElt.setText("org.codehaus.plexus.ISampleRole"); + dCE.addContent(roleElt); + Element roleHintElt = new Element("role-hint"); + roleHintElt.setText("sample-role-hint"); + dCE.addContent(roleHintElt); + Element implElt = new Element("implementation"); + implElt.setText("org.codehaus.plexus.DominantImplementation"); + dCE.addContent(implElt); + Element requirementsElt = new Element("requirements"); + Element reqElt = new Element("requirement"); + Element reqRoleElt = new Element("role"); + reqRoleElt.setText("org.codehaus.plexus.IRequiredRole"); + reqElt.addContent(reqRoleElt); + requirementsElt.addContent(reqElt); + dCE.addContent(requirementsElt); // recessive Component Element - AbstractMergeableElement rParent = new ComponentsElement( new Element( "components" ) ); - Element rCE = new Element( "component" ); - rParent.addContent( rCE ); - roleElt = new Element( "role" ); - roleElt.setText( "org.codehaus.plexus.ISampleRole" ); - rCE.addContent( roleElt ); - roleHintElt = new Element( "role-hint" ); - roleHintElt.setText( "sample-role-hint" ); - rCE.addContent( roleHintElt ); - implElt = new Element( "implementation" ); - implElt.setText( "org.codehaus.plexus.RecessiveImplementation" ); - rCE.addContent( implElt ); - Element lifecycleHandlerElt = new Element( "lifecycle-handler" ); - rCE.addContent( lifecycleHandlerElt ); - lifecycleHandlerElt.setText( "plexus-configurable" ); - requirementsElt = new Element( "requirements" ); - reqElt = new Element( "requirement" ); - reqRoleElt = new Element( "role" ); - reqRoleElt.setText( "org.codehaus.plexus.IRequiredRole" ); - reqElt.addContent( reqRoleElt ); - requirementsElt.addContent( reqElt ); - Element reqRoleHintElt = new Element( "role-hint" ); - reqRoleHintElt.setText( "recessive-required-role-hint" ); - reqElt.addContent( reqRoleHintElt ); - rCE.addContent( requirementsElt ); + AbstractMergeableElement rParent = new ComponentsElement(new Element("components")); + Element rCE = new Element("component"); + rParent.addContent(rCE); + roleElt = new Element("role"); + roleElt.setText("org.codehaus.plexus.ISampleRole"); + rCE.addContent(roleElt); + roleHintElt = new Element("role-hint"); + roleHintElt.setText("sample-role-hint"); + rCE.addContent(roleHintElt); + implElt = new Element("implementation"); + implElt.setText("org.codehaus.plexus.RecessiveImplementation"); + rCE.addContent(implElt); + Element lifecycleHandlerElt = new Element("lifecycle-handler"); + rCE.addContent(lifecycleHandlerElt); + lifecycleHandlerElt.setText("plexus-configurable"); + requirementsElt = new Element("requirements"); + reqElt = new Element("requirement"); + reqRoleElt = new Element("role"); + reqRoleElt.setText("org.codehaus.plexus.IRequiredRole"); + reqElt.addContent(reqRoleElt); + requirementsElt.addContent(reqElt); + Element reqRoleHintElt = new Element("role-hint"); + reqRoleHintElt.setText("recessive-required-role-hint"); + reqElt.addContent(reqRoleHintElt); + rCE.addContent(requirementsElt); // attempt to merge - dParent.merge( rParent ); - assertEquals( 1, dParent.getChildren( "component" ).size() ); - assertEquals( "org.codehaus.plexus.DominantImplementation", dParent.getChild( "component" ) - .getChildText( "implementation" ) ); - assertEquals( 1, dParent.getChild( "component" ).getChild( "requirements" ).getChildren( "requirement" ).size() ); + dParent.merge(rParent); + assertEquals(1, dParent.getChildren("component").size()); + assertEquals( + "org.codehaus.plexus.DominantImplementation", + dParent.getChild("component").getChildText("implementation")); + assertEquals( + 1, + dParent.getChild("component") + .getChild("requirements") + .getChildren("requirement") + .size()); } /** @@ -200,109 +201,107 @@ public void testComponentsMerge() * * @throws Exception in case of an error. */ - public void testDeepComponentsMerge() - throws Exception - { + public void testDeepComponentsMerge() throws Exception { // FIXME: Review this after MergeStrategies are in place. - if ( true ) - { + if (true) { return; } // dominant Component Element - AbstractMergeableElement dCE = new ComponentElement( new Element( "component" ) ); - Element roleElt = new Element( "role" ); - roleElt.setText( "org.codehaus.plexus.ISampleRole" ); - dCE.addContent( roleElt ); + AbstractMergeableElement dCE = new ComponentElement(new Element("component")); + Element roleElt = new Element("role"); + roleElt.setText("org.codehaus.plexus.ISampleRole"); + dCE.addContent(roleElt); Element roleHintElt; // roleHintElt = new Element ("role-hint"); // roleHintElt.setText ("sample-hint"); // dCE.addContent (roleHintElt); - Element implElt = new Element( "implementation" ); - implElt.setText( "org.codehaus.plexus.DominantImplementation" ); - dCE.addContent( implElt ); - Element requirementsElt = new Element( "requirements" ); - Element reqElt = new Element( "requirement" ); - Element reqRoleElt = new Element( "role" ); - reqRoleElt.setText( "org.codehaus.plexus.IRequiredRole" ); - reqElt.addContent( reqRoleElt ); - requirementsElt.addContent( reqElt ); - dCE.addContent( requirementsElt ); + Element implElt = new Element("implementation"); + implElt.setText("org.codehaus.plexus.DominantImplementation"); + dCE.addContent(implElt); + Element requirementsElt = new Element("requirements"); + Element reqElt = new Element("requirement"); + Element reqRoleElt = new Element("role"); + reqRoleElt.setText("org.codehaus.plexus.IRequiredRole"); + reqElt.addContent(reqRoleElt); + requirementsElt.addContent(reqElt); + dCE.addContent(requirementsElt); // recessive Component Element - AbstractMergeableElement rCE = new ComponentElement( new Element( "component" ) ); - roleElt = new Element( "role" ); - roleElt.setText( "org.codehaus.plexus.ISampleRole" ); - rCE.addContent( roleElt ); - roleHintElt = new Element( "role-hint" ); - roleHintElt.setText( "recessive-hint" ); - rCE.addContent( roleHintElt ); - implElt = new Element( "implementation" ); - implElt.setText( "org.codehaus.plexus.RecessiveImplementation" ); - rCE.addContent( implElt ); - Element lifecycleHandlerElt = new Element( "lifecycle-handler" ); - rCE.addContent( lifecycleHandlerElt ); - lifecycleHandlerElt.setText( "plexus-configurable" ); - requirementsElt = new Element( "requirements" ); - reqElt = new Element( "requirement" ); - reqRoleElt = new Element( "role" ); - reqRoleElt.setText( "org.codehaus.plexus.IRequiredRole" ); - reqElt.addContent( reqRoleElt ); - requirementsElt.addContent( reqElt ); - Element reqRoleHintElt = new Element( "role-hint" ); - reqRoleHintElt.setText( "recessive-required-role-hint" ); - reqElt.addContent( reqRoleHintElt ); - rCE.addContent( requirementsElt ); + AbstractMergeableElement rCE = new ComponentElement(new Element("component")); + roleElt = new Element("role"); + roleElt.setText("org.codehaus.plexus.ISampleRole"); + rCE.addContent(roleElt); + roleHintElt = new Element("role-hint"); + roleHintElt.setText("recessive-hint"); + rCE.addContent(roleHintElt); + implElt = new Element("implementation"); + implElt.setText("org.codehaus.plexus.RecessiveImplementation"); + rCE.addContent(implElt); + Element lifecycleHandlerElt = new Element("lifecycle-handler"); + rCE.addContent(lifecycleHandlerElt); + lifecycleHandlerElt.setText("plexus-configurable"); + requirementsElt = new Element("requirements"); + reqElt = new Element("requirement"); + reqRoleElt = new Element("role"); + reqRoleElt.setText("org.codehaus.plexus.IRequiredRole"); + reqElt.addContent(reqRoleElt); + requirementsElt.addContent(reqElt); + Element reqRoleHintElt = new Element("role-hint"); + reqRoleHintElt.setText("recessive-required-role-hint"); + reqElt.addContent(reqRoleHintElt); + rCE.addContent(requirementsElt); // attempt to merge - dCE.merge( rCE ); + dCE.merge(rCE); // verify the merge - assertTrue( null != dCE.getChild( "role" ) ); - assertEquals( "org.codehaus.plexus.ISampleRole", dCE.getChildText( "role" ) ); - assertTrue( null != dCE.getChild( "role-hint" ) ); - assertEquals( "recessive-hint", dCE.getChildText( "role-hint" ) ); - assertTrue( null != dCE.getChild( "lifecycle-handler" ) ); - assertEquals( "plexus-configurable", dCE.getChildText( "lifecycle-handler" ) ); - assertTrue( null != dCE.getChild( "requirements" ) ); - assertEquals( 1, dCE.getChild( "requirements" ).getChildren( "requirement" ).size() ); - assertEquals( "recessive-required-role-hint", ( (Element) dCE.getChild( "requirements" ) - .getChildren( "requirement" ).get( 0 ) ).getChildText( "role-hint" ) ); + assertTrue(null != dCE.getChild("role")); + assertEquals("org.codehaus.plexus.ISampleRole", dCE.getChildText("role")); + assertTrue(null != dCE.getChild("role-hint")); + assertEquals("recessive-hint", dCE.getChildText("role-hint")); + assertTrue(null != dCE.getChild("lifecycle-handler")); + assertEquals("plexus-configurable", dCE.getChildText("lifecycle-handler")); + assertTrue(null != dCE.getChild("requirements")); + assertEquals(1, dCE.getChild("requirements").getChildren("requirement").size()); + assertEquals( + "recessive-required-role-hint", + ((Element) dCE.getChild("requirements") + .getChildren("requirement") + .get(0)) + .getChildText("role-hint")); } - - public void testMergeRoleComponents() throws Exception - { + + public void testMergeRoleComponents() throws Exception { SAXBuilder saxBuilder = new SAXBuilder(); - String source1 = "\n" + - " \n" + - " \n" + - " org.codehaus.plexus.metadata.component.DockerComposeConfigHandler\n" + - " org.codehaus.plexus.metadata.component.DominantComponent\n" + - " \n" + - " \n" + - " org.codehaus.plexus.metadata.component.PropertyConfigHandler\n" + - " org.codehaus.plexus.metadata.component.DominantComponent\n" + - " \n" + - " \n" + - ""; - Document doc1 = saxBuilder.build( new StringReader( source1 ) ); - - String source2 = "\n" + - " \n" + - " \n" + - " org.codehaus.plexus.metadata.component.ExternalConfigHandler\n" + - " org.codehaus.plexus.metadata.component.DominantComponent\n" + - " \n" + - " \n" + - ""; - Document doc2 = saxBuilder.build( new StringReader( source2 ) ); - + String source1 = "\n" + " \n" + + " \n" + + " org.codehaus.plexus.metadata.component.DockerComposeConfigHandler\n" + + " org.codehaus.plexus.metadata.component.DominantComponent\n" + + " \n" + + " \n" + + " org.codehaus.plexus.metadata.component.PropertyConfigHandler\n" + + " org.codehaus.plexus.metadata.component.DominantComponent\n" + + " \n" + + " \n" + + ""; + Document doc1 = saxBuilder.build(new StringReader(source1)); + + String source2 = "\n" + " \n" + + " \n" + + " org.codehaus.plexus.metadata.component.ExternalConfigHandler\n" + + " org.codehaus.plexus.metadata.component.DominantComponent\n" + + " \n" + + " \n" + + ""; + Document doc2 = saxBuilder.build(new StringReader(source2)); + PlexusXmlMerger merger = new PlexusXmlMerger(); - Document mergedDoc = merger.merge( doc1, doc2 ); - - List components = mergedDoc.detachRootElement().getChild( "components" ).getChildren(); - assertEquals( 3, components.size() ); + Document mergedDoc = merger.merge(doc1, doc2); + + List components = + mergedDoc.detachRootElement().getChild("components").getChildren(); + assertEquals(3, components.size()); } - } diff --git a/plexus-container-default/pom.xml b/plexus-container-default/pom.xml index e238ae0d1..3136fc5da 100644 --- a/plexus-container-default/pom.xml +++ b/plexus-container-default/pom.xml @@ -1,3 +1,4 @@ + 4.0.0 @@ -10,9 +11,7 @@ plexus-container-default Plexus :: Default Container (deprecated) - - The Plexus IoC container API and its default implementation. - + The Plexus IoC container API and its default implementation. @@ -59,20 +58,20 @@ xsd-site - pre-site xsd + pre-site ${basedir}/target/generated-site/resources/xsd descriptor-site - pre-site xdoc + pre-site 1.0.0 @@ -89,7 +88,7 @@ -Xdoclint:none false - + diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/ClassRealmUtil.java b/plexus-container-default/src/main/java/org/codehaus/plexus/ClassRealmUtil.java index 975bfe2a4..fe0cb37dd 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/ClassRealmUtil.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/ClassRealmUtil.java @@ -26,52 +26,42 @@ import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; -public class ClassRealmUtil -{ +public class ClassRealmUtil { - public static Set getContextRealms( ClassWorld world ) - { + public static Set getContextRealms(ClassWorld world) { Set realms = new LinkedHashSet(); - for ( ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); classLoader != null; classLoader = - classLoader.getParent() ) - { - if ( classLoader instanceof ClassRealm ) - { - realms.add( (ClassRealm) classLoader ); + for (ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + classLoader != null; + classLoader = classLoader.getParent()) { + if (classLoader instanceof ClassRealm) { + realms.add((ClassRealm) classLoader); Queue queue = new LinkedList(); - queue.add( (ClassRealm) classLoader ); + queue.add((ClassRealm) classLoader); - while ( !queue.isEmpty() ) - { + while (!queue.isEmpty()) { ClassRealm realm = queue.remove(); Collection importRealms = realm.getImportRealms(); - for ( ClassRealm importRealm : importRealms ) - { - if ( realms.add( importRealm ) ) - { - queue.add( importRealm ); + for (ClassRealm importRealm : importRealms) { + if (realms.add(importRealm)) { + queue.add(importRealm); } } ClassRealm parentRealm = realm.getParentRealm(); - if ( parentRealm != null && realms.add( parentRealm ) ) - { - queue.add( parentRealm ); + if (parentRealm != null && realms.add(parentRealm)) { + queue.add(parentRealm); } } } } - if ( world != null ) - { - for ( Iterator it = realms.iterator(); it.hasNext(); ) - { + if (world != null) { + for (Iterator it = realms.iterator(); it.hasNext(); ) { ClassRealm realm = it.next(); - if ( realm.getWorld() != world ) - { + if (realm.getWorld() != world) { it.remove(); } } @@ -79,5 +69,4 @@ public static Set getContextRealms( ClassWorld world ) return realms; } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/ComponentRegistry.java b/plexus-container-default/src/main/java/org/codehaus/plexus/ComponentRegistry.java index a2f1cc0ff..3e7dc22da 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/ComponentRegistry.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/ComponentRegistry.java @@ -31,39 +31,34 @@ * @author Kenney Westerhof * @author Dain Sundstrom */ -public interface ComponentRegistry -{ - void registerComponentManagerFactory( ComponentManagerFactory componentManagerFactory ); +public interface ComponentRegistry { + void registerComponentManagerFactory(ComponentManagerFactory componentManagerFactory); - void addComponentDescriptor( ComponentDescriptor componentDescriptor ) - throws CycleDetectedInComponentGraphException; + void addComponentDescriptor(ComponentDescriptor componentDescriptor) + throws CycleDetectedInComponentGraphException; - ComponentDescriptor getComponentDescriptor( Class type, String role, String roleHint ); + ComponentDescriptor getComponentDescriptor(Class type, String role, String roleHint); @Deprecated - ComponentDescriptor getComponentDescriptor( String role, String roleHint, ClassRealm realm ); + ComponentDescriptor getComponentDescriptor(String role, String roleHint, ClassRealm realm); - List> getComponentDescriptorList( Class type, String role ); + List> getComponentDescriptorList(Class type, String role); - Map> getComponentDescriptorMap( Class type, String role ); + Map> getComponentDescriptorMap(Class type, String role); - T lookup( Class type, String role, String roleHint ) - throws ComponentLookupException; + T lookup(Class type, String role, String roleHint) throws ComponentLookupException; - T lookup( ComponentDescriptor componentDescriptor ) - throws ComponentLookupException; + T lookup(ComponentDescriptor componentDescriptor) throws ComponentLookupException; - List lookupList( Class type, String role, List hints ) - throws ComponentLookupException; + List lookupList(Class type, String role, List hints) throws ComponentLookupException; - Map lookupMap( Class type, String role, List hints ) - throws ComponentLookupException; + Map lookupMap(Class type, String role, List hints) throws ComponentLookupException; - void release( Object component ) throws ComponentLifecycleException; + void release(Object component) throws ComponentLifecycleException; - void removeComponentRealm( ClassRealm classRealm ) throws PlexusContainerException; + void removeComponentRealm(ClassRealm classRealm) throws PlexusContainerException; void dispose(); - void addComponent( T component, String role, String roleHint ); -} \ No newline at end of file + void addComponent(T component, String role, String roleHint); +} diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/ContainerConfiguration.java b/plexus-container-default/src/main/java/org/codehaus/plexus/ContainerConfiguration.java index 0153d7beb..2e1ab9f71 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/ContainerConfiguration.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/ContainerConfiguration.java @@ -19,32 +19,31 @@ /** * @author Jason van Zyl */ -public interface ContainerConfiguration -{ - ContainerConfiguration setName( String name ); +public interface ContainerConfiguration { + ContainerConfiguration setName(String name); String getName(); - ContainerConfiguration setContext( Map context ); + ContainerConfiguration setContext(Map context); Map getContext(); - ContainerConfiguration setClassWorld( ClassWorld classWorld ); + ContainerConfiguration setClassWorld(ClassWorld classWorld); ClassWorld getClassWorld(); - ContainerConfiguration setRealm( ClassRealm realm ); + ContainerConfiguration setRealm(ClassRealm realm); ClassRealm getRealm(); - + // // Configuration // - ContainerConfiguration setContainerConfiguration( String configuration ); + ContainerConfiguration setContainerConfiguration(String configuration); String getContainerConfiguration(); - ContainerConfiguration setContainerConfigurationURL( URL configuration ); + ContainerConfiguration setContainerConfigurationURL(URL configuration); URL getContainerConfigurationURL(); @@ -62,17 +61,17 @@ public interface ContainerConfiguration // Component discoverer manager - ContainerConfiguration addComponentDiscoverer( ComponentDiscoverer componentDiscoverer ); + ContainerConfiguration addComponentDiscoverer(ComponentDiscoverer componentDiscoverer); - ContainerConfiguration addComponentDiscoveryListener( ComponentDiscoveryListener componentDiscoveryListener ); + ContainerConfiguration addComponentDiscoveryListener(ComponentDiscoveryListener componentDiscoveryListener); - ContainerConfiguration setComponentDiscovererManager( ComponentDiscovererManager componentDiscovererManager ); + ContainerConfiguration setComponentDiscovererManager(ComponentDiscovererManager componentDiscovererManager); ComponentDiscovererManager getComponentDiscovererManager(); // Component factory manager - ContainerConfiguration setComponentFactoryManager( ComponentFactoryManager componentFactoryManager ); + ContainerConfiguration setComponentFactoryManager(ComponentFactoryManager componentFactoryManager); ComponentFactoryManager getComponentFactoryManager(); @@ -80,7 +79,7 @@ public interface ContainerConfiguration // Component repository - ContainerConfiguration setComponentRepository( ComponentRepository componentRepository ); + ContainerConfiguration setComponentRepository(ComponentRepository componentRepository); ComponentRepository getComponentRepository(); @@ -88,24 +87,23 @@ public interface ContainerConfiguration // Lifecycle handler manager - ContainerConfiguration addLifecycleHandler( LifecycleHandler lifecycleHandler ); + ContainerConfiguration addLifecycleHandler(LifecycleHandler lifecycleHandler); - ContainerConfiguration setLifecycleHandlerManager( LifecycleHandlerManager lifecycleHandlerManager ); + ContainerConfiguration setLifecycleHandlerManager(LifecycleHandlerManager lifecycleHandlerManager); LifecycleHandlerManager getLifecycleHandlerManager(); // Configuration Sources - ContainerConfiguration setConfigurationSource( ConfigurationSource configurationSource ); + ContainerConfiguration setConfigurationSource(ConfigurationSource configurationSource); ConfigurationSource getConfigurationSource(); - ContainerConfiguration addComponentDiscoverer( Class componentDiscoverer ); - - ContainerConfiguration addComponentDiscoveryListener( Class componentDiscoveryListener ); + ContainerConfiguration addComponentDiscoverer(Class componentDiscoverer); + + ContainerConfiguration addComponentDiscoveryListener(Class componentDiscoveryListener); List getComponentDiscoverers(); - List getComponentDiscoveryListeners(); + List getComponentDiscoveryListeners(); } - diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/DefaultComponentRegistry.java b/plexus-container-default/src/main/java/org/codehaus/plexus/DefaultComponentRegistry.java index 5b0b8a23d..d63cfa48d 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/DefaultComponentRegistry.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/DefaultComponentRegistry.java @@ -1,7 +1,5 @@ package org.codehaus.plexus; -import static org.codehaus.plexus.component.CastUtils.isAssignableFrom; - import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -10,9 +8,9 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; -import java.util.Map.Entry; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.composition.CycleDetectedInComponentGraphException; @@ -29,8 +27,9 @@ import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.util.StringUtils; -public class DefaultComponentRegistry implements ComponentRegistry -{ +import static org.codehaus.plexus.component.CastUtils.isAssignableFrom; + +public class DefaultComponentRegistry implements ComponentRegistry { private static final String DEFAULT_INSTANTIATION_STRATEGY = "singleton"; private final MutablePlexusContainer container; @@ -38,32 +37,31 @@ public class DefaultComponentRegistry implements ComponentRegistry private final LifecycleHandlerManager lifecycleHandlerManager; private final Logger logger; - private boolean disposingComponents; + private boolean disposingComponents; private final Map componentManagerFactories = - Collections.synchronizedMap( new TreeMap() ); + Collections.synchronizedMap(new TreeMap()); private final Map> componentManagers = new TreeMap>(); - private final Map> componentManagersByComponent = new IdentityHashMap>(); + private final Map> componentManagersByComponent = + new IdentityHashMap>(); private final Map unmanagedComponents = new TreeMap(); - public DefaultComponentRegistry( MutablePlexusContainer container, - ComponentRepository repository, - LifecycleHandlerManager lifecycleHandlerManager ) - { + public DefaultComponentRegistry( + MutablePlexusContainer container, + ComponentRepository repository, + LifecycleHandlerManager lifecycleHandlerManager) { this.container = container; this.repository = repository; this.lifecycleHandlerManager = lifecycleHandlerManager; logger = container.getLogger(); } - public void dispose() - { + public void dispose() { List> managers; - synchronized ( this ) - { - managers = new ArrayList>( componentManagers.values() ); + synchronized (this) { + managers = new ArrayList>(componentManagers.values()); componentManagers.clear(); componentManagersByComponent.clear(); unmanagedComponents.clear(); @@ -72,556 +70,454 @@ public void dispose() } // reverse sort the managers by startId - Collections.sort( managers, new Comparator>() { - public int compare( ComponentManager left, ComponentManager right ) - { - if (left.getStartId() < right.getStartId() ) - { + Collections.sort(managers, new Comparator>() { + public int compare(ComponentManager left, ComponentManager right) { + if (left.getStartId() < right.getStartId()) { return 1; - } - else if (left.getStartId() == right.getStartId() ) - { + } else if (left.getStartId() == right.getStartId()) { return 0; - } - else - { + } else { return -1; } } }); // Call dispose callback outside of synchronized lock to avoid deadlocks - try - { - for ( ComponentManager componentManager : managers ) - { - try - { + try { + for (ComponentManager componentManager : managers) { + try { componentManager.dispose(); - } - catch ( Exception e ) - { + } catch (Exception e) { // todo dain use a monitor instead of a logger - logger.error( "Error while disposing component manager. Continuing with the rest", e ); + logger.error("Error while disposing component manager. Continuing with the rest", e); } } - } - finally - { - synchronized ( this ) - { + } finally { + synchronized (this) { disposingComponents = false; } } } - public void registerComponentManagerFactory( ComponentManagerFactory componentManagerFactory ) - { - componentManagerFactories.put( componentManagerFactory.getId(), componentManagerFactory ); + public void registerComponentManagerFactory(ComponentManagerFactory componentManagerFactory) { + componentManagerFactories.put(componentManagerFactory.getId(), componentManagerFactory); } - public void addComponentDescriptor( ComponentDescriptor componentDescriptor ) - throws CycleDetectedInComponentGraphException - { - repository.addComponentDescriptor( componentDescriptor ); + public void addComponentDescriptor(ComponentDescriptor componentDescriptor) + throws CycleDetectedInComponentGraphException { + repository.addComponentDescriptor(componentDescriptor); } @SuppressWarnings("unchecked") - public synchronized void addComponent( T component, String role, String roleHint ) - { - ComponentDescriptor descriptor = new ComponentDescriptor(component.getClass(), null ); - descriptor.setRole( role ); - descriptor.setRoleHint( roleHint ); + public synchronized void addComponent(T component, String role, String roleHint) { + ComponentDescriptor descriptor = new ComponentDescriptor(component.getClass(), null); + descriptor.setRole(role); + descriptor.setRoleHint(roleHint); - Key key = new Key( descriptor.getRealm(), role, roleHint ); + Key key = new Key(descriptor.getRealm(), role, roleHint); - unmanagedComponents.put( key, component ); + unmanagedComponents.put(key, component); } - public ComponentDescriptor getComponentDescriptor( Class type, String role, String roleHint ) - { - return repository.getComponentDescriptor( type, role, roleHint ); + public ComponentDescriptor getComponentDescriptor(Class type, String role, String roleHint) { + return repository.getComponentDescriptor(type, role, roleHint); } @Deprecated - public ComponentDescriptor getComponentDescriptor( String role, String roleHint, ClassRealm realm ) - { - return repository.getComponentDescriptor( role, roleHint, realm ); + public ComponentDescriptor getComponentDescriptor(String role, String roleHint, ClassRealm realm) { + return repository.getComponentDescriptor(role, roleHint, realm); } - public Map> getComponentDescriptorMap( Class type, String role ) - { - return repository.getComponentDescriptorMap( type, role ); + public Map> getComponentDescriptorMap(Class type, String role) { + return repository.getComponentDescriptorMap(type, role); } - public List> getComponentDescriptorList( Class type, String role ) - { - return repository.getComponentDescriptorList( type, role ); + public List> getComponentDescriptorList(Class type, String role) { + return repository.getComponentDescriptorList(type, role); } - public T lookup( Class type, String role, String roleHint ) throws ComponentLookupException - { + public T lookup(Class type, String role, String roleHint) throws ComponentLookupException { // verify arguments - if ( type == null ) - { - throw new NullPointerException( "type is null" ); + if (type == null) { + throw new NullPointerException("type is null"); } - if ( role == null ) - { - throw new NullPointerException( "role is null" ); + if (role == null) { + throw new NullPointerException("role is null"); } - if ( roleHint == null ) - { + if (roleHint == null) { roleHint = ""; } - return getComponent( type, role, roleHint, null ); + return getComponent(type, role, roleHint, null); } - public T lookup( ComponentDescriptor componentDescriptor ) - throws ComponentLookupException - { - return getComponent( componentDescriptor.getRoleClass(), componentDescriptor.getRole(), - componentDescriptor.getRoleHint(), componentDescriptor ); + public T lookup(ComponentDescriptor componentDescriptor) throws ComponentLookupException { + return getComponent( + componentDescriptor.getRoleClass(), + componentDescriptor.getRole(), + componentDescriptor.getRoleHint(), + componentDescriptor); } - public Map lookupMap( Class type, String role, List roleHints ) - throws ComponentLookupException - { + public Map lookupMap(Class type, String role, List roleHints) + throws ComponentLookupException { // verify arguments - if ( type == null ) - { - throw new NullPointerException( "type is null" ); + if (type == null) { + throw new NullPointerException("type is null"); } - if ( role == null ) - { - throw new NullPointerException( "role is null" ); + if (role == null) { + throw new NullPointerException("role is null"); } // if no hints provided, get all valid hints for this role Map components = new LinkedHashMap(); - if ( roleHints == null ) - { - Map> componentDescriptors = getComponentDescriptorMap( type, role ); - for ( Entry> entry : componentDescriptors.entrySet() ) - { + if (roleHints == null) { + Map> componentDescriptors = getComponentDescriptorMap(type, role); + for (Entry> entry : componentDescriptors.entrySet()) { String roleHint = entry.getKey(); ComponentDescriptor componentDescriptor = entry.getValue(); - // todo dain catch the exception... it isn't the callers problem when one component in a collection fails - T component = getComponent( type, role, roleHint, componentDescriptor ); - components.put( roleHint, component ); + // todo dain catch the exception... it isn't the callers problem when one component in a collection + // fails + T component = getComponent(type, role, roleHint, componentDescriptor); + components.put(roleHint, component); } - } - else - { - for ( String roleHint : roleHints ) - { - // todo dain catch the exception... it isn't the callers problem when one component in a collection fails - T component = getComponent( type, role, roleHint, null ); - components.put( roleHint, component ); + } else { + for (String roleHint : roleHints) { + // todo dain catch the exception... it isn't the callers problem when one component in a collection + // fails + T component = getComponent(type, role, roleHint, null); + components.put(roleHint, component); } } return components; } - public List lookupList( Class type, String role, List roleHints ) throws ComponentLookupException - { + public List lookupList(Class type, String role, List roleHints) throws ComponentLookupException { // verify arguments - if ( type == null ) - { - throw new NullPointerException( "type is null" ); + if (type == null) { + throw new NullPointerException("type is null"); } - if ( role == null ) - { - throw new NullPointerException( "role is null" ); + if (role == null) { + throw new NullPointerException("role is null"); } // if no hints provided, get all valid hints for this role List components = new ArrayList(); - if ( roleHints == null ) - { - List> componentDescriptors = getComponentDescriptorList( type, role ); - for ( ComponentDescriptor componentDescriptor : componentDescriptors ) - { - // todo dain catch the exception... it isn't the callers problem when one component in a collection fails - T component = getComponent( type, role, componentDescriptor.getRoleHint(), componentDescriptor ); - components.add( component ); + if (roleHints == null) { + List> componentDescriptors = getComponentDescriptorList(type, role); + for (ComponentDescriptor componentDescriptor : componentDescriptors) { + // todo dain catch the exception... it isn't the callers problem when one component in a collection + // fails + T component = getComponent(type, role, componentDescriptor.getRoleHint(), componentDescriptor); + components.add(component); } - } - else - { - for ( String roleHint : roleHints ) - { - // todo dain catch the exception... it isn't the callers problem when one component in a collection fails - T component = getComponent( type, role, roleHint, null ); - components.add( component ); + } else { + for (String roleHint : roleHints) { + // todo dain catch the exception... it isn't the callers problem when one component in a collection + // fails + T component = getComponent(type, role, roleHint, null); + components.add(component); } } return components; } - public void release( Object component ) - throws ComponentLifecycleException - { - if ( component == null ) - { + public void release(Object component) throws ComponentLifecycleException { + if (component == null) { return; } // get the component manager ComponentManager componentManager; - synchronized ( this ) - { - componentManager = componentManagersByComponent.get( component ); - if ( componentManager == null ) - { + synchronized (this) { + componentManager = componentManagersByComponent.get(component); + if (componentManager == null) { // This needs to be tracked down but the user doesn't need to see this // during the maven bootstrap this logger is null. - //logger.debug( "Component manager not found for returned component. Ignored. component=" + component ); + // logger.debug( "Component manager not found for returned component. Ignored. component=" + component + // ); return; } } // release the component from the manager - componentManager.release( component ); + componentManager.release(component); // only drop the reference to this component if there are no other uses of the component // multiple uses of a component is common with singleton beans - if ( componentManager.getConnections() <= 0 ) - { - synchronized ( this ) - { - componentManagersByComponent.remove( component ); + if (componentManager.getConnections() <= 0) { + synchronized (this) { + componentManagersByComponent.remove(component); } } } - public void removeComponentRealm( ClassRealm classRealm ) throws PlexusContainerException - { - repository.removeComponentRealm( classRealm ); - + public void removeComponentRealm(ClassRealm classRealm) throws PlexusContainerException { + repository.removeComponentRealm(classRealm); + List> dispose = new ArrayList>(); - try - { - synchronized ( this ) - { - for ( Iterator>> it = componentManagers.entrySet().iterator(); it.hasNext(); ) - { + try { + synchronized (this) { + for (Iterator>> it = + componentManagers.entrySet().iterator(); + it.hasNext(); ) { Entry> entry = it.next(); Key key = entry.getKey(); ComponentManager componentManager = entry.getValue(); - if ( key.realm.equals( classRealm ) ) - { - dispose.add( componentManager ); + if (key.realm.equals(classRealm)) { + dispose.add(componentManager); it.remove(); - } - else - { - componentManager.dissociateComponentRealm( classRealm ); + } else { + componentManager.dissociateComponentRealm(classRealm); } } } // Call dispose callback outside of synchronized lock to avoid deadlocks - for ( ComponentManager componentManager : dispose ) - { + for (ComponentManager componentManager : dispose) { componentManager.dispose(); } - } - catch ( ComponentLifecycleException e ) - { - throw new PlexusContainerException( "Failed to dissociate component realm: " + classRealm.getId(), e ); + } catch (ComponentLifecycleException e) { + throw new PlexusContainerException("Failed to dissociate component realm: " + classRealm.getId(), e); } } - private T getComponent( Class type, String role, String roleHint, ComponentDescriptor descriptor ) - throws ComponentLookupException - { + private T getComponent(Class type, String role, String roleHint, ComponentDescriptor descriptor) + throws ComponentLookupException { // lookup for unmanaged components first - T component = this.getUnmanagedComponent( role, roleHint ); // weird syntax due to http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302954 + T component = this.getUnmanagedComponent( + role, roleHint); // weird syntax due to http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302954 - if ( component != null ) - { + if (component != null) { return component; } - ComponentManager componentManager = getComponentManager( type, role, roleHint, descriptor ); + ComponentManager componentManager = getComponentManager(type, role, roleHint, descriptor); // Get instance from manager... may result in creation - try - { + try { component = componentManager.getComponent(); - synchronized ( this ) - { - componentManagersByComponent.put( component, componentManager ); + synchronized (this) { + componentManagersByComponent.put(component, componentManager); } return component; - } - catch ( ComponentInstantiationException e ) - { + } catch (ComponentInstantiationException e) { throw new ComponentLookupException( - "Unable to lookup component '" + componentManager.getRole() + "', it could not be created.", - componentManager.getRole(), componentManager.getRoleHint(), componentManager.getRealm(), e ); - } - catch ( ComponentLifecycleException e ) - { + "Unable to lookup component '" + componentManager.getRole() + "', it could not be created.", + componentManager.getRole(), + componentManager.getRoleHint(), + componentManager.getRealm(), + e); + } catch (ComponentLifecycleException e) { throw new ComponentLookupException( - "Unable to lookup component '" + componentManager.getRole() + "', it could not be started.", - componentManager.getRole(), componentManager.getRoleHint(), componentManager.getRealm(), e ); + "Unable to lookup component '" + componentManager.getRole() + "', it could not be started.", + componentManager.getRole(), + componentManager.getRoleHint(), + componentManager.getRealm(), + e); } } @SuppressWarnings("unchecked") - private synchronized T getUnmanagedComponent( String role, String roleHint ) - { - Set realms = getSearchRealms( true ); - - if ( realms != null ) - { - // ignore unmanaged components, they are not associated with realms - // but lookup realm is provided via thread context classloader + private synchronized T getUnmanagedComponent(String role, String roleHint) { + Set realms = getSearchRealms(true); + + if (realms != null) { + // ignore unmanaged components, they are not associated with realms + // but lookup realm is provided via thread context classloader return null; - } - else - { - if ( StringUtils.isEmpty( roleHint ) ) - { + } else { + if (StringUtils.isEmpty(roleHint)) { roleHint = PlexusConstants.PLEXUS_DEFAULT_HINT; } - return (T) unmanagedComponents.get( new Key( null, role, roleHint ) ); + return (T) unmanagedComponents.get(new Key(null, role, roleHint)); } } - private synchronized ComponentManager getComponentManager( Class type, String role, String roleHint, ComponentDescriptor descriptor ) - throws ComponentLookupException - { - if ( disposingComponents ) - { - throw new ComponentLookupException("ComponentRegistry is not active", - role, - roleHint ); + private synchronized ComponentManager getComponentManager( + Class type, String role, String roleHint, ComponentDescriptor descriptor) + throws ComponentLookupException { + if (disposingComponents) { + throw new ComponentLookupException("ComponentRegistry is not active", role, roleHint); } - if ( descriptor == null ) - { - descriptor = getComponentDescriptor( type, role, roleHint ); + if (descriptor == null) { + descriptor = getComponentDescriptor(type, role, roleHint); } ComponentManager componentManager = null; - if ( descriptor != null ) - { - componentManager = getComponentManager( type, role, descriptor.getRoleHint(), descriptor.getRealm() ); - } - else - { - componentManager = getComponentManager( type, role, roleHint ); + if (descriptor != null) { + componentManager = getComponentManager(type, role, descriptor.getRoleHint(), descriptor.getRealm()); + } else { + componentManager = getComponentManager(type, role, roleHint); } - if ( componentManager == null ) - { + if (componentManager == null) { // we need to create a component manager, but first we must have a descriptor - if ( descriptor == null ) - { - descriptor = getComponentDescriptor( type, role, roleHint ); - if ( descriptor == null ) - { + if (descriptor == null) { + descriptor = getComponentDescriptor(type, role, roleHint); + if (descriptor == null) { throw new ComponentLookupException( - "Component descriptor cannot be found in the component repository", - role, - roleHint ); + "Component descriptor cannot be found in the component repository", role, roleHint); } // search also into descriptor realm as the key of a created component is per descriptor realm - componentManager = getComponentManager( type, role, descriptor.getRoleHint(), descriptor.getRealm() ); + componentManager = getComponentManager(type, role, descriptor.getRoleHint(), descriptor.getRealm()); } - if ( componentManager == null ) - { - componentManager = createComponentManager( descriptor, role, descriptor.getRoleHint() ); + if (componentManager == null) { + componentManager = createComponentManager(descriptor, role, descriptor.getRoleHint()); } } return componentManager; } - @SuppressWarnings( "unchecked" ) - private ComponentManager getComponentManager( Class type, String role, String roleHint ) - { - Set realms = getSearchRealms( false ); + @SuppressWarnings("unchecked") + private ComponentManager getComponentManager(Class type, String role, String roleHint) { + Set realms = getSearchRealms(false); // return the component in the first realm - for ( ClassRealm realm : realms ) - { - ComponentManager manager = componentManagers.get( new Key( realm, role, roleHint ) ); - if ( manager != null && isAssignableFrom( type, manager.getType() ) ) - { + for (ClassRealm realm : realms) { + ComponentManager manager = componentManagers.get(new Key(realm, role, roleHint)); + if (manager != null && isAssignableFrom(type, manager.getType())) { return (ComponentManager) manager; } } return null; } - @SuppressWarnings( "unchecked" ) - private ComponentManager getComponentManager( Class type, String role, String roleHint, ClassRealm realm ) - { - ComponentManager manager = componentManagers.get( new Key( realm, role, roleHint ) ); - if ( manager != null && isAssignableFrom( type, manager.getType() ) ) - { + @SuppressWarnings("unchecked") + private ComponentManager getComponentManager(Class type, String role, String roleHint, ClassRealm realm) { + ComponentManager manager = componentManagers.get(new Key(realm, role, roleHint)); + if (manager != null && isAssignableFrom(type, manager.getType())) { return (ComponentManager) manager; } return null; } - @SuppressWarnings( "unchecked" ) - private Set getSearchRealms( boolean specifiedOnly ) - { + @SuppressWarnings("unchecked") + private Set getSearchRealms(boolean specifiedOnly) { // determine realms to search - Set realms = ClassRealmUtil.getContextRealms( container.getClassWorld() ); + Set realms = ClassRealmUtil.getContextRealms(container.getClassWorld()); - if ( realms.isEmpty() ) - { - if ( specifiedOnly ) - { + if (realms.isEmpty()) { + if (specifiedOnly) { return null; } - realms.addAll( container.getClassWorld().getRealms() ); + realms.addAll(container.getClassWorld().getRealms()); } return realms; } - private ComponentManager createComponentManager( ComponentDescriptor descriptor, - String role, - String roleHint ) - throws ComponentLookupException - { + private ComponentManager createComponentManager( + ComponentDescriptor descriptor, String role, String roleHint) throws ComponentLookupException { // Get the ComponentManagerFactory String instantiationStrategy = descriptor.getInstantiationStrategy(); - if ( instantiationStrategy == null ) - { + if (instantiationStrategy == null) { instantiationStrategy = DEFAULT_INSTANTIATION_STRATEGY; } - ComponentManagerFactory componentManagerFactory = componentManagerFactories.get( instantiationStrategy ); - if ( componentManagerFactory == null ) - { - throw new ComponentLookupException( "Unsupported instantiation strategy: " + instantiationStrategy, - role, - roleHint, - descriptor.getRealm() ); + ComponentManagerFactory componentManagerFactory = componentManagerFactories.get(instantiationStrategy); + if (componentManagerFactory == null) { + throw new ComponentLookupException( + "Unsupported instantiation strategy: " + instantiationStrategy, + role, + roleHint, + descriptor.getRealm()); } // Get the LifecycleHandler LifecycleHandler lifecycleHandler; - try - { - lifecycleHandler = lifecycleHandlerManager.getLifecycleHandler( descriptor.getLifecycleHandler() ); - } - catch ( UndefinedLifecycleHandlerException e ) - { - throw new ComponentLookupException( "Undefined lifecycle handler: " + descriptor.getLifecycleHandler(), - role, - roleHint, - descriptor.getRealm() ); + try { + lifecycleHandler = lifecycleHandlerManager.getLifecycleHandler(descriptor.getLifecycleHandler()); + } catch (UndefinedLifecycleHandlerException e) { + throw new ComponentLookupException( + "Undefined lifecycle handler: " + descriptor.getLifecycleHandler(), + role, + roleHint, + descriptor.getRealm()); } // Create the ComponentManager - ComponentManager componentManager = componentManagerFactory.createComponentManager( container, - lifecycleHandler, - descriptor, - role, - roleHint ); + ComponentManager componentManager = + componentManagerFactory.createComponentManager(container, lifecycleHandler, descriptor, role, roleHint); // Add componentManager to indexes - Key key = new Key( descriptor.getRealm(), role, roleHint ); - componentManagers.put( key, componentManager ); + Key key = new Key(descriptor.getRealm(), role, roleHint); + componentManagers.put(key, componentManager); return componentManager; } - private static class Key implements Comparable - { + private static class Key implements Comparable { private final ClassRealm realm; private final String role; private final String roleHint; private final int hashCode; - private Key( ClassRealm realm, String role, String roleHint ) - { + private Key(ClassRealm realm, String role, String roleHint) { this.realm = realm; - if ( role == null ) - { + if (role == null) { role = "null"; } this.role = role; - if ( roleHint == null ) - { + if (roleHint == null) { roleHint = "null"; } this.roleHint = roleHint; int hashCode; - hashCode = ( realm != null ? realm.hashCode() : 0 ); + hashCode = (realm != null ? realm.hashCode() : 0); hashCode = 31 * hashCode + role.hashCode(); hashCode = 31 * hashCode + roleHint.hashCode(); this.hashCode = hashCode; } - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } Key key = (Key) o; - return !( realm != null ? !realm.equals( key.realm ) : key.realm != null ) && - role.equals( key.role ) && - roleHint.equals( key.roleHint ); - + return !(realm != null ? !realm.equals(key.realm) : key.realm != null) + && role.equals(key.role) + && roleHint.equals(key.roleHint); } - public int hashCode() - { + public int hashCode() { return hashCode; } - public String toString() - { + public String toString() { return realm + "/" + role + "/" + roleHint; } - public int compareTo( Key o ) - { + public int compareTo(Key o) { int value; - if ( realm != null ) - { - value = o.realm == null? -1 : realm.getId().compareTo( o.realm.getId() ); - } - else - { + if (realm != null) { + value = o.realm == null ? -1 : realm.getId().compareTo(o.realm.getId()); + } else { value = o.realm == null ? 0 : 1; } - if ( value == 0 ) - { - value = role.compareTo( o.role ); - if ( value == 0 ) - { - value = roleHint.compareTo( o.roleHint ); + if (value == 0) { + value = role.compareTo(o.role); + if (value == 0) { + value = roleHint.compareTo(o.roleHint); } } return value; diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/DefaultContainerConfiguration.java b/plexus-container-default/src/main/java/org/codehaus/plexus/DefaultContainerConfiguration.java index 954170e24..ef4bb65fb 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/DefaultContainerConfiguration.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/DefaultContainerConfiguration.java @@ -40,9 +40,7 @@ import org.codehaus.plexus.personality.plexus.lifecycle.phase.StopPhase; /** @author Jason van Zyl */ -public class DefaultContainerConfiguration - implements ContainerConfiguration -{ +public class DefaultContainerConfiguration implements ContainerConfiguration { private String name; private Map context; @@ -56,185 +54,159 @@ public class DefaultContainerConfiguration private URL containerConfigurationURL; private ConfigurationSource configurationSource; - + private List componentDiscoverers = new ArrayList(); - + private List componentDiscoveryListeners = new ArrayList(); - - public ContainerConfiguration setName( String name ) - { + + public ContainerConfiguration setName(String name) { this.name = name; return this; } - public ContainerConfiguration setContext( Map context ) - { + public ContainerConfiguration setContext(Map context) { this.context = context; return this; } - public ContainerConfiguration setClassWorld( ClassWorld classWorld ) - { + public ContainerConfiguration setClassWorld(ClassWorld classWorld) { this.classWorld = classWorld; return this; } - public ContainerConfiguration setRealm( ClassRealm realm ) - { + public ContainerConfiguration setRealm(ClassRealm realm) { this.realm = realm; return this; } - public ContainerConfiguration setContainerConfiguration( String containerConfiguration ) - { + public ContainerConfiguration setContainerConfiguration(String containerConfiguration) { this.containerConfiguration = containerConfiguration; return this; } - public String getContainerConfiguration() - { + public String getContainerConfiguration() { return containerConfiguration; } - public ContainerConfiguration setContainerConfigurationURL( URL containerConfiguration ) - { + public ContainerConfiguration setContainerConfigurationURL(URL containerConfiguration) { this.containerConfigurationURL = containerConfiguration; return this; } - public URL getContainerConfigurationURL() - { + public URL getContainerConfigurationURL() { return containerConfigurationURL; } - public String getName() - { + public String getName() { return name; } - public Map getContext() - { + public Map getContext() { return context; } - public ClassWorld getClassWorld() - { + public ClassWorld getClassWorld() { return classWorld; } - public ClassRealm getRealm() - { + public ClassRealm getRealm() { return realm; } // Programmatic Container Initialization and Setup - public ContainerConfiguration setInitializationPhases( ContainerInitializationPhase[] initializationPhases ) - { + public ContainerConfiguration setInitializationPhases(ContainerInitializationPhase[] initializationPhases) { this.initializationPhases = initializationPhases; return this; } - public ContainerInitializationPhase[] getInitializationPhases() - { + public ContainerInitializationPhase[] getInitializationPhases() { return initializationPhases; } - private ContainerInitializationPhase[] initializationPhases = - { - new InitializeComponentRegistryPhase(), - new InitializeComponentFactoryManagerPhase(), - new InitializeContainerConfigurationSourcePhase(), - new InitializeLoggerManagerPhase(), - new InitializeSystemPropertiesPhase(), - new InitializeComponentDiscovererManagerPhase(), - new InitializeUserConfigurationSourcePhase() - - }; + private ContainerInitializationPhase[] initializationPhases = { + new InitializeComponentRegistryPhase(), + new InitializeComponentFactoryManagerPhase(), + new InitializeContainerConfigurationSourcePhase(), + new InitializeLoggerManagerPhase(), + new InitializeSystemPropertiesPhase(), + new InitializeComponentDiscovererManagerPhase(), + new InitializeUserConfigurationSourcePhase() + }; // Component discoverer private ComponentDiscovererManager componentDiscovererManager; - public ContainerConfiguration addComponentDiscoveryListener( ComponentDiscoveryListener componentDiscoveryListener ) - { - getComponentDiscovererManager().registerComponentDiscoveryListener( componentDiscoveryListener ); + public ContainerConfiguration addComponentDiscoveryListener(ComponentDiscoveryListener componentDiscoveryListener) { + getComponentDiscovererManager().registerComponentDiscoveryListener(componentDiscoveryListener); return this; } - public ContainerConfiguration addComponentDiscoverer( ComponentDiscoverer componentDiscoverer ) - { - ((DefaultComponentDiscovererManager)getComponentDiscovererManager()).addComponentDiscoverer( componentDiscoverer ); + public ContainerConfiguration addComponentDiscoverer(ComponentDiscoverer componentDiscoverer) { + ((DefaultComponentDiscovererManager) getComponentDiscovererManager()) + .addComponentDiscoverer(componentDiscoverer); return this; } - public ContainerConfiguration addComponentDiscoverer( Class clazz ) - { - componentDiscoverers.add( clazz ); + public ContainerConfiguration addComponentDiscoverer(Class clazz) { + componentDiscoverers.add(clazz); return this; } - public ContainerConfiguration addComponentDiscoveryListener( Class clazz ) - { - componentDiscoveryListeners.add( clazz ); + public ContainerConfiguration addComponentDiscoveryListener(Class clazz) { + componentDiscoveryListeners.add(clazz); return this; } - public List getComponentDiscoverers() - { + public List getComponentDiscoverers() { return componentDiscoverers; } - public List getComponentDiscoveryListeners() - { + public List getComponentDiscoveryListeners() { return componentDiscoveryListeners; - } - - public ContainerConfiguration setComponentDiscovererManager( ComponentDiscovererManager componentDiscovererManager ) - { + } + + public ContainerConfiguration setComponentDiscovererManager(ComponentDiscovererManager componentDiscovererManager) { this.componentDiscovererManager = componentDiscovererManager; return this; } - public ComponentDiscovererManager getComponentDiscovererManager() - { - if ( componentDiscovererManager == null ) - { + public ComponentDiscovererManager getComponentDiscovererManager() { + if (componentDiscovererManager == null) { componentDiscovererManager = new DefaultComponentDiscovererManager(); - ((DefaultComponentDiscovererManager)componentDiscovererManager).addComponentDiscoverer( new DefaultComponentDiscoverer() ); + ((DefaultComponentDiscovererManager) componentDiscovererManager) + .addComponentDiscoverer(new DefaultComponentDiscoverer()); - ((DefaultComponentDiscovererManager)componentDiscovererManager).addComponentDiscoverer( new PlexusXmlComponentDiscoverer() ); + ((DefaultComponentDiscovererManager) componentDiscovererManager) + .addComponentDiscoverer(new PlexusXmlComponentDiscoverer()); } return componentDiscovererManager; } - private ComponentFactoryManager componentFactoryManager; - public ComponentFactoryManager getComponentFactoryManager() - { - if ( componentFactoryManager == null ) - { - componentFactoryManager = new DefaultComponentFactoryManager(); + public ComponentFactoryManager getComponentFactoryManager() { + if (componentFactoryManager == null) { + componentFactoryManager = new DefaultComponentFactoryManager(); } return componentFactoryManager; } - public ContainerConfiguration setComponentFactoryManager( ComponentFactoryManager componentFactoryManager ) - { + public ContainerConfiguration setComponentFactoryManager(ComponentFactoryManager componentFactoryManager) { this.componentFactoryManager = componentFactoryManager; return this; @@ -242,17 +214,14 @@ public ContainerConfiguration setComponentFactoryManager( ComponentFactoryManage private ComponentRepository componentRepository; - public ContainerConfiguration setComponentRepository( ComponentRepository componentRepository ) - { + public ContainerConfiguration setComponentRepository(ComponentRepository componentRepository) { this.componentRepository = componentRepository; return this; } - public ComponentRepository getComponentRepository() - { - if ( componentRepository == null ) - { + public ComponentRepository getComponentRepository() { + if (componentRepository == null) { componentRepository = new DefaultComponentRepository(); } @@ -263,76 +232,72 @@ public ComponentRepository getComponentRepository() private LifecycleHandlerManager lifecycleHandlerManager; - public ContainerConfiguration addLifecycleHandler( LifecycleHandler lifecycleHandler ) - { - getLifecycleHandlerManager().addLifecycleHandler( lifecycleHandler ); + public ContainerConfiguration addLifecycleHandler(LifecycleHandler lifecycleHandler) { + getLifecycleHandlerManager().addLifecycleHandler(lifecycleHandler); return this; } - public ContainerConfiguration setLifecycleHandlerManager( LifecycleHandlerManager lifecycleHandlerManager ) - { + public ContainerConfiguration setLifecycleHandlerManager(LifecycleHandlerManager lifecycleHandlerManager) { this.lifecycleHandlerManager = lifecycleHandlerManager; return this; } - public LifecycleHandlerManager getLifecycleHandlerManager() - { - if ( lifecycleHandlerManager == null ) - { + public LifecycleHandlerManager getLifecycleHandlerManager() { + if (lifecycleHandlerManager == null) { lifecycleHandlerManager = new DefaultLifecycleHandlerManager(); // Plexus - LifecycleHandler plexus = new BasicLifecycleHandler( "plexus" ); + LifecycleHandler plexus = new BasicLifecycleHandler("plexus"); // Begin - plexus.addBeginSegment( new LogEnablePhase() ); - plexus.addBeginSegment( new ContextualizePhase() ); -// plexus.addBeginSegment( new AutoConfigurePhase() ); - plexus.addBeginSegment( new InitializePhase() ); - plexus.addBeginSegment( new StartPhase() ); + plexus.addBeginSegment(new LogEnablePhase()); + plexus.addBeginSegment(new ContextualizePhase()); + // plexus.addBeginSegment( new AutoConfigurePhase() ); + plexus.addBeginSegment(new InitializePhase()); + plexus.addBeginSegment(new StartPhase()); // End - plexus.addEndSegment( new StopPhase() ); - plexus.addEndSegment( new DisposePhase() ); - plexus.addEndSegment( new LogDisablePhase() ); - lifecycleHandlerManager.addLifecycleHandler( plexus ); + plexus.addEndSegment(new StopPhase()); + plexus.addEndSegment(new DisposePhase()); + plexus.addEndSegment(new LogDisablePhase()); + lifecycleHandlerManager.addLifecycleHandler(plexus); // Basic - LifecycleHandler basic = new BasicLifecycleHandler( "basic" ); + LifecycleHandler basic = new BasicLifecycleHandler("basic"); // Begin - basic.addBeginSegment( new LogEnablePhase() ); - basic.addBeginSegment( new ContextualizePhase() ); -// basic.addBeginSegment( new AutoConfigurePhase() ); - basic.addBeginSegment( new InitializePhase() ); - basic.addBeginSegment( new StartPhase() ); + basic.addBeginSegment(new LogEnablePhase()); + basic.addBeginSegment(new ContextualizePhase()); + // basic.addBeginSegment( new AutoConfigurePhase() ); + basic.addBeginSegment(new InitializePhase()); + basic.addBeginSegment(new StartPhase()); // End - basic.addEndSegment( new StopPhase() ); - basic.addEndSegment( new DisposePhase() ); - basic.addEndSegment( new LogDisablePhase() ); - lifecycleHandlerManager.addLifecycleHandler( basic ); + basic.addEndSegment(new StopPhase()); + basic.addEndSegment(new DisposePhase()); + basic.addEndSegment(new LogDisablePhase()); + lifecycleHandlerManager.addLifecycleHandler(basic); // Plexus configurable - LifecycleHandler plexusConfigurable = new BasicLifecycleHandler( "plexus-configurable" ); + LifecycleHandler plexusConfigurable = new BasicLifecycleHandler("plexus-configurable"); // Begin - plexusConfigurable.addBeginSegment( new LogEnablePhase() ); - plexusConfigurable.addBeginSegment( new ContextualizePhase() ); - plexusConfigurable.addBeginSegment( new ConfigurablePhase() ); - plexusConfigurable.addBeginSegment( new InitializePhase() ); - plexusConfigurable.addBeginSegment( new StartPhase() ); + plexusConfigurable.addBeginSegment(new LogEnablePhase()); + plexusConfigurable.addBeginSegment(new ContextualizePhase()); + plexusConfigurable.addBeginSegment(new ConfigurablePhase()); + plexusConfigurable.addBeginSegment(new InitializePhase()); + plexusConfigurable.addBeginSegment(new StartPhase()); // End - plexusConfigurable.addEndSegment( new StopPhase() ); - plexusConfigurable.addEndSegment( new DisposePhase() ); - plexusConfigurable.addEndSegment( new LogDisablePhase() ); - lifecycleHandlerManager.addLifecycleHandler( plexusConfigurable ); + plexusConfigurable.addEndSegment(new StopPhase()); + plexusConfigurable.addEndSegment(new DisposePhase()); + plexusConfigurable.addEndSegment(new LogDisablePhase()); + lifecycleHandlerManager.addLifecycleHandler(plexusConfigurable); // Passive - LifecycleHandler passive = new BasicLifecycleHandler( "passive" ); - lifecycleHandlerManager.addLifecycleHandler( passive ); + LifecycleHandler passive = new BasicLifecycleHandler("passive"); + lifecycleHandlerManager.addLifecycleHandler(passive); // Bootstrap - LifecycleHandler bootstrap = new BasicLifecycleHandler( "bootstrap" ); - bootstrap.addBeginSegment( new ContextualizePhase() ); - lifecycleHandlerManager.addLifecycleHandler( bootstrap ); + LifecycleHandler bootstrap = new BasicLifecycleHandler("bootstrap"); + bootstrap.addBeginSegment(new ContextualizePhase()); + lifecycleHandlerManager.addLifecycleHandler(bootstrap); } return lifecycleHandlerManager; @@ -340,15 +305,13 @@ public LifecycleHandlerManager getLifecycleHandlerManager() // Configuration Sources - public ContainerConfiguration setConfigurationSource( ConfigurationSource configurationSource ) - { + public ContainerConfiguration setConfigurationSource(ConfigurationSource configurationSource) { this.configurationSource = configurationSource; return this; } - public ConfigurationSource getConfigurationSource() - { + public ConfigurationSource getConfigurationSource() { return configurationSource; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/DefaultPlexusContainer.java b/plexus-container-default/src/main/java/org/codehaus/plexus/DefaultPlexusContainer.java index eb60a76e1..775b78d6c 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/DefaultPlexusContainer.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/DefaultPlexusContainer.java @@ -16,9 +16,6 @@ * limitations under the License. */ -import static org.codehaus.plexus.PlexusConstants.PLEXUS_DEFAULT_HINT; -import static org.codehaus.plexus.component.CastUtils.cast; - import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; @@ -61,15 +58,15 @@ import org.codehaus.plexus.util.InterpolationFilterReader; import org.codehaus.plexus.util.ReaderFactory; +import static org.codehaus.plexus.PlexusConstants.PLEXUS_DEFAULT_HINT; +import static org.codehaus.plexus.component.CastUtils.cast; + /** * Default implementation of PlexusContainer and MutablePlexusContainer. * @author Jason van Zyl * @author Kenney Westerhof */ -public class DefaultPlexusContainer - extends AbstractLogEnabled - implements MutablePlexusContainer -{ +public class DefaultPlexusContainer extends AbstractLogEnabled implements MutablePlexusContainer { protected static final String DEFAULT_CONTAINER_NAME = "default"; protected static final String DEFAULT_REALM_NAME = "plexus.core"; @@ -122,37 +119,31 @@ public class DefaultPlexusContainer // TODO: Is there a more threadpool-friendly way to do this? private ThreadLocal lookupRealm = new ThreadLocal(); - public void addComponent( Object component, String role ) - { - addComponent( component, role, PLEXUS_DEFAULT_HINT ); + public void addComponent(Object component, String role) { + addComponent(component, role, PLEXUS_DEFAULT_HINT); } - public void addComponent( T component, Class role, String roleHint ) - { - addComponent( component, role.getName(), roleHint ); + public void addComponent(T component, Class role, String roleHint) { + addComponent(component, role.getName(), roleHint); } - public void addComponent( Object component, String role, String roleHint ) - { - if ( roleHint == null ) - { + public void addComponent(Object component, String role, String roleHint) { + if (roleHint == null) { roleHint = PLEXUS_DEFAULT_HINT; } - getComponentRegistry().addComponent( component, role, roleHint ); + getComponentRegistry().addComponent(component, role, roleHint); } - public ClassRealm setLookupRealm( ClassRealm realm ) - { + public ClassRealm setLookupRealm(ClassRealm realm) { ClassRealm oldRealm = lookupRealm.get(); - lookupRealm.set( realm ); + lookupRealm.set(realm); return oldRealm; } - public ClassRealm getLookupRealm() - { + public ClassRealm getLookupRealm() { return lookupRealm.get(); } @@ -160,40 +151,27 @@ public ClassRealm getLookupRealm() // Constructors // ---------------------------------------------------------------------- - public DefaultPlexusContainer() - throws PlexusContainerException - { - construct( new DefaultContainerConfiguration() ); + public DefaultPlexusContainer() throws PlexusContainerException { + construct(new DefaultContainerConfiguration()); } - public DefaultPlexusContainer( ContainerConfiguration c ) - throws PlexusContainerException - { - construct( c ); + public DefaultPlexusContainer(ContainerConfiguration c) throws PlexusContainerException { + construct(c); } - public ClassRealm createChildRealm( String id ) - { - try - { - return containerRealm.createChildRealm( id ); - } - catch ( DuplicateRealmException e ) - { - try - { - return classWorld.getRealm( id ); - } - catch ( NoSuchRealmException e1 ) - { + public ClassRealm createChildRealm(String id) { + try { + return containerRealm.createChildRealm(id); + } catch (DuplicateRealmException e) { + try { + return classWorld.getRealm(id); + } catch (NoSuchRealmException e1) { return null; } } } - private void construct( ContainerConfiguration c ) - throws PlexusContainerException - { + private void construct(ContainerConfiguration c) throws PlexusContainerException { configurationSource = c.getConfigurationSource(); // ---------------------------------------------------------------------------- @@ -203,44 +181,36 @@ private void construct( ContainerConfiguration c ) classWorld = c.getClassWorld(); // Make sure we have a valid ClassWorld - if ( classWorld == null ) - { - classWorld = new ClassWorld( DEFAULT_REALM_NAME, Thread.currentThread().getContextClassLoader() ); + if (classWorld == null) { + classWorld = + new ClassWorld(DEFAULT_REALM_NAME, Thread.currentThread().getContextClassLoader()); } containerRealm = c.getRealm(); - if ( containerRealm == null ) - { - try - { - containerRealm = classWorld.getRealm( DEFAULT_REALM_NAME ); - } - catch ( NoSuchRealmException e ) - { + if (containerRealm == null) { + try { + containerRealm = classWorld.getRealm(DEFAULT_REALM_NAME); + } catch (NoSuchRealmException e) { containerRealm = (ClassRealm) classWorld.getRealms().iterator().next(); - if ( containerRealm == null ) - { - System.err.println( "No container realm! Expect errors." ); + if (containerRealm == null) { + System.err.println("No container realm! Expect errors."); new Throwable().printStackTrace(); } } } - setLookupRealm( containerRealm ); + setLookupRealm(containerRealm); // ---------------------------------------------------------------------------- // Context // ---------------------------------------------------------------------------- - if ( c.getContext() != null ) - { - containerContext = new DefaultContext( c.getContext() ); - } - else - { + if (c.getContext() != null) { + containerContext = new DefaultContext(c.getContext()); + } else { containerContext = new DefaultContext(); } @@ -250,295 +220,225 @@ private void construct( ContainerConfiguration c ) InputStream in = null; - if ( c.getContainerConfiguration() != null ) - { - in = toStream( c.getContainerConfiguration() ); + if (c.getContainerConfiguration() != null) { + in = toStream(c.getContainerConfiguration()); } - try - { - if ( c.getContainerConfigurationURL() != null ) - { + try { + if (c.getContainerConfigurationURL() != null) { in = c.getContainerConfigurationURL().openStream(); } - } - catch ( IOException e ) - { - throw new PlexusContainerException( "Error reading configuration URL", e ); + } catch (IOException e) { + throw new PlexusContainerException("Error reading configuration URL", e); } - try - { - configurationReader = in == null ? null : ReaderFactory.newXmlReader( in ); - } - catch ( IOException e ) - { - throw new PlexusContainerException( "Error reading configuration file", e ); + try { + configurationReader = in == null ? null : ReaderFactory.newXmlReader(in); + } catch (IOException e) { + throw new PlexusContainerException("Error reading configuration file", e); } - try - { - initialize( c ); + try { + initialize(c); start(); + } finally { + IOUtil.close(configurationReader); } - finally - { - IOUtil.close( configurationReader ); - } - - for( Class clazz : c.getComponentDiscoverers() ) - { - try - { - ComponentDiscoverer cd = (ComponentDiscoverer) lookup( clazz ); - componentDiscovererManager.addComponentDiscoverer( cd ); - } - catch ( ComponentLookupException e ) - { + + for (Class clazz : c.getComponentDiscoverers()) { + try { + ComponentDiscoverer cd = (ComponentDiscoverer) lookup(clazz); + componentDiscovererManager.addComponentDiscoverer(cd); + } catch (ComponentLookupException e) { } } - - for( Class clazz : c.getComponentDiscoveryListeners() ) - { - try - { - ComponentDiscoveryListener cdl = (ComponentDiscoveryListener) lookup( clazz ); - componentDiscovererManager.registerComponentDiscoveryListener( cdl ); - } - catch ( ComponentLookupException e ) - { + + for (Class clazz : c.getComponentDiscoveryListeners()) { + try { + ComponentDiscoveryListener cdl = (ComponentDiscoveryListener) lookup(clazz); + componentDiscovererManager.registerComponentDiscoveryListener(cdl); + } catch (ComponentLookupException e) { } - } + } } // ---------------------------------------------------------------------------- // Lookup // ---------------------------------------------------------------------------- - private Class getInterfaceClass( String role, String hint ) - { + private Class getInterfaceClass(String role, String hint) { ComponentDescriptor cd; - if ( hint == null ) - { - cd = getComponentDescriptor( role ); + if (hint == null) { + cd = getComponentDescriptor(role); + } else { + cd = getComponentDescriptor(role, hint); } - else - { - cd = getComponentDescriptor( role, hint ); - } - - if ( cd != null ) - { - try - { + + if (cd != null) { + try { ClassRealm realm = getLookupRealm(); - if ( realm != null ) - { - return realm.loadClass( role ); - } - else - { + if (realm != null) { + return realm.loadClass(role); + } else { ClassLoader loader = cd.getImplementationClass().getClassLoader(); - if ( loader != null ) - { - return loader.loadClass( role ); + if (loader != null) { + return loader.loadClass(role); } } - } - catch ( ClassNotFoundException e ) - { + } catch (ClassNotFoundException e) { return Object.class; - } + } } return Object.class; } - - private Class getRoleClass( String role ) - { - return getInterfaceClass( role, null ); + + private Class getRoleClass(String role) { + return getInterfaceClass(role, null); } - private Class getRoleClass( String role, String hint ) - { - return getInterfaceClass( role, hint ); + private Class getRoleClass(String role, String hint) { + return getInterfaceClass(role, hint); } - public Object lookup( String role ) throws ComponentLookupException - { - return componentRegistry.lookup( getRoleClass( role ), role, "" ); + public Object lookup(String role) throws ComponentLookupException { + return componentRegistry.lookup(getRoleClass(role), role, ""); } - public Object lookup( String role, String roleHint ) throws ComponentLookupException - { - return componentRegistry.lookup( getRoleClass( role, roleHint ), role, roleHint ); + public Object lookup(String role, String roleHint) throws ComponentLookupException { + return componentRegistry.lookup(getRoleClass(role, roleHint), role, roleHint); } - public T lookup( Class type ) throws ComponentLookupException - { - return componentRegistry.lookup( type, type.getName(), "" ); + public T lookup(Class type) throws ComponentLookupException { + return componentRegistry.lookup(type, type.getName(), ""); } - public T lookup( Class type, String roleHint ) throws ComponentLookupException - { - return componentRegistry.lookup( type, type.getName(), roleHint ); + public T lookup(Class type, String roleHint) throws ComponentLookupException { + return componentRegistry.lookup(type, type.getName(), roleHint); } - public T lookup( Class type, String role, String roleHint ) throws ComponentLookupException - { - return componentRegistry.lookup( type, role, roleHint ); + public T lookup(Class type, String role, String roleHint) throws ComponentLookupException { + return componentRegistry.lookup(type, role, roleHint); } - public T lookup( ComponentDescriptor componentDescriptor ) - throws ComponentLookupException - { - return componentRegistry.lookup( componentDescriptor ); + public T lookup(ComponentDescriptor componentDescriptor) throws ComponentLookupException { + return componentRegistry.lookup(componentDescriptor); } - public List lookupList( String role ) throws ComponentLookupException - { - return cast(componentRegistry.lookupList( getRoleClass( role ), role, null)); + public List lookupList(String role) throws ComponentLookupException { + return cast(componentRegistry.lookupList(getRoleClass(role), role, null)); } - public List lookupList( String role, List roleHints ) throws ComponentLookupException - { - return cast(componentRegistry.lookupList( getRoleClass( role ), role, roleHints )); + public List lookupList(String role, List roleHints) throws ComponentLookupException { + return cast(componentRegistry.lookupList(getRoleClass(role), role, roleHints)); } - public List lookupList( Class type ) throws ComponentLookupException - { - return componentRegistry.lookupList( type, type.getName(), null ); + public List lookupList(Class type) throws ComponentLookupException { + return componentRegistry.lookupList(type, type.getName(), null); } - public List lookupList( Class type, List roleHints ) throws ComponentLookupException - { - return componentRegistry.lookupList( type, type.getName(), roleHints ); + public List lookupList(Class type, List roleHints) throws ComponentLookupException { + return componentRegistry.lookupList(type, type.getName(), roleHints); } - public Map lookupMap( String role ) throws ComponentLookupException - { - return cast(componentRegistry.lookupMap( getRoleClass( role ), role, null )); + public Map lookupMap(String role) throws ComponentLookupException { + return cast(componentRegistry.lookupMap(getRoleClass(role), role, null)); } - public Map lookupMap( String role, List roleHints ) throws ComponentLookupException - { - return cast(componentRegistry.lookupMap( getRoleClass( role ), role, roleHints )); + public Map lookupMap(String role, List roleHints) throws ComponentLookupException { + return cast(componentRegistry.lookupMap(getRoleClass(role), role, roleHints)); } - public Map lookupMap( Class type ) throws ComponentLookupException - { - return componentRegistry.lookupMap( type, type.getName(), null ); + public Map lookupMap(Class type) throws ComponentLookupException { + return componentRegistry.lookupMap(type, type.getName(), null); } - public Map lookupMap( Class type, List roleHints ) throws ComponentLookupException - { - return componentRegistry.lookupMap( type, type.getName(), roleHints ); + public Map lookupMap(Class type, List roleHints) throws ComponentLookupException { + return componentRegistry.lookupMap(type, type.getName(), roleHints); } // ---------------------------------------------------------------------- // Component Descriptor Lookup // ---------------------------------------------------------------------- - public boolean hasComponent( String role ) - { - return componentRegistry.getComponentDescriptor( Object.class, role, "" ) != null; + public boolean hasComponent(String role) { + return componentRegistry.getComponentDescriptor(Object.class, role, "") != null; } - public boolean hasComponent( String role, String roleHint ) - { - return componentRegistry.getComponentDescriptor( Object.class, role, roleHint ) != null; + public boolean hasComponent(String role, String roleHint) { + return componentRegistry.getComponentDescriptor(Object.class, role, roleHint) != null; } - public boolean hasComponent( Class type ) - { - return componentRegistry.getComponentDescriptor( type, type.getName(), "" ) != null; + public boolean hasComponent(Class type) { + return componentRegistry.getComponentDescriptor(type, type.getName(), "") != null; } - public boolean hasComponent( Class type, String roleHint ) - { - return componentRegistry.getComponentDescriptor( type, type.getName(), roleHint ) != null; + public boolean hasComponent(Class type, String roleHint) { + return componentRegistry.getComponentDescriptor(type, type.getName(), roleHint) != null; } - public boolean hasComponent( Class type, String role, String roleHint ) - { - return componentRegistry.getComponentDescriptor( type, role, roleHint ) != null; + public boolean hasComponent(Class type, String role, String roleHint) { + return componentRegistry.getComponentDescriptor(type, role, roleHint) != null; } - public ComponentDescriptor getComponentDescriptor( String role ) - { - return componentRegistry.getComponentDescriptor( Object.class, role, "" ); + public ComponentDescriptor getComponentDescriptor(String role) { + return componentRegistry.getComponentDescriptor(Object.class, role, ""); } - public ComponentDescriptor getComponentDescriptor( String role, String roleHint ) - { - return componentRegistry.getComponentDescriptor( Object.class, role, roleHint ); + public ComponentDescriptor getComponentDescriptor(String role, String roleHint) { + return componentRegistry.getComponentDescriptor(Object.class, role, roleHint); } - public ComponentDescriptor getComponentDescriptor( Class type, String role, String roleHint ) - { - return componentRegistry.getComponentDescriptor( type, role, roleHint ); + public ComponentDescriptor getComponentDescriptor(Class type, String role, String roleHint) { + return componentRegistry.getComponentDescriptor(type, role, roleHint); } - public Map> getComponentDescriptorMap( String role ) - { - return cast(componentRegistry.getComponentDescriptorMap( Object.class, role )); + public Map> getComponentDescriptorMap(String role) { + return cast(componentRegistry.getComponentDescriptorMap(Object.class, role)); } - public Map> getComponentDescriptorMap( Class type, String role ) - { - return componentRegistry.getComponentDescriptorMap( type, role ); + public Map> getComponentDescriptorMap(Class type, String role) { + return componentRegistry.getComponentDescriptorMap(type, role); } - public List> getComponentDescriptorList( String role ) - { - return cast(componentRegistry.getComponentDescriptorList( Object.class, role )); + public List> getComponentDescriptorList(String role) { + return cast(componentRegistry.getComponentDescriptorList(Object.class, role)); } - public List> getComponentDescriptorList( Class type, String role ) - { - return componentRegistry.getComponentDescriptorList( type, role ); + public List> getComponentDescriptorList(Class type, String role) { + return componentRegistry.getComponentDescriptorList(type, role); } - public void addComponentDescriptor( ComponentDescriptor componentDescriptor ) - throws CycleDetectedInComponentGraphException - { - if ( componentDescriptor.getRealm() == null ) - { - componentDescriptor.setRealm( this.containerRealm ); + public void addComponentDescriptor(ComponentDescriptor componentDescriptor) + throws CycleDetectedInComponentGraphException { + if (componentDescriptor.getRealm() == null) { + componentDescriptor.setRealm(this.containerRealm); // throw new ComponentImplementationNotFoundException( "ComponentDescriptor is missing realmId" ); } - componentRegistry.addComponentDescriptor( componentDescriptor ); + componentRegistry.addComponentDescriptor(componentDescriptor); } // ---------------------------------------------------------------------- // Component Release // ---------------------------------------------------------------------- - public void release( Object component ) - throws ComponentLifecycleException - { - componentRegistry.release( component ); + public void release(Object component) throws ComponentLifecycleException { + componentRegistry.release(component); } - public void releaseAll( Map components ) - throws ComponentLifecycleException - { - for ( Object component : components.values() ) - { - release( component ); + public void releaseAll(Map components) throws ComponentLifecycleException { + for (Object component : components.values()) { + release(component); } } - public void releaseAll( List components ) - throws ComponentLifecycleException - { - for ( Object component : components ) - { - release( component ); + public void releaseAll(List components) throws ComponentLifecycleException { + for (Object component : components) { + release(component); } } @@ -546,172 +446,126 @@ public void releaseAll( List components ) // Lifecycle Management // ---------------------------------------------------------------------- - protected void initialize( ContainerConfiguration containerConfiguration ) - throws PlexusContainerException - { - try - { - initializeConfiguration( containerConfiguration ); + protected void initialize(ContainerConfiguration containerConfiguration) throws PlexusContainerException { + try { + initializeConfiguration(containerConfiguration); - initializePhases( containerConfiguration ); - - containerContext.put( PlexusConstants.PLEXUS_KEY, this ); - - discoverComponents( getContainerRealm() ); - - PlexusConfiguration[] loadOnStartComponents = getConfiguration().getChild( "load-on-start" ).getChildren( "component" ); + initializePhases(containerConfiguration); - getLogger().debug( "Found " + loadOnStartComponents.length + " components to load on start" ); + containerContext.put(PlexusConstants.PLEXUS_KEY, this); + + discoverComponents(getContainerRealm()); + + PlexusConfiguration[] loadOnStartComponents = + getConfiguration().getChild("load-on-start").getChildren("component"); + + getLogger().debug("Found " + loadOnStartComponents.length + " components to load on start"); ClassLoader prevCl = Thread.currentThread().getContextClassLoader(); - try - { - for ( PlexusConfiguration loadOnStartComponent : loadOnStartComponents ) - { - String role = loadOnStartComponent.getChild( "role" ).getValue( null ); + try { + for (PlexusConfiguration loadOnStartComponent : loadOnStartComponents) { + String role = loadOnStartComponent.getChild("role").getValue(null); - String roleHint = loadOnStartComponent.getChild( "role-hint" ).getValue( null ); + String roleHint = loadOnStartComponent.getChild("role-hint").getValue(null); - if ( role == null ) - { - throw new PlexusContainerException( "Missing 'role' element from load-on-start." ); + if (role == null) { + throw new PlexusContainerException("Missing 'role' element from load-on-start."); } - if ( roleHint == null ) - { + if (roleHint == null) { roleHint = PlexusConstants.PLEXUS_DEFAULT_HINT; } - if ( roleHint.equals( "*" ) ) - { - getLogger().info( "Loading on start all components with [role]: " + "[" + role + "]" ); + if (roleHint.equals("*")) { + getLogger().info("Loading on start all components with [role]: " + "[" + role + "]"); - lookupList( role ); - } - else - { - getLogger().info( "Loading on start [role,roleHint]: " + "[" + role + "," + roleHint + "]" ); + lookupList(role); + } else { + getLogger().info("Loading on start [role,roleHint]: " + "[" + role + "," + roleHint + "]"); - lookup( role, roleHint ); + lookup(role, roleHint); } } + } catch (ComponentLookupException e) { + throw new PlexusContainerException("Error looking up load-on-start component.", e); + } finally { + Thread.currentThread().setContextClassLoader(prevCl); } - catch ( ComponentLookupException e ) - { - throw new PlexusContainerException( "Error looking up load-on-start component.", e ); - } - finally - { - Thread.currentThread().setContextClassLoader( prevCl ); - } - - } - catch ( ContextException e ) - { - throw new PlexusContainerException( "Error processing configuration", e ); - } - catch ( PlexusConfigurationException e ) - { - throw new PlexusContainerException( "Error configuring components", e ); - } - catch ( IOException e ) - { - throw new PlexusContainerException( "Error reading configuration file", e ); + + } catch (ContextException e) { + throw new PlexusContainerException("Error processing configuration", e); + } catch (PlexusConfigurationException e) { + throw new PlexusContainerException("Error configuring components", e); + } catch (IOException e) { + throw new PlexusContainerException("Error reading configuration file", e); + } catch (CycleDetectedInComponentGraphException e) { + throw new PlexusContainerException("Cycle detected in component graph in the system: ", e); } - catch ( CycleDetectedInComponentGraphException e ) - { - throw new PlexusContainerException( "Cycle detected in component graph in the system: ", e ); - } } - protected void initializePhases( ContainerConfiguration containerConfiguration ) - throws PlexusContainerException - { + protected void initializePhases(ContainerConfiguration containerConfiguration) throws PlexusContainerException { ContainerInitializationPhase[] initPhases = containerConfiguration.getInitializationPhases(); ContainerInitializationContext initializationContext = new ContainerInitializationContext( - this, - classWorld, - containerRealm, - configuration, - containerConfiguration ); - - for ( ContainerInitializationPhase phase : initPhases ) - { - try - { - phase.execute( initializationContext ); - } - catch ( Exception e ) - { - throw new PlexusContainerException( "Error initializaing container in " + phase.getClass().getName() - + ".", e ); + this, classWorld, containerRealm, configuration, containerConfiguration); + + for (ContainerInitializationPhase phase : initPhases) { + try { + phase.execute(initializationContext); + } catch (Exception e) { + throw new PlexusContainerException( + "Error initializaing container in " + phase.getClass().getName() + ".", e); } } } - protected void start() - throws PlexusContainerException - { + protected void start() throws PlexusContainerException { // XXX this is called after initializeConfiguration - is this correct? configuration = null; } - public void dispose() - { - try - { + public void dispose() { + try { componentRegistry.dispose(); boolean needToDisposeRealm = false; - try - { - containerRealm.setParentRealm( null ); + try { + containerRealm.setParentRealm(null); - if ( needToDisposeRealm ) - { - classWorld.disposeRealm( containerRealm.getId() ); + if (needToDisposeRealm) { + classWorld.disposeRealm(containerRealm.getId()); } + } catch (NoSuchRealmException e) { + getLogger().debug("Failed to dispose realm."); } - catch ( NoSuchRealmException e ) - { - getLogger().debug( "Failed to dispose realm." ); - } - } - finally - { - lookupRealm.set( null ); + } finally { + lookupRealm.set(null); } } - public void addContextValue( Object key, Object value ) - { - containerContext.put( key, value ); + public void addContextValue(Object key, Object value) { + containerContext.put(key, value); } // ---------------------------------------------------------------------- // Misc Configuration // ---------------------------------------------------------------------- - public ClassWorld getClassWorld() - { + public ClassWorld getClassWorld() { return classWorld; } - public void setClassWorld( ClassWorld classWorld ) - { + public void setClassWorld(ClassWorld classWorld) { this.classWorld = classWorld; } - public ClassRealm getContainerRealm() - { + public ClassRealm getContainerRealm() { return containerRealm; } - public void setContainerRealm( ClassRealm containerRealm ) - { + public void setContainerRealm(ClassRealm containerRealm) { this.containerRealm = containerRealm; } @@ -719,8 +573,7 @@ public void setContainerRealm( ClassRealm containerRealm ) // Context // ---------------------------------------------------------------------- - public Context getContext() - { + public Context getContext() { return containerContext; } @@ -730,32 +583,29 @@ public Context getContext() // TODO: put this in a separate helper class and turn into a component if possible, too big. - protected void initializeConfiguration( ContainerConfiguration c ) - throws PlexusConfigurationException, ContextException, IOException -{ - // We need an empty plexus configuration for merging. This is a function of removing the - // plexus-boostrap.xml file. - configuration = new XmlPlexusConfiguration( "plexus" ); + protected void initializeConfiguration(ContainerConfiguration c) + throws PlexusConfigurationException, ContextException, IOException { + // We need an empty plexus configuration for merging. This is a function of removing the + // plexus-boostrap.xml file. + configuration = new XmlPlexusConfiguration("plexus"); - if ( configurationReader != null ) - { - // User userConfiguration + if (configurationReader != null) { + // User userConfiguration - PlexusConfiguration userConfiguration = PlexusTools.buildConfiguration( "", getInterpolationConfigurationReader( configurationReader ) ); + PlexusConfiguration userConfiguration = PlexusTools.buildConfiguration( + "", getInterpolationConfigurationReader(configurationReader)); - // Merger of bootstrapConfiguration and user userConfiguration + // Merger of bootstrapConfiguration and user userConfiguration - configuration = PlexusConfigurationMerger.merge( userConfiguration, configuration ); + configuration = PlexusConfigurationMerger.merge(userConfiguration, configuration); + } } -} - protected Reader getInterpolationConfigurationReader( Reader reader ) - { - return new InterpolationFilterReader( reader, new ContextMapAdapter( containerContext ) ); + protected Reader getInterpolationConfigurationReader(Reader reader) { + return new InterpolationFilterReader(reader, new ContextMapAdapter(containerContext)); } - public Logger getLogger() - { + public Logger getLogger() { return super.getLogger(); } @@ -763,59 +613,49 @@ public Logger getLogger() // Discovery // ---------------------------------------------------------------------- - public void registerComponentDiscoveryListener( ComponentDiscoveryListener listener ) - { - componentDiscovererManager.registerComponentDiscoveryListener( listener ); + public void registerComponentDiscoveryListener(ComponentDiscoveryListener listener) { + componentDiscovererManager.registerComponentDiscoveryListener(listener); } - public void removeComponentDiscoveryListener( ComponentDiscoveryListener listener ) - { - componentDiscovererManager.removeComponentDiscoveryListener( listener ); + public void removeComponentDiscoveryListener(ComponentDiscoveryListener listener) { + componentDiscovererManager.removeComponentDiscoveryListener(listener); } // ---------------------------------------------------------------------------- // Mutable Container Interface // ---------------------------------------------------------------------------- - public ComponentRegistry getComponentRegistry() - { + public ComponentRegistry getComponentRegistry() { return componentRegistry; } - public void setComponentRegistry( ComponentRegistry componentRegistry ) - { + public void setComponentRegistry(ComponentRegistry componentRegistry) { this.componentRegistry = componentRegistry; } - public ComponentDiscovererManager getComponentDiscovererManager() - { + public ComponentDiscovererManager getComponentDiscovererManager() { return componentDiscovererManager; } - public void setComponentDiscovererManager( ComponentDiscovererManager componentDiscovererManager ) - { + public void setComponentDiscovererManager(ComponentDiscovererManager componentDiscovererManager) { this.componentDiscovererManager = componentDiscovererManager; } - public ComponentFactoryManager getComponentFactoryManager() - { + public ComponentFactoryManager getComponentFactoryManager() { return componentFactoryManager; } - public void setComponentFactoryManager( ComponentFactoryManager componentFactoryManager ) - { + public void setComponentFactoryManager(ComponentFactoryManager componentFactoryManager) { this.componentFactoryManager = componentFactoryManager; } // Configuration - public PlexusConfiguration getConfiguration() - { + public PlexusConfiguration getConfiguration() { return configuration; } - public void setConfiguration( PlexusConfiguration configuration ) - { + public void setConfiguration(PlexusConfiguration configuration) { this.configuration = configuration; } @@ -823,22 +663,17 @@ public void setConfiguration( PlexusConfiguration configuration ) // Component Realms // ---------------------------------------------------------------------------- - public ClassRealm getComponentRealm( String realmId ) - { + public ClassRealm getComponentRealm(String realmId) { ClassRealm realm = null; - try - { - realm = classWorld.getRealm( realmId ); - } - catch ( NoSuchRealmException e ) - { + try { + realm = classWorld.getRealm(realmId); + } catch (NoSuchRealmException e) { // This should never happen: when a component is discovered, it is discovered from a realm and // it is at that point the realm id is assigned to the component descriptor. } - if ( realm == null ) - { + if (realm == null) { // The core components need the container realm. realm = containerRealm; } @@ -846,48 +681,36 @@ public ClassRealm getComponentRealm( String realmId ) return realm; } - public void removeComponentRealm( ClassRealm realm ) - throws PlexusContainerException - { - if ( getContainerRealm().getId().equals( realm.getId() ) ) - { - throw new IllegalArgumentException( "Cannot remove container realm: " + realm.getId() - + "\n(trying to remove container realm as if it were a component realm)." ); + public void removeComponentRealm(ClassRealm realm) throws PlexusContainerException { + if (getContainerRealm().getId().equals(realm.getId())) { + throw new IllegalArgumentException("Cannot remove container realm: " + realm.getId() + + "\n(trying to remove container realm as if it were a component realm)."); } - componentRegistry.removeComponentRealm( realm ); + componentRegistry.removeComponentRealm(realm); ClassRealm lookupRealm = getLookupRealm(); - if ( ( lookupRealm != null ) && lookupRealm.getId().equals( realm.getId() ) ) - { - setLookupRealm( getContainerRealm() ); + if ((lookupRealm != null) && lookupRealm.getId().equals(realm.getId())) { + setLookupRealm(getContainerRealm()); } } - private InputStream toStream( String resource ) - throws PlexusContainerException - { - if ( resource == null ) - { + private InputStream toStream(String resource) throws PlexusContainerException { + if (resource == null) { return null; } String relativeResource = resource; - if ( resource.startsWith( "/" ) ) - { - relativeResource = resource.substring( 1 ); + if (resource.startsWith("/")) { + relativeResource = resource.substring(1); } - InputStream is = getClass().getClassLoader().getResourceAsStream( relativeResource ); + InputStream is = getClass().getClassLoader().getResourceAsStream(relativeResource); - if ( is == null ) - { - try - { - return new FileInputStream( resource ); - } - catch ( FileNotFoundException e ) - { + if (is == null) { + try { + return new FileInputStream(resource); + } catch (FileNotFoundException e) { return null; } } @@ -898,77 +721,64 @@ private InputStream toStream( String resource ) /** * Utility method to get a default lookup realm for a component. */ - public ClassRealm getLookupRealm( Object component ) - { - if ( component.getClass().getClassLoader() instanceof ClassRealm ) - { - return ( (ClassRealm) component.getClass().getClassLoader() ); - } - else - { + public ClassRealm getLookupRealm(Object component) { + if (component.getClass().getClassLoader() instanceof ClassRealm) { + return ((ClassRealm) component.getClass().getClassLoader()); + } else { return getLookupRealm(); } - } - public void setConfigurationSource( ConfigurationSource configurationSource ) - { + public void setConfigurationSource(ConfigurationSource configurationSource) { this.configurationSource = configurationSource; } - public ConfigurationSource getConfigurationSource() - { + public ConfigurationSource getConfigurationSource() { return configurationSource; } - public LoggerManager getLoggerManager() - { + public LoggerManager getLoggerManager() { // TODO Auto-generated method stub return loggerManager; } - public void setLoggerManager( LoggerManager loggerManager ) - { + public void setLoggerManager(LoggerManager loggerManager) { this.loggerManager = loggerManager; - } - + // Discovery - public List> discoverComponents( ClassRealm realm ) - throws PlexusConfigurationException, CycleDetectedInComponentGraphException - { - return discoverComponents( realm, null ); - } - - public List> discoverComponents( ClassRealm realm, Object data ) - throws PlexusConfigurationException, CycleDetectedInComponentGraphException - { + public List> discoverComponents(ClassRealm realm) + throws PlexusConfigurationException, CycleDetectedInComponentGraphException { + return discoverComponents(realm, null); + } + + public List> discoverComponents(ClassRealm realm, Object data) + throws PlexusConfigurationException, CycleDetectedInComponentGraphException { List componentSetDescriptors = new ArrayList(); List> discoveredComponentDescriptors = new ArrayList>(); - for ( ComponentDiscoverer componentDiscoverer : getComponentDiscovererManager().getComponentDiscoverers() ) - { - for ( ComponentSetDescriptor componentSetDescriptor : componentDiscoverer.findComponents( getContext(), realm ) ) - { + for (ComponentDiscoverer componentDiscoverer : + getComponentDiscovererManager().getComponentDiscoverers()) { + for (ComponentSetDescriptor componentSetDescriptor : + componentDiscoverer.findComponents(getContext(), realm)) { // Here we should collect all the urls // do the interpolation against the context // register all the components // allow interception and replacement of the components - componentSetDescriptors.add( componentSetDescriptor ); + componentSetDescriptors.add(componentSetDescriptor); // Fire the event - ComponentDiscoveryEvent event = new ComponentDiscoveryEvent( componentSetDescriptor, data ); + ComponentDiscoveryEvent event = new ComponentDiscoveryEvent(componentSetDescriptor, data); - componentDiscovererManager.fireComponentDiscoveryEvent( event ); + componentDiscovererManager.fireComponentDiscoveryEvent(event); - for ( ComponentDescriptor componentDescriptor : componentSetDescriptor.getComponents() ) - { - addComponentDescriptor( componentDescriptor ); + for (ComponentDescriptor componentDescriptor : componentSetDescriptor.getComponents()) { + addComponentDescriptor(componentDescriptor); - discoveredComponentDescriptors.add( componentDescriptor ); + discoveredComponentDescriptors.add(componentDescriptor); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/DuplicateChildContainerException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/DuplicateChildContainerException.java index f0e9fb521..73a1683bb 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/DuplicateChildContainerException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/DuplicateChildContainerException.java @@ -16,30 +16,25 @@ * limitations under the License. */ -public class DuplicateChildContainerException - extends PlexusContainerException -{ +public class DuplicateChildContainerException extends PlexusContainerException { private final String parent; private final String child; - public DuplicateChildContainerException( String parent, String child ) - { - super( "Cannot create child container, because child named \'" + child + "\' already exists in parent \'" + parent + "\'." ); + public DuplicateChildContainerException(String parent, String child) { + super("Cannot create child container, because child named \'" + child + "\' already exists in parent \'" + + parent + "\'."); this.parent = parent; this.child = child; } - - public String getParent() - { + + public String getParent() { return parent; } - - public String getChild() - { + + public String getChild() { return child; } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/MutablePlexusContainer.java b/plexus-container-default/src/main/java/org/codehaus/plexus/MutablePlexusContainer.java index a96647211..3db732a2b 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/MutablePlexusContainer.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/MutablePlexusContainer.java @@ -28,40 +28,38 @@ /** * @author Jason van Zyl */ -public interface MutablePlexusContainer - extends PlexusContainer -{ +public interface MutablePlexusContainer extends PlexusContainer { // Core Components ComponentRegistry getComponentRegistry(); - void setComponentRegistry( ComponentRegistry componentRegistry ); + void setComponentRegistry(ComponentRegistry componentRegistry); ComponentDiscovererManager getComponentDiscovererManager(); - void setComponentDiscovererManager( ComponentDiscovererManager componentDiscovererManager ); + void setComponentDiscovererManager(ComponentDiscovererManager componentDiscovererManager); ComponentFactoryManager getComponentFactoryManager(); - void setComponentFactoryManager( ComponentFactoryManager componentFactoryManager ); + void setComponentFactoryManager(ComponentFactoryManager componentFactoryManager); LoggerManager getLoggerManager(); - void setLoggerManager( LoggerManager loggerManager ); + void setLoggerManager(LoggerManager loggerManager); Logger getLogger(); - - void setConfigurationSource( ConfigurationSource configurationSource ); + + void setConfigurationSource(ConfigurationSource configurationSource); ConfigurationSource getConfigurationSource(); - + // Configuration - void setConfiguration( PlexusConfiguration configuration ); + void setConfiguration(PlexusConfiguration configuration); PlexusConfiguration getConfiguration(); - ClassRealm getComponentRealm( String realmId ); + ClassRealm getComponentRealm(String realmId); ClassWorld getClassWorld(); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusConstants.java b/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusConstants.java index d59abd2b0..5577a5d3f 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusConstants.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusConstants.java @@ -16,8 +16,7 @@ * limitations under the License. */ -public abstract class PlexusConstants -{ +public abstract class PlexusConstants { /** Key used to retrieve the plexus container from the containerContext. */ public static final String PLEXUS_KEY = "plexus"; diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusContainer.java b/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusContainer.java index 203a2e118..1b713f75f 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusContainer.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusContainer.java @@ -25,7 +25,6 @@ import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import org.codehaus.plexus.component.repository.exception.ComponentRepositoryException; import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.codehaus.plexus.context.Context; @@ -33,8 +32,7 @@ * PlexusContainer is the entry-point for loading and accessing other * components. */ -public interface PlexusContainer -{ +public interface PlexusContainer { String ROLE = PlexusContainer.class.getName(); // ------------------------------------------------------------------------ @@ -47,8 +45,7 @@ public interface PlexusContainer * @return a Plexus component object * @throws ComponentLookupException in case of lookup error. */ - Object lookup( String role ) - throws ComponentLookupException; + Object lookup(String role) throws ComponentLookupException; /** * Looks up and returns a component object with the given unique role/role-hint combination. @@ -57,8 +54,7 @@ Object lookup( String role ) * @return a Plexus component object * @throws ComponentLookupException in case of lookup error. */ - Object lookup( String role, String roleHint ) - throws ComponentLookupException; + Object lookup(String role, String roleHint) throws ComponentLookupException; /** * Looks up and returns a component object with the given unique key or role. @@ -67,8 +63,7 @@ Object lookup( String role, String roleHint ) * @return a Plexus component object * @throws ComponentLookupException in case of lookup error. */ - T lookup( Class type ) - throws ComponentLookupException; + T lookup(Class type) throws ComponentLookupException; /** * Looks up and returns a component object with the given unique role/role-hint combination. @@ -78,8 +73,7 @@ T lookup( Class type ) * @return a Plexus component object * @throws ComponentLookupException in case of lookup error. */ - T lookup( Class type, String roleHint ) - throws ComponentLookupException; + T lookup(Class type, String roleHint) throws ComponentLookupException; /** * Looks up and returns a component object with the given unique role/role-hint combination. @@ -90,8 +84,7 @@ T lookup( Class type, String roleHint ) * @return a Plexus component object * @throws ComponentLookupException in case of lookup error. */ - T lookup( Class type, String role, String roleHint ) - throws ComponentLookupException; + T lookup(Class type, String role, String roleHint) throws ComponentLookupException; /** * Looks up and returns a component object matching the given component descriptor. @@ -100,8 +93,7 @@ T lookup( Class type, String role, String roleHint ) * @return a Plexus component object * @throws ComponentLookupException in case of lookup error. */ - T lookup( ComponentDescriptor componentDescriptor ) - throws ComponentLookupException; + T lookup(ComponentDescriptor componentDescriptor) throws ComponentLookupException; /** * Looks up and returns a List of component objects with the given role. @@ -109,8 +101,7 @@ T lookup( ComponentDescriptor componentDescriptor ) * @return a List of component objects * @throws ComponentLookupException in case of lookup error. */ - List lookupList( String role ) - throws ComponentLookupException; + List lookupList(String role) throws ComponentLookupException; /** * Looks up and returns a List of component objects with the given role. @@ -119,8 +110,7 @@ List lookupList( String role ) * @return a List of component objects * @throws ComponentLookupException in case of lookup error. */ - List lookupList( String role, List roleHints ) - throws ComponentLookupException; + List lookupList(String role, List roleHints) throws ComponentLookupException; /** * Looks up and returns a List of component objects with the given role. @@ -129,8 +119,7 @@ List lookupList( String role, List roleHints ) * @return a List of component objects * @throws ComponentLookupException in case of lookup error. */ - List lookupList( Class type ) - throws ComponentLookupException; + List lookupList(Class type) throws ComponentLookupException; /** * Looks up and returns a List of component objects with the given role. @@ -140,8 +129,7 @@ List lookupList( Class type ) * @return a List of component objects * @throws ComponentLookupException in case of lookup error. */ - List lookupList( Class type, List roleHints ) - throws ComponentLookupException; + List lookupList(Class type, List roleHints) throws ComponentLookupException; /** * Looks up and returns a Map of component objects with the given role, keyed by all available role-hints. @@ -149,8 +137,7 @@ List lookupList( Class type, List roleHints ) * @return a Map of component objects * @throws ComponentLookupException in case of lookup error. */ - Map lookupMap( String role ) - throws ComponentLookupException; + Map lookupMap(String role) throws ComponentLookupException; /** * Looks up and returns a Map of component objects with the given role, keyed by all available role-hints. @@ -159,8 +146,7 @@ Map lookupMap( String role ) * @return a Map of component objects * @throws ComponentLookupException in case of lookup error. */ - Map lookupMap( String role, List roleHints ) - throws ComponentLookupException; + Map lookupMap(String role, List roleHints) throws ComponentLookupException; /** * Looks up and returns a Map of component objects with the given role, keyed by all available role-hints. @@ -169,8 +155,7 @@ Map lookupMap( String role, List roleHints ) * @return a Map of component objects * @throws ComponentLookupException in case of lookup error. */ - Map lookupMap( Class type ) - throws ComponentLookupException; + Map lookupMap(Class type) throws ComponentLookupException; /** * Looks up and returns a Map of component objects with the given role, keyed by all available role-hints. @@ -180,8 +165,7 @@ Map lookupMap( Class type ) * @return a Map of component objects * @throws ComponentLookupException in case of lookup error. */ - Map lookupMap( Class type, List roleHints ) - throws ComponentLookupException; + Map lookupMap(Class type, List roleHints) throws ComponentLookupException; // ---------------------------------------------------------------------- // Component Descriptor Lookup @@ -193,7 +177,7 @@ Map lookupMap( Class type, List roleHints ) * @param role a unique role for the desired component's descriptor * @return the ComponentDescriptor with the given component role */ - ComponentDescriptor getComponentDescriptor( String role ); + ComponentDescriptor getComponentDescriptor(String role); /** * Returns the ComponentDescriptor with the given component role and hint. @@ -202,7 +186,7 @@ Map lookupMap( Class type, List roleHints ) * @param roleHint a hint showing which implementation should be used * @return the ComponentDescriptor with the given component role */ - ComponentDescriptor getComponentDescriptor( String role, String roleHint ); + ComponentDescriptor getComponentDescriptor(String role, String roleHint); /** * Returns the ComponentDescriptor with the given component role and hint. @@ -213,7 +197,7 @@ Map lookupMap( Class type, List roleHints ) * @param The type. * @return the ComponentDescriptor with the given component role */ - ComponentDescriptor getComponentDescriptor( Class type, String role, String roleHint ); + ComponentDescriptor getComponentDescriptor(Class type, String role, String roleHint); /** * Returns a Map of ComponentDescriptors with the given role, keyed by role-hint. Searches up the hierarchy until @@ -221,7 +205,7 @@ Map lookupMap( Class type, List roleHints ) * @param role a non-unique key for the desired components * @return a Map of component descriptors keyed by role-hint */ - Map> getComponentDescriptorMap( String role ); + Map> getComponentDescriptorMap(String role); /** * Returns a Map of ComponentDescriptors with the given role, keyed by role-hint. Searches up the hierarchy until @@ -231,7 +215,7 @@ Map lookupMap( Class type, List roleHints ) * @param The type. * @return a Map of component descriptors keyed by role-hint */ - Map> getComponentDescriptorMap( Class type, String role ); + Map> getComponentDescriptorMap(Class type, String role); /** * Returns a List of ComponentDescriptors with the given role. Searches up the hierarchy until all are found, an @@ -239,7 +223,7 @@ Map lookupMap( Class type, List roleHints ) * @param role a non-unique key for the desired components * @return a List of component descriptors */ - List> getComponentDescriptorList( String role ); + List> getComponentDescriptorList(String role); /** * Returns a List of ComponentDescriptors with the given role. Searches up the hierarchy until all are found, an @@ -249,15 +233,15 @@ Map lookupMap( Class type, List roleHints ) * @param The type. * @return a List of component descriptors */ - List> getComponentDescriptorList( Class type, String role ); + List> getComponentDescriptorList(Class type, String role); /** * Adds a component descriptor to this container. componentDescriptor should have realmId set. * @param componentDescriptor {@link ComponentDescriptor} * @throws CycleDetectedInComponentGraphException In case of an error. */ - void addComponentDescriptor( ComponentDescriptor componentDescriptor ) - throws CycleDetectedInComponentGraphException; + void addComponentDescriptor(ComponentDescriptor componentDescriptor) + throws CycleDetectedInComponentGraphException; /** * Releases the component from the container. This is dependent upon how the implementation manages the component, @@ -266,8 +250,7 @@ void addComponentDescriptor( ComponentDescriptor componentDescriptor ) * @param component the plexus component object to release * @throws ComponentLifecycleException in case of an error. */ - void release( Object component ) - throws ComponentLifecycleException; + void release(Object component) throws ComponentLifecycleException; /** * Releases all Mapped component values from the container. @@ -275,8 +258,7 @@ void release( Object component ) * @param components Map of plexus component objects to release * @throws ComponentLifecycleException in case of an error. */ - void releaseAll( Map components ) - throws ComponentLifecycleException; + void releaseAll(Map components) throws ComponentLifecycleException; /** * Releases all Listed components from the container. @@ -284,15 +266,14 @@ void releaseAll( Map components ) * @param components List of plexus component objects to release * @throws ComponentLifecycleException in case of an error. */ - void releaseAll( List components ) - throws ComponentLifecycleException; + void releaseAll(List components) throws ComponentLifecycleException; /** * Returns true if this container has the keyed component. * @param role a non-unique key for the desired component * @return true if this container has the keyed component */ - boolean hasComponent( String role ); + boolean hasComponent(String role); /** * Returns true if this container has a component with the given role/role-hint. @@ -300,14 +281,14 @@ void releaseAll( List components ) * @param roleHint a hint for the desired component implementation * @return true if this container has a component with the given role/role-hint */ - boolean hasComponent( String role, String roleHint ); + boolean hasComponent(String role, String roleHint); /** * Returns true if this container has a component with the given role/role-hint. * @param type the non-unique type of the component * @return true if this container has a component with the given role/role-hint */ - boolean hasComponent( Class type ); + boolean hasComponent(Class type); /** * Returns true if this container has a component with the given role/role-hint. @@ -315,7 +296,7 @@ void releaseAll( List components ) * @param roleHint a hint for the desired component implementation * @return true if this container has a component with the given role/role-hint */ - boolean hasComponent( Class type, String roleHint ); + boolean hasComponent(Class type, String roleHint); /** * Returns true if this container has a component with the given role/role-hint. @@ -324,7 +305,7 @@ void releaseAll( List components ) * @param roleHint a hint for the desired component implementation * @return true if this container has a component with the given role/role-hint */ - boolean hasComponent( Class type, String role, String roleHint ); + boolean hasComponent(Class type, String role, String roleHint); /** * Disposes of this container, which in turn disposes all of it's components. This container should also remove @@ -341,7 +322,7 @@ void releaseAll( List components ) * @param key any unique object valid to the Context's implementation * @param value any object valid to the Context's implementation */ - void addContextValue( Object key, Object value ); + void addContextValue(Object key, Object value); /** * Returns this container's context. A Context is a simple data store used to hold values which may alter the @@ -366,13 +347,13 @@ void releaseAll( List components ) * ComponentDiscoverer events. * @param listener A listener which responds to different ComponentDiscoveryEvents */ - void registerComponentDiscoveryListener( ComponentDiscoveryListener listener ); + void registerComponentDiscoveryListener(ComponentDiscoveryListener listener); /** * Removes the listener from this container. * @param listener A listener to remove */ - void removeComponentDiscoveryListener( ComponentDiscoveryListener listener ); + void removeComponentDiscoveryListener(ComponentDiscoveryListener listener); /** * Discovers components in the given realm. @@ -381,8 +362,8 @@ void releaseAll( List components ) * @throws PlexusConfigurationException in case of an error. * @throws CycleDetectedInComponentGraphException in case of an error. */ - List> discoverComponents( ClassRealm childRealm ) - throws PlexusConfigurationException, CycleDetectedInComponentGraphException; + List> discoverComponents(ClassRealm childRealm) + throws PlexusConfigurationException, CycleDetectedInComponentGraphException; /** * Discovers components in the given realm. @@ -392,16 +373,16 @@ List> discoverComponents( ClassRealm childRealm ) * @throws PlexusConfigurationException in case of an error. * @throws CycleDetectedInComponentGraphException in case of an error. */ - List> discoverComponents( ClassRealm realm, Object data ) - throws PlexusConfigurationException, CycleDetectedInComponentGraphException; + List> discoverComponents(ClassRealm realm, Object data) + throws PlexusConfigurationException, CycleDetectedInComponentGraphException; // ---------------------------------------------------------------------------- // Component/Plugin ClassRealm creation // ---------------------------------------------------------------------------- - ClassRealm createChildRealm( String id ); + ClassRealm createChildRealm(String id); - ClassRealm getComponentRealm( String realmId ); + ClassRealm getComponentRealm(String realmId); /** * Dissociate the realm with the specified id from the container. This will @@ -410,8 +391,7 @@ List> discoverComponents( ClassRealm realm, Object data ) * @param componentRealm Realm to remove from the container. * @throws PlexusContainerException {@link PlexusContainerException}. */ - void removeComponentRealm( ClassRealm componentRealm ) - throws PlexusContainerException; + void removeComponentRealm(ClassRealm componentRealm) throws PlexusContainerException; /** * Returns the lookup realm for this container, which is either @@ -436,10 +416,9 @@ void removeComponentRealm( ClassRealm componentRealm ) * @param component The component. * @return {@link ClassRealm} */ - ClassRealm getLookupRealm( Object component ); + ClassRealm getLookupRealm(Object component); - void addComponent( Object component, String role ) - throws CycleDetectedInComponentGraphException; + void addComponent(Object component, String role) throws CycleDetectedInComponentGraphException; /** * Adds live component instance to this container. @@ -452,5 +431,5 @@ void addComponent( Object component, String role ) * @param roleHint The hint. * @param The type. */ - void addComponent( T component, Class role, String roleHint ); + void addComponent(T component, Class role, String roleHint); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusContainerException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusContainerException.java index 6afa26983..89ca080a1 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusContainerException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusContainerException.java @@ -21,8 +21,7 @@ * * @author Brett Porter */ -public class PlexusContainerException extends Exception -{ +public class PlexusContainerException extends Exception { private static final long serialVersionUID = 2213861902264275451L; /** @@ -30,17 +29,15 @@ public class PlexusContainerException extends Exception * @param message exception message * @param throwable causing exception to chain */ - public PlexusContainerException( String message, Throwable throwable ) - { - super( message, throwable ); + public PlexusContainerException(String message, Throwable throwable) { + super(message, throwable); } /** * Construct a new PlexusContainerException instance. * @param message exception message */ - public PlexusContainerException( String message ) - { - super( message ); + public PlexusContainerException(String message) { + super(message); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusJUnit4TestCase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusJUnit4TestCase.java index e225c5f5a..29316b77e 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusJUnit4TestCase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusJUnit4TestCase.java @@ -16,6 +16,9 @@ * limitations under the License. */ +import java.io.File; +import java.io.InputStream; + import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.component.repository.exception.ComponentLookupRuntimeException; import org.codehaus.plexus.configuration.PlexusConfiguration; @@ -24,9 +27,6 @@ import org.junit.After; import org.junit.Before; -import java.io.File; -import java.io.InputStream; - import static org.junit.Assert.fail; /** @@ -34,43 +34,37 @@ * @author Trygve Laugstøl * @author Michal Maczka */ -public abstract class PlexusJUnit4TestCase -{ +public abstract class PlexusJUnit4TestCase { private PlexusContainer container; private static String basedir; @Before - public void beforeTest() - throws Exception - { + public void beforeTest() throws Exception { basedir = getBasedir(); } - protected void setupContainer() - { + protected void setupContainer() { // ---------------------------------------------------------------------------- // Context Setup // ---------------------------------------------------------------------------- DefaultContext context = new DefaultContext(); - context.put( "basedir", getBasedir() ); + context.put("basedir", getBasedir()); - customizeContext( context ); + customizeContext(context); - boolean hasPlexusHome = context.contains( "plexus.home" ); + boolean hasPlexusHome = context.contains("plexus.home"); - if ( !hasPlexusHome ) - { - File f = getTestFile( "target/plexus-home" ); + if (!hasPlexusHome) { + File f = getTestFile("target/plexus-home"); - if ( !f.isDirectory() ) - { + if (!f.isDirectory()) { f.mkdir(); } - context.put( "plexus.home", f.getAbsolutePath() ); + context.put("plexus.home", f.getAbsolutePath()); } // ---------------------------------------------------------------------------- @@ -79,31 +73,24 @@ protected void setupContainer() String config = getCustomConfigurationName(); - ContainerConfiguration containerConfiguration = new DefaultContainerConfiguration() - .setName( "test" ) - .setContext( context.getContextData() ); + ContainerConfiguration containerConfiguration = + new DefaultContainerConfiguration().setName("test").setContext(context.getContextData()); - if ( config != null ) - { - containerConfiguration.setContainerConfiguration( config ); - } - else - { - String resource = getConfigurationName( null ); + if (config != null) { + containerConfiguration.setContainerConfiguration(config); + } else { + String resource = getConfigurationName(null); - containerConfiguration.setContainerConfiguration( resource ); + containerConfiguration.setContainerConfiguration(resource); } - customizeContainerConfiguration( containerConfiguration ); + customizeContainerConfiguration(containerConfiguration); - try - { - container = new DefaultPlexusContainer( containerConfiguration ); - } - catch ( PlexusContainerException e ) - { + try { + container = new DefaultPlexusContainer(containerConfiguration); + } catch (PlexusContainerException e) { e.printStackTrace(); - fail( "Failed to create plexus container." ); + fail("Failed to create plexus container."); } } @@ -113,53 +100,40 @@ protected void setupContainer() * * @param containerConfiguration The configuration */ - protected void customizeContainerConfiguration( ContainerConfiguration containerConfiguration ) - { - } + protected void customizeContainerConfiguration(ContainerConfiguration containerConfiguration) {} - protected void customizeContext( Context context ) - { - } + protected void customizeContext(Context context) {} - protected PlexusConfiguration customizeComponentConfiguration() - { + protected PlexusConfiguration customizeComponentConfiguration() { return null; } @After - public void afterTest() - throws Exception - { - if ( container != null ) - { + public void afterTest() throws Exception { + if (container != null) { container.dispose(); container = null; } } - protected PlexusContainer getContainer() - { - if ( container == null ) - { + protected PlexusContainer getContainer() { + if (container == null) { setupContainer(); } return container; } - protected InputStream getConfiguration() - { - return getConfiguration( null ); + protected InputStream getConfiguration() { + return getConfiguration(null); } - protected InputStream getConfiguration( String subname ) - { - return getResourceAsStream( getConfigurationName( subname ) ); + protected InputStream getConfiguration(String subname) { + return getResourceAsStream(getConfigurationName(subname)); } - protected String getCustomConfigurationName() - { + protected String getCustomConfigurationName() { return null; } @@ -172,18 +146,15 @@ protected String getCustomConfigurationName() * @param subname the subname (not used) * @return A configuration name */ - protected String getConfigurationName( String subname ) - { - return getClass().getName().replace( '.', '/' ) + ".xml"; + protected String getConfigurationName(String subname) { + return getClass().getName().replace('.', '/') + ".xml"; } - protected InputStream getResourceAsStream( String resource ) - { - return getClass().getResourceAsStream( resource ); + protected InputStream getResourceAsStream(String resource) { + return getClass().getResourceAsStream(resource); } - protected ClassLoader getClassLoader() - { + protected ClassLoader getClassLoader() { return getClass().getClassLoader(); } @@ -191,123 +162,89 @@ protected ClassLoader getClassLoader() // Container access // ---------------------------------------------------------------------- - protected Object lookup( String componentKey ) - { - try - { - return getContainer().lookup( componentKey ); - } - catch ( ComponentLookupException e ) - { - throw new ComponentLookupRuntimeException( e ); + protected Object lookup(String componentKey) { + try { + return getContainer().lookup(componentKey); + } catch (ComponentLookupException e) { + throw new ComponentLookupRuntimeException(e); } } - protected Object lookup( String role, - String roleHint ) - throws ComponentLookupRuntimeException - { - try - { - return getContainer().lookup( role, roleHint ); - } - catch ( ComponentLookupException e ) - { - throw new ComponentLookupRuntimeException( e ); + protected Object lookup(String role, String roleHint) throws ComponentLookupRuntimeException { + try { + return getContainer().lookup(role, roleHint); + } catch (ComponentLookupException e) { + throw new ComponentLookupRuntimeException(e); } } - protected T lookup( Class componentClass ) - throws ComponentLookupRuntimeException - { - try - { - return getContainer().lookup( componentClass ); - } - catch ( ComponentLookupException e ) - { - throw new ComponentLookupRuntimeException( e ); + protected T lookup(Class componentClass) throws ComponentLookupRuntimeException { + try { + return getContainer().lookup(componentClass); + } catch (ComponentLookupException e) { + throw new ComponentLookupRuntimeException(e); } } - protected T lookup( Class componentClass, String roleHint ) - throws ComponentLookupRuntimeException - { - try - { - return getContainer().lookup( componentClass, roleHint ); - } - catch ( ComponentLookupException e ) - { - throw new ComponentLookupRuntimeException( e ); + protected T lookup(Class componentClass, String roleHint) throws ComponentLookupRuntimeException { + try { + return getContainer().lookup(componentClass, roleHint); + } catch (ComponentLookupException e) { + throw new ComponentLookupRuntimeException(e); } } - protected void release( Object component ) - throws Exception - { - getContainer().release( component ); + protected void release(Object component) throws Exception { + getContainer().release(component); } // ---------------------------------------------------------------------- // Helper methods for sub classes // ---------------------------------------------------------------------- - public static File getTestFile( String path ) - { - return new File( getBasedir(), path ); + public static File getTestFile(String path) { + return new File(getBasedir(), path); } - public static File getTestFile( String basedir, - String path ) - { - File basedirFile = new File( basedir ); + public static File getTestFile(String basedir, String path) { + File basedirFile = new File(basedir); - if ( !basedirFile.isAbsolute() ) - { - basedirFile = getTestFile( basedir ); + if (!basedirFile.isAbsolute()) { + basedirFile = getTestFile(basedir); } - return new File( basedirFile, path ); + return new File(basedirFile, path); } - public static String getTestPath( String path ) - { - return getTestFile( path ).getAbsolutePath(); + public static String getTestPath(String path) { + return getTestFile(path).getAbsolutePath(); } - public static String getTestPath( String basedir, - String path ) - { - return getTestFile( basedir, path ).getAbsolutePath(); + public static String getTestPath(String basedir, String path) { + return getTestFile(basedir, path).getAbsolutePath(); } - public static String getBasedir() - { - if ( basedir != null ) - { + public static String getBasedir() { + if (basedir != null) { return basedir; } - basedir = System.getProperty( "basedir" ); + basedir = System.getProperty("basedir"); - if ( basedir == null ) - { - basedir = new File( "" ).getAbsolutePath(); + if (basedir == null) { + basedir = new File("").getAbsolutePath(); } return basedir; } - public String getTestConfiguration() - { - return getTestConfiguration( getClass() ); + public String getTestConfiguration() { + return getTestConfiguration(getClass()); } - public static String getTestConfiguration( Class clazz ) - { - String s = clazz.getName().replace( '.', '/' ); + public static String getTestConfiguration(Class clazz) { + String s = clazz.getName().replace('.', '/'); - return s.substring( 0, s.indexOf( "$" ) ) + ".xml"; + return s.substring(0, s.indexOf("$")) + ".xml"; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusTestCase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusTestCase.java index c3a2706e4..e41806f5e 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusTestCase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/PlexusTestCase.java @@ -20,7 +20,6 @@ import java.io.InputStream; import junit.framework.TestCase; - import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.DefaultContext; @@ -30,44 +29,37 @@ * @author Trygve Laugstøl * @author Michal Maczka */ -public abstract class PlexusTestCase - extends TestCase -{ +public abstract class PlexusTestCase extends TestCase { private PlexusContainer container; private static String basedir; - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { basedir = getBasedir(); } @SuppressWarnings("ResultOfMethodCallIgnored") - protected void setupContainer() - { + protected void setupContainer() { // ---------------------------------------------------------------------------- // Context Setup // ---------------------------------------------------------------------------- DefaultContext context = new DefaultContext(); - context.put( "basedir", getBasedir() ); + context.put("basedir", getBasedir()); - customizeContext( context ); + customizeContext(context); - boolean hasPlexusHome = context.contains( "plexus.home" ); + boolean hasPlexusHome = context.contains("plexus.home"); - if ( !hasPlexusHome ) - { - File f = getTestFile( "target/plexus-home" ); + if (!hasPlexusHome) { + File f = getTestFile("target/plexus-home"); - if ( !f.isDirectory() ) - { + if (!f.isDirectory()) { f.mkdir(); } - context.put( "plexus.home", f.getAbsolutePath() ); + context.put("plexus.home", f.getAbsolutePath()); } // ---------------------------------------------------------------------------- @@ -76,31 +68,24 @@ protected void setupContainer() String config = getCustomConfigurationName(); - ContainerConfiguration containerConfiguration = new DefaultContainerConfiguration() - .setName( "test" ) - .setContext( context.getContextData() ); + ContainerConfiguration containerConfiguration = + new DefaultContainerConfiguration().setName("test").setContext(context.getContextData()); - if ( config != null ) - { - containerConfiguration.setContainerConfiguration( config ); - } - else - { - String resource = getConfigurationName( null ); + if (config != null) { + containerConfiguration.setContainerConfiguration(config); + } else { + String resource = getConfigurationName(null); - containerConfiguration.setContainerConfiguration( resource ); + containerConfiguration.setContainerConfiguration(resource); } - customizeContainerConfiguration( containerConfiguration ); + customizeContainerConfiguration(containerConfiguration); - try - { - container = new DefaultPlexusContainer( containerConfiguration ); - } - catch ( PlexusContainerException e ) - { + try { + container = new DefaultPlexusContainer(containerConfiguration); + } catch (PlexusContainerException e) { e.printStackTrace(); - fail( "Failed to create plexus container." ); + fail("Failed to create plexus container."); } } @@ -110,54 +95,39 @@ protected void setupContainer() * * @param containerConfiguration {@link ContainerConfiguration}. */ - protected void customizeContainerConfiguration( ContainerConfiguration containerConfiguration ) - { - } + protected void customizeContainerConfiguration(ContainerConfiguration containerConfiguration) {} - protected void customizeContext( Context context ) - { - } + protected void customizeContext(Context context) {} - protected PlexusConfiguration customizeComponentConfiguration() - { + protected PlexusConfiguration customizeComponentConfiguration() { return null; } - protected void tearDown() - throws Exception - { - if ( container != null ) - { + protected void tearDown() throws Exception { + if (container != null) { container.dispose(); container = null; } } - protected PlexusContainer getContainer() - { - if ( container == null ) - { + protected PlexusContainer getContainer() { + if (container == null) { setupContainer(); } return container; } - protected InputStream getConfiguration() - throws Exception - { - return getConfiguration( null ); + protected InputStream getConfiguration() throws Exception { + return getConfiguration(null); } - protected InputStream getConfiguration( String subname ) - throws Exception - { - return getResourceAsStream( getConfigurationName( subname ) ); + protected InputStream getConfiguration(String subname) throws Exception { + return getResourceAsStream(getConfigurationName(subname)); } - protected String getCustomConfigurationName() - { + protected String getCustomConfigurationName() { return null; } @@ -170,18 +140,15 @@ protected String getCustomConfigurationName() * @param subname the subname * @return A configruation name */ - protected String getConfigurationName( String subname ) - { - return getClass().getName().replace( '.', '/' ) + ".xml"; + protected String getConfigurationName(String subname) { + return getClass().getName().replace('.', '/') + ".xml"; } - protected InputStream getResourceAsStream( String resource ) - { - return getClass().getResourceAsStream( resource ); + protected InputStream getResourceAsStream(String resource) { + return getClass().getResourceAsStream(resource); } - protected ClassLoader getClassLoader() - { + protected ClassLoader getClassLoader() { return getClass().getClassLoader(); } @@ -190,97 +157,74 @@ protected ClassLoader getClassLoader() // ---------------------------------------------------------------------- @SuppressWarnings("unchecked") - protected T lookup( String componentKey ) - throws Exception - { - return (T) getContainer().lookup( componentKey ); + protected T lookup(String componentKey) throws Exception { + return (T) getContainer().lookup(componentKey); } @SuppressWarnings("unchecked") - protected T lookup( String role, - String roleHint ) - throws Exception - { - return (T) getContainer().lookup( role, roleHint ); + protected T lookup(String role, String roleHint) throws Exception { + return (T) getContainer().lookup(role, roleHint); } - protected T lookup( Class componentClass ) - throws Exception - { - return getContainer().lookup( componentClass ); + protected T lookup(Class componentClass) throws Exception { + return getContainer().lookup(componentClass); } - protected T lookup( Class componentClass, String roleHint ) - throws Exception - { - return getContainer().lookup( componentClass, roleHint ); + protected T lookup(Class componentClass, String roleHint) throws Exception { + return getContainer().lookup(componentClass, roleHint); } - protected void release( Object component ) - throws Exception - { - getContainer().release( component ); + protected void release(Object component) throws Exception { + getContainer().release(component); } // ---------------------------------------------------------------------- // Helper methods for sub classes // ---------------------------------------------------------------------- - public static File getTestFile( String path ) - { - return new File( getBasedir(), path ); + public static File getTestFile(String path) { + return new File(getBasedir(), path); } - public static File getTestFile( String basedir, - String path ) - { - File basedirFile = new File( basedir ); + public static File getTestFile(String basedir, String path) { + File basedirFile = new File(basedir); - if ( !basedirFile.isAbsolute() ) - { - basedirFile = getTestFile( basedir ); + if (!basedirFile.isAbsolute()) { + basedirFile = getTestFile(basedir); } - return new File( basedirFile, path ); + return new File(basedirFile, path); } - public static String getTestPath( String path ) - { - return getTestFile( path ).getAbsolutePath(); + public static String getTestPath(String path) { + return getTestFile(path).getAbsolutePath(); } - public static String getTestPath( String basedir, - String path ) - { - return getTestFile( basedir, path ).getAbsolutePath(); + public static String getTestPath(String basedir, String path) { + return getTestFile(basedir, path).getAbsolutePath(); } - public static String getBasedir() - { - if ( basedir != null ) - { + public static String getBasedir() { + if (basedir != null) { return basedir; } - basedir = System.getProperty( "basedir" ); + basedir = System.getProperty("basedir"); - if ( basedir == null ) - { - basedir = new File( "" ).getAbsolutePath(); + if (basedir == null) { + basedir = new File("").getAbsolutePath(); } return basedir; } - public String getTestConfiguration() - { - return getTestConfiguration( getClass() ); + public String getTestConfiguration() { + return getTestConfiguration(getClass()); } - public static String getTestConfiguration( Class clazz ) - { - String s = clazz.getName().replace( '.', '/' ); + public static String getTestConfiguration(Class clazz) { + String s = clazz.getName().replace('.', '/'); - return s.substring( 0, s.indexOf( "$" ) ) + ".xml"; + return s.substring(0, s.indexOf("$")) + ".xml"; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/CastUtils.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/CastUtils.java index 0a3577281..3c57179f4 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/CastUtils.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/CastUtils.java @@ -1,17 +1,17 @@ package org.codehaus.plexus.component; -import org.apache.xbean.recipe.RecipeHelper; - import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.xbean.recipe.RecipeHelper; + @SuppressWarnings({"unchecked", "UnusedDeclaration"}) public final class CastUtils { private CastUtils() { - //utility class, never constructed + // utility class, never constructed } public static Map cast(Map p) { @@ -64,6 +64,6 @@ public static Map.Entry cast(Map.Entry p, Class pc, Class< // todo remove when recipe helper accecpts nulls public static boolean isAssignableFrom(Class expected, Class actual) { - return actual != null && RecipeHelper.isAssignableFrom( expected, actual ); + return actual != null && RecipeHelper.isAssignableFrom(expected, actual); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/MapOrientedComponent.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/MapOrientedComponent.java index 98433533b..aaa108907 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/MapOrientedComponent.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/MapOrientedComponent.java @@ -16,18 +16,15 @@ * limitations under the License. */ -import org.codehaus.plexus.component.configurator.ComponentConfigurationException; -import org.codehaus.plexus.component.repository.ComponentRequirement; - import java.util.Map; -public interface MapOrientedComponent -{ +import org.codehaus.plexus.component.configurator.ComponentConfigurationException; +import org.codehaus.plexus.component.repository.ComponentRequirement; - void addComponentRequirement( ComponentRequirement requirementDescriptor, Object requirementValue ) - throws ComponentConfigurationException; +public interface MapOrientedComponent { - void setComponentConfiguration( Map componentConfiguration ) - throws ComponentConfigurationException; + void addComponentRequirement(ComponentRequirement requirementDescriptor, Object requirementValue) + throws ComponentConfigurationException; + void setComponentConfiguration(Map componentConfiguration) throws ComponentConfigurationException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/AbstractComponentBuildListener.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/AbstractComponentBuildListener.java index c0ee1ff0b..a6ecd66f6 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/AbstractComponentBuildListener.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/AbstractComponentBuildListener.java @@ -15,16 +15,13 @@ */ package org.codehaus.plexus.component.builder; -import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.classworlds.realm.ClassRealm; +import org.codehaus.plexus.component.repository.ComponentDescriptor; public abstract class AbstractComponentBuildListener implements ComponentBuildListener { - public void beforeComponentCreate(ComponentDescriptor componentDescriptor, ClassRealm realm) { - } + public void beforeComponentCreate(ComponentDescriptor componentDescriptor, ClassRealm realm) {} - public void componentCreated(ComponentDescriptor componentDescriptor, Object component, ClassRealm realm) { - } + public void componentCreated(ComponentDescriptor componentDescriptor, Object component, ClassRealm realm) {} - public void componentConfigured(ComponentDescriptor componentDescriptor, Object component, ClassRealm realm) { - } + public void componentConfigured(ComponentDescriptor componentDescriptor, Object component, ClassRealm realm) {} } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/ComponentBuildListener.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/ComponentBuildListener.java index 179597fa9..9ec6e7ee1 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/ComponentBuildListener.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/ComponentBuildListener.java @@ -20,9 +20,9 @@ public interface ComponentBuildListener { - void beforeComponentCreate(ComponentDescriptor componentDescriptor, ClassRealm realm ); + void beforeComponentCreate(ComponentDescriptor componentDescriptor, ClassRealm realm); - void componentCreated(ComponentDescriptor componentDescriptor, Object component, ClassRealm realm ); + void componentCreated(ComponentDescriptor componentDescriptor, Object component, ClassRealm realm); - void componentConfigured(ComponentDescriptor componentDescriptor, Object component, ClassRealm realm ); + void componentConfigured(ComponentDescriptor componentDescriptor, Object component, ClassRealm realm); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/ComponentBuilder.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/ComponentBuilder.java index 4d5dd8eea..99bbdd158 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/ComponentBuilder.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/ComponentBuilder.java @@ -16,13 +16,12 @@ package org.codehaus.plexus.component.builder; import org.codehaus.plexus.classworlds.realm.ClassRealm; +import org.codehaus.plexus.component.factory.ComponentInstantiationException; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; -import org.codehaus.plexus.component.factory.ComponentInstantiationException; public interface ComponentBuilder { T build(ComponentDescriptor descriptor, ClassRealm realm, ComponentBuildListener listener) throws ComponentInstantiationException, ComponentLifecycleException; - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/XBeanComponentBuilder.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/XBeanComponentBuilder.java index 67ed98ebe..950c7986d 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/XBeanComponentBuilder.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/builder/XBeanComponentBuilder.java @@ -15,17 +15,24 @@ */ package org.codehaus.plexus.component.builder; -import static org.apache.xbean.recipe.RecipeHelper.toClass; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import org.apache.xbean.recipe.AbstractRecipe; import org.apache.xbean.recipe.ConstructionException; import org.apache.xbean.recipe.ObjectRecipe; import org.apache.xbean.recipe.Option; import org.apache.xbean.recipe.RecipeHelper; +import org.codehaus.plexus.ComponentRegistry; import org.codehaus.plexus.MutablePlexusContainer; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.ComponentRegistry; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.MapOrientedComponent; import org.codehaus.plexus.component.collections.ComponentList; @@ -54,29 +61,19 @@ import org.codehaus.plexus.personality.plexus.lifecycle.phase.PhaseExecutionException; import org.codehaus.plexus.util.StringUtils; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.LinkedHashSet; +import static org.apache.xbean.recipe.RecipeHelper.toClass; public class XBeanComponentBuilder implements ComponentBuilder { private static final ThreadLocal>> STACK = - new ThreadLocal>>() - { - protected LinkedHashSet> initialValue() - { - return new LinkedHashSet>(); - } - }; + new ThreadLocal>>() { + protected LinkedHashSet> initialValue() { + return new LinkedHashSet>(); + } + }; private ComponentManager componentManager; - public XBeanComponentBuilder() { - } + public XBeanComponentBuilder() {} public XBeanComponentBuilder(ComponentManager componentManager) { setComponentManager(componentManager); @@ -94,28 +91,24 @@ protected MutablePlexusContainer getContainer() { return componentManager.getContainer(); } - public T build( ComponentDescriptor descriptor, ClassRealm realm, ComponentBuildListener listener ) - throws ComponentInstantiationException, ComponentLifecycleException - { + public T build(ComponentDescriptor descriptor, ClassRealm realm, ComponentBuildListener listener) + throws ComponentInstantiationException, ComponentLifecycleException { LinkedHashSet> stack = STACK.get(); - if ( stack.contains( descriptor ) ) - { + if (stack.contains(descriptor)) { // create list of circularity - List> circularity = new ArrayList>( stack ); - circularity.subList( circularity.indexOf( descriptor ), circularity.size() ); - circularity.add( descriptor ); + List> circularity = new ArrayList>(stack); + circularity.subList(circularity.indexOf(descriptor), circularity.size()); + circularity.add(descriptor); // nice circularity message String message = "Creation circularity: "; - for ( ComponentDescriptor componentDescriptor : circularity ) - { + for (ComponentDescriptor componentDescriptor : circularity) { message += "\n\t[" + componentDescriptor.getRole() + ", " + componentDescriptor.getRoleHint() + "]"; } - throw new ComponentInstantiationException( message ); + throw new ComponentInstantiationException(message); } - stack.add( descriptor ); - try - { + stack.add(descriptor); + try { if (listener != null) { listener.beforeComponentCreate(descriptor, realm); } @@ -133,14 +126,13 @@ public T build( ComponentDescriptor descriptor, ClassRealm realm, ComponentBu } return component; - } - finally - { - stack.remove( descriptor ); + } finally { + stack.remove(descriptor); } } - protected T createComponentInstance(ComponentDescriptor descriptor, ClassRealm realm) throws ComponentInstantiationException, ComponentLifecycleException { + protected T createComponentInstance(ComponentDescriptor descriptor, ClassRealm realm) + throws ComponentInstantiationException, ComponentLifecycleException { MutablePlexusContainer container = getContainer(); if (realm == null) { realm = descriptor.getRealm(); @@ -152,73 +144,73 @@ protected T createComponentInstance(ComponentDescriptor descriptor, ClassReal ObjectRecipe recipe; T instance; - ComponentFactory componentFactory = container.getComponentFactoryManager().findComponentFactory(descriptor.getComponentFactory()); + ComponentFactory componentFactory = + container.getComponentFactoryManager().findComponentFactory(descriptor.getComponentFactory()); if (JavaComponentFactory.class.equals(componentFactory.getClass())) { // xbean-reflect will create object and do injection - recipe = createObjectRecipe( null, descriptor, realm ); + recipe = createObjectRecipe(null, descriptor, realm); instance = (T) recipe.create(); } else { // todo figure out how to easily let xbean use the factory to construct the component // use object factory to construct component and then inject into that object instance = (T) componentFactory.newInstance(descriptor, realm, container); - recipe = createObjectRecipe( instance, descriptor, realm ); - recipe.setProperties( instance ); + recipe = createObjectRecipe(instance, descriptor, realm); + recipe.setProperties(instance); } // todo figure out how to easily let xbean do this map oriented stuff (if it is actually used in plexus) - if ( instance instanceof MapOrientedComponent) { + if (instance instanceof MapOrientedComponent) { MapOrientedComponent mapOrientedComponent = (MapOrientedComponent) instance; processMapOrientedComponent(descriptor, mapOrientedComponent, realm); } return instance; } catch (Exception e) { - throw new ComponentLifecycleException("Error constructing component " + descriptor.getHumanReadableKey(), e); + throw new ComponentLifecycleException( + "Error constructing component " + descriptor.getHumanReadableKey(), e); } catch (LinkageError e) { - throw new ComponentLifecycleException("Error constructing component " + descriptor.getHumanReadableKey(), e); + throw new ComponentLifecycleException( + "Error constructing component " + descriptor.getHumanReadableKey(), e); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } } - public ObjectRecipe createObjectRecipe(T instance, ComponentDescriptor descriptor, ClassRealm realm) throws ComponentInstantiationException, PlexusConfigurationException { + public ObjectRecipe createObjectRecipe(T instance, ComponentDescriptor descriptor, ClassRealm realm) + throws ComponentInstantiationException, PlexusConfigurationException { String factoryMethod = null; String[] constructorArgNames = null; Class[] constructorArgTypes = null; - Class implClass = ( instance != null ) ? instance.getClass() : descriptor.getImplementationClass(); + Class implClass = (instance != null) ? instance.getClass() : descriptor.getImplementationClass(); - if ( implClass == null || implClass == Object.class ) - { + if (implClass == null || implClass == Object.class) { // if the descriptor could not load the class, it's time to report this up to the caller now - try - { - realm.loadClass( descriptor.getImplementation() ); - } - catch ( ClassNotFoundException e ) - { - throw new ComponentInstantiationException( "Could not load implementation class for component " - + descriptor.getHumanReadableKey() + " from class realm " + realm, e ); - } - catch ( LinkageError e ) - { - throw new ComponentInstantiationException( "Could not load implementation class for component " - + descriptor.getHumanReadableKey() + " from class realm " + realm, e ); + try { + realm.loadClass(descriptor.getImplementation()); + } catch (ClassNotFoundException e) { + throw new ComponentInstantiationException( + "Could not load implementation class for component " + descriptor.getHumanReadableKey() + + " from class realm " + realm, + e); + } catch (LinkageError e) { + throw new ComponentInstantiationException( + "Could not load implementation class for component " + descriptor.getHumanReadableKey() + + " from class realm " + realm, + e); } } - ObjectRecipe recipe = new ObjectRecipe( implClass, - factoryMethod, - constructorArgNames, - constructorArgTypes); + ObjectRecipe recipe = new ObjectRecipe(implClass, factoryMethod, constructorArgNames, constructorArgTypes); recipe.allow(Option.FIELD_INJECTION); recipe.allow(Option.PRIVATE_PROPERTIES); // MapOrientedComponents don't get normal injection - if (!MapOrientedComponent.class.isAssignableFrom( implClass )) { - for (ComponentRequirement requirement : descriptor.getRequirements() ) { + if (!MapOrientedComponent.class.isAssignableFrom(implClass)) { + for (ComponentRequirement requirement : descriptor.getRequirements()) { String name = requirement.getFieldName(); - RequirementRecipe requirementRecipe = new RequirementRecipe(descriptor, requirement, getContainer(), name == null); + RequirementRecipe requirementRecipe = + new RequirementRecipe(descriptor, requirement, getContainer(), name == null); if (name != null) { recipe.setProperty(name, requirementRecipe); @@ -228,7 +220,7 @@ public ObjectRecipe createObjectRecipe(T instance, ComponentDescriptor descri } // add configuration data - if (shouldConfigure(descriptor )) { + if (shouldConfigure(descriptor)) { PlexusConfiguration configuration = descriptor.getConfiguration(); if (configuration != null) { for (String name : configuration.getAttributeNames()) { @@ -244,13 +236,10 @@ public ObjectRecipe createObjectRecipe(T instance, ComponentDescriptor descri for (PlexusConfiguration child : configuration.getChildren()) { String name = child.getName(); name = fromXML(name); - if ( StringUtils.isNotEmpty( child.getValue( null ) ) ) - { - recipe.setProperty( name, child.getValue() ); - } - else - { - recipe.setProperty( name, new PlexusConfigurationRecipe( child ) ); + if (StringUtils.isNotEmpty(child.getValue(null))) { + recipe.setProperty(name, child.getValue()); + } else { + recipe.setProperty(name, new PlexusConfigurationRecipe(child)); } } } @@ -259,7 +248,7 @@ public ObjectRecipe createObjectRecipe(T instance, ComponentDescriptor descri return recipe; } - protected boolean shouldConfigure( ComponentDescriptor descriptor ) { + protected boolean shouldConfigure(ComponentDescriptor descriptor) { String configuratorId = descriptor.getComponentConfigurator(); if (StringUtils.isEmpty(configuratorId)) { @@ -267,13 +256,16 @@ protected boolean shouldConfigure( ComponentDescriptor descriptor ) { } try { - ComponentConfigurator componentConfigurator = getContainer().lookup(ComponentConfigurator.class, configuratorId); - return componentConfigurator == null || componentConfigurator.getClass().equals(BasicComponentConfigurator.class); + ComponentConfigurator componentConfigurator = + getContainer().lookup(ComponentConfigurator.class, configuratorId); + return componentConfigurator == null + || componentConfigurator.getClass().equals(BasicComponentConfigurator.class); } catch (ComponentLookupException e) { } return true; } + protected String fromXML(String elementName) { return StringUtils.lowercaseFirstLetter(StringUtils.removeAndHump(elementName, "-")); } @@ -292,7 +284,11 @@ public static class RequirementRecipe extends AbstractRecipe { private MutablePlexusContainer container; private boolean autoMatch; - public RequirementRecipe(ComponentDescriptor componentDescriptor, ComponentRequirement requirement, MutablePlexusContainer container, boolean autoMatch) { + public RequirementRecipe( + ComponentDescriptor componentDescriptor, + ComponentRequirement requirement, + MutablePlexusContainer container, + boolean autoMatch) { this.componentDescriptor = componentDescriptor; this.requirement = requirement; this.container = container; @@ -300,15 +296,17 @@ public RequirementRecipe(ComponentDescriptor componentDescriptor, ComponentRe } public boolean canCreate(Type expectedType) { - if (!autoMatch) - { + if (!autoMatch) { return true; } Class propertyType = toClass(expectedType); // Never auto match array, map or collection - if (propertyType.isArray() || Map.class.isAssignableFrom(propertyType) || Collection.class.isAssignableFrom(propertyType) || requirement instanceof ComponentRequirementList) { + if (propertyType.isArray() + || Map.class.isAssignableFrom(propertyType) + || Collection.class.isAssignableFrom(propertyType) + || requirement instanceof ComponentRequirementList) { return false; } @@ -316,7 +314,9 @@ public boolean canCreate(Type expectedType) { try { ComponentRegistry componentRegistry = container.getComponentRegistry(); - return componentRegistry.getComponentDescriptor(propertyType, requirement.getRole(), requirement.getRoleHint()) != null; + return componentRegistry.getComponentDescriptor( + propertyType, requirement.getRole(), requirement.getRoleHint()) + != null; } catch (Exception e) { } @@ -360,7 +360,8 @@ protected Object internalCreate(Type expectedType, boolean lazyRefAllowed) throw // todo verify key type is String - assignment = new ComponentMap(container, + assignment = new ComponentMap( + container, toClass(valueType), role, roleHints, @@ -374,12 +375,15 @@ else if (List.class.equals(propertyType)) { // get component type Type[] typeParameters = RecipeHelper.getTypeParameters(Collection.class, expectedType); Type componentType = Object.class; - if (typeParameters != null && typeParameters.length == 1 && typeParameters[0] instanceof Class) { + if (typeParameters != null + && typeParameters.length == 1 + && typeParameters[0] instanceof Class) { componentType = typeParameters[0]; } - assignment = new ComponentList(container, - toClass( componentType ), + assignment = new ComponentList( + container, + toClass(componentType), role, roleHints, componentDescriptor.getHumanReadableKey()); @@ -405,20 +409,23 @@ else if (Set.class.equals(propertyType) || Collection.class.isAssignableFrom(pro return assignment; } catch (ComponentLookupException e) { - if ( requirement.isOptional() ) - { + if (requirement.isOptional()) { return null; } - throw new ConstructionException("Composition failed of field " + requirement.getFieldName() + " " - + "in object of type " + componentDescriptor.getImplementation() + " because the requirement " - + requirement + " was missing)", e); + throw new ConstructionException( + "Composition failed of field " + requirement.getFieldName() + " " + + "in object of type " + componentDescriptor.getImplementation() + + " because the requirement " + + requirement + " was missing)", + e); } } @Override public String toString() { - return "RequirementRecipe[fieldName=" + requirement.getFieldName() + ", role=" + componentDescriptor.getRole() + "]"; + return "RequirementRecipe[fieldName=" + requirement.getFieldName() + ", role=" + + componentDescriptor.getRole() + "]"; } } @@ -449,23 +456,31 @@ protected Object internalCreate(Type expectedType, boolean lazyRefAllowed) throw ObjectRecipe caller = (ObjectRecipe) RecipeHelper.getCaller(); Class parentClass = toClass(caller.getType()); - Object value = converter.fromConfiguration(lookup, child, toClass(expectedType), parentClass, Thread.currentThread().getContextClassLoader(), new DefaultExpressionEvaluator()); + Object value = converter.fromConfiguration( + lookup, + child, + toClass(expectedType), + parentClass, + Thread.currentThread().getContextClassLoader(), + new DefaultExpressionEvaluator()); return value; } catch (ComponentConfigurationException e) { - throw new ConstructionException("Unable to convert configuration for property " + child.getName() + " to " + toClass(expectedType).getName()); + throw new ConstructionException("Unable to convert configuration for property " + child.getName() + + " to " + toClass(expectedType).getName()); } } private ConverterLookup createConverterLookup() { ClassRealm realm = (ClassRealm) Thread.currentThread().getContextClassLoader(); ConverterLookup lookup = new DefaultConverterLookup(); - lookup.registerConverter( new ClassRealmConverter(realm) ); + lookup.registerConverter(new ClassRealmConverter(realm)); return lookup; } } - - private void processMapOrientedComponent(ComponentDescriptor descriptor, MapOrientedComponent mapOrientedComponent, ClassRealm realm) throws ComponentConfigurationException, ComponentLookupException { + private void processMapOrientedComponent( + ComponentDescriptor descriptor, MapOrientedComponent mapOrientedComponent, ClassRealm realm) + throws ComponentConfigurationException, ComponentLookupException { MutablePlexusContainer container = getContainer(); for (ComponentRequirement requirement : descriptor.getRequirements()) { @@ -495,19 +510,13 @@ private void processMapOrientedComponent(ComponentDescriptor descriptor, MapO MapConverter converter = new MapConverter(); ConverterLookup converterLookup = new DefaultConverterLookup(); DefaultExpressionEvaluator expressionEvaluator = new DefaultExpressionEvaluator(); - PlexusConfiguration configuration = container.getConfigurationSource().getConfiguration( descriptor ); - - if ( configuration != null ) - { - Map context = (Map) converter.fromConfiguration(converterLookup, - configuration, - null, - null, - realm, - expressionEvaluator, - null ); - - mapOrientedComponent.setComponentConfiguration( context ); + PlexusConfiguration configuration = container.getConfigurationSource().getConfiguration(descriptor); + + if (configuration != null) { + Map context = (Map) converter.fromConfiguration( + converterLookup, configuration, null, null, realm, expressionEvaluator, null); + + mapOrientedComponent.setComponentConfiguration(context); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/collections/AbstractComponentCollection.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/collections/AbstractComponentCollection.java index ee058a986..bd1bd0593 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/collections/AbstractComponentCollection.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/collections/AbstractComponentCollection.java @@ -1,5 +1,11 @@ package org.codehaus.plexus.component.collections; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + import org.codehaus.plexus.MutablePlexusContainer; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; @@ -7,12 +13,6 @@ import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.logging.Logger; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - /* * Copyright 2001-2006 Codehaus Foundation. * @@ -39,8 +39,7 @@ // NOTE: This includes component additions, but also component purges from the // container, as when a component realm is disposed // (and PlexusContainer.removeComponentRealm(..) is called). -public abstract class AbstractComponentCollection -{ +public abstract class AbstractComponentCollection { /** The reference to the PlexusContainer */ protected MutablePlexusContainer container; @@ -65,12 +64,12 @@ public abstract class AbstractComponentCollection private Map> componentDescriptorMap; private final ClassWorld world; - public AbstractComponentCollection( final MutablePlexusContainer container, - final Class componentType, - final String role, - final List roleHints, - final String hostComponent ) - { + public AbstractComponentCollection( + final MutablePlexusContainer container, + final Class componentType, + final String role, + final List roleHints, + final String hostComponent) { this.container = container; this.componentType = componentType; @@ -81,65 +80,53 @@ public AbstractComponentCollection( final MutablePlexusContainer container, this.hostComponent = hostComponent; - logger = container.getLoggerManager().getLoggerForComponent( role ); + logger = container.getLoggerManager().getLoggerForComponent(role); world = container.getContainerRealm().getWorld(); } - private boolean realmsHaveChanged() - { - return ( tccl != Thread.currentThread().getContextClassLoader() ) || - ( realms == null ) || ( !realms.equals( world.getRealms() ) ); + private boolean realmsHaveChanged() { + return (tccl != Thread.currentThread().getContextClassLoader()) + || (realms == null) + || (!realms.equals(world.getRealms())); } - protected synchronized Map> getComponentDescriptorMap() - { + protected synchronized Map> getComponentDescriptorMap() { checkUpdate(); return componentDescriptorMap; } - @SuppressWarnings( "unchecked" ) - protected boolean checkUpdate() - { - if ( componentDescriptorMap != null && !realmsHaveChanged() ) - { + @SuppressWarnings("unchecked") + protected boolean checkUpdate() { + if (componentDescriptorMap != null && !realmsHaveChanged()) { return false; } tccl = Thread.currentThread().getContextClassLoader(); Collection fromWorld = world.getRealms(); - if ( fromWorld == null || fromWorld.isEmpty() ) - { + if (fromWorld == null || fromWorld.isEmpty()) { realms = null; - } - else - { - realms = new HashSet( fromWorld ); + } else { + realms = new HashSet(fromWorld); } - Map> componentMap = container.getComponentDescriptorMap( componentType, role ); + Map> componentMap = container.getComponentDescriptorMap(componentType, role); Map> newComponentDescriptors = - new HashMap>( componentMap.size() * 2 ); - - if ( roleHints != null && !roleHints.isEmpty() ) - { - for ( String roleHint : roleHints ) - { - ComponentDescriptor componentDescriptor = componentMap.get( roleHint ); - if ( componentDescriptor != null ) - { - newComponentDescriptors.put( roleHint, componentDescriptor ); + new HashMap>(componentMap.size() * 2); + + if (roleHints != null && !roleHints.isEmpty()) { + for (String roleHint : roleHints) { + ComponentDescriptor componentDescriptor = componentMap.get(roleHint); + if (componentDescriptor != null) { + newComponentDescriptors.put(roleHint, componentDescriptor); } } - } - else - { - newComponentDescriptors.putAll( componentMap ); + } else { + newComponentDescriptors.putAll(componentMap); } - if ( componentDescriptorMap == null || !newComponentDescriptors.equals( componentDescriptorMap ) ) - { + if (componentDescriptorMap == null || !newComponentDescriptors.equals(componentDescriptorMap)) { componentDescriptorMap = newComponentDescriptors; return true; @@ -148,28 +135,24 @@ protected boolean checkUpdate() return false; } - protected T lookup( ComponentDescriptor componentDescriptor ) - { + protected T lookup(ComponentDescriptor componentDescriptor) { T component = null; - try - { - if ( componentDescriptor != null ) - { - component = container.lookup( componentDescriptor ); + try { + if (componentDescriptor != null) { + component = container.lookup(componentDescriptor); } - } - catch ( ComponentLookupException e ) - { - logger.debug( "Failed to lookup a member of active collection with role: " + role + " and role-hint: " - + componentDescriptor.getRoleHint(), e ); + } catch (ComponentLookupException e) { + logger.debug( + "Failed to lookup a member of active collection with role: " + role + " and role-hint: " + + componentDescriptor.getRoleHint(), + e); } return component; } - public synchronized void clear() - { + public synchronized void clear() { releaseAllCallback(); componentDescriptorMap = null; @@ -179,5 +162,4 @@ public synchronized void clear() } protected abstract void releaseAllCallback(); - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/collections/ComponentList.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/collections/ComponentList.java index 419651711..6db2e8ea4 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/collections/ComponentList.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/collections/ComponentList.java @@ -16,10 +16,6 @@ * limitations under the License. */ -import org.codehaus.plexus.MutablePlexusContainer; -import org.codehaus.plexus.component.repository.ComponentDescriptor; -import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; - import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; @@ -28,53 +24,51 @@ import java.util.Map; import java.util.Map.Entry; +import org.codehaus.plexus.MutablePlexusContainer; +import org.codehaus.plexus.component.repository.ComponentDescriptor; +import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; + /** * @author Jason van Zyl FIXME: [jdcasey] We need to review the efficiency (in speed and memory) of this collection... */ -public class ComponentList - extends AbstractComponentCollection - implements List -{ +public class ComponentList extends AbstractComponentCollection implements List { private List components; - public ComponentList( MutablePlexusContainer container, Class type, String role, List roleHints, String hostComponent ) - { - super( container, type, role, roleHints, hostComponent ); + public ComponentList( + MutablePlexusContainer container, + Class type, + String role, + List roleHints, + String hostComponent) { + super(container, type, role, roleHints, hostComponent); } - public int size() - { + public int size() { return getComponentDescriptorMap().size(); } - public boolean isEmpty() - { + public boolean isEmpty() { return getComponentDescriptorMap().isEmpty(); } - public boolean contains( Object object ) - { - return getList().contains( object ); + public boolean contains(Object object) { + return getList().contains(object); } - public Iterator iterator() - { + public Iterator iterator() { return getList().iterator(); } - public Object[] toArray() - { + public Object[] toArray() { return getList().toArray(); } - public X[] toArray( X[] ts ) - { - return getList().toArray( ts ); + public X[] toArray(X[] ts) { + return getList().toArray(ts); } - public synchronized boolean add( T object ) - { - getList().add( object ); + public synchronized boolean add(T object) { + getList().add(object); /* * PLX-352 This is strictly to support the hack in the Ant Run plugin that tries to poke in a custom converter. @@ -86,143 +80,115 @@ public synchronized boolean add( T object ) return true; } - public boolean remove( Object object ) - { - throw new UnsupportedOperationException( "You cannot modify this list. This list is a requirement of " - + hostComponent + " and managed by the container." ); + public boolean remove(Object object) { + throw new UnsupportedOperationException("You cannot modify this list. This list is a requirement of " + + hostComponent + " and managed by the container."); } - public boolean containsAll( Collection collection ) - { - return getList().containsAll( collection ); + public boolean containsAll(Collection collection) { + return getList().containsAll(collection); } - public boolean addAll( Collection collection ) - { - throw new UnsupportedOperationException( "You cannot modify this list. This list is a requirement of " - + hostComponent + " and managed by the container." ); + public boolean addAll(Collection collection) { + throw new UnsupportedOperationException("You cannot modify this list. This list is a requirement of " + + hostComponent + " and managed by the container."); } - public boolean addAll( int i, Collection collection ) - { - throw new UnsupportedOperationException( "You cannot modify this list. This list is a requirement of " - + hostComponent + " and managed by the container." ); + public boolean addAll(int i, Collection collection) { + throw new UnsupportedOperationException("You cannot modify this list. This list is a requirement of " + + hostComponent + " and managed by the container."); } - public synchronized boolean removeAll( Collection collection ) - { - return getList().removeAll( collection ); + public synchronized boolean removeAll(Collection collection) { + return getList().removeAll(collection); } - public synchronized boolean retainAll( Collection collection ) - { - return getList().retainAll( collection ); + public synchronized boolean retainAll(Collection collection) { + return getList().retainAll(collection); } - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( !( o instanceof List ) ) - { + if (!(o instanceof List)) { return false; } List other = (List) o; - return getList().equals( other ); + return getList().equals(other); } - public int hashCode() - { + public int hashCode() { return getList().hashCode(); } - public T get( int i ) - { - return getList().get( i ); + public T get(int i) { + return getList().get(i); } - public T set( int i, T object ) - { - throw new UnsupportedOperationException( "You cannot modify this list. This list is a requirement of " - + hostComponent + " and managed by the container." ); + public T set(int i, T object) { + throw new UnsupportedOperationException("You cannot modify this list. This list is a requirement of " + + hostComponent + " and managed by the container."); } - public void add( int i, T object ) - { - throw new UnsupportedOperationException( "You cannot modify this list. This list is a requirement of " - + hostComponent + " and managed by the container." ); + public void add(int i, T object) { + throw new UnsupportedOperationException("You cannot modify this list. This list is a requirement of " + + hostComponent + " and managed by the container."); } - public T remove( int i ) - { - throw new UnsupportedOperationException( "You cannot modify this list. This list is a requirement of " - + hostComponent + " and managed by the container." ); + public T remove(int i) { + throw new UnsupportedOperationException("You cannot modify this list. This list is a requirement of " + + hostComponent + " and managed by the container."); } - public int indexOf( Object object ) - { - return getList().indexOf( object ); + public int indexOf(Object object) { + return getList().indexOf(object); } - public int lastIndexOf( Object object ) - { - return getList().lastIndexOf( object ); + public int lastIndexOf(Object object) { + return getList().lastIndexOf(object); } - public ListIterator listIterator() - { + public ListIterator listIterator() { return getList().listIterator(); } - public ListIterator listIterator( int index ) - { - return getList().listIterator( index ); + public ListIterator listIterator(int index) { + return getList().listIterator(index); } - public List subList( int fromIndex, int toIndex ) - { - return getList().subList( fromIndex, toIndex ); + public List subList(int fromIndex, int toIndex) { + return getList().subList(fromIndex, toIndex); } - private synchronized List getList() - { + private synchronized List getList() { // NOTE: If we cache the component map, we have a problem with releasing any of the // components in this map...we need to be able to release them all. - if ( ( components == null ) || checkUpdate() ) - { + if ((components == null) || checkUpdate()) { List componentList = new ArrayList(); Map> descriptorMap = getComponentDescriptorMap(); - if ( roleHints != null ) - { + if (roleHints != null) { // we must follow the order in roleHints - for ( String roleHint : roleHints ) - { - ComponentDescriptor componentDescriptor = descriptorMap.get( roleHint ); + for (String roleHint : roleHints) { + ComponentDescriptor componentDescriptor = descriptorMap.get(roleHint); - T component = lookup( componentDescriptor ); + T component = lookup(componentDescriptor); - if ( component != null ) - { - componentList.add( component ); + if (component != null) { + componentList.add(component); } } - } - else - { - for ( Entry> entry : descriptorMap.entrySet() ) - { + } else { + for (Entry> entry : descriptorMap.entrySet()) { ComponentDescriptor componentDescriptor = entry.getValue(); - T component = lookup( componentDescriptor ); + T component = lookup(componentDescriptor); - if ( component != null ) - { - componentList.add( component ); + if (component != null) { + componentList.add(component); } } } @@ -233,10 +199,8 @@ private synchronized List getList() } @Override - protected boolean checkUpdate() - { - if ( super.checkUpdate() ) - { + protected boolean checkUpdate() { + if (super.checkUpdate()) { components = null; return true; @@ -245,17 +209,12 @@ protected boolean checkUpdate() return false; } - protected void releaseAllCallback() - { - if ( components != null ) - { - try - { - container.releaseAll( components ); - } - catch ( ComponentLifecycleException e ) - { - logger.debug( "Error releasing components in active collection: " + e.getMessage(), e ); + protected void releaseAllCallback() { + if (components != null) { + try { + container.releaseAll(components); + } catch (ComponentLifecycleException e) { + logger.debug("Error releasing components in active collection: " + e.getMessage(), e); } components = null; diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/collections/ComponentMap.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/collections/ComponentMap.java index ddf3e4f3b..740a4f5f2 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/collections/ComponentMap.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/collections/ComponentMap.java @@ -16,179 +16,152 @@ * limitations under the License. */ -import org.codehaus.plexus.MutablePlexusContainer; -import org.codehaus.plexus.component.repository.ComponentDescriptor; -import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; - import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; +import org.codehaus.plexus.MutablePlexusContainer; +import org.codehaus.plexus.component.repository.ComponentDescriptor; +import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; + /** * @author Jason van Zyl FIXME: [jdcasey] We need to review the efficiency (in speed and memory) of this collection... */ -public class ComponentMap - extends AbstractComponentCollection - implements Map -{ +public class ComponentMap extends AbstractComponentCollection implements Map { private Map components; private Map customAdditions = new LinkedHashMap(); - public ComponentMap( MutablePlexusContainer container, Class type, String role, List roleHints, String hostComponent ) - { - super( container, type, role, roleHints, hostComponent ); + public ComponentMap( + MutablePlexusContainer container, + Class type, + String role, + List roleHints, + String hostComponent) { + super(container, type, role, roleHints, hostComponent); } - public int size() - { + public int size() { return getComponentDescriptorMap().size(); } - public boolean isEmpty() - { + public boolean isEmpty() { return getComponentDescriptorMap().isEmpty(); } - public boolean containsKey( Object key ) - { - return getComponentDescriptorMap().containsKey( key ); + public boolean containsKey(Object key) { + return getComponentDescriptorMap().containsKey(key); } - public boolean containsValue( Object value ) - { - return getMap().containsValue( value ); + public boolean containsValue(Object value) { + return getMap().containsValue(value); } - public T get( Object k ) - { - return getMap().get( k ); + public T get(Object k) { + return getMap().get(k); } - public synchronized T put( String key, T value ) - { - logger.warn( "Custom " - + role - + " implementations should NOT be added directly to this Map. Instead, add them as Plexus components." ); + public synchronized T put(String key, T value) { + logger.warn("Custom " + + role + + " implementations should NOT be added directly to this Map. Instead, add them as Plexus components."); - T prev = customAdditions.put( key, value ); - if ( prev == null ) - { - prev = getComponentMap().get( key ); + T prev = customAdditions.put(key, value); + if (prev == null) { + prev = getComponentMap().get(key); } return prev; } - public synchronized void putAll( Map map ) - { - logger.warn( "Custom " - + role - + " implementations should NOT be added directly to this Map. Instead, add them as Plexus components." ); + public synchronized void putAll(Map map) { + logger.warn("Custom " + + role + + " implementations should NOT be added directly to this Map. Instead, add them as Plexus components."); - customAdditions.putAll( map ); + customAdditions.putAll(map); } - public Set keySet() - { + public Set keySet() { return getMap().keySet(); } - public Collection values() - { + public Collection values() { return getMap().values(); } - public Set> entrySet() - { + public Set> entrySet() { return getMap().entrySet(); } - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( !( o instanceof Map ) ) - { + if (!(o instanceof Map)) { return false; } - Map object = (Map) o; - return getMap().equals( object ); + Map object = (Map) o; + return getMap().equals(object); } - public int hashCode() - { + public int hashCode() { return getMap().hashCode(); } - public synchronized T remove( Object key ) - { - logger.warn( "Items in this Map should NOT be removed directly. If the matching entry is a component, it will NOT be removed." ); + public synchronized T remove(Object key) { + logger.warn( + "Items in this Map should NOT be removed directly. If the matching entry is a component, it will NOT be removed."); - if ( key instanceof String ) - { - if ( customAdditions.containsKey( key ) ) - { - return customAdditions.remove( key ); + if (key instanceof String) { + if (customAdditions.containsKey(key)) { + return customAdditions.remove(key); } } return null; } - private synchronized Map getMap() - { + private synchronized Map getMap() { Map result = getComponentMap(); - if ( !customAdditions.isEmpty() ) - { - result.putAll( customAdditions ); + if (!customAdditions.isEmpty()) { + result.putAll(customAdditions); } return result; } - private synchronized Map getComponentMap() - { - if ( ( components == null ) || checkUpdate() ) - { + private synchronized Map getComponentMap() { + if ((components == null) || checkUpdate()) { Map componentMap = new LinkedHashMap(); Map> descriptorMap = getComponentDescriptorMap(); - if ( roleHints != null ) - { + if (roleHints != null) { // we must follow the order given in roleHints - for ( String roleHint : roleHints ) - { - ComponentDescriptor componentDescriptor = descriptorMap.get( roleHint ); + for (String roleHint : roleHints) { + ComponentDescriptor componentDescriptor = descriptorMap.get(roleHint); - T component = lookup( componentDescriptor ); + T component = lookup(componentDescriptor); - if ( component != null ) - { - componentMap.put( roleHint, component ); + if (component != null) { + componentMap.put(roleHint, component); } } - } - else - { - for ( Entry> entry : descriptorMap.entrySet() ) - { + } else { + for (Entry> entry : descriptorMap.entrySet()) { String roleHint = entry.getKey(); ComponentDescriptor componentDescriptor = entry.getValue(); - T component = lookup( componentDescriptor ); + T component = lookup(componentDescriptor); - if ( component != null ) - { - componentMap.put( roleHint, component ); + if (component != null) { + componentMap.put(roleHint, component); } } } @@ -199,10 +172,8 @@ private synchronized Map getComponentMap() } @Override - protected boolean checkUpdate() - { - if ( super.checkUpdate() ) - { + protected boolean checkUpdate() { + if (super.checkUpdate()) { components = null; return true; @@ -211,21 +182,15 @@ protected boolean checkUpdate() return false; } - protected void releaseAllCallback() - { - if ( components != null ) - { - try - { - container.releaseAll( components ); - } - catch ( ComponentLifecycleException e ) - { - logger.debug( "Error releasing components in active collection: " + e.getMessage(), e ); + protected void releaseAllCallback() { + if (components != null) { + try { + container.releaseAll(components); + } catch (ComponentLifecycleException e) { + logger.debug("Error releasing components in active collection: " + e.getMessage(), e); } components = null; } } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/CompositionResolver.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/CompositionResolver.java index 0dbf1efc7..bea3da55f 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/CompositionResolver.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/CompositionResolver.java @@ -16,24 +16,23 @@ * limitations under the License. */ -import org.codehaus.plexus.component.repository.ComponentDescriptor; - import java.util.List; +import org.codehaus.plexus.component.repository.ComponentDescriptor; + /** * @author Jason van Zyl * @author Michal Maczka */ -public interface CompositionResolver -{ +public interface CompositionResolver { public static final char SEPARATOR_CHAR = ':'; /** * @param componentDescriptor {@link ComponentDescriptor}. * @throws CycleDetectedInComponentGraphException when cycle is detected */ - void addComponentDescriptor( ComponentDescriptor componentDescriptor ) - throws CycleDetectedInComponentGraphException; + void addComponentDescriptor(ComponentDescriptor componentDescriptor) + throws CycleDetectedInComponentGraphException; /** * Returns the list of names of components which are required @@ -44,8 +43,7 @@ void addComponentDescriptor( ComponentDescriptor componentDescriptor ) * @param roleHint The implementation hint of the component * @return The list of components which are required by given component */ - List getRequirements( String role, String roleHint ); - + List getRequirements(String role, String roleHint); /** * Returns the list of names of components which are using the component. @@ -56,7 +54,5 @@ void addComponentDescriptor( ComponentDescriptor componentDescriptor ) * @param roleHint The implementation hint of the component * @return The list of components which are requiring given component */ - List findRequirements( String role, String roleHint ); - - + List findRequirements(String role, String roleHint); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/CycleDetectedInComponentGraphException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/CycleDetectedInComponentGraphException.java index 1ff989e7c..f2398fdc7 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/CycleDetectedInComponentGraphException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/CycleDetectedInComponentGraphException.java @@ -18,13 +18,11 @@ /** * Thrown when component composition goes awry. - * - * @author Jason van Zyl + * + * @author Jason van Zyl * @author Michal Maczka */ -public class CycleDetectedInComponentGraphException - extends Exception -{ +public class CycleDetectedInComponentGraphException extends Exception { private static final long serialVersionUID = -5587124702588800322L; /** @@ -32,9 +30,8 @@ public class CycleDetectedInComponentGraphException * * @param message The detail message for this exception. */ - public CycleDetectedInComponentGraphException( String message ) - { - super( message ); + public CycleDetectedInComponentGraphException(String message) { + super(message); } /** @@ -43,8 +40,7 @@ public CycleDetectedInComponentGraphException( String message ) * @param message The detail message for this exception. * @param throwable the root cause of the exception */ - public CycleDetectedInComponentGraphException( String message, Throwable throwable ) - { - super( message, throwable ); + public CycleDetectedInComponentGraphException(String message, Throwable throwable) { + super(message, throwable); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/DefaultCompositionResolver.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/DefaultCompositionResolver.java index abd2d4763..9ed986ebd 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/DefaultCompositionResolver.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/DefaultCompositionResolver.java @@ -26,42 +26,30 @@ import org.codehaus.plexus.util.dag.CycleDetectedException; import org.codehaus.plexus.util.dag.DAG; - /** * @author Jason van Zyl * @author Michal Maczka */ -public class DefaultCompositionResolver - implements CompositionResolver -{ +public class DefaultCompositionResolver implements CompositionResolver { private DAG dag = new DAG(); - public void addComponentDescriptor( ComponentDescriptor componentDescriptor ) - throws CycleDetectedInComponentGraphException - { - String key = getDAGKey( componentDescriptor.getRole(), componentDescriptor.getRoleHint() ); + public void addComponentDescriptor(ComponentDescriptor componentDescriptor) + throws CycleDetectedInComponentGraphException { + String key = getDAGKey(componentDescriptor.getRole(), componentDescriptor.getRoleHint()); List requirements = componentDescriptor.getRequirements(); - for ( ComponentRequirement requirement : requirements ) - { - try - { - if ( requirement instanceof ComponentRequirementList ) - { - for ( String hint : ( (ComponentRequirementList) requirement ).getRoleHints() ) - { - dag.addEdge( key, getDAGKey( requirement.getRole(), hint ) ); + for (ComponentRequirement requirement : requirements) { + try { + if (requirement instanceof ComponentRequirementList) { + for (String hint : ((ComponentRequirementList) requirement).getRoleHints()) { + dag.addEdge(key, getDAGKey(requirement.getRole(), hint)); } + } else { + dag.addEdge(key, getDAGKey(requirement.getRole(), requirement.getRoleHint())); } - else - { - dag.addEdge( key, getDAGKey( requirement.getRole(), requirement.getRoleHint() ) ); - } - } - catch ( CycleDetectedException e ) - { - throw new CycleDetectedInComponentGraphException( "Cyclic requirement detected", e ); + } catch (CycleDetectedException e) { + throw new CycleDetectedInComponentGraphException("Cyclic requirement detected", e); } } } @@ -69,23 +57,20 @@ public void addComponentDescriptor( ComponentDescriptor componentDescriptor ) /** * @see org.codehaus.plexus.component.composition.CompositionResolver#getRequirements(String,String) */ - public List getRequirements( String role, String roleHint ) - { - return dag.getChildLabels( getDAGKey( role, roleHint ) ); + public List getRequirements(String role, String roleHint) { + return dag.getChildLabels(getDAGKey(role, roleHint)); } - /** * @see org.codehaus.plexus.component.composition.CompositionResolver#findRequirements(String,String) */ - public List findRequirements( String role, String roleHint ) - { - return dag.getParentLabels( getDAGKey( role, roleHint ) ); + public List findRequirements(String role, String roleHint) { + return dag.getParentLabels(getDAGKey(role, roleHint)); } - private String getDAGKey( String role, String roleHint ) - { - return role + SEPARATOR_CHAR - + ( StringUtils.isNotEmpty( roleHint ) ? roleHint : PlexusConstants.PLEXUS_DEFAULT_HINT ); + private String getDAGKey(String role, String roleHint) { + return role + + SEPARATOR_CHAR + + (StringUtils.isNotEmpty(roleHint) ? roleHint : PlexusConstants.PLEXUS_DEFAULT_HINT); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/UndefinedComponentComposerException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/UndefinedComponentComposerException.java index b50cb9112..bfd22a553 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/UndefinedComponentComposerException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/composition/UndefinedComponentComposerException.java @@ -19,21 +19,16 @@ /** * @author Michal Maczka */ -public class UndefinedComponentComposerException - extends Exception -{ - public UndefinedComponentComposerException( String message ) - { - super( message ); +public class UndefinedComponentComposerException extends Exception { + public UndefinedComponentComposerException(String message) { + super(message); } - public UndefinedComponentComposerException( String message, Throwable cause ) - { - super( message, cause ); + public UndefinedComponentComposerException(String message, Throwable cause) { + super(message, cause); } - public UndefinedComponentComposerException( Throwable cause ) - { - super( cause ); + public UndefinedComponentComposerException(Throwable cause) { + super(cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/AbstractComponentConfigurator.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/AbstractComponentConfigurator.java index 267cdba53..320747827 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/AbstractComponentConfigurator.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/AbstractComponentConfigurator.java @@ -24,6 +24,9 @@ * SOFTWARE. */ +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + import org.codehaus.classworlds.ClassRealmAdapter; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; @@ -32,15 +35,10 @@ import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - /** * @author Brett Porter */ -public abstract class AbstractComponentConfigurator - implements ComponentConfigurator -{ +public abstract class AbstractComponentConfigurator implements ComponentConfigurator { /** * This is being instantiated here because there are old component factories (beanshell) that directly access * the converterLookup but do not yet state the ConverterLookup as a requirement in the component metadata. @@ -50,74 +48,69 @@ public abstract class AbstractComponentConfigurator */ protected ConverterLookup converterLookup = new DefaultConverterLookup(); - public void configureComponent( Object component, - PlexusConfiguration configuration, - ClassRealm containerRealm ) - throws ComponentConfigurationException - { - configureComponent( component, configuration, new DefaultExpressionEvaluator(), containerRealm ); + public void configureComponent(Object component, PlexusConfiguration configuration, ClassRealm containerRealm) + throws ComponentConfigurationException { + configureComponent(component, configuration, new DefaultExpressionEvaluator(), containerRealm); } - public void configureComponent( Object component, - PlexusConfiguration configuration, - ExpressionEvaluator expressionEvaluator, - ClassRealm containerRealm ) - throws ComponentConfigurationException - { - configureComponent( component, configuration, expressionEvaluator, containerRealm, null ); + public void configureComponent( + Object component, + PlexusConfiguration configuration, + ExpressionEvaluator expressionEvaluator, + ClassRealm containerRealm) + throws ComponentConfigurationException { + configureComponent(component, configuration, expressionEvaluator, containerRealm, null); } - public void configureComponent( final Object component, final PlexusConfiguration configuration, - final ExpressionEvaluator expressionEvaluator, final ClassRealm containerRealm, - final ConfigurationListener listener ) - throws ComponentConfigurationException - { + public void configureComponent( + final Object component, + final PlexusConfiguration configuration, + final ExpressionEvaluator expressionEvaluator, + final ClassRealm containerRealm, + final ConfigurationListener listener) + throws ComponentConfigurationException { // ---------------------------------------------------------------------------- // For compatibility with old ComponentFactories that use old ClassWorlds // ---------------------------------------------------------------------------- - final org.codehaus.classworlds.ClassRealm cr = ClassRealmAdapter.getInstance( containerRealm ); + final org.codehaus.classworlds.ClassRealm cr = ClassRealmAdapter.getInstance(containerRealm); Method method; - try - { - try - { - method = - getClass().getMethod( "configureComponent", Object.class, PlexusConfiguration.class, - ExpressionEvaluator.class, org.codehaus.classworlds.ClassRealm.class, - ConfigurationListener.class ); - method.invoke( this, component, configuration, expressionEvaluator, cr, listener ); + try { + try { + method = getClass() + .getMethod( + "configureComponent", + Object.class, + PlexusConfiguration.class, + ExpressionEvaluator.class, + org.codehaus.classworlds.ClassRealm.class, + ConfigurationListener.class); + method.invoke(this, component, configuration, expressionEvaluator, cr, listener); + } catch (final NoSuchMethodException e) { + method = getClass() + .getMethod( + "configureComponent", + Object.class, + PlexusConfiguration.class, + ExpressionEvaluator.class, + org.codehaus.classworlds.ClassRealm.class); + method.invoke(this, component, configuration, expressionEvaluator, cr); } - catch ( final NoSuchMethodException e ) - { - method = - getClass().getMethod( "configureComponent", Object.class, PlexusConfiguration.class, - ExpressionEvaluator.class, org.codehaus.classworlds.ClassRealm.class ); - method.invoke( this, component, configuration, expressionEvaluator, cr ); - } - } - catch ( final InvocationTargetException e ) - { - if ( e.getCause() instanceof ComponentConfigurationException ) - { + } catch (final InvocationTargetException e) { + if (e.getCause() instanceof ComponentConfigurationException) { throw (ComponentConfigurationException) e.getCause(); - } - else if ( e.getCause() instanceof RuntimeException ) - { + } else if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); - } - else if ( e.getCause() instanceof Error ) - { + } else if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } - throw new ComponentConfigurationException( "Incompatible configurator " + getClass().getName(), e ); - } - catch ( final Exception e ) - { - throw new ComponentConfigurationException( "Incompatible configurator " + getClass().getName(), e ); + throw new ComponentConfigurationException( + "Incompatible configurator " + getClass().getName(), e); + } catch (final Exception e) { + throw new ComponentConfigurationException( + "Incompatible configurator " + getClass().getName(), e); } } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/BasicComponentConfigurator.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/BasicComponentConfigurator.java index 26f0337ba..671d4311a 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/BasicComponentConfigurator.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/BasicComponentConfigurator.java @@ -30,30 +30,28 @@ import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; - /** * @author Jason van Zyl * @author Michal Maczka */ -public class BasicComponentConfigurator - extends AbstractComponentConfigurator -{ - public void configureComponent( Object component, - PlexusConfiguration configuration, - ExpressionEvaluator expressionEvaluator, - ClassRealm containerRealm, - ConfigurationListener listener ) - throws ComponentConfigurationException - { +public class BasicComponentConfigurator extends AbstractComponentConfigurator { + public void configureComponent( + Object component, + PlexusConfiguration configuration, + ExpressionEvaluator expressionEvaluator, + ClassRealm containerRealm, + ConfigurationListener listener) + throws ComponentConfigurationException { // ---------------------------------------------------------------------- // We should probably take into consideration the realm that the component // came from in order to load the correct classes. // ---------------------------------------------------------------------- - converterLookup.registerConverter( new ClassRealmConverter( containerRealm ) ); + converterLookup.registerConverter(new ClassRealmConverter(containerRealm)); ObjectWithFieldsConverter converter = new ObjectWithFieldsConverter(); - converter.processConfiguration( converterLookup, component, containerRealm, configuration, expressionEvaluator, listener ); + converter.processConfiguration( + converterLookup, component, containerRealm, configuration, expressionEvaluator, listener); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/ComponentConfigurationException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/ComponentConfigurationException.java index 4a24b2cb8..3c5331f10 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/ComponentConfigurationException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/ComponentConfigurationException.java @@ -4,55 +4,45 @@ /** * - * + * * @author Jason van Zyl * */ -public class ComponentConfigurationException - extends Exception -{ +public class ComponentConfigurationException extends Exception { private PlexusConfiguration failedConfiguration; - public ComponentConfigurationException( String message ) - { - super( message ); + public ComponentConfigurationException(String message) { + super(message); } - public ComponentConfigurationException( String message, Throwable cause ) - { - super( message, cause ); + public ComponentConfigurationException(String message, Throwable cause) { + super(message, cause); } - public ComponentConfigurationException( Throwable cause ) - { - super( cause ); + public ComponentConfigurationException(Throwable cause) { + super(cause); } - - public ComponentConfigurationException( PlexusConfiguration failedConfiguration, String message ) - { - super( message ); + + public ComponentConfigurationException(PlexusConfiguration failedConfiguration, String message) { + super(message); this.failedConfiguration = failedConfiguration; } - public ComponentConfigurationException( PlexusConfiguration failedConfiguration, String message, Throwable cause ) - { - super( message, cause ); + public ComponentConfigurationException(PlexusConfiguration failedConfiguration, String message, Throwable cause) { + super(message, cause); this.failedConfiguration = failedConfiguration; } - public ComponentConfigurationException( PlexusConfiguration failedConfiguration, Throwable cause ) - { - super( cause ); + public ComponentConfigurationException(PlexusConfiguration failedConfiguration, Throwable cause) { + super(cause); this.failedConfiguration = failedConfiguration; } - - public void setFailedConfiguration( PlexusConfiguration failedConfiguration ) - { + + public void setFailedConfiguration(PlexusConfiguration failedConfiguration) { this.failedConfiguration = failedConfiguration; } - - public PlexusConfiguration getFailedConfiguration() - { + + public PlexusConfiguration getFailedConfiguration() { return failedConfiguration; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/ComponentConfigurator.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/ComponentConfigurator.java index 04bb3b112..9e53e9de7 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/ComponentConfigurator.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/ComponentConfigurator.java @@ -31,19 +31,24 @@ /** * @author Jason van Zyl */ -public interface ComponentConfigurator -{ +public interface ComponentConfigurator { String ROLE = ComponentConfigurator.class.getName(); - void configureComponent( Object component, PlexusConfiguration configuration, ClassRealm containerRealm ) - throws ComponentConfigurationException; + void configureComponent(Object component, PlexusConfiguration configuration, ClassRealm containerRealm) + throws ComponentConfigurationException; - void configureComponent( Object component, PlexusConfiguration configuration, - ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm ) - throws ComponentConfigurationException; + void configureComponent( + Object component, + PlexusConfiguration configuration, + ExpressionEvaluator expressionEvaluator, + ClassRealm containerRealm) + throws ComponentConfigurationException; - void configureComponent( Object component, PlexusConfiguration configuration, - ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm, - ConfigurationListener listener ) - throws ComponentConfigurationException; + void configureComponent( + Object component, + PlexusConfiguration configuration, + ExpressionEvaluator expressionEvaluator, + ClassRealm containerRealm, + ConfigurationListener listener) + throws ComponentConfigurationException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/ConfigurationListener.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/ConfigurationListener.java index ba7b76ec7..3a881122b 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/ConfigurationListener.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/ConfigurationListener.java @@ -24,21 +24,19 @@ * SOFTWARE. */ - /** * Listen for configuration changes on an object. * * @author Brett Porter */ -public interface ConfigurationListener -{ +public interface ConfigurationListener { /** * Notify the listener that a field has been set using its setter. * @param fieldName the field * @param value the value set * @param target the target object */ - void notifyFieldChangeUsingSetter( String fieldName, Object value, Object target ); + void notifyFieldChangeUsingSetter(String fieldName, Object value, Object target); /** * Notify the listener that a field has been set using private field injection. @@ -46,5 +44,5 @@ public interface ConfigurationListener * @param value the value set * @param target the target object */ - void notifyFieldChangeUsingReflection( String fieldName, Object value, Object target ); + void notifyFieldChangeUsingReflection(String fieldName, Object value, Object target); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/MapOrientedComponentConfigurator.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/MapOrientedComponentConfigurator.java index d2fbf3b05..547c3814f 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/MapOrientedComponentConfigurator.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/MapOrientedComponentConfigurator.java @@ -1,13 +1,13 @@ package org.codehaus.plexus.component.configurator; +import java.util.Map; + import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.MapOrientedComponent; import org.codehaus.plexus.component.configurator.converters.composite.MapConverter; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; -import java.util.Map; - /* * Copyright 2001-2005 The Apache Software Foundation. * @@ -24,28 +24,25 @@ * limitations under the License. */ -public class MapOrientedComponentConfigurator - extends AbstractComponentConfigurator -{ - - public void configureComponent( Object component, PlexusConfiguration configuration, - ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm, - ConfigurationListener listener ) - throws ComponentConfigurationException - { - if ( !( component instanceof MapOrientedComponent ) ) - { +public class MapOrientedComponentConfigurator extends AbstractComponentConfigurator { + + public void configureComponent( + Object component, + PlexusConfiguration configuration, + ExpressionEvaluator expressionEvaluator, + ClassRealm containerRealm, + ConfigurationListener listener) + throws ComponentConfigurationException { + if (!(component instanceof MapOrientedComponent)) { throw new ComponentConfigurationException( - "This configurator can only process implementations of " + MapOrientedComponent.class.getName() ); + "This configurator can only process implementations of " + MapOrientedComponent.class.getName()); } MapConverter converter = new MapConverter(); - Map context = (Map) converter.fromConfiguration( converterLookup, configuration, null, null, - containerRealm, expressionEvaluator, - listener ); + Map context = (Map) converter.fromConfiguration( + converterLookup, configuration, null, null, containerRealm, expressionEvaluator, listener); - ( (MapOrientedComponent) component ).setComponentConfiguration( context ); + ((MapOrientedComponent) component).setComponentConfiguration(context); } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/AbstractConfigurationConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/AbstractConfigurationConverter.java index e0f0a261d..380bbb4d7 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/AbstractConfigurationConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/AbstractConfigurationConverter.java @@ -34,9 +34,7 @@ /** * @author Michal Maczka */ -public abstract class AbstractConfigurationConverter - implements ConfigurationConverter -{ +public abstract class AbstractConfigurationConverter implements ConfigurationConverter { private static final String IMPLEMENTATION = "implementation"; /** @@ -50,169 +48,136 @@ public abstract class AbstractConfigurationConverter * @return The class. * @throws ComponentConfigurationException in case of an error. */ - protected Class getClassForImplementationHint( Class type, PlexusConfiguration configuration, - ClassLoader classLoader ) - throws ComponentConfigurationException - { + protected Class getClassForImplementationHint( + Class type, PlexusConfiguration configuration, ClassLoader classLoader) + throws ComponentConfigurationException { Class retValue = type; - String implementation = configuration.getAttribute( IMPLEMENTATION, null ); + String implementation = configuration.getAttribute(IMPLEMENTATION, null); - if ( implementation != null ) - { - try - { - retValue = classLoader.loadClass( implementation ); + if (implementation != null) { + try { + retValue = classLoader.loadClass(implementation); - } - catch ( ClassNotFoundException e ) - { + } catch (ClassNotFoundException e) { String msg = "ClassNotFoundException: Class name which was explicitly given in configuration using" - + " 'implementation' attribute: '" + implementation + "' cannot be loaded"; + + " 'implementation' attribute: '" + implementation + "' cannot be loaded"; - throw new ComponentConfigurationException( msg, e ); - } - catch ( UnsupportedClassVersionError e ) - { + throw new ComponentConfigurationException(msg, e); + } catch (UnsupportedClassVersionError e) { String msg = "UnsupportedClassVersionError: Class name which was explicitly given in configuration" - + " using 'implementation' attribute: '" + implementation + "' cannot be loaded"; + + " using 'implementation' attribute: '" + implementation + "' cannot be loaded"; - throw new ComponentConfigurationException( msg, e ); - } - catch ( LinkageError e ) - { + throw new ComponentConfigurationException(msg, e); + } catch (LinkageError e) { String msg = "LinkageError: Class name which was explicitly given in configuration using" - + " 'implementation' attribute: '" + implementation + "' cannot be loaded"; + + " 'implementation' attribute: '" + implementation + "' cannot be loaded"; - throw new ComponentConfigurationException( msg, e ); + throw new ComponentConfigurationException(msg, e); } } return retValue; } - - protected Class loadClass( String classname, ClassLoader classLoader ) - throws ComponentConfigurationException - { + protected Class loadClass(String classname, ClassLoader classLoader) throws ComponentConfigurationException { Class retValue; - try - { - retValue = classLoader.loadClass( classname ); - } - catch ( ClassNotFoundException e ) - { - throw new ComponentConfigurationException( "Error loading class '" + classname + "'", e ); + try { + retValue = classLoader.loadClass(classname); + } catch (ClassNotFoundException e) { + throw new ComponentConfigurationException("Error loading class '" + classname + "'", e); } return retValue; } - protected Object instantiateObject( String classname, ClassLoader classLoader ) - throws ComponentConfigurationException - { - Class clazz = loadClass( classname, classLoader ); + protected Object instantiateObject(String classname, ClassLoader classLoader) + throws ComponentConfigurationException { + Class clazz = loadClass(classname, classLoader); - return instantiateObject( clazz ); + return instantiateObject(clazz); } - protected Object instantiateObject( Class clazz ) - throws ComponentConfigurationException - { + protected Object instantiateObject(Class clazz) throws ComponentConfigurationException { Object retValue; - try - { + try { retValue = clazz.newInstance(); return retValue; - } - catch ( IllegalAccessException e ) - { - throw new ComponentConfigurationException( "Class '" + clazz.getName() + "' cannot be instantiated", e ); - } - catch ( InstantiationException e ) - { - throw new ComponentConfigurationException( "Class '" + clazz.getName() + "' cannot be instantiated", e ); + } catch (IllegalAccessException e) { + throw new ComponentConfigurationException("Class '" + clazz.getName() + "' cannot be instantiated", e); + } catch (InstantiationException e) { + throw new ComponentConfigurationException("Class '" + clazz.getName() + "' cannot be instantiated", e); } } - // first-name --> firstName - protected String fromXML( String elementName ) - { - return StringUtils.lowercaseFirstLetter( StringUtils.removeAndHump( elementName, "-" ) ); + protected String fromXML(String elementName) { + return StringUtils.lowercaseFirstLetter(StringUtils.removeAndHump(elementName, "-")); } // firstName --> first-name - protected String toXML( String fieldName ) - { - return StringUtils.addAndDeHump( fieldName ); + protected String toXML(String fieldName) { + return StringUtils.addAndDeHump(fieldName); } - protected Object fromExpression( PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator, Class type ) - throws ComponentConfigurationException - { - Object v = fromExpression( configuration, expressionEvaluator ); - - if ( v != null ) - { - if ( !type.isAssignableFrom( v.getClass() ) ) - { - String msg = "Cannot assign configuration entry '" + configuration.getName() + "' to '" + type + - "' from '" + configuration.getValue( null ) + "', which is of type " + v.getClass(); - throw new ComponentConfigurationException( configuration, msg ); + protected Object fromExpression( + PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator, Class type) + throws ComponentConfigurationException { + Object v = fromExpression(configuration, expressionEvaluator); + + if (v != null) { + if (!type.isAssignableFrom(v.getClass())) { + String msg = "Cannot assign configuration entry '" + configuration.getName() + "' to '" + type + + "' from '" + configuration.getValue(null) + "', which is of type " + v.getClass(); + throw new ComponentConfigurationException(configuration, msg); } } return v; } - protected Object fromExpression( PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator ) - throws ComponentConfigurationException - { + protected Object fromExpression(PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator) + throws ComponentConfigurationException { Object v = null; - String value = configuration.getValue( null ); - if ( value != null && value.length() > 0 ) - { + String value = configuration.getValue(null); + if (value != null && value.length() > 0) { // Object is provided by an expression // This seems a bit ugly... canConvert really should return false in this instance, but it doesn't have the // configuration to know better - try - { - v = expressionEvaluator.evaluate( value ); - } - catch ( ExpressionEvaluationException e ) - { - String msg = "Error evaluating the expression '" + value + "' for configuration value '" + - configuration.getName() + "'"; - throw new ComponentConfigurationException( configuration, msg, e ); + try { + v = expressionEvaluator.evaluate(value); + } catch (ExpressionEvaluationException e) { + String msg = "Error evaluating the expression '" + value + "' for configuration value '" + + configuration.getName() + "'"; + throw new ComponentConfigurationException(configuration, msg, e); } } - if ( v == null ) - { - value = configuration.getAttribute( "default-value", null ); - if ( value != null && value.length() > 0 ) - { - try - { - v = expressionEvaluator.evaluate( value ); - } - catch ( ExpressionEvaluationException e ) - { - String msg = "Error evaluating the expression '" + value + "' for configuration value '" + - configuration.getName() + "'"; - throw new ComponentConfigurationException( configuration, msg, e ); + if (v == null) { + value = configuration.getAttribute("default-value", null); + if (value != null && value.length() > 0) { + try { + v = expressionEvaluator.evaluate(value); + } catch (ExpressionEvaluationException e) { + String msg = "Error evaluating the expression '" + value + "' for configuration value '" + + configuration.getName() + "'"; + throw new ComponentConfigurationException(configuration, msg, e); } } } return v; } - public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, - Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator ) - throws ComponentConfigurationException - { - return fromConfiguration( converterLookup, configuration, type, baseType, classLoader, expressionEvaluator, null ); + public Object fromConfiguration( + ConverterLookup converterLookup, + PlexusConfiguration configuration, + Class type, + Class baseType, + ClassLoader classLoader, + ExpressionEvaluator expressionEvaluator) + throws ComponentConfigurationException { + return fromConfiguration( + converterLookup, configuration, type, baseType, classLoader, expressionEvaluator, null); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/ComponentValueSetter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/ComponentValueSetter.java index 806490a9c..f448f0e80 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/ComponentValueSetter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/ComponentValueSetter.java @@ -16,6 +16,10 @@ * limitations under the License. */ +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; @@ -23,14 +27,8 @@ import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.util.ReflectionUtils; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - - /** @author Kenney Westerhof */ -public class ComponentValueSetter -{ +public class ComponentValueSetter { private Object object; private String fieldName; @@ -51,185 +49,140 @@ public class ComponentValueSetter private ConfigurationListener listener; - public ComponentValueSetter( String fieldName, - Object object, - ConverterLookup lookup ) - throws ComponentConfigurationException - { - this( fieldName, object, lookup, null ); + public ComponentValueSetter(String fieldName, Object object, ConverterLookup lookup) + throws ComponentConfigurationException { + this(fieldName, object, lookup, null); } - public ComponentValueSetter( String fieldName, - Object object, - ConverterLookup lookup, - ConfigurationListener listener ) - throws ComponentConfigurationException - { + public ComponentValueSetter(String fieldName, Object object, ConverterLookup lookup, ConfigurationListener listener) + throws ComponentConfigurationException { this.fieldName = fieldName; this.object = object; this.lookup = lookup; this.listener = listener; - if ( object == null ) - { - throw new ComponentConfigurationException( "Component is null" ); + if (object == null) { + throw new ComponentConfigurationException("Component is null"); } initSetter(); initField(); - if ( setter == null && field == null ) - { + if (setter == null && field == null) { throw new ComponentConfigurationException( - "Cannot find setter nor field in " + object.getClass().getName() + " for '" + fieldName + "'" ); + "Cannot find setter nor field in " + object.getClass().getName() + " for '" + fieldName + "'"); } - if ( setterTypeConverter == null && fieldTypeConverter == null ) - { - throw new ComponentConfigurationException( - "Cannot find converter for " + setterParamType.getName() + ( fieldType != null && !fieldType.equals( - setterParamType ) ? " or " + fieldType.getName() : "" ) ); + if (setterTypeConverter == null && fieldTypeConverter == null) { + throw new ComponentConfigurationException("Cannot find converter for " + setterParamType.getName() + + (fieldType != null && !fieldType.equals(setterParamType) ? " or " + fieldType.getName() : "")); } } - private void initSetter() - { - setter = ReflectionUtils.getSetter( fieldName, object.getClass() ); + private void initSetter() { + setter = ReflectionUtils.getSetter(fieldName, object.getClass()); - if ( setter == null ) - { + if (setter == null) { return; } setterParamType = setter.getParameterTypes()[0]; - try - { - setterTypeConverter = lookup.lookupConverterForType( setterParamType ); - } - catch ( ComponentConfigurationException e ) - { + try { + setterTypeConverter = lookup.lookupConverterForType(setterParamType); + } catch (ComponentConfigurationException e) { // ignore, handle later } } - private void initField() - { - field = ReflectionUtils.getFieldByNameIncludingSuperclasses( fieldName, object.getClass() ); + private void initField() { + field = ReflectionUtils.getFieldByNameIncludingSuperclasses(fieldName, object.getClass()); - if ( field == null ) - { + if (field == null) { return; } fieldType = field.getType(); - try - { - fieldTypeConverter = lookup.lookupConverterForType( fieldType ); - } - catch ( ComponentConfigurationException e ) - { + try { + fieldTypeConverter = lookup.lookupConverterForType(fieldType); + } catch (ComponentConfigurationException e) { // ignore, handle later } } - private void setValueUsingField( Object value ) - throws ComponentConfigurationException - { - try - { + private void setValueUsingField(Object value) throws ComponentConfigurationException { + try { boolean wasAccessible = field.isAccessible(); - if ( !wasAccessible ) - { - field.setAccessible( true ); + if (!wasAccessible) { + field.setAccessible(true); } - if ( listener != null ) - { - listener.notifyFieldChangeUsingReflection( fieldName, value, object ); + if (listener != null) { + listener.notifyFieldChangeUsingReflection(fieldName, value, object); } - field.set( object, value ); + field.set(object, value); - if ( !wasAccessible ) - { - field.setAccessible( false ); + if (!wasAccessible) { + field.setAccessible(false); } - } - catch ( IllegalAccessException e ) - { - throw new ComponentConfigurationException( "Cannot access field: " + field, e ); - } - catch ( IllegalArgumentException e ) - { - throw new ComponentConfigurationException( "Cannot assign value '" + value + "' (type: " - + value.getClass() + ") to " + field, e ); + } catch (IllegalAccessException e) { + throw new ComponentConfigurationException("Cannot access field: " + field, e); + } catch (IllegalArgumentException e) { + throw new ComponentConfigurationException( + "Cannot assign value '" + value + "' (type: " + value.getClass() + ") to " + field, e); } } - private void setValueUsingSetter( Object value ) - throws ComponentConfigurationException - { - if ( setterParamType == null || setter == null ) - { - throw new ComponentConfigurationException( "No setter found" ); + private void setValueUsingSetter(Object value) throws ComponentConfigurationException { + if (setterParamType == null || setter == null) { + throw new ComponentConfigurationException("No setter found"); } - String exceptionInfo = object.getClass().getName() + "." + setter.getName() + "( " + setterParamType.getClass().getName() + " )"; + String exceptionInfo = object.getClass().getName() + "." + setter.getName() + "( " + + setterParamType.getClass().getName() + " )"; - if ( listener != null ) - { - listener.notifyFieldChangeUsingSetter( fieldName, value, object ); + if (listener != null) { + listener.notifyFieldChangeUsingSetter(fieldName, value, object); } - try - { - setter.invoke( object, new Object[]{value} ); - } - catch ( IllegalAccessException e ) - { - throw new ComponentConfigurationException( "Cannot access method: " + exceptionInfo, e ); - } - catch ( IllegalArgumentException e ) - { + try { + setter.invoke(object, new Object[] {value}); + } catch (IllegalAccessException e) { + throw new ComponentConfigurationException("Cannot access method: " + exceptionInfo, e); + } catch (IllegalArgumentException e) { throw new ComponentConfigurationException( - "Invalid parameter supplied while setting '" + value + "' to " + exceptionInfo, e ); - } - catch ( InvocationTargetException e ) - { - throw new ComponentConfigurationException( "Setter " + exceptionInfo + - " threw exception when called with parameter '" + value + "': " + e.getTargetException().getMessage(), - e ); + "Invalid parameter supplied while setting '" + value + "' to " + exceptionInfo, e); + } catch (InvocationTargetException e) { + throw new ComponentConfigurationException( + "Setter " + exceptionInfo + " threw exception when called with parameter '" + value + "': " + + e.getTargetException().getMessage(), + e); } } - public void configure( PlexusConfiguration config, ClassLoader classLoader, ExpressionEvaluator evaluator ) - throws ComponentConfigurationException - { + public void configure(PlexusConfiguration config, ClassLoader classLoader, ExpressionEvaluator evaluator) + throws ComponentConfigurationException { Object value = null; // try setter converter + method first - if ( setterTypeConverter != null ) - { - try - { - value = setterTypeConverter.fromConfiguration( lookup, config, setterParamType, object.getClass(), classLoader, evaluator, listener ); + if (setterTypeConverter != null) { + try { + value = setterTypeConverter.fromConfiguration( + lookup, config, setterParamType, object.getClass(), classLoader, evaluator, listener); - if ( value != null ) - { - setValueUsingSetter( value ); + if (value != null) { + setValueUsingSetter(value); return; } - } - catch ( ComponentConfigurationException e ) - { - if ( fieldTypeConverter == null || fieldTypeConverter.getClass().equals( setterTypeConverter.getClass() ) ) - { + } catch (ComponentConfigurationException e) { + if (fieldTypeConverter == null + || fieldTypeConverter.getClass().equals(setterTypeConverter.getClass())) { throw e; } } @@ -240,15 +193,11 @@ public void configure( PlexusConfiguration config, ClassLoader classLoader, Expr ComponentConfigurationException savedEx = null; - if ( value != null ) - { - try - { - setValueUsingField( value ); + if (value != null) { + try { + setValueUsingField(value); return; - } - catch ( ComponentConfigurationException e ) - { + } catch (ComponentConfigurationException e) { savedEx = e; } } @@ -256,17 +205,15 @@ public void configure( PlexusConfiguration config, ClassLoader classLoader, Expr // either no value or setting went wrong. Try // new converter. - value = fieldTypeConverter.fromConfiguration( lookup, config, fieldType, object.getClass(), classLoader, evaluator, listener ); + value = fieldTypeConverter.fromConfiguration( + lookup, config, fieldType, object.getClass(), classLoader, evaluator, listener); - if ( value != null ) - { - setValueUsingField( value ); + if (value != null) { + setValueUsingField(value); } // FIXME: need this? - else if ( savedEx != null ) - { + else if (savedEx != null) { throw savedEx; } } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/ConfigurationConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/ConfigurationConverter.java index 5bdc139e6..d161d026c 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/ConfigurationConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/ConfigurationConverter.java @@ -30,10 +30,8 @@ import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; - -public interface ConfigurationConverter -{ - boolean canConvert( Class type ); +public interface ConfigurationConverter { + boolean canConvert(Class type); /** * @param converterLookup Repository of available converters @@ -46,9 +44,14 @@ public interface ConfigurationConverter * @throws ComponentConfigurationException in case of an error. * TODO: a better way, instead of baseType, would be to pass in a factory for new classes that could be based from the given package */ - Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, - Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator ) - throws ComponentConfigurationException; + Object fromConfiguration( + ConverterLookup converterLookup, + PlexusConfiguration configuration, + Class type, + Class baseType, + ClassLoader classLoader, + ExpressionEvaluator expressionEvaluator) + throws ComponentConfigurationException; /** * @param converterLookup Repository of available converters @@ -62,8 +65,13 @@ Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration c * @throws ComponentConfigurationException in case of an error. * TODO: a better way, instead of baseType, would be to pass in a factory for new classes that could be based from the given package */ - Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, - Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator, - ConfigurationListener listener ) - throws ComponentConfigurationException; + Object fromConfiguration( + ConverterLookup converterLookup, + PlexusConfiguration configuration, + Class type, + Class baseType, + ClassLoader classLoader, + ExpressionEvaluator expressionEvaluator, + ConfigurationListener listener) + throws ComponentConfigurationException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/AbstractBasicConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/AbstractBasicConverter.java index 95061e9c0..1bd7bcbe8 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/AbstractBasicConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/AbstractBasicConverter.java @@ -35,65 +35,47 @@ /** */ -public abstract class AbstractBasicConverter - extends AbstractConfigurationConverter -{ - protected abstract Object fromString( String str ) - throws ComponentConfigurationException; +public abstract class AbstractBasicConverter extends AbstractConfigurationConverter { + protected abstract Object fromString(String str) throws ComponentConfigurationException; - protected Object fromExpression( PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator, Class type ) - throws ComponentConfigurationException - { + protected Object fromExpression( + PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator, Class type) + throws ComponentConfigurationException { Object v = null; - String value = configuration.getValue( null ); + String value = configuration.getValue(null); - if ( value != null && value.length() > 0 ) - { + if (value != null && value.length() > 0) { // Object is provided by an expression // This seems a bit ugly... canConvert really should return false in this instance, but it doesn't have the // configuration to know better - try - { - if ( expressionEvaluator instanceof TypeAwareExpressionEvaluator ) - { - v = ( (TypeAwareExpressionEvaluator) expressionEvaluator ).evaluate( value, type ); + try { + if (expressionEvaluator instanceof TypeAwareExpressionEvaluator) { + v = ((TypeAwareExpressionEvaluator) expressionEvaluator).evaluate(value, type); + } else { + v = expressionEvaluator.evaluate(value); } - else - { - v = expressionEvaluator.evaluate( value ); - } - } - catch ( ExpressionEvaluationException e ) - { - String msg = "Error evaluating the expression '" + value + "' for configuration value '" + - configuration.getName() + "'"; - throw new ComponentConfigurationException( configuration, msg, e ); + } catch (ExpressionEvaluationException e) { + String msg = "Error evaluating the expression '" + value + "' for configuration value '" + + configuration.getName() + "'"; + throw new ComponentConfigurationException(configuration, msg, e); } } - if ( v == null ) - { - value = configuration.getAttribute( "default-value", null ); + if (v == null) { + value = configuration.getAttribute("default-value", null); - if ( value != null && value.length() > 0 ) - { - try - { - if ( expressionEvaluator instanceof TypeAwareExpressionEvaluator ) - { - v = ( (TypeAwareExpressionEvaluator) expressionEvaluator ).evaluate( value, type ); - } - else - { - v = expressionEvaluator.evaluate( value ); + if (value != null && value.length() > 0) { + try { + if (expressionEvaluator instanceof TypeAwareExpressionEvaluator) { + v = ((TypeAwareExpressionEvaluator) expressionEvaluator).evaluate(value, type); + } else { + v = expressionEvaluator.evaluate(value); } - } - catch ( ExpressionEvaluationException e ) - { - String msg = "Error evaluating the expression '" + value + "' for configuration value '" + - configuration.getName() + "'"; - throw new ComponentConfigurationException( configuration, msg, e ); + } catch (ExpressionEvaluationException e) { + String msg = "Error evaluating the expression '" + value + "' for configuration value '" + + configuration.getName() + "'"; + throw new ComponentConfigurationException(configuration, msg, e); } } } @@ -106,30 +88,28 @@ protected Object fromExpression( PlexusConfiguration configuration, ExpressionEv return v; } - public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, - Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator, - ConfigurationListener listener ) - throws ComponentConfigurationException - { - if ( configuration.getChildCount() > 0 ) - { - throw new ComponentConfigurationException( "When configuring a basic element the configuration cannot " + - "contain any child elements. " + "Configuration element '" + configuration.getName() + "'." ); + public Object fromConfiguration( + ConverterLookup converterLookup, + PlexusConfiguration configuration, + Class type, + Class baseType, + ClassLoader classLoader, + ExpressionEvaluator expressionEvaluator, + ConfigurationListener listener) + throws ComponentConfigurationException { + if (configuration.getChildCount() > 0) { + throw new ComponentConfigurationException("When configuring a basic element the configuration cannot " + + "contain any child elements. " + "Configuration element '" + configuration.getName() + "'."); } - Object retValue = fromExpression( configuration, expressionEvaluator, type ); + Object retValue = fromExpression(configuration, expressionEvaluator, type); - if ( retValue instanceof String ) - { - try - { - retValue = fromString( (String) retValue ); - } - catch ( ComponentConfigurationException e ) - { - if ( e.getFailedConfiguration() == null ) - { - e.setFailedConfiguration( configuration ); + if (retValue instanceof String) { + try { + retValue = fromString((String) retValue); + } catch (ComponentConfigurationException e) { + if (e.getFailedConfiguration() == null) { + e.setFailedConfiguration(configuration); } throw e; diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/BooleanConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/BooleanConverter.java index 9f2ea46b9..7ac6aeb38 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/BooleanConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/BooleanConverter.java @@ -24,17 +24,13 @@ * SOFTWARE. */ -public class BooleanConverter extends AbstractBasicConverter -{ +public class BooleanConverter extends AbstractBasicConverter { - public boolean canConvert( Class type ) - { - return type.equals( boolean.class ) || type.equals( Boolean.class ); + public boolean canConvert(Class type) { + return type.equals(boolean.class) || type.equals(Boolean.class); } - public Object fromString( String str ) - { - return str.equals( "true" ) ? Boolean.TRUE : Boolean.FALSE; + public Object fromString(String str) { + return str.equals("true") ? Boolean.TRUE : Boolean.FALSE; } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/ByteConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/ByteConverter.java index d45ba6ba0..da0fd57cc 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/ByteConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/ByteConverter.java @@ -24,17 +24,13 @@ * SOFTWARE. */ -public class ByteConverter extends AbstractBasicConverter -{ +public class ByteConverter extends AbstractBasicConverter { - public boolean canConvert( Class type ) - { - return type.equals( byte.class ) || type.equals( Byte.class ); + public boolean canConvert(Class type) { + return type.equals(byte.class) || type.equals(Byte.class); } - public Object fromString( String str ) - { + public Object fromString(String str) { return (byte) Integer.parseInt(str); } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/CharConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/CharConverter.java index 5498d9f11..4d0af27c9 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/CharConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/CharConverter.java @@ -24,17 +24,13 @@ * SOFTWARE. */ -public class CharConverter extends AbstractBasicConverter -{ +public class CharConverter extends AbstractBasicConverter { - public boolean canConvert( Class type ) - { - return type.equals( char.class ) || type.equals( Character.class ); + public boolean canConvert(Class type) { + return type.equals(char.class) || type.equals(Character.class); } - public Object fromString( String str ) - { + public Object fromString(String str) { return str.charAt(0); } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/ClassConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/ClassConverter.java index 82bfeddf2..77ae3b1ef 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/ClassConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/ClassConverter.java @@ -21,24 +21,16 @@ /** * @author Brett Porter */ -public class ClassConverter - extends AbstractBasicConverter -{ - public boolean canConvert( Class type ) - { - return type.equals( Class.class ); +public class ClassConverter extends AbstractBasicConverter { + public boolean canConvert(Class type) { + return type.equals(Class.class); } - public Object fromString( String str ) - throws ComponentConfigurationException - { - try - { - return Class.forName( str ); - } - catch ( ClassNotFoundException e ) - { - throw new ComponentConfigurationException( "Unable to find class in conversion", e ); + public Object fromString(String str) throws ComponentConfigurationException { + try { + return Class.forName(str); + } catch (ClassNotFoundException e) { + throw new ComponentConfigurationException("Unable to find class in conversion", e); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/Converter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/Converter.java index a54410506..b5e61c328 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/Converter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/Converter.java @@ -29,9 +29,8 @@ * an instance of the class and vice versa * */ -public interface Converter -{ - boolean canConvert( Class type ); +public interface Converter { + boolean canConvert(Class type); /** * Parses a given String and return @@ -39,7 +38,7 @@ public interface Converter * @param str String representation of the class * @return an instance of the class */ - Object fromString( String str ); + Object fromString(String str); - String toString( Object obj ); + String toString(Object obj); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/DateConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/DateConverter.java index cd4f5ebc2..710b39da6 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/DateConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/DateConverter.java @@ -29,23 +29,19 @@ import java.text.SimpleDateFormat; import java.util.Date; -public class DateConverter extends AbstractBasicConverter -{ +public class DateConverter extends AbstractBasicConverter { /*** * @todo DateFormat is not thread safe! */ private static final DateFormat[] formats = { - new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.S a" ), - new SimpleDateFormat( "yyyy-MM-dd HH:mm:ssa" ) + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S a"), new SimpleDateFormat("yyyy-MM-dd HH:mm:ssa") }; - public boolean canConvert( Class type ) - { - return type.equals( Date.class ); + public boolean canConvert(Class type) { + return type.equals(Date.class); } - public Object fromString( String str ) - { + public Object fromString(String str) { for (DateFormat format : formats) { try { return format.parse(str); @@ -57,10 +53,8 @@ public Object fromString( String str ) return null; } - public String toString( Object obj ) - { + public String toString(Object obj) { Date date = (Date) obj; - return formats[0].format( date ); + return formats[0].format(date); } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/DoubleConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/DoubleConverter.java index 49bb32ddc..9037251e7 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/DoubleConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/DoubleConverter.java @@ -24,17 +24,13 @@ * SOFTWARE. */ -public class DoubleConverter extends AbstractBasicConverter -{ +public class DoubleConverter extends AbstractBasicConverter { - public boolean canConvert( Class type ) - { - return type.equals( double.class ) || type.equals( Double.class ); + public boolean canConvert(Class type) { + return type.equals(double.class) || type.equals(Double.class); } - public Object fromString( String str ) - { - return Double.valueOf( str ); + public Object fromString(String str) { + return Double.valueOf(str); } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/EnumConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/EnumConverter.java index 560888edf..b4d62381a 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/EnumConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/EnumConverter.java @@ -34,42 +34,39 @@ /** * @author Benjamin Bentmann */ -public class EnumConverter - extends AbstractConfigurationConverter -{ +public class EnumConverter extends AbstractConfigurationConverter { - public boolean canConvert( Class type ) - { + public boolean canConvert(Class type) { return type.isEnum(); } - public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, - Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator, - ConfigurationListener listener ) - throws ComponentConfigurationException - { - if ( configuration.getChildCount() > 0 ) - { - throw new ComponentConfigurationException( "When configuring a basic element the configuration cannot " - + "contain any child elements. " + "Configuration element '" + configuration.getName() + "'." ); + public Object fromConfiguration( + ConverterLookup converterLookup, + PlexusConfiguration configuration, + Class type, + Class baseType, + ClassLoader classLoader, + ExpressionEvaluator expressionEvaluator, + ConfigurationListener listener) + throws ComponentConfigurationException { + if (configuration.getChildCount() > 0) { + throw new ComponentConfigurationException("When configuring a basic element the configuration cannot " + + "contain any child elements. " + "Configuration element '" + configuration.getName() + "'."); } - Object retValue = fromExpression( configuration, expressionEvaluator ); + Object retValue = fromExpression(configuration, expressionEvaluator); - if ( retValue instanceof String ) - { - try - { - retValue = Enum.valueOf( type, (String) retValue ); - } - catch ( RuntimeException e ) - { - throw new ComponentConfigurationException( "Cannot assign value " + retValue + " to property " - + configuration.getName() + " of " + baseType.getName() + ": " + e.getMessage(), e ); + if (retValue instanceof String) { + try { + retValue = Enum.valueOf(type, (String) retValue); + } catch (RuntimeException e) { + throw new ComponentConfigurationException( + "Cannot assign value " + retValue + " to property " + configuration.getName() + " of " + + baseType.getName() + ": " + e.getMessage(), + e); } } return retValue; } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/FileConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/FileConverter.java index c273865d0..69ebb4ddb 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/FileConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/FileConverter.java @@ -24,46 +24,43 @@ * SOFTWARE. */ +import java.io.File; + import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; -import java.io.File; - /** * @author Brett Porter */ -public class FileConverter - extends AbstractBasicConverter -{ - public boolean canConvert( Class type ) - { - return type.equals( File.class ); +public class FileConverter extends AbstractBasicConverter { + public boolean canConvert(Class type) { + return type.equals(File.class); } - public Object fromString( String str ) - { - str = str.replace( '\\', File.separatorChar ).replace( '/', File.separatorChar ); - return new File( str ); + public Object fromString(String str) { + str = str.replace('\\', File.separatorChar).replace('/', File.separatorChar); + return new File(str); } - public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, - Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator, - ConfigurationListener listener ) - throws ComponentConfigurationException - { - File f = (File) super.fromConfiguration( converterLookup, configuration, type, baseType, classLoader, - expressionEvaluator, listener ); + public Object fromConfiguration( + ConverterLookup converterLookup, + PlexusConfiguration configuration, + Class type, + Class baseType, + ClassLoader classLoader, + ExpressionEvaluator expressionEvaluator, + ConfigurationListener listener) + throws ComponentConfigurationException { + File f = (File) super.fromConfiguration( + converterLookup, configuration, type, baseType, classLoader, expressionEvaluator, listener); - if ( f != null ) - { + if (f != null) { // Hmmm... is this cheating? Can't think of a better way right now - return expressionEvaluator.alignToBaseDirectory( f ); - } - else - { + return expressionEvaluator.alignToBaseDirectory(f); + } else { return null; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/FloatConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/FloatConverter.java index 2a445a061..38db43779 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/FloatConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/FloatConverter.java @@ -24,17 +24,13 @@ * SOFTWARE. */ -public class FloatConverter extends AbstractBasicConverter -{ +public class FloatConverter extends AbstractBasicConverter { - public boolean canConvert( Class type ) - { - return type.equals( float.class ) || type.equals( Float.class ); + public boolean canConvert(Class type) { + return type.equals(float.class) || type.equals(Float.class); } - public Object fromString( String str ) - { - return Float.valueOf( str ); + public Object fromString(String str) { + return Float.valueOf(str); } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/IntConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/IntConverter.java index 55df99461..19f422846 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/IntConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/IntConverter.java @@ -26,27 +26,17 @@ * SOFTWARE. */ -public class IntConverter extends AbstractBasicConverter -{ +public class IntConverter extends AbstractBasicConverter { - public boolean canConvert( Class type ) - { - return type.equals( int.class ) || type.equals( Integer.class ); + public boolean canConvert(Class type) { + return type.equals(int.class) || type.equals(Integer.class); } - public Object fromString( String str ) - throws ComponentConfigurationException - { - try - { - return Integer.valueOf( str ); - } - catch ( NumberFormatException e ) - { - throw new ComponentConfigurationException( - "Not a number: '" + str + "'", e - ); + public Object fromString(String str) throws ComponentConfigurationException { + try { + return Integer.valueOf(str); + } catch (NumberFormatException e) { + throw new ComponentConfigurationException("Not a number: '" + str + "'", e); } } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/LongConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/LongConverter.java index 3aaab95ac..c549bc417 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/LongConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/LongConverter.java @@ -24,17 +24,13 @@ * SOFTWARE. */ -public class LongConverter extends AbstractBasicConverter -{ +public class LongConverter extends AbstractBasicConverter { - public boolean canConvert( Class type ) - { - return type.equals( long.class ) || type.equals( Long.class ); + public boolean canConvert(Class type) { + return type.equals(long.class) || type.equals(Long.class); } - public Object fromString( String str ) - { - return Long.valueOf( str ); + public Object fromString(String str) { + return Long.valueOf(str); } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/ShortConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/ShortConverter.java index 8d3462079..6fba68c08 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/ShortConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/ShortConverter.java @@ -24,17 +24,13 @@ * SOFTWARE. */ -public class ShortConverter extends AbstractBasicConverter -{ +public class ShortConverter extends AbstractBasicConverter { - public boolean canConvert( Class type ) - { - return type.equals( short.class ) || type.equals( Short.class ); + public boolean canConvert(Class type) { + return type.equals(short.class) || type.equals(Short.class); } - public Object fromString( String str ) - { - return Short.valueOf( str ); + public Object fromString(String str) { + return Short.valueOf(str); } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/StringBufferConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/StringBufferConverter.java index cd5969cae..2a42198b5 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/StringBufferConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/StringBufferConverter.java @@ -24,15 +24,12 @@ * SOFTWARE. */ -public class StringBufferConverter extends AbstractBasicConverter -{ - public boolean canConvert( Class type ) - { - return type.equals( StringBuffer.class ); +public class StringBufferConverter extends AbstractBasicConverter { + public boolean canConvert(Class type) { + return type.equals(StringBuffer.class); } - public Object fromString( String str ) - { - return new StringBuffer( str ); + public Object fromString(String str) { + return new StringBuffer(str); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/StringConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/StringConverter.java index f628383b8..0a72a9834 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/StringConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/StringConverter.java @@ -24,16 +24,12 @@ * SOFTWARE. */ -public class StringConverter extends AbstractBasicConverter -{ - public boolean canConvert( Class type ) - { - return type.equals( String.class ); +public class StringConverter extends AbstractBasicConverter { + public boolean canConvert(Class type) { + return type.equals(String.class); } - public Object fromString( String str ) - { + public Object fromString(String str) { return str; } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/UriConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/UriConverter.java index d0c8c7506..39b84143f 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/UriConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/UriConverter.java @@ -25,9 +25,7 @@ * Converter for {@link URI} objects. * */ -public class UriConverter - extends AbstractBasicConverter -{ +public class UriConverter extends AbstractBasicConverter { public boolean canConvert(final Class type) { assert type != null; @@ -39,9 +37,8 @@ public Object fromString(final String str) throws ComponentConfigurationExceptio try { return new URI(str); - } - catch (URISyntaxException e) { + } catch (URISyntaxException e) { throw new ComponentConfigurationException("Unable to convert to URI: " + str, e); } } -} \ No newline at end of file +} diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/UrlConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/UrlConverter.java index 34583aad7..05ef952c8 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/UrlConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/basic/UrlConverter.java @@ -24,32 +24,24 @@ * SOFTWARE. */ -import org.codehaus.plexus.component.configurator.ComponentConfigurationException; - import java.net.MalformedURLException; import java.net.URL; +import org.codehaus.plexus.component.configurator.ComponentConfigurationException; + /** * @author Brett Porter */ -public class UrlConverter - extends AbstractBasicConverter -{ - public boolean canConvert( Class type ) - { - return type.equals( URL.class ); +public class UrlConverter extends AbstractBasicConverter { + public boolean canConvert(Class type) { + return type.equals(URL.class); } - public Object fromString( String str ) - throws ComponentConfigurationException - { - try - { - return new URL( str ); - } - catch ( MalformedURLException e ) - { - throw new ComponentConfigurationException( "Unable to convert '" + str + "' to an URL", e ); + public Object fromString(String str) throws ComponentConfigurationException { + try { + return new URL(str); + } catch (MalformedURLException e) { + throw new ComponentConfigurationException("Unable to convert '" + str + "' to an URL", e); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/ArrayConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/ArrayConverter.java index e13c95ab4..aded3b09c 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/ArrayConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/ArrayConverter.java @@ -24,6 +24,10 @@ * SOFTWARE. */ +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.List; + import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; @@ -33,119 +37,98 @@ import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.util.StringUtils; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.List; - - /** * @author Kenney Westerhof */ -public class ArrayConverter - extends AbstractConfigurationConverter -{ - public boolean canConvert( Class type ) - { +public class ArrayConverter extends AbstractConfigurationConverter { + public boolean canConvert(Class type) { return type.isArray(); } - public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, - Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator, - ConfigurationListener listener ) - throws ComponentConfigurationException - { - Object retValue = fromExpression( configuration, expressionEvaluator, type ); - if ( retValue != null ) - { + public Object fromConfiguration( + ConverterLookup converterLookup, + PlexusConfiguration configuration, + Class type, + Class baseType, + ClassLoader classLoader, + ExpressionEvaluator expressionEvaluator, + ConfigurationListener listener) + throws ComponentConfigurationException { + Object retValue = fromExpression(configuration, expressionEvaluator, type); + if (retValue != null) { return retValue; } List values = new ArrayList(); - for ( int i = 0; i < configuration.getChildCount(); i++ ) - { - PlexusConfiguration childConfiguration = configuration.getChild( i ); + for (int i = 0; i < configuration.getChildCount(); i++) { + PlexusConfiguration childConfiguration = configuration.getChild(i); String configEntry = childConfiguration.getName(); - String name = fromXML( configEntry ); - - Class childType = getClassForImplementationHint( null, childConfiguration, classLoader ); - + String name = fromXML(configEntry); + + Class childType = getClassForImplementationHint(null, childConfiguration, classLoader); + // check if the name is a fully qualified classname - if ( childType == null && name.indexOf( '.' ) > 0 ) - { - try - { - childType = classLoader.loadClass( name ); - } - catch ( ClassNotFoundException e ) - { + if (childType == null && name.indexOf('.') > 0) { + try { + childType = classLoader.loadClass(name); + } catch (ClassNotFoundException e) { // doesn't exist - continue processing } } - if ( childType == null ) - { + if (childType == null) { // try to find the class in the package of the baseType // (which is the component being configured) String baseTypeName = baseType.getName(); - int lastDot = baseTypeName.lastIndexOf( '.' ); + int lastDot = baseTypeName.lastIndexOf('.'); String className; - if ( lastDot == -1 ) - { + if (lastDot == -1) { className = name; + } else { + String basePackage = baseTypeName.substring(0, lastDot); + className = basePackage + "." + StringUtils.capitalizeFirstLetter(name); } - else - { - String basePackage = baseTypeName.substring( 0, lastDot ); - className = basePackage + "." + StringUtils.capitalizeFirstLetter( name ); - } - - try - { - childType = classLoader.loadClass( className ); - } - catch ( ClassNotFoundException e ) - { + + try { + childType = classLoader.loadClass(className); + } catch (ClassNotFoundException e) { // doesn't exist, continue processing - } + } } // finally just try the component type of the array - if ( childType == null ) - { + if (childType == null) { childType = type.getComponentType(); } - ConfigurationConverter converter = converterLookup.lookupConverterForType( childType ); - - Object object = converter.fromConfiguration( converterLookup, - childConfiguration, - childType, - baseType, - classLoader, - expressionEvaluator, - listener ); - - values.add( object ); - } + ConfigurationConverter converter = converterLookup.lookupConverterForType(childType); + + Object object = converter.fromConfiguration( + converterLookup, + childConfiguration, + childType, + baseType, + classLoader, + expressionEvaluator, + listener); - try - { - return values.toArray( (Object[]) Array.newInstance( type.getComponentType(), 0 ) ); + values.add(object); } - catch ( ArrayStoreException e ) - { - throw new ComponentConfigurationException( "Cannot assign configuration values to array of type " - + type.getComponentType().getName() + ": " + values ); + + try { + return values.toArray((Object[]) Array.newInstance(type.getComponentType(), 0)); + } catch (ArrayStoreException e) { + throw new ComponentConfigurationException("Cannot assign configuration values to array of type " + + type.getComponentType().getName() + ": " + values); } } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/CollectionConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/CollectionConverter.java index 7fa545c4d..46a6bc003 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/CollectionConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/CollectionConverter.java @@ -24,15 +24,6 @@ * SOFTWARE. */ -import org.codehaus.plexus.component.configurator.ComponentConfigurationException; -import org.codehaus.plexus.component.configurator.ConfigurationListener; -import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; -import org.codehaus.plexus.component.configurator.converters.ConfigurationConverter; -import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; -import org.codehaus.plexus.configuration.PlexusConfiguration; -import org.codehaus.plexus.util.StringUtils; - import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; @@ -43,165 +34,141 @@ import java.util.SortedSet; import java.util.TreeSet; +import org.codehaus.plexus.component.configurator.ComponentConfigurationException; +import org.codehaus.plexus.component.configurator.ConfigurationListener; +import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; +import org.codehaus.plexus.component.configurator.converters.ConfigurationConverter; +import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; +import org.codehaus.plexus.configuration.PlexusConfiguration; +import org.codehaus.plexus.util.StringUtils; /** * @author Michal Maczka */ -public class CollectionConverter - extends AbstractConfigurationConverter -{ - public boolean canConvert( Class type ) - { - return Collection.class.isAssignableFrom( type ) && !Map.class.isAssignableFrom( type ); +public class CollectionConverter extends AbstractConfigurationConverter { + public boolean canConvert(Class type) { + return Collection.class.isAssignableFrom(type) && !Map.class.isAssignableFrom(type); } - public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, - Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator, - ConfigurationListener listener ) - throws ComponentConfigurationException - { - Object retValue = fromExpression( configuration, expressionEvaluator, type ); - if ( retValue != null ) - { + public Object fromConfiguration( + ConverterLookup converterLookup, + PlexusConfiguration configuration, + Class type, + Class baseType, + ClassLoader classLoader, + ExpressionEvaluator expressionEvaluator, + ConfigurationListener listener) + throws ComponentConfigurationException { + Object retValue = fromExpression(configuration, expressionEvaluator, type); + if (retValue != null) { return retValue; } - Class implementation = getClassForImplementationHint( null, configuration, classLoader ); + Class implementation = getClassForImplementationHint(null, configuration, classLoader); - if ( implementation != null ) - { - retValue = instantiateObject( implementation ); - } - else - { + if (implementation != null) { + retValue = instantiateObject(implementation); + } else { // we can have 2 cases here: // - provided collection class which is not abstract // like Vector, ArrayList, HashSet - so we will just instantantiate it // - we have an abtract class so we have to use default collection type int modifiers = type.getModifiers(); - if ( Modifier.isAbstract( modifiers ) ) - { - retValue = getDefaultCollection( type ); - } - else - { - try - { + if (Modifier.isAbstract(modifiers)) { + retValue = getDefaultCollection(type); + } else { + try { retValue = type.newInstance(); - } - catch ( IllegalAccessException e ) - { - String msg = "An attempt to convert configuration entry " + configuration.getName() + "' into " + - type + " object failed: " + e.getMessage(); + } catch (IllegalAccessException e) { + String msg = "An attempt to convert configuration entry " + configuration.getName() + "' into " + + type + " object failed: " + e.getMessage(); - throw new ComponentConfigurationException( msg, e ); - } - catch ( InstantiationException e ) - { - String msg = "An attempt to convert configuration entry " + configuration.getName() + "' into " + - type + " object failed: " + e.getMessage(); + throw new ComponentConfigurationException(msg, e); + } catch (InstantiationException e) { + String msg = "An attempt to convert configuration entry " + configuration.getName() + "' into " + + type + " object failed: " + e.getMessage(); - throw new ComponentConfigurationException( msg, e ); + throw new ComponentConfigurationException(msg, e); } } } // now we have collection and we have to add some objects to it - for ( int i = 0; i < configuration.getChildCount(); i++ ) - { - PlexusConfiguration c = configuration.getChild( i ); - //Object o = null; + for (int i = 0; i < configuration.getChildCount(); i++) { + PlexusConfiguration c = configuration.getChild(i); + // Object o = null; String configEntry = c.getName(); - String name = fromXML( configEntry ); + String name = fromXML(configEntry); - Class childType = getClassForImplementationHint( null, c, classLoader ); + Class childType = getClassForImplementationHint(null, c, classLoader); - if ( childType == null && name.indexOf( '.' ) > 0 ) - { - try - { - childType = classLoader.loadClass( name ); - } - catch ( ClassNotFoundException e ) - { + if (childType == null && name.indexOf('.') > 0) { + try { + childType = classLoader.loadClass(name); + } catch (ClassNotFoundException e) { // not found, continue processing } } - if ( childType == null ) - { + if (childType == null) { // Some classloaders don't create Package objects for classes // so we have to resort to slicing up the class name String baseTypeName = baseType.getName(); - int lastDot = baseTypeName.lastIndexOf( '.' ); + int lastDot = baseTypeName.lastIndexOf('.'); String className; - if ( lastDot == -1 ) - { + if (lastDot == -1) { className = name; - } - else - { - String basePackage = baseTypeName.substring( 0, lastDot ); + } else { + String basePackage = baseTypeName.substring(0, lastDot); - className = basePackage + "." + StringUtils.capitalizeFirstLetter( name ); + className = basePackage + "." + StringUtils.capitalizeFirstLetter(name); } - try - { - childType = classLoader.loadClass( className ); - } - catch ( ClassNotFoundException e ) - { - if ( c.getChildCount() == 0 ) - { + try { + childType = classLoader.loadClass(className); + } catch (ClassNotFoundException e) { + if (c.getChildCount() == 0) { // If no children, try a String. - // TODO: If we had generics we could try that instead - or could the component descriptor list an impl? + // TODO: If we had generics we could try that instead - or could the component descriptor list + // an impl? childType = String.class; - } - else - { - throw new ComponentConfigurationException( "Error loading class '" + className + "'", e ); + } else { + throw new ComponentConfigurationException("Error loading class '" + className + "'", e); } } } - ConfigurationConverter converter = converterLookup.lookupConverterForType( childType ); + ConfigurationConverter converter = converterLookup.lookupConverterForType(childType); - Object object = converter.fromConfiguration( converterLookup, c, childType, baseType, classLoader, - expressionEvaluator, listener ); + Object object = converter.fromConfiguration( + converterLookup, c, childType, baseType, classLoader, expressionEvaluator, listener); Collection collection = (Collection) retValue; - collection.add( object ); + collection.add(object); } return retValue; } - protected Collection getDefaultCollection( Class collectionType ) - { + protected Collection getDefaultCollection(Class collectionType) { Collection retValue = null; - if ( List.class.isAssignableFrom( collectionType ) ) - { + if (List.class.isAssignableFrom(collectionType)) { retValue = new ArrayList(); - } - else if ( SortedSet.class.isAssignableFrom( collectionType ) ) - { + } else if (SortedSet.class.isAssignableFrom(collectionType)) { retValue = new TreeSet(); - } - else if ( Set.class.isAssignableFrom( collectionType ) ) - { + } else if (Set.class.isAssignableFrom(collectionType)) { retValue = new HashSet(); } return retValue; } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/MapConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/MapConverter.java index afa4edec9..d5cebe3ed 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/MapConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/MapConverter.java @@ -24,6 +24,10 @@ * SOFTWARE. */ +import java.util.Map; +import java.util.Properties; +import java.util.TreeMap; + import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; @@ -31,39 +35,34 @@ import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; -import java.util.Map; -import java.util.Properties; -import java.util.TreeMap; - /** * Converter for java.util.Properties. * * @author Michal Maczka */ -public class MapConverter - extends AbstractConfigurationConverter -{ - public boolean canConvert( Class type ) - { - return Map.class.isAssignableFrom( type ) && !Properties.class.isAssignableFrom( type ); +public class MapConverter extends AbstractConfigurationConverter { + public boolean canConvert(Class type) { + return Map.class.isAssignableFrom(type) && !Properties.class.isAssignableFrom(type); } - public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, - Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator, - ConfigurationListener listener ) - throws ComponentConfigurationException - { + public Object fromConfiguration( + ConverterLookup converterLookup, + PlexusConfiguration configuration, + Class type, + Class baseType, + ClassLoader classLoader, + ExpressionEvaluator expressionEvaluator, + ConfigurationListener listener) + throws ComponentConfigurationException { Object retValue; - String expression = configuration.getValue( null ); + String expression = configuration.getValue(null); - if ( expression == null ) - { - expression = configuration.getAttribute( "default-value", null ); + if (expression == null) { + expression = configuration.getAttribute("default-value", null); } - if ( expression == null ) - { + if (expression == null) { Map map = new TreeMap(); PlexusConfiguration[] children = configuration.getChildren(); @@ -74,12 +73,9 @@ public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfigur map.put(name, fromExpression(child, expressionEvaluator)); } retValue = map; - } - else - { - retValue = fromExpression( configuration, expressionEvaluator ); + } else { + retValue = fromExpression(configuration, expressionEvaluator); } return retValue; } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/ObjectWithFieldsConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/ObjectWithFieldsConverter.java index dc2b9bd2c..5d4bb6964 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/ObjectWithFieldsConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/ObjectWithFieldsConverter.java @@ -24,6 +24,10 @@ * SOFTWARE. */ +import java.util.Collection; +import java.util.Dictionary; +import java.util.Map; + import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; @@ -32,69 +36,51 @@ import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; -import java.util.Collection; -import java.util.Dictionary; -import java.util.Map; - /** * @author Michal Maczka */ -public class ObjectWithFieldsConverter - extends AbstractConfigurationConverter -{ - public boolean canConvert( Class type ) - { +public class ObjectWithFieldsConverter extends AbstractConfigurationConverter { + public boolean canConvert(Class type) { boolean retValue = true; - if ( Dictionary.class.isAssignableFrom( type ) ) - { + if (Dictionary.class.isAssignableFrom(type)) { retValue = false; - } - - else if ( Map.class.isAssignableFrom( type ) ) - { + } else if (Map.class.isAssignableFrom(type)) { retValue = false; - } - else if ( Collection.class.isAssignableFrom( type ) ) - { + } else if (Collection.class.isAssignableFrom(type)) { retValue = false; } return retValue; } - public Object fromConfiguration( ConverterLookup converterLookup, - PlexusConfiguration configuration, - Class type, - Class baseType, - ClassLoader classLoader, - ExpressionEvaluator expressionEvaluator, - ConfigurationListener listener ) - throws ComponentConfigurationException - { - Object retValue = fromExpression( configuration, expressionEvaluator, type ); - - if ( retValue == null ) - { - try - { + public Object fromConfiguration( + ConverterLookup converterLookup, + PlexusConfiguration configuration, + Class type, + Class baseType, + ClassLoader classLoader, + ExpressionEvaluator expressionEvaluator, + ConfigurationListener listener) + throws ComponentConfigurationException { + Object retValue = fromExpression(configuration, expressionEvaluator, type); + + if (retValue == null) { + try { // it is a "composite" - we compose it from its children. It does not have a value of its own - Class implementation = getClassForImplementationHint( type, configuration, classLoader ); + Class implementation = getClassForImplementationHint(type, configuration, classLoader); - if ( type == implementation && type.isInterface() && configuration.getChildCount() <= 0 ) - { + if (type == implementation && type.isInterface() && configuration.getChildCount() <= 0) { return null; } - retValue = instantiateObject( implementation ); + retValue = instantiateObject(implementation); - processConfiguration( converterLookup, retValue, classLoader, configuration, expressionEvaluator, listener ); - } - catch ( ComponentConfigurationException e ) - { - if ( e.getFailedConfiguration() == null ) - { - e.setFailedConfiguration( configuration ); + processConfiguration( + converterLookup, retValue, classLoader, configuration, expressionEvaluator, listener); + } catch (ComponentConfigurationException e) { + if (e.getFailedConfiguration() == null) { + e.setFailedConfiguration(configuration); } throw e; @@ -103,45 +89,41 @@ public Object fromConfiguration( ConverterLookup converterLookup, return retValue; } - - public void processConfiguration( ConverterLookup converterLookup, - Object object, - ClassLoader classLoader, - PlexusConfiguration configuration ) - throws ComponentConfigurationException - { - processConfiguration( converterLookup, object, classLoader, configuration, null ); + public void processConfiguration( + ConverterLookup converterLookup, Object object, ClassLoader classLoader, PlexusConfiguration configuration) + throws ComponentConfigurationException { + processConfiguration(converterLookup, object, classLoader, configuration, null); } - public void processConfiguration( ConverterLookup converterLookup, - Object object, - ClassLoader classLoader, - PlexusConfiguration configuration, - ExpressionEvaluator expressionEvaluator ) - throws ComponentConfigurationException - { - processConfiguration( converterLookup, object, classLoader, configuration, expressionEvaluator, null ); + public void processConfiguration( + ConverterLookup converterLookup, + Object object, + ClassLoader classLoader, + PlexusConfiguration configuration, + ExpressionEvaluator expressionEvaluator) + throws ComponentConfigurationException { + processConfiguration(converterLookup, object, classLoader, configuration, expressionEvaluator, null); } - public void processConfiguration( ConverterLookup converterLookup, - Object object, - ClassLoader classLoader, - PlexusConfiguration configuration, - ExpressionEvaluator expressionEvaluator, - ConfigurationListener listener ) - throws ComponentConfigurationException - { + public void processConfiguration( + ConverterLookup converterLookup, + Object object, + ClassLoader classLoader, + PlexusConfiguration configuration, + ExpressionEvaluator expressionEvaluator, + ConfigurationListener listener) + throws ComponentConfigurationException { int items = configuration.getChildCount(); - for ( int i = 0; i < items; i++ ) - { - PlexusConfiguration childConfiguration = configuration.getChild( i ); + for (int i = 0; i < items; i++) { + PlexusConfiguration childConfiguration = configuration.getChild(i); String elementName = childConfiguration.getName(); - ComponentValueSetter valueSetter = new ComponentValueSetter( fromXML( elementName ), object, converterLookup, listener ); + ComponentValueSetter valueSetter = + new ComponentValueSetter(fromXML(elementName), object, converterLookup, listener); - valueSetter.configure( childConfiguration, classLoader, expressionEvaluator ); + valueSetter.configure(childConfiguration, classLoader, expressionEvaluator); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/PlexusConfigurationConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/PlexusConfigurationConverter.java index ec57d38b9..d8723994f 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/PlexusConfigurationConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/PlexusConfigurationConverter.java @@ -31,25 +31,25 @@ import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; - /** * Converter for org.codehaus.plexus.configuration.PlexusConfiguration * * @author Michal Maczka */ -public class PlexusConfigurationConverter - extends AbstractConfigurationConverter -{ - public boolean canConvert( Class type ) - { - return PlexusConfiguration.class.isAssignableFrom( type ); +public class PlexusConfigurationConverter extends AbstractConfigurationConverter { + public boolean canConvert(Class type) { + return PlexusConfiguration.class.isAssignableFrom(type); } - public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, - Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator, - ConfigurationListener listener ) - throws ComponentConfigurationException - { + public Object fromConfiguration( + ConverterLookup converterLookup, + PlexusConfiguration configuration, + Class type, + Class baseType, + ClassLoader classLoader, + ExpressionEvaluator expressionEvaluator, + ConfigurationListener listener) + throws ComponentConfigurationException { return configuration; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/PropertiesConverter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/PropertiesConverter.java index f1a0a45be..b6a6463a1 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/PropertiesConverter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/composite/PropertiesConverter.java @@ -24,6 +24,8 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter; @@ -31,30 +33,28 @@ import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; -import java.util.Properties; - /** * Converter for java.util.Properties. * * @author Michal Maczka */ -public class PropertiesConverter - extends AbstractConfigurationConverter -{ - public boolean canConvert( Class type ) - { - return Properties.class.isAssignableFrom( type ); +public class PropertiesConverter extends AbstractConfigurationConverter { + public boolean canConvert(Class type) { + return Properties.class.isAssignableFrom(type); } - public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, - Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator, - ConfigurationListener listener ) - throws ComponentConfigurationException - { - - Object retValueInterpolated = fromExpression( configuration, expressionEvaluator, type ); - if ( retValueInterpolated != null ) - { + public Object fromConfiguration( + ConverterLookup converterLookup, + PlexusConfiguration configuration, + Class type, + Class baseType, + ClassLoader classLoader, + ExpressionEvaluator expressionEvaluator, + ConfigurationListener listener) + throws ComponentConfigurationException { + + Object retValueInterpolated = fromExpression(configuration, expressionEvaluator, type); + if (retValueInterpolated != null) { return retValueInterpolated; } @@ -62,10 +62,9 @@ public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfigur Properties retValue = new Properties(); - PlexusConfiguration[] children = configuration.getChildren( "property" ); + PlexusConfiguration[] children = configuration.getChildren("property"); - if ( children != null && children.length > 0 ) - { + if (children != null && children.length > 0) { for (PlexusConfiguration child : children) { addEntry(retValue, element, child, expressionEvaluator); } @@ -74,31 +73,27 @@ public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfigur return retValue; } - private void addEntry( Properties properties, String element, PlexusConfiguration property, - ExpressionEvaluator expressionEvaluator ) - throws ComponentConfigurationException - { - Object name = fromExpression( property.getChild( "name" ), expressionEvaluator ); + private void addEntry( + Properties properties, + String element, + PlexusConfiguration property, + ExpressionEvaluator expressionEvaluator) + throws ComponentConfigurationException { + Object name = fromExpression(property.getChild("name"), expressionEvaluator); - if ( name == null ) - { - String msg = - "Trying to convert the configuration element: '" + element + if (name == null) { + String msg = "Trying to convert the configuration element: '" + element + "', missing child element 'name' for property."; - throw new ComponentConfigurationException( msg ); + throw new ComponentConfigurationException(msg); } - Object value = fromExpression( property.getChild( "value" ), expressionEvaluator ); + Object value = fromExpression(property.getChild("value"), expressionEvaluator); - if ( value == null ) - { - properties.setProperty( name.toString(), "" ); - } - else - { - properties.setProperty( name.toString(), value.toString() ); + if (value == null) { + properties.setProperty(name.toString(), ""); + } else { + properties.setProperty(name.toString(), value.toString()); } } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/lookup/ConverterLookup.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/lookup/ConverterLookup.java index d61d1ccf0..2696d75bc 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/lookup/ConverterLookup.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/lookup/ConverterLookup.java @@ -28,10 +28,8 @@ import org.codehaus.plexus.component.configurator.converters.ConfigurationConverter; /** @version $Id$ */ -public interface ConverterLookup -{ - void registerConverter( ConfigurationConverter converter ); +public interface ConverterLookup { + void registerConverter(ConfigurationConverter converter); - ConfigurationConverter lookupConverterForType( Class type ) - throws ComponentConfigurationException; + ConfigurationConverter lookupConverterForType(Class type) throws ComponentConfigurationException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/lookup/DefaultConverterLookup.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/lookup/DefaultConverterLookup.java index 916c2f347..e8afde898 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/lookup/DefaultConverterLookup.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/converters/lookup/DefaultConverterLookup.java @@ -24,6 +24,12 @@ * SOFTWARE. */ +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.converters.ConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.basic.BooleanConverter; @@ -48,73 +54,54 @@ import org.codehaus.plexus.component.configurator.converters.composite.PlexusConfigurationConverter; import org.codehaus.plexus.component.configurator.converters.composite.PropertiesConverter; -import java.util.List; -import java.util.Map; -import java.util.ArrayList; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; - -public class DefaultConverterLookup - implements ConverterLookup -{ +public class DefaultConverterLookup implements ConverterLookup { private final List converters = new ArrayList(); private final List customConverters = new CopyOnWriteArrayList(); - private final Map, ConfigurationConverter> converterMap = new ConcurrentHashMap, ConfigurationConverter>(); + private final Map, ConfigurationConverter> converterMap = + new ConcurrentHashMap, ConfigurationConverter>(); - public DefaultConverterLookup() - { + public DefaultConverterLookup() { registerDefaultBasicConverters(); registerDefaultCompositeConverters(); } - public synchronized void registerConverter( ConfigurationConverter converter ) - { - customConverters.add( converter ); + public synchronized void registerConverter(ConfigurationConverter converter) { + customConverters.add(converter); } - protected void registerDefaultConverter( ConfigurationConverter converter ) - { - converters.add( converter ); + protected void registerDefaultConverter(ConfigurationConverter converter) { + converters.add(converter); } - public ConfigurationConverter lookupConverterForType( Class type ) - throws ComponentConfigurationException - { - ConfigurationConverter retValue = converterMap.get( type ); + public ConfigurationConverter lookupConverterForType(Class type) throws ComponentConfigurationException { + ConfigurationConverter retValue = converterMap.get(type); - if ( retValue == null ) - { - if ( customConverters != null ) - { - retValue = findConverterForType( customConverters, type ); + if (retValue == null) { + if (customConverters != null) { + retValue = findConverterForType(customConverters, type); } - if ( retValue == null ) - { - retValue = findConverterForType( converters, type ); + if (retValue == null) { + retValue = findConverterForType(converters, type); } - if ( retValue == null ) - { + if (retValue == null) { // this is highly irregular - throw new ComponentConfigurationException( "Configuration converter lookup failed for type: " + type ); + throw new ComponentConfigurationException("Configuration converter lookup failed for type: " + type); } - converterMap.put( type, retValue ); + converterMap.put(type, retValue); } return retValue; } - private ConfigurationConverter findConverterForType( List converters, Class type ) - { - for ( ConfigurationConverter converter : converters ) - { - if ( converter.canConvert( type ) ) - { + private ConfigurationConverter findConverterForType(List converters, Class type) { + for (ConfigurationConverter converter : converters) { + if (converter.canConvert(type)) { return converter; } } @@ -122,53 +109,50 @@ private ConfigurationConverter findConverterForType( ListKenney Westerhof */ -public class ClassRealmConverter - extends AbstractConfigurationConverter -{ +public class ClassRealmConverter extends AbstractConfigurationConverter { public static final String ROLE = ConfigurationConverter.class.getName(); private ClassRealm classRealm; @@ -30,61 +28,54 @@ public class ClassRealmConverter * * @param classRealm {@link ClassRealm}. */ - public ClassRealmConverter( ClassRealm classRealm ) - { - setClassRealm( classRealm ); + public ClassRealmConverter(ClassRealm classRealm) { + setClassRealm(classRealm); } @Deprecated - public ClassRealmConverter( final org.codehaus.classworlds.ClassRealm classRealm ) - { - setClassRealm( classRealm ); + public ClassRealmConverter(final org.codehaus.classworlds.ClassRealm classRealm) { + setClassRealm(classRealm); } - public void setClassRealm( final ClassRealm classRealm ) - { + public void setClassRealm(final ClassRealm classRealm) { this.classRealm = classRealm; } @Deprecated - public void setClassRealm( final org.codehaus.classworlds.ClassRealm classRealm ) - { - if ( classRealm.getClassLoader() instanceof ClassRealm ) - { - setClassRealm( (ClassRealm) classRealm.getClassLoader() ); - } - else - { - setClassRealm( ClassRealmReverseAdapter.getInstance( classRealm ) ); + public void setClassRealm(final org.codehaus.classworlds.ClassRealm classRealm) { + if (classRealm.getClassLoader() instanceof ClassRealm) { + setClassRealm((ClassRealm) classRealm.getClassLoader()); + } else { + setClassRealm(ClassRealmReverseAdapter.getInstance(classRealm)); } } - public boolean canConvert( Class type ) - { + public boolean canConvert(Class type) { // backwards compatibility for old ClassWorld fields - return org.codehaus.classworlds.ClassRealm.class.isAssignableFrom( type ) - || ClassRealm.class.isAssignableFrom( type ); + return org.codehaus.classworlds.ClassRealm.class.isAssignableFrom(type) + || ClassRealm.class.isAssignableFrom(type); } - public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type, - Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator, - ConfigurationListener listener ) - throws ComponentConfigurationException - { - Object retValue = fromExpression( configuration, expressionEvaluator, type ); + public Object fromConfiguration( + ConverterLookup converterLookup, + PlexusConfiguration configuration, + Class type, + Class baseType, + ClassLoader classLoader, + ExpressionEvaluator expressionEvaluator, + ConfigurationListener listener) + throws ComponentConfigurationException { + Object retValue = fromExpression(configuration, expressionEvaluator, type); - if ( retValue == null ) - { + if (retValue == null) { retValue = classRealm; } // backwards compatibility for old ClassWorld fields - if ( retValue instanceof ClassRealm && org.codehaus.classworlds.ClassRealm.class.isAssignableFrom( type ) ) - { - retValue = ClassRealmAdapter.getInstance( (ClassRealm) retValue ); + if (retValue instanceof ClassRealm && org.codehaus.classworlds.ClassRealm.class.isAssignableFrom(type)) { + retValue = ClassRealmAdapter.getInstance((ClassRealm) retValue); } return retValue; } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/DefaultExpressionEvaluator.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/DefaultExpressionEvaluator.java index 4d4d31a86..f6fed31de 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/DefaultExpressionEvaluator.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/DefaultExpressionEvaluator.java @@ -23,22 +23,18 @@ * * @author Brett Porter */ -public class DefaultExpressionEvaluator - implements ExpressionEvaluator -{ +public class DefaultExpressionEvaluator implements ExpressionEvaluator { /** * Evaluate an expression. * * @param expression the expression * @return the value of the expression */ - public Object evaluate( String expression ) - { + public Object evaluate(String expression) { return expression; } - public File alignToBaseDirectory( File file ) - { + public File alignToBaseDirectory(File file) { return file; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/ExpressionEvaluationException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/ExpressionEvaluationException.java index 0c3356ddb..78b7ca313 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/ExpressionEvaluationException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/ExpressionEvaluationException.java @@ -21,16 +21,12 @@ * * @author Brett Porter */ -public class ExpressionEvaluationException - extends Exception -{ - public ExpressionEvaluationException( String message ) - { - super( message ); +public class ExpressionEvaluationException extends Exception { + public ExpressionEvaluationException(String message) { + super(message); } - public ExpressionEvaluationException( String message, Throwable cause ) - { - super( message, cause ); + public ExpressionEvaluationException(String message, Throwable cause) { + super(message, cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/ExpressionEvaluator.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/ExpressionEvaluator.java index e7ec30fa8..f14d96937 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/ExpressionEvaluator.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/ExpressionEvaluator.java @@ -23,19 +23,17 @@ * * @author Brett Porter */ -public interface ExpressionEvaluator -{ +public interface ExpressionEvaluator { String ROLE = ExpressionEvaluator.class.getName(); - + /** * Evaluate an expression. * * @param expression the expression * @return the value of the expression - * @throws ExpressionEvaluationException in case of an error. + * @throws ExpressionEvaluationException in case of an error. */ - Object evaluate( String expression ) - throws ExpressionEvaluationException; + Object evaluate(String expression) throws ExpressionEvaluationException; /** * Align a given path to the base directory that can be evaluated by this expression evaluator, if known. @@ -43,5 +41,5 @@ Object evaluate( String expression ) * @param file the file * @return the aligned file */ - File alignToBaseDirectory( File file ); + File alignToBaseDirectory(File file); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/TypeAwareExpressionEvaluator.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/TypeAwareExpressionEvaluator.java index 9498dfbe2..871999c6a 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/TypeAwareExpressionEvaluator.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/configurator/expression/TypeAwareExpressionEvaluator.java @@ -21,21 +21,17 @@ * * @author Brett Porter */ -public interface TypeAwareExpressionEvaluator - extends ExpressionEvaluator -{ +public interface TypeAwareExpressionEvaluator extends ExpressionEvaluator { /** * Evaluate an expression. The optional type provided to this method is a hint (not a requirement) for the evaluator * to resolve the expression to a compatible value. The evaluator is not expected to perform any conversion but * rather filter out incompatible values from its result. - * + * * @param expression the expression * @param type The expected type of expression result, may be {@code null}. * @return the value of the expression - * @throws ExpressionEvaluationException in case of an error. + * @throws ExpressionEvaluationException in case of an error. */ - Object evaluate( String expression, Class type ) - throws ExpressionEvaluationException; - + Object evaluate(String expression, Class type) throws ExpressionEvaluationException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/AbstractResourceBasedComponentDiscoverer.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/AbstractResourceBasedComponentDiscoverer.java index b1260d110..71f75a009 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/AbstractResourceBasedComponentDiscoverer.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/AbstractResourceBasedComponentDiscoverer.java @@ -34,63 +34,54 @@ import org.codehaus.plexus.util.InterpolationFilterReader; import org.codehaus.plexus.util.ReaderFactory; -//TODO: this should be a default strategy of searching through classloaders. a discoverer should really not have to be +// TODO: this should be a default strategy of searching through classloaders. a discoverer should really not have to be // concerned finding a particular resource and how to turn it into a set of component descriptors. /** * @author Jason van Zyl */ -public abstract class AbstractResourceBasedComponentDiscoverer - implements ComponentDiscoverer -{ +public abstract class AbstractResourceBasedComponentDiscoverer implements ComponentDiscoverer { protected abstract String getComponentDescriptorLocation(); - protected abstract ComponentSetDescriptor createComponentDescriptors( Reader reader, String source, ClassRealm realm ) - throws PlexusConfigurationException; + protected abstract ComponentSetDescriptor createComponentDescriptors(Reader reader, String source, ClassRealm realm) + throws PlexusConfigurationException; - public List findComponents( Context context, ClassRealm realm ) - throws PlexusConfigurationException - { + public List findComponents(Context context, ClassRealm realm) + throws PlexusConfigurationException { List componentSetDescriptors = new ArrayList(); Enumeration resources; - - try - { - resources = realm.getResources( getComponentDescriptorLocation() ); - } - catch ( IOException e ) - { - throw new PlexusConfigurationException( "Unable to retrieve resources for: " + getComponentDescriptorLocation() + " in class realm: " + realm.getId() ); + + try { + resources = realm.getResources(getComponentDescriptorLocation()); + } catch (IOException e) { + throw new PlexusConfigurationException("Unable to retrieve resources for: " + + getComponentDescriptorLocation() + " in class realm: " + realm.getId()); } - for ( URL url : Collections.list( resources )) - { + for (URL url : Collections.list(resources)) { Reader reader = null; - - try - { + + try { URLConnection conn = url.openConnection(); - conn.setUseCaches( false ); + conn.setUseCaches(false); conn.connect(); - reader = ReaderFactory.newXmlReader( conn.getInputStream() ); + reader = ReaderFactory.newXmlReader(conn.getInputStream()); - InterpolationFilterReader interpolationFilterReader = new InterpolationFilterReader( reader, new ContextMapAdapter( context ) ); + InterpolationFilterReader interpolationFilterReader = + new InterpolationFilterReader(reader, new ContextMapAdapter(context)); - ComponentSetDescriptor componentSetDescriptor = createComponentDescriptors( interpolationFilterReader, url.toString(), realm ); + ComponentSetDescriptor componentSetDescriptor = + createComponentDescriptors(interpolationFilterReader, url.toString(), realm); - componentSetDescriptors.add( componentSetDescriptor ); - } - catch ( IOException ex ) - { - throw new PlexusConfigurationException( "Error reading configuration " + url, ex ); - } - finally - { - IOUtil.close( reader ); + componentSetDescriptors.add(componentSetDescriptor); + } catch (IOException ex) { + throw new PlexusConfigurationException("Error reading configuration " + url, ex); + } finally { + IOUtil.close(reader); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/AnnotationBasedComponentDiscoverer.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/AnnotationBasedComponentDiscoverer.java index 1fbfbd4b4..3b0230685 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/AnnotationBasedComponentDiscoverer.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/AnnotationBasedComponentDiscoverer.java @@ -2,10 +2,7 @@ /** * Component discoverer which relies on annotation information to define component definitions. - * + * * @author jvanzyl */ -public interface AnnotationBasedComponentDiscoverer - extends ComponentDiscoverer -{ -} +public interface AnnotationBasedComponentDiscoverer extends ComponentDiscoverer {} diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscoverer.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscoverer.java index 9cb248a07..f3c63e1bb 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscoverer.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscoverer.java @@ -16,18 +16,17 @@ * limitations under the License. */ +import java.util.List; + import org.codehaus.plexus.classworlds.realm.ClassRealm; +import org.codehaus.plexus.component.repository.ComponentSetDescriptor; import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.codehaus.plexus.context.Context; -import org.codehaus.plexus.component.repository.ComponentSetDescriptor; - -import java.util.List; /** * @author Jason van Zyl */ -public interface ComponentDiscoverer -{ - List findComponents( Context context, ClassRealm classRealm ) - throws PlexusConfigurationException; +public interface ComponentDiscoverer { + List findComponents(Context context, ClassRealm classRealm) + throws PlexusConfigurationException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscovererManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscovererManager.java index 0be53328f..c4a72eb02 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscovererManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscovererManager.java @@ -22,18 +22,17 @@ /** * ComponentDiscovererManager is a simple index (registry) of ComponentDiscovers and ComponentDiscoveryListener. */ -public interface ComponentDiscovererManager -{ - void addComponentDiscoverer( ComponentDiscoverer componentDiscoverer ); +public interface ComponentDiscovererManager { + void addComponentDiscoverer(ComponentDiscoverer componentDiscoverer); List getComponentDiscoverers(); // todo dain change this to Set (requires change to maven) Map getComponentDiscoveryListeners(); - void registerComponentDiscoveryListener( ComponentDiscoveryListener listener); + void registerComponentDiscoveryListener(ComponentDiscoveryListener listener); - void removeComponentDiscoveryListener( ComponentDiscoveryListener listener ); + void removeComponentDiscoveryListener(ComponentDiscoveryListener listener); - void fireComponentDiscoveryEvent( ComponentDiscoveryEvent event ); + void fireComponentDiscoveryEvent(ComponentDiscoveryEvent event); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscoveryEvent.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscoveryEvent.java index 783432b46..a47ce3f12 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscoveryEvent.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscoveryEvent.java @@ -23,8 +23,7 @@ * involving a set of components. It is up to the Listener to decide what * to do with that information. */ -public class ComponentDiscoveryEvent -{ +public class ComponentDiscoveryEvent { private ComponentSetDescriptor componentSetDescriptor; private Object data; @@ -34,13 +33,11 @@ public class ComponentDiscoveryEvent * ComponentDescriptors. * @param componentSetDescriptor a set of ComponentDescriptors */ - public ComponentDiscoveryEvent( ComponentSetDescriptor componentSetDescriptor ) - { + public ComponentDiscoveryEvent(ComponentSetDescriptor componentSetDescriptor) { this.componentSetDescriptor = componentSetDescriptor; } - public ComponentDiscoveryEvent( ComponentSetDescriptor componentSetDescriptor, Object data ) - { + public ComponentDiscoveryEvent(ComponentSetDescriptor componentSetDescriptor, Object data) { this.componentSetDescriptor = componentSetDescriptor; this.data = data; } @@ -49,13 +46,11 @@ public ComponentDiscoveryEvent( ComponentSetDescriptor componentSetDescriptor, O * Returns this event's set of ComponentDescriptors. * @return this event's set of ComponentDescriptors */ - public ComponentSetDescriptor getComponentSetDescriptor() - { + public ComponentSetDescriptor getComponentSetDescriptor() { return componentSetDescriptor; } - public Object getData() - { + public Object getData() { return data; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscoveryListener.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscoveryListener.java index bfbd9a75f..02ce760ae 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscoveryListener.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ComponentDiscoveryListener.java @@ -19,11 +19,10 @@ /** * A listener which responds in some way to component discovery by a PlexusContainer. */ -public interface ComponentDiscoveryListener -{ +public interface ComponentDiscoveryListener { /** * Signals to this listener that a component has been discovered. * @param event the event that signals what components have been discovered */ - void componentDiscovered( ComponentDiscoveryEvent event ); + void componentDiscovered(ComponentDiscoveryEvent event); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/DefaultComponentDiscoverer.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/DefaultComponentDiscoverer.java index a975a90ec..40a040825 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/DefaultComponentDiscoverer.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/DefaultComponentDiscoverer.java @@ -16,70 +16,64 @@ * limitations under the License. */ +import java.io.Reader; +import java.util.ArrayList; +import java.util.List; + +import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.ComponentSetDescriptor; import org.codehaus.plexus.component.repository.io.PlexusTools; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.PlexusConfigurationException; -import org.codehaus.plexus.classworlds.realm.ClassRealm; - -import java.io.Reader; -import java.util.ArrayList; -import java.util.List; /** * @author Jason van Zyl */ -public class DefaultComponentDiscoverer - extends AbstractResourceBasedComponentDiscoverer -{ - public String getComponentDescriptorLocation() - { +public class DefaultComponentDiscoverer extends AbstractResourceBasedComponentDiscoverer { + public String getComponentDescriptorLocation() { return "META-INF/plexus/components.xml"; } - public ComponentSetDescriptor createComponentDescriptors( Reader componentDescriptorReader, String source, ClassRealm realm ) - throws PlexusConfigurationException - { - PlexusConfiguration componentDescriptorConfiguration = PlexusTools.buildConfiguration( source, componentDescriptorReader ); + public ComponentSetDescriptor createComponentDescriptors( + Reader componentDescriptorReader, String source, ClassRealm realm) throws PlexusConfigurationException { + PlexusConfiguration componentDescriptorConfiguration = + PlexusTools.buildConfiguration(source, componentDescriptorReader); ComponentSetDescriptor componentSetDescriptor = new ComponentSetDescriptor(); List> componentDescriptors = new ArrayList>(); - PlexusConfiguration[] componentConfigurations = componentDescriptorConfiguration.getChild( "components" ).getChildren( "component" ); + PlexusConfiguration[] componentConfigurations = + componentDescriptorConfiguration.getChild("components").getChildren("component"); - for ( PlexusConfiguration componentConfiguration : componentConfigurations ) - { + for (PlexusConfiguration componentConfiguration : componentConfigurations) { ComponentDescriptor componentDescriptor; - try - { - componentDescriptor = PlexusTools.buildComponentDescriptor( componentConfiguration, realm ); - } - catch ( PlexusConfigurationException e ) - { - // This is not the most accurate of exceptions as the only real case where this exception - // will be thrown is when the implementation class of the component sited cannot be loaded. - // In the case where role and implementation classes do not exist then we just shouldn't - // create the component descriptor. All information should be taken from annotations which - // will be correct, so in the case we can't load the class it must be coming from and older - // hand written descriptor which is incorrect. - - continue; + try { + componentDescriptor = PlexusTools.buildComponentDescriptor(componentConfiguration, realm); + } catch (PlexusConfigurationException e) { + // This is not the most accurate of exceptions as the only real case where this exception + // will be thrown is when the implementation class of the component sited cannot be loaded. + // In the case where role and implementation classes do not exist then we just shouldn't + // create the component descriptor. All information should be taken from annotations which + // will be correct, so in the case we can't load the class it must be coming from and older + // hand written descriptor which is incorrect. + + continue; } - componentDescriptor.setSource( source ); + componentDescriptor.setSource(source); - componentDescriptor.setComponentType( "plexus" ); + componentDescriptor.setComponentType("plexus"); - componentDescriptor.setComponentSetDescriptor( componentSetDescriptor ); + componentDescriptor.setComponentSetDescriptor(componentSetDescriptor); - componentDescriptors.add( componentDescriptor ); + componentDescriptors.add(componentDescriptor); } - componentSetDescriptor.setComponents( componentDescriptors ); + componentSetDescriptor.setComponents(componentDescriptors); - componentSetDescriptor.setSource( source ); + componentSetDescriptor.setSource(source); return componentSetDescriptor; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/DefaultComponentDiscovererManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/DefaultComponentDiscovererManager.java index 51e194ad0..6ed22f80d 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/DefaultComponentDiscovererManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/DefaultComponentDiscovererManager.java @@ -17,62 +17,52 @@ */ import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; -import java.util.Set; import java.util.Map; -import java.util.LinkedHashMap; +import java.util.Set; -public class DefaultComponentDiscovererManager - implements ComponentDiscovererManager -{ +public class DefaultComponentDiscovererManager implements ComponentDiscovererManager { private final List componentDiscoverers = new ArrayList(); // todo dain change this to LinkedHashSet (requires change to maven) - private final Map listeners = new LinkedHashMap(); + private final Map listeners = + new LinkedHashMap(); - public synchronized void addComponentDiscoverer( ComponentDiscoverer discoverer ) - { - componentDiscoverers.add( discoverer ); + public synchronized void addComponentDiscoverer(ComponentDiscoverer discoverer) { + componentDiscoverers.add(discoverer); } // todo this is not thread safe... we are returning the raw collection - public synchronized List getComponentDiscoverers() - { + public synchronized List getComponentDiscoverers() { return componentDiscoverers; } // Listeners // todo this is not thread safe... we are returning the raw collection - public synchronized Map getComponentDiscoveryListeners() - { + public synchronized Map getComponentDiscoveryListeners() { return listeners; } - public synchronized void registerComponentDiscoveryListener( ComponentDiscoveryListener listener ) - { - if ( !listeners.containsKey( listener ) ) - { - listeners.put( listener, new Object() ); + public synchronized void registerComponentDiscoveryListener(ComponentDiscoveryListener listener) { + if (!listeners.containsKey(listener)) { + listeners.put(listener, new Object()); } } - public synchronized void removeComponentDiscoveryListener( ComponentDiscoveryListener listener ) - { - listeners.remove( listener ); + public synchronized void removeComponentDiscoveryListener(ComponentDiscoveryListener listener) { + listeners.remove(listener); } - public void fireComponentDiscoveryEvent( ComponentDiscoveryEvent event ) - { + public void fireComponentDiscoveryEvent(ComponentDiscoveryEvent event) { Set listeners; - synchronized ( this ) - { + synchronized (this) { listeners = this.listeners.keySet(); } - for ( ComponentDiscoveryListener listener : listeners ) - { - listener.componentDiscovered( event ); + for (ComponentDiscoveryListener listener : listeners) { + listener.componentDiscovered(event); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/DiscoveryListenerDescriptor.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/DiscoveryListenerDescriptor.java index c0a4f2359..a2e7135e5 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/DiscoveryListenerDescriptor.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/DiscoveryListenerDescriptor.java @@ -20,19 +20,16 @@ * @author Jason van Zyl * */ -public class DiscoveryListenerDescriptor -{ +public class DiscoveryListenerDescriptor { private String role; private String roleHint; - public String getRole() - { + public String getRole() { return role; } - public String getRoleHint() - { + public String getRoleHint() { return roleHint; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/PlexusXmlComponentDiscoverer.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/PlexusXmlComponentDiscoverer.java index 778911312..e812c0d00 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/PlexusXmlComponentDiscoverer.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/PlexusXmlComponentDiscoverer.java @@ -2,12 +2,12 @@ /* * Copyright 2001-2006 Codehaus 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 @@ -24,49 +24,43 @@ import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.PlexusConfigurationException; -public class PlexusXmlComponentDiscoverer - extends AbstractResourceBasedComponentDiscoverer -{ - public String getComponentDescriptorLocation() - { +public class PlexusXmlComponentDiscoverer extends AbstractResourceBasedComponentDiscoverer { + public String getComponentDescriptorLocation() { return "META-INF/plexus/plexus.xml"; } @Override - protected ComponentSetDescriptor createComponentDescriptors( Reader reader, String source, ClassRealm realm ) - throws PlexusConfigurationException - { + protected ComponentSetDescriptor createComponentDescriptors(Reader reader, String source, ClassRealm realm) + throws PlexusConfigurationException { ComponentSetDescriptor componentSetDescriptor = new ComponentSetDescriptor(); - PlexusConfiguration configuration = PlexusTools.buildConfiguration( source, reader ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration(source, reader); - if ( configuration != null ) - { - PlexusConfiguration[] componentConfigurations = configuration.getChild( "components" ).getChildren( "component" ); + if (configuration != null) { + PlexusConfiguration[] componentConfigurations = + configuration.getChild("components").getChildren("component"); - for ( PlexusConfiguration componentConfiguration : componentConfigurations ) - { + for (PlexusConfiguration componentConfiguration : componentConfigurations) { ComponentDescriptor componentDescriptor; - - try - { - componentDescriptor = PlexusTools.buildComponentDescriptor( componentConfiguration, realm ); - if ( componentDescriptor == null ) - { + try { + componentDescriptor = PlexusTools.buildComponentDescriptor(componentConfiguration, realm); + + if (componentDescriptor == null) { continue; } - } - catch ( PlexusConfigurationException e ) - { - throw new PlexusConfigurationException( "Cannot build component descriptor from resource found in:\n" + Arrays.asList( realm.getURLs() ), e ); + } catch (PlexusConfigurationException e) { + throw new PlexusConfigurationException( + "Cannot build component descriptor from resource found in:\n" + + Arrays.asList(realm.getURLs()), + e); } - componentDescriptor.setComponentType( "plexus" ); + componentDescriptor.setComponentType("plexus"); - componentDescriptor.setComponentSetDescriptor( componentSetDescriptor ); + componentDescriptor.setComponentSetDescriptor(componentSetDescriptor); - componentSetDescriptor.addComponentDescriptor( componentDescriptor ); + componentSetDescriptor.addComponentDescriptor(componentDescriptor); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ResourceBasedComponentDiscoverer.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ResourceBasedComponentDiscoverer.java index 2626ef846..02edfb1fa 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ResourceBasedComponentDiscoverer.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/discovery/ResourceBasedComponentDiscoverer.java @@ -3,11 +3,9 @@ /** * Component discoverer which relies on the metadata for the components residing in a resource that * can be found in a classloader. - * + * * @author jvanzyl */ -public interface ResourceBasedComponentDiscoverer - extends ComponentDiscoverer -{ +public interface ResourceBasedComponentDiscoverer extends ComponentDiscoverer { String getComponentDescriptorLocation(); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/AbstractComponentFactory.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/AbstractComponentFactory.java index 5a870a9e9..68bce9d94 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/AbstractComponentFactory.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/AbstractComponentFactory.java @@ -27,24 +27,21 @@ * @author Jason van Zyl * */ -public abstract class AbstractComponentFactory - implements ComponentFactory -{ +public abstract class AbstractComponentFactory implements ComponentFactory { // This is for backward compatibility private String id; - public Object newInstance( ComponentDescriptor componentDescriptor, ClassRealm classRealm, PlexusContainer container ) - throws ComponentInstantiationException - { + public Object newInstance(ComponentDescriptor componentDescriptor, ClassRealm classRealm, PlexusContainer container) + throws ComponentInstantiationException { // for backward-compatibility with the old component factories delegate to the old-style method - return newInstance( componentDescriptor, ClassRealmAdapter.getInstance( classRealm ), container ); + return newInstance(componentDescriptor, ClassRealmAdapter.getInstance(classRealm), container); } - protected Object newInstance( ComponentDescriptor componentDescriptor, - org.codehaus.classworlds.ClassRealm classRealm, PlexusContainer container ) - throws ComponentInstantiationException - { - throw new IllegalStateException( getClass().getName() + " does not implement component creation." ); + protected Object newInstance( + ComponentDescriptor componentDescriptor, + org.codehaus.classworlds.ClassRealm classRealm, + PlexusContainer container) + throws ComponentInstantiationException { + throw new IllegalStateException(getClass().getName() + " does not implement component creation."); } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/ComponentFactory.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/ComponentFactory.java index 66efd4ccc..d4545b9a8 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/ComponentFactory.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/ComponentFactory.java @@ -27,13 +27,12 @@ * * @version $Id$ */ -public interface ComponentFactory -{ +public interface ComponentFactory { /** Component role. */ static String ROLE = ComponentFactory.class.getName(); String getId(); - Object newInstance( ComponentDescriptor componentDescriptor, ClassRealm classRealm, PlexusContainer container ) - throws ComponentInstantiationException; + Object newInstance(ComponentDescriptor componentDescriptor, ClassRealm classRealm, PlexusContainer container) + throws ComponentInstantiationException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/ComponentFactoryManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/ComponentFactoryManager.java index 2b10432b6..7f6a36add 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/ComponentFactoryManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/ComponentFactoryManager.java @@ -22,8 +22,6 @@ * @author Jason van Zyl * */ -public interface ComponentFactoryManager -{ - ComponentFactory findComponentFactory( String id ) - throws UndefinedComponentFactoryException; +public interface ComponentFactoryManager { + ComponentFactory findComponentFactory(String id) throws UndefinedComponentFactoryException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/ComponentInstantiationException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/ComponentInstantiationException.java index 20fb20708..a226a160f 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/ComponentInstantiationException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/ComponentInstantiationException.java @@ -18,25 +18,20 @@ /** * - * + * * @author Michal Maczka * */ -public class ComponentInstantiationException - extends Exception -{ - public ComponentInstantiationException( String message ) - { - super( message ); +public class ComponentInstantiationException extends Exception { + public ComponentInstantiationException(String message) { + super(message); } - public ComponentInstantiationException( String message, Throwable cause ) - { - super( message, cause ); + public ComponentInstantiationException(String message, Throwable cause) { + super(message, cause); } - public ComponentInstantiationException( Throwable cause ) - { - super( cause ); + public ComponentInstantiationException(Throwable cause) { + super(cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/DefaultComponentFactoryManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/DefaultComponentFactoryManager.java index c4f82f5ec..5db9fc347 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/DefaultComponentFactoryManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/DefaultComponentFactoryManager.java @@ -27,34 +27,24 @@ /** * @author Jason van Zyl */ -public class DefaultComponentFactoryManager - implements ComponentFactoryManager, Contextualizable -{ +public class DefaultComponentFactoryManager implements ComponentFactoryManager, Contextualizable { private ComponentFactory defaultComponentFactory = new JavaComponentFactory(); private PlexusContainer container; - public ComponentFactory findComponentFactory( String id ) - throws UndefinedComponentFactoryException - { - if ( id == null || id.equals( "java" ) ) - { + public ComponentFactory findComponentFactory(String id) throws UndefinedComponentFactoryException { + if (id == null || id.equals("java")) { return defaultComponentFactory; } - try - { - return container.lookup( ComponentFactory.class, id ); - } - catch ( ComponentLookupException e ) - { - throw new UndefinedComponentFactoryException( "Specified component factory cannot be found: " + id ); + try { + return container.lookup(ComponentFactory.class, id); + } catch (ComponentLookupException e) { + throw new UndefinedComponentFactoryException("Specified component factory cannot be found: " + id); } } - public void contextualize( Context context ) - throws ContextException - { - container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); + public void contextualize(Context context) throws ContextException { + container = (PlexusContainer) context.get(PlexusConstants.PLEXUS_KEY); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/UndefinedComponentFactoryException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/UndefinedComponentFactoryException.java index 66eaf4ab0..a1b50e748 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/UndefinedComponentFactoryException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/UndefinedComponentFactoryException.java @@ -18,25 +18,20 @@ /** * - * + * * @author Jason van Zyl * */ -public class UndefinedComponentFactoryException - extends Exception -{ - public UndefinedComponentFactoryException( String message ) - { - super( message ); +public class UndefinedComponentFactoryException extends Exception { + public UndefinedComponentFactoryException(String message) { + super(message); } - public UndefinedComponentFactoryException( String message, Throwable cause ) - { - super( message, cause ); + public UndefinedComponentFactoryException(String message, Throwable cause) { + super(message, cause); } - public UndefinedComponentFactoryException( Throwable cause ) - { - super( cause ); + public UndefinedComponentFactoryException(Throwable cause) { + super(cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/java/JavaComponentFactory.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/java/JavaComponentFactory.java index 390ffee18..82250064d 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/java/JavaComponentFactory.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/factory/java/JavaComponentFactory.java @@ -16,84 +16,67 @@ * limitations under the License. */ +import java.lang.reflect.Modifier; + import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.factory.AbstractComponentFactory; import org.codehaus.plexus.component.factory.ComponentInstantiationException; import org.codehaus.plexus.component.repository.ComponentDescriptor; -import java.lang.reflect.Modifier; - /** * Component Factory for components written in Java Language which have default no parameter constructor * * @author Jason van Zyl * @author Michal Maczka */ -public class JavaComponentFactory - extends AbstractComponentFactory -{ - public String getId() - { +public class JavaComponentFactory extends AbstractComponentFactory { + public String getId() { return "java"; } - public Object newInstance( ComponentDescriptor componentDescriptor, - ClassRealm classRealm, - PlexusContainer container ) - throws ComponentInstantiationException - { + public Object newInstance(ComponentDescriptor componentDescriptor, ClassRealm classRealm, PlexusContainer container) + throws ComponentInstantiationException { Class implementationClass = null; - try - { + try { String implementation = componentDescriptor.getImplementation(); - implementationClass = classRealm.loadClass( implementation ); + implementationClass = classRealm.loadClass(implementation); int modifiers = implementationClass.getModifiers(); - if ( Modifier.isInterface( modifiers ) ) - { + if (Modifier.isInterface(modifiers)) { throw new ComponentInstantiationException( - "Cannot instantiate implementation '" + implementation + "' because the class is a interface." ); + "Cannot instantiate implementation '" + implementation + "' because the class is a interface."); } - if ( Modifier.isAbstract( modifiers ) ) - { + if (Modifier.isAbstract(modifiers)) { throw new ComponentInstantiationException( - "Cannot instantiate implementation '" + implementation + "' because the class is abstract." ); + "Cannot instantiate implementation '" + implementation + "' because the class is abstract."); } Object instance = implementationClass.newInstance(); return instance; - } - catch ( InstantiationException e ) - { - //PLXAPI: most probably cause of this is the implementation class not having + } catch (InstantiationException e) { + // PLXAPI: most probably cause of this is the implementation class not having // a default constructor. - throw makeException( classRealm, componentDescriptor, implementationClass, e ); - } - catch ( ClassNotFoundException e ) - { - throw makeException( classRealm, componentDescriptor, implementationClass, e ); - } - catch ( IllegalAccessException e ) - { - throw makeException( classRealm, componentDescriptor, implementationClass, e ); - } - catch ( LinkageError e ) - { - throw makeException( classRealm, componentDescriptor, implementationClass, e ); + throw makeException(classRealm, componentDescriptor, implementationClass, e); + } catch (ClassNotFoundException e) { + throw makeException(classRealm, componentDescriptor, implementationClass, e); + } catch (IllegalAccessException e) { + throw makeException(classRealm, componentDescriptor, implementationClass, e); + } catch (LinkageError e) { + throw makeException(classRealm, componentDescriptor, implementationClass, e); } } - private ComponentInstantiationException makeException( ClassRealm componentClassRealm, - ComponentDescriptor componentDescriptor, - Class implementationClass, - Throwable e ) - { + private ComponentInstantiationException makeException( + ClassRealm componentClassRealm, + ComponentDescriptor componentDescriptor, + Class implementationClass, + Throwable e) { // ---------------------------------------------------------------------- // Display the realm when there is an error, We should probably return a string here so we // can incorporate this into the error message for easy debugging. @@ -101,16 +84,13 @@ private ComponentInstantiationException makeException( ClassRealm componentClass String msg; - if ( componentClassRealm == null ) - { + if (componentClassRealm == null) { msg = "classRealm is null for " + componentDescriptor; - } - else - { + } else { msg = "Could not instantiate component: " + componentDescriptor.getHumanReadableKey() + " realm: " - + componentClassRealm.getId(); + + componentClassRealm.getId(); } - return new ComponentInstantiationException( msg, e ); + return new ComponentInstantiationException(msg, e); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/AbstractComponentManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/AbstractComponentManager.java index 35ee2cb92..381a8ab6d 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/AbstractComponentManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/AbstractComponentManager.java @@ -1,20 +1,26 @@ package org.codehaus.plexus.component.manager; /* -* Copyright 2001-2006 Codehaus 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. -*/ + * Copyright 2001-2006 Codehaus 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. + */ + +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; import org.codehaus.plexus.MutablePlexusContainer; import org.codehaus.plexus.classworlds.realm.ClassRealm; @@ -28,15 +34,7 @@ import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.personality.plexus.lifecycle.phase.PhaseExecutionException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; - -public abstract class AbstractComponentManager - implements ComponentManager -{ +public abstract class AbstractComponentManager implements ComponentManager { protected final MutablePlexusContainer container; private final ClassRealm realm; @@ -46,12 +44,11 @@ public abstract class AbstractComponentManager private final Class type; private final String role; - + private final String roleHint; protected final ComponentBuilder builder = new XBeanComponentBuilder(this); - private final LifecycleHandler lifecycleHandler; /** @@ -60,45 +57,41 @@ public abstract class AbstractComponentManager * call all lifecycle methods. * This will define a synchronized map, make sure to synchronize the map when iterating. */ - protected final Map componentContextRealms = Collections.synchronizedMap(new HashMap()); + protected final Map componentContextRealms = + Collections.synchronizedMap(new HashMap()); private int connections; private long startId; - public AbstractComponentManager( MutablePlexusContainer container, - LifecycleHandler lifecycleHandler, - ComponentDescriptor componentDescriptor, - String role, - String roleHint) - { - if ( container == null ) - { - throw new NullPointerException( "container is null" ); + public AbstractComponentManager( + MutablePlexusContainer container, + LifecycleHandler lifecycleHandler, + ComponentDescriptor componentDescriptor, + String role, + String roleHint) { + if (container == null) { + throw new NullPointerException("container is null"); } this.container = container; - if ( lifecycleHandler == null ) - { - throw new NullPointerException( "lifecycleHandler is null" ); + if (lifecycleHandler == null) { + throw new NullPointerException("lifecycleHandler is null"); } this.lifecycleHandler = lifecycleHandler; - if ( componentDescriptor == null ) - { - throw new NullPointerException( "componentDescriptor is null" ); + if (componentDescriptor == null) { + throw new NullPointerException("componentDescriptor is null"); } this.componentDescriptor = componentDescriptor; - if ( role == null ) - { - throw new NullPointerException( "role is null" ); + if (role == null) { + throw new NullPointerException("role is null"); } this.role = role; - if ( roleHint == null ) - { - throw new NullPointerException( "roleHint is null" ); + if (roleHint == null) { + throw new NullPointerException("roleHint is null"); } this.roleHint = roleHint; @@ -107,53 +100,43 @@ public AbstractComponentManager( MutablePlexusContainer container, this.type = componentDescriptor.getImplementationClass(); } - public ComponentDescriptor getComponentDescriptor() - { + public ComponentDescriptor getComponentDescriptor() { return componentDescriptor; } - public Class getType() - { + public Class getType() { return type; } - public ClassRealm getRealm() - { + public ClassRealm getRealm() { return realm; } - public String getRole() - { + public String getRole() { return role; } - public String getRoleHint() - { + public String getRoleHint() { return roleHint; } - public LifecycleHandler getLifecycleHandler() - { + public LifecycleHandler getLifecycleHandler() { return lifecycleHandler; } - protected void incrementConnectionCount() - { + protected void incrementConnectionCount() { connections++; } - protected void decrementConnectionCount() - { + protected void decrementConnectionCount() { connections--; } - protected boolean connected() - { + protected boolean connected() { return connections > 0; } - public int getConnections() - { + public int getConnections() { return connections; } @@ -161,71 +144,57 @@ public int getConnections() // Lifecylce Management // ---------------------------------------------------------------------- - public void start( Object component ) throws PhaseExecutionException - { + public void start(Object component) throws PhaseExecutionException { startId = NEXT_START_ID.getAndIncrement(); - getLifecycleHandler().start( component, this, componentDescriptor.getRealm() ); + getLifecycleHandler().start(component, this, componentDescriptor.getRealm()); } /** * @deprecated for internal use only.. will be removed */ - public long getStartId() - { + public long getStartId() { return startId; } - protected T createComponentInstance() - throws ComponentInstantiationException, ComponentLifecycleException - { + protected T createComponentInstance() throws ComponentInstantiationException, ComponentLifecycleException { return builder.build(componentDescriptor, realm, new AbstractComponentBuildListener() { - public void componentCreated( ComponentDescriptor componentDescriptor, Object component, ClassRealm realm) { - componentContextRealms.put( component, realm ); + public void componentCreated( + ComponentDescriptor componentDescriptor, Object component, ClassRealm realm) { + componentContextRealms.put(component, realm); } }); } - protected void endComponentLifecycle( Object component ) - throws ComponentLifecycleException - { - ClassRealm contextRealm = componentContextRealms.remove( component ); - if ( contextRealm == null ) - { - contextRealm = container.getLookupRealm( component ); + protected void endComponentLifecycle(Object component) throws ComponentLifecycleException { + ClassRealm contextRealm = componentContextRealms.remove(component); + if (contextRealm == null) { + contextRealm = container.getLookupRealm(component); } - try - { - getLifecycleHandler().end( component, this, contextRealm ); - } - catch ( PhaseExecutionException e ) - { - throw new ComponentLifecycleException( "Error ending component lifecycle", e ); + try { + getLifecycleHandler().end(component, this, contextRealm); + } catch (PhaseExecutionException e) { + throw new ComponentLifecycleException("Error ending component lifecycle", e); } } - public MutablePlexusContainer getContainer() - { + public MutablePlexusContainer getContainer() { return container; } - public Logger getLogger() - { + public Logger getLogger() { return container.getLogger(); } - public void dissociateComponentRealm( ClassRealm realm ) - throws ComponentLifecycleException - { - synchronized ( componentContextRealms ) - { - for ( Iterator> iterator = componentContextRealms.entrySet().iterator(); iterator.hasNext(); ) - { + public void dissociateComponentRealm(ClassRealm realm) throws ComponentLifecycleException { + synchronized (componentContextRealms) { + for (Iterator> iterator = + componentContextRealms.entrySet().iterator(); + iterator.hasNext(); ) { Entry entry = iterator.next(); ClassRealm componentRealm = entry.getValue(); - if ( componentRealm.getId().equals( realm.getId() ) ) - { + if (componentRealm.getId().equals(realm.getId())) { iterator.remove(); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/ComponentManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/ComponentManager.java index 15c9499de..c79ca59bd 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/ComponentManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/ComponentManager.java @@ -1,6 +1,5 @@ package org.codehaus.plexus.component.manager; - /* * Copyright 2001-2006 Codehaus Foundation. * @@ -17,15 +16,15 @@ * limitations under the License. */ +import java.util.concurrent.atomic.AtomicLong; + import org.codehaus.plexus.MutablePlexusContainer; -import org.codehaus.plexus.personality.plexus.lifecycle.phase.PhaseExecutionException; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.factory.ComponentInstantiationException; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.lifecycle.LifecycleHandler; - -import java.util.concurrent.atomic.AtomicLong; +import org.codehaus.plexus.personality.plexus.lifecycle.phase.PhaseExecutionException; /** * Manages a component manager. @@ -36,14 +35,13 @@ * @author Jason van Zyl * */ -public interface ComponentManager -{ +public interface ComponentManager { String ROLE = ComponentManager.class.getName(); /** * @deprecated for internal use only.. will be removed */ - AtomicLong NEXT_START_ID = new AtomicLong( 1 ); + AtomicLong NEXT_START_ID = new AtomicLong(1); int getConnections(); @@ -53,11 +51,9 @@ public interface ComponentManager */ LifecycleHandler getLifecycleHandler(); - void dispose() - throws ComponentLifecycleException; + void dispose() throws ComponentLifecycleException; - void release( Object component ) - throws ComponentLifecycleException; + void release(Object component) throws ComponentLifecycleException; T getComponent() throws ComponentInstantiationException, ComponentLifecycleException; @@ -71,8 +67,7 @@ void release( Object component ) MutablePlexusContainer getContainer(); - void dissociateComponentRealm( ClassRealm realm ) - throws ComponentLifecycleException; + void dissociateComponentRealm(ClassRealm realm) throws ComponentLifecycleException; ClassRealm getRealm(); @@ -83,4 +78,4 @@ void dissociateComponentRealm( ClassRealm realm ) * @deprecated for internal use only.. will be removed */ long getStartId(); -} \ No newline at end of file +} diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/ComponentManagerFactory.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/ComponentManagerFactory.java index 328ea6982..ae8aaf05f 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/ComponentManagerFactory.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/ComponentManagerFactory.java @@ -4,8 +4,7 @@ import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.lifecycle.LifecycleHandler; -public interface ComponentManagerFactory -{ +public interface ComponentManagerFactory { /** * Gets the unique identifier of this ComponentManagerFactory. This id is the instantiation strategy specified * in a component descriptor. @@ -23,9 +22,10 @@ public interface ComponentManagerFactory * @param The type. * @return {@link ComponentManager} */ - ComponentManager createComponentManager( MutablePlexusContainer container, - LifecycleHandler lifecycleHandler, - ComponentDescriptor componentDescriptor, - String role, - String roleHint ); + ComponentManager createComponentManager( + MutablePlexusContainer container, + LifecycleHandler lifecycleHandler, + ComponentDescriptor componentDescriptor, + String role, + String roleHint); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/PerLookupComponentManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/PerLookupComponentManager.java index 300f89dcc..1abd43c08 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/PerLookupComponentManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/PerLookupComponentManager.java @@ -16,10 +16,10 @@ * limitations under the License. */ +import org.codehaus.plexus.MutablePlexusContainer; import org.codehaus.plexus.component.factory.ComponentInstantiationException; -import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.ComponentDescriptor; -import org.codehaus.plexus.MutablePlexusContainer; +import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.lifecycle.LifecycleHandler; /** @@ -28,36 +28,28 @@ * @author Jason van Zyl * */ -public class PerLookupComponentManager - extends AbstractComponentManager -{ - public PerLookupComponentManager( MutablePlexusContainer container, - LifecycleHandler lifecycleHandler, - ComponentDescriptor componentDescriptor, - String role, - String roleHint ) - { - super( container, lifecycleHandler, componentDescriptor, role, roleHint ); +public class PerLookupComponentManager extends AbstractComponentManager { + public PerLookupComponentManager( + MutablePlexusContainer container, + LifecycleHandler lifecycleHandler, + ComponentDescriptor componentDescriptor, + String role, + String roleHint) { + super(container, lifecycleHandler, componentDescriptor, role, roleHint); } - public void dispose() - { - } + public void dispose() {} - public T getComponent( ) - throws ComponentInstantiationException, ComponentLifecycleException - { + public T getComponent() throws ComponentInstantiationException, ComponentLifecycleException { T component = createComponentInstance(); return component; } - public void release( Object component ) - throws ComponentLifecycleException - { + public void release(Object component) throws ComponentLifecycleException { decrementConnectionCount(); - endComponentLifecycle( component ); + endComponentLifecycle(component); // non cleanup map references for per-lookup cause leak - componentContextRealms.remove( component ); + componentContextRealms.remove(component); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/PerLookupComponentManagerFactory.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/PerLookupComponentManagerFactory.java index 69f180ba6..414a5f0e0 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/PerLookupComponentManagerFactory.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/PerLookupComponentManagerFactory.java @@ -4,20 +4,18 @@ import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.lifecycle.LifecycleHandler; -public class PerLookupComponentManagerFactory implements ComponentManagerFactory -{ - public String getId() - { +public class PerLookupComponentManagerFactory implements ComponentManagerFactory { + public String getId() { return "per-lookup"; } @SuppressWarnings({"RawUseOfParameterizedType"}) - public ComponentManager createComponentManager( MutablePlexusContainer container, - LifecycleHandler lifecycleHandler, - ComponentDescriptor componentDescriptor, - String role, - String roleHint ) - { - return new PerLookupComponentManager( container, lifecycleHandler, componentDescriptor, role, roleHint ); + public ComponentManager createComponentManager( + MutablePlexusContainer container, + LifecycleHandler lifecycleHandler, + ComponentDescriptor componentDescriptor, + String role, + String roleHint) { + return new PerLookupComponentManager(container, lifecycleHandler, componentDescriptor, role, roleHint); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/SingletonComponentManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/SingletonComponentManager.java index bf489d850..e0ff6c2a8 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/SingletonComponentManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/SingletonComponentManager.java @@ -2,68 +2,57 @@ /* * Copyright 2001-2006 Codehaus 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. */ +import org.codehaus.plexus.MutablePlexusContainer; import org.codehaus.plexus.component.factory.ComponentInstantiationException; -import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.ComponentDescriptor; -import org.codehaus.plexus.MutablePlexusContainer; +import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.lifecycle.LifecycleHandler; /** * This ensures a component is only used as a singleton, and is only shutdown when the container * shuts down. - * + * * @author Jason van Zyl */ -public class SingletonComponentManager - extends AbstractComponentManager -{ +public class SingletonComponentManager extends AbstractComponentManager { private T singleton; - public SingletonComponentManager( MutablePlexusContainer container, - LifecycleHandler lifecycleHandler, - ComponentDescriptor componentDescriptor, - String role, - String roleHint ) - { - super( container, lifecycleHandler, componentDescriptor, role, roleHint ); + public SingletonComponentManager( + MutablePlexusContainer container, + LifecycleHandler lifecycleHandler, + ComponentDescriptor componentDescriptor, + String role, + String roleHint) { + super(container, lifecycleHandler, componentDescriptor, role, roleHint); } - public synchronized void release( Object component ) - throws ComponentLifecycleException - { - if ( singleton == component ) - { + public synchronized void release(Object component) throws ComponentLifecycleException { + if (singleton == component) { dispose(); } } - public synchronized void dispose() - throws ComponentLifecycleException - { - if ( singleton != null ) - { - endComponentLifecycle( singleton ); + public synchronized void dispose() throws ComponentLifecycleException { + if (singleton != null) { + endComponentLifecycle(singleton); singleton = null; } } - public synchronized T getComponent( ) - throws ComponentInstantiationException, ComponentLifecycleException - { - if ( singleton == null ) - { + public synchronized T getComponent() throws ComponentInstantiationException, ComponentLifecycleException { + if (singleton == null) { singleton = createComponentInstance(); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/SingletonComponentManagerFactory.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/SingletonComponentManagerFactory.java index db2528df3..60c12f239 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/SingletonComponentManagerFactory.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/SingletonComponentManagerFactory.java @@ -4,20 +4,18 @@ import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.lifecycle.LifecycleHandler; -public class SingletonComponentManagerFactory implements ComponentManagerFactory -{ - public String getId() - { +public class SingletonComponentManagerFactory implements ComponentManagerFactory { + public String getId() { return "singleton"; } @SuppressWarnings({"RawUseOfParameterizedType"}) - public ComponentManager createComponentManager( MutablePlexusContainer container, - LifecycleHandler lifecycleHandler, - ComponentDescriptor componentDescriptor, - String role, - String roleHint ) - { - return new SingletonComponentManager( container, lifecycleHandler, componentDescriptor, role, roleHint ); + public ComponentManager createComponentManager( + MutablePlexusContainer container, + LifecycleHandler lifecycleHandler, + ComponentDescriptor componentDescriptor, + String role, + String roleHint) { + return new SingletonComponentManager(container, lifecycleHandler, componentDescriptor, role, roleHint); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/UndefinedComponentManagerException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/UndefinedComponentManagerException.java index 11db5d581..b91f2499f 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/UndefinedComponentManagerException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/manager/UndefinedComponentManagerException.java @@ -19,11 +19,8 @@ /** * @author Jason van Zyl */ -public class UndefinedComponentManagerException - extends Exception -{ - public UndefinedComponentManagerException( String message ) - { - super( message ); +public class UndefinedComponentManagerException extends Exception { + public UndefinedComponentManagerException(String message) { + super(message); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentDependency.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentDependency.java index b3d9f05d8..e440ba371 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentDependency.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentDependency.java @@ -20,14 +20,13 @@ * This represents a project which this component depends upon to function * properly, for example, a required jar file. See Apache Maven for an * example of a dependency in action. - * + * * @author Jason van Zyl * @author Trygve Laugstøl */ -public class ComponentDependency -{ +public class ComponentDependency { private static final String DEAULT_DEPENDENCY_TYPE = "jar"; - + private String groupId; private String artifactId; @@ -41,8 +40,7 @@ public class ComponentDependency * project timeline in a group. * @return a key for an artifact */ - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } @@ -50,8 +48,7 @@ public String getArtifactId() * Sets the dependency's artifact ID. * @param artifactId the artifact ID */ - public void setArtifactId(String artifactId) - { + public void setArtifactId(String artifactId) { this.artifactId = artifactId; } @@ -59,8 +56,7 @@ public void setArtifactId(String artifactId) * Gets a key for a group, which represents a set of artifacts timelines. * @return a key for a group */ - public String getGroupId() - { + public String getGroupId() { return groupId; } @@ -68,8 +64,7 @@ public String getGroupId() * Sets the dependency's group ID. * @param groupId the group ID */ - public void setGroupId(String groupId) - { + public void setGroupId(String groupId) { this.groupId = groupId; } @@ -77,8 +72,7 @@ public void setGroupId(String groupId) * Gets the type of dependency, for example a "jar". * @return the type of dependency */ - public String getType() - { + public String getType() { return type; } @@ -86,8 +80,7 @@ public String getType() * Sets the dependency project's type. * @param type the dependency's type */ - public void setType(String type) - { + public void setType(String type) { this.type = type; } @@ -96,8 +89,7 @@ public void setType(String type) * i.e. version 1, or 2.1.4 * @return a specific point in a project's timeline */ - public String getVersion() - { + public String getVersion() { return version; } @@ -105,19 +97,21 @@ public String getVersion() * Sets the point in a project's development timeline * @param version the project's version */ - public void setVersion(String version) - { + public void setVersion(String version) { this.version = version; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - sb.append( "groupId = " ).append( groupId ). - append( ", artifactId = " ).append( artifactId ). - append( ", version = " ).append( version ). - append( ", type = " ).append( type ); + sb.append("groupId = ") + .append(groupId) + .append(", artifactId = ") + .append(artifactId) + .append(", version = ") + .append(version) + .append(", type = ") + .append(type); return sb.toString(); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentDescriptor.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentDescriptor.java index 36eebd3f0..2f4eb096a 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentDescriptor.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentDescriptor.java @@ -16,14 +16,14 @@ * limitations under the License. */ -import org.codehaus.plexus.PlexusConstants; -import org.codehaus.plexus.classworlds.realm.ClassRealm; -import org.codehaus.plexus.configuration.PlexusConfiguration; - import java.util.ArrayList; -import java.util.List; import java.util.Arrays; import java.util.Collections; +import java.util.List; + +import org.codehaus.plexus.PlexusConstants; +import org.codehaus.plexus.classworlds.realm.ClassRealm; +import org.codehaus.plexus.configuration.PlexusConfiguration; /** * Component instantiation description. @@ -32,8 +32,7 @@ * @author bob mcwhirter * @author Michal Maczka */ -public class ComponentDescriptor -{ +public class ComponentDescriptor { private String alias = null; private String role = null; @@ -89,12 +88,9 @@ public class ComponentDescriptor // Instance methods // ---------------------------------------------------------------------- - public ComponentDescriptor() - { - } + public ComponentDescriptor() {} - public ComponentDescriptor( Class implementationClass, ClassRealm realm ) - { + public ComponentDescriptor(Class implementationClass, ClassRealm realm) { this.implementationClass = implementationClass; this.implementation = implementationClass.getName(); this.realm = realm; @@ -104,8 +100,7 @@ public ComponentDescriptor( Class implementationClass, ClassRealm realm ) * The location this information came from (descriptor file URI). * @param source The source of the descriptor. */ - public void setSource( String source ) - { + public void setSource(String source) { this.source = source; } @@ -113,8 +108,7 @@ public void setSource( String source ) * The location this information came from (descriptor file URI). * @return The source. */ - public String getSource() - { + public String getSource() { return source; } @@ -123,22 +117,19 @@ public String getSource() * * @return a human-friendly key */ - public String getHumanReadableKey() - { + public String getHumanReadableKey() { StringBuilder key = new StringBuilder(); - key.append( "role: '" ).append( getRole() ).append( "'" ); + key.append("role: '").append(getRole()).append("'"); - key.append( ", implementation: '" ).append( getImplementation() ).append( "'" ); + key.append(", implementation: '").append(getImplementation()).append("'"); - if ( roleHint != null ) - { - key.append( ", role hint: '" ).append( getRoleHint() ).append( "'" ); + if (roleHint != null) { + key.append(", role hint: '").append(getRoleHint()).append("'"); } - if ( alias != null ) - { - key.append( ", alias: '" ).append( getAlias() ).append( "'" ); + if (alias != null) { + key.append(", alias: '").append(getAlias()).append("'"); } return key.toString(); @@ -149,8 +140,7 @@ public String getHumanReadableKey() * * @return an alias for this component */ - public String getAlias() - { + public String getAlias() { return alias; } @@ -159,8 +149,7 @@ public String getAlias() * * @param alias alternate name to set */ - public void setAlias( String alias ) - { + public void setAlias(String alias) { this.alias = alias; } @@ -169,13 +158,11 @@ public void setAlias( String alias ) * * @return the role of this component */ - public String getRole() - { + public String getRole() { return role; } - public Class getRoleClass() - { + public Class getRoleClass() { attemptRoleLoad(); if (roleClass == null) { @@ -184,30 +171,23 @@ public Class getRoleClass() return (Class) roleClass; } - private void attemptRoleLoad() - { - if ( roleClass == null && getRole() != null && getRealm() != null ) - { - try - { - roleClass = (Class) getRealm().loadClass( getRole() ); + private void attemptRoleLoad() { + if (roleClass == null && getRole() != null && getRealm() != null) { + try { + roleClass = (Class) getRealm().loadClass(getRole()); Thread.currentThread(); - } - catch ( Throwable ignored ) - { + } catch (Throwable ignored) { Thread.currentThread(); } } } - /** * Sets the role of this component. * * @param role this component's role */ - public void setRole( String role ) - { + public void setRole(String role) { this.role = role; // reload role class @@ -215,8 +195,7 @@ public void setRole( String role ) attemptRoleLoad(); } - public void setRoleClass( Class roleClass ) - { + public void setRoleClass(Class roleClass) { this.roleClass = roleClass; if (roleClass == null) { @@ -231,8 +210,7 @@ public void setRoleClass( Class roleClass ) * * @return the role-hint of this component */ - public String getRoleHint() - { + public String getRoleHint() { return roleHint; } @@ -241,14 +219,10 @@ public String getRoleHint() * * @param roleHint this component's role-hint */ - public void setRoleHint( String roleHint ) - { - if ( ( roleHint == null ) || roleHint.trim().equals( "" ) ) - { + public void setRoleHint(String roleHint) { + if ((roleHint == null) || roleHint.trim().equals("")) { this.roleHint = PlexusConstants.PLEXUS_DEFAULT_HINT; - } - else - { + } else { this.roleHint = roleHint; } } @@ -259,8 +233,7 @@ public void setRoleHint( String roleHint ) * * @return the implementation of this componet's role. */ - public String getImplementation() - { + public String getImplementation() { return implementation; } @@ -270,8 +243,7 @@ public String getImplementation() * @param implementation string denoting a FQCN in normal Java components, or some other name or file for other * component factory implementations */ - public void setImplementation( String implementation ) - { + public void setImplementation(String implementation) { this.implementation = implementation; // reload implementation class @@ -284,34 +256,27 @@ public void setImplementation( String implementation ) * * @return the implementation of this componet's role. */ - public Class getImplementationClass() - { + public Class getImplementationClass() { attemptImplementationLoad(); if (implementationClass == null) { return (Class) Object.class; } - return (Class)implementationClass; + return (Class) implementationClass; } - private void attemptImplementationLoad() - { - if ( implementationClass == null && getImplementation() != null && getRealm() != null ) - { - try - { - implementationClass = (Class) getRealm().loadClass( getImplementation() ); + private void attemptImplementationLoad() { + if (implementationClass == null && getImplementation() != null && getRealm() != null) { + try { + implementationClass = (Class) getRealm().loadClass(getImplementation()); Thread.currentThread(); - } - catch ( Throwable ignored ) - { + } catch (Throwable ignored) { Thread.currentThread(); } } } - public void setImplementationClass( Class implementationClass ) - { + public void setImplementationClass(Class implementationClass) { this.implementationClass = implementationClass; if (implementationClass == null) { implementation = null; @@ -325,8 +290,7 @@ public void setImplementationClass( Class implementationClass ) * * @return a specific point in a components's project timeline */ - public String getVersion() - { + public String getVersion() { return version; } @@ -335,8 +299,7 @@ public String getVersion() * * @param version the components's version */ - public void setVersion( String version ) - { + public void setVersion(String version) { this.version = version; } @@ -345,8 +308,7 @@ public void setVersion( String version ) * * @return the type of this component */ - public String getComponentType() - { + public String getComponentType() { return componentType; } @@ -355,8 +317,7 @@ public String getComponentType() * * @param componentType the type to set */ - public void setComponentType( String componentType ) - { + public void setComponentType(String componentType) { this.componentType = componentType; } @@ -365,8 +326,7 @@ public void setComponentType( String componentType ) * * @return the type of instantiation strategy for this component */ - public String getInstantiationStrategy() - { + public String getInstantiationStrategy() { return instantiationStrategy; } @@ -375,8 +335,7 @@ public String getInstantiationStrategy() * * @return configuration values defined for this component */ - public PlexusConfiguration getConfiguration() - { + public PlexusConfiguration getConfiguration() { return configuration; } @@ -385,9 +344,8 @@ public PlexusConfiguration getConfiguration() * * @param configuration the configuration hierarchy to set */ - public void setConfiguration( PlexusConfiguration configuration ) - { - this.configuration = configuration; + public void setConfiguration(PlexusConfiguration configuration) { + this.configuration = configuration; } /** @@ -395,8 +353,7 @@ public void setConfiguration( PlexusConfiguration configuration ) * * @return true if this component has a configuration */ - public boolean hasConfiguration() - { + public boolean hasConfiguration() { return configuration != null; } @@ -405,8 +362,7 @@ public boolean hasConfiguration() * * @return the lifecycle-handler for this component */ - public String getLifecycleHandler() - { + public String getLifecycleHandler() { return lifecycleHandler; } @@ -415,18 +371,15 @@ public String getLifecycleHandler() * * @param lifecycleHandler the lifecycle handler string to set */ - public void setLifecycleHandler( String lifecycleHandler ) - { + public void setLifecycleHandler(String lifecycleHandler) { this.lifecycleHandler = lifecycleHandler; } - public String getComponentProfile() - { + public String getComponentProfile() { return componentProfile; } - public void setComponentProfile( String componentProfile ) - { + public void setComponentProfile(String componentProfile) { this.componentProfile = componentProfile; } @@ -435,9 +388,8 @@ public void setComponentProfile( String componentProfile ) * * @param requirement the requirement to add */ - public void addRequirement( ComponentRequirement requirement ) - { - this.requirements.add( requirement ); + public void addRequirement(ComponentRequirement requirement) { + this.requirements.add(requirement); } /** @@ -445,9 +397,8 @@ public void addRequirement( ComponentRequirement requirement ) * * @param requirement the requirement to add */ - public void addRequirement( ComponentRequirement... requirement ) - { - this.requirements.addAll( Arrays.asList( requirement )); + public void addRequirement(ComponentRequirement... requirement) { + this.requirements.addAll(Arrays.asList(requirement)); } /** @@ -455,9 +406,8 @@ public void addRequirement( ComponentRequirement... requirement ) * * @param requirements the requirements to add */ - public void addRequirements( List requirements ) - { - this.requirements.addAll( requirements ); + public void addRequirements(List requirements) { + this.requirements.addAll(requirements); } /** @@ -465,9 +415,8 @@ public void addRequirements( List requirements ) * * @param requirement the requirement to remove */ - public void removeRequirement( ComponentRequirement... requirement ) - { - this.requirements.removeAll( Arrays.asList( requirement )); + public void removeRequirement(ComponentRequirement... requirement) { + this.requirements.removeAll(Arrays.asList(requirement)); } /** @@ -475,9 +424,8 @@ public void removeRequirement( ComponentRequirement... requirement ) * * @param requirements the requirements to remove */ - public void removeRequirements( List requirements ) - { - this.requirements.removeAll( requirements ); + public void removeRequirements(List requirements) { + this.requirements.removeAll(requirements); } /** @@ -485,9 +433,8 @@ public void removeRequirements( List requirements ) * * @return all project requirements of this component */ - public List getRequirements() - { - return Collections.unmodifiableList( requirements ); + public List getRequirements() { + return Collections.unmodifiableList(requirements); } /** @@ -495,8 +442,7 @@ public List getRequirements() * * @return an id of the factory used to create this component */ - public String getComponentFactory() - { + public String getComponentFactory() { return componentFactory; } @@ -505,8 +451,7 @@ public String getComponentFactory() * * @param componentFactory The componentFactor. */ - public void setComponentFactory( String componentFactory ) - { + public void setComponentFactory(String componentFactory) { this.componentFactory = componentFactory; } @@ -516,8 +461,7 @@ public void setComponentFactory( String componentFactory ) * * @return the ID of the type of composer this component will use */ - public String getComponentComposer() - { + public String getComponentComposer() { return componentComposer; } @@ -526,8 +470,7 @@ public String getComponentComposer() * * @param componentComposer string representation of the composer to use */ - public void setComponentComposer( String componentComposer ) - { + public void setComponentComposer(String componentComposer) { this.componentComposer = componentComposer; } @@ -536,8 +479,7 @@ public void setComponentComposer( String componentComposer ) * * @return a human-readable description of this component */ - public String getDescription() - { + public String getDescription() { return description; } @@ -546,8 +488,7 @@ public String getDescription() * * @param description a human-readable description of this component */ - public void setDescription( String description ) - { + public void setDescription(String description) { this.description = description; } @@ -556,8 +497,7 @@ public void setDescription( String description ) * * @param instantiationStrategy The strategy. */ - public void setInstantiationStrategy( String instantiationStrategy ) - { + public void setInstantiationStrategy(String instantiationStrategy) { this.instantiationStrategy = instantiationStrategy; } @@ -570,8 +510,7 @@ public void setInstantiationStrategy( String instantiationStrategy ) * * @return true if this may be in an isolated classrealm */ - public boolean isIsolatedRealm() - { + public boolean isIsolatedRealm() { return isolatedRealm; } @@ -580,8 +519,7 @@ public boolean isIsolatedRealm() * * @param componentSetDescriptor the component set descriptor of components and dependencies */ - public void setComponentSetDescriptor( ComponentSetDescriptor componentSetDescriptor ) - { + public void setComponentSetDescriptor(ComponentSetDescriptor componentSetDescriptor) { this.componentSetDescriptor = componentSetDescriptor; } @@ -590,8 +528,7 @@ public void setComponentSetDescriptor( ComponentSetDescriptor componentSetDescri * * @return the component set descriptor */ - public ComponentSetDescriptor getComponentSetDescriptor() - { + public ComponentSetDescriptor getComponentSetDescriptor() { return componentSetDescriptor; } @@ -600,8 +537,7 @@ public ComponentSetDescriptor getComponentSetDescriptor() * * @param isolatedRealm true if this component may be in an isolated classrealm */ - public void setIsolatedRealm( boolean isolatedRealm ) - { + public void setIsolatedRealm(boolean isolatedRealm) { this.isolatedRealm = isolatedRealm; } @@ -611,8 +547,7 @@ public void setIsolatedRealm( boolean isolatedRealm ) * * @return the type of component configurator for this project */ - public String getComponentConfigurator() - { + public String getComponentConfigurator() { return componentConfigurator; } @@ -621,8 +556,7 @@ public String getComponentConfigurator() * * @param componentConfigurator The component configurator. */ - public void setComponentConfigurator( String componentConfigurator ) - { + public void setComponentConfigurator(String componentConfigurator) { this.componentConfigurator = componentConfigurator; } @@ -631,8 +565,7 @@ public void setComponentConfigurator( String componentConfigurator ) * * @return ClassRealm that this component lives under */ - public ClassRealm getRealm() - { + public ClassRealm getRealm() { return realm; } @@ -641,8 +574,7 @@ public ClassRealm getRealm() * * @param realm the ClassRealm that this component lives under */ - public void setRealm( ClassRealm realm ) - { + public void setRealm(ClassRealm realm) { this.realm = realm; // reload implementation class @@ -654,50 +586,43 @@ public void setRealm( ClassRealm realm ) attemptRoleLoad(); } - public String toString() - { + public String toString() { return getClass().getName() + " [role: '" + getRole() + "', hint: '" + getRoleHint() + "', realm: " - + ( realm == null ? "NULL" : "'" + realm + "'" ) + "]"; + + (realm == null ? "NULL" : "'" + realm + "'") + "]"; } // Component identity established here! - public boolean equals( Object other ) - { - if ( this == other ) - { + public boolean equals(Object other) { + if (this == other) { return true; } - if ( !( other instanceof ComponentDescriptor ) ) - { + if (!(other instanceof ComponentDescriptor)) { return false; } ComponentDescriptor that = (ComponentDescriptor) other; - return eq( getRole(), that.getRole() ) && eq( getRoleHint(), that.getRoleHint() ) - && eq( getRealm(), that.getRealm() ); + return eq(getRole(), that.getRole()) + && eq(getRoleHint(), that.getRoleHint()) + && eq(getRealm(), that.getRealm()); } - private static boolean eq( T o1, T o2 ) - { - return ( o1 != null ) ? o1.equals( o2 ) : o2 == null; + private static boolean eq(T o1, T o2) { + return (o1 != null) ? o1.equals(o2) : o2 == null; } - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + hash( getRole() ); - hash = hash * 31 + hash( getRoleHint() ); - hash = hash * 31 + hash( getRealm() ); + hash = hash * 31 + hash(getRole()); + hash = hash * 31 + hash(getRoleHint()); + hash = hash * 31 + hash(getRealm()); return hash; } - private static int hash( Object obj ) - { - return ( obj != null ) ? obj.hashCode() : 0; + private static int hash(Object obj) { + return (obj != null) ? obj.hashCode() : 0; } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentRepository.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentRepository.java index 2574a7901..ca735ebaa 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentRepository.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentRepository.java @@ -16,25 +16,24 @@ * limitations under the License. */ -import org.codehaus.plexus.classworlds.realm.ClassRealm; -import org.codehaus.plexus.component.composition.CycleDetectedInComponentGraphException; - import java.util.List; import java.util.Map; -public interface ComponentRepository -{ - void addComponentDescriptor( ComponentDescriptor componentDescriptor ) - throws CycleDetectedInComponentGraphException; +import org.codehaus.plexus.classworlds.realm.ClassRealm; +import org.codehaus.plexus.component.composition.CycleDetectedInComponentGraphException; + +public interface ComponentRepository { + void addComponentDescriptor(ComponentDescriptor componentDescriptor) + throws CycleDetectedInComponentGraphException; - ComponentDescriptor getComponentDescriptor( Class type, String role, String roleHint ); + ComponentDescriptor getComponentDescriptor(Class type, String role, String roleHint); @Deprecated - ComponentDescriptor getComponentDescriptor( String role, String roleHint, ClassRealm realm ); + ComponentDescriptor getComponentDescriptor(String role, String roleHint, ClassRealm realm); - Map> getComponentDescriptorMap( Class type, String role ); + Map> getComponentDescriptorMap(Class type, String role); - List> getComponentDescriptorList( Class type, String role ); + List> getComponentDescriptorList(Class type, String role); - void removeComponentRealm( ClassRealm classRealm ); + void removeComponentRealm(ClassRealm classRealm); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentRequirement.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentRequirement.java index af176da1f..aa6a10dd8 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentRequirement.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentRequirement.java @@ -21,8 +21,7 @@ * * @author Michal Maczka */ -public class ComponentRequirement -{ +public class ComponentRequirement { private String role; private String roleHint = ""; @@ -37,8 +36,7 @@ public class ComponentRequirement * Returns the field name that this component requirement will inject. * @return the field name that this component requirement will inject */ - public String getFieldName() - { + public String getFieldName() { return fieldName; } @@ -47,8 +45,7 @@ public String getFieldName() * component. * @param fieldName the name of the field to be populated */ - public void setFieldName( String fieldName ) - { + public void setFieldName(String fieldName) { this.fieldName = fieldName; } @@ -56,8 +53,7 @@ public void setFieldName( String fieldName ) * Returns the role of the required component. * @return the role of the required component */ - public String getRole() - { + public String getRole() { return role; } @@ -65,8 +61,7 @@ public String getRole() * Sets the role of the require component. * @param role the required component's role */ - public void setRole( String role ) - { + public void setRole(String role) { this.role = role; } @@ -74,8 +69,7 @@ public void setRole( String role ) * Returns the role-hint of the required component. * @return the role-hint of the required component */ - public String getRoleHint() - { + public String getRoleHint() { return roleHint; } @@ -84,17 +78,15 @@ public String getRoleHint() * Passing null or an empty string will match any available implementation. * @param roleHint the required component's role-hint */ - public void setRoleHint( String roleHint ) - { - this.roleHint = ( roleHint != null ) ? roleHint : ""; + public void setRoleHint(String roleHint) { + this.roleHint = (roleHint != null) ? roleHint : ""; } /** * Returns the type of the field this component requirement will inject. * @return the type of the field this component requirement will inject */ - public String getFieldMappingType() - { + public String getFieldMappingType() { return fieldMappingType; } @@ -103,8 +95,7 @@ public String getFieldMappingType() * component. * @param fieldType the type of the field to be populated */ - public void setFieldMappingType( String fieldType ) - { + public void setFieldMappingType(String fieldType) { this.fieldMappingType = fieldType; } @@ -114,8 +105,7 @@ public void setFieldMappingType( String fieldType ) * @return {@code true} if the requested component may be missing, {@code false} if the component is mandatory. * @since 1.3.0 */ - public boolean isOptional() - { + public boolean isOptional() { return optional; } @@ -127,60 +117,51 @@ public boolean isOptional() * mandatory. * @since 1.3.0 */ - public void setOptional( boolean optional ) - { + public void setOptional(boolean optional) { this.optional = optional; } - public String toString() - { - return "ComponentRequirement{" + - "role='" + getRole() + "'" + ", " + - "roleHint='" + getRoleHint() + "', " + - "fieldName='" + getFieldName() + "'" + - "}"; + public String toString() { + return "ComponentRequirement{" + "role='" + + getRole() + "'" + ", " + "roleHint='" + + getRoleHint() + "', " + "fieldName='" + + getFieldName() + "'" + "}"; } /** * Returns a human-friendly key, suitable for display. * @return a human-friendly key */ - public String getHumanReadableKey() - { + public String getHumanReadableKey() { StringBuilder key = new StringBuilder(); - key.append( "role: '").append( getRole() ).append( "'" ); + key.append("role: '").append(getRole()).append("'"); - if ( getRoleHint() != null ) - { - key.append( ", role-hint: '" ).append( getRoleHint() ).append( "'. " ); + if (getRoleHint() != null) { + key.append(", role-hint: '").append(getRoleHint()).append("'. "); } - if ( getFieldName() != null ) - { - key.append( ", field name: '" ).append( getFieldName() ).append( "' " ); + if (getFieldName() != null) { + key.append(", field name: '").append(getFieldName()).append("' "); } return key.toString(); } - public boolean equals( Object other ) - { - if ( other instanceof ComponentRequirement ) - { + public boolean equals(Object other) { + if (other instanceof ComponentRequirement) { String myId = role + ":" + roleHint; ComponentRequirement req = (ComponentRequirement) other; String otherId = req.role + ":" + req.roleHint; - return myId.equals( otherId ); + return myId.equals(otherId); } return false; } - public int hashCode() - { - return ( role + ":" + roleHint ).hashCode(); + public int hashCode() { + return (role + ":" + roleHint).hashCode(); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentRequirementList.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentRequirementList.java index 991787fc1..288a1f766 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentRequirementList.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentRequirementList.java @@ -8,33 +8,25 @@ * @author Andrew Williams * @since 1.0 */ -public class ComponentRequirementList - extends ComponentRequirement -{ +public class ComponentRequirementList extends ComponentRequirement { private List roleHints; - public List getRoleHints() - { + public List getRoleHints() { return roleHints; } - public void setRoleHints(List roleHints) - { + public void setRoleHints(List roleHints) { this.roleHints = roleHints; } - public String getRoleHint() - { + public String getRoleHint() { StringBuilder buffer = new StringBuilder(); - for ( String hint : roleHints ) - { - if (buffer.length() > 0) - { + for (String hint : roleHints) { + if (buffer.length() > 0) { buffer.append(","); } buffer.append(hint); - } return buffer.toString(); diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentSetDescriptor.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentSetDescriptor.java index 33cd99dbf..53c21455b 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentSetDescriptor.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/ComponentSetDescriptor.java @@ -25,8 +25,7 @@ * @author Jason van Zyl * @author Trygve Laugstøl */ -public class ComponentSetDescriptor -{ +public class ComponentSetDescriptor { // This field is not currently used in Maven, or Plexus private String id; @@ -35,19 +34,18 @@ public class ComponentSetDescriptor /** Flag to indicate whether this component should be loaded in a realm/classloader of its own. */ private boolean isolatedRealm; - + /** The component descriptors that can be found within this component set descriptor. */ private final List> components = new ArrayList>(); /** The dependencies that are required by the set of components found in this component set descriptor. */ private final List dependencies = new ArrayList(); - + /** * Returns a list of components in this set. * @return a list of components */ - public List> getComponents() - { + public List> getComponents() { return components; } @@ -55,17 +53,15 @@ public List> getComponents() * Add a new ComponentDescriptor to this set. * @param cd the ComponentDescriptor to add */ - public void addComponentDescriptor( ComponentDescriptor cd ) - { - components.add( cd ); + public void addComponentDescriptor(ComponentDescriptor cd) { + components.add(cd); } /** * Sets a List of components as this set's contents. * @param components the List of components to set */ - public void setComponents( List> components ) - { + public void setComponents(List> components) { this.components.clear(); this.components.addAll(components); } @@ -74,8 +70,7 @@ public void setComponents( List> components ) * Returns a List of dependencies of this set of components. * @return a List of dependencies of this set of components */ - public List getDependencies() - { + public List getDependencies() { return dependencies; } @@ -83,17 +78,15 @@ public List getDependencies() * Add a depenency to this set's contents. * @param cd the ComponentDependency to add */ - public void addDependency( ComponentDependency cd ) - { - dependencies.add( cd ); + public void addDependency(ComponentDependency cd) { + dependencies.add(cd); } /** * Sets a List of dependencies as this set's component dependencies. * @param dependencies the List of components to set */ - public void setDependencies( List dependencies ) - { + public void setDependencies(List dependencies) { this.dependencies.clear(); this.dependencies.addAll(dependencies); } @@ -103,8 +96,7 @@ public void setDependencies( List dependencies ) * @param isolatedRealm true if this set of components may be in an * isolated classrealm */ - public void setIsolatedRealm( boolean isolatedRealm ) - { + public void setIsolatedRealm(boolean isolatedRealm) { this.isolatedRealm = isolatedRealm; } @@ -112,8 +104,7 @@ public void setIsolatedRealm( boolean isolatedRealm ) * Returns true if this set may be in an isolated classrealm. * @return true if this set may be in an isolated classrealm */ - public boolean isIsolatedRealm() - { + public boolean isIsolatedRealm() { return isolatedRealm; } @@ -121,8 +112,7 @@ public boolean isIsolatedRealm() * Returns the identifier of this set. * @return the identifier of this set */ - public String getId() - { + public String getId() { return id; } @@ -130,34 +120,29 @@ public String getId() * Sets the identifier of this set. * @param id the identifier to set */ - public void setId( String id ) - { + public void setId(String id) { this.id = id; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - sb.append( "Component Descriptor: " ); + sb.append("Component Descriptor: "); - for ( ComponentDescriptor cd : components ) - { - sb.append( cd.getHumanReadableKey() ).append( "\n" ); + for (ComponentDescriptor cd : components) { + sb.append(cd.getHumanReadableKey()).append("\n"); } - sb.append( "---" ); + sb.append("---"); return sb.toString(); } - public String getSource() - { + public String getSource() { return source; } - public void setSource( String source ) - { + public void setSource(String source) { this.source = source; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/DefaultComponentRepository.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/DefaultComponentRepository.java index e56bc1e19..44e0e1106 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/DefaultComponentRepository.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/DefaultComponentRepository.java @@ -16,8 +16,6 @@ * limitations under the License. */ -import static org.codehaus.plexus.component.CastUtils.isAssignableFrom; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -34,151 +32,123 @@ import org.codehaus.plexus.ClassRealmUtil; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.classworlds.realm.ClassRealm; -import org.codehaus.plexus.component.composition.CycleDetectedInComponentGraphException; import org.codehaus.plexus.component.composition.CompositionResolver; +import org.codehaus.plexus.component.composition.CycleDetectedInComponentGraphException; import org.codehaus.plexus.component.composition.DefaultCompositionResolver; import org.codehaus.plexus.logging.AbstractLogEnabled; import org.codehaus.plexus.util.StringUtils; +import static org.codehaus.plexus.component.CastUtils.isAssignableFrom; + /** * @author Jason van Zyl */ -public class DefaultComponentRepository - extends AbstractLogEnabled - implements ComponentRepository -{ +public class DefaultComponentRepository extends AbstractLogEnabled implements ComponentRepository { private final Map>>>> index = new LinkedHashMap>>>>(); private final CompositionResolver compositionResolver = new DefaultCompositionResolver(); - public DefaultComponentRepository() - { - } + public DefaultComponentRepository() {} // ---------------------------------------------------------------------- // Accessors // ---------------------------------------------------------------------- - private Map>> getComponentDescriptors( String role ) - { + private Map>> getComponentDescriptors(String role) { // verify arguments - if ( role == null ) - { - throw new NullPointerException( "role is null" ); + if (role == null) { + throw new NullPointerException("role is null"); } // determine realms to search - Set realms = ClassRealmUtil.getContextRealms( null ); - if ( realms.isEmpty() ) - { - realms.addAll( index.keySet() ); + Set realms = ClassRealmUtil.getContextRealms(null); + if (realms.isEmpty()) { + realms.addAll(index.keySet()); } - // Get all valid component descriptors Map>> roleHintIndex = new LinkedHashMap>>(); - for ( ClassRealm realm : realms ) - { - SortedMap>>> roleIndex = index.get( realm ); + for (ClassRealm realm : realms) { + SortedMap>>> roleIndex = index.get(realm); if (roleIndex != null) { - Map>> descriptors = roleIndex.get( role ); - if ( descriptors != null ) - { - for ( Entry>> descriptor : descriptors.entrySet() ) - { - Set> componentDescriptors = roleHintIndex.get( descriptor.getKey() ); - if ( componentDescriptors == null ) - { + Map>> descriptors = roleIndex.get(role); + if (descriptors != null) { + for (Entry>> descriptor : descriptors.entrySet()) { + Set> componentDescriptors = roleHintIndex.get(descriptor.getKey()); + if (componentDescriptors == null) { componentDescriptors = new LinkedHashSet>(); - roleHintIndex.put( descriptor.getKey(), componentDescriptors ); + roleHintIndex.put(descriptor.getKey(), componentDescriptors); } - componentDescriptors.addAll( descriptor.getValue() ); + componentDescriptors.addAll(descriptor.getValue()); } - } } } - return Collections.unmodifiableMap( roleHintIndex ); + return Collections.unmodifiableMap(roleHintIndex); } - public ComponentDescriptor getComponentDescriptor( Class type, String role, String roleHint ) - { - Map>> roleHintIndex = getComponentDescriptors( role ); + public ComponentDescriptor getComponentDescriptor(Class type, String role, String roleHint) { + Map>> roleHintIndex = getComponentDescriptors(role); Collection> descriptors; - if ( StringUtils.isNotEmpty( roleHint ) ) - { + if (StringUtils.isNotEmpty(roleHint)) { // specific role hint -> get only those - descriptors = roleHintIndex.get( roleHint ); - } - else - { + descriptors = roleHintIndex.get(roleHint); + } else { // missing role hint -> get all (wildcard) Collection> allDescriptors = new ArrayList>(); - descriptors = roleHintIndex.get( PlexusConstants.PLEXUS_DEFAULT_HINT ); - if ( descriptors != null ) - { - allDescriptors.addAll( descriptors ); + descriptors = roleHintIndex.get(PlexusConstants.PLEXUS_DEFAULT_HINT); + if (descriptors != null) { + allDescriptors.addAll(descriptors); } - for ( String hint : roleHintIndex.keySet() ) - { - descriptors = roleHintIndex.get( hint ); - if ( descriptors != null ) - { - allDescriptors.addAll( descriptors ); + for (String hint : roleHintIndex.keySet()) { + descriptors = roleHintIndex.get(hint); + if (descriptors != null) { + allDescriptors.addAll(descriptors); } } descriptors = allDescriptors; } - if ( descriptors!= null ) - { - for ( ComponentDescriptor descriptor : descriptors ) - { + if (descriptors != null) { + for (ComponentDescriptor descriptor : descriptors) { Class implClass = descriptor.getImplementationClass(); - if ( isAssignableFrom( type, implClass ) || Object.class == implClass && role.equals( type.getName() ) ) - { + if (isAssignableFrom(type, implClass) || Object.class == implClass && role.equals(type.getName())) { return (ComponentDescriptor) descriptor; } } } - + return null; } - public Map> getComponentDescriptorMap( Class type, String role ) - { + public Map> getComponentDescriptorMap(Class type, String role) { Map> descriptors = new TreeMap>(); - for ( Set> componentDescriptors : getComponentDescriptors( role ).values() ) - { - for ( ComponentDescriptor descriptor : componentDescriptors ) - { - if ( !descriptors.containsKey( descriptor.getRoleHint() ) && isAssignableFrom( type, - descriptor.getImplementationClass() ) ) - { - descriptors.put( descriptor.getRoleHint(), (ComponentDescriptor) descriptor ); + for (Set> componentDescriptors : + getComponentDescriptors(role).values()) { + for (ComponentDescriptor descriptor : componentDescriptors) { + if (!descriptors.containsKey(descriptor.getRoleHint()) + && isAssignableFrom(type, descriptor.getImplementationClass())) { + descriptors.put(descriptor.getRoleHint(), (ComponentDescriptor) descriptor); } } } return descriptors; } - public List> getComponentDescriptorList( Class type, String role ) - { + public List> getComponentDescriptorList(Class type, String role) { List> descriptors = new ArrayList>(); - for ( Set> componentDescriptors : getComponentDescriptors( role ).values() ) - { - for ( ComponentDescriptor descriptor : componentDescriptors ) - { - if ( isAssignableFrom( type, descriptor.getImplementationClass() ) ) - { - descriptors.add( (ComponentDescriptor) descriptor ); + for (Set> componentDescriptors : + getComponentDescriptors(role).values()) { + for (ComponentDescriptor descriptor : componentDescriptors) { + if (isAssignableFrom(type, descriptor.getImplementationClass())) { + descriptors.add((ComponentDescriptor) descriptor); } } } @@ -186,21 +156,18 @@ public List> getComponentDescriptorList( Class typ } @Deprecated - public ComponentDescriptor getComponentDescriptor( String role, String roleHint, ClassRealm realm ) - { + public ComponentDescriptor getComponentDescriptor(String role, String roleHint, ClassRealm realm) { // find all realms from our realm to the root realm Set realms = new HashSet(); - for ( ClassRealm r = realm; r != null; r = r.getParentRealm() ) - { - realms.add( r ); + for (ClassRealm r = realm; r != null; r = r.getParentRealm()) { + realms.add(r); } // get the component descriptors by roleHint - for ( ComponentDescriptor componentDescriptor : getComponentDescriptors( role ).get( roleHint ) ) - { + for (ComponentDescriptor componentDescriptor : + getComponentDescriptors(role).get(roleHint)) { // return the first descriptor from our target realms - if ( realms.contains( componentDescriptor.getRealm() ) ) - { + if (realms.contains(componentDescriptor.getRealm())) { return componentDescriptor; } } @@ -208,9 +175,8 @@ public ComponentDescriptor getComponentDescriptor( String role, String roleHi return null; } - public void removeComponentRealm( ClassRealm classRealm ) - { - index.remove( classRealm ); + public void removeComponentRealm(ClassRealm classRealm) { + index.remove(classRealm); } // ---------------------------------------------------------------------- @@ -221,32 +187,29 @@ public void removeComponentRealm( ClassRealm classRealm ) // Component Descriptor processing. // ---------------------------------------------------------------------- - public void addComponentDescriptor( ComponentDescriptor componentDescriptor ) - throws CycleDetectedInComponentGraphException - { + public void addComponentDescriptor(ComponentDescriptor componentDescriptor) + throws CycleDetectedInComponentGraphException { ClassRealm classRealm = componentDescriptor.getRealm(); - SortedMap>>> roleIndex = index.get( classRealm ); + SortedMap>>> roleIndex = index.get(classRealm); if (roleIndex == null) { roleIndex = new TreeMap>>>(); - index.put(classRealm, roleIndex); + index.put(classRealm, roleIndex); } String role = componentDescriptor.getRole(); - Map>> roleHintIndex = roleIndex.get( role ); - if ( roleHintIndex == null ) - { + Map>> roleHintIndex = roleIndex.get(role); + if (roleHintIndex == null) { roleHintIndex = new LinkedHashMap>>(); - roleIndex.put( role, roleHintIndex ); + roleIndex.put(role, roleHintIndex); } String roleHint = componentDescriptor.getRoleHint(); - Set> componentDescriptors = roleHintIndex.get( roleHint ); - if ( componentDescriptors == null ) - { + Set> componentDescriptors = roleHintIndex.get(roleHint); + if (componentDescriptors == null) { componentDescriptors = new LinkedHashSet>(); - roleHintIndex.put( roleHint, componentDescriptors ); + roleHintIndex.put(roleHint, componentDescriptors); } componentDescriptors.add(componentDescriptor); - compositionResolver.addComponentDescriptor( componentDescriptor ); + compositionResolver.addComponentDescriptor(componentDescriptor); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentConfigurationException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentConfigurationException.java index ab94cd710..ea0139e46 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentConfigurationException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentConfigurationException.java @@ -22,18 +22,15 @@ * * @author Jason van Zyl */ -public class ComponentConfigurationException - extends Exception -{ +public class ComponentConfigurationException extends Exception { private static final long serialVersionUID = -921278352685045303L; /** * Construct a new ComponentConfigurationException instance. * @param message exception message */ - public ComponentConfigurationException( String message ) - { - super( message ); + public ComponentConfigurationException(String message) { + super(message); } /** @@ -41,8 +38,7 @@ public ComponentConfigurationException( String message ) * @param message exception message * @param cause causing exception to chain */ - public ComponentConfigurationException( String message, Throwable cause ) - { - super( message, cause ); + public ComponentConfigurationException(String message, Throwable cause) { + super(message, cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentDescriptorUnmarshallingException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentDescriptorUnmarshallingException.java index 864f99fdc..9e6110ca0 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentDescriptorUnmarshallingException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentDescriptorUnmarshallingException.java @@ -22,18 +22,15 @@ * * @author Jason van Zyl */ -public class ComponentDescriptorUnmarshallingException - extends Exception -{ +public class ComponentDescriptorUnmarshallingException extends Exception { private static final long serialVersionUID = 6991583130117543536L; /** * Construct a new ComponentDescriptorUnmarshallingException instance. * @param message exception message */ - public ComponentDescriptorUnmarshallingException( String message ) - { - super( message ); + public ComponentDescriptorUnmarshallingException(String message) { + super(message); } /** @@ -41,8 +38,7 @@ public ComponentDescriptorUnmarshallingException( String message ) * @param message exception message * @param cause causing exception to chain */ - public ComponentDescriptorUnmarshallingException( String message, Throwable cause ) - { - super( message, cause ); + public ComponentDescriptorUnmarshallingException(String message, Throwable cause) { + super(message, cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentImplementationNotFoundException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentImplementationNotFoundException.java index b7df24db2..efa578293 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentImplementationNotFoundException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentImplementationNotFoundException.java @@ -23,18 +23,15 @@ * @author Jason van Zyl * */ -public class ComponentImplementationNotFoundException - extends Exception -{ +public class ComponentImplementationNotFoundException extends Exception { private static final long serialVersionUID = -9171668987729438489L; /** * Construct a new ComponentImplementationNotFoundException instance. * @param message exception message */ - public ComponentImplementationNotFoundException( String message ) - { - super( message ); + public ComponentImplementationNotFoundException(String message) { + super(message); } /** @@ -42,8 +39,7 @@ public ComponentImplementationNotFoundException( String message ) * @param message exception message * @param cause causing exception to chain */ - public ComponentImplementationNotFoundException( String message, Throwable cause ) - { - super( message, cause ); + public ComponentImplementationNotFoundException(String message, Throwable cause) { + super(message, cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentLifecycleException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentLifecycleException.java index af638a3b0..b030be9c9 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentLifecycleException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentLifecycleException.java @@ -22,18 +22,15 @@ * * @author Jason van Zyl */ -public class ComponentLifecycleException - extends Exception -{ +public class ComponentLifecycleException extends Exception { private static final long serialVersionUID = 146489359157036908L; /** * Construct a new ComponentLifecycleException instance. * @param message exception message */ - public ComponentLifecycleException( String message ) - { - super( message ); + public ComponentLifecycleException(String message) { + super(message); } /** @@ -41,8 +38,7 @@ public ComponentLifecycleException( String message ) * @param message exception message * @param cause causing exception to chain */ - public ComponentLifecycleException( String message, Throwable cause ) - { - super( message, cause ); + public ComponentLifecycleException(String message, Throwable cause) { + super(message, cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentLookupException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentLookupException.java index 42587285c..0cd7b2ece 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentLookupException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentLookupException.java @@ -27,10 +27,8 @@ * * @author Jason van Zyl */ -public class ComponentLookupException - extends Exception -{ - private String LS = System.getProperty( "line.separator" ); +public class ComponentLookupException extends Exception { + private String LS = System.getProperty("line.separator"); private String role; @@ -38,27 +36,24 @@ public class ComponentLookupException private ClassRealm realm; - public ComponentLookupException( String message, String role, String roleHint ) - { - super( message ); + public ComponentLookupException(String message, String role, String roleHint) { + super(message); this.role = role; this.roleHint = roleHint; } - public ComponentLookupException( String message, String role, String roleHint, Throwable cause ) - { - super( message, cause ); + public ComponentLookupException(String message, String role, String roleHint, Throwable cause) { + super(message, cause); this.role = role; this.roleHint = roleHint; } - public ComponentLookupException( String message, String role, String roleHint, ClassRealm realm ) - { - super( message ); + public ComponentLookupException(String message, String role, String roleHint, ClassRealm realm) { + super(message); this.role = role; @@ -67,9 +62,8 @@ public ComponentLookupException( String message, String role, String roleHint, C this.realm = realm; } - public ComponentLookupException( String message, String role, String roleHint, ClassRealm realm, Throwable cause ) - { - super( message, cause ); + public ComponentLookupException(String message, String role, String roleHint, ClassRealm realm, Throwable cause) { + super(message, cause); this.role = role; @@ -78,25 +72,26 @@ public ComponentLookupException( String message, String role, String roleHint, C this.realm = realm; } - public String getMessage() - { + public String getMessage() { StringBuilder sb = new StringBuilder() - .append( super.getMessage() ).append( LS ) - .append( " role: ").append( role ).append( LS ) - .append( " roleHint: ").append( roleHint ).append( LS ) - .append("classRealm: "); - - if ( realm != null ) - { - sb.append( realm.getId() ).append( LS ); - ByteArrayOutputStream os = new ByteArrayOutputStream( 1024 ); - PrintStream ps = new PrintStream( os ); - realm.display( ps ); - sb.append( os.toString() ); - } - else - { - sb.append( "none specified" ); + .append(super.getMessage()) + .append(LS) + .append(" role: ") + .append(role) + .append(LS) + .append(" roleHint: ") + .append(roleHint) + .append(LS) + .append("classRealm: "); + + if (realm != null) { + sb.append(realm.getId()).append(LS); + ByteArrayOutputStream os = new ByteArrayOutputStream(1024); + PrintStream ps = new PrintStream(os); + realm.display(ps); + sb.append(os.toString()); + } else { + sb.append("none specified"); } return sb.toString(); diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentLookupRuntimeException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentLookupRuntimeException.java index acec6d5de..f544921ab 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentLookupRuntimeException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentLookupRuntimeException.java @@ -22,16 +22,12 @@ * * @author Kristian Rosenvold */ -public class ComponentLookupRuntimeException - extends RuntimeException -{ - public ComponentLookupRuntimeException( ComponentLookupException cause ) - { - super( cause ); +public class ComponentLookupRuntimeException extends RuntimeException { + public ComponentLookupRuntimeException(ComponentLookupException cause) { + super(cause); } - public String getMessage() - { + public String getMessage() { return getCause().getMessage(); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentManagerImplementationNotFoundException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentManagerImplementationNotFoundException.java index b07339553..a0bbda0a7 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentManagerImplementationNotFoundException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentManagerImplementationNotFoundException.java @@ -22,18 +22,15 @@ * * @author Jason van Zyl */ -public class ComponentManagerImplementationNotFoundException - extends Exception -{ +public class ComponentManagerImplementationNotFoundException extends Exception { private static final long serialVersionUID = 2365017114180373632L; /** * Construct a new ComponentManagerImplementationNotFoundException instance. * @param message exception message */ - public ComponentManagerImplementationNotFoundException( String message ) - { - super( message ); + public ComponentManagerImplementationNotFoundException(String message) { + super(message); } /** @@ -41,8 +38,7 @@ public ComponentManagerImplementationNotFoundException( String message ) * @param message exception message * @param cause causing exception to chain */ - public ComponentManagerImplementationNotFoundException( String message, Throwable cause ) - { - super( message, cause ); + public ComponentManagerImplementationNotFoundException(String message, Throwable cause) { + super(message, cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentProfileException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentProfileException.java index ebdbd9ddf..529af0c9c 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentProfileException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentProfileException.java @@ -22,18 +22,15 @@ * * @author Jason van Zyl */ -public class ComponentProfileException - extends Exception -{ +public class ComponentProfileException extends Exception { private static final long serialVersionUID = -4099483467183306853L; /** * Construct a new ComponentProfileException instance. * @param message exception message */ - public ComponentProfileException( String message ) - { - super( message ); + public ComponentProfileException(String message) { + super(message); } /** @@ -41,8 +38,7 @@ public ComponentProfileException( String message ) * @param message exception message * @param cause causing exception to chain */ - public ComponentProfileException( String message, Throwable cause ) - { - super( message, cause ); + public ComponentProfileException(String message, Throwable cause) { + super(message, cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentRepositoryException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentRepositoryException.java index ee169f83d..3074821c7 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentRepositoryException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/exception/ComponentRepositoryException.java @@ -22,18 +22,15 @@ * * @author Jason van Zyl */ -public class ComponentRepositoryException - extends Exception -{ +public class ComponentRepositoryException extends Exception { private static final long serialVersionUID = 3698017788731736736L; /** * Construct a new ComponentRepositoryException instance. * @param message exception message */ - public ComponentRepositoryException( String message ) - { - super( message ); + public ComponentRepositoryException(String message) { + super(message); } /** @@ -41,8 +38,7 @@ public ComponentRepositoryException( String message ) * @param message exception message * @param cause causing exception to chain */ - public ComponentRepositoryException( String message, Throwable cause ) - { - super( message, cause ); + public ComponentRepositoryException(String message, Throwable cause) { + super(message, cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/io/PlexusTools.java b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/io/PlexusTools.java index 9c5b8d79e..c7263ea87 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/io/PlexusTools.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/component/repository/io/PlexusTools.java @@ -33,121 +33,100 @@ import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.codehaus.plexus.configuration.io.XmlPlexusConfigurationReader; - /** - * @author Jason van Zyl + * @author Jason van Zyl */ -public class PlexusTools -{ - public static PlexusConfiguration buildConfiguration( String resourceName, Reader configuration ) - throws PlexusConfigurationException - { - try - { +public class PlexusTools { + public static PlexusConfiguration buildConfiguration(String resourceName, Reader configuration) + throws PlexusConfigurationException { + try { XmlPlexusConfigurationReader reader = new XmlPlexusConfigurationReader(); - - PlexusConfiguration result = reader.read( configuration ); + + PlexusConfiguration result = reader.read(configuration); return result; - } - catch ( PlexusConfigurationException e ) - { - throw new PlexusConfigurationException( "PlexusConfigurationException building configuration from: " + resourceName, e ); - } - catch ( IOException e ) - { - throw new PlexusConfigurationException( "IO error building configuration from: " + resourceName, e ); + } catch (PlexusConfigurationException e) { + throw new PlexusConfigurationException( + "PlexusConfigurationException building configuration from: " + resourceName, e); + } catch (IOException e) { + throw new PlexusConfigurationException("IO error building configuration from: " + resourceName, e); } } - public static PlexusConfiguration buildConfiguration( String configuration ) - throws PlexusConfigurationException - { - return buildConfiguration( "", new StringReader( configuration ) ); + public static PlexusConfiguration buildConfiguration(String configuration) throws PlexusConfigurationException { + return buildConfiguration("", new StringReader(configuration)); } - public static ComponentDescriptor buildComponentDescriptor( String configuration, ClassRealm realm ) - throws PlexusConfigurationException - { - return buildComponentDescriptor( buildConfiguration( configuration ), realm ); + public static ComponentDescriptor buildComponentDescriptor(String configuration, ClassRealm realm) + throws PlexusConfigurationException { + return buildComponentDescriptor(buildConfiguration(configuration), realm); } - public static ComponentDescriptor buildComponentDescriptor( PlexusConfiguration configuration ) - throws PlexusConfigurationException - { - return buildComponentDescriptorImpl( configuration, null ); + public static ComponentDescriptor buildComponentDescriptor(PlexusConfiguration configuration) + throws PlexusConfigurationException { + return buildComponentDescriptorImpl(configuration, null); } - - public static ComponentDescriptor buildComponentDescriptor( PlexusConfiguration configuration, ClassRealm realm ) - throws PlexusConfigurationException - { - if ( realm == null ) - { - throw new NullPointerException( "realm is null" ); + + public static ComponentDescriptor buildComponentDescriptor(PlexusConfiguration configuration, ClassRealm realm) + throws PlexusConfigurationException { + if (realm == null) { + throw new NullPointerException("realm is null"); } - return buildComponentDescriptorImpl( configuration, realm ); + return buildComponentDescriptorImpl(configuration, realm); } - private static ComponentDescriptor buildComponentDescriptorImpl( PlexusConfiguration configuration, - ClassRealm realm ) - throws PlexusConfigurationException - { - String implementation = configuration.getChild( "implementation" ).getValue(); - if (implementation == null) - { - throw new PlexusConfigurationException( "implementation is null" ); + private static ComponentDescriptor buildComponentDescriptorImpl( + PlexusConfiguration configuration, ClassRealm realm) throws PlexusConfigurationException { + String implementation = configuration.getChild("implementation").getValue(); + if (implementation == null) { + throw new PlexusConfigurationException("implementation is null"); } ComponentDescriptor cd; - try - { - if ( realm != null ) - { - Class implementationClass = realm.loadClass( implementation ); + try { + if (realm != null) { + Class implementationClass = realm.loadClass(implementation); cd = new ComponentDescriptor(implementationClass, realm); - } - else - { + } else { cd = new ComponentDescriptor(); - cd.setImplementation( implementation ); + cd.setImplementation(implementation); } - } - catch ( Throwable e ) - { - throw new PlexusConfigurationException("Can not load implementation class " + implementation + - " from realm " + realm, e); + } catch (Throwable e) { + throw new PlexusConfigurationException( + "Can not load implementation class " + implementation + " from realm " + realm, e); } - cd.setRole( configuration.getChild( "role" ).getValue() ); + cd.setRole(configuration.getChild("role").getValue()); - cd.setRoleHint( configuration.getChild( "role-hint" ).getValue() ); + cd.setRoleHint(configuration.getChild("role-hint").getValue()); - cd.setVersion( configuration.getChild( "version" ).getValue() ); + cd.setVersion(configuration.getChild("version").getValue()); - cd.setComponentType( configuration.getChild( "component-type" ).getValue() ); + cd.setComponentType(configuration.getChild("component-type").getValue()); - cd.setInstantiationStrategy( configuration.getChild( "instantiation-strategy" ).getValue() ); + cd.setInstantiationStrategy( + configuration.getChild("instantiation-strategy").getValue()); - cd.setLifecycleHandler( configuration.getChild( "lifecycle-handler" ).getValue() ); + cd.setLifecycleHandler(configuration.getChild("lifecycle-handler").getValue()); - cd.setComponentProfile( configuration.getChild( "component-profile" ).getValue() ); + cd.setComponentProfile(configuration.getChild("component-profile").getValue()); - cd.setComponentComposer( configuration.getChild( "component-composer" ).getValue() ); + cd.setComponentComposer(configuration.getChild("component-composer").getValue()); - cd.setComponentConfigurator( configuration.getChild( "component-configurator" ).getValue() ); + cd.setComponentConfigurator( + configuration.getChild("component-configurator").getValue()); - cd.setComponentFactory( configuration.getChild( "component-factory" ).getValue() ); + cd.setComponentFactory(configuration.getChild("component-factory").getValue()); - cd.setDescription( configuration.getChild( "description" ).getValue() ); + cd.setDescription(configuration.getChild("description").getValue()); - cd.setAlias( configuration.getChild( "alias" ).getValue() ); + cd.setAlias(configuration.getChild("alias").getValue()); - String s = configuration.getChild( "isolated-realm" ).getValue(); + String s = configuration.getChild("isolated-realm").getValue(); - if ( s != null ) - { - cd.setIsolatedRealm( s.equals( "true" ) ? true : false ); + if (s != null) { + cd.setIsolatedRealm(s.equals("true") ? true : false); } // ---------------------------------------------------------------------- @@ -155,13 +134,14 @@ private static ComponentDescriptor buildComponentDescriptorImpl( PlexusConfig // configurations. we probably want to take them from files or URLs. // ---------------------------------------------------------------------- - cd.setConfiguration( configuration.getChild( "configuration" ) ); + cd.setConfiguration(configuration.getChild("configuration")); // ---------------------------------------------------------------------- // Requirements // ---------------------------------------------------------------------- - PlexusConfiguration[] requirements = configuration.getChild( "requirements" ).getChildren( "requirement" ); + PlexusConfiguration[] requirements = + configuration.getChild("requirements").getChildren("requirement"); for (PlexusConfiguration requirement : requirements) { ComponentRequirement cr; @@ -194,22 +174,19 @@ private static ComponentDescriptor buildComponentDescriptorImpl( PlexusConfig return cd; } - public static ComponentSetDescriptor buildComponentSet( PlexusConfiguration c ) - throws PlexusConfigurationException - { - return buildComponentSet( c, null ); + public static ComponentSetDescriptor buildComponentSet(PlexusConfiguration c) throws PlexusConfigurationException { + return buildComponentSet(c, null); } - public static ComponentSetDescriptor buildComponentSet( PlexusConfiguration c, ClassRealm realm ) - throws PlexusConfigurationException - { + public static ComponentSetDescriptor buildComponentSet(PlexusConfiguration c, ClassRealm realm) + throws PlexusConfigurationException { ComponentSetDescriptor csd = new ComponentSetDescriptor(); // ---------------------------------------------------------------------- // Components // ---------------------------------------------------------------------- - PlexusConfiguration[] components = c.getChild( "components" ).getChildren( "component" ); + PlexusConfiguration[] components = c.getChild("components").getChildren("component"); for (PlexusConfiguration component : components) { csd.addComponentDescriptor(buildComponentDescriptorImpl(component, realm)); @@ -219,7 +196,7 @@ public static ComponentSetDescriptor buildComponentSet( PlexusConfiguration c, C // Dependencies // ---------------------------------------------------------------------- - PlexusConfiguration[] dependencies = c.getChild( "dependencies" ).getChildren( "dependency" ); + PlexusConfiguration[] dependencies = c.getChild("dependencies").getChildren("dependency"); for (PlexusConfiguration d : dependencies) { ComponentDependency cd = new ComponentDependency(); @@ -241,20 +218,17 @@ public static ComponentSetDescriptor buildComponentSet( PlexusConfiguration c, C return csd; } - public static void writeConfiguration( PrintStream out, PlexusConfiguration configuration ) - throws PlexusConfigurationException - { - writeConfiguration( out, configuration, "" ); + public static void writeConfiguration(PrintStream out, PlexusConfiguration configuration) + throws PlexusConfigurationException { + writeConfiguration(out, configuration, ""); } - private static void writeConfiguration( PrintStream out, PlexusConfiguration configuration, String indent ) - throws PlexusConfigurationException - { - out.print( indent + "<" + configuration.getName() ); + private static void writeConfiguration(PrintStream out, PlexusConfiguration configuration, String indent) + throws PlexusConfigurationException { + out.print(indent + "<" + configuration.getName()); String[] atts = configuration.getAttributeNames(); - if ( atts.length > 0 ) - { + if (atts.length > 0) { for (String att : atts) { out.print("\n" + indent + " " + att + "='" + configuration.getAttribute(att) + "'"); } @@ -262,25 +236,23 @@ private static void writeConfiguration( PrintStream out, PlexusConfiguration con PlexusConfiguration[] pc = configuration.getChildren(); - if ( ( configuration.getValue() != null && configuration.getValue().trim().length() > 0 ) || pc.length > 0 ) - { - out.print( ">" + ( configuration.getValue() == null ? "" : configuration.getValue().trim() ) ); + if ((configuration.getValue() != null && configuration.getValue().trim().length() > 0) || pc.length > 0) { + out.print(">" + + (configuration.getValue() == null + ? "" + : configuration.getValue().trim())); - if ( pc.length > 0 ) - { + if (pc.length > 0) { out.println(); for (PlexusConfiguration aPc : pc) { writeConfiguration(out, aPc, indent + " "); } - out.print( indent ); + out.print(indent); } - out.println( "" ); - } - else - { - out.println( "/>" ); + out.println(""); + } else { + out.println("/>"); } } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/DefaultPlexusConfiguration.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/DefaultPlexusConfiguration.java index 56668723d..bbad08ac7 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/DefaultPlexusConfiguration.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/DefaultPlexusConfiguration.java @@ -23,9 +23,7 @@ /** */ -public class DefaultPlexusConfiguration - implements PlexusConfiguration -{ +public class DefaultPlexusConfiguration implements PlexusConfiguration { private String name; @@ -37,18 +35,15 @@ public class DefaultPlexusConfiguration private List childList; - protected DefaultPlexusConfiguration() - { - this( "configuration" ); + protected DefaultPlexusConfiguration() { + this("configuration"); } - protected DefaultPlexusConfiguration( String name ) - { - this( name, null ); + protected DefaultPlexusConfiguration(String name) { + this(name, null); } - protected DefaultPlexusConfiguration( String name, String value ) - { + protected DefaultPlexusConfiguration(String name, String value) { super(); this.name = name; @@ -66,13 +61,11 @@ protected DefaultPlexusConfiguration( String name, String value ) // Name handling // ---------------------------------------------------------------------- - public String getName() - { + public String getName() { return name; } - public void setName( String name ) - { + public void setName(String name) { this.name = name; } @@ -80,31 +73,26 @@ public void setName( String name ) // Value handling // ---------------------------------------------------------------------- - public String getValue() - { + public String getValue() { return value; } - public String getValue( String defaultValue ) - { + public String getValue(String defaultValue) { String value = getValue(); - if ( value == null ) - { + if (value == null) { value = defaultValue; } return value; } - public void setValue( String val ) - { + public void setValue(String val) { value = val; } - public PlexusConfiguration setValueAndGetSelf( String val ) - { - setValue( val ); + public PlexusConfiguration setValueAndGetSelf(String val) { + setValue(val); return this; } @@ -112,137 +100,112 @@ public PlexusConfiguration setValueAndGetSelf( String val ) // ---------------------------------------------------------------------- // Attribute handling // ---------------------------------------------------------------------- - public void setAttribute( String name, String value ) - { - attributes.put( name, value ); + public void setAttribute(String name, String value) { + attributes.put(name, value); } - public String getAttribute( String name ) - { - return attributes.get( name ); + public String getAttribute(String name) { + return attributes.get(name); } - public String getAttribute( String name, String defaultValue ) - { - String value = getAttribute( name ); + public String getAttribute(String name, String defaultValue) { + String value = getAttribute(name); - if ( value == null ) - { + if (value == null) { value = defaultValue; } return value; } - public String[] getAttributeNames() - { - return attributes.keySet().toArray( new String[attributes.size()] ); + public String[] getAttributeNames() { + return attributes.keySet().toArray(new String[attributes.size()]); } // ---------------------------------------------------------------------- // Child handling // ---------------------------------------------------------------------- - public PlexusConfiguration getChild( String name ) - { - return getChild( name, true ); + public PlexusConfiguration getChild(String name) { + return getChild(name, true); } - public PlexusConfiguration getChild( int i ) - { - return childList.get( i ); + public PlexusConfiguration getChild(int i) { + return childList.get(i); } - public PlexusConfiguration getChild( String name, boolean createChild ) - { - List childs = childMap.get( name ); + public PlexusConfiguration getChild(String name, boolean createChild) { + List childs = childMap.get(name); - boolean noneFound = ( childs == null || childs.size() == 0 ); + boolean noneFound = (childs == null || childs.size() == 0); - if ( noneFound && createChild ) - { - addChild( name ); + if (noneFound && createChild) { + addChild(name); - return getChild( name, false ); - } - else if ( noneFound && !createChild ) - { + return getChild(name, false); + } else if (noneFound && !createChild) { return null; - } - else - { - return childs.get( 0 ); + } else { + return childs.get(0); } } - public PlexusConfiguration[] getChildren() - { - return childList.toArray( new PlexusConfiguration[childList.size()] ); + public PlexusConfiguration[] getChildren() { + return childList.toArray(new PlexusConfiguration[childList.size()]); } - public PlexusConfiguration[] getChildren( String name ) - { + public PlexusConfiguration[] getChildren(String name) { List childs = new ArrayList(); - List childList = childMap.get( name ); + List childList = childMap.get(name); - if ( childList != null ) - { - childs.addAll( childList ); + if (childList != null) { + childs.addAll(childList); } - return childs.toArray( new PlexusConfiguration[childs.size()] ); + return childs.toArray(new PlexusConfiguration[childs.size()]); } - public void addChild( PlexusConfiguration child ) - { - childList.add( child ); + public void addChild(PlexusConfiguration child) { + childList.add(child); - List children = childMap.get( child.getName() ); - if ( children == null ) - { - childMap.put( child.getName(), children = new ArrayList() ); + List children = childMap.get(child.getName()); + if (children == null) { + childMap.put(child.getName(), children = new ArrayList()); } - children.add( child ); + children.add(child); } - public PlexusConfiguration addChild( String name ) - { + public PlexusConfiguration addChild(String name) { // we are using reflection to try to create same class childs as parent is, // since many Maven and Maven plugins stuff casts the incoming result of this call // to the evil XmlPlexusConfiguration PlexusConfiguration child = null; - try - { + try { child = getClass().newInstance(); - child.setName( name ); - } - catch ( Exception e ) - { + child.setName(name); + } catch (Exception e) { // we have a PlexusConfiguration that has no constructor(name) - child = new DefaultPlexusConfiguration( name ); + child = new DefaultPlexusConfiguration(name); } - addChild( child ); + addChild(child); return this; } - public PlexusConfiguration addChild( String name, String value ) - { - PlexusConfiguration child = new DefaultPlexusConfiguration( name, value ); + public PlexusConfiguration addChild(String name, String value) { + PlexusConfiguration child = new DefaultPlexusConfiguration(name, value); - addChild( child ); + addChild(child); return this; } - public int getChildCount() - { + public int getChildCount() { return this.childList.size(); } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusComponentDescriptorMerger.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusComponentDescriptorMerger.java index 2ccd4b8e8..286ee31d8 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusComponentDescriptorMerger.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusComponentDescriptorMerger.java @@ -17,44 +17,36 @@ * @author Kenney Westerhof * */ -public class PlexusComponentDescriptorMerger -{ +public class PlexusComponentDescriptorMerger { /** * Merges override and target, where target is updated with override. * @param override {@link ComponentDescriptor} * @param target {@link ComponentDescriptor}. */ - public static void merge( ComponentDescriptor override, ComponentDescriptor target ) - { - if ( override.getImplementation() != null ) - { - target.setImplementation( override.getImplementation() ); + public static void merge(ComponentDescriptor override, ComponentDescriptor target) { + if (override.getImplementation() != null) { + target.setImplementation(override.getImplementation()); } - mergeRequirements( override, target ); + mergeRequirements(override, target); - mergeConfiguration( override, target ); + mergeConfiguration(override, target); // TODO: other getters/setters. } - private static void mergeConfiguration( ComponentDescriptor override, ComponentDescriptor target ) - { + private static void mergeConfiguration(ComponentDescriptor override, ComponentDescriptor target) { // try to parse the override dom. If this fails, do not update anything and keep // the original target configuration. Xpp3Dom overrideDom; - try - { + try { - overrideDom = Xpp3DomBuilder.build( new StringReader( override.getConfiguration().toString() ) ); - } - catch ( XmlPullParserException e1 ) - { + overrideDom = Xpp3DomBuilder.build( + new StringReader(override.getConfiguration().toString())); + } catch (XmlPullParserException e1) { return; - } - catch ( IOException e1 ) - { + } catch (IOException e1) { return; } @@ -63,68 +55,51 @@ private static void mergeConfiguration( ComponentDescriptor override, Compone Xpp3Dom targetDom = null; - if ( target.getConfiguration() != null ) - { - try - { - targetDom = Xpp3DomBuilder.build( new StringReader( target.getConfiguration().toString() ) ); - } - catch ( XmlPullParserException e1 ) - { - } - catch ( IOException e1 ) - { + if (target.getConfiguration() != null) { + try { + targetDom = Xpp3DomBuilder.build( + new StringReader(target.getConfiguration().toString())); + } catch (XmlPullParserException e1) { + } catch (IOException e1) { } } - if ( targetDom != null ) - { - Xpp3Dom.mergeXpp3Dom( overrideDom, targetDom ); - } - else - { + if (targetDom != null) { + Xpp3Dom.mergeXpp3Dom(overrideDom, targetDom); + } else { targetDom = overrideDom; } - target.setConfiguration( new XmlPlexusConfiguration( targetDom ) ); + target.setConfiguration(new XmlPlexusConfiguration(targetDom)); } - private static void mergeRequirements( ComponentDescriptor override, ComponentDescriptor target ) - { + private static void mergeRequirements(ComponentDescriptor override, ComponentDescriptor target) { List toAdd = new ArrayList(); List toRemove = new ArrayList(); - for ( ComponentRequirement sourceReq : override.getRequirements() ) - { - for ( ComponentRequirement targetReq : target.getRequirements() ) - { + for (ComponentRequirement sourceReq : override.getRequirements()) { + for (ComponentRequirement targetReq : target.getRequirements()) { // if a fieldName is specified, only override target requirements // that also have a fieldname. - if ( sourceReq.getFieldName() != null ) - { - if ( sourceReq.getFieldName().equals( targetReq.getFieldName() ) ) - { - toRemove.add( targetReq ); - toAdd.add( sourceReq ); + if (sourceReq.getFieldName() != null) { + if (sourceReq.getFieldName().equals(targetReq.getFieldName())) { + toRemove.add(targetReq); + toAdd.add(sourceReq); break; } - } - else if ( targetReq.getFieldName() == null ) - { + } else if (targetReq.getFieldName() == null) { // no fieldnames specified - just check for the role; hints may be // overriden too. - if ( sourceReq.getRole().equals( targetReq.getRole() ) ) - { - toRemove.add( targetReq ); - toAdd.add( sourceReq ); + if (sourceReq.getRole().equals(targetReq.getRole())) { + toRemove.add(targetReq); + toAdd.add(sourceReq); } } } } - target.removeRequirements( toRemove ); - target.addRequirements( toAdd ); + target.removeRequirements(toRemove); + target.addRequirements(toAdd); } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfiguration.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfiguration.java index dfe1a99b3..d68924fda 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfiguration.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfiguration.java @@ -21,8 +21,7 @@ * example, to populate a ComponentDescriptor. Implementation of * PlexusConfiguration may be populated by any means, for example, by XML file. */ -public interface PlexusConfiguration -{ +public interface PlexusConfiguration { // ---------------------------------------------------------------------- // Name handling // ---------------------------------------------------------------------- @@ -32,7 +31,7 @@ public interface PlexusConfiguration * @return the name of this configuration */ String getName(); - + /** * Sets the name of this configuration. * @param name The name of the configuration. @@ -48,8 +47,7 @@ public interface PlexusConfiguration * @return the value of this configuration * @throws PlexusConfigurationException in case of an error. */ - String getValue() - throws PlexusConfigurationException; + String getValue() throws PlexusConfigurationException; /** * Returns the value of this configuration, or default if one cannot be @@ -57,13 +55,13 @@ String getValue() * @param defaultValue value to return if none is found * @return the value of this configuration */ - String getValue( String defaultValue ); + String getValue(String defaultValue); /** * Set the value of a configuration element. * @param value The value of the configuration element. */ - void setValue( String value ); + void setValue(String value); /** * Set the value of a configuration element and return the PlexusConfiguration object @@ -71,18 +69,18 @@ String getValue() * @param value set the value. * @return {@link PlexusConfiguration} */ - PlexusConfiguration setValueAndGetSelf( String value ); + PlexusConfiguration setValueAndGetSelf(String value); // ---------------------------------------------------------------------- // Attribute handling // ---------------------------------------------------------------------- - + /** * Sets an attribute on this configuration. * @param name name of the attribute * @param value the value of the attribute. */ - void setAttribute( String name, String value ); + void setAttribute(String name, String value); /** * Returns an array of attribute names. @@ -96,8 +94,7 @@ String getValue() * @return the value of the named attribute * @throws PlexusConfigurationException in case of an error. */ - String getAttribute( String paramName ) - throws PlexusConfigurationException; + String getAttribute(String paramName) throws PlexusConfigurationException; /** * Returns the value of the named attribute, or default if one cannot be @@ -106,7 +103,7 @@ String getAttribute( String paramName ) * @param defaultValue value to return if none is found * @return the value of the named attribute */ - String getAttribute( String name, String defaultValue ); + String getAttribute(String name, String defaultValue); // ---------------------------------------------------------------------- // Child handling @@ -117,14 +114,14 @@ String getAttribute( String paramName ) * @param child the name of the child to return * @return the child configuration of the given name */ - PlexusConfiguration getChild( String child ); + PlexusConfiguration getChild(String child); /** * Returns the child configuration at the given location. * @param i the position of the child under this configuration * @return the child configuration at the given location */ - PlexusConfiguration getChild( int i ); + PlexusConfiguration getChild(int i); /** * Returns the child configuration of the given name. @@ -133,7 +130,7 @@ String getAttribute( String paramName ) * @return the child configuration of the given name, or new child if * created */ - PlexusConfiguration getChild( String child, boolean createChild ); + PlexusConfiguration getChild(String child, boolean createChild); /** * Returns an array of all child configurations. @@ -146,21 +143,21 @@ String getAttribute( String paramName ) * @param name the name of the children configurations to return * @return an array of all child configurations with the given name */ - PlexusConfiguration[] getChildren( String name ); + PlexusConfiguration[] getChildren(String name); /** * Adds a configuration under this configuration, which acts as * a parent. * @param configuration the child configuration to add */ - void addChild( PlexusConfiguration configuration ); + void addChild(PlexusConfiguration configuration); /** * Add a child element with a given name and return the newly created element. * @param name The name of the element. * @return {@link PlexusConfiguration} */ - PlexusConfiguration addChild( String name ); + PlexusConfiguration addChild(String name); /** * Add a child element with a given name, and given value and return the @@ -169,7 +166,7 @@ String getAttribute( String paramName ) * @param value The value of the child element. * @return {@link PlexusConfiguration} */ - PlexusConfiguration addChild( String name, String value ); + PlexusConfiguration addChild(String name, String value); /** * Returns the number of directly children under this configuration. diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfigurationException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfigurationException.java index 4ea88d949..69e84fd93 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfigurationException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfigurationException.java @@ -20,18 +20,15 @@ * Exception that is thrown when an expected configuration value encounters * problems loading correctly. */ -public class PlexusConfigurationException - extends Exception -{ +public class PlexusConfigurationException extends Exception { private static final long serialVersionUID = 7559886640184983689L; /** * Construct a new PlexusConfigurationException instance. * @param message exception message */ - public PlexusConfigurationException( String message ) - { - this( message, null ); + public PlexusConfigurationException(String message) { + this(message, null); } /** @@ -39,8 +36,7 @@ public PlexusConfigurationException( String message ) * @param message exception message * @param throwable causing exception to chain */ - public PlexusConfigurationException( String message, Throwable throwable ) - { - super( message, throwable ); + public PlexusConfigurationException(String message, Throwable throwable) { + super(message, throwable); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfigurationMerger.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfigurationMerger.java index cfd4d307d..ab782da05 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfigurationMerger.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfigurationMerger.java @@ -22,8 +22,7 @@ * TODO: This merger explicity uses the XML implementation of the plexus configuration but * it must work for configurations coming from any source. */ -public class PlexusConfigurationMerger -{ +public class PlexusConfigurationMerger { // -----------------------------------+----------------------------------------------------------------- // E L E M E N T | // -----------------------------------+----------------------------------------------------------------- @@ -40,52 +39,48 @@ public class PlexusConfigurationMerger // resources | user wins, but system resources show through // -----------------------------------+----------------------------------------------------------------- // component-manager-manager | user wins, but system resources show through - // -----------------------------------+----------------------------------------------------------------- - // component-discoverer-manager | user wins, but system resources show through - // -----------------------------------+----------------------------------------------------------------- - // component-factory-manager | user wins, but system resources show through + // -----------------------------------+----------------------------------------------------------------- + // component-discoverer-manager | user wins, but system resources show through + // -----------------------------------+----------------------------------------------------------------- + // component-factory-manager | user wins, but system resources show through // -----------------------------------+----------------------------------------------------------------- // lifecycle-handler-manager | user wins, but system lifecycles show through - // -----------------------------------+----------------------------------------------------------------- - // component-composer-manager | user wins, but system lifecycles show through + // -----------------------------------+----------------------------------------------------------------- + // component-composer-manager | user wins, but system lifecycles show through // -----------------------------------+----------------------------------------------------------------- // components | user // -----------------------------------+----------------------------------------------------------------- - public static PlexusConfiguration merge( PlexusConfiguration user, PlexusConfiguration system ) - { - PlexusConfiguration mergedConfiguration = new XmlPlexusConfiguration( "plexus" ); + public static PlexusConfiguration merge(PlexusConfiguration user, PlexusConfiguration system) { + PlexusConfiguration mergedConfiguration = new XmlPlexusConfiguration("plexus"); // ---------------------------------------------------------------------- // Load on start // ---------------------------------------------------------------------- - PlexusConfiguration loadOnStart = user.getChild( "load-on-start" ); + PlexusConfiguration loadOnStart = user.getChild("load-on-start"); - if ( loadOnStart.getChildCount() != 0 ) - { - mergedConfiguration.addChild( loadOnStart ); + if (loadOnStart.getChildCount() != 0) { + mergedConfiguration.addChild(loadOnStart); } // ---------------------------------------------------------------------- // System properties // ---------------------------------------------------------------------- - PlexusConfiguration systemProperties = user.getChild( "system-properties" ); + PlexusConfiguration systemProperties = user.getChild("system-properties"); - if ( systemProperties.getChildCount() != 0 ) - { - mergedConfiguration.addChild( systemProperties ); + if (systemProperties.getChildCount() != 0) { + mergedConfiguration.addChild(systemProperties); } // ---------------------------------------------------------------------- // Configurations directory // ---------------------------------------------------------------------- - PlexusConfiguration[] configurationsDirectories = user.getChildren( "configurations-directory" ); + PlexusConfiguration[] configurationsDirectories = user.getChildren("configurations-directory"); - if ( configurationsDirectories.length != 0 ) - { + if (configurationsDirectories.length != 0) { for (PlexusConfiguration configurationsDirectory : configurationsDirectories) { mergedConfiguration.addChild(configurationsDirectory); } @@ -95,131 +90,110 @@ public static PlexusConfiguration merge( PlexusConfiguration user, PlexusConfigu // Logging // ---------------------------------------------------------------------- - PlexusConfiguration logging = user.getChild( "logging" ); + PlexusConfiguration logging = user.getChild("logging"); - if ( logging.getChildCount() != 0 ) - { - mergedConfiguration.addChild( logging ); - } - else - { - mergedConfiguration.addChild( system.getChild( "logging" ) ); + if (logging.getChildCount() != 0) { + mergedConfiguration.addChild(logging); + } else { + mergedConfiguration.addChild(system.getChild("logging")); } // ---------------------------------------------------------------------- // Container initialization phases // ---------------------------------------------------------------------- - mergedConfiguration.addChild( system.getChild( "container-initialization") ); + mergedConfiguration.addChild(system.getChild("container-initialization")); - mergedConfiguration.addChild( system.getChild( "component-lookup-manager") ); + mergedConfiguration.addChild(system.getChild("component-lookup-manager")); // ---------------------------------------------------------------------- // Component repository // ---------------------------------------------------------------------- - PlexusConfiguration componentRepository = user.getChild( "component-repository" ); + PlexusConfiguration componentRepository = user.getChild("component-repository"); - if ( componentRepository.getChildCount() != 0 ) - { - mergedConfiguration.addChild( componentRepository ); - } - else - { - mergedConfiguration.addChild( system.getChild( "component-repository" ) ); + if (componentRepository.getChildCount() != 0) { + mergedConfiguration.addChild(componentRepository); + } else { + mergedConfiguration.addChild(system.getChild("component-repository")); } // ---------------------------------------------------------------------- // Resources // ---------------------------------------------------------------------- - copyResources( system, mergedConfiguration ); + copyResources(system, mergedConfiguration); - copyResources( user, mergedConfiguration ); + copyResources(user, mergedConfiguration); // ---------------------------------------------------------------------- // Component manager manager // ---------------------------------------------------------------------- - PlexusConfiguration componentManagerManager = user.getChild( "component-manager-manager" ); + PlexusConfiguration componentManagerManager = user.getChild("component-manager-manager"); - if ( componentManagerManager.getChildCount() != 0 ) - { - mergedConfiguration.addChild( componentManagerManager ); + if (componentManagerManager.getChildCount() != 0) { + mergedConfiguration.addChild(componentManagerManager); - copyComponentManagers( system.getChild( "component-manager-manager" ), componentManagerManager ); - } - else - { - mergedConfiguration.addChild( system.getChild( "component-manager-manager" ) ); + copyComponentManagers(system.getChild("component-manager-manager"), componentManagerManager); + } else { + mergedConfiguration.addChild(system.getChild("component-manager-manager")); } // ---------------------------------------------------------------------- // Component discoverer manager // ---------------------------------------------------------------------- - PlexusConfiguration componentDiscovererManager = user.getChild( "component-discoverer-manager" ); + PlexusConfiguration componentDiscovererManager = user.getChild("component-discoverer-manager"); - if ( componentDiscovererManager.getChildCount() != 0 ) - { - mergedConfiguration.addChild( componentDiscovererManager ); + if (componentDiscovererManager.getChildCount() != 0) { + mergedConfiguration.addChild(componentDiscovererManager); - copyComponentDiscoverers( system.getChild( "component-discoverer-manager" ), componentDiscovererManager ); - } - else - { - mergedConfiguration.addChild( system.getChild( "component-discoverer-manager" ) ); + copyComponentDiscoverers(system.getChild("component-discoverer-manager"), componentDiscovererManager); + } else { + mergedConfiguration.addChild(system.getChild("component-discoverer-manager")); } // ---------------------------------------------------------------------- // Component factory manager // ---------------------------------------------------------------------- - PlexusConfiguration componentFactoryManager = user.getChild( "component-factory-manager" ); + PlexusConfiguration componentFactoryManager = user.getChild("component-factory-manager"); - if ( componentFactoryManager.getChildCount() != 0 ) - { - mergedConfiguration.addChild( componentFactoryManager ); + if (componentFactoryManager.getChildCount() != 0) { + mergedConfiguration.addChild(componentFactoryManager); - copyComponentFactories( system.getChild( "component-factory-manager" ), componentFactoryManager ); - } - else - { - mergedConfiguration.addChild( system.getChild( "component-factory-manager" ) ); + copyComponentFactories(system.getChild("component-factory-manager"), componentFactoryManager); + } else { + mergedConfiguration.addChild(system.getChild("component-factory-manager")); } // ---------------------------------------------------------------------- // Lifecycle handler managers // ---------------------------------------------------------------------- - PlexusConfiguration lifecycleHandlerManager = user.getChild( "lifecycle-handler-manager" ); + PlexusConfiguration lifecycleHandlerManager = user.getChild("lifecycle-handler-manager"); - if ( lifecycleHandlerManager.getChildCount() != 0 ) - { - mergedConfiguration.addChild( lifecycleHandlerManager ); + if (lifecycleHandlerManager.getChildCount() != 0) { + mergedConfiguration.addChild(lifecycleHandlerManager); - copyLifecycles( system.getChild( "lifecycle-handler-manager" ), lifecycleHandlerManager ); - } - else - { - mergedConfiguration.addChild( system.getChild( "lifecycle-handler-manager" ) ); + copyLifecycles(system.getChild("lifecycle-handler-manager"), lifecycleHandlerManager); + } else { + mergedConfiguration.addChild(system.getChild("lifecycle-handler-manager")); } // ---------------------------------------------------------------------- // Component factory manager // ---------------------------------------------------------------------- - PlexusConfiguration componentComposerManager = user.getChild( "component-composer-manager" ); + PlexusConfiguration componentComposerManager = user.getChild("component-composer-manager"); - if ( componentComposerManager.getChildCount() != 0 ) - { - mergedConfiguration.addChild( componentComposerManager ); + if (componentComposerManager.getChildCount() != 0) { + mergedConfiguration.addChild(componentComposerManager); - copyComponentComposers( system.getChild( "component-composer-manager" ), componentComposerManager ); - } - else - { - mergedConfiguration.addChild( system.getChild( "component-composer-manager" ) ); + copyComponentComposers(system.getChild("component-composer-manager"), componentComposerManager); + } else { + mergedConfiguration.addChild(system.getChild("component-composer-manager")); } // ---------------------------------------------------------------------- @@ -231,117 +205,102 @@ public static PlexusConfiguration merge( PlexusConfiguration user, PlexusConfigu // descriptors are stored in a Map in the component repository. // ---------------------------------------------------------------------- - PlexusConfiguration components = system.getChild( "components" ); + PlexusConfiguration components = system.getChild("components"); - mergedConfiguration.addChild( components ); + mergedConfiguration.addChild(components); - copyComponents( user.getChild( "components" ), components ); + copyComponents(user.getChild("components"), components); return mergedConfiguration; } - private static void copyResources( PlexusConfiguration source, PlexusConfiguration destination ) - { - PlexusConfiguration handlers[] = source.getChild( "resources" ).getChildren(); + private static void copyResources(PlexusConfiguration source, PlexusConfiguration destination) { + PlexusConfiguration handlers[] = source.getChild("resources").getChildren(); - PlexusConfiguration dest = destination.getChild( "resources" ); + PlexusConfiguration dest = destination.getChild("resources"); for (PlexusConfiguration handler : handlers) { dest.addChild(handler); } } - private static void copyComponentManagers( PlexusConfiguration source, PlexusConfiguration destination ) - { - try - { - PlexusConfiguration id = destination.getChild( "default-component-manager-id" ); + private static void copyComponentManagers(PlexusConfiguration source, PlexusConfiguration destination) { + try { + PlexusConfiguration id = destination.getChild("default-component-manager-id"); - String sid = source.getChild( "default-component-manager-id" ).getValue(); + String sid = source.getChild("default-component-manager-id").getValue(); - if ( id.getValue() == null ) - { - id.setValue( sid ); + if (id.getValue() == null) { + id.setValue(sid); } - } - catch ( PlexusConfigurationException e ) - { + } catch (PlexusConfigurationException e) { // do nothing } + PlexusConfiguration handlers[] = source.getChild("component-managers").getChildren("component-manager"); - PlexusConfiguration handlers[] = source.getChild( "component-managers" ).getChildren( "component-manager" ); - - PlexusConfiguration dest = destination.getChild( "component-managers" ); + PlexusConfiguration dest = destination.getChild("component-managers"); for (PlexusConfiguration handler : handlers) { dest.addChild(handler); } } - private static void copyComponentDiscoverers( PlexusConfiguration source, PlexusConfiguration destination ) - { - PlexusConfiguration handlers[] = source.getChild( "component-discoverers" ).getChildren( "component-discoverer" ); + private static void copyComponentDiscoverers(PlexusConfiguration source, PlexusConfiguration destination) { + PlexusConfiguration handlers[] = + source.getChild("component-discoverers").getChildren("component-discoverer"); - PlexusConfiguration dest = destination.getChild( "component-discoverers" ); + PlexusConfiguration dest = destination.getChild("component-discoverers"); for (PlexusConfiguration handler : handlers) { dest.addChild(handler); } } - private static void copyComponentFactories( PlexusConfiguration source, PlexusConfiguration destination ) - { - PlexusConfiguration handlers[] = source.getChild( "component-factories" ).getChildren( "component-factory" ); + private static void copyComponentFactories(PlexusConfiguration source, PlexusConfiguration destination) { + PlexusConfiguration handlers[] = source.getChild("component-factories").getChildren("component-factory"); - PlexusConfiguration dest = destination.getChild( "component-factories" ); + PlexusConfiguration dest = destination.getChild("component-factories"); for (PlexusConfiguration handler : handlers) { dest.addChild(handler); } } - private static void copyComponentComposers( PlexusConfiguration source, PlexusConfiguration destination ) - { - try - { - PlexusConfiguration id = destination.getChild( "default-component-composer-id" ); + private static void copyComponentComposers(PlexusConfiguration source, PlexusConfiguration destination) { + try { + PlexusConfiguration id = destination.getChild("default-component-composer-id"); - String sid = source.getChild( "default-component-composer-id" ).getValue(); + String sid = source.getChild("default-component-composer-id").getValue(); - if ( id.getValue() == null ) - { - id.setValue( sid ); + if (id.getValue() == null) { + id.setValue(sid); } - } - catch ( PlexusConfigurationException e ) - { + } catch (PlexusConfigurationException e) { // do nothing } - PlexusConfiguration composers[] = source.getChild( "component-composers" ).getChildren( "component-composer" ); + PlexusConfiguration composers[] = source.getChild("component-composers").getChildren("component-composer"); - PlexusConfiguration dest = destination.getChild( "component-composers" ); + PlexusConfiguration dest = destination.getChild("component-composers"); for (PlexusConfiguration composer : composers) { dest.addChild(composer); } } - private static void copyLifecycles( PlexusConfiguration source, PlexusConfiguration destination ) - { - PlexusConfiguration handlers[] = source.getChild( "lifecycle-handlers" ).getChildren( "lifecycle-handler" ); + private static void copyLifecycles(PlexusConfiguration source, PlexusConfiguration destination) { + PlexusConfiguration handlers[] = source.getChild("lifecycle-handlers").getChildren("lifecycle-handler"); - PlexusConfiguration dest = destination.getChild( "lifecycle-handlers" ); + PlexusConfiguration dest = destination.getChild("lifecycle-handlers"); for (PlexusConfiguration handler : handlers) { dest.addChild(handler); } } - private static void copyComponents( PlexusConfiguration source, PlexusConfiguration destination ) - { - PlexusConfiguration components[] = source.getChildren( "component" ); + private static void copyComponents(PlexusConfiguration source, PlexusConfiguration destination) { + PlexusConfiguration components[] = source.getChildren("component"); for (PlexusConfiguration component : components) { destination.addChild(component); diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfigurationResourceException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfigurationResourceException.java index 7ce6344ee..3573560ab 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfigurationResourceException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/PlexusConfigurationResourceException.java @@ -16,11 +16,8 @@ * limitations under the License. */ -public class PlexusConfigurationResourceException - extends Exception -{ - public PlexusConfigurationResourceException( String message ) - { - super( message ); +public class PlexusConfigurationResourceException extends Exception { + public PlexusConfigurationResourceException(String message) { + super(message); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/PlexusConfigurationReader.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/PlexusConfigurationReader.java index 1acbd3d64..8a93b239d 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/PlexusConfigurationReader.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/PlexusConfigurationReader.java @@ -7,13 +7,8 @@ import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.PlexusConfigurationException; -public interface PlexusConfigurationReader -{ - public PlexusConfiguration read( Reader reader ) - throws IOException, - PlexusConfigurationException; +public interface PlexusConfigurationReader { + public PlexusConfiguration read(Reader reader) throws IOException, PlexusConfigurationException; - public PlexusConfiguration read( InputStream inputStream ) - throws IOException, - PlexusConfigurationException; + public PlexusConfiguration read(InputStream inputStream) throws IOException, PlexusConfigurationException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/PlexusConfigurationWriter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/PlexusConfigurationWriter.java index a302172f3..1eb1df0ae 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/PlexusConfigurationWriter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/PlexusConfigurationWriter.java @@ -6,11 +6,8 @@ import org.codehaus.plexus.configuration.PlexusConfiguration; -public interface PlexusConfigurationWriter -{ - void write( Writer writer, PlexusConfiguration configuration ) - throws IOException; +public interface PlexusConfigurationWriter { + void write(Writer writer, PlexusConfiguration configuration) throws IOException; - void write( OutputStream outputStream, PlexusConfiguration configuration ) - throws IOException; + void write(OutputStream outputStream, PlexusConfiguration configuration) throws IOException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationReader.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationReader.java index 88db61aad..dd19a99b8 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationReader.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationReader.java @@ -12,31 +12,20 @@ import org.codehaus.plexus.util.xml.Xpp3DomBuilder; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -public class XmlPlexusConfigurationReader - implements PlexusConfigurationReader -{ +public class XmlPlexusConfigurationReader implements PlexusConfigurationReader { - public PlexusConfiguration read( InputStream inputStream ) - throws IOException, - PlexusConfigurationException - { - return read( new InputStreamReader( inputStream ) ); + public PlexusConfiguration read(InputStream inputStream) throws IOException, PlexusConfigurationException { + return read(new InputStreamReader(inputStream)); } - public PlexusConfiguration read( Reader reader ) - throws IOException, - PlexusConfigurationException - { - try - { - Xpp3Dom dom = Xpp3DomBuilder.build( reader ); + public PlexusConfiguration read(Reader reader) throws IOException, PlexusConfigurationException { + try { + Xpp3Dom dom = Xpp3DomBuilder.build(reader); - return new XmlPlexusConfiguration( dom ); - } - catch ( XmlPullParserException e ) - { - throw new PlexusConfigurationException( "Failed to parse configuration resource!\nError was: \'" - + e.getLocalizedMessage() + "\'", e ); + return new XmlPlexusConfiguration(dom); + } catch (XmlPullParserException e) { + throw new PlexusConfigurationException( + "Failed to parse configuration resource!\nError was: \'" + e.getLocalizedMessage() + "\'", e); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationWriter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationWriter.java index 0865fac4e..7221981bf 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationWriter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationWriter.java @@ -1,104 +1,85 @@ package org.codehaus.plexus.configuration.io; -import org.codehaus.plexus.configuration.PlexusConfiguration; - import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; -public class XmlPlexusConfigurationWriter - implements PlexusConfigurationWriter -{ +import org.codehaus.plexus.configuration.PlexusConfiguration; - public void write( OutputStream outputStream, PlexusConfiguration configuration ) - throws IOException - { - write( new OutputStreamWriter( outputStream ), configuration ); +public class XmlPlexusConfigurationWriter implements PlexusConfigurationWriter { + + public void write(OutputStream outputStream, PlexusConfiguration configuration) throws IOException { + write(new OutputStreamWriter(outputStream), configuration); } - public void write( Writer writer, PlexusConfiguration configuration ) - throws IOException - { + public void write(Writer writer, PlexusConfiguration configuration) throws IOException { int depth = 0; - display( configuration, writer, depth ); + display(configuration, writer, depth); } - private void display( PlexusConfiguration c, Writer w, int depth ) - throws IOException - { + private void display(PlexusConfiguration c, Writer w, int depth) throws IOException { int count = c.getChildCount(); - if ( count == 0 ) - { - displayTag( c, w, depth ); - } - else - { - indent( depth, w ); - w.write( '<' ); - w.write( c.getName() ); + if (count == 0) { + displayTag(c, w, depth); + } else { + indent(depth, w); + w.write('<'); + w.write(c.getName()); - attributes( c, w ); + attributes(c, w); - w.write( '>' ); - w.write( '\n' ); + w.write('>'); + w.write('\n'); - for ( int i = 0; i < count; i++ ) - { - PlexusConfiguration child = c.getChild( i ); + for (int i = 0; i < count; i++) { + PlexusConfiguration child = c.getChild(i); - display( child, w, depth + 1 ); + display(child, w, depth + 1); } - indent( depth, w ); - w.write( '<' ); - w.write( '/' ); - w.write( c.getName() ); - w.write( '>' ); - w.write( '\n' ); + indent(depth, w); + w.write('<'); + w.write('/'); + w.write(c.getName()); + w.write('>'); + w.write('\n'); } } - private void displayTag( PlexusConfiguration c, Writer w, int depth ) - throws IOException - { - String value = c.getValue( null ); - - if ( value != null ) - { - indent( depth, w ); - w.write( '<' ); - w.write( c.getName() ); - - attributes( c, w ); - - w.write( '>' ); - w.write( c.getValue( null ) ); - w.write( '<' ); - w.write( '/' ); - w.write( c.getName() ); - w.write( '>' ); - w.write( '\n' ); - } - else - { - indent( depth, w ); - w.write( '<' ); - w.write( c.getName() ); - - attributes( c, w ); - - w.write( '/' ); - w.write( '>' ); - w.write( "\n" ); + private void displayTag(PlexusConfiguration c, Writer w, int depth) throws IOException { + String value = c.getValue(null); + + if (value != null) { + indent(depth, w); + w.write('<'); + w.write(c.getName()); + + attributes(c, w); + + w.write('>'); + w.write(c.getValue(null)); + w.write('<'); + w.write('/'); + w.write(c.getName()); + w.write('>'); + w.write('\n'); + } else { + indent(depth, w); + w.write('<'); + w.write(c.getName()); + + attributes(c, w); + + w.write('/'); + w.write('>'); + w.write("\n"); } } - private void attributes( PlexusConfiguration c, Writer w ) - throws IOException - { + private void attributes(PlexusConfiguration c, Writer w) throws IOException { String[] names = c.getAttributeNames(); for (String name : names) { @@ -111,13 +92,9 @@ private void attributes( PlexusConfiguration c, Writer w ) } } - private void indent( int depth, Writer w ) - throws IOException - { - for ( int i = 0; i < depth; i++ ) - { - w.write( ' ' ); + private void indent(int depth, Writer w) throws IOException { + for (int i = 0; i < depth; i++) { + w.write(' '); } } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/source/ChainedConfigurationSource.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/source/ChainedConfigurationSource.java index e23c3ac59..09fc5934b 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/source/ChainedConfigurationSource.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/source/ChainedConfigurationSource.java @@ -10,21 +10,17 @@ * author and want to create a custom source of configuration for the components in your application then you would most * likely want to create a chained configuration source where you can decide the order of processing, but still have the * container perform its default behavior. - * + * * @author Jason van Zyl */ -public class ChainedConfigurationSource - implements ConfigurationSource -{ +public class ChainedConfigurationSource implements ConfigurationSource { private List configurationSources; - public ChainedConfigurationSource( List configurationSources ) - { + public ChainedConfigurationSource(List configurationSources) { this.configurationSources = configurationSources; } - public PlexusConfiguration getConfiguration( ComponentDescriptor componentDescriptor ) - { + public PlexusConfiguration getConfiguration(ComponentDescriptor componentDescriptor) { for (Object configurationSource1 : configurationSources) { ConfigurationSource configurationSource = (ConfigurationSource) configurationSource1; @@ -38,8 +34,7 @@ public PlexusConfiguration getConfiguration( ComponentDescriptor componentDescri return null; } - public List getConfigurationSources() - { + public List getConfigurationSources() { return configurationSources; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/source/ConfigurationSource.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/source/ConfigurationSource.java index e46e66130..25ec1f765 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/source/ConfigurationSource.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/source/ConfigurationSource.java @@ -8,12 +8,11 @@ * common usecase for this is to create a unified configuration for a set of components. For an application it is more * convenient to present the user with a single configuration, instead of making users work directly with a Plexus * configuration file which exposes component details including implementation, and wiring information. - * + * * @author Jason van Zyl */ -public interface ConfigurationSource -{ +public interface ConfigurationSource { String ROLE = ConfigurationSource.class.getName(); - PlexusConfiguration getConfiguration( ComponentDescriptor componentDescriptor ); + PlexusConfiguration getConfiguration(ComponentDescriptor componentDescriptor); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/source/ContainerConfigurationSource.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/source/ContainerConfigurationSource.java index 0ee6cd31b..63ae94f1f 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/source/ContainerConfigurationSource.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/source/ContainerConfigurationSource.java @@ -4,16 +4,12 @@ import org.codehaus.plexus.configuration.PlexusConfiguration; /** @author Jason van Zyl */ -public class ContainerConfigurationSource - implements ConfigurationSource -{ - public PlexusConfiguration getConfiguration( ComponentDescriptor componentDescriptor ) - { - if ( componentDescriptor.hasConfiguration() ) - { +public class ContainerConfigurationSource implements ConfigurationSource { + public PlexusConfiguration getConfiguration(ComponentDescriptor componentDescriptor) { + if (componentDescriptor.hasConfiguration()) { return componentDescriptor.getConfiguration(); } - return null; + return null; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/xml/XmlPlexusConfiguration.java b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/xml/XmlPlexusConfiguration.java index 2d58892c5..05825fcac 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/xml/XmlPlexusConfiguration.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/configuration/xml/XmlPlexusConfiguration.java @@ -25,27 +25,21 @@ /** */ -public class XmlPlexusConfiguration - extends DefaultPlexusConfiguration -{ - public XmlPlexusConfiguration() - { +public class XmlPlexusConfiguration extends DefaultPlexusConfiguration { + public XmlPlexusConfiguration() { super(); } - public XmlPlexusConfiguration( String name ) - { - super( name ); + public XmlPlexusConfiguration(String name) { + super(name); } - - public XmlPlexusConfiguration( String name, String value ) - { - super( name, value ); + + public XmlPlexusConfiguration(String name, String value) { + super(name, value); } - public XmlPlexusConfiguration( Xpp3Dom dom ) - { - super( dom.getName(), dom.getValue() ); + public XmlPlexusConfiguration(Xpp3Dom dom) { + super(dom.getName(), dom.getValue()); // attrs String[] attributes = dom.getAttributeNames(); @@ -56,9 +50,8 @@ public XmlPlexusConfiguration( Xpp3Dom dom ) // children int childCount = dom.getChildCount(); - for ( int i = 0; i < childCount; i++ ) - { - addChild( new XmlPlexusConfiguration( dom.getChild( i ) ) ); + for (int i = 0; i < childCount; i++) { + addChild(new XmlPlexusConfiguration(dom.getChild(i))); } } @@ -66,18 +59,14 @@ public XmlPlexusConfiguration( Xpp3Dom dom ) // // ---------------------------------------------------------------------- - public String toString() - { + public String toString() { StringWriter sw = new StringWriter(); XmlPlexusConfigurationWriter xw = new XmlPlexusConfigurationWriter(); - try - { - xw.write( sw, this ); - } - catch ( IOException e ) - { + try { + xw.write(sw, this); + } catch (IOException e) { // will not happen with StringWriter } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/AbstractContainerInitializationPhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/AbstractContainerInitializationPhase.java index 47a2215b0..69b656b14 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/AbstractContainerInitializationPhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/AbstractContainerInitializationPhase.java @@ -19,7 +19,4 @@ /** * @author Jason van Zyl */ -public abstract class AbstractContainerInitializationPhase - implements ContainerInitializationPhase -{ -} +public abstract class AbstractContainerInitializationPhase implements ContainerInitializationPhase {} diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/AbstractCoreComponentInitializationPhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/AbstractCoreComponentInitializationPhase.java index f66c20864..fd6709d46 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/AbstractCoreComponentInitializationPhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/AbstractCoreComponentInitializationPhase.java @@ -17,15 +17,11 @@ */ /** @author Jason van Zyl */ -public abstract class AbstractCoreComponentInitializationPhase - extends AbstractContainerInitializationPhase -{ - public void execute( ContainerInitializationContext context ) - throws ContainerInitializationException - { - initializeCoreComponent( context ); +public abstract class AbstractCoreComponentInitializationPhase extends AbstractContainerInitializationPhase { + public void execute(ContainerInitializationContext context) throws ContainerInitializationException { + initializeCoreComponent(context); } - protected abstract void initializeCoreComponent( ContainerInitializationContext context ) - throws ContainerInitializationException; + protected abstract void initializeCoreComponent(ContainerInitializationContext context) + throws ContainerInitializationException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/ContainerInitializationContext.java b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/ContainerInitializationContext.java index 7a6b819c9..c2536e4cb 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/ContainerInitializationContext.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/ContainerInitializationContext.java @@ -25,8 +25,7 @@ /** * @author Jason van Zyl */ -public class ContainerInitializationContext -{ +public class ContainerInitializationContext { private DefaultPlexusContainer container; ClassWorld classWorld; @@ -37,12 +36,12 @@ public class ContainerInitializationContext ContainerConfiguration containerConfiguration; - public ContainerInitializationContext( DefaultPlexusContainer container, - ClassWorld classWorld, - ClassRealm containerRealm, - PlexusConfiguration configuration, - ContainerConfiguration containerConfiguration ) - { + public ContainerInitializationContext( + DefaultPlexusContainer container, + ClassWorld classWorld, + ClassRealm containerRealm, + PlexusConfiguration configuration, + ContainerConfiguration containerConfiguration) { this.container = container; this.classWorld = classWorld; @@ -54,28 +53,23 @@ public ContainerInitializationContext( DefaultPlexusContainer container, this.containerConfiguration = containerConfiguration; } - public DefaultPlexusContainer getContainer() - { + public DefaultPlexusContainer getContainer() { return container; } - public ClassWorld getClassWorld() - { + public ClassWorld getClassWorld() { return classWorld; } - public ClassRealm getContainerRealm() - { + public ClassRealm getContainerRealm() { return containerRealm; } - public PlexusConfiguration getContainerXmlConfiguration() - { + public PlexusConfiguration getContainerXmlConfiguration() { return containerXmlConfiguration; } - public ContainerConfiguration getContainerConfiguration() - { + public ContainerConfiguration getContainerConfiguration() { return containerConfiguration; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/ContainerInitializationException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/ContainerInitializationException.java index 65ed22a36..9571143e9 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/ContainerInitializationException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/ContainerInitializationException.java @@ -19,22 +19,16 @@ /** * @author Jason van Zyl */ -public class ContainerInitializationException - extends Exception -{ - public ContainerInitializationException( String id ) - { - super( id ); +public class ContainerInitializationException extends Exception { + public ContainerInitializationException(String id) { + super(id); } - public ContainerInitializationException( String id, - Throwable throwable ) - { - super( id, throwable ); + public ContainerInitializationException(String id, Throwable throwable) { + super(id, throwable); } - public ContainerInitializationException( Throwable throwable ) - { - super( throwable ); + public ContainerInitializationException(Throwable throwable) { + super(throwable); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/ContainerInitializationPhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/ContainerInitializationPhase.java index 8e333faa3..cc030d93d 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/ContainerInitializationPhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/ContainerInitializationPhase.java @@ -19,10 +19,8 @@ /** * @author Jason van Zyl */ -public interface ContainerInitializationPhase -{ +public interface ContainerInitializationPhase { String ROLE = ContainerInitializationPhase.class.getName(); - void execute( ContainerInitializationContext context ) - throws ContainerInitializationException; + void execute(ContainerInitializationContext context) throws ContainerInitializationException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeComponentDiscovererManagerPhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeComponentDiscovererManagerPhase.java index 7ccf43b3f..22e85fe6a 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeComponentDiscovererManagerPhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeComponentDiscovererManagerPhase.java @@ -22,33 +22,29 @@ /** * @author Jason van Zyl */ -public class InitializeComponentDiscovererManagerPhase - extends AbstractCoreComponentInitializationPhase -{ - public void initializeCoreComponent( ContainerInitializationContext context ) - throws ContainerInitializationException - { - ComponentDiscovererManager componentDiscovererManager = context.getContainerConfiguration().getComponentDiscovererManager(); - - context.getContainer().setComponentDiscovererManager( componentDiscovererManager ); - - for ( ComponentDiscoveryListener listener : componentDiscovererManager.getComponentDiscoveryListeners().keySet() ) - { - try - { +public class InitializeComponentDiscovererManagerPhase extends AbstractCoreComponentInitializationPhase { + public void initializeCoreComponent(ContainerInitializationContext context) + throws ContainerInitializationException { + ComponentDiscovererManager componentDiscovererManager = + context.getContainerConfiguration().getComponentDiscovererManager(); + + context.getContainer().setComponentDiscovererManager(componentDiscovererManager); + + for (ComponentDiscoveryListener listener : + componentDiscovererManager.getComponentDiscoveryListeners().keySet()) { + try { // This is a hack until we have completely live components - context.getContainer().addComponent( listener, listener.getClass().getName() ); + context.getContainer() + .addComponent(listener, listener.getClass().getName()); - context.getContainer().getComponentDiscovererManager().removeComponentDiscoveryListener( listener ); + context.getContainer().getComponentDiscovererManager().removeComponentDiscoveryListener(listener); - ComponentDiscoveryListener cdl = context.getContainer().lookup( listener.getClass() ); + ComponentDiscoveryListener cdl = context.getContainer().lookup(listener.getClass()); - context.getContainer().getComponentDiscovererManager().registerComponentDiscoveryListener( cdl ); - } - catch ( Exception e ) - { - throw new ContainerInitializationException( "Error initializing component discovery listener.", e ); + context.getContainer().getComponentDiscovererManager().registerComponentDiscoveryListener(cdl); + } catch (Exception e) { + throw new ContainerInitializationException("Error initializing component discovery listener.", e); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeComponentFactoryManagerPhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeComponentFactoryManagerPhase.java index 8e0a2aa43..a02de88ec 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeComponentFactoryManagerPhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeComponentFactoryManagerPhase.java @@ -24,29 +24,24 @@ /** * @author Jason van Zyl */ -public class InitializeComponentFactoryManagerPhase - extends AbstractCoreComponentInitializationPhase -{ - public void initializeCoreComponent( ContainerInitializationContext context ) - throws ContainerInitializationException - { - ComponentFactoryManager componentFactoryManager = context.getContainerConfiguration().getComponentFactoryManager(); +public class InitializeComponentFactoryManagerPhase extends AbstractCoreComponentInitializationPhase { + public void initializeCoreComponent(ContainerInitializationContext context) + throws ContainerInitializationException { + ComponentFactoryManager componentFactoryManager = + context.getContainerConfiguration().getComponentFactoryManager(); - if ( componentFactoryManager instanceof Contextualizable ) - { - //TODO: this is wrong here jvz. - context.getContainer().getContext().put( PlexusConstants.PLEXUS_KEY, context.getContainer() ); + if (componentFactoryManager instanceof Contextualizable) { + // TODO: this is wrong here jvz. + context.getContainer().getContext().put(PlexusConstants.PLEXUS_KEY, context.getContainer()); - try - { - ( (Contextualizable) componentFactoryManager).contextualize( context.getContainer().getContext() ); - } - catch ( ContextException e ) - { - throw new ContainerInitializationException( "Error contextualization component factory manager.", e ); + try { + ((Contextualizable) componentFactoryManager) + .contextualize(context.getContainer().getContext()); + } catch (ContextException e) { + throw new ContainerInitializationException("Error contextualization component factory manager.", e); } } - context.getContainer().setComponentFactoryManager( componentFactoryManager ); + context.getContainer().setComponentFactoryManager(componentFactoryManager); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeComponentRegistryPhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeComponentRegistryPhase.java index 5a3f3c7b3..8188c8624 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeComponentRegistryPhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeComponentRegistryPhase.java @@ -16,76 +16,68 @@ * limitations under the License. */ -import org.codehaus.plexus.component.repository.ComponentRepository; -import org.codehaus.plexus.component.repository.ComponentDescriptor; -import org.codehaus.plexus.component.repository.io.PlexusTools; +import org.codehaus.plexus.ComponentRegistry; +import org.codehaus.plexus.DefaultComponentRegistry; import org.codehaus.plexus.component.composition.CycleDetectedInComponentGraphException; import org.codehaus.plexus.component.manager.PerLookupComponentManagerFactory; import org.codehaus.plexus.component.manager.SingletonComponentManagerFactory; +import org.codehaus.plexus.component.repository.ComponentDescriptor; +import org.codehaus.plexus.component.repository.ComponentRepository; +import org.codehaus.plexus.component.repository.io.PlexusTools; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.PlexusConfigurationException; -import org.codehaus.plexus.DefaultComponentRegistry; -import org.codehaus.plexus.ComponentRegistry; import org.codehaus.plexus.lifecycle.LifecycleHandlerManager; /** * @author Jason van Zyl */ -public class InitializeComponentRegistryPhase - implements ContainerInitializationPhase -{ - public void execute( ContainerInitializationContext context ) - throws ContainerInitializationException - { - ComponentRepository repository = getComponentRepository( context ); +public class InitializeComponentRegistryPhase implements ContainerInitializationPhase { + public void execute(ContainerInitializationContext context) throws ContainerInitializationException { + ComponentRepository repository = getComponentRepository(context); - LifecycleHandlerManager lifecycleHandlerManager = getLifecycleHandlerManager( context ); + LifecycleHandlerManager lifecycleHandlerManager = getLifecycleHandlerManager(context); - ComponentRegistry componentRegistry = new DefaultComponentRegistry( context.getContainer(), - repository, - lifecycleHandlerManager ); + ComponentRegistry componentRegistry = + new DefaultComponentRegistry(context.getContainer(), repository, lifecycleHandlerManager); - componentRegistry.registerComponentManagerFactory( new PerLookupComponentManagerFactory() ); + componentRegistry.registerComponentManagerFactory(new PerLookupComponentManagerFactory()); - componentRegistry.registerComponentManagerFactory( new SingletonComponentManagerFactory() ); + componentRegistry.registerComponentManagerFactory(new SingletonComponentManagerFactory()); - context.getContainer().setComponentRegistry( componentRegistry ); + context.getContainer().setComponentRegistry(componentRegistry); } - private ComponentRepository getComponentRepository( ContainerInitializationContext context ) - throws ContainerInitializationException - { + private ComponentRepository getComponentRepository(ContainerInitializationContext context) + throws ContainerInitializationException { ComponentRepository repository = context.getContainerConfiguration().getComponentRepository(); // Add the components defined in the container xml configuration - try - { + try { PlexusConfiguration configuration = context.getContainerXmlConfiguration(); - PlexusConfiguration[] componentConfigurations = configuration.getChild( "components" ).getChildren( "component" ); - for ( PlexusConfiguration componentConfiguration : componentConfigurations ) - { - ComponentDescriptor componentDescriptor = PlexusTools.buildComponentDescriptor( componentConfiguration, context.getContainer().getContainerRealm() ); - componentDescriptor.setRealm( context.getContainer().getContainerRealm() ); - repository.addComponentDescriptor( componentDescriptor ); + PlexusConfiguration[] componentConfigurations = + configuration.getChild("components").getChildren("component"); + for (PlexusConfiguration componentConfiguration : componentConfigurations) { + ComponentDescriptor componentDescriptor = PlexusTools.buildComponentDescriptor( + componentConfiguration, context.getContainer().getContainerRealm()); + componentDescriptor.setRealm(context.getContainer().getContainerRealm()); + repository.addComponentDescriptor(componentDescriptor); } + } catch (PlexusConfigurationException e) { + throw new ContainerInitializationException( + "Error initializing component repository: " + "Cannot unmarshall component descriptor: ", e); + } catch (CycleDetectedInComponentGraphException e) { + throw new ContainerInitializationException( + "A cycle has been detected in the components of the system: ", e); } - catch ( PlexusConfigurationException e ) - { - throw new ContainerInitializationException( "Error initializing component repository: " + "Cannot unmarshall component descriptor: ", e ); - } - catch ( CycleDetectedInComponentGraphException e ) - { - throw new ContainerInitializationException( "A cycle has been detected in the components of the system: ", e ); - } - + return repository; } - private LifecycleHandlerManager getLifecycleHandlerManager( ContainerInitializationContext context ) - { - LifecycleHandlerManager lifecycleHandlerManager = context.getContainerConfiguration().getLifecycleHandlerManager(); + private LifecycleHandlerManager getLifecycleHandlerManager(ContainerInitializationContext context) { + LifecycleHandlerManager lifecycleHandlerManager = + context.getContainerConfiguration().getLifecycleHandlerManager(); lifecycleHandlerManager.initialize(); return lifecycleHandlerManager; } -} \ No newline at end of file +} diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeContainerConfigurationSourcePhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeContainerConfigurationSourcePhase.java index 807867908..d7877716c 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeContainerConfigurationSourcePhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeContainerConfigurationSourcePhase.java @@ -23,12 +23,9 @@ * @author Jason van Zyl * @author cstamas */ -public class InitializeContainerConfigurationSourcePhase - extends AbstractCoreComponentInitializationPhase -{ - public void initializeCoreComponent( ContainerInitializationContext context ) - throws ContainerInitializationException - { +public class InitializeContainerConfigurationSourcePhase extends AbstractCoreComponentInitializationPhase { + public void initializeCoreComponent(ContainerInitializationContext context) + throws ContainerInitializationException { ConfigurationSource configurationSource = context.getContainer().getConfigurationSource(); // ---------------------------------------------------------------------- @@ -36,10 +33,9 @@ public void initializeCoreComponent( ContainerInitializationContext context ) // to check. If it hasn't then we will add the default container config source. // ---------------------------------------------------------------------- - if ( configurationSource == null ) - { + if (configurationSource == null) { // adding default source for container to enable lookups - context.getContainer().setConfigurationSource( new ContainerConfigurationSource() ); + context.getContainer().setConfigurationSource(new ContainerConfigurationSource()); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeLoggerManagerPhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeLoggerManagerPhase.java index 80589fa27..5f635f9fc 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeLoggerManagerPhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeLoggerManagerPhase.java @@ -26,12 +26,9 @@ import org.codehaus.plexus.logging.console.ConsoleLoggerManager; /** @author Jason van Zyl */ -public class InitializeLoggerManagerPhase - extends AbstractCoreComponentInitializationPhase -{ - public void initializeCoreComponent( ContainerInitializationContext context ) - throws ContainerInitializationException - { +public class InitializeLoggerManagerPhase extends AbstractCoreComponentInitializationPhase { + public void initializeCoreComponent(ContainerInitializationContext context) + throws ContainerInitializationException { LoggerManager loggerManager = context.getContainer().getLoggerManager(); // ---------------------------------------------------------------------- @@ -41,39 +38,32 @@ public void initializeCoreComponent( ContainerInitializationContext context ) // work then we'll programmatcially stuff in the console logger. // ---------------------------------------------------------------------- - if ( loggerManager == null ) - { - try - { - loggerManager = context.getContainer().lookup( LoggerManager.class ); - } - catch ( ComponentLookupException e ) - { + if (loggerManager == null) { + try { + loggerManager = context.getContainer().lookup(LoggerManager.class); + } catch (ComponentLookupException e) { ComponentDescriptor cd = new ComponentDescriptor(); - cd.setRole( LoggerManager.ROLE ); + cd.setRole(LoggerManager.ROLE); - cd.setRoleHint( PlexusConstants.PLEXUS_DEFAULT_HINT ); + cd.setRoleHint(PlexusConstants.PLEXUS_DEFAULT_HINT); - cd.setImplementation( ConsoleLoggerManager.class.getName() ); + cd.setImplementation(ConsoleLoggerManager.class.getName()); - try - { - context.getContainer().addComponentDescriptor( cd ); - } - catch ( CycleDetectedInComponentGraphException cre ) - { - throw new ContainerInitializationException( "Error setting up logging manager.", cre ); + try { + context.getContainer().addComponentDescriptor(cd); + } catch (CycleDetectedInComponentGraphException cre) { + throw new ContainerInitializationException("Error setting up logging manager.", cre); } - loggerManager = new ConsoleLoggerManager( "info" ); + loggerManager = new ConsoleLoggerManager("info"); } - context.getContainer().setLoggerManager( loggerManager ); + context.getContainer().setLoggerManager(loggerManager); } - Logger logger = loggerManager.getLoggerForComponent( PlexusContainer.class.getName() ); + Logger logger = loggerManager.getLoggerForComponent(PlexusContainer.class.getName()); - context.getContainer().enableLogging( logger ); + context.getContainer().enableLogging(logger); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeSystemPropertiesPhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeSystemPropertiesPhase.java index b5e011c55..52b2ebdff 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeSystemPropertiesPhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeSystemPropertiesPhase.java @@ -21,14 +21,11 @@ /** * @author Jason van Zyl */ -public class InitializeSystemPropertiesPhase - extends AbstractContainerInitializationPhase -{ - public void execute( ContainerInitializationContext context ) - throws ContainerInitializationException - { - PlexusConfiguration[] systemProperties = - context.getContainerXmlConfiguration().getChild( "system-properties" ).getChildren( "property" ); +public class InitializeSystemPropertiesPhase extends AbstractContainerInitializationPhase { + public void execute(ContainerInitializationContext context) throws ContainerInitializationException { + PlexusConfiguration[] systemProperties = context.getContainerXmlConfiguration() + .getChild("system-properties") + .getChildren("property"); for (PlexusConfiguration systemProperty : systemProperties) { String name = systemProperty.getAttribute("name", null); diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeUserConfigurationSourcePhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeUserConfigurationSourcePhase.java index 38bf90ac9..7d6a0461b 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeUserConfigurationSourcePhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/container/initialization/InitializeUserConfigurationSourcePhase.java @@ -30,72 +30,60 @@ * @author Jason van Zyl * @author cstamas */ -public class InitializeUserConfigurationSourcePhase - extends AbstractCoreComponentInitializationPhase -{ - public void initializeCoreComponent( ContainerInitializationContext context ) - throws ContainerInitializationException - { +public class InitializeUserConfigurationSourcePhase extends AbstractCoreComponentInitializationPhase { + public void initializeCoreComponent(ContainerInitializationContext context) + throws ContainerInitializationException { ConfigurationSource existingConfigurationSource = context.getContainer().getConfigurationSource(); - try - { + try { // is the user overriding the ConfigurationSource (role-hint: default) or only extending it? - if ( context.getContainer().hasComponent( ConfigurationSource.class, PlexusConstants.PLEXUS_DEFAULT_HINT ) ) - { + if (context.getContainer().hasComponent(ConfigurationSource.class, PlexusConstants.PLEXUS_DEFAULT_HINT)) { // overriding - ConfigurationSource cs = context.getContainer().lookup( ConfigurationSource.class ); + ConfigurationSource cs = context.getContainer().lookup(ConfigurationSource.class); // swap the user provided configuration source with current one - context.getContainer().setConfigurationSource( cs ); - } - else - { + context.getContainer().setConfigurationSource(cs); + } else { // extending - List userConfigurationSources = context.getContainer().lookupList( ConfigurationSource.class ); + List userConfigurationSources = + context.getContainer().lookupList(ConfigurationSource.class); - if ( userConfigurationSources.size() > 0 ) - { + if (userConfigurationSources.size() > 0) { List configurationSources = - new ArrayList( userConfigurationSources.size() + 1 ); + new ArrayList(userConfigurationSources.size() + 1); // adding user provied ones to be able to interfere - configurationSources.addAll( userConfigurationSources ); + configurationSources.addAll(userConfigurationSources); // at the end adding the container source, to make sure config will be returned // from plexus.xml if no user interference is given - configurationSources.add( existingConfigurationSource ); - - ConfigurationSource configurationSource = new ChainedConfigurationSource( configurationSources ); + configurationSources.add(existingConfigurationSource); - context.getContainer().setConfigurationSource( configurationSource ); + ConfigurationSource configurationSource = new ChainedConfigurationSource(configurationSources); + context.getContainer().setConfigurationSource(configurationSource); } // register the default source, either the chained or the existing one as default ComponentDescriptor cd = new ComponentDescriptor(); - cd.setRole( ConfigurationSource.ROLE ); + cd.setRole(ConfigurationSource.ROLE); - cd.setRoleHint( PlexusConstants.PLEXUS_DEFAULT_HINT ); + cd.setRoleHint(PlexusConstants.PLEXUS_DEFAULT_HINT); - cd.setImplementationClass( context.getContainer().getConfigurationSource().getClass() ); + cd.setImplementationClass( + context.getContainer().getConfigurationSource().getClass()); - try - { - context.getContainer().addComponentDescriptor( cd ); - } - catch ( CycleDetectedInComponentGraphException cre ) - { - throw new ContainerInitializationException( "Error setting up configuration source.", cre ); + try { + context.getContainer().addComponentDescriptor(cd); + } catch (CycleDetectedInComponentGraphException cre) { + throw new ContainerInitializationException("Error setting up configuration source.", cre); } } - } - catch ( ComponentLookupException e ) - { - throw new ContainerInitializationException( "Error setting up user configuration source.", e ); + } catch (ComponentLookupException e) { + throw new ContainerInitializationException("Error setting up user configuration source.", e); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/context/Context.java b/plexus-container-default/src/main/java/org/codehaus/plexus/context/Context.java index 901f4ab7c..c03373590 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/context/Context.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/context/Context.java @@ -21,15 +21,14 @@ /** * Context is a Map of arbitrary data associated with the container. */ -public interface Context -{ +public interface Context { /** * Returns true if this context contains a value for the specified key. * * @param key the key to search * @return true if the key was found; false otherwise */ - boolean contains( Object key ); + boolean contains(Object key); /** * Returns the value of the key. If the key can't be found it will throw a exception. @@ -38,8 +37,7 @@ public interface Context * @return returns the value associated with the key * @throws ContextException if the key doesn't exist */ - Object get( Object key ) - throws ContextException; + Object get(Object key) throws ContextException; /** * Utility method to retrieve containerContext data. @@ -56,8 +54,7 @@ Object get( Object key ) * @param value the item * @throws IllegalStateException if this context is read-only */ - public void put( Object key, Object value ) - throws IllegalStateException; + public void put(Object key, Object value) throws IllegalStateException; // todo [dain] this isn't needed anymore since containers are no longer nestable /** @@ -69,8 +66,7 @@ public void put( Object key, Object value ) * @param key the items key * @throws IllegalStateException if this context is read-only */ - void hide( Object key ) - throws IllegalStateException; + void hide(Object key) throws IllegalStateException; /** * Make the containerContext read-only. diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/context/ContextException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/context/ContextException.java index 0f859ed9b..a9eea45f8 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/context/ContextException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/context/ContextException.java @@ -1,6 +1,5 @@ package org.codehaus.plexus.context; - /* * Copyright 2001-2006 Codehaus Foundation. * @@ -27,9 +26,7 @@ * @author Avalon Development Team * @version CVS $Revision$ $Date$ */ -public class ContextException - extends Exception -{ +public class ContextException extends Exception { private static final long serialVersionUID = 2030206863811644180L; /** @@ -37,9 +34,8 @@ public class ContextException * * @param message The detail message for this exception. */ - public ContextException( final String message ) - { - this( message, null ); + public ContextException(final String message) { + this(message, null); } /** @@ -48,8 +44,7 @@ public ContextException( final String message ) * @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 ); + public ContextException(final String message, final Throwable throwable) { + super(message, throwable); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/context/ContextMapAdapter.java b/plexus-container-default/src/main/java/org/codehaus/plexus/context/ContextMapAdapter.java index 56daa0b93..d59e856ae 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/context/ContextMapAdapter.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/context/ContextMapAdapter.java @@ -1,6 +1,5 @@ package org.codehaus.plexus.context; - /* * Copyright 2001-2006 Codehaus Foundation. * @@ -19,33 +18,23 @@ import java.util.HashMap; -public class ContextMapAdapter - extends HashMap -{ +public class ContextMapAdapter extends HashMap { private Context context; - public ContextMapAdapter( Context context ) - { + public ContextMapAdapter(Context context) { this.context = context; } - public Object get( Object key ) - { - try - { - Object value = context.get( key ); - - if ( value instanceof String ) - { + public Object get(Object key) { + try { + Object value = context.get(key); + + if (value instanceof String) { return value; - } - else - { + } else { return null; } - } - catch ( ContextException e ) - { + } catch (ContextException e) { return null; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/context/DefaultContext.java b/plexus-container-default/src/main/java/org/codehaus/plexus/context/DefaultContext.java index 176dad774..17d236d5d 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/context/DefaultContext.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/context/DefaultContext.java @@ -32,9 +32,7 @@ * * @author Avalon Development Team */ -public class DefaultContext - implements Context -{ +public class DefaultContext implements Context { /** * Context data. */ @@ -48,9 +46,7 @@ public class DefaultContext /** * Create an empty Context. */ - public DefaultContext() - { - } + public DefaultContext() {} /** * Create a Context with specified data. The specified data is copied into the context so any subsequent updates @@ -59,76 +55,59 @@ public DefaultContext() * * @param contextData the containerContext data */ - public DefaultContext( Map contextData ) - { - if ( contextData == null ) - { - throw new NullPointerException( "contextData is null" ); + public DefaultContext(Map contextData) { + if (contextData == null) { + throw new NullPointerException("contextData is null"); } // check for nulls in key and value - for ( Entry entry : contextData.entrySet() ) - { + for (Entry entry : contextData.entrySet()) { Object key = entry.getKey(); Object value = entry.getValue(); - if ( key == null ) - { - throw new IllegalArgumentException( "Key is null" ); + if (key == null) { + throw new IllegalArgumentException("Key is null"); } - if ( value != null ) - { - this.contextData.put( key, value ); + if (value != null) { + this.contextData.put(key, value); } } } - public boolean contains( Object key ) - { - Object data = contextData.get( key ); + public boolean contains(Object key) { + Object data = contextData.get(key); return data != null; } - public Object get( Object key ) - throws ContextException - { - Object data = contextData.get( key ); + public Object get(Object key) throws ContextException { + Object data = contextData.get(key); - if ( data == null ) - { + if (data == null) { // There is no data for the key - throw new ContextException( "Unable to resolve context key: " + key ); + throw new ContextException("Unable to resolve context key: " + key); } return data; } - public void put( Object key, Object value ) - throws IllegalStateException - { + public void put(Object key, Object value) throws IllegalStateException { checkWriteable(); // check for a null key - if (key == null) - { + if (key == null) { throw new IllegalArgumentException("Key is null"); } - if ( value == null ) - { - contextData.remove( key ); - } - else - { - contextData.put( key, value ); + if (value == null) { + contextData.remove(key); + } else { + contextData.put(key, value); } } - public void hide( Object key ) - throws IllegalStateException - { + public void hide(Object key) throws IllegalStateException { checkWriteable(); - - contextData.remove( key ); + + contextData.remove(key); } /** @@ -136,10 +115,8 @@ public void hide( Object key ) * * @return the containerContext data */ - public Map getContextData() - { - return Collections.unmodifiableMap( contextData ); - + public Map getContextData() { + return Collections.unmodifiableMap(contextData); } /** @@ -147,9 +124,8 @@ public Map getContextData() * Any attempt to write to the containerContext via put() * will result in an IllegalStateException. */ - public void makeReadOnly() - { - readOnly.set( true ); + public void makeReadOnly() { + readOnly.set(true); } /** @@ -157,17 +133,13 @@ public void makeReadOnly() * * @throws java.lang.IllegalStateException if containerContext is read only */ - protected void checkWriteable() - throws IllegalStateException - { - if ( readOnly.get() ) - { - throw new IllegalStateException( "Context is read only and can not be modified" ); + protected void checkWriteable() throws IllegalStateException { + if (readOnly.get()) { + throw new IllegalStateException("Context is read only and can not be modified"); } } - - public String toString() - { + + public String toString() { return contextData.toString(); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/AbstractLifecycleHandler.java b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/AbstractLifecycleHandler.java index 3e848834b..208906c45 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/AbstractLifecycleHandler.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/AbstractLifecycleHandler.java @@ -16,17 +16,15 @@ * limitations under the License. */ +import java.util.ArrayList; +import java.util.List; + import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.lifecycle.phase.Phase; import org.codehaus.plexus.personality.plexus.lifecycle.phase.PhaseExecutionException; -import java.util.ArrayList; -import java.util.List; - -public abstract class AbstractLifecycleHandler - implements LifecycleHandler -{ +public abstract class AbstractLifecycleHandler implements LifecycleHandler { private List beginSegment; private List endSegment; @@ -35,33 +33,27 @@ public abstract class AbstractLifecycleHandler // Begin Segment // ---------------------------------------------------------------------- - public void addBeginSegment( Phase phase ) - { - if ( beginSegment == null ) - { + public void addBeginSegment(Phase phase) { + if (beginSegment == null) { beginSegment = new ArrayList(); } - beginSegment.add( phase ); + beginSegment.add(phase); } - public List getBeginSegment() - { + public List getBeginSegment() { return beginSegment; } - public void addEndSegment( Phase phase ) - { - if ( endSegment == null ) - { + public void addEndSegment(Phase phase) { + if (endSegment == null) { endSegment = new ArrayList(); } - endSegment.add( phase ); + endSegment.add(phase); } - public List getEndSegment() - { + public List getEndSegment() { return endSegment; } @@ -72,20 +64,15 @@ public List getEndSegment() /** * @deprecated */ - public void start( Object component, ComponentManager manager ) - throws PhaseExecutionException - { - start( component, manager, manager.getContainer().getLookupRealm( component ) ); + public void start(Object component, ComponentManager manager) throws PhaseExecutionException { + start(component, manager, manager.getContainer().getLookupRealm(component)); } /** * Start a component's lifecycle. */ - public void start( Object component, ComponentManager manager, ClassRealm realm ) - throws PhaseExecutionException - { - if ( segmentIsEmpty( getBeginSegment() ) ) - { + public void start(Object component, ComponentManager manager, ClassRealm realm) throws PhaseExecutionException { + if (segmentIsEmpty(getBeginSegment())) { return; } @@ -100,20 +87,16 @@ public void start( Object component, ComponentManager manager, ClassRealm realm * End a component's lifecycle. * @deprecated */ - public void end( Object component, ComponentManager manager ) - throws PhaseExecutionException - { - end( component, manager, manager.getContainer().getLookupRealm( component ) ); + public void end(Object component, ComponentManager manager) throws PhaseExecutionException { + end(component, manager, manager.getContainer().getLookupRealm(component)); } /** * End a component's lifecycle. */ - public void end( Object component, ComponentManager manager, ClassRealm contextRealm ) - throws PhaseExecutionException - { - if ( segmentIsEmpty( getEndSegment() ) ) - { + public void end(Object component, ComponentManager manager, ClassRealm contextRealm) + throws PhaseExecutionException { + if (segmentIsEmpty(getEndSegment())) { return; } @@ -124,10 +107,8 @@ public void end( Object component, ComponentManager manager, ClassRealm contextR } } - private boolean segmentIsEmpty( List segment ) - { - if ( segment == null || segment.size() == 0 ) - { + private boolean segmentIsEmpty(List segment) { + if (segment == null || segment.size() == 0) { return true; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/BasicLifecycleHandler.java b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/BasicLifecycleHandler.java index 11e0a37b4..73484f376 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/BasicLifecycleHandler.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/BasicLifecycleHandler.java @@ -16,23 +16,17 @@ * limitations under the License. */ -public class BasicLifecycleHandler - extends AbstractLifecycleHandler -{ +public class BasicLifecycleHandler extends AbstractLifecycleHandler { protected String id; - public BasicLifecycleHandler( String id ) - { + public BasicLifecycleHandler(String id) { this.id = id; } - public String getId() - { + public String getId() { return id; } /** @see org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable#initialize */ - public void initialize() - { - } + public void initialize() {} } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/DefaultLifecycleHandlerManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/DefaultLifecycleHandlerManager.java index ca9c9346a..0ae7b707c 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/DefaultLifecycleHandlerManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/DefaultLifecycleHandlerManager.java @@ -22,41 +22,33 @@ /** * @author Jason van Zyl */ -public class DefaultLifecycleHandlerManager - implements LifecycleHandlerManager -{ - private final ConcurrentMap lifecycleHandlers = new ConcurrentHashMap(); +public class DefaultLifecycleHandlerManager implements LifecycleHandlerManager { + private final ConcurrentMap lifecycleHandlers = + new ConcurrentHashMap(); private String defaultLifecycleHandlerId = "plexus"; - public void addLifecycleHandler( LifecycleHandler lifecycleHandler ) - { - lifecycleHandlers.put( lifecycleHandler.getId(), lifecycleHandler ); + public void addLifecycleHandler(LifecycleHandler lifecycleHandler) { + lifecycleHandlers.put(lifecycleHandler.getId(), lifecycleHandler); } - public void initialize() - { - for ( LifecycleHandler lifecycleHandler : lifecycleHandlers.values() ) - { + public void initialize() { + for (LifecycleHandler lifecycleHandler : lifecycleHandlers.values()) { lifecycleHandler.initialize(); } } - public LifecycleHandler getLifecycleHandler( String id ) - throws UndefinedLifecycleHandlerException - { - if ( id == null ) - { + public LifecycleHandler getLifecycleHandler(String id) throws UndefinedLifecycleHandlerException { + if (id == null) { id = defaultLifecycleHandlerId; } - LifecycleHandler lifecycleHandler = lifecycleHandlers.get( id ); + LifecycleHandler lifecycleHandler = lifecycleHandlers.get(id); - if ( lifecycleHandler == null ) - { - throw new UndefinedLifecycleHandlerException( "Specified lifecycle handler cannot be found: " + id ); + if (lifecycleHandler == null) { + throw new UndefinedLifecycleHandlerException("Specified lifecycle handler cannot be found: " + id); } return lifecycleHandler; - } + } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/LifecycleHandler.java b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/LifecycleHandler.java index 560077368..a462b74df 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/LifecycleHandler.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/LifecycleHandler.java @@ -21,19 +21,18 @@ import org.codehaus.plexus.lifecycle.phase.Phase; import org.codehaus.plexus.personality.plexus.lifecycle.phase.PhaseExecutionException; -public interface LifecycleHandler -{ +public interface LifecycleHandler { String getId(); /** * @param phase {@link Phase} */ - void addBeginSegment( Phase phase ); + void addBeginSegment(Phase phase); /** * @param phase {@link Phase} */ - void addEndSegment( Phase phase ); + void addEndSegment(Phase phase); /** * @param component The component. @@ -41,8 +40,7 @@ public interface LifecycleHandler * @throws PhaseExecutionException in case of an error. * @deprecated */ - void start( Object component, ComponentManager manager ) - throws PhaseExecutionException; + void start(Object component, ComponentManager manager) throws PhaseExecutionException; /** * @param component The component. @@ -50,8 +48,7 @@ void start( Object component, ComponentManager manager ) * @param realm The {@link ClassRealm}. * @throws PhaseExecutionException in case of an error. */ - void start( Object component, ComponentManager manager, ClassRealm realm ) - throws PhaseExecutionException; + void start(Object component, ComponentManager manager, ClassRealm realm) throws PhaseExecutionException; /** * @param component The component. @@ -59,8 +56,7 @@ void start( Object component, ComponentManager manager, ClassRealm realm ) * @throws PhaseExecutionException in case of an error. * @deprecated */ - void end( Object component, ComponentManager manager ) - throws PhaseExecutionException; + void end(Object component, ComponentManager manager) throws PhaseExecutionException; /** * @@ -71,8 +67,8 @@ void end( Object component, ComponentManager manager ) * used to lookup the same manager components that were used to start the component. * @throws PhaseExecutionException in case of an error. */ - void end( Object component, ComponentManager manager, ClassRealm componentContextRealm ) - throws PhaseExecutionException; + void end(Object component, ComponentManager manager, ClassRealm componentContextRealm) + throws PhaseExecutionException; /** * initialize. diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/LifecycleHandlerManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/LifecycleHandlerManager.java index c79419f23..44ca6b819 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/LifecycleHandlerManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/LifecycleHandlerManager.java @@ -1,8 +1,5 @@ package org.codehaus.plexus.lifecycle; - - - /* * Copyright 2001-2006 Codehaus Foundation. * @@ -25,12 +22,10 @@ * @author Jason van Zyl * */ -public interface LifecycleHandlerManager -{ +public interface LifecycleHandlerManager { void initialize(); - void addLifecycleHandler( LifecycleHandler lifecycleHandler ); + void addLifecycleHandler(LifecycleHandler lifecycleHandler); - LifecycleHandler getLifecycleHandler( String id ) - throws UndefinedLifecycleHandlerException; + LifecycleHandler getLifecycleHandler(String id) throws UndefinedLifecycleHandlerException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/UndefinedLifecycleHandlerException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/UndefinedLifecycleHandlerException.java index aa96c659e..29fcfec42 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/UndefinedLifecycleHandlerException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/UndefinedLifecycleHandlerException.java @@ -16,11 +16,8 @@ * limitations under the License. */ -public class UndefinedLifecycleHandlerException - extends Exception -{ - public UndefinedLifecycleHandlerException( String message ) - { - super( message ); +public class UndefinedLifecycleHandlerException extends Exception { + public UndefinedLifecycleHandlerException(String message) { + super(message); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/phase/AbstractPhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/phase/AbstractPhase.java index 31e8c7d33..b2028361c 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/phase/AbstractPhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/phase/AbstractPhase.java @@ -20,12 +20,10 @@ import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.personality.plexus.lifecycle.phase.PhaseExecutionException; -public abstract class AbstractPhase - implements Phase -{ +public abstract class AbstractPhase implements Phase { /** {@inheritDoc} */ - public abstract void execute( Object component, ComponentManager manager, ClassRealm realm ) - throws PhaseExecutionException; + public abstract void execute(Object component, ComponentManager manager, ClassRealm realm) + throws PhaseExecutionException; /** * @param component The component. @@ -33,9 +31,7 @@ public abstract void execute( Object component, ComponentManager manager, ClassR * @throws PhaseExecutionException in case of an error. * @deprecated */ - public final void execute( Object component, ComponentManager manager ) - throws PhaseExecutionException - { - execute( component, manager, manager.getContainer().getLookupRealm( component ) ); + public final void execute(Object component, ComponentManager manager) throws PhaseExecutionException { + execute(component, manager, manager.getContainer().getLookupRealm(component)); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/phase/Phase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/phase/Phase.java index 57f88022f..fe40e5e12 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/phase/Phase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/lifecycle/phase/Phase.java @@ -20,15 +20,13 @@ import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.personality.plexus.lifecycle.phase.PhaseExecutionException; -public interface Phase -{ - /** +public interface Phase { + /** * Execute the phase. * @param component The component. * @param manager {@link ComponentManager} * @param realm {@link ClassRealm} * @throws PhaseExecutionException in case of an error. */ - public void execute( Object component, ComponentManager manager, ClassRealm realm ) - throws PhaseExecutionException; + public void execute(Object component, ComponentManager manager, ClassRealm realm) throws PhaseExecutionException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/AbstractLogEnabled.java b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/AbstractLogEnabled.java index 79ace08a3..b42a8de18 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/AbstractLogEnabled.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/AbstractLogEnabled.java @@ -20,43 +20,34 @@ * @author Jason van Zyl * @author Trygve Laugstøl */ -public abstract class AbstractLogEnabled - implements LogEnabled -{ +public abstract class AbstractLogEnabled implements LogEnabled { private Logger logger; - public void enableLogging( Logger logger ) - { + public void enableLogging(Logger logger) { this.logger = logger; } - protected Logger getLogger() - { + protected Logger getLogger() { return logger; } - protected void setupLogger( Object component ) - { - setupLogger( component, logger ); + protected void setupLogger(Object component) { + setupLogger(component, logger); } - protected void setupLogger( Object component, String subCategory ) - { - if ( subCategory == null ) - { - throw new IllegalStateException( "Logging category must be defined." ); + protected void setupLogger(Object component, String subCategory) { + if (subCategory == null) { + throw new IllegalStateException("Logging category must be defined."); } - Logger logger = this.logger.getChildLogger( subCategory ); + Logger logger = this.logger.getChildLogger(subCategory); - setupLogger( component, logger ); + setupLogger(component, logger); } - protected void setupLogger( Object component, Logger logger ) - { - if ( component instanceof LogEnabled ) - { - ( (LogEnabled) component ).enableLogging( logger ); + protected void setupLogger(Object component, Logger logger) { + if (component instanceof LogEnabled) { + ((LogEnabled) component).enableLogging(logger); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/AbstractLogger.java b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/AbstractLogger.java index e24cc24c4..8f2305fbc 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/AbstractLogger.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/AbstractLogger.java @@ -23,113 +23,89 @@ /** * @author Trygve Laugstøl */ -public abstract class AbstractLogger - implements Logger -{ +public abstract class AbstractLogger implements Logger { private int threshold; private String name; - public AbstractLogger( int threshold, String name ) - { - if ( !isValidThreshold( threshold ) ) - { - throw new IllegalArgumentException( "Threshold " + threshold + " is not valid" ); + public AbstractLogger(int threshold, String name) { + if (!isValidThreshold(threshold)) { + throw new IllegalArgumentException("Threshold " + threshold + " is not valid"); } this.threshold = threshold; this.name = name; } - public int getThreshold() - { + public int getThreshold() { return threshold; } - public void setThreshold( int threshold ) - { + public void setThreshold(int threshold) { this.threshold = threshold; } - public String getName() - { + public String getName() { return name; } - public void debug( String message ) - { - debug( message, null ); + public void debug(String message) { + debug(message, null); } - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return threshold <= LEVEL_DEBUG; } - public void info( String message ) - { - info( message, null ); + public void info(String message) { + info(message, null); } - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return threshold <= LEVEL_INFO; } - public void warn( String message ) - { - warn( message, null ); + public void warn(String message) { + warn(message, null); } - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return threshold <= LEVEL_WARN; } - public void error( String message ) - { - error( message, null ); + public void error(String message) { + error(message, null); } - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return threshold <= LEVEL_ERROR; } - public void fatalError( String message ) - { - fatalError( message, null ); + public void fatalError(String message) { + fatalError(message, null); } - public boolean isFatalErrorEnabled() - { + public boolean isFatalErrorEnabled() { return threshold <= LEVEL_FATAL; } - protected boolean isValidThreshold( int threshold ) - { - if ( threshold == LEVEL_DEBUG ) - { + protected boolean isValidThreshold(int threshold) { + if (threshold == LEVEL_DEBUG) { return true; } - if ( threshold == LEVEL_INFO ) - { + if (threshold == LEVEL_INFO) { return true; } - if ( threshold == LEVEL_WARN ) - { + if (threshold == LEVEL_WARN) { return true; } - if ( threshold == LEVEL_ERROR ) - { + if (threshold == LEVEL_ERROR) { return true; } - if ( threshold == LEVEL_FATAL ) - { + if (threshold == LEVEL_FATAL) { return true; } - if ( threshold == LEVEL_DISABLED ) - { + if (threshold == LEVEL_DISABLED) { return true; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/AbstractLoggerManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/AbstractLoggerManager.java index 73801c4fb..4a6c48ced 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/AbstractLoggerManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/AbstractLoggerManager.java @@ -20,50 +20,38 @@ * @author Jason van Zyl * @author Trygve Laugstøl */ -public abstract class AbstractLoggerManager - implements LoggerManager -{ +public abstract class AbstractLoggerManager implements LoggerManager { /** */ - public AbstractLoggerManager() - { - } + public AbstractLoggerManager() {} - public void setThreshold( String role, int threshold ) - { - setThreshold( role, null, threshold ); + public void setThreshold(String role, int threshold) { + setThreshold(role, null, threshold); } - public int getThreshold( String role ) - { - return getThreshold( role, null ); + public int getThreshold(String role) { + return getThreshold(role, null); } - public Logger getLoggerForComponent( String role ) - { - return getLoggerForComponent( role, null ); + public Logger getLoggerForComponent(String role) { + return getLoggerForComponent(role, null); } - public void returnComponentLogger( String role ) - { - returnComponentLogger( role, null ); + public void returnComponentLogger(String role) { + returnComponentLogger(role, null); } /** * Creates a string key useful as keys in Map's. - * + * * @param role The component role. * @param roleHint The component role hint. * @return Returns a string thats useful as a key for components. */ - protected String toMapKey( String role, String roleHint ) - { - if ( roleHint == null ) - { - return role; - } - else - { - return role + ":" + roleHint; - } + protected String toMapKey(String role, String roleHint) { + if (roleHint == null) { + return role; + } else { + return role + ":" + roleHint; + } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/BaseLoggerManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/BaseLoggerManager.java index c80fad801..6ba3400a1 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/BaseLoggerManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/BaseLoggerManager.java @@ -16,58 +16,44 @@ * limitations under the License. */ -import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; - import java.util.HashMap; import java.util.Locale; import java.util.Map; +import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; + /** * Base class for all LoggerManagers which use cache of Loggers. * * @author Michal Maczka */ -public abstract class BaseLoggerManager - extends AbstractLoggerManager implements Initializable -{ +public abstract class BaseLoggerManager extends AbstractLoggerManager implements Initializable { private Map loggerCache = new HashMap(); private String threshold = "info"; private int currentThreshold; - public void initialize() - { - currentThreshold = parseThreshold( threshold ); + public void initialize() { + currentThreshold = parseThreshold(threshold); - if ( currentThreshold == -1 ) - { + if (currentThreshold == -1) { currentThreshold = Logger.LEVEL_DEBUG; } } - protected int parseThreshold( String text ) - { - text = text.trim().toLowerCase( Locale.ENGLISH ); + protected int parseThreshold(String text) { + text = text.trim().toLowerCase(Locale.ENGLISH); - if ( text.equals( "debug" ) ) - { + if (text.equals("debug")) { return Logger.LEVEL_DEBUG; - } - else if ( text.equals( "info" ) ) - { + } else if (text.equals("info")) { return Logger.LEVEL_INFO; - } - else if ( text.equals( "warn" ) ) - { + } else if (text.equals("warn")) { return Logger.LEVEL_WARN; - } - else if ( text.equals( "error" ) ) - { + } else if (text.equals("error")) { return Logger.LEVEL_ERROR; - } - else if ( text.equals( "fatal" ) ) - { + } else if (text.equals("fatal")) { return Logger.LEVEL_FATAL; } @@ -80,8 +66,7 @@ else if ( text.equals( "fatal" ) ) * * @param currentThreshold The new threshold. */ - public void setThreshold( int currentThreshold ) - { + public void setThreshold(int currentThreshold) { this.currentThreshold = currentThreshold; } @@ -91,8 +76,7 @@ public void setThreshold( int currentThreshold ) * * @param currentThreshold The new threshold. */ - public void setThresholds( int currentThreshold ) - { + public void setThresholds(int currentThreshold) { this.currentThreshold = currentThreshold; for (Object o : loggerCache.values()) { @@ -106,88 +90,76 @@ public void setThresholds( int currentThreshold ) * * @return Returns the current threshold for all new loggers. */ - public int getThreshold() - { + public int getThreshold() { return currentThreshold; } - public void setThreshold( String role, String roleHint, int threshold ) - { + public void setThreshold(String role, String roleHint, int threshold) { AbstractLogger logger; - String key = toMapKey( role, roleHint ); + String key = toMapKey(role, roleHint); - logger = ( AbstractLogger ) loggerCache.get( key ); + logger = (AbstractLogger) loggerCache.get(key); - if ( logger == null ) - { + if (logger == null) { return; // nothing to do } - logger.setThreshold( threshold ); + logger.setThreshold(threshold); } - public int getThreshold( String role, String roleHint ) - { + public int getThreshold(String role, String roleHint) { AbstractLogger logger; - String key = toMapKey( role, roleHint ); + String key = toMapKey(role, roleHint); - logger = ( AbstractLogger ) loggerCache.get( key ); + logger = (AbstractLogger) loggerCache.get(key); - if ( logger == null ) - { + if (logger == null) { return Logger.LEVEL_DEBUG; // does not return null because that could create a NPE } return logger.getThreshold(); } - public Logger getLoggerForComponent( String role, String roleHint ) - { + public Logger getLoggerForComponent(String role, String roleHint) { Logger logger; - String key = toMapKey( role, roleHint ); + String key = toMapKey(role, roleHint); - logger = ( Logger ) loggerCache.get( key ); + logger = (Logger) loggerCache.get(key); - if ( logger != null ) - { + if (logger != null) { return logger; } - logger = createLogger( key ); + logger = createLogger(key); - loggerCache.put( key, logger ); + loggerCache.put(key, logger); return logger; } - protected abstract Logger createLogger( String key ); + protected abstract Logger createLogger(String key); - public void returnComponentLogger( String role, String roleHint ) - { + public void returnComponentLogger(String role, String roleHint) { Object obj; - String key = toMapKey( role, roleHint ); + String key = toMapKey(role, roleHint); - obj = loggerCache.remove( key ); + obj = loggerCache.remove(key); - if ( obj == null ) - { + if (obj == null) { // TODO: use a logger! - System.err.println( "There was no such logger '" + key + "' " + hashCode() + "." ); + System.err.println("There was no such logger '" + key + "' " + hashCode() + "."); } } - public int getActiveLoggerCount() - { + public int getActiveLoggerCount() { return loggerCache.size(); } - public String getThresholdAsString() - { + public String getThresholdAsString() { return threshold; } - } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/LogEnabled.java b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/LogEnabled.java index 68084820a..84a6b3f2a 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/LogEnabled.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/LogEnabled.java @@ -18,7 +18,6 @@ /** */ -public interface LogEnabled -{ - void enableLogging( Logger logger ); +public interface LogEnabled { + void enableLogging(Logger logger); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/Logger.java b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/Logger.java index 8c30963fe..15bb4737b 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/Logger.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/Logger.java @@ -20,8 +20,7 @@ * @author Jason van Zyl * @author Trygve Laugstøl */ -public interface Logger -{ +public interface Logger { /** Typecode for debugging messages. */ int LEVEL_DEBUG = 0; @@ -40,41 +39,41 @@ public interface Logger /** Typecode for disabled log levels. */ int LEVEL_DISABLED = 5; - void debug( String message ); + void debug(String message); - void debug( String message, Throwable throwable ); + void debug(String message, Throwable throwable); boolean isDebugEnabled(); - void info( String message ); + void info(String message); - void info( String message, Throwable throwable ); + void info(String message, Throwable throwable); boolean isInfoEnabled(); - void warn( String message ); + void warn(String message); - void warn( String message, Throwable throwable ); + void warn(String message, Throwable throwable); boolean isWarnEnabled(); - void error( String message ); + void error(String message); - void error( String message, Throwable throwable ); + void error(String message, Throwable throwable); boolean isErrorEnabled(); - void fatalError( String message ); + void fatalError(String message); - void fatalError( String message, Throwable throwable ); + void fatalError(String message, Throwable throwable); boolean isFatalErrorEnabled(); - Logger getChildLogger( String name ); + Logger getChildLogger(String name); int getThreshold(); - void setThreshold( int threshold ); + void setThreshold(int threshold); String getName(); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/LoggerManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/LoggerManager.java index 62badffe2..5eed77c63 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/LoggerManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/LoggerManager.java @@ -20,18 +20,17 @@ * @author Jason van Zyl * @author Trygve Laugstøl */ -public interface LoggerManager -{ +public interface LoggerManager { String ROLE = LoggerManager.class.getName(); /** * Sets the threshold for all new loggers. It will NOT affect the existing loggers. * * This is usually only set once while the logger manager is configured. - * + * * @param threshold The new threshold. */ - void setThreshold( int threshold ); + void setThreshold(int threshold); /** * Returns the current threshold for all new loggers. @@ -46,24 +45,24 @@ public interface LoggerManager * * @param threshold The new threshold. */ - void setThresholds( int threshold ); + void setThresholds(int threshold); // The new stuff - void setThreshold( String role, int threshold ); + void setThreshold(String role, int threshold); - void setThreshold( String role, String roleHint, int threshold ); + void setThreshold(String role, String roleHint, int threshold); - int getThreshold( String role ); + int getThreshold(String role); - int getThreshold( String role, String roleHint ); + int getThreshold(String role, String roleHint); - Logger getLoggerForComponent( String role ); + Logger getLoggerForComponent(String role); - Logger getLoggerForComponent( String role, String roleHint ); + Logger getLoggerForComponent(String role, String roleHint); - void returnComponentLogger( String role ); + void returnComponentLogger(String role); - void returnComponentLogger( String role, String hint ); + void returnComponentLogger(String role, String hint); int getActiveLoggerCount(); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/console/ConsoleLogger.java b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/console/ConsoleLogger.java index 0f4c5aa32..53c5165de 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/console/ConsoleLogger.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/console/ConsoleLogger.java @@ -26,86 +26,67 @@ * * @author Avalon Development Team */ -public final class ConsoleLogger - extends AbstractLogger -{ - public ConsoleLogger( int threshold, String name ) - { - super( threshold, name ); +public final class ConsoleLogger extends AbstractLogger { + public ConsoleLogger(int threshold, String name) { + super(threshold, name); } - public void debug( String message, Throwable throwable ) - { - if ( isDebugEnabled() ) - { - System.out.print( "[DEBUG] " ); - System.out.println( message ); + public void debug(String message, Throwable throwable) { + if (isDebugEnabled()) { + System.out.print("[DEBUG] "); + System.out.println(message); - if ( null != throwable ) - { - throwable.printStackTrace( System.out ); + if (null != throwable) { + throwable.printStackTrace(System.out); } } } - public void info( String message, Throwable throwable ) - { - if ( isInfoEnabled() ) - { - System.out.print( "[INFO] " ); - System.out.println( message ); + public void info(String message, Throwable throwable) { + if (isInfoEnabled()) { + System.out.print("[INFO] "); + System.out.println(message); - if ( null != throwable ) - { - throwable.printStackTrace( System.out ); + if (null != throwable) { + throwable.printStackTrace(System.out); } } } - public void warn( String message, Throwable throwable ) - { - if ( isWarnEnabled() ) - { - System.out.print( "[WARNING] " ); - System.out.println( message ); + public void warn(String message, Throwable throwable) { + if (isWarnEnabled()) { + System.out.print("[WARNING] "); + System.out.println(message); - if ( null != throwable ) - { - throwable.printStackTrace( System.out ); + if (null != throwable) { + throwable.printStackTrace(System.out); } } } - public void error( String message, Throwable throwable ) - { - if ( isErrorEnabled() ) - { - System.out.print( "[ERROR] " ); - System.out.println( message ); + public void error(String message, Throwable throwable) { + if (isErrorEnabled()) { + System.out.print("[ERROR] "); + System.out.println(message); - if ( null != throwable ) - { - throwable.printStackTrace( System.out ); + if (null != throwable) { + throwable.printStackTrace(System.out); } } } - public void fatalError( String message, Throwable throwable ) - { - if ( isFatalErrorEnabled() ) - { - System.out.print( "[FATAL ERROR] " ); - System.out.println( message ); + public void fatalError(String message, Throwable throwable) { + if (isFatalErrorEnabled()) { + System.out.print("[FATAL ERROR] "); + System.out.println(message); - if ( null != throwable ) - { - throwable.printStackTrace( System.out ); + if (null != throwable) { + throwable.printStackTrace(System.out); } } } - public Logger getChildLogger( String name ) - { + public Logger getChildLogger(String name) { return this; } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/console/ConsoleLoggerManager.java b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/console/ConsoleLoggerManager.java index 9a72866b6..96c766749 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/logging/console/ConsoleLoggerManager.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/logging/console/ConsoleLoggerManager.java @@ -16,15 +16,15 @@ * limitations under the License. */ +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + import org.codehaus.plexus.logging.AbstractLoggerManager; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.logging.LoggerManager; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - /** * This is a simple logger manager that will only write the logging statements to the console. * @@ -37,17 +37,14 @@ * * * } - * + * * @author Jason van Zyl * @author Trygve Laugstøl */ -public class ConsoleLoggerManager - extends AbstractLoggerManager - implements LoggerManager, Initializable -{ +public class ConsoleLoggerManager extends AbstractLoggerManager implements LoggerManager, Initializable { /** - * Message of this level or higher will be logged. - * + * Message of this level or higher will be logged. + * * This field is set by the plexus container thus the name is 'threshold'. The field * currentThreshold contains the current setting of the threshold. */ @@ -62,16 +59,13 @@ public class ConsoleLoggerManager private boolean bootTimeLogger = false; - public ConsoleLoggerManager() - { - } + public ConsoleLoggerManager() {} /** * This special constructor is called directly when the container is bootstrapping itself. * @param threshold The threshold. */ - public ConsoleLoggerManager( String threshold ) - { + public ConsoleLoggerManager(String threshold) { this.threshold = threshold; bootTimeLogger = true; @@ -79,29 +73,25 @@ public ConsoleLoggerManager( String threshold ) initialize(); } - public void initialize() - { - debug( "Initializing ConsoleLoggerManager: " + this.hashCode() + "." ); -// if ( !bootTimeLogger ) -// new Throwable().printStackTrace(System.err); - currentThreshold = parseThreshold( threshold ); + public void initialize() { + debug("Initializing ConsoleLoggerManager: " + this.hashCode() + "."); + // if ( !bootTimeLogger ) + // new Throwable().printStackTrace(System.err); + currentThreshold = parseThreshold(threshold); - if ( currentThreshold == -1 ) - { - debug( "Could not parse the threshold level: '" + threshold + "', setting to debug." ); + if (currentThreshold == -1) { + debug("Could not parse the threshold level: '" + threshold + "', setting to debug."); currentThreshold = Logger.LEVEL_DEBUG; } loggers = new HashMap(); } - public void setThreshold( int currentThreshold ) - { + public void setThreshold(int currentThreshold) { this.currentThreshold = currentThreshold; } - public void setThresholds( int currentThreshold ) - { + public void setThresholds(int currentThreshold) { this.currentThreshold = currentThreshold; for (Object o : loggers.values()) { @@ -113,127 +103,114 @@ public void setThresholds( int currentThreshold ) /** * @return Returns the threshold. */ - public int getThreshold() - { + public int getThreshold() { return currentThreshold; } // new stuff - public void setThreshold( String role, String roleHint, int threshold ) { + public void setThreshold(String role, String roleHint, int threshold) { ConsoleLogger logger; String name; - name = toMapKey( role, roleHint ); - logger = (ConsoleLogger)loggers.get( name ); + name = toMapKey(role, roleHint); + logger = (ConsoleLogger) loggers.get(name); - if(logger == null) { - debug( "Trying to set the threshold of a unknown logger '" + name + "'." ); + if (logger == null) { + debug("Trying to set the threshold of a unknown logger '" + name + "'."); return; // nothing to do } - logger.setThreshold( threshold ); + logger.setThreshold(threshold); } - public int getThreshold( String role, String roleHint ) { + public int getThreshold(String role, String roleHint) { ConsoleLogger logger; String name; - name = toMapKey( role, roleHint ); - logger = (ConsoleLogger)loggers.get( name ); + name = toMapKey(role, roleHint); + logger = (ConsoleLogger) loggers.get(name); - if(logger == null) { - debug( "Trying to get the threshold of a unknown logger '" + name + "'." ); + if (logger == null) { + debug("Trying to get the threshold of a unknown logger '" + name + "'."); return Logger.LEVEL_DEBUG; // does not return null because that could create a NPE } return logger.getThreshold(); } - public Logger createLogger(int threshold, String name) - { - return new ConsoleLogger( threshold, name ); + public Logger createLogger(int threshold, String name) { + return new ConsoleLogger(threshold, name); } - public Logger getLoggerForComponent( String role, String roleHint ) - { + public Logger getLoggerForComponent(String role, String roleHint) { Logger logger; String name; - name = toMapKey( role, roleHint ); - logger = (Logger)loggers.get( name ); + name = toMapKey(role, roleHint); + logger = (Logger) loggers.get(name); - if ( logger != null ) - return logger; + if (logger != null) return logger; - debug( "Creating logger '" + name + "' " + this.hashCode() + "." ); - logger = createLogger( getThreshold(), name ); - loggers.put( name, logger ); + debug("Creating logger '" + name + "' " + this.hashCode() + "."); + logger = createLogger(getThreshold(), name); + loggers.put(name, logger); return logger; } - public void returnComponentLogger( String role, String roleHint ) - { + public void returnComponentLogger(String role, String roleHint) { Object obj; String name; - name = toMapKey( role, roleHint ); - obj = loggers.remove( name ); + name = toMapKey(role, roleHint); + obj = loggers.remove(name); - if ( obj == null ) - { - debug( "There was no such logger '" + name + "' " + this.hashCode() + "."); - } - else - { - debug( "Removed logger '" + name + "' " + this.hashCode() + "."); + if (obj == null) { + debug("There was no such logger '" + name + "' " + this.hashCode() + "."); + } else { + debug("Removed logger '" + name + "' " + this.hashCode() + "."); } } - public int getActiveLoggerCount() - { + public int getActiveLoggerCount() { return loggers.size(); } - private int parseThreshold( String text ) - { - text = text.trim().toLowerCase( Locale.ENGLISH ); + private int parseThreshold(String text) { + text = text.trim().toLowerCase(Locale.ENGLISH); - if ( text.equals( "debug" ) ) - { + if (text.equals("debug")) { return ConsoleLogger.LEVEL_DEBUG; - } - else if ( text.equals( "info" ) ) - { + } else if (text.equals("info")) { return ConsoleLogger.LEVEL_INFO; - } - else if ( text.equals( "warn" ) ) - { + } else if (text.equals("warn")) { return ConsoleLogger.LEVEL_WARN; - } - else if ( text.equals( "error" ) ) - { + } else if (text.equals("error")) { return ConsoleLogger.LEVEL_ERROR; - } - else if ( text.equals( "fatal" ) ) - { + } else if (text.equals("fatal")) { return ConsoleLogger.LEVEL_FATAL; } return -1; } - private String decodeLogLevel( int logLevel ) - { - switch(logLevel) { - case ConsoleLogger.LEVEL_DEBUG: return "debug"; - case ConsoleLogger.LEVEL_INFO: return "info"; - case ConsoleLogger.LEVEL_WARN: return "warn"; - case ConsoleLogger.LEVEL_ERROR: return "error"; - case ConsoleLogger.LEVEL_FATAL: return "fatal"; - case ConsoleLogger.LEVEL_DISABLED: return "disabled"; - default: return "unknown"; + private String decodeLogLevel(int logLevel) { + switch (logLevel) { + case ConsoleLogger.LEVEL_DEBUG: + return "debug"; + case ConsoleLogger.LEVEL_INFO: + return "info"; + case ConsoleLogger.LEVEL_WARN: + return "warn"; + case ConsoleLogger.LEVEL_ERROR: + return "error"; + case ConsoleLogger.LEVEL_FATAL: + return "fatal"; + case ConsoleLogger.LEVEL_DISABLED: + return "disabled"; + default: + return "unknown"; } } @@ -242,9 +219,8 @@ private String decodeLogLevel( int logLevel ) * * @param msg */ - private void debug( String msg ) - { -// if ( !bootTimeLogger ) -// System.out.println( "[Console] " + msg ); + private void debug(String msg) { + // if ( !bootTimeLogger ) + // System.out.println( "[Console] " + msg ); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/AutoConfigurePhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/AutoConfigurePhase.java index db89b8c4b..b30f81b9e 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/AutoConfigurePhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/AutoConfigurePhase.java @@ -26,45 +26,36 @@ import org.codehaus.plexus.lifecycle.phase.AbstractPhase; import org.codehaus.plexus.util.StringUtils; -public class AutoConfigurePhase - extends AbstractPhase -{ +public class AutoConfigurePhase extends AbstractPhase { public static final String DEFAULT_CONFIGURATOR_ID = "default"; - public void execute( Object object, - ComponentManager manager, - ClassRealm lookupRealm ) - throws PhaseExecutionException - { - try - { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) + throws PhaseExecutionException { + try { ComponentDescriptor descriptor = manager.getComponentDescriptor(); String configuratorId = descriptor.getComponentConfigurator(); - if ( StringUtils.isEmpty( configuratorId ) ) - { + if (StringUtils.isEmpty(configuratorId)) { configuratorId = DEFAULT_CONFIGURATOR_ID; } - ComponentConfigurator componentConfigurator = manager.getContainer().lookup( ComponentConfigurator.class, configuratorId ); + ComponentConfigurator componentConfigurator = + manager.getContainer().lookup(ComponentConfigurator.class, configuratorId); - PlexusConfiguration configuration = manager.getContainer().getConfigurationSource().getConfiguration( descriptor ); + PlexusConfiguration configuration = + manager.getContainer().getConfigurationSource().getConfiguration(descriptor); - if ( configuration != null ) - { + if (configuration != null) { ClassRealm realm = manager.getRealm(); - componentConfigurator.configureComponent( object, configuration, realm ); + componentConfigurator.configureComponent(object, configuration, realm); } - } - catch ( ComponentLookupException e ) - { - throw new PhaseExecutionException( "Unable to auto-configure component as its configurator could not be found", e ); - } - catch ( ComponentConfigurationException e ) - { - throw new PhaseExecutionException( "Unable to auto-configure component", e ); + } catch (ComponentLookupException e) { + throw new PhaseExecutionException( + "Unable to auto-configure component as its configurator could not be found", e); + } catch (ComponentConfigurationException e) { + throw new PhaseExecutionException("Unable to auto-configure component", e); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Configurable.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Configurable.java index c0b138740..8baa74c8d 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Configurable.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Configurable.java @@ -21,10 +21,9 @@ /** * Configures a component. - * + * * @author Dan Diephouse */ -public interface Configurable -{ - void configure( PlexusConfiguration configuration ) throws PlexusConfigurationException; +public interface Configurable { + void configure(PlexusConfiguration configuration) throws PlexusConfigurationException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ConfigurablePhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ConfigurablePhase.java index 9d22c343d..859e8d384 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ConfigurablePhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ConfigurablePhase.java @@ -21,21 +21,15 @@ import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.codehaus.plexus.lifecycle.phase.AbstractPhase; -public class ConfigurablePhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager manager, ClassRealm lookupRealm ) - throws PhaseExecutionException - { - if ( object instanceof Configurable ) - { - try - { - ( (Configurable) object ).configure( manager.getComponentDescriptor().getConfiguration() ); - } - catch ( PlexusConfigurationException e ) - { - throw new PhaseExecutionException( "Error occurred during phase execution", e ); +public class ConfigurablePhase extends AbstractPhase { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) + throws PhaseExecutionException { + if (object instanceof Configurable) { + try { + ((Configurable) object) + .configure(manager.getComponentDescriptor().getConfiguration()); + } catch (PlexusConfigurationException e) { + throw new PhaseExecutionException("Error occurred during phase execution", e); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Contextualizable.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Contextualizable.java index 6c9339c23..0f65882b4 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Contextualizable.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Contextualizable.java @@ -22,8 +22,6 @@ /** * @author Jason van Zyl */ -public interface Contextualizable -{ - public void contextualize( Context context ) - throws ContextException; +public interface Contextualizable { + public void contextualize(Context context) throws ContextException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ContextualizePhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ContextualizePhase.java index ee1e6b852..bf75d6981 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ContextualizePhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ContextualizePhase.java @@ -22,29 +22,20 @@ import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.lifecycle.phase.AbstractPhase; -public class ContextualizePhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager manager, ClassRealm lookupRealm ) - throws PhaseExecutionException - { - if ( object instanceof Contextualizable ) - { +public class ContextualizePhase extends AbstractPhase { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) + throws PhaseExecutionException { + if (object instanceof Contextualizable) { Context context = manager.getContainer().getContext(); - ClassRealm origRealm = manager.getContainer().setLookupRealm( lookupRealm ); + ClassRealm origRealm = manager.getContainer().setLookupRealm(lookupRealm); - try - { - ( (Contextualizable) object ).contextualize( context ); - } - catch ( ContextException e ) - { - throw new PhaseExecutionException( "Unable to contextualize component", e ); - } - finally - { - manager.getContainer().setLookupRealm( origRealm ); + try { + ((Contextualizable) object).contextualize(context); + } catch (ContextException e) { + throw new PhaseExecutionException("Unable to contextualize component", e); + } finally { + manager.getContainer().setLookupRealm(origRealm); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Disposable.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Disposable.java index b1a68e61c..185609725 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Disposable.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Disposable.java @@ -22,7 +22,6 @@ * @author Jason van Zyl * */ -public interface Disposable -{ +public interface Disposable { public void dispose(); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/DisposePhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/DisposePhase.java index 114ada958..ad74ac072 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/DisposePhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/DisposePhase.java @@ -20,14 +20,10 @@ import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.lifecycle.phase.AbstractPhase; -public class DisposePhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager manager, ClassRealm lookupRealm ) - { - if ( object instanceof Disposable ) - { - ( (Disposable) object ).dispose(); +public class DisposePhase extends AbstractPhase { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) { + if (object instanceof Disposable) { + ((Disposable) object).dispose(); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Initializable.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Initializable.java index 77bbeabd4..4d29ec728 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Initializable.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Initializable.java @@ -22,8 +22,6 @@ * @author Jason van Zyl * */ -public interface Initializable -{ - public void initialize() - throws InitializationException; +public interface Initializable { + public void initialize() throws InitializationException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/InitializationException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/InitializationException.java index 099f763f4..aaf89b521 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/InitializationException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/InitializationException.java @@ -21,15 +21,12 @@ * * @author Brett Porter */ -public class InitializationException extends Exception -{ - public InitializationException( String message ) - { - super( message ); +public class InitializationException extends Exception { + public InitializationException(String message) { + super(message); } - public InitializationException( String message, Throwable cause ) - { - super( message, cause ); + public InitializationException(String message, Throwable cause) { + super(message, cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/InitializePhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/InitializePhase.java index 4be1036de..b03ffd1dd 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/InitializePhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/InitializePhase.java @@ -20,21 +20,14 @@ import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.lifecycle.phase.AbstractPhase; -public class InitializePhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager manager, ClassRealm lookupRealm ) - throws PhaseExecutionException - { - if ( object instanceof Initializable ) - { - try - { - ( (Initializable) object ).initialize(); - } - catch ( InitializationException e ) - { - throw new PhaseExecutionException( "Error initialising component", e ); +public class InitializePhase extends AbstractPhase { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) + throws PhaseExecutionException { + if (object instanceof Initializable) { + try { + ((Initializable) object).initialize(); + } catch (InitializationException e) { + throw new PhaseExecutionException("Error initialising component", e); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/LogDisablePhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/LogDisablePhase.java index 172784157..2a4115851 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/LogDisablePhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/LogDisablePhase.java @@ -25,16 +25,12 @@ /** * @author Trygve Laugstøl */ -public class LogDisablePhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager componentManager, ClassRealm lookupRealm ) - throws PhaseExecutionException - { - if ( object instanceof LogEnabled ) - { +public class LogDisablePhase extends AbstractPhase { + public void execute(Object object, ComponentManager componentManager, ClassRealm lookupRealm) + throws PhaseExecutionException { + if (object instanceof LogEnabled) { LoggerManager loggerManager = componentManager.getContainer().getLoggerManager(); - loggerManager.returnComponentLogger( componentManager.getRole(), componentManager.getRoleHint() ); + loggerManager.returnComponentLogger(componentManager.getRole(), componentManager.getRoleHint()); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/LogEnablePhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/LogEnablePhase.java index b3980c8ed..b5e301205 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/LogEnablePhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/LogEnablePhase.java @@ -23,21 +23,18 @@ import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.logging.LoggerManager; -public class LogEnablePhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager componentManager, ClassRealm lookupRealm ) - throws PhaseExecutionException - { - if ( object instanceof LogEnabled ) - { +public class LogEnablePhase extends AbstractPhase { + public void execute(Object object, ComponentManager componentManager, ClassRealm lookupRealm) + throws PhaseExecutionException { + if (object instanceof LogEnabled) { LogEnabled logEnabled = (LogEnabled) object; LoggerManager loggerManager = componentManager.getContainer().getLoggerManager(); - Logger logger = loggerManager.getLoggerForComponent( componentManager.getRole(), componentManager.getRoleHint() ); + Logger logger = + loggerManager.getLoggerForComponent(componentManager.getRole(), componentManager.getRoleHint()); - logEnabled.enableLogging( logger ); + logEnabled.enableLogging(logger); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/PhaseExecutionException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/PhaseExecutionException.java index eff1193db..0c62f936a 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/PhaseExecutionException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/PhaseExecutionException.java @@ -21,10 +21,8 @@ * * @author Brett Porter */ -public class PhaseExecutionException extends Exception -{ - public PhaseExecutionException( String message, Throwable throwable ) - { - super( message, throwable ); +public class PhaseExecutionException extends Exception { + public PhaseExecutionException(String message, Throwable throwable) { + super(message, throwable); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/PlexusContainerLocator.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/PlexusContainerLocator.java index 96e9d3907..4ad39ae1c 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/PlexusContainerLocator.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/PlexusContainerLocator.java @@ -16,79 +16,58 @@ * limitations under the License. */ +import java.util.List; +import java.util.Map; + import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import java.util.List; -import java.util.Map; - /** * A ServiceLocator for PlexusContainer. * * @author Dan Diephouse */ -public class PlexusContainerLocator - implements ServiceLocator -{ +public class PlexusContainerLocator implements ServiceLocator { private PlexusContainer container; - public PlexusContainerLocator( PlexusContainer container ) - { + public PlexusContainerLocator(PlexusContainer container) { this.container = container; } - public Object lookup( String role ) - throws ComponentLookupException - { - return container.lookup( role ); + public Object lookup(String role) throws ComponentLookupException { + return container.lookup(role); } - public Object lookup( String role, - String roleHint ) - throws ComponentLookupException - { - return container.lookup( role, roleHint ); + public Object lookup(String role, String roleHint) throws ComponentLookupException { + return container.lookup(role, roleHint); } - public Map lookupMap( String role ) - throws ComponentLookupException - { - return container.lookupMap( role ); + public Map lookupMap(String role) throws ComponentLookupException { + return container.lookupMap(role); } - public List lookupList( String role ) - throws ComponentLookupException - { - return container.lookupList( role ); + public List lookupList(String role) throws ComponentLookupException { + return container.lookupList(role); } - public void release( Object component ) - throws ComponentLifecycleException - { - container.release( component ); + public void release(Object component) throws ComponentLifecycleException { + container.release(component); } - public void releaseAll( Map components ) - throws ComponentLifecycleException - { - container.releaseAll( components ); + public void releaseAll(Map components) throws ComponentLifecycleException { + container.releaseAll(components); } - public void releaseAll( List components ) - throws ComponentLifecycleException - { - container.releaseAll( components ); + public void releaseAll(List components) throws ComponentLifecycleException { + container.releaseAll(components); } - public boolean hasComponent( String componentKey ) - { - return container.hasComponent( componentKey ); + public boolean hasComponent(String componentKey) { + return container.hasComponent(componentKey); } - public boolean hasComponent( String role, - String roleHint ) - { - return container.hasComponent( role, roleHint ); + public boolean hasComponent(String role, String roleHint) { + return container.hasComponent(role, roleHint); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ResumePhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ResumePhase.java index a6373e5c9..57a1d6b2b 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ResumePhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ResumePhase.java @@ -20,14 +20,10 @@ import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.lifecycle.phase.AbstractPhase; -public class ResumePhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager manager, ClassRealm lookupRealm ) - { - if ( object instanceof Suspendable ) - { - ( (Suspendable) object ).resume(); +public class ResumePhase extends AbstractPhase { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) { + if (object instanceof Suspendable) { + ((Suspendable) object).resume(); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ServiceLocator.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ServiceLocator.java index 55ef4180e..80b20177e 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ServiceLocator.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ServiceLocator.java @@ -16,53 +16,45 @@ * limitations under the License. */ -import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; - import java.util.List; import java.util.Map; +import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; +import org.codehaus.plexus.component.repository.exception.ComponentLookupException; + /** * Provides services to components by means of a lookup. - * + * * @author Dan Diephouse */ -public interface ServiceLocator -{ - //---------------------------------------------------------------------- +public interface ServiceLocator { + // ---------------------------------------------------------------------- // Component lookup // ---------------------------------------------------------------------- - Object lookup( String componentKey ) - throws ComponentLookupException; + Object lookup(String componentKey) throws ComponentLookupException; - Object lookup( String role, String roleHint ) - throws ComponentLookupException; + Object lookup(String role, String roleHint) throws ComponentLookupException; - Map lookupMap( String role ) - throws ComponentLookupException; + Map lookupMap(String role) throws ComponentLookupException; - List lookupList( String role ) - throws ComponentLookupException; - - //---------------------------------------------------------------------- + List lookupList(String role) throws ComponentLookupException; + + // ---------------------------------------------------------------------- // Component release // ---------------------------------------------------------------------- - void release( Object component ) - throws ComponentLifecycleException; + void release(Object component) throws ComponentLifecycleException; - void releaseAll( Map components ) - throws ComponentLifecycleException; + void releaseAll(Map components) throws ComponentLifecycleException; - void releaseAll( List components ) - throws ComponentLifecycleException; + void releaseAll(List components) throws ComponentLifecycleException; // ---------------------------------------------------------------------- // Component discovery // ---------------------------------------------------------------------- - boolean hasComponent( String componentKey ); + boolean hasComponent(String componentKey); - boolean hasComponent( String role, String roleHint ); + boolean hasComponent(String role, String roleHint); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Serviceable.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Serviceable.java index a964af590..6c0f7eedc 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Serviceable.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Serviceable.java @@ -18,10 +18,9 @@ /** * Indicates that a class wants a hold on a ServiceLocator. - * + * * @author Dan Diephouse */ -public interface Serviceable -{ - void service( ServiceLocator locator ); +public interface Serviceable { + void service(ServiceLocator locator); } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ServiceablePhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ServiceablePhase.java index 527a2d077..f648a483f 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ServiceablePhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/ServiceablePhase.java @@ -21,16 +21,12 @@ import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.lifecycle.phase.AbstractPhase; -public class ServiceablePhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager manager, ClassRealm lookupRealm ) - { - if ( object instanceof Serviceable ) - { +public class ServiceablePhase extends AbstractPhase { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) { + if (object instanceof Serviceable) { PlexusContainer container = manager.getContainer(); - ( (Serviceable) object ).service( new PlexusContainerLocator(container) ); + ((Serviceable) object).service(new PlexusContainerLocator(container)); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StartPhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StartPhase.java index d2b31da01..cbba44360 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StartPhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StartPhase.java @@ -20,21 +20,14 @@ import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.lifecycle.phase.AbstractPhase; -public class StartPhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager manager, ClassRealm lookupRealm ) - throws PhaseExecutionException - { - if ( object instanceof Startable ) - { - try - { - ( (Startable) object ).start(); - } - catch ( StartingException e ) - { - throw new PhaseExecutionException( "Error starting component", e ); +public class StartPhase extends AbstractPhase { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) + throws PhaseExecutionException { + if (object instanceof Startable) { + try { + ((Startable) object).start(); + } catch (StartingException e) { + throw new PhaseExecutionException("Error starting component", e); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Startable.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Startable.java index c0308b2fb..d56286124 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Startable.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Startable.java @@ -16,11 +16,8 @@ * limitations under the License. */ -public interface Startable -{ - void start() - throws StartingException; +public interface Startable { + void start() throws StartingException; - void stop() - throws StoppingException; + void stop() throws StoppingException; } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StartingException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StartingException.java index 1fd1508a4..ae81fd976 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StartingException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StartingException.java @@ -21,16 +21,12 @@ * * @author Brett Porter */ -public class StartingException - extends Exception -{ - public StartingException( String message ) - { - super( message ); +public class StartingException extends Exception { + public StartingException(String message) { + super(message); } - public StartingException( String message, Throwable cause ) - { - super( message, cause ); + public StartingException(String message, Throwable cause) { + super(message, cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StopPhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StopPhase.java index d2aa1fc4f..1acc2272b 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StopPhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StopPhase.java @@ -20,21 +20,14 @@ import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.lifecycle.phase.AbstractPhase; -public class StopPhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager manager, ClassRealm lookupRealm ) - throws PhaseExecutionException - { - if ( object instanceof Startable ) - { - try - { - ( (Startable) object ).stop(); - } - catch ( StoppingException e ) - { - throw new PhaseExecutionException( "Error stopping component", e ); +public class StopPhase extends AbstractPhase { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) + throws PhaseExecutionException { + if (object instanceof Startable) { + try { + ((Startable) object).stop(); + } catch (StoppingException e) { + throw new PhaseExecutionException("Error stopping component", e); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StoppingException.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StoppingException.java index 28bd8cb4d..c68c5acd9 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StoppingException.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/StoppingException.java @@ -21,16 +21,12 @@ * * @author Brett Porter */ -public class StoppingException - extends Exception -{ - public StoppingException( String message ) - { - super( message ); +public class StoppingException extends Exception { + public StoppingException(String message) { + super(message); } - public StoppingException( String message, Throwable cause ) - { - super( message, cause ); + public StoppingException(String message, Throwable cause) { + super(message, cause); } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/SuspendPhase.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/SuspendPhase.java index ba333df95..16d0f8a1d 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/SuspendPhase.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/SuspendPhase.java @@ -20,14 +20,10 @@ import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.lifecycle.phase.AbstractPhase; -public class SuspendPhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager manager, ClassRealm lookupRealm ) - { - if ( object instanceof Suspendable ) - { - ( (Suspendable) object ).suspend(); +public class SuspendPhase extends AbstractPhase { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) { + if (object instanceof Suspendable) { + ((Suspendable) object).suspend(); } } } diff --git a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Suspendable.java b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Suspendable.java index 66afe256b..ae675450b 100644 --- a/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Suspendable.java +++ b/plexus-container-default/src/main/java/org/codehaus/plexus/personality/plexus/lifecycle/phase/Suspendable.java @@ -16,8 +16,7 @@ * limitations under the License. */ -public interface Suspendable -{ +public interface Suspendable { void suspend(); void resume(); diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/DefaultComponentLookupManagerTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/DefaultComponentLookupManagerTest.java index 345dadc3d..3620c21a8 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/DefaultComponentLookupManagerTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/DefaultComponentLookupManagerTest.java @@ -6,32 +6,24 @@ /** * @author Trygve Laugstøl */ -public class DefaultComponentLookupManagerTest - extends PlexusTestCase -{ - public void testLookupsWithAndWithoutRoleHint() - throws Exception - { - String resource = getConfigurationName( "components.xml" ); +public class DefaultComponentLookupManagerTest extends PlexusTestCase { + public void testLookupsWithAndWithoutRoleHint() throws Exception { + String resource = getConfigurationName("components.xml"); - System.out.println( "resource = " + resource ); + System.out.println("resource = " + resource); - assertNotNull( resource ); + assertNotNull(resource); - ContainerConfiguration c = new DefaultContainerConfiguration() - .setName( "test" ) - .setContainerConfiguration( resource ); + ContainerConfiguration c = + new DefaultContainerConfiguration().setName("test").setContainerConfiguration(resource); - DefaultPlexusContainer container = new DefaultPlexusContainer( c ); + DefaultPlexusContainer container = new DefaultPlexusContainer(c); - try - { - container.lookup( ComponentA.class ); + try { + container.lookup(ComponentA.class); - fail( "Expected exception" ); - } - catch ( ComponentLookupException e ) - { + fail("Expected exception"); + } catch (ComponentLookupException e) { // expected } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/DyanamicComponentKungFuTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/DyanamicComponentKungFuTest.java index cc9c869b0..2e191ff92 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/DyanamicComponentKungFuTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/DyanamicComponentKungFuTest.java @@ -25,9 +25,7 @@ * @author Jason van Zyl * */ -public class DyanamicComponentKungFuTest - extends TestCase -{ +public class DyanamicComponentKungFuTest extends TestCase { /** * Component additions during container operation. * @@ -70,13 +68,10 @@ public class DyanamicComponentKungFuTest * *
  • Release the component
  • * - * + * * @throws Exception in case of a failure. */ - public void testAdditionOfComponentDuringContainerOperation() - throws Exception - { - } + public void testAdditionOfComponentDuringContainerOperation() throws Exception {} /** * Component replacement during container operation. @@ -95,12 +90,8 @@ public void testAdditionOfComponentDuringContainerOperation() * and error but until much field testing has occurred I'm sure there will be * instances where miscalculations happen simply due to lack of experience and * usage with dynamic component replacement. - * + * * @throws Exception in case of a failure. */ - public void testComponentReplacementDuringContainerOperation() - throws Exception - { - - } + public void testComponentReplacementDuringContainerOperation() throws Exception {} } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/PlexusJUnit4TestCaseTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/PlexusJUnit4TestCaseTest.java index 66baa506a..3a72f9d51 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/PlexusJUnit4TestCaseTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/PlexusJUnit4TestCaseTest.java @@ -1,28 +1,27 @@ package org.codehaus.plexus; +import java.util.concurrent.atomic.AtomicBoolean; + import org.junit.Test; import org.junit.runner.JUnitCore; -import java.util.concurrent.atomic.AtomicBoolean; - import static org.junit.Assert.*; -public class PlexusJUnit4TestCaseTest -{ +public class PlexusJUnit4TestCaseTest { + + private static AtomicBoolean run = new AtomicBoolean(false); - private static AtomicBoolean run = new AtomicBoolean( false ); - public static class MyTest - extends PlexusJUnit4TestCase { + public static class MyTest extends PlexusJUnit4TestCase { @Test - public void yeah(){ - run.set( true ); + public void yeah() { + run.set(true); } } @Test - public void runMytest(){ + public void runMytest() { JUnitCore.runClasses(MyTest.class); - assertTrue( run.get() ); + assertTrue(run.get()); } -} \ No newline at end of file +} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/PlexusTestCaseTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/PlexusTestCaseTest.java index 7f084ceaa..b8d2eda24 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/PlexusTestCaseTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/PlexusTestCaseTest.java @@ -16,69 +16,54 @@ * limitations under the License. */ +import java.io.File; + import junit.framework.TestCase; import org.codehaus.plexus.component.discovery.DiscoveredComponent; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.test.DefaultLoadOnStartService; -import java.io.File; - /** * @author Jason van Zyl */ -public class PlexusTestCaseTest - extends TestCase -{ +public class PlexusTestCaseTest extends TestCase { private String basedir; - public void setUp() - { - basedir = System.getProperty( "basedir" ); + public void setUp() { + basedir = System.getProperty("basedir"); - if ( basedir == null ) - { - basedir = new File( "." ).getAbsolutePath(); + if (basedir == null) { + basedir = new File(".").getAbsolutePath(); } } - public void testPlexusTestCase() - throws Exception - { - PlexusTestCase tc = new PlexusTestCase() - { - }; + public void testPlexusTestCase() throws Exception { + PlexusTestCase tc = new PlexusTestCase() {}; tc.setUp(); - try - { - tc.lookup( DiscoveredComponent.class, "unknown" ); + try { + tc.lookup(DiscoveredComponent.class, "unknown"); - fail( "Expected ComponentLookupException." ); - } - catch ( ComponentLookupException ex ) - { - assertTrue( true ); + fail("Expected ComponentLookupException."); + } catch (ComponentLookupException ex) { + assertTrue(true); } // This component is discovered from src/test/META-INF/plexus/components.xml - DiscoveredComponent component = tc.lookup( DiscoveredComponent.class ); + DiscoveredComponent component = tc.lookup(DiscoveredComponent.class); - assertNotNull( component ); + assertNotNull(component); - assertNotNull( tc.getClassLoader() ); + assertNotNull(tc.getClassLoader()); tc.tearDown(); } - public void testLoadOnStartComponents() - throws Exception - { - PlexusTestCase tc = new PlexusTestCase() - { - protected String getCustomConfigurationName() - { - return PlexusTestCase.getTestConfiguration( getClass() ); + public void testLoadOnStartComponents() throws Exception { + PlexusTestCase tc = new PlexusTestCase() { + protected String getCustomConfigurationName() { + return PlexusTestCase.getTestConfiguration(getClass()); } }; @@ -86,30 +71,28 @@ protected String getCustomConfigurationName() // Assert that the load on start component has started. - assertTrue( "The load on start components haven't been started.", DefaultLoadOnStartService.isStarted ); + assertTrue("The load on start components haven't been started.", DefaultLoadOnStartService.isStarted); tc.tearDown(); } - public void testGetFile() - { - File file = PlexusTestCase.getTestFile( "pom.xml" ); + public void testGetFile() { + File file = PlexusTestCase.getTestFile("pom.xml"); - assertTrue( file.exists() ); + assertTrue(file.exists()); - file = PlexusTestCase.getTestFile( basedir, "pom.xml" ); + file = PlexusTestCase.getTestFile(basedir, "pom.xml"); - assertTrue( file.exists() ); + assertTrue(file.exists()); } - public void testGetPath() - { - File file = new File( PlexusTestCase.getTestPath( "pom.xml" ) ); + public void testGetPath() { + File file = new File(PlexusTestCase.getTestPath("pom.xml")); - assertTrue( file.exists() ); + assertTrue(file.exists()); - file = new File( PlexusTestCase.getTestPath( basedir, "pom.xml" ) ); + file = new File(PlexusTestCase.getTestPath(basedir, "pom.xml")); - assertTrue( file.exists() ); + assertTrue(file.exists()); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/MapOrientedComponentProcessingTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/MapOrientedComponentProcessingTest.java index de1d5cb78..3fbec0dae 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/MapOrientedComponentProcessingTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/MapOrientedComponentProcessingTest.java @@ -19,7 +19,6 @@ import java.util.Map; import junit.framework.TestCase; - import org.codehaus.plexus.DefaultPlexusContainer; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.ComponentDescriptor; @@ -28,55 +27,50 @@ import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.logging.LoggerManager; -public class MapOrientedComponentProcessingTest - extends TestCase -{ +public class MapOrientedComponentProcessingTest extends TestCase { - public void testShouldFindAndInitializeMapOrientedComponent() - throws Exception - { + public void testShouldFindAndInitializeMapOrientedComponent() throws Exception { PlexusContainer embedder = new DefaultPlexusContainer(); ComponentDescriptor descriptor = - new ComponentDescriptor(TestMapOrientedComponent.class, embedder.getContainerRealm()); + new ComponentDescriptor(TestMapOrientedComponent.class, embedder.getContainerRealm()); - descriptor.setRole( TestMapOrientedComponent.ROLE ); + descriptor.setRole(TestMapOrientedComponent.ROLE); - descriptor.setImplementation( TestMapOrientedComponent.ROLE ); + descriptor.setImplementation(TestMapOrientedComponent.ROLE); - descriptor.setComponentComposer( "map-oriented" ); + descriptor.setComponentComposer("map-oriented"); - descriptor.setComponentConfigurator( "map-oriented" ); + descriptor.setComponentConfigurator("map-oriented"); ComponentRequirement requirement = new ComponentRequirement(); - requirement.setFieldName( "testRequirement" ); - - requirement.setRole( LoggerManager.ROLE ); + requirement.setFieldName("testRequirement"); - descriptor.addRequirement( requirement ); + requirement.setRole(LoggerManager.ROLE); - PlexusConfiguration param = new XmlPlexusConfiguration( "testParameter" ); + descriptor.addRequirement(requirement); - param.setValue( "testValue" ); + PlexusConfiguration param = new XmlPlexusConfiguration("testParameter"); - PlexusConfiguration configuration = new XmlPlexusConfiguration( "configuration" ); + param.setValue("testValue"); - configuration.addChild( param ); + PlexusConfiguration configuration = new XmlPlexusConfiguration("configuration"); - descriptor.setConfiguration( configuration ); + configuration.addChild(param); + descriptor.setConfiguration(configuration); - embedder.addComponentDescriptor( descriptor ); + embedder.addComponentDescriptor(descriptor); - TestMapOrientedComponent component = embedder.lookup( TestMapOrientedComponent.class ); + TestMapOrientedComponent component = embedder.lookup(TestMapOrientedComponent.class); Map context = component.getContext(); - assertTrue( "requirement (LogManager) missing from containerContext.", - ( context.get( "testRequirement" ) instanceof LoggerManager ) ); + assertTrue( + "requirement (LogManager) missing from containerContext.", + (context.get("testRequirement") instanceof LoggerManager)); - assertEquals( "parameter missing from containerContext.", "testValue", context.get( "testParameter" ) ); + assertEquals("parameter missing from containerContext.", "testValue", context.get("testParameter")); } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/PlexusTestCaseTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/PlexusTestCaseTest.java index aedec63f8..867afa453 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/PlexusTestCaseTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/PlexusTestCaseTest.java @@ -4,25 +4,21 @@ import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; -public class PlexusTestCaseTest - extends PlexusTestCase -{ - +public class PlexusTestCaseTest extends PlexusTestCase { + private static final String CUSTOM_PROPERTY = "custom.property"; private static final String CUSTOM_VALUE = "custom.value"; @Override - protected void customizeContext( Context context ) - { - super.customizeContext( context ); - - context.put( CUSTOM_PROPERTY, CUSTOM_VALUE ); + protected void customizeContext(Context context) { + super.customizeContext(context); + + context.put(CUSTOM_PROPERTY, CUSTOM_VALUE); } - - public void testCustomizeContext() throws ContextException - { - String value = (String) getContainer().getContext().get( CUSTOM_PROPERTY ); - - assertEquals( CUSTOM_VALUE, value ); + + public void testCustomizeContext() throws ContextException { + String value = (String) getContainer().getContext().get(CUSTOM_PROPERTY); + + assertEquals(CUSTOM_VALUE, value); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/TestMapOrientedComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/TestMapOrientedComponent.java index d0dd9dd68..3660e671a 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/TestMapOrientedComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/TestMapOrientedComponent.java @@ -16,32 +16,26 @@ * limitations under the License. */ -import org.codehaus.plexus.component.repository.ComponentRequirement; - import java.util.Map; import java.util.TreeMap; -public class TestMapOrientedComponent - implements MapOrientedComponent -{ - +import org.codehaus.plexus.component.repository.ComponentRequirement; + +public class TestMapOrientedComponent implements MapOrientedComponent { + public static final String ROLE = TestMapOrientedComponent.class.getName(); private Map context = new TreeMap(); - public void addComponentRequirement( ComponentRequirement requirementDescriptor, Object requirementValue ) - { - context.put( requirementDescriptor.getFieldName(), requirementValue ); + public void addComponentRequirement(ComponentRequirement requirementDescriptor, Object requirementValue) { + context.put(requirementDescriptor.getFieldName(), requirementValue); } - public void setComponentConfiguration( Map componentConfiguration ) - { - context.putAll( componentConfiguration ); + public void setComponentConfiguration(Map componentConfiguration) { + context.putAll(componentConfiguration); } - - public Map getContext() - { + + public Map getContext() { return context; } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/AbstractComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/AbstractComponent.java index 1ec598978..340f36f33 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/AbstractComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/AbstractComponent.java @@ -18,17 +18,14 @@ /** * - * + * * @author Jason van Zyl * */ -public class AbstractComponent - implements Component -{ +public class AbstractComponent implements Component { private ComponentA componentA; - public ComponentA getComponentA() - { + public ComponentA getComponentA() { return componentA; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/AbstractCompositionResolverTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/AbstractCompositionResolverTest.java index 9496f8527..e3528b9ec 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/AbstractCompositionResolverTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/AbstractCompositionResolverTest.java @@ -16,13 +16,13 @@ * limitations under the License. */ +import java.util.List; + import junit.framework.TestCase; -import org.codehaus.plexus.component.repository.ComponentDescriptor; -import org.codehaus.plexus.component.repository.io.PlexusTools; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; - -import java.util.List; +import org.codehaus.plexus.component.repository.ComponentDescriptor; +import org.codehaus.plexus.component.repository.io.PlexusTools; /** * @@ -30,9 +30,7 @@ * @author Jason van Zyl * */ -public abstract class AbstractCompositionResolverTest - extends TestCase -{ +public abstract class AbstractCompositionResolverTest extends TestCase { /** * @@ -40,7 +38,6 @@ public abstract class AbstractCompositionResolverTest */ protected abstract CompositionResolver getCompositionResolver(); - // ------------------------------------------------------------------------ // // +-------+ +-------+ @@ -54,61 +51,53 @@ public abstract class AbstractCompositionResolverTest // +-------+ // // ------------------------------------------------------------------------ - public void testSimpleComponentResolution() - throws Exception - { - String cc1 = - "" + - " java.lang.String" + - " c1" + - " " + - " " + - " c2" + - " " + - " " + - " c3" + - " " + - " " + - ""; - - String cc2 = - "" + - " java.lang.String" + - " c2" + - ""; - - String cc3 = - "" + - " java.lang.String" + - " c3" + - ""; - - ClassWorld classWorld = new ClassWorld( "test", Thread.currentThread().getContextClassLoader() ); - ClassRealm realm = classWorld.getRealm( "test" ); + public void testSimpleComponentResolution() throws Exception { + String cc1 = "" + " java.lang.String" + + " c1" + + " " + + " " + + " c2" + + " " + + " " + + " c3" + + " " + + " " + + ""; + + String cc2 = "" + " java.lang.String" + + " c2" + + ""; + + String cc3 = "" + " java.lang.String" + + " c3" + + ""; + + ClassWorld classWorld = new ClassWorld("test", Thread.currentThread().getContextClassLoader()); + ClassRealm realm = classWorld.getRealm("test"); CompositionResolver compositionResolver = getCompositionResolver(); - ComponentDescriptor c1 = PlexusTools.buildComponentDescriptor( cc1, realm ); + ComponentDescriptor c1 = PlexusTools.buildComponentDescriptor(cc1, realm); - ComponentDescriptor c2 = PlexusTools.buildComponentDescriptor( cc2, realm ); + ComponentDescriptor c2 = PlexusTools.buildComponentDescriptor(cc2, realm); - ComponentDescriptor c3 = PlexusTools.buildComponentDescriptor( cc3, realm ); + ComponentDescriptor c3 = PlexusTools.buildComponentDescriptor(cc3, realm); - compositionResolver.addComponentDescriptor( c1 ); + compositionResolver.addComponentDescriptor(c1); - compositionResolver.addComponentDescriptor( c2 ); + compositionResolver.addComponentDescriptor(c2); - compositionResolver.addComponentDescriptor( c3 ); + compositionResolver.addComponentDescriptor(c3); - List dependencies = compositionResolver.getRequirements( c1.getRole(), c1.getRoleHint() ); + List dependencies = compositionResolver.getRequirements(c1.getRole(), c1.getRoleHint()); - assertEquals( 2, dependencies.size() ); + assertEquals(2, dependencies.size()); - assertTrue( dependencies.contains( c2.getRole() + CompositionResolver.SEPARATOR_CHAR + c2.getRoleHint() ) ); + assertTrue(dependencies.contains(c2.getRole() + CompositionResolver.SEPARATOR_CHAR + c2.getRoleHint())); - assertTrue( dependencies.contains( c3.getRole() + CompositionResolver.SEPARATOR_CHAR + c2.getRoleHint() ) ); + assertTrue(dependencies.contains(c3.getRole() + CompositionResolver.SEPARATOR_CHAR + c2.getRoleHint())); - assertEquals( 2, dependencies.size() ); + assertEquals(2, dependencies.size()); } // ------------------------------------------------------------------------ @@ -130,83 +119,71 @@ public void testSimpleComponentResolution() // +-------+ // // ------------------------------------------------------------------------ - public void testComplexComponentResolution() - throws Exception - { - String cc1 = - "" + - " java.lang.String" + - " c1" + - " " + - " " + - " c2" + - " " + - " " + - " c3" + - " " + - " " + - ""; - - String cc2 = - "" + - " java.lang.String" + - " c2" + - ""; - - String cc3 = - "" + - " java.lang.String" + - " c3" + - " " + - " " + - " c4" + - " " + - " " + - " c5" + - " " + - " " + - ""; - - String cc4 = - "" + - " java.lang.String" + - " c4" + - ""; - - String cc5 = - "" + - " java.lang.String" + - " c5" + - ""; - - ClassWorld classWorld = new ClassWorld( "test", Thread.currentThread().getContextClassLoader() ); - ClassRealm realm = classWorld.getRealm( "test" ); + public void testComplexComponentResolution() throws Exception { + String cc1 = "" + " java.lang.String" + + " c1" + + " " + + " " + + " c2" + + " " + + " " + + " c3" + + " " + + " " + + ""; + + String cc2 = "" + " java.lang.String" + + " c2" + + ""; + + String cc3 = "" + " java.lang.String" + + " c3" + + " " + + " " + + " c4" + + " " + + " " + + " c5" + + " " + + " " + + ""; + + String cc4 = "" + " java.lang.String" + + " c4" + + ""; + + String cc5 = "" + " java.lang.String" + + " c5" + + ""; + + ClassWorld classWorld = new ClassWorld("test", Thread.currentThread().getContextClassLoader()); + ClassRealm realm = classWorld.getRealm("test"); CompositionResolver compositionResolver = getCompositionResolver(); - ComponentDescriptor c1 = PlexusTools.buildComponentDescriptor( cc1, realm ); + ComponentDescriptor c1 = PlexusTools.buildComponentDescriptor(cc1, realm); - ComponentDescriptor c2 = PlexusTools.buildComponentDescriptor( cc2, realm ); + ComponentDescriptor c2 = PlexusTools.buildComponentDescriptor(cc2, realm); - ComponentDescriptor c3 = PlexusTools.buildComponentDescriptor( cc3, realm ); + ComponentDescriptor c3 = PlexusTools.buildComponentDescriptor(cc3, realm); - ComponentDescriptor c4 = PlexusTools.buildComponentDescriptor( cc4, realm ); + ComponentDescriptor c4 = PlexusTools.buildComponentDescriptor(cc4, realm); - ComponentDescriptor c5 = PlexusTools.buildComponentDescriptor( cc5, realm ); + ComponentDescriptor c5 = PlexusTools.buildComponentDescriptor(cc5, realm); - compositionResolver.addComponentDescriptor( c1 ); + compositionResolver.addComponentDescriptor(c1); - compositionResolver.addComponentDescriptor( c2 ); + compositionResolver.addComponentDescriptor(c2); - compositionResolver.addComponentDescriptor( c3 ); + compositionResolver.addComponentDescriptor(c3); - compositionResolver.addComponentDescriptor( c4 ); + compositionResolver.addComponentDescriptor(c4); - compositionResolver.addComponentDescriptor( c5 ); + compositionResolver.addComponentDescriptor(c5); - List dependencies = compositionResolver.getRequirements( c1.getRole(), c1.getRoleHint() ); + List dependencies = compositionResolver.getRequirements(c1.getRole(), c1.getRoleHint()); - assertEquals( 2, dependencies.size() ); + assertEquals(2, dependencies.size()); // I just leave this at the moment as I am just 99% sure that this is not needed and not // correct. compositionResolver.getComponentDependencies() should return only direct dependencies @@ -221,11 +198,11 @@ public void testComplexComponentResolution() // if there are cycles. /** - // c5 must come before c3 - assertTrue( dependencies.indexOf( "c5" ) < dependencies.indexOf( "c3" ) ); - - // c4 must come before c3 - assertTrue( dependencies.indexOf( "c4" ) < dependencies.indexOf( "c3" ) ); - */ + * // c5 must come before c3 + * assertTrue( dependencies.indexOf( "c5" ) < dependencies.indexOf( "c3" ) ); + * + * // c4 must come before c3 + * assertTrue( dependencies.indexOf( "c4" ) < dependencies.indexOf( "c3" ) ); + */ } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/Component.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/Component.java index 26d6247ae..6368a9d3d 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/Component.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/Component.java @@ -18,10 +18,8 @@ /** * - * + * * @author Jason van Zyl * */ -public interface Component -{ -} +public interface Component {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentA.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentA.java index 0d3434c42..fea5dc33a 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentA.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentA.java @@ -22,8 +22,7 @@ * @author Jason van Zyl * */ -public interface ComponentA -{ +public interface ComponentA { String ROLE = ComponentA.class.getName(); ComponentB getComponentB(); diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentB.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentB.java index 6b4983e0d..f9625fc06 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentB.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentB.java @@ -22,8 +22,6 @@ * @author Jason van Zyl * */ -public interface ComponentB -{ - ComponentC getComponentC(); - +public interface ComponentB { + ComponentC getComponentC(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentC.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentC.java index 8f8f67728..1a473c2de 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentC.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentC.java @@ -22,6 +22,4 @@ * @author Jason van Zyl * */ -public interface ComponentC -{ -} +public interface ComponentC {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentD.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentD.java index 097df271e..501acc81b 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentD.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentD.java @@ -22,6 +22,4 @@ * @author Jason van Zyl * */ -public interface ComponentD -{ -} +public interface ComponentD {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentE.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentE.java index 84852bc12..9c38c6bef 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentE.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentE.java @@ -22,6 +22,4 @@ * @author Jason van Zyl * */ -public interface ComponentE -{ -} +public interface ComponentE {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentF.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentF.java index 731d72b30..35d40705f 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentF.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentF.java @@ -22,61 +22,50 @@ /** * @author Michal Maczka */ -public class ComponentF -{ +public class ComponentF { private ComponentA componentA; private ComponentB componentB; private ComponentC[] componentC; private List componentD; private Map componentE; - public ComponentA getComponentA() - { + public ComponentA getComponentA() { return componentA; } - public void setComponentA( ComponentA componentA ) - { + public void setComponentA(ComponentA componentA) { this.componentA = componentA; } - public ComponentB getComponentB() - { + public ComponentB getComponentB() { return componentB; } - public void setComponentB( ComponentB componentB ) - { + public void setComponentB(ComponentB componentB) { this.componentB = componentB; } - public ComponentC[] getComponentC() - { + public ComponentC[] getComponentC() { return componentC; } - public void setComponentC( ComponentC[] componentC ) - { + public void setComponentC(ComponentC[] componentC) { this.componentC = componentC; } - public List getComponentD() - { + public List getComponentD() { return componentD; } - public void setComponentD( List componentD ) - { + public void setComponentD(List componentD) { this.componentD = componentD; } - public Map getComponentE() - { + public Map getComponentE() { return componentE; } - public void setComponentE( Map componentE ) - { + public void setComponentE(Map componentE) { this.componentE = componentE; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentRealmCompositionTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentRealmCompositionTest.java index 318b32992..c7c5ba920 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentRealmCompositionTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentRealmCompositionTest.java @@ -1,19 +1,18 @@ package org.codehaus.plexus.component.composition; -import org.codehaus.plexus.PlexusTestCase; -import static org.codehaus.plexus.PlexusConstants.PLEXUS_DEFAULT_HINT; -import org.codehaus.plexus.classworlds.realm.ClassRealm; - import java.io.File; import java.net.URL; -import java.util.Map; import java.util.List; +import java.util.Map; import java.util.TreeMap; +import org.codehaus.plexus.PlexusTestCase; +import org.codehaus.plexus.classworlds.realm.ClassRealm; + +import static org.codehaus.plexus.PlexusConstants.PLEXUS_DEFAULT_HINT; + /** @author Jason van Zyl */ -public class ComponentRealmCompositionTest - extends PlexusTestCase -{ +public class ComponentRealmCompositionTest extends PlexusTestCase { // // Component archives // @@ -36,122 +35,97 @@ public class ComponentRealmCompositionTest private static final String PLUGIN_0_REALM = "plugin0Realm"; private static final String PLUGIN_1_REALM = "plugin1Realm"; - protected void setUp() throws Exception - { + protected void setUp() throws Exception { super.setUp(); // Create ClassRealm plugin0 with plugin0 -> A, plugin0 -> B - createClassRealm( PLUGIN_0_REALM, - PLUGIN_0_JAR, - COMPONENT_A_JAR, - COMPONENT_B_JAR, - ARCHIVER_JAR ); + createClassRealm(PLUGIN_0_REALM, PLUGIN_0_JAR, COMPONENT_A_JAR, COMPONENT_B_JAR, ARCHIVER_JAR); // Create ClassRealm plugin1 with plugin1 -> A, plugin1 -> C - createClassRealm( PLUGIN_1_REALM, - PLUGIN_1_JAR, - COMPONENT_A_JAR, - COMPONENT_C_JAR, - ARCHIVER_JAR ); + createClassRealm(PLUGIN_1_REALM, PLUGIN_1_JAR, COMPONENT_A_JAR, COMPONENT_C_JAR, ARCHIVER_JAR); } /* - * We are testing that when the same component implementation exists in more then one - * realm and components depend on those implementations, that the right realm is used - * to wire up the components. - * - * An example of this in practice are Maven plugins where each plugin is loaded into - * a separate realm and the plugin may have dependencies on other components. We want - * to make sure that a requirement, say a JarArchiver, for a given component, say the - * maven-jar-plugin, is wired up with a JarArchiver taken from the same realm as the - * maven-jar-plugin and not a different realm. - */ - - public void testCompositionWhereTheSameImplementationExistsInDifferentRealms() - throws Exception - { + * We are testing that when the same component implementation exists in more then one + * realm and components depend on those implementations, that the right realm is used + * to wire up the components. + * + * An example of this in practice are Maven plugins where each plugin is loaded into + * a separate realm and the plugin may have dependencies on other components. We want + * to make sure that a requirement, say a JarArchiver, for a given component, say the + * maven-jar-plugin, is wired up with a JarArchiver taken from the same realm as the + * maven-jar-plugin and not a different realm. + */ + + public void testCompositionWhereTheSameImplementationExistsInDifferentRealms() throws Exception { // Plugin0 - getContainer().lookup( PLUGIN_0_ROLE ); - + getContainer().lookup(PLUGIN_0_ROLE); // Plugin1 - getContainer().lookup( PLUGIN_1_ROLE ); + getContainer().lookup(PLUGIN_1_ROLE); // Plugin0(alt) - getContainer().lookup( PLUGIN_0_ROLE, "alt" ); - + getContainer().lookup(PLUGIN_0_ROLE, "alt"); // Plugin1(alt) - getContainer().lookup( PLUGIN_1_ROLE, "alt" ); + getContainer().lookup(PLUGIN_1_ROLE, "alt"); } public void testThatASingletonComponentIntheCoreRealmWhenLookedUpInComponentRealmsYieldsTheSameInstance() - throws Exception - { - } + throws Exception {} - public void testMultiRealmLookupMap() - throws Exception - { - Map plugin0Map = getContainer().lookupMap( PLUGIN_0_ROLE ); - assertNotNull("plugin0Map is null", plugin0Map ); - assertNotNull("plugin0Map does not contain a DefaultPlugin0", plugin0Map.get( PLEXUS_DEFAULT_HINT)); - assertNotNull("plugin0Map does not contain a AltPlugin0", plugin0Map.get( "alt")); + public void testMultiRealmLookupMap() throws Exception { + Map plugin0Map = getContainer().lookupMap(PLUGIN_0_ROLE); + assertNotNull("plugin0Map is null", plugin0Map); + assertNotNull("plugin0Map does not contain a DefaultPlugin0", plugin0Map.get(PLEXUS_DEFAULT_HINT)); + assertNotNull("plugin0Map does not contain a AltPlugin0", plugin0Map.get("alt")); assertEquals("Expected only 2 components in plugin0Map", 2, plugin0Map.size()); - Map plugin1Map = getContainer().lookupMap( PLUGIN_1_ROLE ); + Map plugin1Map = getContainer().lookupMap(PLUGIN_1_ROLE); assertNotNull("plugin1Map is null", plugin1Map); - assertNotNull("plugin1Map does not contain a DefaultPlugin1", plugin1Map.get( PLEXUS_DEFAULT_HINT)); - assertNotNull("plugin1Map does not contain a AltPlugin1", plugin1Map.get( "alt")); + assertNotNull("plugin1Map does not contain a DefaultPlugin1", plugin1Map.get(PLEXUS_DEFAULT_HINT)); + assertNotNull("plugin1Map does not contain a AltPlugin1", plugin1Map.get("alt")); assertEquals("Expected only 2 components in plugin1Map", 2, plugin1Map.size()); - } - public void testMultiRealmLookupList() - throws Exception - { - List plugin0List = getContainer().lookupList( PLUGIN_0_ROLE ); - assertNotNull("plugin0List is null", plugin0List ); - Map plugin0Map = mapByClassSimpleName( plugin0List ); - assertNotNull("plugin0List does not contain a DefaultPlugin0", plugin0Map.get( "DefaultPlugin0")); - assertNotNull("plugin0List does not contain a AltPlugin0", plugin0Map.get( "AltPlugin0")); + public void testMultiRealmLookupList() throws Exception { + List plugin0List = getContainer().lookupList(PLUGIN_0_ROLE); + assertNotNull("plugin0List is null", plugin0List); + Map plugin0Map = mapByClassSimpleName(plugin0List); + assertNotNull("plugin0List does not contain a DefaultPlugin0", plugin0Map.get("DefaultPlugin0")); + assertNotNull("plugin0List does not contain a AltPlugin0", plugin0Map.get("AltPlugin0")); assertEquals("Expected only 2 components in plugin0Map", 2, plugin0Map.size()); - List plugin1List = getContainer().lookupList( PLUGIN_1_ROLE ); - assertNotNull("plugin1List is null", plugin1List ); - Map plugin1Map = mapByClassSimpleName( plugin1List ); - assertNotNull("plugin1List does not contain a DefaultPlugin1", plugin1Map.get( "DefaultPlugin1")); - assertNotNull("plugin1List does not contain a AltPlugin1", plugin1Map.get( "AltPlugin1")); + List plugin1List = getContainer().lookupList(PLUGIN_1_ROLE); + assertNotNull("plugin1List is null", plugin1List); + Map plugin1Map = mapByClassSimpleName(plugin1List); + assertNotNull("plugin1List does not contain a DefaultPlugin1", plugin1Map.get("DefaultPlugin1")); + assertNotNull("plugin1List does not contain a AltPlugin1", plugin1Map.get("AltPlugin1")); assertEquals("Expected only 2 components in plugin0Map", 2, plugin1Map.size()); } - private ClassRealm createClassRealm(String id, String... jars) - throws Exception - { + private ClassRealm createClassRealm(String id, String... jars) throws Exception { // create the realm - ClassRealm classRealm = getContainer().createChildRealm( id ); + ClassRealm classRealm = getContainer().createChildRealm(id); // populate the realm - for ( String jar : jars ) - { + for (String jar : jars) { File file = new File(jar); - assertTrue( jar + " is not a file", file.isFile() ); + assertTrue(jar + " is not a file", file.isFile()); URL url = file.toURI().toURL(); - classRealm.addURL( url ); + classRealm.addURL(url); } // descover all component definitions in the realm and register them with the repository - getContainer().discoverComponents( classRealm ); + getContainer().discoverComponents(classRealm); return classRealm; } - private Map mapByClassSimpleName(List objects) - { + private Map mapByClassSimpleName(List objects) { Map map = new TreeMap(); - for ( Object object : objects ) - { + for (Object object : objects) { map.put(object.getClass().getSimpleName(), object); } return map; diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentWithSeveralFieldsOfTheSameType.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentWithSeveralFieldsOfTheSameType.java index 002160df8..b113c7e4a 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentWithSeveralFieldsOfTheSameType.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/ComponentWithSeveralFieldsOfTheSameType.java @@ -19,19 +19,16 @@ /** * @author Trygve Laugstøl */ -public class ComponentWithSeveralFieldsOfTheSameType -{ +public class ComponentWithSeveralFieldsOfTheSameType { private ComponentE one; private ComponentE two; - public ComponentE getOne() - { + public ComponentE getOne() { return one; } - public ComponentE getTwo() - { + public ComponentE getTwo() { return two; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponent.java index 0579724f6..708319e90 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponent.java @@ -18,11 +18,8 @@ /** * - * + * * @author Jason van Zyl * */ -public class DefaultComponent - extends AbstractComponent -{ -} +public class DefaultComponent extends AbstractComponent {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentA.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentA.java index 3e774b17c..85da06c96 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentA.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentA.java @@ -22,9 +22,7 @@ * @author Jason van Zyl * */ -public class DefaultComponentA - implements ComponentA -{ +public class DefaultComponentA implements ComponentA { private ComponentB componentB; private String host; @@ -32,9 +30,7 @@ public class DefaultComponentA private String port; // Just so we can retrieve the value of componentB for testing. */ - public ComponentB getComponentB() - { + public ComponentB getComponentB() { return componentB; } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentB.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentB.java index 34bf2686a..71405d3e4 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentB.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentB.java @@ -20,19 +20,15 @@ * @author Jason van Zyl * */ -public class DefaultComponentB - implements ComponentB -{ +public class DefaultComponentB implements ComponentB { private ComponentC componentC; - public ComponentC getComponentC() - { + public ComponentC getComponentC() { return componentC; } - public void setComponentC( ComponentC componentC ) - { - System.out.println( "Setting componentC:" + componentC ); + public void setComponentC(ComponentC componentC) { + System.out.println("Setting componentC:" + componentC); this.componentC = componentC; } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentC.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentC.java index 9de52d229..279f9fca3 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentC.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentC.java @@ -22,6 +22,4 @@ * @author Jason van Zyl * */ -public class DefaultComponentC implements ComponentC -{ -} +public class DefaultComponentC implements ComponentC {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentComposerManagerTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentComposerManagerTest.java index 5e641dad7..9b8b12e72 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentComposerManagerTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultComponentComposerManagerTest.java @@ -21,27 +21,22 @@ /** * @author Michal Maczka */ -public class DefaultComponentComposerManagerTest - extends PlexusTestCase -{ - protected String getCustomConfigurationName() - { +public class DefaultComponentComposerManagerTest extends PlexusTestCase { + protected String getCustomConfigurationName() { return "org/codehaus/plexus/component/composition/components.xml"; } - public void testComposition() - throws Exception - { - ComponentA componentA = lookup( ComponentA.class ); + public void testComposition() throws Exception { + ComponentA componentA = lookup(ComponentA.class); - assertNotNull( componentA ); + assertNotNull(componentA); ComponentB componentB = componentA.getComponentB(); - assertNotNull( componentB ); + assertNotNull(componentB); ComponentC componentC = componentB.getComponentC(); - assertNotNull( componentC ); + assertNotNull(componentC); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultCompositionResolverTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultCompositionResolverTest.java index 2e78ef168..021e40dad 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultCompositionResolverTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/composition/DefaultCompositionResolverTest.java @@ -22,11 +22,8 @@ * @author Jason van Zyl * */ -public class DefaultCompositionResolverTest - extends AbstractCompositionResolverTest -{ - protected CompositionResolver getCompositionResolver() - { +public class DefaultCompositionResolverTest extends AbstractCompositionResolverTest { + protected CompositionResolver getCompositionResolver() { return new DefaultCompositionResolver(); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/AbstractComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/AbstractComponent.java index 8eabe220a..2179af6be 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/AbstractComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/AbstractComponent.java @@ -26,17 +26,14 @@ /** * - * + * * @author Jason van Zyl * */ -public class AbstractComponent - implements Component -{ +public class AbstractComponent implements Component { private String name; - public String getName() - { + public String getName() { return name; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/AbstractComponentConfiguratorTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/AbstractComponentConfiguratorTest.java index 5f0740e6c..e04e8c2bd 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/AbstractComponentConfiguratorTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/AbstractComponentConfiguratorTest.java @@ -50,680 +50,625 @@ /** * @author Michal Maczka */ -public abstract class AbstractComponentConfiguratorTest - extends PlexusTestCase -{ - protected void configureComponent(Object component, ComponentDescriptor descriptor, ClassRealm realm) throws Exception { +public abstract class AbstractComponentConfiguratorTest extends PlexusTestCase { + protected void configureComponent(Object component, ComponentDescriptor descriptor, ClassRealm realm) + throws Exception { ComponentConfigurator cc = getComponentConfigurator(); - cc.configureComponent( component, descriptor.getConfiguration(), realm ); + cc.configureComponent(component, descriptor.getConfiguration(), realm); } - - protected void configureComponent(Object component, ComponentDescriptor descriptor, ClassRealm realm, ExpressionEvaluator expressionEvaluator) throws Exception { + protected void configureComponent( + Object component, ComponentDescriptor descriptor, ClassRealm realm, ExpressionEvaluator expressionEvaluator) + throws Exception { ComponentConfigurator cc = getComponentConfigurator(); - cc.configureComponent( component, descriptor.getConfiguration(), expressionEvaluator, realm ); + cc.configureComponent(component, descriptor.getConfiguration(), expressionEvaluator, realm); } protected abstract ComponentConfigurator getComponentConfigurator() throws Exception; - public void testComponentConfigurator() - throws Exception - { - String xml = "" + - " true" + - " 64" + - " -128" + - " -1" + - " 1" + - " 2" + - " 3" + - " X" + - " foo" + - " test.txt" + - " http://www.apache.org/" + - " http://maven.apache.org/" + - " " + - " jason" + - " tess" + - " " + - " " + - " jason" + - " " + - ""; - - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + public void testComponentConfigurator() throws Exception { + String xml = "" + " true" + + " 64" + + " -128" + + " -1" + + " 1" + + " 2" + + " 3" + + " X" + + " foo" + + " test.txt" + + " http://www.apache.org/" + + " http://maven.apache.org/" + + " " + + " jason" + + " tess" + + " " + + " " + + " jason" + + " " + + ""; + + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ConfigurableComponent component = new ConfigurableComponent(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); configureComponent(component, descriptor, realm); - assertEquals( "check boolean value", true, component.getBooleanValue() ); + assertEquals("check boolean value", true, component.getBooleanValue()); - assertEquals( "check byte value", 64, component.getByteValue() ); + assertEquals("check byte value", 64, component.getByteValue()); - assertEquals( "check short value", -128, component.getShortValue() ); + assertEquals("check short value", -128, component.getShortValue()); - assertEquals( "check integer value", -1, component.getIntValue() ); + assertEquals("check integer value", -1, component.getIntValue()); - assertEquals( "check float value", 1.0f, component.getFloatValue(), 0.001f ); + assertEquals("check float value", 1.0f, component.getFloatValue(), 0.001f); - assertEquals( "check long value", 2L, component.getLongValue() ); + assertEquals("check long value", 2L, component.getLongValue()); - assertEquals( "check double value", 3.0, component.getDoubleValue(), 0.001 ); + assertEquals("check double value", 3.0, component.getDoubleValue(), 0.001); - assertEquals( 'X', component.getCharValue() ); + assertEquals('X', component.getCharValue()); - assertEquals( "foo", component.getStringValue() ); + assertEquals("foo", component.getStringValue()); - assertEquals( new File( "test.txt" ), component.getFileValue() ); + assertEquals(new File("test.txt"), component.getFileValue()); - assertEquals( new URI( "http://www.apache.org/" ), component.getUriValue() ); + assertEquals(new URI("http://www.apache.org/"), component.getUriValue()); - assertEquals( new URL( "http://maven.apache.org/" ), component.getUrlValue() ); + assertEquals(new URL("http://maven.apache.org/"), component.getUrlValue()); List list = component.getImportantThings(); - assertEquals( 2, list.size() ); + assertEquals(2, list.size()); - assertEquals( "jason", ( (ImportantThing) list.get( 0 ) ).getName() ); + assertEquals("jason", ((ImportantThing) list.get(0)).getName()); - assertEquals( "tess", ( (ImportantThing) list.get( 1 ) ).getName() ); + assertEquals("tess", ((ImportantThing) list.get(1)).getName()); // Embedded Configuration PlexusConfiguration c = component.getConfiguration(); - assertEquals( "jason", c.getChild( "name" ).getValue() ); + assertEquals("jason", c.getChild("name").getValue()); } - public void testComponentConfiguratorWithAComponentThatProvidesSettersForConfiguration() - throws Exception - { + public void testComponentConfiguratorWithAComponentThatProvidesSettersForConfiguration() throws Exception { String xml = "" + " 0" + " 1" - + " 2" + " 3" - + " foo" + " " - + " jason" - + " tess" + " " - + " " + " jason" + " " + ""; + + " 2" + " 3" + + " foo" + " " + + " jason" + + " tess" + " " + + " " + " jason" + " " + ""; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ComponentWithSetters component = new ComponentWithSetters(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); configureComponent(component, descriptor, realm); - assertEquals( "check integer value", 0, component.getIntValue() ); + assertEquals("check integer value", 0, component.getIntValue()); - assertTrue( component.intValueSet ); + assertTrue(component.intValueSet); - assertEquals( "check float value", 1.0f, component.getFloatValue(), 0.001f ); + assertEquals("check float value", 1.0f, component.getFloatValue(), 0.001f); - assertTrue( component.floatValueSet ); + assertTrue(component.floatValueSet); - assertEquals( "check long value", 2L, component.getLongValue() ); + assertEquals("check long value", 2L, component.getLongValue()); - assertTrue( component.longValueSet ); + assertTrue(component.longValueSet); - assertEquals( "check double value", 3.0, component.getDoubleValue(), 0.001 ); + assertEquals("check double value", 3.0, component.getDoubleValue(), 0.001); - assertTrue( component.doubleValueSet ); + assertTrue(component.doubleValueSet); - assertEquals( "foo", component.getStringValue() ); + assertEquals("foo", component.getStringValue()); - assertTrue( component.stringValueSet ); + assertTrue(component.stringValueSet); List list = component.getImportantThings(); - assertEquals( 2, list.size() ); + assertEquals(2, list.size()); - assertEquals( "jason", ( (ImportantThing) list.get( 0 ) ).getName() ); + assertEquals("jason", ((ImportantThing) list.get(0)).getName()); - assertEquals( "tess", ( (ImportantThing) list.get( 1 ) ).getName() ); + assertEquals("tess", ((ImportantThing) list.get(1)).getName()); - assertTrue( component.importantThingsValueSet ); + assertTrue(component.importantThingsValueSet); // Embedded Configuration PlexusConfiguration c = component.getConfiguration(); - assertEquals( "jason", c.getChild( "name" ).getValue() ); + assertEquals("jason", c.getChild("name").getValue()); - assertTrue( component.configurationValueSet ); + assertTrue(component.configurationValueSet); } - public void testComponentConfigurationWhereFieldsToConfigureResideInTheSuperclass() - throws Exception - { + public void testComponentConfigurationWhereFieldsToConfigureResideInTheSuperclass() throws Exception { String xml = "" + " jason" + "
    bollywood
    " + "
    "; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); DefaultComponent component = new DefaultComponent(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); configureComponent(component, descriptor, realm); - assertEquals( "jason", component.getName() ); + assertEquals("jason", component.getName()); - assertEquals( "bollywood", component.getAddress() ); + assertEquals("bollywood", component.getAddress()); } - public void testComponentConfigurationWhereFieldsAreCollections() - throws Exception - { + public void testComponentConfigurationWhereFieldsAreCollections() throws Exception { String xml = "" + " " + " " + " life" - + " " + " " + " " + " " - + " life" + " " + " " - + " " + " " - + " life" + " " + " " + " " - + " abc" + " def" + " " - + " abc" - + " abc" + - // TODO: implement List etc.. - // "" + - // " 12" + - // " 34" + - // "" + - ""; - - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + + " " + " " + " " + " " + + " life" + " " + " " + + " " + " " + + " life" + " " + " " + " " + + " abc" + " def" + " " + + " abc" + + " abc" + + // TODO: implement List etc.. + // "" + + // " 12" + + // " 34" + + // "" + + ""; + + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ComponentWithCollectionFields component = new ComponentWithCollectionFields(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); configureComponent(component, descriptor, realm); Vector vector = component.getVector(); - assertEquals( "life", ( (ImportantThing) vector.get( 0 ) ).getName() ); + assertEquals("life", ((ImportantThing) vector.get(0)).getName()); - assertEquals( 1, vector.size() ); + assertEquals(1, vector.size()); Set set = component.getHashSet(); - assertEquals( 1, set.size() ); + assertEquals(1, set.size()); Object[] setContents = set.toArray(); - assertEquals( "life", ( (ImportantThing) setContents[0] ).getName() ); + assertEquals("life", ((ImportantThing) setContents[0]).getName()); List list = component.getList(); - assertEquals( list.getClass(), LinkedList.class ); + assertEquals(list.getClass(), LinkedList.class); - assertEquals( "life", ( (ImportantThing) list.get( 0 ) ).getName() ); + assertEquals("life", ((ImportantThing) list.get(0)).getName()); - assertEquals( 1, list.size() ); + assertEquals(1, list.size()); List stringList = component.getStringList(); - assertEquals( "abc", (String) stringList.get( 0 ) ); + assertEquals("abc", (String) stringList.get(0)); - assertEquals( "def", (String) stringList.get( 1 ) ); + assertEquals("def", (String) stringList.get(1)); - assertEquals( 2, stringList.size() ); + assertEquals(2, stringList.size()); set = component.getSet(); - assertEquals( 1, set.size() ); + assertEquals(1, set.size()); set = component.getSortedSet(); - assertEquals( 1, set.size() ); + assertEquals(1, set.size()); } - public void testComponentConfigurationWhereFieldsAreArrays() - throws Exception - { + public void testComponentConfigurationWhereFieldsAreArrays() throws Exception { String xml = "" + " " + " value1" - + " value2" + " " + " " - + " 42" + " 69" + " " - + " " + " Hello" - + " World!" + " " - + " " + " some string" - + " something important" - + " 303" + " " + " " - + " http://foo.com/bar" + " file://localhost/c:/windows" + " " - + " " + " c:/windows" + " /usr/local/bin/foo.sh" - + " " + ""; - - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + + " value2" + " " + " " + + " 42" + " 69" + " " + + " " + " Hello" + + " World!" + " " + + " " + " some string" + + " something important" + + " 303" + " " + + " " + + " http://foo.com/bar" + " file://localhost/c:/windows" + " " + + " " + " c:/windows" + " /usr/local/bin/foo.sh" + + " " + ""; + + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ComponentWithArrayFields component = new ComponentWithArrayFields(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); configureComponent(component, descriptor, realm); String[] stringArray = component.getStringArray(); - assertEquals( 2, stringArray.length ); + assertEquals(2, stringArray.length); - assertEquals( "value1", stringArray[0] ); + assertEquals("value1", stringArray[0]); - assertEquals( "value2", stringArray[1] ); + assertEquals("value2", stringArray[1]); Integer[] integerArray = component.getIntegerArray(); - assertEquals( 2, integerArray.length ); + assertEquals(2, integerArray.length); - assertEquals( new Integer( 42 ), integerArray[0] ); + assertEquals(new Integer(42), integerArray[0]); - assertEquals( new Integer( 69 ), integerArray[1] ); + assertEquals(new Integer(69), integerArray[1]); ImportantThing[] importantThingArray = component.getImportantThingArray(); - assertEquals( 2, importantThingArray.length ); + assertEquals(2, importantThingArray.length); - assertEquals( "Hello", importantThingArray[0].getName() ); + assertEquals("Hello", importantThingArray[0].getName()); - assertEquals( "World!", importantThingArray[1].getName() ); + assertEquals("World!", importantThingArray[1].getName()); Object[] objectArray = component.getObjectArray(); - assertEquals( 3, objectArray.length ); + assertEquals(3, objectArray.length); - assertEquals( "some string", objectArray[0] ); + assertEquals("some string", objectArray[0]); - assertEquals( "something important", ( (ImportantThing) objectArray[1] ).getName() ); + assertEquals("something important", ((ImportantThing) objectArray[1]).getName()); - assertEquals(303, objectArray[2] ); + assertEquals(303, objectArray[2]); URL[] urls = component.getUrlArray(); - assertEquals( new URL( "http://foo.com/bar" ), urls[0] ); + assertEquals(new URL("http://foo.com/bar"), urls[0]); - assertEquals( new URL( "file://localhost/c:/windows" ), urls[1] ); + assertEquals(new URL("file://localhost/c:/windows"), urls[1]); File[] files = component.getFileArray(); - assertEquals( new File( "c:/windows" ), files[0] ); + assertEquals(new File("c:/windows"), files[0]); - assertEquals( new File( "/usr/local/bin/foo.sh" ), files[1] ); + assertEquals(new File("/usr/local/bin/foo.sh"), files[1]); } - public void testComponentConfigurationWithCompositeFields() - throws Exception - { + public void testComponentConfigurationWithCompositeFields() throws Exception { String xml = "" - + " " - + " I am not abstract!" + " " + ""; + + " " + + " I am not abstract!" + " " + ""; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ComponentWithCompositeFields component = new ComponentWithCompositeFields(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); configureComponent(component, descriptor, realm); - assertNotNull( component.getThing() ); - - assertEquals( "I am not abstract!", component.getThing().getName() ); + assertNotNull(component.getThing()); + assertEquals("I am not abstract!", component.getThing().getName()); } - public void testInvalidComponentConfiguration() - throws Exception - { + public void testInvalidComponentConfiguration() throws Exception { String xml = "theName"; - try - { - PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + try { + PlexusTools.buildConfiguration("", new StringReader(xml)); - fail( "Should have caused an error because of the invalid XML." ); - } - catch ( PlexusConfigurationException e ) - { + fail("Should have caused an error because of the invalid XML."); + } catch (PlexusConfigurationException e) { // Error should be caught here. + } catch (Exception e) { + fail("Should have caught the invalid plexus configuration exception."); } - catch ( Exception e ) - { - fail( "Should have caught the invalid plexus configuration exception." ); - } - } - public void testComponentConfigurationWithPropertiesFields() - throws Exception - { + public void testComponentConfigurationWithPropertiesFields() throws Exception { String xml = "" + " " + " " + " firstname" - + " michal" + " " + " " - + " lastname" + " maczka" + " " - + " " + ""; + + " michal" + " " + " " + + " lastname" + " maczka" + " " + + " " + ""; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ComponentWithPropertiesField component = new ComponentWithPropertiesField(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); configureComponent(component, descriptor, realm); Properties properties = component.getSomeProperties(); - assertNotNull( properties ); - - assertEquals( "michal", properties.get( "firstname" ) ); + assertNotNull(properties); - assertEquals( "maczka", properties.get( "lastname" ) ); + assertEquals("michal", properties.get("firstname")); + assertEquals("maczka", properties.get("lastname")); } - public void testComponentConfigurationWithPropertiesFieldsWithExpression() - throws Exception - { + public void testComponentConfigurationWithPropertiesFieldsWithExpression() throws Exception { - String xml = "" + " ${injectedProperties} " + ""; + String xml = + "" + " ${injectedProperties} " + ""; final Properties propertiesInterpolated = new Properties(); - propertiesInterpolated.put( "firstname", "olivier" ); - propertiesInterpolated.put( "lastname", "lamy" ); + propertiesInterpolated.put("firstname", "olivier"); + propertiesInterpolated.put("lastname", "lamy"); - ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator() - { - public Object evaluate( String expression ) - { + ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator() { + public Object evaluate(String expression) { return propertiesInterpolated; } - public File alignToBaseDirectory( File file ) - { + public File alignToBaseDirectory(File file) { return null; } }; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ComponentWithPropertiesField component = new ComponentWithPropertiesField(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); configureComponent(component, descriptor, realm, expressionEvaluator); Properties properties = component.getSomeProperties(); - assertNotNull( properties ); + assertNotNull(properties); - assertEquals( "olivier", properties.get( "firstname" ) ); - - assertEquals( "lamy", properties.get( "lastname" ) ); + assertEquals("olivier", properties.get("firstname")); + assertEquals("lamy", properties.get("lastname")); } - public void testComponentConfigurationWithPropertiesFieldsWithExpressions() - throws Exception - { + public void testComponentConfigurationWithPropertiesFieldsWithExpressions() throws Exception { String xml = "" + "" // - + "${theName}${theValue}" // - + "empty" // - + "" + ""; + + "${theName}${theValue}" // + + "empty" // + + "" + ""; final Properties values = new Properties(); - values.put( "${theName}", "test" ); - values.put( "${theValue}", "PASSED" ); - - ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator() - { - public Object evaluate( String expression ) - { - return values.containsKey( expression ) ? values.get( expression ) : expression; + values.put("${theName}", "test"); + values.put("${theValue}", "PASSED"); + + ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator() { + public Object evaluate(String expression) { + return values.containsKey(expression) ? values.get(expression) : expression; } - public File alignToBaseDirectory( File file ) - { + public File alignToBaseDirectory(File file) { return null; } }; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ComponentWithPropertiesField component = new ComponentWithPropertiesField(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); - descriptor.setConfiguration( configuration ); + descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); - configureComponent( component, descriptor, realm, expressionEvaluator ); + configureComponent(component, descriptor, realm, expressionEvaluator); Properties properties = component.getSomeProperties(); - assertNotNull( properties ); + assertNotNull(properties); - assertEquals( "PASSED", properties.get( "test" ) ); - assertEquals( "", properties.get( "empty" ) ); + assertEquals("PASSED", properties.get("test")); + assertEquals("", properties.get("empty")); } - public void testComponentConfigurationWithMapField() - throws Exception - { + public void testComponentConfigurationWithMapField() throws Exception { String xml = "" + " " + " Kenney" - + " Westerhof" + " " + ""; + + " Westerhof" + " " + ""; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ComponentWithMapField component = new ComponentWithMapField(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); configureComponent(component, descriptor, realm); Map map = component.getMap(); - assertNotNull( map ); + assertNotNull(map); - assertEquals( "Kenney", map.get( "firstName" ) ); - - assertEquals( "Westerhof", map.get( "lastName" ) ); + assertEquals("Kenney", map.get("firstName")); + assertEquals("Westerhof", map.get("lastName")); } - public void testComponentConfigurationWhereFieldIsBadArray() - throws Exception - { + public void testComponentConfigurationWhereFieldIsBadArray() throws Exception { String xml = "" // - + " string" // - + ""; + + " string" // + + ""; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ComponentWithArrayFields component = new ComponentWithArrayFields(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); - descriptor.setConfiguration( configuration ); + descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); - try - { - configureComponent( component, descriptor, realm ); - fail( "Configuration did not fail" ); - } - catch ( ComponentConfigurationException e ) - { + try { + configureComponent(component, descriptor, realm); + fail("Configuration did not fail"); + } catch (ComponentConfigurationException e) { } } - public void testComponentConfigurationWhereFieldIsEnum() - throws Exception - { + public void testComponentConfigurationWhereFieldIsEnum() throws Exception { String xml = "" // - + " TYPE" // - + " ONE" // - + ""; + + " TYPE" // + + " ONE" // + + ""; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ComponentWithEnumFields component = new ComponentWithEnumFields(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); - descriptor.setConfiguration( configuration ); + descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); - configureComponent( component, descriptor, realm ); + configureComponent(component, descriptor, realm); - assertEquals( ElementType.TYPE, component.getSimpleEnum() ); + assertEquals(ElementType.TYPE, component.getSimpleEnum()); - assertEquals( ComponentWithEnumFields.NestedEnum.ONE, component.getNestedEnum() ); + assertEquals(ComponentWithEnumFields.NestedEnum.ONE, component.getNestedEnum()); } - public void testComponentConfigurationWithAmbiguousExpressionValue() - throws Exception - { + public void testComponentConfigurationWithAmbiguousExpressionValue() throws Exception { String xml = "" // - + "
    ${address}
    " // - + "
    "; + + "
    ${address}
    " // + + ""; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); DefaultComponent component = new DefaultComponent(); - ExpressionEvaluator expressionEvaluator = new TypeAwareExpressionEvaluator() - { - public Object evaluate( String expression ) - throws ExpressionEvaluationException - { - return evaluate( expression, null ); + ExpressionEvaluator expressionEvaluator = new TypeAwareExpressionEvaluator() { + public Object evaluate(String expression) throws ExpressionEvaluationException { + return evaluate(expression, null); } - public File alignToBaseDirectory( File file ) - { + public File alignToBaseDirectory(File file) { return null; } - public Object evaluate( String expression, Class type ) - throws ExpressionEvaluationException - { - if ( String.class == type ) - { + public Object evaluate(String expression, Class type) throws ExpressionEvaluationException { + if (String.class == type) { return "PASSED"; - } - else - { + } else { return Boolean.FALSE; } } @@ -731,48 +676,40 @@ public Object evaluate( String expression, Class type ) ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); - descriptor.setConfiguration( configuration ); + descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); - configureComponent( component, descriptor, realm, expressionEvaluator ); + configureComponent(component, descriptor, realm, expressionEvaluator); - assertEquals( "PASSED", component.getAddress() ); + assertEquals("PASSED", component.getAddress()); } - public void testComponentConfigurationWithPrimitiveValueConversion() - throws Exception - { + public void testComponentConfigurationWithPrimitiveValueConversion() throws Exception { String xml = "" // - + " ${primitive}" // - + ""; + + " ${primitive}" // + + ""; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ConfigurableComponent component = new ConfigurableComponent(); - ExpressionEvaluator expressionEvaluator = new TypeAwareExpressionEvaluator() - { - public Object evaluate( String expression ) - throws ExpressionEvaluationException - { - return evaluate( expression, null ); + ExpressionEvaluator expressionEvaluator = new TypeAwareExpressionEvaluator() { + public Object evaluate(String expression) throws ExpressionEvaluationException { + return evaluate(expression, null); } - public File alignToBaseDirectory( File file ) - { + public File alignToBaseDirectory(File file) { return null; } - public Object evaluate( String expression, Class type ) - throws ExpressionEvaluationException - { + public Object evaluate(String expression, Class type) throws ExpressionEvaluationException { // java.lang.Short -> short -> int return (short) 23; } @@ -780,147 +717,134 @@ public Object evaluate( String expression, Class type ) ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); - descriptor.setConfiguration( configuration ); + descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); - configureComponent( component, descriptor, realm, expressionEvaluator ); + configureComponent(component, descriptor, realm, expressionEvaluator); - assertEquals( 23, component.getIntValue() ); + assertEquals(23, component.getIntValue()); } - public void testComponentConfigurationWithEmptyContentForBasicField() - throws Exception - { + public void testComponentConfigurationWithEmptyContentForBasicField() throws Exception { String xml = "" // - + "
    " // - + "
    "; + + "
    " // + + ""; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); DefaultComponent component = new DefaultComponent(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); - descriptor.setConfiguration( configuration ); + descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); - configureComponent( component, descriptor, realm ); + configureComponent(component, descriptor, realm); - assertEquals( null, component.getAddress() ); + assertEquals(null, component.getAddress()); } - public void testComponentConfigurationWithEmptyContentForCompositeField() - throws Exception - { + public void testComponentConfigurationWithEmptyContentForCompositeField() throws Exception { String xml = "" // - + " " // - + ""; + + " " // + + ""; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ComponentWithCompositeFields component = new ComponentWithCompositeFields(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); - descriptor.setConfiguration( configuration ); + descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); - configureComponent( component, descriptor, realm ); + configureComponent(component, descriptor, realm); - assertNotNull( component.getBean() ); + assertNotNull(component.getBean()); } public void testComponentConfigurationWithUnresolvedExpressionContentForCompositeFieldOfNonInstantiatableType() - throws Exception - { + throws Exception { String xml = "" // - + " ${null-valued-expression}" // - + ""; + + " ${null-valued-expression}" // + + ""; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ComponentWithCompositeFields component = new ComponentWithCompositeFields(); - ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator() - { - public Object evaluate( String expression ) - throws ExpressionEvaluationException - { + ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator() { + public Object evaluate(String expression) throws ExpressionEvaluationException { return null; } - public File alignToBaseDirectory( File file ) - { + public File alignToBaseDirectory(File file) { return null; } }; ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); - descriptor.setConfiguration( configuration ); + descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); - configureComponent( component, descriptor, realm, expressionEvaluator ); + configureComponent(component, descriptor, realm, expressionEvaluator); - assertEquals( null, component.getThing() ); + assertEquals(null, component.getThing()); } - public void testComponentConfiguratorFileNormalizesSeparator() - throws Exception - { - String xml = "" + - " dir/test.txt" + - " dir\\test.txt" + - ""; + public void testComponentConfiguratorFileNormalizesSeparator() throws Exception { + String xml = "" + " dir/test.txt" + + " dir\\test.txt" + + ""; - PlexusConfiguration configuration = PlexusTools.buildConfiguration( "", new StringReader( xml ) ); + PlexusConfiguration configuration = PlexusTools.buildConfiguration("", new StringReader(xml)); ComponentWithArrayFields component = new ComponentWithArrayFields(); ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setImplementation( component.getClass().getName() ); + descriptor.setImplementation(component.getClass().getName()); descriptor.setConfiguration(configuration); ClassWorld classWorld = new ClassWorld(); - ClassRealm realm = classWorld.newRealm( "test", getClass().getClassLoader() ); + ClassRealm realm = classWorld.newRealm("test", getClass().getClassLoader()); configureComponent(component, descriptor, realm); - assertEquals( new File( "dir", "test.txt" ), component.getFileArray()[0] ); - assertEquals( new File( "dir", "test.txt" ), component.getFileArray()[1] ); + assertEquals(new File("dir", "test.txt"), component.getFileArray()[0]); + assertEquals(new File("dir", "test.txt"), component.getFileArray()[1]); } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/AbstractThing.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/AbstractThing.java index 455a6910b..5e6dbda57 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/AbstractThing.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/AbstractThing.java @@ -24,7 +24,4 @@ * SOFTWARE. */ - -public abstract class AbstractThing -{ -} +public abstract class AbstractThing {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/BasicComponentConfiguratorTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/BasicComponentConfiguratorTest.java index 73576cab1..5e4645027 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/BasicComponentConfiguratorTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/BasicComponentConfiguratorTest.java @@ -24,13 +24,8 @@ * SOFTWARE. */ -public class BasicComponentConfiguratorTest - extends AbstractComponentConfiguratorTest -{ - protected ComponentConfigurator getComponentConfigurator() - throws Exception - { - return new BasicComponentConfigurator(); +public class BasicComponentConfiguratorTest extends AbstractComponentConfiguratorTest { + protected ComponentConfigurator getComponentConfigurator() throws Exception { + return new BasicComponentConfigurator(); } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/Component.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/Component.java index a223e5449..de3edd21a 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/Component.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/Component.java @@ -26,10 +26,8 @@ /** * - * + * * @author Jason van Zyl * */ -public interface Component -{ -} +public interface Component {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithArrayFields.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithArrayFields.java index 4d6197493..f797ce82b 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithArrayFields.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithArrayFields.java @@ -30,8 +30,7 @@ /** * @author Kenney Westerhof */ -public class ComponentWithArrayFields -{ +public class ComponentWithArrayFields { private String[] stringArray; private Integer[] integerArray; @@ -46,38 +45,31 @@ public class ComponentWithArrayFields private File[] fileArray; - public String [] getStringArray() - { + public String[] getStringArray() { return stringArray; } - public Integer [] getIntegerArray() - { + public Integer[] getIntegerArray() { return integerArray; } - public ImportantThing [] getImportantThingArray() - { + public ImportantThing[] getImportantThingArray() { return importantThingArray; } - public Object [] getObjectArray() - { + public Object[] getObjectArray() { return objectArray; } - public AbstractThing [] getAbstractThingArray() - { + public AbstractThing[] getAbstractThingArray() { return abstractArray; } - public URL[] getUrlArray() - { + public URL[] getUrlArray() { return urlArray; } - public File[] getFileArray() - { + public File[] getFileArray() { return fileArray; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithCollectionFields.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithCollectionFields.java index e5c50c06f..9bbb1316f 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithCollectionFields.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithCollectionFields.java @@ -33,8 +33,7 @@ /** * @author Michal Maczka */ -public class ComponentWithCollectionFields -{ +public class ComponentWithCollectionFields { private Vector vector; private HashSet hashSet; @@ -47,33 +46,27 @@ public class ComponentWithCollectionFields private SortedSet sortedSet; - public Vector getVector() - { + public Vector getVector() { return vector; } - public HashSet getHashSet() - { + public HashSet getHashSet() { return hashSet; } - public List getList() - { + public List getList() { return list; } - public List getStringList() - { + public List getStringList() { return stringList; } - public Set getSet() - { + public Set getSet() { return set; } - public SortedSet getSortedSet() - { + public SortedSet getSortedSet() { return sortedSet; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithCompositeFields.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithCompositeFields.java index 0e0347be5..9dcc359ab 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithCompositeFields.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithCompositeFields.java @@ -24,28 +24,21 @@ * SOFTWARE. */ - /** * * @author Michal Maczka * */ -public class ComponentWithCompositeFields -{ +public class ComponentWithCompositeFields { private ThingInterface thing; private DefaultComponent bean; - public ThingInterface getThing() - { + public ThingInterface getThing() { return thing; } - public DefaultComponent getBean() - { + public DefaultComponent getBean() { return bean; } - } - - diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithEnumFields.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithEnumFields.java index 1dc99423a..da964b449 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithEnumFields.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithEnumFields.java @@ -29,28 +29,23 @@ /** * @author Benjamin Bentmann */ -public class ComponentWithEnumFields -{ - - public enum NestedEnum - { - - ONE, TWO, THREE, +public class ComponentWithEnumFields { + public enum NestedEnum { + ONE, + TWO, + THREE, } private NestedEnum nestedEnum; private ElementType simpleEnum; - public NestedEnum getNestedEnum() - { + public NestedEnum getNestedEnum() { return nestedEnum; } - public ElementType getSimpleEnum() - { + public ElementType getSimpleEnum() { return simpleEnum; } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithMapField.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithMapField.java index 37f83a652..2dac3d9d0 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithMapField.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithMapField.java @@ -26,20 +26,15 @@ import java.util.Map; - /** * * @author Michal Maczka * */ -public class ComponentWithMapField -{ +public class ComponentWithMapField { private Map map; - public Map getMap() - { + public Map getMap() { return map; } } - - diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithPropertiesField.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithPropertiesField.java index cc7139ce9..fef0c5b6a 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithPropertiesField.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithPropertiesField.java @@ -26,20 +26,15 @@ import java.util.Properties; - /** * * @author Michal Maczka * */ -public class ComponentWithPropertiesField -{ +public class ComponentWithPropertiesField { private Properties someProperties; - public Properties getSomeProperties() - { + public Properties getSomeProperties() { return someProperties; } } - - diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithSetters.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithSetters.java index cc3b4128a..8387adbd7 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithSetters.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ComponentWithSetters.java @@ -24,19 +24,17 @@ * SOFTWARE. */ +import java.util.List; import org.codehaus.plexus.configuration.PlexusConfiguration; -import java.util.List; - /** * - * + * * @author Jason van Zyl * */ -public class ComponentWithSetters -{ +public class ComponentWithSetters { private int intValueVariable; private float floatValueVariable; private long longValueVariable; @@ -45,38 +43,31 @@ public class ComponentWithSetters private List importantThingsVariable; private PlexusConfiguration configurationVariable; - public int getIntValue() - { + public int getIntValue() { return intValueVariable; } - - public float getFloatValue() - { + + public float getFloatValue() { return floatValueVariable; } - public long getLongValue() - { + public long getLongValue() { return longValueVariable; } - public double getDoubleValue() - { + public double getDoubleValue() { return doubleValueVariable; } - public String getStringValue() - { + public String getStringValue() { return stringValueVariable; } - public List getImportantThings() - { + public List getImportantThings() { return importantThingsVariable; } - public PlexusConfiguration getConfiguration() - { + public PlexusConfiguration getConfiguration() { return configurationVariable; } @@ -92,50 +83,43 @@ public PlexusConfiguration getConfiguration() boolean importantThingsValueSet; boolean configurationValueSet; - public void setIntValue( int intValue ) - { + public void setIntValue(int intValue) { this.intValueVariable = intValue; intValueSet = true; } - public void setFloatValue( float floatValue ) - { + public void setFloatValue(float floatValue) { this.floatValueVariable = floatValue; floatValueSet = true; } - public void setLongValue( long longValue ) - { + public void setLongValue(long longValue) { this.longValueVariable = longValue; longValueSet = true; } - public void setDoubleValue( double doubleValue ) - { + public void setDoubleValue(double doubleValue) { this.doubleValueVariable = doubleValue; doubleValueSet = true; } - public void setStringValue( String stringValue ) - { + public void setStringValue(String stringValue) { this.stringValueVariable = stringValue; stringValueSet = true; } - public void setImportantThings( List importantThings ) - { + public void setImportantThings(List importantThings) { this.importantThingsVariable = importantThings; importantThingsValueSet = true; } - public void setConfiguration( PlexusConfiguration configuration ) - { + public void setConfiguration(PlexusConfiguration configuration) { this.configurationVariable = configuration; configurationValueSet = true; diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ConfigurableComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ConfigurableComponent.java index 6d4b051c3..e98a465fb 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ConfigurableComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ConfigurableComponent.java @@ -24,21 +24,20 @@ * SOFTWARE. */ -import org.codehaus.plexus.configuration.PlexusConfiguration; - import java.io.File; import java.net.URI; import java.net.URL; import java.util.List; +import org.codehaus.plexus.configuration.PlexusConfiguration; + /** * - * + * * @author Jason van Zyl * */ -public class ConfigurableComponent -{ +public class ConfigurableComponent { private boolean booleanValue; private byte byteValue; private short shortValue; @@ -54,73 +53,59 @@ public class ConfigurableComponent private List importantThings; private PlexusConfiguration configuration; - public boolean getBooleanValue() - { + public boolean getBooleanValue() { return booleanValue; } - public int getByteValue() - { + public int getByteValue() { return byteValue; } - public int getShortValue() - { + public int getShortValue() { return shortValue; } - public int getIntValue() - { + public int getIntValue() { return intValue; } - public float getFloatValue() - { + public float getFloatValue() { return floatValue; } - public long getLongValue() - { + public long getLongValue() { return longValue; } - public double getDoubleValue() - { + public double getDoubleValue() { return doubleValue; } - public char getCharValue() - { + public char getCharValue() { return charValue; } - public String getStringValue() - { + public String getStringValue() { return stringValue; } - public File getFileValue() - { + public File getFileValue() { return fileValue; } - public URI getUriValue() - { + public URI getUriValue() { return uriValue; } - public URL getUrlValue() - { + public URL getUrlValue() { return urlValue; } - public List getImportantThings() - { + public List getImportantThings() { return importantThings; } - public PlexusConfiguration getConfiguration() - { + public PlexusConfiguration getConfiguration() { return configuration; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/DefaultComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/DefaultComponent.java index f11bc9be6..2ac3f6a34 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/DefaultComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/DefaultComponent.java @@ -26,17 +26,14 @@ /** * - * + * * @author Jason van Zyl * */ -public class DefaultComponent - extends AbstractComponent -{ +public class DefaultComponent extends AbstractComponent { private String address; - public String getAddress() - { + public String getAddress() { return address; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ImportantThing.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ImportantThing.java index 54b9fe706..8506f56d4 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ImportantThing.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ImportantThing.java @@ -24,19 +24,16 @@ * SOFTWARE. */ - /** * - * + * * @author Jason van Zyl * */ -public class ImportantThing extends AbstractThing implements ThingInterface -{ +public class ImportantThing extends AbstractThing implements ThingInterface { private String name; - public String getName() - { + public String getName() { return name; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ThingInterface.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ThingInterface.java index 2d657b17a..e35a622f6 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ThingInterface.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/ThingInterface.java @@ -24,8 +24,6 @@ * SOFTWARE. */ - -public interface ThingInterface -{ +public interface ThingInterface { String getName(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/XBeanComponentConfiguratorTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/XBeanComponentConfiguratorTest.java index 7f6d6da95..08a52fac3 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/XBeanComponentConfiguratorTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/configurator/XBeanComponentConfiguratorTest.java @@ -1,19 +1,20 @@ package org.codehaus.plexus.component.configurator; -import org.codehaus.plexus.component.repository.ComponentDescriptor; -import org.codehaus.plexus.component.builder.XBeanComponentBuilder; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; -import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.apache.xbean.recipe.ConstructionException; -import org.apache.xbean.recipe.ObjectRecipe; -import org.apache.xbean.recipe.ExecutionContext; import org.apache.xbean.recipe.DefaultExecutionContext; +import org.apache.xbean.recipe.ExecutionContext; +import org.apache.xbean.recipe.ObjectRecipe; +import org.codehaus.plexus.classworlds.realm.ClassRealm; +import org.codehaus.plexus.component.builder.XBeanComponentBuilder; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; +import org.codehaus.plexus.component.repository.ComponentDescriptor; public class XBeanComponentConfiguratorTest extends AbstractComponentConfiguratorTest { @Override - protected void configureComponent(Object component, ComponentDescriptor descriptor, ClassRealm realm) throws Exception { + protected void configureComponent(Object component, ComponentDescriptor descriptor, ClassRealm realm) + throws Exception { XBeanComponentBuilder componentBuilder = new XBeanComponentBuilder(); - ObjectRecipe recipe = componentBuilder.createObjectRecipe( component, descriptor, realm); + ObjectRecipe recipe = componentBuilder.createObjectRecipe(component, descriptor, realm); // need a caller context ExecutionContext executionContext = new DefaultExecutionContext(); @@ -23,23 +24,20 @@ protected void configureComponent(Object component, ComponentDescriptor descript ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(realm); ExecutionContext.setContext(executionContext); - try - { - recipe.setProperties( component ); - } - catch ( ConstructionException e ) - { - throw new ComponentConfigurationException( "Failed to configure component", e ); - } - finally - { + try { + recipe.setProperties(component); + } catch (ConstructionException e) { + throw new ComponentConfigurationException("Failed to configure component", e); + } finally { ExecutionContext.setContext(null); Thread.currentThread().setContextClassLoader(oldClassLoader); } } - protected void configureComponent(Object component, ComponentDescriptor descriptor, ClassRealm realm, ExpressionEvaluator expressionEvaluator) throws Exception { - this.configureComponent(component, descriptor, realm); + protected void configureComponent( + Object component, ComponentDescriptor descriptor, ClassRealm realm, ExpressionEvaluator expressionEvaluator) + throws Exception { + this.configureComponent(component, descriptor, realm); } public void testComponentConfigurationWithPropertiesFieldsWithExpression() throws Exception { @@ -50,21 +48,16 @@ public void testComponentConfigurationWithPropertiesFieldsWithExpressions() thro // expression evalator is not supported since it is not used by normal AutoConfigurePhase } - public void testComponentConfigurationWithAmbiguousExpressionValue() - throws Exception - { + public void testComponentConfigurationWithAmbiguousExpressionValue() throws Exception { // expression evalator is not supported since it is not used by normal AutoConfigurePhase } - public void testComponentConfigurationWithPrimitiveValueConversion() - throws Exception - { + public void testComponentConfigurationWithPrimitiveValueConversion() throws Exception { // expression evalator is not supported since it is not used by normal AutoConfigurePhase } public void testComponentConfigurationWithUnresolvedExpressionContentForCompositeFieldOfNonInstantiatableType() - throws Exception - { + throws Exception { // expression evalator is not supported since it is not used by normal AutoConfigurePhase } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/discovery/ComponentDiscovererTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/discovery/ComponentDiscovererTest.java index 30f802ec4..7f18ad12b 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/discovery/ComponentDiscovererTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/discovery/ComponentDiscovererTest.java @@ -16,6 +16,11 @@ * limitations under the License. */ +import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + import org.codehaus.plexus.PlexusTestCase; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; @@ -23,52 +28,45 @@ import org.codehaus.plexus.component.repository.ComponentSetDescriptor; import org.codehaus.plexus.context.DefaultContext; -import java.io.File; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - /** * @author Jason van Zyl * */ -public class ComponentDiscovererTest - extends PlexusTestCase -{ - public void testDefaultComponentDiscoverer() - throws Exception - { +public class ComponentDiscovererTest extends PlexusTestCase { + public void testDefaultComponentDiscoverer() throws Exception { ComponentDiscoverer componentDiscoverer = new DefaultComponentDiscoverer(); ClassWorld classWorld = new ClassWorld(); - ClassRealm core = classWorld.newRealm( "core" ); + ClassRealm core = classWorld.newRealm("core"); - File testClasses = new File( getBasedir(), "target/test-classes" ); + File testClasses = new File(getBasedir(), "target/test-classes"); - core.addURL( testClasses.toURL() ); + core.addURL(testClasses.toURL()); - File classes = new File( getBasedir(), "target/classes" ); + File classes = new File(getBasedir(), "target/classes"); - core.addURL( classes.toURL() ); + core.addURL(classes.toURL()); - List componentSetDescriptors = componentDiscoverer.findComponents( new DefaultContext(), core ); + List componentSetDescriptors = + componentDiscoverer.findComponents(new DefaultContext(), core); - ComponentDescriptor componentDescriptor = byImplementation(componentSetDescriptors).get( "org.codehaus.plexus.component.discovery.DefaultDiscoveredComponent" ); + ComponentDescriptor componentDescriptor = byImplementation(componentSetDescriptors) + .get("org.codehaus.plexus.component.discovery.DefaultDiscoveredComponent"); - assertNotNull("componentDescriptor is null", componentDescriptor ); + assertNotNull("componentDescriptor is null", componentDescriptor); - assertEquals( "org.codehaus.plexus.component.discovery.DiscoveredComponent", componentDescriptor.getRole() ); + assertEquals("org.codehaus.plexus.component.discovery.DiscoveredComponent", componentDescriptor.getRole()); - assertEquals( "org.codehaus.plexus.component.discovery.DefaultDiscoveredComponent", componentDescriptor.getImplementation() ); + assertEquals( + "org.codehaus.plexus.component.discovery.DefaultDiscoveredComponent", + componentDescriptor.getImplementation()); } private static Map> byImplementation(List descriptorSets) { TreeMap> index = new TreeMap>(); - for ( ComponentSetDescriptor descriptorSet : descriptorSets ) - { - for ( ComponentDescriptor descriptor : descriptorSet.getComponents() ) - { + for (ComponentSetDescriptor descriptorSet : descriptorSets) { + for (ComponentDescriptor descriptor : descriptorSet.getComponents()) { index.put(descriptor.getImplementation(), descriptor); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/discovery/DefaultDiscoveredComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/discovery/DefaultDiscoveredComponent.java index 89ca156dc..d1197a6b9 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/discovery/DefaultDiscoveredComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/discovery/DefaultDiscoveredComponent.java @@ -18,11 +18,8 @@ /** * - * + * * @author Jason van Zyl * */ -public class DefaultDiscoveredComponent - implements DiscoveredComponent -{ -} +public class DefaultDiscoveredComponent implements DiscoveredComponent {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/discovery/DiscoveredComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/discovery/DiscoveredComponent.java index e80f06ad8..0c0580fa1 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/discovery/DiscoveredComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/discovery/DiscoveredComponent.java @@ -18,11 +18,10 @@ /** * - * + * * @author Jason van Zyl * */ -public interface DiscoveredComponent -{ +public interface DiscoveredComponent { String ROLE = DiscoveredComponent.class.getName(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/Component.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/Component.java index f7d68d8d2..b96679973 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/Component.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/Component.java @@ -17,9 +17,7 @@ */ /** - * @author Michal Maczka - * @version $Id$ + * @author Michal Maczka + * @version $Id$ */ -public interface Component -{ -} +public interface Component {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/ComponentImplA.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/ComponentImplA.java index 730c20e22..48686223c 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/ComponentImplA.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/ComponentImplA.java @@ -22,6 +22,4 @@ * @author Jason van Zyl * */ -public class ComponentImplA implements Component -{ -} +public class ComponentImplA implements Component {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/ComponentImplB.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/ComponentImplB.java index aabab3291..49babe9aa 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/ComponentImplB.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/ComponentImplB.java @@ -17,9 +17,7 @@ */ /** - * @author Michal Maczka - * @version $Id$ + * @author Michal Maczka + * @version $Id$ */ -public class ComponentImplB -{ -} +public class ComponentImplB {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/ComponentImplC.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/ComponentImplC.java index b1a61e3c7..5d98f904b 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/ComponentImplC.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/ComponentImplC.java @@ -17,9 +17,7 @@ */ /** - * @author Michal Maczka - * @version $Id$ + * @author Michal Maczka + * @version $Id$ */ -public abstract class ComponentImplC -{ -} +public abstract class ComponentImplC {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/DiscoveredComponentFactoryTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/DiscoveredComponentFactoryTest.java index 95ec7b791..67177a86b 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/DiscoveredComponentFactoryTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/DiscoveredComponentFactoryTest.java @@ -19,49 +19,40 @@ import org.codehaus.plexus.PlexusTestCase; import org.codehaus.plexus.component.repository.ComponentDescriptor; -public class DiscoveredComponentFactoryTest - extends PlexusTestCase -{ - public void testShouldFindComponentFactoriesDefinedInBothPlexusXmlAndComponentsXml() - throws Exception - { - assertNotNull( "Cannot find test component factory from plexus.xml test resource.", - lookup( ComponentFactory.class, "testFactory1" ) ); - - assertNotNull( "Cannot find test component factory from components.xml test resource.", - lookup( ComponentFactory.class, "testFactory2" ) ); +public class DiscoveredComponentFactoryTest extends PlexusTestCase { + public void testShouldFindComponentFactoriesDefinedInBothPlexusXmlAndComponentsXml() throws Exception { + assertNotNull( + "Cannot find test component factory from plexus.xml test resource.", + lookup(ComponentFactory.class, "testFactory1")); + + assertNotNull( + "Cannot find test component factory from components.xml test resource.", + lookup(ComponentFactory.class, "testFactory2")); } - public void testShouldInstantiateComponentUsingFactoryDiscoveredInPlexusXml() - throws Exception - { - } + public void testShouldInstantiateComponentUsingFactoryDiscoveredInPlexusXml() throws Exception {} - public void testShouldInstantiateComponentUsingFactoryDiscoveredInComponentsXml() - throws Exception - { - lookupTestComponent( "testFactory2" ); + public void testShouldInstantiateComponentUsingFactoryDiscoveredInComponentsXml() throws Exception { + lookupTestComponent("testFactory2"); } - private void lookupTestComponent( String factoryId ) - throws Exception - { + private void lookupTestComponent(String factoryId) throws Exception { ComponentDescriptor descriptor = new ComponentDescriptor(); - descriptor.setComponentFactory( factoryId ); + descriptor.setComponentFactory(factoryId); - descriptor.setRole( "role" ); + descriptor.setRole("role"); - descriptor.setRoleHint( "hint" ); + descriptor.setRoleHint("hint"); - descriptor.setImplementation( "something interesting" ); + descriptor.setImplementation("something interesting"); - getContainer().addComponentDescriptor( descriptor ); + getContainer().addComponentDescriptor(descriptor); - Object component = lookup( "role", "hint" ); + Object component = lookup("role", "hint"); - assertTrue( component instanceof TestFactoryResultComponent ); + assertTrue(component instanceof TestFactoryResultComponent); - assertEquals( factoryId, ( (TestFactoryResultComponent) component ).getFactoryId() ); + assertEquals(factoryId, ((TestFactoryResultComponent) component).getFactoryId()); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/TestComponentFactory1.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/TestComponentFactory1.java index b9c0ef3fc..ad120eb98 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/TestComponentFactory1.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/TestComponentFactory1.java @@ -20,19 +20,14 @@ import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.ComponentDescriptor; -public class TestComponentFactory1 - implements ComponentFactory -{ +public class TestComponentFactory1 implements ComponentFactory { - public String getId() - { + public String getId() { return "testFactory1"; } - public Object newInstance( ComponentDescriptor componentDescriptor, ClassRealm classRealm, PlexusContainer container ) - throws ComponentInstantiationException - { + public Object newInstance(ComponentDescriptor componentDescriptor, ClassRealm classRealm, PlexusContainer container) + throws ComponentInstantiationException { return new TestFactoryResultComponent(getId()); } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/TestComponentFactory2.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/TestComponentFactory2.java index e403805b0..052b9a1b5 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/TestComponentFactory2.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/TestComponentFactory2.java @@ -20,19 +20,14 @@ import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.ComponentDescriptor; -public class TestComponentFactory2 - implements ComponentFactory -{ +public class TestComponentFactory2 implements ComponentFactory { - public String getId() - { + public String getId() { return "testFactory2"; } - public Object newInstance( ComponentDescriptor componentDescriptor, ClassRealm classRealm, PlexusContainer container ) - throws ComponentInstantiationException - { + public Object newInstance(ComponentDescriptor componentDescriptor, ClassRealm classRealm, PlexusContainer container) + throws ComponentInstantiationException { return new TestFactoryResultComponent(getId()); } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/TestFactoryResultComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/TestFactoryResultComponent.java index 9d399d257..ae80517d5 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/TestFactoryResultComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/TestFactoryResultComponent.java @@ -16,19 +16,15 @@ * limitations under the License. */ -public class TestFactoryResultComponent -{ +public class TestFactoryResultComponent { private final String factoryId; - public TestFactoryResultComponent( String factoryId ) - { + public TestFactoryResultComponent(String factoryId) { this.factoryId = factoryId; } - public String getFactoryId() - { + public String getFactoryId() { return factoryId; } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/java/JavaComponentFactoryTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/java/JavaComponentFactoryTest.java index c39d94743..80e75a1e4 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/java/JavaComponentFactoryTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/java/JavaComponentFactoryTest.java @@ -33,84 +33,71 @@ * @author Jason van Zyl * @author Michal Maczka */ -public class JavaComponentFactoryTest - extends TestCase -{ - public void testComponentCreation() - throws Exception - { +public class JavaComponentFactoryTest extends TestCase { + public void testComponentCreation() throws Exception { JavaComponentFactory factory = new JavaComponentFactory(); ComponentDescriptor componentDescriptor = new ComponentDescriptor(); - componentDescriptor.setRole( Component.class.getName() ); + componentDescriptor.setRole(Component.class.getName()); - componentDescriptor.setImplementation( ComponentImplA.class.getName() ); + componentDescriptor.setImplementation(ComponentImplA.class.getName()); ClassWorld classWorld = new ClassWorld(); - classWorld.newRealm( "core", Thread.currentThread().getContextClassLoader() ); + classWorld.newRealm("core", Thread.currentThread().getContextClassLoader()); - PlexusContainer container = new DefaultPlexusContainer( containerConfiguration( classWorld )); + PlexusContainer container = new DefaultPlexusContainer(containerConfiguration(classWorld)); - Object component = factory.newInstance( componentDescriptor, classWorld.getRealm( "core" ), container ); + Object component = factory.newInstance(componentDescriptor, classWorld.getRealm("core"), container); - assertNotNull( component ); + assertNotNull(component); } - public void testComponentCreationWithNotMatchingRoleAndImplemenation() - throws Exception - { + public void testComponentCreationWithNotMatchingRoleAndImplemenation() throws Exception { JavaComponentFactory factory = new JavaComponentFactory(); ComponentDescriptor componentDescriptor = new ComponentDescriptor(); - componentDescriptor.setRole( Component.class.getName() ); + componentDescriptor.setRole(Component.class.getName()); - componentDescriptor.setImplementation( ComponentImplB.class.getName() ); + componentDescriptor.setImplementation(ComponentImplB.class.getName()); ClassWorld classWorld = new ClassWorld(); - classWorld.newRealm( "core", Thread.currentThread().getContextClassLoader() ); + classWorld.newRealm("core", Thread.currentThread().getContextClassLoader()); - PlexusContainer container = new DefaultPlexusContainer( containerConfiguration( classWorld )); + PlexusContainer container = new DefaultPlexusContainer(containerConfiguration(classWorld)); - factory.newInstance( componentDescriptor, classWorld.getRealm( "core" ), container ); + factory.newInstance(componentDescriptor, classWorld.getRealm("core"), container); } - public void testInstanciationOfAAbstractComponent() - throws Exception - { + public void testInstanciationOfAAbstractComponent() throws Exception { JavaComponentFactory factory = new JavaComponentFactory(); ComponentDescriptor componentDescriptor = new ComponentDescriptor(); - componentDescriptor.setRole( Component.class.getName() ); + componentDescriptor.setRole(Component.class.getName()); - componentDescriptor.setImplementation( ComponentImplC.class.getName() ); + componentDescriptor.setImplementation(ComponentImplC.class.getName()); ClassWorld classWorld = new ClassWorld(); - classWorld.newRealm( "core", Thread.currentThread().getContextClassLoader() ); + classWorld.newRealm("core", Thread.currentThread().getContextClassLoader()); - PlexusContainer container = new DefaultPlexusContainer( containerConfiguration( classWorld ) ); + PlexusContainer container = new DefaultPlexusContainer(containerConfiguration(classWorld)); - try - { - factory.newInstance( componentDescriptor, classWorld.getRealm( "core" ), container ); + try { + factory.newInstance(componentDescriptor, classWorld.getRealm("core"), container); - fail( "Expected ComponentInstantiationException when instanciating a abstract class." ); - } - catch( ComponentInstantiationException ex ) - { - assertTrue( true ); + fail("Expected ComponentInstantiationException when instanciating a abstract class."); + } catch (ComponentInstantiationException ex) { + assertTrue(true); } } - private ContainerConfiguration containerConfiguration( ClassWorld classWorld ) - { - ContainerConfiguration c = new DefaultContainerConfiguration() - .setClassWorld( classWorld ); + private ContainerConfiguration containerConfiguration(ClassWorld classWorld) { + ContainerConfiguration c = new DefaultContainerConfiguration().setClassWorld(classWorld); return c; } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/nonjava/NonJavaComponentFactory.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/nonjava/NonJavaComponentFactory.java index e9d236d11..5b68cbf60 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/nonjava/NonJavaComponentFactory.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/nonjava/NonJavaComponentFactory.java @@ -1,25 +1,19 @@ package org.codehaus.plexus.component.factory.nonjava; +import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.factory.ComponentFactory; import org.codehaus.plexus.component.factory.ComponentInstantiationException; import org.codehaus.plexus.component.repository.ComponentDescriptor; -import org.codehaus.plexus.classworlds.realm.ClassRealm; -import org.codehaus.plexus.PlexusContainer; /** @author Jason van Zyl */ -public class NonJavaComponentFactory - implements ComponentFactory -{ - public String getId() - { +public class NonJavaComponentFactory implements ComponentFactory { + public String getId() { return "nonjava"; } - public Object newInstance( ComponentDescriptor componentDescriptor, - ClassRealm classRealm, - PlexusContainer container ) - throws ComponentInstantiationException - { + public Object newInstance(ComponentDescriptor componentDescriptor, ClassRealm classRealm, PlexusContainer container) + throws ComponentInstantiationException { return "component"; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/nonjava/NonJavaComponentFactoryTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/nonjava/NonJavaComponentFactoryTest.java index 9cb933416..37d533a81 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/nonjava/NonJavaComponentFactoryTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/factory/nonjava/NonJavaComponentFactoryTest.java @@ -4,14 +4,10 @@ import org.codehaus.plexus.component.factory.ComponentFactory; /** @author Jason van Zyl */ -public class NonJavaComponentFactoryTest - extends PlexusTestCase -{ - public void testNonJavaComponentFactory() - throws Exception - { - ComponentFactory factory = lookup( ComponentFactory.class, "nonjava" ); +public class NonJavaComponentFactoryTest extends PlexusTestCase { + public void testNonJavaComponentFactory() throws Exception { + ComponentFactory factory = lookup(ComponentFactory.class, "nonjava"); - assertNotNull( factory ); + assertNotNull(factory); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/ClassicSingletonComponentManagerTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/ClassicSingletonComponentManagerTest.java index 0f4810214..c22402336 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/ClassicSingletonComponentManagerTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/ClassicSingletonComponentManagerTest.java @@ -5,24 +5,20 @@ /** * @author Ben Walding */ -public class ClassicSingletonComponentManagerTest - extends PlexusTestCase -{ - public void testSequentialLookupsReturnTheSameInstance() - throws Exception - { - Component a = lookup( Component.class ); +public class ClassicSingletonComponentManagerTest extends PlexusTestCase { + public void testSequentialLookupsReturnTheSameInstance() throws Exception { + Component a = lookup(Component.class); - Component b = lookup( Component.class ); + Component b = lookup(Component.class); - Component c = lookup( Component.class ); + Component c = lookup(Component.class); - Component d = lookup( Component.class ); + Component d = lookup(Component.class); - assertTrue( a == b ); + assertTrue(a == b); - assertTrue( a == c ); + assertTrue(a == c); - assertTrue( a == d ); + assertTrue(a == d); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/Component.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/Component.java index 183b7ea1f..b63639233 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/Component.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/Component.java @@ -1,7 +1,6 @@ package org.codehaus.plexus.component.manager; /** @author Jason van Zyl */ -public interface Component -{ +public interface Component { String ROLE = Component.class.getName(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/DefaultComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/DefaultComponent.java index c23a39d0b..28b5787b8 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/DefaultComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/DefaultComponent.java @@ -1,7 +1,4 @@ package org.codehaus.plexus.component.manager; /** @author Jason van Zyl */ -public class DefaultComponent - implements Component -{ -} +public class DefaultComponent implements Component {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/SlowComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/SlowComponent.java index 8194299e7..9bb04c1fd 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/SlowComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/SlowComponent.java @@ -25,26 +25,18 @@ * delay - number of milliseconds to sleep during start() * @author Ben Walding */ -public class SlowComponent - implements Startable -{ +public class SlowComponent implements Startable { public static final String ROLE = SlowComponent.class.getName(); /* Number of ms to sleep during start() */ private long delay; - public void start() - { - try - { - Thread.sleep( delay ); - } - catch ( InterruptedException e ) - { + public void start() { + try { + Thread.sleep(delay); + } catch (InterruptedException e) { } } - public void stop() - { - } + public void stop() {} } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/SlowComponentClassicSingletonComponentManagerTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/SlowComponentClassicSingletonComponentManagerTest.java index 72c2f2f8e..b5d8fb3f5 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/SlowComponentClassicSingletonComponentManagerTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/manager/SlowComponentClassicSingletonComponentManagerTest.java @@ -22,99 +22,78 @@ /** * @author Ben Walding */ -public class SlowComponentClassicSingletonComponentManagerTest - extends PlexusTestCase -{ - public void testThreads1() - throws Exception - { - test( 1 ); +public class SlowComponentClassicSingletonComponentManagerTest extends PlexusTestCase { + public void testThreads1() throws Exception { + test(1); } /** * Tests that multiple concurrent threads don't acquire different components. * @throws Exception in case of an error. */ - public void testThreads1000() - throws Exception - { - test( 1000 ); + public void testThreads1000() throws Exception { + test(1000); } - private void test( int count ) - throws Exception - { - ComponentLookupThread components[] = new ComponentLookupThread[ count ]; - //Create them - for ( int i = 0; i < count; i++ ) - { - components[ i ] = new ComponentLookupThread( getContainer() ); + private void test(int count) throws Exception { + ComponentLookupThread components[] = new ComponentLookupThread[count]; + // Create them + for (int i = 0; i < count; i++) { + components[i] = new ComponentLookupThread(getContainer()); } - //Start them - for ( int i = 0; i < count; i++ ) - { + // Start them + for (int i = 0; i < count; i++) { components[i].start(); } - //Wait for them to finish - for ( int i = 0; i < count; i++ ) - { - components[i].join( 10000 ); + // Wait for them to finish + for (int i = 0; i < count; i++) { + components[i].join(10000); } - //Get master component - SlowComponent masterComponent = lookup( SlowComponent.class ); + // Get master component + SlowComponent masterComponent = lookup(SlowComponent.class); - //Verify them - for ( int i = 0; i < count; i++ ) - { - assertSame( i + ":" + components[i].getComponent() + " == " + masterComponent, - masterComponent, - components[i].getComponent() ); + // Verify them + for (int i = 0; i < count; i++) { + assertSame( + i + ":" + components[i].getComponent() + " == " + masterComponent, + masterComponent, + components[i].getComponent()); } } - class ComponentLookupThread - extends Thread - { + class ComponentLookupThread extends Thread { final PlexusContainer container; private SlowComponent component; - public ComponentLookupThread( PlexusContainer container ) - { + public ComponentLookupThread(PlexusContainer container) { /* * NOTE: A high priority seems to increase the likelihood of exhibiting missing synchronization. */ - setPriority( MAX_PRIORITY ); + setPriority(MAX_PRIORITY); this.container = container; } - public void run() - { - try - { -// DefaultPlexusContainer.setLookupRealm( lookupRealm ); - SlowComponent tmpComponent = container.lookup( SlowComponent.class ); + public void run() { + try { + // DefaultPlexusContainer.setLookupRealm( lookupRealm ); + SlowComponent tmpComponent = container.lookup(SlowComponent.class); - synchronized ( this ) - { + synchronized (this) { this.component = tmpComponent; } - } - catch ( Exception e ) - { + } catch (Exception e) { container.getLookupRealm().display(); e.printStackTrace(); } } - public SlowComponent getComponent() - { - synchronized ( this ) - { + public SlowComponent getComponent() { + synchronized (this) { return component; } } - } + } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/registry/DefaultComponentRegistryTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/registry/DefaultComponentRegistryTest.java index d978a41e6..5821ba8ee 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/registry/DefaultComponentRegistryTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/registry/DefaultComponentRegistryTest.java @@ -1,59 +1,47 @@ package org.codehaus.plexus.component.registry; import junit.framework.TestCase; - import org.codehaus.plexus.DefaultPlexusContainer; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -public class DefaultComponentRegistryTest - extends TestCase -{ +public class DefaultComponentRegistryTest extends TestCase { - public void testConcurrentDisposeAndLookup() - throws Exception - { + public void testConcurrentDisposeAndLookup() throws Exception { final PlexusContainer plexus = new DefaultPlexusContainer(); ComponentDescriptor descriptor = new ComponentDescriptor( - TestSynchronizedComponent.class, plexus.getContainerRealm() ); - descriptor.setRole( TestSynchronizedComponent.class.getCanonicalName() ); - descriptor.setImplementation( TestSynchronizedComponent.class.getCanonicalName() ); - plexus.addComponentDescriptor( descriptor ); - - TestSynchronizedComponent component = plexus.lookup( TestSynchronizedComponent.class ); - - class LookupThread extends Thread - { + TestSynchronizedComponent.class, plexus.getContainerRealm()); + descriptor.setRole(TestSynchronizedComponent.class.getCanonicalName()); + descriptor.setImplementation(TestSynchronizedComponent.class.getCanonicalName()); + plexus.addComponentDescriptor(descriptor); + + TestSynchronizedComponent component = plexus.lookup(TestSynchronizedComponent.class); + + class LookupThread extends Thread { private TestSynchronizedComponent component; @Override - public synchronized void run() - { - try - { - this.component = plexus.lookup( TestSynchronizedComponent.class ); - } - catch ( ComponentLookupException e ) - { + public synchronized void run() { + try { + this.component = plexus.lookup(TestSynchronizedComponent.class); + } catch (ComponentLookupException e) { // expected } } - public synchronized TestSynchronizedComponent getComponent() - { + public synchronized TestSynchronizedComponent getComponent() { return component; } } LookupThread lookupThread = new LookupThread(); - component.setLookupThread( lookupThread ); + component.setLookupThread(lookupThread); plexus.dispose(); - assertNull( lookupThread.getComponent() ); + assertNull(lookupThread.getComponent()); } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/registry/TestSynchronizedComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/registry/TestSynchronizedComponent.java index f67aea0f1..84e90e731 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/registry/TestSynchronizedComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/registry/TestSynchronizedComponent.java @@ -4,34 +4,22 @@ import org.codehaus.plexus.personality.plexus.lifecycle.phase.StartingException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StoppingException; -public class TestSynchronizedComponent - implements Startable -{ +public class TestSynchronizedComponent implements Startable { private Thread lookupThread; - public synchronized void start() - throws StartingException - { - } + public synchronized void start() throws StartingException {} - public synchronized void stop() - throws StoppingException - { + public synchronized void stop() throws StoppingException { lookupThread.start(); - try - { + try { lookupThread.join(); - } - catch ( InterruptedException e ) - { - throw new StoppingException( "Can't stop lookupThread", e ); + } catch (InterruptedException e) { + throw new StoppingException("Can't stop lookupThread", e); } } - public synchronized void setLookupThread( Thread lookupThread ) - { + public synchronized void setLookupThread(Thread lookupThread) { this.lookupThread = lookupThread; } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/ComponentDescriptorTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/ComponentDescriptorTest.java index b69ec992e..8e06ea351 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/ComponentDescriptorTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/ComponentDescriptorTest.java @@ -16,12 +16,12 @@ * limitations under the License. */ +import java.util.List; + import junit.framework.TestCase; -import org.codehaus.plexus.component.repository.io.PlexusTools; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; - -import java.util.List; +import org.codehaus.plexus.component.repository.io.PlexusTools; /** * @@ -29,75 +29,63 @@ * @author Jason van Zyl * */ -public class ComponentDescriptorTest - extends TestCase -{ - public void testSimpleComponentResolution() - throws Exception - { - String cc1 = - "" + - " java.lang.String" + - " c1" + - " role-hint" + - " component-profile" + - " " + - " " + - " c2" + - " " + - " " + - " c3" + - " " + - " " + - ""; - - ClassWorld classWorld = new ClassWorld( "test", Thread.currentThread().getContextClassLoader() ); - ClassRealm realm = classWorld.getRealm( "test" ); - - ComponentDescriptor c1 = PlexusTools.buildComponentDescriptor( cc1, realm ); - - assertEquals( "c1", c1.getRole() ); - - assertEquals( "role-hint", c1.getRoleHint() ); - - assertEquals( "component-profile", c1.getComponentProfile() ); +public class ComponentDescriptorTest extends TestCase { + public void testSimpleComponentResolution() throws Exception { + String cc1 = "" + " java.lang.String" + + " c1" + + " role-hint" + + " component-profile" + + " " + + " " + + " c2" + + " " + + " " + + " c3" + + " " + + " " + + ""; + + ClassWorld classWorld = new ClassWorld("test", Thread.currentThread().getContextClassLoader()); + ClassRealm realm = classWorld.getRealm("test"); + + ComponentDescriptor c1 = PlexusTools.buildComponentDescriptor(cc1, realm); + + assertEquals("c1", c1.getRole()); + + assertEquals("role-hint", c1.getRoleHint()); + + assertEquals("component-profile", c1.getComponentProfile()); List requirements = c1.getRequirements(); - assertEquals( 2, requirements.size() ); + assertEquals(2, requirements.size()); boolean containsC2 = false; boolean containsC3 = false; - for ( ComponentRequirement requirement : requirements ) - { - if ( requirement.getRole().equals( "c2" ) ) - { + for (ComponentRequirement requirement : requirements) { + if (requirement.getRole().equals("c2")) { containsC2 = true; - } - else if ( requirement.getRole().equals( "c3" ) ) - { + } else if (requirement.getRole().equals("c3")) { containsC3 = true; } - } - assertTrue( containsC2 ); + assertTrue(containsC2); - assertTrue( containsC3 ); + assertTrue(containsC3); } - - public void testShouldNotBeEqualWhenRolesAreSameButHintsAreDifferent() - { + + public void testShouldNotBeEqualWhenRolesAreSameButHintsAreDifferent() { ComponentDescriptor desc = new ComponentDescriptor(); desc.setRole("one"); desc.setRoleHint("one"); - + ComponentDescriptor desc2 = new ComponentDescriptor(); desc2.setRole("one"); desc2.setRoleHint("two"); - + assertFalse(desc.equals(desc2)); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/ComponentRequirementTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/ComponentRequirementTest.java index 9c8f691ff..95a10a8f3 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/ComponentRequirementTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/ComponentRequirementTest.java @@ -21,16 +21,13 @@ /** * @author Michal Maczka */ -public class ComponentRequirementTest - extends TestCase -{ - public void testComponentRequirement() - { +public class ComponentRequirementTest extends TestCase { + public void testComponentRequirement() { ComponentRequirement requirement = new ComponentRequirement(); - requirement.setFieldName( "field" ); - requirement.setRole( "role" ); + requirement.setFieldName("field"); + requirement.setRole("role"); - assertEquals( "field", requirement.getFieldName() ); - assertEquals( "role", requirement.getRole() ); + assertEquals("field", requirement.getFieldName()); + assertEquals("role", requirement.getRole()); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/ComponentSetTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/ComponentSetTest.java index 7f3d89767..9ac15cb30 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/ComponentSetTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/ComponentSetTest.java @@ -16,12 +16,12 @@ * limitations under the License. */ +import java.util.List; + import junit.framework.TestCase; -import org.codehaus.plexus.component.repository.io.PlexusTools; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; - -import java.util.List; +import org.codehaus.plexus.component.repository.io.PlexusTools; /** * @@ -29,83 +29,72 @@ * @author Jason van Zyl * */ -public class ComponentSetTest - extends TestCase -{ - public void testSimpleComponentResolution() - throws Exception - { - String xml = - "" + - " " + - " " + - " java.lang.String" + - " c1" + - " role-hint" + - " component-profile" + - " " + - " " + - " c2" + - " " + - " " + - " c3" + - " " + - " " + - " " + - " " + - " " + - " " + - " plexus" + - " wedgy" + - " 1.0" + - " " + - " " + - ""; - - ClassWorld classWorld = new ClassWorld( "test", Thread.currentThread().getContextClassLoader() ); - ClassRealm realm = classWorld.getRealm( "test" ); - - ComponentSetDescriptor cs = PlexusTools.buildComponentSet( PlexusTools.buildConfiguration( xml ), realm ); - - ComponentDescriptor c1 = cs.getComponents().get( 0 ); - - assertEquals( "c1", c1.getRole() ); - - assertEquals( "role-hint", c1.getRoleHint() ); - - assertEquals( "component-profile", c1.getComponentProfile() ); +public class ComponentSetTest extends TestCase { + public void testSimpleComponentResolution() throws Exception { + String xml = "" + " " + + " " + + " java.lang.String" + + " c1" + + " role-hint" + + " component-profile" + + " " + + " " + + " c2" + + " " + + " " + + " c3" + + " " + + " " + + " " + + " " + + " " + + " " + + " plexus" + + " wedgy" + + " 1.0" + + " " + + " " + + ""; + + ClassWorld classWorld = new ClassWorld("test", Thread.currentThread().getContextClassLoader()); + ClassRealm realm = classWorld.getRealm("test"); + + ComponentSetDescriptor cs = PlexusTools.buildComponentSet(PlexusTools.buildConfiguration(xml), realm); + + ComponentDescriptor c1 = cs.getComponents().get(0); + + assertEquals("c1", c1.getRole()); + + assertEquals("role-hint", c1.getRoleHint()); + + assertEquals("component-profile", c1.getComponentProfile()); List requirements = c1.getRequirements(); - assertEquals( 2, requirements.size() ); + assertEquals(2, requirements.size()); boolean containsC2 = false; boolean containsC3 = false; - for ( ComponentRequirement requirement : requirements ) - { - if ( requirement.getRole().equals( "c2" ) ) - { + for (ComponentRequirement requirement : requirements) { + if (requirement.getRole().equals("c2")) { containsC2 = true; - } - else if ( requirement.getRole().equals( "c3" ) ) - { + } else if (requirement.getRole().equals("c3")) { containsC3 = true; } - } - assertTrue( containsC2 ); + assertTrue(containsC2); - assertTrue( containsC3 ); + assertTrue(containsC3); - ComponentDependency d1 = cs.getDependencies().get( 0 ); + ComponentDependency d1 = cs.getDependencies().get(0); - assertEquals( "plexus", d1.getGroupId() ); + assertEquals("plexus", d1.getGroupId()); - assertEquals( "wedgy", d1.getArtifactId() ); + assertEquals("wedgy", d1.getArtifactId()); - assertEquals( "1.0", d1.getVersion() ); + assertEquals("1.0", d1.getVersion()); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/DefaultComponentRepositoryTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/DefaultComponentRepositoryTest.java index 0b454ef82..15ccc0548 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/DefaultComponentRepositoryTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/component/repository/DefaultComponentRepositoryTest.java @@ -24,14 +24,8 @@ * @author Jason van Zyl * */ -public class DefaultComponentRepositoryTest - extends TestCase -{ - private static String configuration = - "" + - ""; +public class DefaultComponentRepositoryTest extends TestCase { + private static String configuration = "" + ""; - public void testDefaultComponentRepository() - { - } + public void testDefaultComponentRepository() {} } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/ConfigurationResourceExceptionTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/ConfigurationResourceExceptionTest.java index 80aeb9345..40ff32a65 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/ConfigurationResourceExceptionTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/ConfigurationResourceExceptionTest.java @@ -24,13 +24,10 @@ * @author Jason van Zyl * */ -public class ConfigurationResourceExceptionTest - extends TestCase -{ - public void testException() - { - PlexusConfigurationResourceException e = new PlexusConfigurationResourceException( "bad doggy!" ); +public class ConfigurationResourceExceptionTest extends TestCase { + public void testException() { + PlexusConfigurationResourceException e = new PlexusConfigurationResourceException("bad doggy!"); - assertEquals( "bad doggy!", e.getMessage() ); + assertEquals("bad doggy!", e.getMessage()); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/ConfigurationTestHelper.java b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/ConfigurationTestHelper.java index ccb5eba21..574ebdf3f 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/ConfigurationTestHelper.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/ConfigurationTestHelper.java @@ -16,65 +16,58 @@ * limitations under the License. */ +import java.io.StringReader; + import junit.framework.TestCase; import org.codehaus.plexus.component.repository.io.PlexusTools; -import java.io.StringReader; - /** * @author Jason van Zyl */ -public abstract class ConfigurationTestHelper - extends TestCase -{ - public static PlexusConfiguration getTestConfiguration() - throws Exception - { - return PlexusTools.buildConfiguration( "", new StringReader( ConfigurationTestHelper.getXmlConfiguration() ) ); +public abstract class ConfigurationTestHelper extends TestCase { + public static PlexusConfiguration getTestConfiguration() throws Exception { + return PlexusTools.buildConfiguration( + "", new StringReader(ConfigurationTestHelper.getXmlConfiguration())); } - public static String getXmlConfiguration() - { - return "" + - "" + - "" + - "string" + - "0" + - "not-a-number" + - "true" + - "false" + - "not-a-boolean" + - ""; + public static String getXmlConfiguration() { + return "" + "" + + "" + + "string" + + "0" + + "not-a-number" + + "true" + + "false" + + "not-a-boolean" + + ""; } - public static void testConfiguration( PlexusConfiguration c ) - throws Exception - { + public static void testConfiguration(PlexusConfiguration c) throws Exception { // Exercise all value/attribute retrieval methods. // Values -// TODO: uncomment once maven can test the latest plexus-utils -// assertNull( c.getChild( "singleton" ).getValue( null ) ); + // TODO: uncomment once maven can test the latest plexus-utils + // assertNull( c.getChild( "singleton" ).getValue( null ) ); // String - assertEquals( "string", c.getValue( "string" ) ); + assertEquals("string", c.getValue("string")); - assertEquals( "string", c.getChild( "string" ).getValue() ); + assertEquals("string", c.getChild("string").getValue()); - assertEquals( "string", c.getChild( "ne-string" ).getValue( "string" ) ); + assertEquals("string", c.getChild("ne-string").getValue("string")); - assertNull( c.getChild( "not-existing" ).getValue( null ) ); + assertNull(c.getChild("not-existing").getValue(null)); - assertEquals( "''", "'" + c.getChild( "empty-element" ).getValue() + "'" ); + assertEquals("''", "'" + c.getChild("empty-element").getValue() + "'"); - assertEquals( "", c.getChild( "empty-element" ).getValue( null ) ); + assertEquals("", c.getChild("empty-element").getValue(null)); // Attributes - assertEquals( "string", c.getChild( "string" ).getAttribute( "string" )); + assertEquals("string", c.getChild("string").getAttribute("string")); - assertEquals( "attribute", c.getChild( "singleton" ).getAttribute( "attribute" )); + assertEquals("attribute", c.getChild("singleton").getAttribute("attribute")); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/DefaultPlexusConfigurationTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/DefaultPlexusConfigurationTest.java index ab2fe937e..6db0494d3 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/DefaultPlexusConfigurationTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/DefaultPlexusConfigurationTest.java @@ -21,107 +21,93 @@ /** * @author Ran Tene */ -public final class DefaultPlexusConfigurationTest - extends TestCase -{ +public final class DefaultPlexusConfigurationTest extends TestCase { private DefaultPlexusConfiguration configuration; - public void setUp() - { - configuration = new DefaultPlexusConfiguration( "a" ); + public void setUp() { + configuration = new DefaultPlexusConfiguration("a"); } - public void testWithHelper() - throws Exception - { + public void testWithHelper() throws Exception { PlexusConfiguration c = ConfigurationTestHelper.getTestConfiguration(); - ConfigurationTestHelper.testConfiguration( c ); + ConfigurationTestHelper.testConfiguration(c); } - public void testGetValue() - throws Exception - { + public void testGetValue() throws Exception { String orgValue = "Original String"; - configuration.setValue( orgValue ); - assertEquals( orgValue, configuration.getValue() ); + configuration.setValue(orgValue); + assertEquals(orgValue, configuration.getValue()); } - public void testGetAttribute() - throws Exception - { + public void testGetAttribute() throws Exception { String key = "key"; String value = "original value"; String defaultStr = "default"; - configuration.setAttribute( key, value ); - assertEquals( value, configuration.getAttribute( key, defaultStr ) ); - assertEquals( defaultStr, configuration.getAttribute( "newKey", defaultStr ) ); + configuration.setAttribute(key, value); + assertEquals(value, configuration.getAttribute(key, defaultStr)); + assertEquals(defaultStr, configuration.getAttribute("newKey", defaultStr)); } - public void testGetChild() - throws Exception - { - DefaultPlexusConfiguration child = (DefaultPlexusConfiguration) configuration.getChild( "child" ); + public void testGetChild() throws Exception { + DefaultPlexusConfiguration child = (DefaultPlexusConfiguration) configuration.getChild("child"); - assertNotNull( child ); + assertNotNull(child); - child.setValue( "child value" ); + child.setValue("child value"); - assertEquals( 1, configuration.getChildCount() ); + assertEquals(1, configuration.getChildCount()); - child = (DefaultPlexusConfiguration) configuration.getChild( "child" ); + child = (DefaultPlexusConfiguration) configuration.getChild("child"); - assertNotNull( child ); + assertNotNull(child); - assertEquals( "child value", child.getValue() ); + assertEquals("child value", child.getValue()); - assertEquals( 1, configuration.getChildCount() ); + assertEquals(1, configuration.getChildCount()); } - public void testToString() - throws Exception - { + public void testToString() throws Exception { // TODO: this currently works since getTestConfiguration() invokes PlexusTools.buildConfiguration() // and it returns XmlPlexusConfiguration actually. PlexusConfiguration c = ConfigurationTestHelper.getTestConfiguration(); - assertEquals( "string\n", c.getChild( "string" ).toString() ); + assertEquals( + "string\n", + c.getChild("string").toString()); // TODO: uncomment once maven can test the latest plexus-utils - assertEquals( "\n", c.getChild( "singleton" ).toString() ); + assertEquals( + "\n", + c.getChild("singleton").toString()); } - public void testProgrammaticConfigurationCreation() - throws Exception - { + public void testProgrammaticConfigurationCreation() throws Exception { String viewRoot = "/path/to/viewRoot"; - PlexusConfiguration c = new DefaultPlexusConfiguration( "configuration" ).addChild( "viewRoot", viewRoot ); + PlexusConfiguration c = new DefaultPlexusConfiguration("configuration").addChild("viewRoot", viewRoot); - assertEquals( viewRoot, c.getChild( "viewRoot" ).getValue() ); + assertEquals(viewRoot, c.getChild("viewRoot").getValue()); } - public void testChildOrdering() - throws Exception - { - PlexusConfiguration child0 = new DefaultPlexusConfiguration( "child" ); - PlexusConfiguration child1 = new DefaultPlexusConfiguration( "child" ); - PlexusConfiguration child2 = new DefaultPlexusConfiguration( "special-child" ); - PlexusConfiguration child3 = new DefaultPlexusConfiguration( "child" ); - PlexusConfiguration child4 = new DefaultPlexusConfiguration( "child" ); - - configuration.addChild( child0 ); - configuration.addChild( child1 ); - configuration.addChild( child2 ); - configuration.addChild( child3 ); - configuration.addChild( child4 ); - - assertEquals( 5, configuration.getChildCount() ); - assertSame( child0, configuration.getChild( 0 ) ); - assertSame( child1, configuration.getChild( 1 ) ); - assertSame( child2, configuration.getChild( 2 ) ); - assertSame( child3, configuration.getChild( 3 ) ); - assertSame( child4, configuration.getChild( 4 ) ); + public void testChildOrdering() throws Exception { + PlexusConfiguration child0 = new DefaultPlexusConfiguration("child"); + PlexusConfiguration child1 = new DefaultPlexusConfiguration("child"); + PlexusConfiguration child2 = new DefaultPlexusConfiguration("special-child"); + PlexusConfiguration child3 = new DefaultPlexusConfiguration("child"); + PlexusConfiguration child4 = new DefaultPlexusConfiguration("child"); + + configuration.addChild(child0); + configuration.addChild(child1); + configuration.addChild(child2); + configuration.addChild(child3); + configuration.addChild(child4); + + assertEquals(5, configuration.getChildCount()); + assertSame(child0, configuration.getChild(0)); + assertSame(child1, configuration.getChild(1)); + assertSame(child2, configuration.getChild(2)); + assertSame(child3, configuration.getChild(3)); + assertSame(child4, configuration.getChild(4)); } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationReaderTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationReaderTest.java index f40e1d48f..2d9d02432 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationReaderTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationReaderTest.java @@ -3,23 +3,17 @@ import java.io.StringReader; import junit.framework.TestCase; - import org.codehaus.plexus.configuration.ConfigurationTestHelper; import org.codehaus.plexus.configuration.PlexusConfiguration; -public class XmlPlexusConfigurationReaderTest - extends TestCase -{ - public void testRead() - throws Exception - { - StringReader sr = new StringReader( ConfigurationTestHelper.getXmlConfiguration() ); +public class XmlPlexusConfigurationReaderTest extends TestCase { + public void testRead() throws Exception { + StringReader sr = new StringReader(ConfigurationTestHelper.getXmlConfiguration()); XmlPlexusConfigurationReader reader = new XmlPlexusConfigurationReader(); - PlexusConfiguration c = reader.read( sr ); + PlexusConfiguration c = reader.read(sr); - ConfigurationTestHelper.testConfiguration( c ); + ConfigurationTestHelper.testConfiguration(c); } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationWriterTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationWriterTest.java index 803119904..191b0ad61 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationWriterTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/io/XmlPlexusConfigurationWriterTest.java @@ -4,33 +4,27 @@ import java.io.StringWriter; import junit.framework.TestCase; - import org.codehaus.plexus.configuration.ConfigurationTestHelper; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; -public class XmlPlexusConfigurationWriterTest - extends TestCase -{ +public class XmlPlexusConfigurationWriterTest extends TestCase { - public void testWrite() - throws Exception - { + public void testWrite() throws Exception { PlexusConfiguration c = ConfigurationTestHelper.getTestConfiguration(); XmlPlexusConfigurationWriter cw = new XmlPlexusConfigurationWriter(); StringWriter writer = new StringWriter(); - cw.write( writer, c ); + cw.write(writer, c); - Xpp3Dom dom = Xpp3DomBuilder.build( new StringReader( writer.toString() ) ); + Xpp3Dom dom = Xpp3DomBuilder.build(new StringReader(writer.toString())); - XmlPlexusConfiguration c1 = new XmlPlexusConfiguration( dom ); - - ConfigurationTestHelper.testConfiguration( c1 ); - } + XmlPlexusConfiguration c1 = new XmlPlexusConfiguration(dom); + ConfigurationTestHelper.testConfiguration(c1); + } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/ADummyConfigurationSource.java b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/ADummyConfigurationSource.java index ed64cf47b..6a287b4c5 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/ADummyConfigurationSource.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/ADummyConfigurationSource.java @@ -3,13 +3,9 @@ import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.configuration.PlexusConfiguration; -public class ADummyConfigurationSource - implements ConfigurationSource -{ +public class ADummyConfigurationSource implements ConfigurationSource { - public PlexusConfiguration getConfiguration( ComponentDescriptor componentDescriptor ) - { + public PlexusConfiguration getConfiguration(ComponentDescriptor componentDescriptor) { return null; } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/AnotherDummyConfigurationSource.java b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/AnotherDummyConfigurationSource.java index a17d67b88..1d726be04 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/AnotherDummyConfigurationSource.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/AnotherDummyConfigurationSource.java @@ -3,14 +3,11 @@ import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.configuration.PlexusConfiguration; -public class AnotherDummyConfigurationSource implements ConfigurationSource -{ - +public class AnotherDummyConfigurationSource implements ConfigurationSource { + private ConfigurationSource configurationSource; - public PlexusConfiguration getConfiguration( ComponentDescriptor componentDescriptor ) - { + public PlexusConfiguration getConfiguration(ComponentDescriptor componentDescriptor) { return null; } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/DefaultConfigurationSourceTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/DefaultConfigurationSourceTest.java index 6de8f0146..24432f9dd 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/DefaultConfigurationSourceTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/DefaultConfigurationSourceTest.java @@ -3,21 +3,16 @@ import org.codehaus.plexus.MutablePlexusContainer; import org.codehaus.plexus.PlexusTestCase; -public class DefaultConfigurationSourceTest - extends PlexusTestCase -{ +public class DefaultConfigurationSourceTest extends PlexusTestCase { - public void testBasic() - throws Exception - { + public void testBasic() throws Exception { // we have no plexus.xml, so the container should use the "default" source, // which is ContainerConfigurationSource - ConfigurationSource cs = ( (MutablePlexusContainer) getContainer() ).getConfigurationSource(); + ConfigurationSource cs = ((MutablePlexusContainer) getContainer()).getConfigurationSource(); - assertNotNull( cs ); + assertNotNull(cs); - assertEquals( ContainerConfigurationSource.class.getName(), cs.getClass().getName() ); + assertEquals(ContainerConfigurationSource.class.getName(), cs.getClass().getName()); } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/ExtendingConfigurationSourceTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/ExtendingConfigurationSourceTest.java index 5f902a818..292624c49 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/ExtendingConfigurationSourceTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/ExtendingConfigurationSourceTest.java @@ -3,31 +3,26 @@ import org.codehaus.plexus.MutablePlexusContainer; import org.codehaus.plexus.PlexusTestCase; -public class ExtendingConfigurationSourceTest - extends PlexusTestCase -{ - public void testBasic() - throws Exception - { +public class ExtendingConfigurationSourceTest extends PlexusTestCase { + public void testBasic() throws Exception { // we have plexus.xml with two configSources, so the container should use the "chained" case, // which is ChainedConfigurationSource with 3 elem in list: the plexusDefaultConfig source, // and the two user provided, in this order: ADummyConfigurationSource, AnotherDummyConfigurationSource - ConfigurationSource cs = ( (MutablePlexusContainer) getContainer() ).getConfigurationSource(); + ConfigurationSource cs = ((MutablePlexusContainer) getContainer()).getConfigurationSource(); - assertNotNull( cs ); + assertNotNull(cs); - assertEquals( ChainedConfigurationSource.class.getName(), cs.getClass().getName() ); + assertEquals(ChainedConfigurationSource.class.getName(), cs.getClass().getName()); ChainedConfigurationSource ccs = (ChainedConfigurationSource) cs; // we have 3 config sources overall - assertEquals( 3, ccs.getConfigurationSources().size() ); + assertEquals(3, ccs.getConfigurationSources().size()); // and the last in the source list is container source - assertEquals( ContainerConfigurationSource.class.getName(), ccs - .getConfigurationSources().get( 2 ).getClass().getName() ); - + assertEquals( + ContainerConfigurationSource.class.getName(), + ccs.getConfigurationSources().get(2).getClass().getName()); } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/OverridingConfigurationSourceTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/OverridingConfigurationSourceTest.java index 0506ef728..1b20009dc 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/OverridingConfigurationSourceTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/source/OverridingConfigurationSourceTest.java @@ -3,20 +3,15 @@ import org.codehaus.plexus.MutablePlexusContainer; import org.codehaus.plexus.PlexusTestCase; -public class OverridingConfigurationSourceTest - extends PlexusTestCase -{ - public void testBasic() - throws Exception - { - // we have plexus.xml with configSource that overrides the Plexus default one, so the container +public class OverridingConfigurationSourceTest extends PlexusTestCase { + public void testBasic() throws Exception { + // we have plexus.xml with configSource that overrides the Plexus default one, so the container // should use it instead of the "default" one - ConfigurationSource cs = ( (MutablePlexusContainer) getContainer() ).getConfigurationSource(); + ConfigurationSource cs = ((MutablePlexusContainer) getContainer()).getConfigurationSource(); - assertNotNull( cs ); + assertNotNull(cs); - assertEquals( ADummyConfigurationSource.class.getName(), cs.getClass().getName() ); + assertEquals(ADummyConfigurationSource.class.getName(), cs.getClass().getName()); } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/xml/XmlPlexusConfigurationTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/xml/XmlPlexusConfigurationTest.java index 14341ff74..18b5ab795 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/xml/XmlPlexusConfigurationTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/configuration/xml/XmlPlexusConfigurationTest.java @@ -23,83 +23,68 @@ /** * @author Ran Tene */ -public final class XmlPlexusConfigurationTest - extends TestCase -{ +public final class XmlPlexusConfigurationTest extends TestCase { private XmlPlexusConfiguration configuration; - public void setUp() - { - configuration = new XmlPlexusConfiguration( "a" ); + public void setUp() { + configuration = new XmlPlexusConfiguration("a"); } - public void testWithHelper() - throws Exception - { + public void testWithHelper() throws Exception { PlexusConfiguration c = ConfigurationTestHelper.getTestConfiguration(); - ConfigurationTestHelper.testConfiguration( c ); + ConfigurationTestHelper.testConfiguration(c); } - public void testGetValue() - throws Exception - { + public void testGetValue() throws Exception { String orgValue = "Original String"; - configuration.setValue( orgValue ); - assertEquals( orgValue, configuration.getValue() ); + configuration.setValue(orgValue); + assertEquals(orgValue, configuration.getValue()); } - public void testGetAttribute() - throws Exception - { + public void testGetAttribute() throws Exception { String key = "key"; String value = "original value"; String defaultStr = "default"; - configuration.setAttribute( key, value ); - assertEquals( value, configuration.getAttribute( key, defaultStr ) ); - assertEquals( defaultStr, configuration.getAttribute( "newKey", defaultStr ) ); + configuration.setAttribute(key, value); + assertEquals(value, configuration.getAttribute(key, defaultStr)); + assertEquals(defaultStr, configuration.getAttribute("newKey", defaultStr)); } - public void testGetChild() - throws Exception - { - PlexusConfiguration child = (XmlPlexusConfiguration) configuration.getChild( "child" ); + public void testGetChild() throws Exception { + PlexusConfiguration child = (XmlPlexusConfiguration) configuration.getChild("child"); - assertNotNull( child ); + assertNotNull(child); - child.setValue( "child value" ); + child.setValue("child value"); - assertEquals( 1, configuration.getChildCount() ); + assertEquals(1, configuration.getChildCount()); - child = (XmlPlexusConfiguration) configuration.getChild( "child" ); + child = (XmlPlexusConfiguration) configuration.getChild("child"); - assertNotNull( child ); + assertNotNull(child); - assertEquals( "child value", child.getValue() ); + assertEquals("child value", child.getValue()); - assertEquals( 1, configuration.getChildCount() ); + assertEquals(1, configuration.getChildCount()); } - public void testToString() - throws Exception - { + public void testToString() throws Exception { PlexusConfiguration c = ConfigurationTestHelper.getTestConfiguration(); - assertEquals( "string\n", c.getChild( "string" ).toString() ); + assertEquals( + "string\n", + c.getChild("string").toString()); -// TODO: uncomment once maven can test the latest plexus-utils -// assertEquals( "\n", c.getChild( "singleton" ).toString() ); + // TODO: uncomment once maven can test the latest plexus-utils + // assertEquals( "\n", c.getChild( "singleton" ).toString() ); } - public void testProgrammaticConfigurationCreation() - throws Exception - { + public void testProgrammaticConfigurationCreation() throws Exception { String viewRoot = "/path/to/viewRoot"; - - PlexusConfiguration c = new XmlPlexusConfiguration( "configuration" ) - .addChild( "viewRoot", viewRoot ); - assertEquals( viewRoot, c.getChild( "viewRoot" ).getValue() ); + PlexusConfiguration c = new XmlPlexusConfiguration("configuration").addChild("viewRoot", viewRoot); + + assertEquals(viewRoot, c.getChild("viewRoot").getValue()); } } - diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/context/ContextMapAdapterTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/context/ContextMapAdapterTest.java index e776ed724..a404dd108 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/context/ContextMapAdapterTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/context/ContextMapAdapterTest.java @@ -16,60 +16,53 @@ * limitations under the License. */ +import java.io.StringReader; +import java.io.StringWriter; + import junit.framework.TestCase; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.InterpolationFilterReader; -import java.io.StringReader; -import java.io.StringWriter; - /** * Generated by JUnitDoclet, a tool provided by ObjectFab GmbH under LGPL. * Please see www.junitdoclet.org, www.gnu.org and www.objectfab.de for * informations about the tool, the licence and the authors. */ -public class ContextMapAdapterTest - extends TestCase -{ - public ContextMapAdapterTest( String name ) - { - super( name ); +public class ContextMapAdapterTest extends TestCase { + public ContextMapAdapterTest(String name) { + super(name); } - public void testInterpolation() - throws Exception - { + public void testInterpolation() throws Exception { DefaultContext context = new DefaultContext(); - context.put( "name", "jason" ); + context.put("name", "jason"); - context.put( "occupation", "exotic dancer" ); + context.put("occupation", "exotic dancer"); - ContextMapAdapter adapter = new ContextMapAdapter( context ); + ContextMapAdapter adapter = new ContextMapAdapter(context); - assertEquals( "jason", (String) adapter.get( "name" ) ); + assertEquals("jason", (String) adapter.get("name")); - assertEquals( "exotic dancer", (String) adapter.get( "occupation" ) ); + assertEquals("exotic dancer", (String) adapter.get("occupation")); - assertNull( adapter.get( "foo" ) ); + assertNull(adapter.get("foo")); } - public void testInterpolationWithContext() - throws Exception - { + public void testInterpolationWithContext() throws Exception { DefaultContext context = new DefaultContext(); - context.put( "name", "jason" ); - context.put( "noun", "asshole" ); + context.put("name", "jason"); + context.put("noun", "asshole"); String foo = "${name} is an ${noun}. ${not.interpolated}"; InterpolationFilterReader reader = - new InterpolationFilterReader( new StringReader( foo ), new ContextMapAdapter( context ) ); + new InterpolationFilterReader(new StringReader(foo), new ContextMapAdapter(context)); StringWriter writer = new StringWriter(); - IOUtil.copy( reader, writer ); + IOUtil.copy(reader, writer); String bar = writer.toString(); - assertEquals( "jason is an asshole. ${not.interpolated}", bar ); + assertEquals("jason is an asshole. ${not.interpolated}", bar); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/context/DefaultContextTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/context/DefaultContextTest.java index 83b49f953..bd55956f2 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/context/DefaultContextTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/context/DefaultContextTest.java @@ -16,118 +16,95 @@ * limitations under the License. */ -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - import java.util.HashMap; import java.util.Map; +import junit.framework.AssertionFailedError; +import junit.framework.TestCase; + /** * TestCase for Context. * * @author Berin Loritsch * @author Leo Sutic */ -public class DefaultContextTest - extends TestCase -{ +public class DefaultContextTest extends TestCase { - public DefaultContextTest( String name ) - { - super( name ); + public DefaultContextTest(String name) { + super(name); } - public void testContextCreationWithMap() - throws Exception - { + public void testContextCreationWithMap() throws Exception { Map map = new HashMap(); - map.put( "name", "jason" ); + map.put("name", "jason"); - DefaultContext context = new DefaultContext( map ); + DefaultContext context = new DefaultContext(map); - assertEquals( "jason", (String) context.get( "name" ) ); + assertEquals("jason", (String) context.get("name")); - assertEquals( map, context.getContextData() ); + assertEquals(map, context.getContextData()); // Test removal - context.put( "name", null ); + context.put("name", null); // There is no data and no parent containerContext. - try - { - context.get( "name" ); - } - catch ( ContextException e ) - { + try { + context.get("name"); + } catch (ContextException e) { // do nothing } - - } - public void testAddContext() - throws Exception - { + public void testAddContext() throws Exception { 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"); + assertTrue("value1".equals(context.get("key1"))); + context.put("key1", ""); + assertTrue("".equals(context.get("key1"))); - context.put( "key1", "value1" ); + 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" ) ) ); + 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 testHiddenItems() - throws ContextException - { + public void testHiddenItems() throws ContextException { // initalize DefaultContext context = new DefaultContext(); - context.put( "test", "test" ); + context.put("test", "test"); // verify inital state - assertTrue( "test".equals( context.get( "test" ) ) ); + assertTrue("test".equals(context.get("test"))); // hide value and verify - context.hide( "test" ); - try - { - context.get( "test" ); - fail( "The item \"test\" was hidden in the child containerContext, but could still be retrieved via get()." ); - } - catch ( ContextException ce ) - { - assertTrue( true ); + context.hide("test"); + try { + context.get("test"); + fail("The item \"test\" was hidden in the child containerContext, but could still be retrieved via get()."); + } catch (ContextException ce) { + assertTrue(true); } // reset to inital state and verify - context.put( "test", "test" ); - assertTrue( "test".equals( context.get( "test" ) ) ); + context.put("test", "test"); + assertTrue("test".equals(context.get("test"))); // mark context read-only and verify that item can not be hidden context.makeReadOnly(); - try - { - context.hide( "test" ); - fail( "hide() did not throw an exception, even though the containerContext is supposed to be read-only." ); - } - catch ( IllegalStateException ise ) - { - assertTrue( true ); + try { + context.hide("test"); + fail("hide() did not throw an exception, even though the containerContext is supposed to be read-only."); + } catch (IllegalStateException ise) { + assertTrue(true); } // verify state did not change in failed hide() invocation - assertTrue( "test".equals( context.get( "test" ) ) ); + assertTrue("test".equals(context.get("test"))); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/AbstractLoggerManagerTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/AbstractLoggerManagerTest.java index f92a500c6..21ab211b5 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/AbstractLoggerManagerTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/AbstractLoggerManagerTest.java @@ -26,213 +26,188 @@ * @author Trygve Laugstøl * @version $Revision$ */ -public abstract class AbstractLoggerManagerTest - extends PlexusTestCase -{ - protected abstract LoggerManager createLoggerManager() - throws Exception; - - public void testSetThreshold() - throws Exception - { +public abstract class AbstractLoggerManagerTest extends PlexusTestCase { + protected abstract LoggerManager createLoggerManager() throws Exception; + + public void testSetThreshold() throws Exception { LoggerManager manager; Logger logger1, logger2; manager = createLoggerManager(); - manager.setThreshold( Logger.LEVEL_FATAL ); - logger1 = manager.getLoggerForComponent( "role1", "roleHint1" ); - assertEquals( Logger.LEVEL_FATAL, logger1.getThreshold() ); + manager.setThreshold(Logger.LEVEL_FATAL); + logger1 = manager.getLoggerForComponent("role1", "roleHint1"); + assertEquals(Logger.LEVEL_FATAL, logger1.getThreshold()); - manager.setThreshold( Logger.LEVEL_DEBUG ); - logger2 = manager.getLoggerForComponent( "role2", "roleHint2" ); - assertEquals( Logger.LEVEL_FATAL, logger1.getThreshold() ); - assertEquals( Logger.LEVEL_DEBUG, logger2.getThreshold() ); + manager.setThreshold(Logger.LEVEL_DEBUG); + logger2 = manager.getLoggerForComponent("role2", "roleHint2"); + assertEquals(Logger.LEVEL_FATAL, logger1.getThreshold()); + assertEquals(Logger.LEVEL_DEBUG, logger2.getThreshold()); } /** * There is only one logger instance pr component even if looked up more that once. * @throws Exception in case of an error. */ - public void testActiveLoggerCount() - throws Exception - { + public void testActiveLoggerCount() throws Exception { LoggerManager manager; Logger b, c1_1, c1_2, c2; - manager = getManager( Logger.LEVEL_FATAL ); + manager = getManager(Logger.LEVEL_FATAL); assertEquals(0, manager.getActiveLoggerCount()); - b = manager.getLoggerForComponent( "b" ); - assertNotNull( b ); + b = manager.getLoggerForComponent("b"); + assertNotNull(b); assertEquals(1, manager.getActiveLoggerCount()); - c1_1 = manager.getLoggerForComponent( "c", "1" ); - c1_2 = manager.getLoggerForComponent( "c", "1" ); - assertNotNull( c1_1 ); - assertNotNull( c1_2 ); - assertSame( c1_1, c1_2 ); + c1_1 = manager.getLoggerForComponent("c", "1"); + c1_2 = manager.getLoggerForComponent("c", "1"); + assertNotNull(c1_1); + assertNotNull(c1_2); + assertSame(c1_1, c1_2); assertEquals(2, manager.getActiveLoggerCount()); - c2 = manager.getLoggerForComponent( "c", "2" ); - assertNotNull( c2 ); + c2 = manager.getLoggerForComponent("c", "2"); + assertNotNull(c2); assertEquals(3, manager.getActiveLoggerCount()); - manager.returnComponentLogger( "c", "1" ); + manager.returnComponentLogger("c", "1"); assertEquals(2, manager.getActiveLoggerCount()); - manager.returnComponentLogger( "c", "2" ); - manager.returnComponentLogger( "c", "2" ); - manager.returnComponentLogger( "c", "1" ); + manager.returnComponentLogger("c", "2"); + manager.returnComponentLogger("c", "2"); + manager.returnComponentLogger("c", "1"); assertEquals(1, manager.getActiveLoggerCount()); - manager.returnComponentLogger( "b" ); + manager.returnComponentLogger("b"); assertEquals(0, manager.getActiveLoggerCount()); } - public void testDebugLevelConfiguration() - throws Exception - { - LoggerManager manager = getManager( Logger.LEVEL_DEBUG ); + public void testDebugLevelConfiguration() throws Exception { + LoggerManager manager = getManager(Logger.LEVEL_DEBUG); - Logger logger = extractLogger( manager ); + Logger logger = extractLogger(manager); - checkDebugLevel( logger ); + checkDebugLevel(logger); - logger = extractLogger( manager ); + logger = extractLogger(manager); - checkDebugLevel( logger ); + checkDebugLevel(logger); } - public void testInfoLevelConfiguration() - throws Exception - { - LoggerManager manager = getManager( Logger.LEVEL_INFO ); + public void testInfoLevelConfiguration() throws Exception { + LoggerManager manager = getManager(Logger.LEVEL_INFO); - Logger logger = extractLogger( manager ); + Logger logger = extractLogger(manager); - checkInfoLevel( logger ); + checkInfoLevel(logger); - logger = extractLogger( manager ); + logger = extractLogger(manager); - checkInfoLevel( logger ); + checkInfoLevel(logger); } - public void testWarnLevelConfiguration() - throws Exception - { - LoggerManager manager = getManager( Logger.LEVEL_WARN ); + public void testWarnLevelConfiguration() throws Exception { + LoggerManager manager = getManager(Logger.LEVEL_WARN); - Logger logger = extractLogger( manager ); + Logger logger = extractLogger(manager); - checkWarnLevel( logger ); + checkWarnLevel(logger); - logger = extractLogger( manager ); + logger = extractLogger(manager); - checkWarnLevel( logger ); + checkWarnLevel(logger); } - public void testErrorLevelConfiguration() - throws Exception - { - LoggerManager manager = getManager( Logger.LEVEL_ERROR ); + public void testErrorLevelConfiguration() throws Exception { + LoggerManager manager = getManager(Logger.LEVEL_ERROR); - Logger logger = extractLogger( manager ); + Logger logger = extractLogger(manager); - checkErrorLevel( logger ); + checkErrorLevel(logger); - logger = extractLogger( manager ); + logger = extractLogger(manager); - checkErrorLevel( logger ); + checkErrorLevel(logger); } - public void testFatalLevelConfiguration() - throws Exception - { - LoggerManager manager = getManager( Logger.LEVEL_FATAL ); + public void testFatalLevelConfiguration() throws Exception { + LoggerManager manager = getManager(Logger.LEVEL_FATAL); - Logger logger = extractLogger( manager ); + Logger logger = extractLogger(manager); - checkFatalLevel( logger ); + checkFatalLevel(logger); - logger = extractLogger( manager ); + logger = extractLogger(manager); - checkFatalLevel( logger ); + checkFatalLevel(logger); } - private LoggerManager getManager( int threshold ) - throws Exception - { + private LoggerManager getManager(int threshold) throws Exception { LoggerManager manager = createLoggerManager(); - manager.setThreshold( threshold ); + manager.setThreshold(threshold); - assertNotNull( manager ); + assertNotNull(manager); return manager; } -/* - private Logger extractRootLogger( LoggerManager manager ) - { - Logger logger = manager.getRootLogger(); + /* + private Logger extractRootLogger( LoggerManager manager ) + { + Logger logger = manager.getRootLogger(); - assertNotNull( logger ); + assertNotNull( logger ); - return logger; - } -*/ - private Logger extractLogger( LoggerManager manager ) - { - Logger logger = manager.getLoggerForComponent( "foo" ); + return logger; + } + */ + private Logger extractLogger(LoggerManager manager) { + Logger logger = manager.getLoggerForComponent("foo"); - assertNotNull( logger ); - assertEquals( "foo", logger.getName() ); + assertNotNull(logger); + assertEquals("foo", logger.getName()); return logger; } - private void checkDebugLevel( Logger logger ) - { - assertTrue( "debug enabled", logger.isDebugEnabled() ); - assertTrue( "info enabled", logger.isInfoEnabled() ); - assertTrue( "warn enabled", logger.isWarnEnabled() ); - assertTrue( "error enabled", logger.isErrorEnabled() ); - assertTrue( "fatal enabled", logger.isFatalErrorEnabled() ); + private void checkDebugLevel(Logger logger) { + assertTrue("debug enabled", logger.isDebugEnabled()); + assertTrue("info enabled", logger.isInfoEnabled()); + assertTrue("warn enabled", logger.isWarnEnabled()); + assertTrue("error enabled", logger.isErrorEnabled()); + assertTrue("fatal enabled", logger.isFatalErrorEnabled()); } - private void checkInfoLevel( Logger logger ) - { - assertFalse( "debug disabled", logger.isDebugEnabled() ); - assertTrue( "info enabled", logger.isInfoEnabled() ); - assertTrue( "warn enabled", logger.isWarnEnabled() ); - assertTrue( "error enabled", logger.isErrorEnabled() ); - assertTrue( "fatal enabled", logger.isFatalErrorEnabled() ); + private void checkInfoLevel(Logger logger) { + assertFalse("debug disabled", logger.isDebugEnabled()); + assertTrue("info enabled", logger.isInfoEnabled()); + assertTrue("warn enabled", logger.isWarnEnabled()); + assertTrue("error enabled", logger.isErrorEnabled()); + assertTrue("fatal enabled", logger.isFatalErrorEnabled()); } - private void checkWarnLevel( Logger logger ) - { - assertFalse( "debug disabled", logger.isDebugEnabled() ); - assertFalse( "info disabled", logger.isInfoEnabled() ); - assertTrue( "warn enabled", logger.isWarnEnabled() ); - assertTrue( "error enabled", logger.isErrorEnabled() ); - assertTrue( "fatal enabled", logger.isFatalErrorEnabled() ); + private void checkWarnLevel(Logger logger) { + assertFalse("debug disabled", logger.isDebugEnabled()); + assertFalse("info disabled", logger.isInfoEnabled()); + assertTrue("warn enabled", logger.isWarnEnabled()); + assertTrue("error enabled", logger.isErrorEnabled()); + assertTrue("fatal enabled", logger.isFatalErrorEnabled()); } - private void checkErrorLevel( Logger logger ) - { - assertFalse( "debug disabled", logger.isDebugEnabled() ); - assertFalse( "info disabled", logger.isInfoEnabled() ); - assertFalse( "warn disabled", logger.isWarnEnabled() ); - assertTrue( "error enabled", logger.isErrorEnabled() ); - assertTrue( "fatal enabled", logger.isFatalErrorEnabled() ); + private void checkErrorLevel(Logger logger) { + assertFalse("debug disabled", logger.isDebugEnabled()); + assertFalse("info disabled", logger.isInfoEnabled()); + assertFalse("warn disabled", logger.isWarnEnabled()); + assertTrue("error enabled", logger.isErrorEnabled()); + assertTrue("fatal enabled", logger.isFatalErrorEnabled()); } - private void checkFatalLevel( Logger logger ) - { - assertFalse( "debug disabled", logger.isDebugEnabled() ); - assertFalse( "info disabled", logger.isInfoEnabled() ); - assertFalse( "warn disabled", logger.isWarnEnabled() ); - assertFalse( "error disabled", logger.isErrorEnabled() ); - assertTrue( "fatal enabled", logger.isFatalErrorEnabled() ); + private void checkFatalLevel(Logger logger) { + assertFalse("debug disabled", logger.isDebugEnabled()); + assertFalse("info disabled", logger.isInfoEnabled()); + assertFalse("warn disabled", logger.isWarnEnabled()); + assertFalse("error disabled", logger.isErrorEnabled()); + assertTrue("fatal enabled", logger.isFatalErrorEnabled()); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/CustomLoggerManagerTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/CustomLoggerManagerTest.java index 435bb7b8c..96b93048b 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/CustomLoggerManagerTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/CustomLoggerManagerTest.java @@ -18,21 +18,17 @@ import org.codehaus.plexus.PlexusTestCase; -//TODO: this test will get nuked, this needs to be done programmatically +// TODO: this test will get nuked, this needs to be done programmatically /** * @author Trygve Laugstøl */ -public class CustomLoggerManagerTest - extends PlexusTestCase -{ - public void testBasic() - throws Exception - { - LoggerManager manager = lookup( LoggerManager.class ); +public class CustomLoggerManagerTest extends PlexusTestCase { + public void testBasic() throws Exception { + LoggerManager manager = lookup(LoggerManager.class); - assertNotNull( manager ); + assertNotNull(manager); - assertEquals( MockLoggerManager.class.getName(), manager.getClass().getName() ); + assertEquals(MockLoggerManager.class.getName(), manager.getClass().getName()); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/LogEnabledTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/LogEnabledTest.java index 7d3100c6b..26e0cbc25 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/LogEnabledTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/LogEnabledTest.java @@ -22,68 +22,51 @@ * * @author peter at realityforge.org Peter Donald */ -public class LogEnabledTest - extends TestCase -{ - public void testGetLogger() - throws Exception - { +public class LogEnabledTest extends TestCase { + public void testGetLogger() throws Exception { MockLogEnabled logEnabled = new MockLogEnabled(); - MockLogger logger = new MockLogger( "base" ); - logEnabled.enableLogging( logger ); - assertEquals( "logger", logger, logEnabled.getLogger() ); + MockLogger logger = new MockLogger("base"); + logEnabled.enableLogging(logger); + assertEquals("logger", logger, logEnabled.getLogger()); } - public void testSetupLoggerOnLogEnabled() - throws Exception - { + public void testSetupLoggerOnLogEnabled() throws Exception { MockLogEnabled logEnabled = new MockLogEnabled(); MockLogEnabled childLogEnabled = new MockLogEnabled(); - MockLogger logger = new MockLogger( "base" ); - logEnabled.enableLogging( logger ); - logEnabled.setupLogger( childLogEnabled ); - assertEquals( "logEnabled.logger", logger, logEnabled.getLogger() ); - assertEquals( "childLogEnabled.logger", logger, childLogEnabled.getLogger() ); + MockLogger logger = new MockLogger("base"); + logEnabled.enableLogging(logger); + logEnabled.setupLogger(childLogEnabled); + assertEquals("logEnabled.logger", logger, logEnabled.getLogger()); + assertEquals("childLogEnabled.logger", logger, childLogEnabled.getLogger()); } - public void testSetupLoggerOnNonLogEnabled() - throws Exception - { + public void testSetupLoggerOnNonLogEnabled() throws Exception { MockLogEnabled logEnabled = new MockLogEnabled(); - MockLogger logger = new MockLogger( "base" ); - logEnabled.enableLogging( logger ); - logEnabled.setupLogger( new Object() ); + MockLogger logger = new MockLogger("base"); + logEnabled.enableLogging(logger); + logEnabled.setupLogger(new Object()); } - public void testSetupLoggerWithNameOnLogEnabled() - throws Exception - { + public void testSetupLoggerWithNameOnLogEnabled() throws Exception { MockLogEnabled logEnabled = new MockLogEnabled(); MockLogEnabled childLogEnabled = new MockLogEnabled(); - MockLogger logger = new MockLogger( "base" ); - logEnabled.enableLogging( logger ); - logEnabled.setupLogger( childLogEnabled, "child" ); - assertEquals( "logEnabled.logger", logger, logEnabled.getLogger() ); - assertEquals( "childLogEnabled.logger.name", - "base.child", - ( (MockLogger) childLogEnabled.getLogger() ).getName() ); + MockLogger logger = new MockLogger("base"); + logEnabled.enableLogging(logger); + logEnabled.setupLogger(childLogEnabled, "child"); + assertEquals("logEnabled.logger", logger, logEnabled.getLogger()); + assertEquals("childLogEnabled.logger.name", "base.child", ((MockLogger) childLogEnabled.getLogger()).getName()); } - public void testSetupLoggerWithNullName() - throws Exception - { + public void testSetupLoggerWithNullName() throws Exception { MockLogEnabled logEnabled = new MockLogEnabled(); MockLogEnabled childLogEnabled = new MockLogEnabled(); - MockLogger logger = new MockLogger( "base" ); - logEnabled.enableLogging( logger ); - try - { - logEnabled.setupLogger( childLogEnabled, (String) null ); - } - catch ( IllegalStateException npe ) - { + MockLogger logger = new MockLogger("base"); + logEnabled.enableLogging(logger); + try { + logEnabled.setupLogger(childLogEnabled, (String) null); + } catch (IllegalStateException npe) { return; } - fail( "Expected to fail setting up child logger with null name" ); + fail("Expected to fail setting up child logger with null name"); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/MockLogEnabled.java b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/MockLogEnabled.java index 6989f4443..ddc136f04 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/MockLogEnabled.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/MockLogEnabled.java @@ -21,7 +21,4 @@ * @author Peter Donald * @version $Revision$ $Date$ */ -class MockLogEnabled - extends AbstractLogEnabled -{ -} +class MockLogEnabled extends AbstractLogEnabled {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/MockLogger.java b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/MockLogger.java index 8907470bd..a403046be 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/MockLogger.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/MockLogger.java @@ -21,97 +21,64 @@ * @author Peter Donald * @version $Revision$ $Date$ */ -class MockLogger - implements Logger -{ +class MockLogger implements Logger { private final String m_name; - MockLogger( String name ) - { + MockLogger(String name) { m_name = name; } - public String getName() - { + public String getName() { return m_name; } - public Logger getChildLogger( final String name ) - { - return new MockLogger( getName() + "." + name ); + public Logger getChildLogger(final String name) { + return new MockLogger(getName() + "." + name); } - public void debug( String message ) - { - } + public void debug(String message) {} - public void debug( String message, Throwable throwable ) - { - } + public void debug(String message, Throwable throwable) {} - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return false; } - public void info( String message ) - { - } + public void info(String message) {} - public void info( String message, Throwable throwable ) - { - } + public void info(String message, Throwable throwable) {} - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return false; } - public void warn( String message ) - { - } + public void warn(String message) {} - public void warn( String message, Throwable throwable ) - { - } + public void warn(String message, Throwable throwable) {} - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return false; } - public boolean isFatalErrorEnabled() - { + public boolean isFatalErrorEnabled() { return false; } - public void fatalError( String message ) - { - } + public void fatalError(String message) {} - public void fatalError( String message, Throwable throwable ) - { - } + public void fatalError(String message, Throwable throwable) {} - public void error( String message ) - { - } + public void error(String message) {} - public void error( String message, Throwable throwable ) - { - } + public void error(String message, Throwable throwable) {} - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return false; } - public int getThreshold() - { + public int getThreshold() { return 0; } - public void setThreshold( int threshold ) - { - } + public void setThreshold(int threshold) {} } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/MockLoggerManager.java b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/MockLoggerManager.java index afe84f45d..5b7c4b52b 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/MockLoggerManager.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/MockLoggerManager.java @@ -19,60 +19,40 @@ /** * @author Trygve Laugstøl */ -public class MockLoggerManager - implements LoggerManager -{ - public void setThreshold(int threshold) - { - } +public class MockLoggerManager implements LoggerManager { + public void setThreshold(int threshold) {} - public void setThresholds(int threshold) - { - } + public void setThresholds(int threshold) {} - public int getThreshold() - { + public int getThreshold() { return 0; } - public void setThreshold(String role, int threshold) - { - } + public void setThreshold(String role, int threshold) {} - public void setThreshold(String role, String roleHint, int threshold) - { - } + public void setThreshold(String role, String roleHint, int threshold) {} - public int getThreshold(String role) - { + public int getThreshold(String role) { return 0; } - public int getThreshold(String role, String roleHint) - { + public int getThreshold(String role, String roleHint) { return 0; } - public Logger getLoggerForComponent(String role) - { + public Logger getLoggerForComponent(String role) { return new MockLogger(role.getClass().getName()); } - public Logger getLoggerForComponent(String role, String roleHint) - { + public Logger getLoggerForComponent(String role, String roleHint) { return new MockLogger(role.getClass().getName() + ":" + roleHint); } - public void returnComponentLogger(String role) - { - } + public void returnComponentLogger(String role) {} - public void returnComponentLogger(String role, String hint) - { - } + public void returnComponentLogger(String role, String hint) {} - public int getActiveLoggerCount() - { + public int getActiveLoggerCount() { return 0; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/console/ConsoleLoggerManagerTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/console/ConsoleLoggerManagerTest.java index 8716f38ce..86376c3f1 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/console/ConsoleLoggerManagerTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/console/ConsoleLoggerManagerTest.java @@ -21,29 +21,25 @@ import org.codehaus.plexus.logging.LoggerManager; /** - * Test for {@link org.codehaus.plexus.logging.console.ConsoleLoggerManager} and + * Test for {@link org.codehaus.plexus.logging.console.ConsoleLoggerManager} and * {@link org.codehaus.plexus.logging.console.ConsoleLogger}. * * @author Mark H. Wilkinson * @version $Revision$ */ -public final class ConsoleLoggerManagerTest - extends AbstractLoggerManagerTest -{ - protected LoggerManager createLoggerManager() throws Exception - { +public final class ConsoleLoggerManagerTest extends AbstractLoggerManagerTest { + protected LoggerManager createLoggerManager() throws Exception { return lookup(LoggerManager.class); } - public void testSetAllThresholds() throws Exception - { + public void testSetAllThresholds() throws Exception { LoggerManager manager = createLoggerManager(); - manager.setThreshold( Logger.LEVEL_ERROR ); + manager.setThreshold(Logger.LEVEL_ERROR); - Logger logger = manager.getLoggerForComponent( "test" ); - assertEquals( logger.getThreshold(), Logger.LEVEL_ERROR ); + Logger logger = manager.getLoggerForComponent("test"); + assertEquals(logger.getThreshold(), Logger.LEVEL_ERROR); - manager.setThresholds( Logger.LEVEL_DEBUG ); - assertEquals( logger.getThreshold(), Logger.LEVEL_DEBUG ); + manager.setThresholds(Logger.LEVEL_DEBUG); + assertEquals(logger.getThreshold(), Logger.LEVEL_DEBUG); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/console/ConsoleLoggerTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/console/ConsoleLoggerTest.java index 7ee6e23ca..74b87ddf4 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/logging/console/ConsoleLoggerTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/logging/console/ConsoleLoggerTest.java @@ -16,123 +16,114 @@ * limitations under the License. */ -import junit.framework.TestCase; -import org.codehaus.plexus.util.StringUtils; - import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import junit.framework.TestCase; +import org.codehaus.plexus.util.StringUtils; + /** * @author Jason van Zyl * */ -public class ConsoleLoggerTest - extends TestCase -{ - public void testConsoleLogger() - { - ConsoleLogger logger = new ConsoleLogger( ConsoleLogger.LEVEL_DEBUG, "test" ); +public class ConsoleLoggerTest extends TestCase { + public void testConsoleLogger() { + ConsoleLogger logger = new ConsoleLogger(ConsoleLogger.LEVEL_DEBUG, "test"); - assertTrue( logger.isDebugEnabled() ); + assertTrue(logger.isDebugEnabled()); - assertTrue( logger.isInfoEnabled() ); + assertTrue(logger.isInfoEnabled()); - assertTrue( logger.isWarnEnabled() ); + assertTrue(logger.isWarnEnabled()); - assertTrue( logger.isErrorEnabled() ); + assertTrue(logger.isErrorEnabled()); - assertTrue( logger.isFatalErrorEnabled() ); + assertTrue(logger.isFatalErrorEnabled()); // Save the original print stream. PrintStream original = System.out; - Throwable t = new Throwable( "throwable" ); + Throwable t = new Throwable("throwable"); ByteArrayOutputStream os = new ByteArrayOutputStream(); - PrintStream consoleStream = new PrintStream( os ); + PrintStream consoleStream = new PrintStream(os); - System.setOut( consoleStream ); + System.setOut(consoleStream); + logger.debug("debug"); - logger.debug( "debug" ); + assertEquals("[DEBUG] debug", getMessage(consoleStream, os)); - assertEquals( "[DEBUG] debug", getMessage( consoleStream, os ) ); - - logger.debug( "debug", t ); - - assertEquals( "[DEBUG] debug", getMessage( consoleStream, os ) ); + logger.debug("debug", t); + assertEquals("[DEBUG] debug", getMessage(consoleStream, os)); os = new ByteArrayOutputStream(); - consoleStream = new PrintStream( os ); - - System.setOut( consoleStream ); + consoleStream = new PrintStream(os); - logger.info( "info" ); + System.setOut(consoleStream); - assertEquals( "[INFO] info", getMessage( consoleStream, os ) ); + logger.info("info"); - logger.info( "info", t ); + assertEquals("[INFO] info", getMessage(consoleStream, os)); - assertEquals( "[INFO] info", getMessage( consoleStream, os ) ); + logger.info("info", t); + assertEquals("[INFO] info", getMessage(consoleStream, os)); os = new ByteArrayOutputStream(); - consoleStream = new PrintStream( os ); + consoleStream = new PrintStream(os); - System.setOut( consoleStream ); + System.setOut(consoleStream); - logger.warn( "warn" ); + logger.warn("warn"); - assertEquals( "[WARNING] warn", getMessage( consoleStream, os ) ); + assertEquals("[WARNING] warn", getMessage(consoleStream, os)); - logger.warn( "warn", t ); - - assertEquals( "[WARNING] warn", getMessage( consoleStream, os ) ); + logger.warn("warn", t); + assertEquals("[WARNING] warn", getMessage(consoleStream, os)); os = new ByteArrayOutputStream(); - consoleStream = new PrintStream( os ); - - System.setOut( consoleStream ); + consoleStream = new PrintStream(os); - logger.error( "error" ); + System.setOut(consoleStream); - assertEquals( "[ERROR] error", getMessage( consoleStream, os ) ); + logger.error("error"); - logger.error( "error", t ); + assertEquals("[ERROR] error", getMessage(consoleStream, os)); - assertEquals( "[ERROR] error", getMessage( consoleStream, os ) ); + logger.error("error", t); + assertEquals("[ERROR] error", getMessage(consoleStream, os)); os = new ByteArrayOutputStream(); - consoleStream = new PrintStream( os ); + consoleStream = new PrintStream(os); - System.setOut( consoleStream ); + System.setOut(consoleStream); - logger.fatalError( "error" ); + logger.fatalError("error"); - assertEquals( "[FATAL ERROR] error", getMessage( consoleStream, os ) ); + assertEquals("[FATAL ERROR] error", getMessage(consoleStream, os)); - logger.fatalError( "error", t ); + logger.fatalError("error", t); - assertEquals( "[FATAL ERROR] error", getMessage( consoleStream, os ) ); + assertEquals("[FATAL ERROR] error", getMessage(consoleStream, os)); // Set the original print stream. - System.setOut( original ); + System.setOut(original); } - private String getMessage( PrintStream consoleStream, ByteArrayOutputStream os ) - { + private String getMessage(PrintStream consoleStream, ByteArrayOutputStream os) { consoleStream.flush(); consoleStream.close(); - return StringUtils.chopNewline( os.toString() ); + return StringUtils.chopNewline(os.toString()); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/AbstractStartableComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/AbstractStartableComponent.java index 46c5f67a6..3d858d0f9 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/AbstractStartableComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/AbstractStartableComponent.java @@ -6,9 +6,7 @@ import static junit.framework.Assert.assertTrue; -public class AbstractStartableComponent - implements StartableComponent, Startable -{ +public class AbstractStartableComponent implements StartableComponent, Startable { public int startOrder; public int stopOrder; @@ -17,58 +15,44 @@ public class AbstractStartableComponent public AbstractStartableComponent component2; - public void start() - throws StartingException - { + public void start() throws StartingException { startOrder = startGenerator.getAndIncrement(); } - public void stop() - throws StoppingException - { + public void stop() throws StoppingException { stopOrder = stopGenerator.getAndIncrement(); } - public void assertStartOrderCorrect() - { - if ( component1 != null ) - { - assertTrue( "This component started before injected component1", startOrder > component1.startOrder ); + public void assertStartOrderCorrect() { + if (component1 != null) { + assertTrue("This component started before injected component1", startOrder > component1.startOrder); } - if ( component2 != null ) - { - assertTrue( "This component started before injected component2", startOrder > component2.startOrder ); + if (component2 != null) { + assertTrue("This component started before injected component2", startOrder > component2.startOrder); } // assert children are correct - if ( component1 != null ) - { + if (component1 != null) { component1.assertStartOrderCorrect(); } - if ( component2 != null ) - { + if (component2 != null) { component2.assertStartOrderCorrect(); } } - public void assertStopOrderCorrect() - { - if ( component1 != null ) - { - assertTrue( "This component stopped after injected component1", stopOrder < component1.stopOrder ); + public void assertStopOrderCorrect() { + if (component1 != null) { + assertTrue("This component stopped after injected component1", stopOrder < component1.stopOrder); } - if ( component2 != null ) - { - assertTrue( "This component stopped after injected component2", stopOrder < component2.stopOrder ); + if (component2 != null) { + assertTrue("This component stopped after injected component2", stopOrder < component2.stopOrder); } // assert children are correct - if ( component1 != null ) - { + if (component1 != null) { component1.assertStopOrderCorrect(); } - if ( component2 != null ) - { + if (component2 != null) { component2.assertStopOrderCorrect(); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/Action.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/Action.java index 8be2d5c7f..1c6c73817 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/Action.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/Action.java @@ -18,10 +18,8 @@ /** * - * + * * @author Jason van Zyl * */ -public interface Action -{ -} +public interface Action {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/AddUserAction.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/AddUserAction.java index f3813ad44..3eed8190d 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/AddUserAction.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/AddUserAction.java @@ -18,11 +18,8 @@ /** * - * + * * @author Jason van Zyl * */ -public class AddUserAction - implements Action -{ -} +public class AddUserAction implements Action {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/CircularComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/CircularComponent.java index b1f4b8228..a831f7ba4 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/CircularComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/CircularComponent.java @@ -1,6 +1,5 @@ package org.codehaus.plexus.test; -public interface CircularComponent -{ +public interface CircularComponent { static String ROLE = CircularComponent.class.getName(); -} \ No newline at end of file +} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/Component.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/Component.java index d9e7be4b8..09583297d 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/Component.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/Component.java @@ -20,12 +20,11 @@ /** * - * + * * @author Jason van Zyl * */ -public interface Component -{ +public interface Component { static String ROLE = Component.class.getName(); String getHost(); diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentA.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentA.java index b8f6bb0a2..6ef1ba1bd 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentA.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentA.java @@ -16,8 +16,7 @@ * limitations under the License. */ -public interface ComponentA -{ +public interface ComponentA { static String ROLE = ComponentA.class.getName(); ComponentB getComponentB(); diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentB.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentB.java index fb343c0f9..b7aae6b82 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentB.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentB.java @@ -16,7 +16,6 @@ * limitations under the License. */ -public interface ComponentB -{ +public interface ComponentB { static String ROLE = ComponentB.class.getName(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentC.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentC.java index c7d424a78..9001e0ce4 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentC.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentC.java @@ -16,8 +16,7 @@ * limitations under the License. */ -public interface ComponentC -{ +public interface ComponentC { static String ROLE = ComponentC.class.getName(); ComponentD getComponentD(); diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentD.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentD.java index 782200363..fc3f29cf5 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentD.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentD.java @@ -16,8 +16,7 @@ * limitations under the License. */ -public interface ComponentD -{ +public interface ComponentD { static String ROLE = ComponentD.class.getName(); String getName(); diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentManager.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentManager.java index e93170e0a..2f48ee51c 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentManager.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentManager.java @@ -19,11 +19,9 @@ import java.util.List; import java.util.Map; -public interface ComponentManager -{ +public interface ComponentManager { List getList(); Map getMap(); - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentWithRoleDefault.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentWithRoleDefault.java index a4164346e..304339835 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentWithRoleDefault.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ComponentWithRoleDefault.java @@ -16,8 +16,4 @@ * limitations under the License. */ - -public class ComponentWithRoleDefault -{ - -} +public class ComponentWithRoleDefault {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ConcreteThing.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ConcreteThing.java index 3e45a1738..705f138a8 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ConcreteThing.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ConcreteThing.java @@ -16,8 +16,4 @@ * limitations under the License. */ -public class ConcreteThing - implements Thing -{ - -} +public class ConcreteThing implements Thing {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/CountInstancesComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/CountInstancesComponent.java index 01ef98679..7f2d4566e 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/CountInstancesComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/CountInstancesComponent.java @@ -18,27 +18,23 @@ /** * Component counts number of created instances of it. - * + * * @author ptab at newitech.com Piotr Tabor */ -public class CountInstancesComponent -{ +public class CountInstancesComponent { public static String ROLE = CountInstancesComponent.class.getName(); private static int instances = 0; - public CountInstancesComponent() - { + public CountInstancesComponent() { instances++; } - public static void reset() - { + public static void reset() { instances = 0; } - public static int getInstancesCount() - { + public static int getInstancesCount() { return instances; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultCircularComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultCircularComponent.java index 4f161de4e..35a59a57b 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultCircularComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultCircularComponent.java @@ -5,30 +5,20 @@ import org.codehaus.plexus.personality.plexus.lifecycle.phase.StartingException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StoppingException; -public class DefaultCircularComponent - implements CircularComponent, Startable -{ +public class DefaultCircularComponent implements CircularComponent, Startable { private PlexusContainer container; private String lookup; private CircularComponent requirement; - public void start() - throws StartingException - { - try - { + public void start() throws StartingException { + try { if (lookup != null) { - container.lookup( CircularComponent.class, lookup ); + container.lookup(CircularComponent.class, lookup); } - } - catch ( Exception e ) - { + } catch (Exception e) { throw new StartingException("failed", e); } } - public void stop() - throws StoppingException - { - } -} \ No newline at end of file + public void stop() throws StoppingException {} +} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponent.java index c63d3dd02..80fb8d918 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponent.java @@ -18,27 +18,22 @@ import org.codehaus.plexus.test.map.Activity; -public class DefaultComponent - implements Component -{ +public class DefaultComponent implements Component { private String host; private int port; private Activity activity; - public Activity getActivity() - { + public Activity getActivity() { return activity; } - public String getHost() - { + public String getHost() { return host; } - public int getPort() - { + public int getPort() { return port; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentA.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentA.java index f462a80e3..63d3ad612 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentA.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentA.java @@ -22,9 +22,7 @@ * @component.requirement org.codehaus.plexus.test.ComponentC * @component.version 1.0 */ -public class DefaultComponentA - implements ComponentA -{ +public class DefaultComponentA implements ComponentA { private ComponentB componentB; private ComponentC componentC; @@ -35,23 +33,19 @@ public class DefaultComponentA /** @default 10000 */ private int port; - public ComponentB getComponentB() - { + public ComponentB getComponentB() { return componentB; } - public ComponentC getComponentC() - { + public ComponentC getComponentC() { return componentC; } - public String getHost() - { + public String getHost() { return host; } - public int getPort() - { + public int getPort() { return port; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentB.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentB.java index 5e44dcd8f..a10c4c5cf 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentB.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentB.java @@ -19,7 +19,4 @@ /** * 2.0 */ -public class DefaultComponentB - implements ComponentB -{ -} +public class DefaultComponentB implements ComponentB {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentC.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentC.java index d5258451a..c8d65a4b0 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentC.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentC.java @@ -16,13 +16,10 @@ * limitations under the License. */ -public class DefaultComponentC - implements ComponentC -{ +public class DefaultComponentC implements ComponentC { private ComponentD componentD; - public ComponentD getComponentD() - { + public ComponentD getComponentD() { return componentD; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentD.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentD.java index f643451f9..30faeb0b4 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentD.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentD.java @@ -16,13 +16,10 @@ * limitations under the License. */ -public class DefaultComponentD - implements ComponentD -{ +public class DefaultComponentD implements ComponentD { private String name; - public String getName() - { + public String getName() { return name; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentManager.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentManager.java index a96f6a162..17b5d5128 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentManager.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentManager.java @@ -19,22 +19,17 @@ import java.util.List; import java.util.Map; -public class DefaultComponentManager - implements ComponentManager -{ +public class DefaultComponentManager implements ComponentManager { private List list; private Map map; - public List getList() - { + public List getList() { return list; } - public Map getMap() - { + public Map getMap() { return map; } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentWithOptionalRequirement.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentWithOptionalRequirement.java index 16e284301..6a963e85e 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentWithOptionalRequirement.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultComponentWithOptionalRequirement.java @@ -16,10 +16,7 @@ * limitations under the License. */ -public class DefaultComponentWithOptionalRequirement - extends DefaultComponent -{ +public class DefaultComponentWithOptionalRequirement extends DefaultComponent { public Object optionalComponent; - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultLoadOnStartService.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultLoadOnStartService.java index 1e5c6a08d..4aae834ee 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultLoadOnStartService.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultLoadOnStartService.java @@ -24,17 +24,12 @@ * @author Jason van Zyl * */ -public class DefaultLoadOnStartService - implements LoadOnStartService, Startable -{ +public class DefaultLoadOnStartService implements LoadOnStartService, Startable { public static boolean isStarted = false; - public void start() - { + public void start() { isStarted = true; } - public void stop() - { - } + public void stop() {} } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultLoadOnStartServiceWithRoleHint.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultLoadOnStartServiceWithRoleHint.java index 3ce7bd684..0d9190207 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultLoadOnStartServiceWithRoleHint.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultLoadOnStartServiceWithRoleHint.java @@ -16,14 +16,10 @@ * limitations under the License. */ - /** * * * @author Jason van Zyl * */ -public class DefaultLoadOnStartServiceWithRoleHint - implements LoadOnStartService -{ -} +public class DefaultLoadOnStartServiceWithRoleHint implements LoadOnStartService {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceB.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceB.java index 2ee43affe..9d5b9951c 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceB.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceB.java @@ -27,39 +27,31 @@ /** * A simple native plexus component. */ -public class DefaultServiceB - extends AbstractLogEnabled - implements ServiceB, Contextualizable, Initializable, Startable -{ +public class DefaultServiceB extends AbstractLogEnabled + implements ServiceB, Contextualizable, Initializable, Startable { public boolean enableLogging; public boolean contextualize; public boolean initialize; public boolean start; public boolean stop; - public void enableLogging( Logger logger ) - { + public void enableLogging(Logger logger) { enableLogging = true; } - public void contextualize( Context context ) - throws ContextException - { + public void contextualize(Context context) throws ContextException { contextualize = true; } - public void initialize() - { + public void initialize() { initialize = true; } - public void start() - { + public void start() { start = true; } - public void stop() - { + public void stop() { stop = true; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceC.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceC.java index a914b1962..3f55367bd 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceC.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceC.java @@ -18,19 +18,15 @@ import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable; -public class DefaultServiceC - implements ServiceC, Startable -{ +public class DefaultServiceC implements ServiceC, Startable { public boolean started = false; public boolean stopped = false; - public void start() - { + public void start() { started = true; } - public void stop() - { + public void stop() { stopped = true; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceD.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceD.java index e4d441926..9cb719259 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceD.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceD.java @@ -16,8 +16,4 @@ * limitations under the License. */ - -public class DefaultServiceD - implements ServiceD -{ -} +public class DefaultServiceD implements ServiceD {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceE.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceE.java index fa553e6fd..1d46952cf 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceE.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceE.java @@ -27,10 +27,8 @@ /** * A simple native plexus component implementing the manual configuration phase. */ -public class DefaultServiceE - extends AbstractLogEnabled - implements ServiceE, Contextualizable, Initializable, Startable -{ +public class DefaultServiceE extends AbstractLogEnabled + implements ServiceE, Contextualizable, Initializable, Startable { public boolean enableLogging; public boolean configured; public boolean contextualize; @@ -39,29 +37,23 @@ public class DefaultServiceE public boolean stop; public boolean serviced; - public void enableLogging( Logger logger ) - { + public void enableLogging(Logger logger) { enableLogging = true; } - public void contextualize( Context context ) - throws ContextException - { + public void contextualize(Context context) throws ContextException { contextualize = true; } - public void initialize() - { + public void initialize() { initialize = true; } - public void start() - { + public void start() { start = true; } - public void stop() - { + public void stop() { stop = true; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceH.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceH.java index 5aa19ddca..8c2015ffb 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceH.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultServiceH.java @@ -30,10 +30,7 @@ * Mo * */ -public class DefaultServiceH - extends AbstractLogEnabled - implements ServiceH, Eeny, Meeny, Miny, Mo -{ +public class DefaultServiceH extends AbstractLogEnabled implements ServiceH, Eeny, Meeny, Miny, Mo { public boolean eeny; public boolean meeny; public boolean miny; @@ -43,23 +40,19 @@ public class DefaultServiceH // Lifecycle Management // ---------------------------------------------------------------------- - public void eeny() - { + public void eeny() { eeny = true; } - public void meeny() - { + public void meeny() { meeny = true; } - public void miny() - { + public void miny() { miny = true; } - public void mo() - { + public void mo() { mo = true; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentA.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentA.java index 136816720..988ca4b13 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentA.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentA.java @@ -1,6 +1,3 @@ package org.codehaus.plexus.test; -public class DefaultStartableComponentA - extends AbstractStartableComponent -{ -} +public class DefaultStartableComponentA extends AbstractStartableComponent {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentB.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentB.java index 89c64b947..e34bf6851 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentB.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentB.java @@ -1,6 +1,3 @@ package org.codehaus.plexus.test; -public class DefaultStartableComponentB - extends AbstractStartableComponent -{ -} +public class DefaultStartableComponentB extends AbstractStartableComponent {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentC.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentC.java index 646a23cbb..9645bbb56 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentC.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentC.java @@ -1,6 +1,3 @@ package org.codehaus.plexus.test; -public class DefaultStartableComponentC - extends AbstractStartableComponent -{ -} +public class DefaultStartableComponentC extends AbstractStartableComponent {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentD.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentD.java index d811b26c6..517bd8497 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentD.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentD.java @@ -1,6 +1,3 @@ package org.codehaus.plexus.test; -public class DefaultStartableComponentD - extends AbstractStartableComponent -{ -} +public class DefaultStartableComponentD extends AbstractStartableComponent {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentE.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentE.java index a04b3636f..d7d15ab19 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentE.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultStartableComponentE.java @@ -1,6 +1,3 @@ package org.codehaus.plexus.test; -public class DefaultStartableComponentE - extends AbstractStartableComponent -{ -} +public class DefaultStartableComponentE extends AbstractStartableComponent {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultThingUser.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultThingUser.java index 945674635..19a3ebe65 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultThingUser.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/DefaultThingUser.java @@ -16,10 +16,7 @@ * limitations under the License. */ -public class DefaultThingUser - implements ThingUser -{ +public class DefaultThingUser implements ThingUser { public Thing thing; - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/LiveComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/LiveComponent.java index 64b8cbe10..bebf57bbb 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/LiveComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/LiveComponent.java @@ -16,8 +16,4 @@ * limitations under the License. */ - -public class LiveComponent -{ - -} +public class LiveComponent {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/LoadOnStartService.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/LoadOnStartService.java index f03e3a555..e7d9929fc 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/LoadOnStartService.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/LoadOnStartService.java @@ -22,7 +22,6 @@ * @author Jason van Zyl * */ -public interface LoadOnStartService -{ +public interface LoadOnStartService { String ROLE = LoadOnStartService.class.getName(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/LoadOnStartServiceWithRoleHint.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/LoadOnStartServiceWithRoleHint.java index dadf986d5..219aa0db8 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/LoadOnStartServiceWithRoleHint.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/LoadOnStartServiceWithRoleHint.java @@ -22,7 +22,6 @@ * @author Jason van Zyl * */ -public interface LoadOnStartServiceWithRoleHint -{ +public interface LoadOnStartServiceWithRoleHint { String ROLE = LoadOnStartServiceWithRoleHint.class.getName(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/PlexusContainerTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/PlexusContainerTest.java index 6cb22385c..43898dc4d 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/PlexusContainerTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/PlexusContainerTest.java @@ -28,7 +28,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import junit.framework.TestCase; - import org.codehaus.plexus.ContainerConfiguration; import org.codehaus.plexus.DefaultContainerConfiguration; import org.codehaus.plexus.DefaultPlexusContainer; @@ -50,9 +49,7 @@ import org.codehaus.plexus.test.map.Activity; import org.codehaus.plexus.test.map.ActivityManager; -public class PlexusContainerTest - extends TestCase -{ +public class PlexusContainerTest extends TestCase { private String basedir; private ClassLoader classLoader; @@ -61,21 +58,18 @@ public class PlexusContainerTest private DefaultPlexusContainer container; - public PlexusContainerTest( String name ) - { - super( name ); + public PlexusContainerTest(String name) { + super(name); } - public void setUp() - throws Exception - { - basedir = System.getProperty( "basedir" ); + public void setUp() throws Exception { + basedir = System.getProperty("basedir"); classLoader = getClass().getClassLoader(); - configuration = "/" + getClass().getName().replace( '.', '/' ) + ".xml"; + configuration = "/" + getClass().getName().replace('.', '/') + ".xml"; - assertNotNull( classLoader ); + assertNotNull(classLoader); // ---------------------------------------------------------------------------- // Context @@ -83,37 +77,33 @@ public void setUp() Map context = new HashMap(); - context.put( "basedir", basedir ); + context.put("basedir", basedir); - context.put( "plexus.home", basedir + "/target/plexus-home" ); + context.put("plexus.home", basedir + "/target/plexus-home"); - LifecycleHandler arbitrary = new BasicLifecycleHandler( "arbitrary" ); - arbitrary.addBeginSegment( new EenyPhase() ); - arbitrary.addBeginSegment( new MeenyPhase() ); - arbitrary.addBeginSegment( new MinyPhase() ); - arbitrary.addBeginSegment( new MoPhase() ); + LifecycleHandler arbitrary = new BasicLifecycleHandler("arbitrary"); + arbitrary.addBeginSegment(new EenyPhase()); + arbitrary.addBeginSegment(new MeenyPhase()); + arbitrary.addBeginSegment(new MinyPhase()); + arbitrary.addBeginSegment(new MoPhase()); ContainerConfiguration containerConfiguration = new DefaultContainerConfiguration() - .setName( "test" ) - .setContext( context ) - .setContainerConfiguration( configuration ) - .addLifecycleHandler( arbitrary ); + .setName("test") + .setContext(context) + .setContainerConfiguration(configuration) + .addLifecycleHandler(arbitrary); - container = new DefaultPlexusContainer( containerConfiguration ); + container = new DefaultPlexusContainer(containerConfiguration); } - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { container.dispose(); container = null; } - public void testDefaultPlexusContainerSetup() - throws Exception - { - assertEquals( "bar", System.getProperty( "foo" ) ); + public void testDefaultPlexusContainerSetup() throws Exception { + assertEquals("bar", System.getProperty("foo")); } // ---------------------------------------------------------------------- @@ -122,285 +112,263 @@ public void testDefaultPlexusContainerSetup() // the native lifecycle is available after configuration merging. // ---------------------------------------------------------------------- - public void testNativeLifecyclePassage() - throws Exception - { - DefaultServiceB serviceB = (DefaultServiceB) container.lookup( ServiceB.class ); + public void testNativeLifecyclePassage() throws Exception { + DefaultServiceB serviceB = (DefaultServiceB) container.lookup(ServiceB.class); // Make sure the component is alive. - assertNotNull( serviceB ); + assertNotNull(serviceB); // Make sure the component went through all the lifecycle phases - assertEquals( true, serviceB.enableLogging ); + assertEquals(true, serviceB.enableLogging); - assertEquals( true, serviceB.contextualize ); + assertEquals(true, serviceB.contextualize); - assertEquals( true, serviceB.initialize ); + assertEquals(true, serviceB.initialize); - assertEquals( true, serviceB.start ); + assertEquals(true, serviceB.start); - assertEquals( false, serviceB.stop ); + assertEquals(false, serviceB.stop); - container.release( serviceB ); + container.release(serviceB); - assertEquals( true, serviceB.stop ); + assertEquals(true, serviceB.stop); } - public void testConfigurableLifecyclePassage() - throws Exception - { - DefaultServiceE serviceE = (DefaultServiceE) container.lookup( ServiceE.class ); + public void testConfigurableLifecyclePassage() throws Exception { + DefaultServiceE serviceE = (DefaultServiceE) container.lookup(ServiceE.class); // Make sure the component is alive. - assertNotNull( serviceE ); + assertNotNull(serviceE); // Make sure the component went through all the lifecycle phases - assertEquals( true, serviceE.enableLogging ); + assertEquals(true, serviceE.enableLogging); - assertEquals( true, serviceE.contextualize ); + assertEquals(true, serviceE.contextualize); - assertEquals( true, serviceE.initialize ); + assertEquals(true, serviceE.initialize); - assertEquals( true, serviceE.start ); + assertEquals(true, serviceE.start); - assertEquals( false, serviceE.stop ); + assertEquals(false, serviceE.stop); - container.release( serviceE ); + container.release(serviceE); - assertEquals( true, serviceE.stop ); + assertEquals(true, serviceE.stop); } /* * Check that we can get references to a single component with a role * hint. */ - public void testSingleComponentLookupWithRoleHint() - throws Exception - { + public void testSingleComponentLookupWithRoleHint() throws Exception { // Retrieve an instance of component c. - DefaultServiceC serviceC1 = (DefaultServiceC) container.lookup( ServiceC.class, "first-instance" ); + DefaultServiceC serviceC1 = (DefaultServiceC) container.lookup(ServiceC.class, "first-instance"); // Make sure the component is alive. - assertNotNull( serviceC1 ); + assertNotNull(serviceC1); - assertTrue( serviceC1.started ); + assertTrue(serviceC1.started); - assertFalse( serviceC1.stopped ); + assertFalse(serviceC1.stopped); // Retrieve a second reference to the same component. - DefaultServiceC serviceC2 = (DefaultServiceC) container.lookup( ServiceC.class, "first-instance" ); + DefaultServiceC serviceC2 = (DefaultServiceC) container.lookup(ServiceC.class, "first-instance"); // Make sure component is alive. - assertNotNull( serviceC2 ); + assertNotNull(serviceC2); - assertTrue( serviceC2.started ); + assertTrue(serviceC2.started); - assertFalse( serviceC2.stopped ); + assertFalse(serviceC2.stopped); // Let's make sure it gave us back the same component. - assertSame( serviceC1, serviceC2 ); + assertSame(serviceC1, serviceC2); - container.release( serviceC1 ); + container.release(serviceC1); // The component should still be alive. - assertTrue( serviceC2.started ); + assertTrue(serviceC2.started); - assertTrue( serviceC2.stopped ); + assertTrue(serviceC2.stopped); - container.release( serviceC2 ); + container.release(serviceC2); // The component should now have been stopped. - assertTrue( serviceC2.started ); + assertTrue(serviceC2.started); - assertTrue( serviceC2.stopped ); + assertTrue(serviceC2.stopped); } /* * Check that distinct components with the same implementation are managed correctly. */ - public void testMultipleSingletonComponentInstances() - throws Exception - { + public void testMultipleSingletonComponentInstances() throws Exception { // Retrieve an instance of component c. - DefaultServiceC serviceC1 = (DefaultServiceC) container.lookup( ServiceC.class, "first-instance" ); + DefaultServiceC serviceC1 = (DefaultServiceC) container.lookup(ServiceC.class, "first-instance"); // Make sure the component is alive. - assertNotNull( serviceC1 ); + assertNotNull(serviceC1); - assertTrue( serviceC1.started ); + assertTrue(serviceC1.started); - assertFalse( serviceC1.stopped ); + assertFalse(serviceC1.stopped); // Retrieve an instance of component c, with a different role hint. // This should give us a different component instance. - DefaultServiceC serviceC2 = (DefaultServiceC) container.lookup( ServiceC.class, "second-instance" ); + DefaultServiceC serviceC2 = (DefaultServiceC) container.lookup(ServiceC.class, "second-instance"); // Make sure component is alive. - assertNotNull( serviceC2 ); + assertNotNull(serviceC2); - assertTrue( serviceC2.started ); + assertTrue(serviceC2.started); - assertFalse( serviceC2.stopped ); + assertFalse(serviceC2.stopped); // The components should be distinct. - assertNotSame( serviceC1, serviceC2 ); + assertNotSame(serviceC1, serviceC2); - container.release( serviceC1 ); + container.release(serviceC1); // The first component should now have been stopped, the second // one should still be alive. - assertTrue( serviceC1.started ); + assertTrue(serviceC1.started); - assertTrue( serviceC1.stopped ); + assertTrue(serviceC1.stopped); - assertTrue( serviceC2.started ); + assertTrue(serviceC2.started); - assertFalse( serviceC2.stopped ); + assertFalse(serviceC2.stopped); - container.release( serviceC2 ); + container.release(serviceC2); // The second component should now have been stopped. - assertTrue( serviceC2.started ); + assertTrue(serviceC2.started); - assertTrue( serviceC2.stopped ); + assertTrue(serviceC2.stopped); } // ---------------------------------------------------------------------- // Test using an arbitrary component lifecycle handler // ---------------------------------------------------------------------- - public void testArbitraryLifecyclePassageUsingFourArbitraryPhases() - throws Exception - { + public void testArbitraryLifecyclePassageUsingFourArbitraryPhases() throws Exception { // Retrieve an manager of component H. - DefaultServiceH serviceH = (DefaultServiceH) container.lookup( ServiceH.class ); + DefaultServiceH serviceH = (DefaultServiceH) container.lookup(ServiceH.class); // Make sure the component is alive. - assertNotNull( serviceH ); + assertNotNull(serviceH); // Make sure the component went through all the lifecycle phases - assertEquals( true, serviceH.eeny ); + assertEquals(true, serviceH.eeny); - assertEquals( true, serviceH.meeny ); + assertEquals(true, serviceH.meeny); - assertEquals( true, serviceH.miny ); + assertEquals(true, serviceH.miny); - assertEquals( true, serviceH.mo ); + assertEquals(true, serviceH.mo); - container.release( serviceH ); + container.release(serviceH); } - public void testLookupAll() - throws Exception - { - Map components = container.lookupMap( ServiceC.class ); + public void testLookupAll() throws Exception { + Map components = container.lookupMap(ServiceC.class); - assertNotNull( components ); + assertNotNull(components); - assertEquals( 2, components.size() ); + assertEquals(2, components.size()); - ServiceC component = components.get( "first-instance" ); + ServiceC component = components.get("first-instance"); - assertNotNull( component ); + assertNotNull(component); - component = components.get( "second-instance" ); + component = components.get("second-instance"); - assertNotNull( component ); + assertNotNull(component); - container.releaseAll( components ); + container.releaseAll(components); } - public void testAutomatedComponentConfigurationUsingXStreamPoweredComponentConfigurator() - throws Exception - { - Component component = container.lookup( Component.class ); + public void testAutomatedComponentConfigurationUsingXStreamPoweredComponentConfigurator() throws Exception { + Component component = container.lookup(Component.class); - assertNotNull( component ); + assertNotNull(component); - assertNotNull( component.getActivity() ); + assertNotNull(component.getActivity()); - assertEquals( "localhost", component.getHost() ); + assertEquals("localhost", component.getHost()); - assertEquals( 10000, component.getPort() ); + assertEquals(10000, component.getPort()); } - public void testAutomatedComponentComposition() - throws Exception - { - ComponentA componentA = container.lookup( ComponentA.class ); + public void testAutomatedComponentComposition() throws Exception { + ComponentA componentA = container.lookup(ComponentA.class); - assertNotNull( componentA ); + assertNotNull(componentA); - assertEquals( "localhost", componentA.getHost() ); + assertEquals("localhost", componentA.getHost()); - assertEquals( 10000, componentA.getPort() ); + assertEquals(10000, componentA.getPort()); ComponentB componentB = componentA.getComponentB(); - assertNotNull( componentB ); + assertNotNull(componentB); ComponentC componentC = componentA.getComponentC(); - assertNotNull( componentC ); + assertNotNull(componentC); ComponentD componentD = componentC.getComponentD(); - assertNotNull( componentD ); + assertNotNull(componentD); - assertEquals( "jason", componentD.getName() ); + assertEquals("jason", componentD.getName()); } - public void testComponentCompositionWhereTargetFieldIsAMap() - throws Exception - { - ActivityManager am = container.lookup( ActivityManager.class ); + public void testComponentCompositionWhereTargetFieldIsAMap() throws Exception { + ActivityManager am = container.lookup(ActivityManager.class); - Activity one = am.getActivity( "one" ); + Activity one = am.getActivity("one"); - assertNotNull( one ); + assertNotNull(one); // repeated retrieval from map should not cause re-lookup even if instantiation strategy is per-lookup - assertSame( one, am.getActivity( "one" ) ); + assertSame(one, am.getActivity("one")); - assertFalse( one.getState() ); + assertFalse(one.getState()); - am.execute( "one" ); + am.execute("one"); - assertTrue( one.getState() ); + assertTrue(one.getState()); - Activity two = am.getActivity( "two" ); + Activity two = am.getActivity("two"); - assertNotNull( two ); + assertNotNull(two); - assertFalse( two.getState() ); + assertFalse(two.getState()); - am.execute( "two" ); + am.execute("two"); - assertTrue( two.getState() ); + assertTrue(two.getState()); } - public void testComponentCompositionWhereTargetFieldIsAPartialMap() - throws Exception - { - ActivityManager am = container.lookup( ActivityManager.class, "slim" ); + public void testComponentCompositionWhereTargetFieldIsAPartialMap() throws Exception { + ActivityManager am = container.lookup(ActivityManager.class, "slim"); - assertEquals( 1, am.getActivityCount() ); + assertEquals(1, am.getActivityCount()); - Activity one = am.getActivity( "one" ); + Activity one = am.getActivity("one"); - assertNotNull( one ); + assertNotNull(one); - assertFalse( one.getState() ); + assertFalse(one.getState()); - am.execute( "one" ); + am.execute("one"); - assertTrue( one.getState() ); + assertTrue(one.getState()); } - public void testComponentCompositionWhereTargetFieldIsAList() - throws Exception - { - Pipeline pipeline = container.lookup( Pipeline.class ); + public void testComponentCompositionWhereTargetFieldIsAList() throws Exception { + Pipeline pipeline = container.lookup(Pipeline.class); List valves = pipeline.getValves(); @@ -409,82 +377,73 @@ public void testComponentCompositionWhereTargetFieldIsAList() assertSame(valve, valve); } - assertFalse( ( (Valve) valves.get( 0 ) ).getState() ); + assertFalse(((Valve) valves.get(0)).getState()); - assertFalse( ( (Valve) valves.get( 1 ) ).getState() ); + assertFalse(((Valve) valves.get(1)).getState()); pipeline.execute(); - assertTrue( ( (Valve) valves.get( 0 ) ).getState() ); + assertTrue(((Valve) valves.get(0)).getState()); - assertTrue( ( (Valve) valves.get( 1 ) ).getState() ); + assertTrue(((Valve) valves.get(1)).getState()); } - public void testComponentCompositionWhereTargetFieldIsAPartialList() - throws Exception - { - Pipeline pipeline = container.lookup( Pipeline.class, "slim" ); + public void testComponentCompositionWhereTargetFieldIsAPartialList() throws Exception { + Pipeline pipeline = container.lookup(Pipeline.class, "slim"); List valves = pipeline.getValves(); - assertEquals( valves.size(), 1 ); + assertEquals(valves.size(), 1); - assertFalse( ( (Valve) valves.get( 0 ) ).getState() ); + assertFalse(((Valve) valves.get(0)).getState()); pipeline.execute(); - assertTrue( ( (Valve) valves.get( 0 ) ).getState() ); + assertTrue(((Valve) valves.get(0)).getState()); } public void testComponentCompositionWhereTargetFieldAMapThatMustRetainTheOrderOfComponentsGivenASetOfRoleHints() - throws Exception - { - Pipeline pipeline = container.lookup( Pipeline.class, "chubby" ); + throws Exception { + Pipeline pipeline = container.lookup(Pipeline.class, "chubby"); Map valveMap = pipeline.getValveMap(); - List valves = new ArrayList( valveMap.values() ); + List valves = new ArrayList(valveMap.values()); - assertEquals( "Expecting three valves.", 4, valves.size() ); + assertEquals("Expecting three valves.", 4, valves.size()); - assertTrue( "Expecting valve one.", valves.get(0) instanceof ValveOne ); + assertTrue("Expecting valve one.", valves.get(0) instanceof ValveOne); - assertTrue( "Expecting valve two.", valves.get(1) instanceof ValveTwo ); + assertTrue("Expecting valve two.", valves.get(1) instanceof ValveTwo); - assertTrue( "Expecting valve three.", valves.get(2) instanceof ValveThree ); + assertTrue("Expecting valve three.", valves.get(2) instanceof ValveThree); - assertTrue( "Expecting valve four.", valves.get(3) instanceof ValveFour ); + assertTrue("Expecting valve four.", valves.get(3) instanceof ValveFour); } - public void testLookupOfComponentThatShouldBeDiscovered() - throws Exception - { - DiscoveredComponent discoveredComponent = container.lookup( DiscoveredComponent.class ); + public void testLookupOfComponentThatShouldBeDiscovered() throws Exception { + DiscoveredComponent discoveredComponent = container.lookup(DiscoveredComponent.class); - assertNotNull( discoveredComponent ); + assertNotNull(discoveredComponent); } - - public void testStartableComponentSnake() - throws Exception - { - StartableComponent ca = container.lookup( StartableComponent.class, "A-snake" ); - - assertNotNull( ca ); - + + public void testStartableComponentSnake() throws Exception { + StartableComponent ca = container.lookup(StartableComponent.class, "A-snake"); + + assertNotNull(ca); + ca.assertStartOrderCorrect(); - + container.dispose(); - + ca.assertStopOrderCorrect(); } - - public void testStartableComponentTree() - throws Exception - { - StartableComponent ca = container.lookup( StartableComponent.class, "A-tree" ); - - assertNotNull( ca ); - + + public void testStartableComponentTree() throws Exception { + StartableComponent ca = container.lookup(StartableComponent.class, "A-tree"); + + assertNotNull(ca); + ca.assertStartOrderCorrect(); container.dispose(); @@ -492,70 +451,57 @@ public void testStartableComponentTree() ca.assertStopOrderCorrect(); } - public void testLookupCircularity() - throws Exception - { - try - { - container.lookup( CircularComponent.class, "A" ); + public void testLookupCircularity() throws Exception { + try { + container.lookup(CircularComponent.class, "A"); fail("Expected ComponentLookupException due to circularity"); - } - catch ( ComponentLookupException e ) - { - // todo actually test nested exception is as expected when + } catch (ComponentLookupException e) { + // todo actually test nested exception is as expected when } } - public void testAddComponent() - throws Exception - { + public void testAddComponent() throws Exception { LiveComponent live = new LiveComponent(); - container.addComponent( live, LiveComponent.class.getName() ); + container.addComponent(live, LiveComponent.class.getName()); - LiveComponent c = container.lookup( LiveComponent.class ); + LiveComponent c = container.lookup(LiveComponent.class); - assertSame( live, c ); + assertSame(live, c); } - public void testComponentOverride() - throws Exception - { - assertNotNull( container.lookup( Component.class ) ); + public void testComponentOverride() throws Exception { + assertNotNull(container.lookup(Component.class)); - Component live = new Component() - { - public Activity getActivity() - { + Component live = new Component() { + public Activity getActivity() { return null; } - public String getHost() - { + + public String getHost() { return null; } - public int getPort() - { + + public int getPort() { return 0; } }; - container.addComponent( live, Component.class, null ); + container.addComponent(live, Component.class, null); - assertSame( live, container.lookup( Component.class ) ); + assertSame(live, container.lookup(Component.class)); } - public void testUpdateOfActiveComponentCollectionUponChangeOfThreadContextClassLoader() - throws Exception - { - ComponentManager manager = container.lookup( ComponentManager.class ); + public void testUpdateOfActiveComponentCollectionUponChangeOfThreadContextClassLoader() throws Exception { + ComponentManager manager = container.lookup(ComponentManager.class); Map map = manager.getMap(); - assertNotNull( map ); - assertEquals( 0, map.size() ); + assertNotNull(map); + assertEquals(0, map.size()); List list = manager.getList(); - assertNotNull( list ); - assertEquals( 0, list.size() ); + assertNotNull(list); + assertEquals(0, list.size()); /* * Below we're creating two realms which basically contain the same components, only their bytecode/version @@ -563,60 +509,60 @@ public void testUpdateOfActiveComponentCollectionUponChangeOfThreadContextClassL * manager must accurately reflect the components from the current realm (and not from a previous realm). */ - ClassRealm realmA = container.createChildRealm( "realm-a" ); - realmA.addURL( new File( "src/test/test-components/component-a-1.0-SNAPSHOT.jar" ).toURI().toURL() ); - container.discoverComponents( realmA ); + ClassRealm realmA = container.createChildRealm("realm-a"); + realmA.addURL(new File("src/test/test-components/component-a-1.0-SNAPSHOT.jar") + .toURI() + .toURL()); + container.discoverComponents(realmA); - ClassRealm realmB = container.createChildRealm( "realm-b" ); - realmB.addURL( new File( "src/test/test-components/component-a-2.0-SNAPSHOT.jar" ).toURI().toURL() ); - container.discoverComponents( realmB ); + ClassRealm realmB = container.createChildRealm("realm-b"); + realmB.addURL(new File("src/test/test-components/component-a-2.0-SNAPSHOT.jar") + .toURI() + .toURL()); + container.discoverComponents(realmB); ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); - try - { - Thread.currentThread().setContextClassLoader( realmA ); + try { + Thread.currentThread().setContextClassLoader(realmA); map = manager.getMap(); - assertNotNull( map ); - assertEquals( 1, map.size() ); - assertSame( realmA, map.values().iterator().next().getClass().getClassLoader() ); + assertNotNull(map); + assertEquals(1, map.size()); + assertSame(realmA, map.values().iterator().next().getClass().getClassLoader()); list = manager.getList(); - assertNotNull( list ); - assertEquals( 1, list.size() ); - assertSame( realmA, list.iterator().next().getClass().getClassLoader() ); + assertNotNull(list); + assertEquals(1, list.size()); + assertSame(realmA, list.iterator().next().getClass().getClassLoader()); - Thread.currentThread().setContextClassLoader( realmB ); + Thread.currentThread().setContextClassLoader(realmB); map = manager.getMap(); - assertNotNull( map ); - assertEquals( 1, map.size() ); - assertSame( realmB, map.values().iterator().next().getClass().getClassLoader() ); + assertNotNull(map); + assertEquals(1, map.size()); + assertSame(realmB, map.values().iterator().next().getClass().getClassLoader()); list = manager.getList(); - assertNotNull( list ); - assertEquals( 1, list.size() ); - assertSame( realmB, list.iterator().next().getClass().getClassLoader() ); - } - finally - { - Thread.currentThread().setContextClassLoader( oldClassLoader ); + assertNotNull(list); + assertEquals(1, list.size()); + assertSame(realmB, list.iterator().next().getClass().getClassLoader()); + } finally { + Thread.currentThread().setContextClassLoader(oldClassLoader); } } public void testUpdateOfActiveComponentCollectionUponChangeOfThreadContextClassLoaderFromParentToChildRealm() - throws Exception - { - ComponentManager manager = container.lookup( ComponentManager.class ); + throws Exception { + ComponentManager manager = container.lookup(ComponentManager.class); Map map = manager.getMap(); - assertNotNull( map ); - assertEquals( 0, map.size() ); + assertNotNull(map); + assertEquals(0, map.size()); List list = manager.getList(); - assertNotNull( list ); - assertEquals( 0, list.size() ); + assertNotNull(list); + assertEquals(0, list.size()); /* * Below we're creating two realms which basically contain the same components, only their bytecode/version @@ -626,130 +572,121 @@ public void testUpdateOfActiveComponentCollectionUponChangeOfThreadContextClassL * current realm (and not from a previous realm). */ - ClassRealm realmA = container.createChildRealm( "realm-a" ); - realmA.addURL( new File( "src/test/test-components/component-a-1.0-SNAPSHOT.jar" ).toURI().toURL() ); - container.discoverComponents( realmA ); + ClassRealm realmA = container.createChildRealm("realm-a"); + realmA.addURL(new File("src/test/test-components/component-a-1.0-SNAPSHOT.jar") + .toURI() + .toURL()); + container.discoverComponents(realmA); - ClassRealm realmB = realmA.createChildRealm( "realm-b" ); - realmB.importFrom( realmA, "org.codehaus.plexus.components.A" ); - realmB.importFromParent( "nothing" ); - realmB.addURL( new File( "src/test/test-components/component-a-2.0-SNAPSHOT.jar" ).toURI().toURL() ); - container.discoverComponents( realmB ); + ClassRealm realmB = realmA.createChildRealm("realm-b"); + realmB.importFrom(realmA, "org.codehaus.plexus.components.A"); + realmB.importFromParent("nothing"); + realmB.addURL(new File("src/test/test-components/component-a-2.0-SNAPSHOT.jar") + .toURI() + .toURL()); + container.discoverComponents(realmB); ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); - try - { - Thread.currentThread().setContextClassLoader( realmA ); + try { + Thread.currentThread().setContextClassLoader(realmA); map = manager.getMap(); - assertNotNull( map ); - assertEquals( 1, map.size() ); - assertSame( realmA, map.values().iterator().next().getClass().getClassLoader() ); + assertNotNull(map); + assertEquals(1, map.size()); + assertSame(realmA, map.values().iterator().next().getClass().getClassLoader()); list = manager.getList(); - assertNotNull( list ); - assertEquals( 1, list.size() ); - assertSame( realmA, list.iterator().next().getClass().getClassLoader() ); + assertNotNull(list); + assertEquals(1, list.size()); + assertSame(realmA, list.iterator().next().getClass().getClassLoader()); - Thread.currentThread().setContextClassLoader( realmB ); + Thread.currentThread().setContextClassLoader(realmB); map = manager.getMap(); - assertNotNull( map ); - assertEquals( 1, map.size() ); - assertSame( realmB, map.values().iterator().next().getClass().getClassLoader() ); + assertNotNull(map); + assertEquals(1, map.size()); + assertSame(realmB, map.values().iterator().next().getClass().getClassLoader()); list = manager.getList(); - assertNotNull( list ); - assertEquals( 1, list.size() ); - assertSame( realmB, list.iterator().next().getClass().getClassLoader() ); - } - finally - { - Thread.currentThread().setContextClassLoader( oldClassLoader ); + assertNotNull(list); + assertEquals(1, list.size()); + assertSame(realmB, list.iterator().next().getClass().getClassLoader()); + } finally { + Thread.currentThread().setContextClassLoader(oldClassLoader); } } - public void testComponentLookupFromParentRealmOfImportedRealms() - throws Exception - { - ComponentManager manager = container.lookup( ComponentManager.class ); + public void testComponentLookupFromParentRealmOfImportedRealms() throws Exception { + ComponentManager manager = container.lookup(ComponentManager.class); Map map = manager.getMap(); - assertNotNull( map ); - assertEquals( 0, map.size() ); + assertNotNull(map); + assertEquals(0, map.size()); List list = manager.getList(); - assertNotNull( list ); - assertEquals( 0, list.size() ); + assertNotNull(list); + assertEquals(0, list.size()); - URL componentUrl = new File( "src/test/test-components/component-a-1.0-SNAPSHOT.jar" ).toURI().toURL(); + URL componentUrl = new File("src/test/test-components/component-a-1.0-SNAPSHOT.jar") + .toURI() + .toURL(); - ClassRealm realmP = container.createChildRealm( "parent-of-imported-realm" ); - realmP.addURL( componentUrl ); - container.discoverComponents( realmP ); + ClassRealm realmP = container.createChildRealm("parent-of-imported-realm"); + realmP.addURL(componentUrl); + container.discoverComponents(realmP); - ClassRealm realmI = realmP.createChildRealm( "imported-realm" ); + ClassRealm realmI = realmP.createChildRealm("imported-realm"); - ClassRealm realmL = container.createChildRealm( "lookup-realm" ); - realmL.importFrom( realmI, "org.something" ); + ClassRealm realmL = container.createChildRealm("lookup-realm"); + realmL.importFrom(realmI, "org.something"); ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); - try - { - Thread.currentThread().setContextClassLoader( realmL ); + try { + Thread.currentThread().setContextClassLoader(realmL); map = manager.getMap(); - assertNotNull( map ); - assertEquals( 1, map.size() ); - assertSame( realmP, map.values().iterator().next().getClass().getClassLoader() ); + assertNotNull(map); + assertEquals(1, map.size()); + assertSame(realmP, map.values().iterator().next().getClass().getClassLoader()); list = manager.getList(); - assertNotNull( list ); - assertEquals( 1, list.size() ); - assertSame( realmP, list.iterator().next().getClass().getClassLoader() ); - } - finally - { - Thread.currentThread().setContextClassLoader( oldClassLoader ); + assertNotNull(list); + assertEquals(1, list.size()); + assertSame(realmP, list.iterator().next().getClass().getClassLoader()); + } finally { + Thread.currentThread().setContextClassLoader(oldClassLoader); } } - public void testOptionalComponentRequirement() - throws Exception - { + public void testOptionalComponentRequirement() throws Exception { DefaultComponentWithOptionalRequirement ca = - (DefaultComponentWithOptionalRequirement) container.lookup( Component.class, "with-optional" ); + (DefaultComponentWithOptionalRequirement) container.lookup(Component.class, "with-optional"); - assertNotNull( ca ); + assertNotNull(ca); - assertNotNull( ca.getActivity() ); + assertNotNull(ca.getActivity()); - assertNull( ca.optionalComponent ); + assertNull(ca.optionalComponent); } public void testLookupOfComponentThatHasARequirementWithoutRoleHintAndTheOneAndOnlyImplHasNoDefaultHint() - throws Exception - { - DefaultThingUser component = (DefaultThingUser) container.lookup( ThingUser.class ); + throws Exception { + DefaultThingUser component = (DefaultThingUser) container.lookup(ThingUser.class); - assertNotNull( component.thing ); + assertNotNull(component.thing); } - public void testSingleLookupWithAndWithoutRoleHint() - throws Exception - { - ComponentWithRoleDefault withRoleHint = container.lookup( ComponentWithRoleDefault.class, "default" ); + public void testSingleLookupWithAndWithoutRoleHint() throws Exception { + ComponentWithRoleDefault withRoleHint = container.lookup(ComponentWithRoleDefault.class, "default"); - ComponentWithRoleDefault withoutRoleHint = container.lookup( ComponentWithRoleDefault.class ); + ComponentWithRoleDefault withoutRoleHint = container.lookup(ComponentWithRoleDefault.class); - assertSame( withRoleHint, withoutRoleHint ); + assertSame(withRoleHint, withoutRoleHint); } - public void testLookupUponChangeOfThreadContextClassLoaderFromParentToChildRealm() - throws Exception - { + public void testLookupUponChangeOfThreadContextClassLoaderFromParentToChildRealm() throws Exception { /* * Below we're creating two realms which basically contain the same components, only their bytecode/version * differs. The realms form a parent-child relationship where the child imports the component role from the @@ -758,109 +695,98 @@ public void testLookupUponChangeOfThreadContextClassLoaderFromParentToChildRealm * realm). */ - ClassRealm realmA = container.createChildRealm( "realm-a" ); - realmA.addURL( new File( "src/test/test-components/component-a-1.0-SNAPSHOT.jar" ).toURI().toURL() ); - container.discoverComponents( realmA ); + ClassRealm realmA = container.createChildRealm("realm-a"); + realmA.addURL(new File("src/test/test-components/component-a-1.0-SNAPSHOT.jar") + .toURI() + .toURL()); + container.discoverComponents(realmA); - ClassRealm realmB = realmA.createChildRealm( "realm-b" ); - realmB.importFrom( realmA, "org.codehaus.plexus.components.A" ); - realmB.importFromParent( "nothing" ); - realmB.addURL( new File( "src/test/test-components/component-a-2.0-SNAPSHOT.jar" ).toURI().toURL() ); - container.discoverComponents( realmB ); + ClassRealm realmB = realmA.createChildRealm("realm-b"); + realmB.importFrom(realmA, "org.codehaus.plexus.components.A"); + realmB.importFromParent("nothing"); + realmB.addURL(new File("src/test/test-components/component-a-2.0-SNAPSHOT.jar") + .toURI() + .toURL()); + container.discoverComponents(realmB); - Class role = realmA.loadClass( "org.codehaus.plexus.components.A" ); + Class role = realmA.loadClass("org.codehaus.plexus.components.A"); ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); - try - { - Thread.currentThread().setContextClassLoader( realmA ); + try { + Thread.currentThread().setContextClassLoader(realmA); - Object comp1 = container.lookup( role, "default" ); + Object comp1 = container.lookup(role, "default"); - Thread.currentThread().setContextClassLoader( realmB ); + Thread.currentThread().setContextClassLoader(realmB); - Object comp2 = container.lookup( role, "default" ); + Object comp2 = container.lookup(role, "default"); - assertNotNull( comp1 ); - assertNotNull( comp2 ); - assertNotSame( comp1, comp2 ); - assertSame( realmA, comp1.getClass().getClassLoader() ); - assertSame( realmB, comp2.getClass().getClassLoader() ); - } - finally - { - Thread.currentThread().setContextClassLoader( oldClassLoader ); + assertNotNull(comp1); + assertNotNull(comp2); + assertNotSame(comp1, comp2); + assertSame(realmA, comp1.getClass().getClassLoader()); + assertSame(realmB, comp2.getClass().getClassLoader()); + } finally { + Thread.currentThread().setContextClassLoader(oldClassLoader); } } - public void testSafeConcurrentAccessToActiveComponentCollection() - throws Exception - { - ComponentManager manager = container.lookup( ComponentManager.class ); + public void testSafeConcurrentAccessToActiveComponentCollection() throws Exception { + ComponentManager manager = container.lookup(ComponentManager.class); final Map map = manager.getMap(); - assertNotNull( map ); - assertEquals( 0, map.size() ); + assertNotNull(map); + assertEquals(0, map.size()); final List list = manager.getList(); - assertNotNull( list ); - assertEquals( 0, list.size() ); + assertNotNull(list); + assertEquals(0, list.size()); - final AtomicBoolean go = new AtomicBoolean( false ); + final AtomicBoolean go = new AtomicBoolean(false); final List exceptions = new CopyOnWriteArrayList(); Thread[] threads = new Thread[64]; - final CountDownLatch latch = new CountDownLatch( threads.length ); - for ( int i = 0; i < threads.length; i++ ) - { - threads[i] = new Thread() - { + final CountDownLatch latch = new CountDownLatch(threads.length); + for (int i = 0; i < threads.length; i++) { + threads[i] = new Thread() { @Override - public void run() - { - try - { - ClassRealm realm = container.createChildRealm( "realm-" + UUID.randomUUID().toString() ); - realm.addURL( new File( "src/test/test-components/component-a-1.0-SNAPSHOT.jar" ).toURI().toURL() ); - container.discoverComponents( realm ); - Thread.currentThread().setContextClassLoader( realm ); - - while ( !go.get() ) - { + public void run() { + try { + ClassRealm realm = container.createChildRealm( + "realm-" + UUID.randomUUID().toString()); + realm.addURL(new File("src/test/test-components/component-a-1.0-SNAPSHOT.jar") + .toURI() + .toURL()); + container.discoverComponents(realm); + Thread.currentThread().setContextClassLoader(realm); + + while (!go.get()) { // just wait } - for ( int j = 0; j < 1000; j++ ) - { + for (int j = 0; j < 1000; j++) { // this just must not die with some exception - for ( Object value : map.values() ) - { + for (Object value : map.values()) { value.toString(); } - for ( Object value : list ) - { + for (Object value : list) { value.toString(); } } - } - catch ( Exception e ) - { + } catch (Exception e) { e.printStackTrace(); - exceptions.add( e ); - } - finally - { + exceptions.add(e); + } finally { latch.countDown(); } } }; threads[i].start(); } - go.set( true ); + go.set(true); latch.await(); - assertTrue( exceptions.toString(), exceptions.isEmpty() ); + assertTrue(exceptions.toString(), exceptions.isEmpty()); } - } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceB.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceB.java index 52e5de0b9..848dd0ea3 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceB.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceB.java @@ -16,7 +16,6 @@ * limitations under the License. */ -public interface ServiceB -{ +public interface ServiceB { static String ROLE = ServiceB.class.getName(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceC.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceC.java index bb6c0464b..b9c4540da 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceC.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceC.java @@ -16,7 +16,6 @@ * limitations under the License. */ -public interface ServiceC -{ +public interface ServiceC { static String ROLE = ServiceC.class.getName(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceD.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceD.java index b7f71d148..d705ba588 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceD.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceD.java @@ -16,7 +16,6 @@ * limitations under the License. */ -public interface ServiceD -{ +public interface ServiceD { static String ROLE = ServiceD.class.getName(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceE.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceE.java index b1f794ba6..a1f40a767 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceE.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceE.java @@ -16,7 +16,6 @@ * limitations under the License. */ -public interface ServiceE -{ +public interface ServiceE { static String ROLE = ServiceE.class.getName(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceH.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceH.java index 0075fd02e..5be82241a 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceH.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ServiceH.java @@ -16,7 +16,6 @@ * limitations under the License. */ -public interface ServiceH -{ +public interface ServiceH { static String ROLE = ServiceH.class.getName(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/SimpleLifecycleHandler.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/SimpleLifecycleHandler.java index fe8ebff13..4ad0f9261 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/SimpleLifecycleHandler.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/SimpleLifecycleHandler.java @@ -24,15 +24,10 @@ * @author Jason van Zyl * */ -public class SimpleLifecycleHandler - extends AbstractLifecycleHandler -{ - public String getId() - { +public class SimpleLifecycleHandler extends AbstractLifecycleHandler { + public String getId() { return "simple"; } - public void initialize() - { - } + public void initialize() {} } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/StartableComponent.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/StartableComponent.java index 83d62544e..ab1b52ddc 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/StartableComponent.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/StartableComponent.java @@ -2,13 +2,12 @@ import java.util.concurrent.atomic.AtomicInteger; -public interface StartableComponent -{ +public interface StartableComponent { static String ROLE = StartableComponent.class.getName(); - AtomicInteger startGenerator = new AtomicInteger( 1 ); + AtomicInteger startGenerator = new AtomicInteger(1); - AtomicInteger stopGenerator = new AtomicInteger( 1 ); + AtomicInteger stopGenerator = new AtomicInteger(1); void assertStartOrderCorrect(); diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/Thing.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/Thing.java index 94d915d41..99669f4d8 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/Thing.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/Thing.java @@ -16,7 +16,4 @@ * limitations under the License. */ -public interface Thing -{ - -} +public interface Thing {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ThingUser.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ThingUser.java index 62f049f83..857131440 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/ThingUser.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/ThingUser.java @@ -16,7 +16,4 @@ * limitations under the License. */ -public interface ThingUser -{ - -} +public interface ThingUser {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Eeny.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Eeny.java index 3086146e1..cc3e87d70 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Eeny.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Eeny.java @@ -22,7 +22,6 @@ * @author Jason van Zyl * */ -public interface Eeny -{ +public interface Eeny { void eeny(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/EenyPhase.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/EenyPhase.java index c8ba33bf5..0ea4cdb8c 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/EenyPhase.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/EenyPhase.java @@ -20,14 +20,10 @@ import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.lifecycle.phase.AbstractPhase; -public class EenyPhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager manager, ClassRealm lookupRealm ) - { - if ( object instanceof Eeny ) - { - ( (Eeny) object ).eeny(); +public class EenyPhase extends AbstractPhase { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) { + if (object instanceof Eeny) { + ((Eeny) object).eeny(); } } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Meeny.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Meeny.java index cc32f66f9..323ddc2d5 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Meeny.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Meeny.java @@ -22,7 +22,6 @@ * @author Jason van Zyl * */ -public interface Meeny -{ +public interface Meeny { void meeny(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/MeenyPhase.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/MeenyPhase.java index 1be22b2a4..2999ce218 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/MeenyPhase.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/MeenyPhase.java @@ -20,14 +20,10 @@ import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.lifecycle.phase.AbstractPhase; -public class MeenyPhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager manager, ClassRealm lookupRealm ) - { - if ( object instanceof Meeny ) - { - ( (Meeny) object ).meeny(); +public class MeenyPhase extends AbstractPhase { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) { + if (object instanceof Meeny) { + ((Meeny) object).meeny(); } } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Miny.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Miny.java index 382b9cf8f..4ee8f0870 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Miny.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Miny.java @@ -22,7 +22,6 @@ * @author Jason van Zyl * */ -public interface Miny -{ +public interface Miny { void miny(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/MinyPhase.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/MinyPhase.java index 01b32ea32..473946752 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/MinyPhase.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/MinyPhase.java @@ -20,14 +20,10 @@ import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.lifecycle.phase.AbstractPhase; -public class MinyPhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager manager, ClassRealm lookupRealm ) - { - if ( object instanceof Miny ) - { - ( (Miny) object ).miny(); +public class MinyPhase extends AbstractPhase { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) { + if (object instanceof Miny) { + ((Miny) object).miny(); } } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Mo.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Mo.java index 92c621ad8..15c6873a6 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Mo.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/Mo.java @@ -22,7 +22,6 @@ * @author Jason van Zyl * */ -public interface Mo -{ +public interface Mo { void mo(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/MoPhase.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/MoPhase.java index 676485447..14a9e2267 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/MoPhase.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/lifecycle/phase/MoPhase.java @@ -20,14 +20,10 @@ import org.codehaus.plexus.component.manager.ComponentManager; import org.codehaus.plexus.lifecycle.phase.AbstractPhase; -public class MoPhase - extends AbstractPhase -{ - public void execute( Object object, ComponentManager manager, ClassRealm lookupRealm ) - { - if ( object instanceof Mo ) - { - ( (Mo) object ).mo(); +public class MoPhase extends AbstractPhase { + public void execute(Object object, ComponentManager manager, ClassRealm lookupRealm) { + if (object instanceof Mo) { + ((Mo) object).mo(); } } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/AbstractValve.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/AbstractValve.java index 8a89b8c1c..1db108596 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/AbstractValve.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/AbstractValve.java @@ -18,22 +18,18 @@ /** * - * + * * @author Jason van Zyl * */ -public abstract class AbstractValve - implements Valve -{ +public abstract class AbstractValve implements Valve { private boolean state; - public boolean getState() - { + public boolean getState() { return state; } - public void execute() - { + public void execute() { state = true; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/DefaultPipeline.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/DefaultPipeline.java index 60d6e0e67..d1072ab18 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/DefaultPipeline.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/DefaultPipeline.java @@ -21,31 +21,26 @@ /** * - * + * * @author Jason van Zyl * */ -public class DefaultPipeline - implements Pipeline -{ +public class DefaultPipeline implements Pipeline { private List valves; private Map valveMap; - public void execute() - { + public void execute() { for (Object valve : valves) { ((Valve) valve).execute(); } } - public List getValves() - { + public List getValves() { return valves; } - public Map getValveMap() - { + public Map getValveMap() { return valveMap; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/Pipeline.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/Pipeline.java index 9b1a05b6b..fd2133cbe 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/Pipeline.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/Pipeline.java @@ -23,8 +23,7 @@ * @author Jason van Zyl * */ -public interface Pipeline -{ +public interface Pipeline { static String ROLE = Pipeline.class.getName(); void execute(); diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/Valve.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/Valve.java index 95523b5c8..ba8b35991 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/Valve.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/Valve.java @@ -18,12 +18,11 @@ /** * - * + * * @author Jason van Zyl * */ -public interface Valve -{ +public interface Valve { static String ROLE = Valve.class.getName(); void execute(); diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveFour.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveFour.java index ba80a60a8..668afa491 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveFour.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveFour.java @@ -22,7 +22,4 @@ * @author Jason van Zyl * */ -public class ValveFour - extends AbstractValve -{ -} \ No newline at end of file +public class ValveFour extends AbstractValve {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveOne.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveOne.java index d423b8d77..9c0f8cc91 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveOne.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveOne.java @@ -18,11 +18,8 @@ /** * - * + * * @author Jason van Zyl * */ -public class ValveOne - extends AbstractValve -{ -} +public class ValveOne extends AbstractValve {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveThree.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveThree.java index 4ba57b62b..960d4e618 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveThree.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveThree.java @@ -22,7 +22,4 @@ * @author Jason van Zyl * */ -public class ValveThree - extends AbstractValve -{ -} \ No newline at end of file +public class ValveThree extends AbstractValve {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveTwo.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveTwo.java index 7d2350671..9fbf5c3af 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveTwo.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/list/ValveTwo.java @@ -18,11 +18,8 @@ /** * - * + * * @author Jason van Zyl * */ -public class ValveTwo - extends AbstractValve -{ -} +public class ValveTwo extends AbstractValve {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/AbstractActivity.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/AbstractActivity.java index 8c1eff156..17ecd172c 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/AbstractActivity.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/AbstractActivity.java @@ -18,22 +18,18 @@ /** * - * + * * @author Jason van Zyl * */ -public abstract class AbstractActivity - implements Activity -{ +public abstract class AbstractActivity implements Activity { private boolean state; - public boolean getState() - { + public boolean getState() { return state; } - public void execute() - { + public void execute() { state = true; } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/Activity.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/Activity.java index 03e958be1..4345b5ba2 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/Activity.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/Activity.java @@ -18,12 +18,11 @@ /** * - * + * * @author Jason van Zyl * */ -public interface Activity -{ +public interface Activity { static String ROLE = Activity.class.getName(); void execute(); diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/ActivityManager.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/ActivityManager.java index 0338c85c2..05cb9e07c 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/ActivityManager.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/ActivityManager.java @@ -18,17 +18,16 @@ /** * - * + * * @author Jason van Zyl * */ -public interface ActivityManager -{ +public interface ActivityManager { static String ROLE = ActivityManager.class.getName(); - void execute( String id ); + void execute(String id); + + Activity getActivity(String id); - Activity getActivity( String id ); - int getActivityCount(); } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/ActivityOne.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/ActivityOne.java index 30567ae91..da94af30e 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/ActivityOne.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/ActivityOne.java @@ -18,11 +18,8 @@ /** * - * + * * @author Jason van Zyl * */ -public class ActivityOne - extends AbstractActivity -{ -} +public class ActivityOne extends AbstractActivity {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/ActivityTwo.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/ActivityTwo.java index 3690c5289..3628b8e09 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/ActivityTwo.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/ActivityTwo.java @@ -18,11 +18,8 @@ /** * - * + * * @author Jason van Zyl * */ -public class ActivityTwo - extends AbstractActivity -{ -} +public class ActivityTwo extends AbstractActivity {} diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/DefaultActivityManager.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/DefaultActivityManager.java index f3a764092..6aaf4f8bb 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/DefaultActivityManager.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/DefaultActivityManager.java @@ -20,27 +20,22 @@ /** * - * + * * @author Jason van Zyl * */ -public class DefaultActivityManager - implements ActivityManager -{ +public class DefaultActivityManager implements ActivityManager { private Map activities; - public void execute( String id ) - { - getActivity( id ).execute(); + public void execute(String id) { + getActivity(id).execute(); } - public Activity getActivity( String id ) - { - return (Activity) activities.get( id ); + public Activity getActivity(String id) { + return (Activity) activities.get(id); } - - public int getActivityCount() - { - return activities.size(); + + public int getActivityCount() { + return activities.size(); } } diff --git a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/NoComponentsMapTest.java b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/NoComponentsMapTest.java index 3b62bd939..e2c461ecd 100644 --- a/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/NoComponentsMapTest.java +++ b/plexus-container-default/src/test/java/org/codehaus/plexus/test/map/NoComponentsMapTest.java @@ -21,16 +21,12 @@ /** * @author Trygve Laugstøl */ -public class NoComponentsMapTest - extends PlexusTestCase -{ - public void testNoComponents() - throws Exception - { +public class NoComponentsMapTest extends PlexusTestCase { + public void testNoComponents() throws Exception { ActivityManager manager; - - manager = lookup( ActivityManager.class ); - assertEquals( 0, manager.getActivityCount() ); + manager = lookup(ActivityManager.class); + + assertEquals(0, manager.getActivityCount()); } } diff --git a/pom.xml b/pom.xml index 5ddc4dbd4..99a9f776e 100644 --- a/pom.xml +++ b/pom.xml @@ -13,9 +13,7 @@ pom Plexus Containers (deprecated) - - Plexus IoC Container core with companion tools. - + Plexus IoC Container core with companion tools. plexus-component-annotations @@ -26,8 +24,8 @@ scm:git:https://github.com/codehaus-plexus/plexus-containers.git scm:git:https://github.com/codehaus-plexus/plexus-containers.git - https://github.com/codehaus-plexus/plexus-containers/tree/${project.scm.tag}/ master + https://github.com/codehaus-plexus/plexus-containers/tree/${project.scm.tag}/ github